gt
stringclasses
1 value
context
stringlengths
2.49k
119k
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Python Imports import os import re # Resource Management Imports from resource_management.core.resources.service import ServiceConfig from resource_management.core.resources.system import Directory, Execute, File from resource_management.core.source import DownloadSource from resource_management.core.source import InlineTemplate from resource_management.core.source import Template from resource_management.libraries.functions.format import format from resource_management.libraries.functions.default import default from resource_management.libraries.functions import StackFeature from resource_management.libraries.functions.version import format_stack_version from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions.oozie_prepare_war import prepare_war from resource_management.libraries.functions.copy_tarball import get_current_version from resource_management.libraries.resources.xml_config import XmlConfig from resource_management.libraries.script.script import Script from resource_management.libraries.functions.security_commons import update_credential_provider_path from resource_management.core.resources.packaging import Package from resource_management.core.shell import as_user, as_sudo, call, checked_call from resource_management.core.exceptions import Fail from resource_management.libraries.functions.setup_atlas_hook import has_atlas_in_cluster, setup_atlas_hook from ambari_commons.constants import SERVICE, UPGRADE_TYPE_NON_ROLLING, UPGRADE_TYPE_ROLLING from resource_management.libraries.functions.constants import Direction from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl from ambari_commons import OSConst from ambari_commons.inet_utils import download_file from resource_management.core import Logger @OsFamilyFuncImpl(os_family=OSConst.WINSRV_FAMILY) def oozie(is_server=False): import params from status_params import oozie_server_win_service_name XmlConfig("oozie-site.xml", conf_dir=params.oozie_conf_dir, configurations=params.config['configurations']['oozie-site'], owner=params.oozie_user, mode='f', configuration_attributes=params.config['configuration_attributes']['oozie-site'] ) File(os.path.join(params.oozie_conf_dir, "oozie-env.cmd"), owner=params.oozie_user, content=InlineTemplate(params.oozie_env_cmd_template) ) Directory(params.oozie_tmp_dir, owner=params.oozie_user, create_parents = True, ) if is_server: # Manually overriding service logon user & password set by the installation package ServiceConfig(oozie_server_win_service_name, action="change_user", username = params.oozie_user, password = Script.get_password(params.oozie_user)) download_file(os.path.join(params.config['hostLevelParams']['jdk_location'], "sqljdbc4.jar"), os.path.join(params.oozie_root, "extra_libs", "sqljdbc4.jar") ) webapps_sqljdbc_path = os.path.join(params.oozie_home, "oozie-server", "webapps", "oozie", "WEB-INF", "lib", "sqljdbc4.jar") if os.path.isfile(webapps_sqljdbc_path): download_file(os.path.join(params.config['hostLevelParams']['jdk_location'], "sqljdbc4.jar"), webapps_sqljdbc_path ) download_file(os.path.join(params.config['hostLevelParams']['jdk_location'], "sqljdbc4.jar"), os.path.join(params.oozie_home, "share", "lib", "oozie", "sqljdbc4.jar") ) download_file(os.path.join(params.config['hostLevelParams']['jdk_location'], "sqljdbc4.jar"), os.path.join(params.oozie_home, "temp", "WEB-INF", "lib", "sqljdbc4.jar") ) # TODO: see if see can remove this @OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT) def oozie(is_server=False): import params if is_server: params.HdfsResource(params.oozie_hdfs_user_dir, type="directory", action="create_on_execute", owner=params.oozie_user, mode=params.oozie_hdfs_user_mode ) params.HdfsResource(None, action="execute") Directory(params.conf_dir, create_parents = True, owner = params.oozie_user, group = params.user_group ) params.oozie_site = update_credential_provider_path(params.oozie_site, 'oozie-site', os.path.join(params.conf_dir, 'oozie-site.jceks'), params.oozie_user, params.user_group ) XmlConfig("oozie-site.xml", conf_dir = params.conf_dir, configurations = params.oozie_site, configuration_attributes=params.config['configuration_attributes']['oozie-site'], owner = params.oozie_user, group = params.user_group, mode = 0664 ) File(format("{conf_dir}/oozie-env.sh"), owner=params.oozie_user, content=InlineTemplate(params.oozie_env_sh_template), group=params.user_group, ) # On some OS this folder could be not exists, so we will create it before pushing there files Directory(params.limits_conf_dir, create_parents=True, owner='root', group='root' ) File(os.path.join(params.limits_conf_dir, 'oozie.conf'), owner='root', group='root', mode=0644, content=Template("oozie.conf.j2") ) if (params.log4j_props != None): File(format("{params.conf_dir}/oozie-log4j.properties"), mode=0644, group=params.user_group, owner=params.oozie_user, content=InlineTemplate(params.log4j_props) ) elif (os.path.exists(format("{params.conf_dir}/oozie-log4j.properties"))): File(format("{params.conf_dir}/oozie-log4j.properties"), mode=0644, group=params.user_group, owner=params.oozie_user ) if params.stack_version_formatted and check_stack_feature(StackFeature.OOZIE_ADMIN_USER, params.stack_version_formatted): File(format("{params.conf_dir}/adminusers.txt"), mode=0644, group=params.user_group, owner=params.oozie_user, content=Template('adminusers.txt.j2', oozie_admin_users=params.oozie_admin_users) ) else: File ( format("{params.conf_dir}/adminusers.txt"), owner = params.oozie_user, group = params.user_group ) if params.jdbc_driver_name == "com.mysql.jdbc.Driver" or \ params.jdbc_driver_name == "com.microsoft.sqlserver.jdbc.SQLServerDriver" or \ params.jdbc_driver_name == "org.postgresql.Driver" or \ params.jdbc_driver_name == "oracle.jdbc.driver.OracleDriver": File(format("/usr/lib/ambari-agent/{check_db_connection_jar_name}"), content = DownloadSource(format("{jdk_location}{check_db_connection_jar_name}")), ) pass oozie_ownership() if is_server: oozie_server_specific() def oozie_ownership(): import params File ( format("{conf_dir}/hadoop-config.xml"), owner = params.oozie_user, group = params.user_group ) File ( format("{conf_dir}/oozie-default.xml"), owner = params.oozie_user, group = params.user_group ) Directory ( format("{conf_dir}/action-conf"), owner = params.oozie_user, group = params.user_group ) File ( format("{conf_dir}/action-conf/hive.xml"), owner = params.oozie_user, group = params.user_group ) def oozie_server_specific(): import params no_op_test = as_user(format("ls {pid_file} >/dev/null 2>&1 && ps -p `cat {pid_file}` >/dev/null 2>&1"), user=params.oozie_user) File(params.pid_file, action="delete", not_if=no_op_test ) oozie_server_directories = [format("{oozie_home}/{oozie_tmp_dir}"), params.oozie_pid_dir, params.oozie_log_dir, params.oozie_tmp_dir, params.oozie_data_dir, params.oozie_lib_dir, params.oozie_webapps_dir, params.oozie_webapps_conf_dir, params.oozie_server_dir] Directory( oozie_server_directories, owner = params.oozie_user, group = params.user_group, mode = 0755, create_parents = True, cd_access="a", ) Directory(params.oozie_libext_dir, create_parents = True, ) hashcode_file = format("{oozie_home}/.hashcode") skip_recreate_sharelib = format("test -f {hashcode_file} && test -d {oozie_home}/share") untar_sharelib = ('tar','-xvf',format('{oozie_home}/oozie-sharelib.tar.gz'),'-C',params.oozie_home) Execute( untar_sharelib, # time-expensive not_if = format("{no_op_test} || {skip_recreate_sharelib}"), sudo = True, ) configure_cmds = [] configure_cmds.append(('cp', params.ext_js_path, params.oozie_libext_dir)) configure_cmds.append(('chown', format('{oozie_user}:{user_group}'), format('{oozie_libext_dir}/{ext_js_file}'))) Execute( configure_cmds, not_if = no_op_test, sudo = True, ) Directory(params.oozie_webapps_conf_dir, owner = params.oozie_user, group = params.user_group, recursive_ownership = True, recursion_follow_links = True, ) # download the database JAR download_database_library_if_needed() #falcon el extension if params.has_falcon_host: Execute(format('{sudo} cp {falcon_home}/oozie/ext/falcon-oozie-el-extension-*.jar {oozie_libext_dir}'), not_if = no_op_test) Execute(format('{sudo} chown {oozie_user}:{user_group} {oozie_libext_dir}/falcon-oozie-el-extension-*.jar'), not_if = no_op_test) if params.lzo_enabled and len(params.all_lzo_packages) > 0: Package(params.all_lzo_packages, retry_on_repo_unavailability=params.agent_stack_retry_on_unavailability, retry_count=params.agent_stack_retry_count) Execute(format('{sudo} cp {hadoop_lib_home}/hadoop-lzo*.jar {oozie_lib_dir}'), not_if = no_op_test, ) prepare_war(params) File(hashcode_file, mode = 0644, ) if params.stack_version_formatted and check_stack_feature(StackFeature.OOZIE_CREATE_HIVE_TEZ_CONFIGS, params.stack_version_formatted): # Create hive-site and tez-site configs for oozie Directory(params.hive_conf_dir, create_parents = True, owner = params.oozie_user, group = params.user_group ) if 'hive-site' in params.config['configurations']: hive_site_config = update_credential_provider_path(params.config['configurations']['hive-site'], 'hive-site', os.path.join(params.hive_conf_dir, 'hive-site.jceks'), params.oozie_user, params.user_group ) XmlConfig("hive-site.xml", conf_dir=params.hive_conf_dir, configurations=hive_site_config, configuration_attributes=params.config['configuration_attributes']['hive-site'], owner=params.oozie_user, group=params.user_group, mode=0644 ) if 'tez-site' in params.config['configurations']: XmlConfig( "tez-site.xml", conf_dir = params.hive_conf_dir, configurations = params.config['configurations']['tez-site'], configuration_attributes=params.config['configuration_attributes']['tez-site'], owner = params.oozie_user, group = params.user_group, mode = 0664 ) # If Atlas is also installed, need to generate Atlas Hive hook (hive-atlas-application.properties file) in directory # {stack_root}/{current_version}/atlas/hook/hive/ # Because this is a .properties file instead of an xml file, it will not be read automatically by Oozie. # However, should still save the file on this host so that can upload it to the Oozie Sharelib in DFS. if has_atlas_in_cluster(): atlas_hook_filepath = os.path.join(params.hive_conf_dir, params.atlas_hook_filename) Logger.info("Has atlas in cluster, will save Atlas Hive hook into location %s" % str(atlas_hook_filepath)) setup_atlas_hook(SERVICE.HIVE, params.hive_atlas_application_properties, atlas_hook_filepath, params.oozie_user, params.user_group) Directory(params.oozie_server_dir, owner = params.oozie_user, group = params.user_group, recursive_ownership = True, ) if params.security_enabled: File(os.path.join(params.conf_dir, 'zkmigrator_jaas.conf'), owner=params.oozie_user, group=params.user_group, content=Template("zkmigrator_jaas.conf.j2") ) def __parse_sharelib_from_output(output): """ Return the parent directory of the first path from the output of the "oozie admin -shareliblist command $comp" Output will match pattern like: Potential errors [Available ShareLib] hive hdfs://server:8020/user/oozie/share/lib/lib_20160811235630/hive/file1.jar hdfs://server:8020/user/oozie/share/lib/lib_20160811235630/hive/file2.jar """ if output is not None: pattern = re.compile(r"\[Available ShareLib\]\n\S*?\n(.*share.*)", re.IGNORECASE) m = pattern.search(output) if m and len(m.groups()) == 1: jar_path = m.group(1) # Remove leading/trailing spaces and get the containing directory sharelib_dir = os.path.dirname(jar_path.strip()) return sharelib_dir return None def copy_atlas_hive_hook_to_dfs_share_lib(upgrade_type=None, upgrade_direction=None): """ If the Atlas Hive Hook direcotry is present, Atlas is installed, and this is the first Oozie Server, then copy the entire contents of that directory to the Oozie Sharelib in DFS, e.g., /usr/$stack/$current_version/atlas/hook/hive/ -> hdfs:///user/oozie/share/lib/lib_$timetamp/hive :param upgrade_type: If in the middle of a stack upgrade, the type as UPGRADE_TYPE_ROLLING or UPGRADE_TYPE_NON_ROLLING :param upgrade_direction: If in the middle of a stack upgrade, the direction as Direction.UPGRADE or Direction.DOWNGRADE. """ import params # Calculate the effective version since this code can also be called during EU/RU in the upgrade direction. effective_version = params.stack_version_formatted if upgrade_type is None else format_stack_version(params.version) if not check_stack_feature(StackFeature.ATLAS_HOOK_SUPPORT, effective_version): return # Important that oozie_server_hostnames is sorted by name so that this only runs on a single Oozie server. if not (len(params.oozie_server_hostnames) > 0 and params.hostname == params.oozie_server_hostnames[0]): Logger.debug("Will not attempt to copy Atlas Hive hook to DFS since this is not the first Oozie Server " "sorted by hostname.") return if not has_atlas_in_cluster(): Logger.debug("Will not attempt to copy Atlas Hve hook to DFS since Atlas is not installed on the cluster.") return if upgrade_type is not None and upgrade_direction == Direction.DOWNGRADE: Logger.debug("Will not attempt to copy Atlas Hve hook to DFS since in the middle of Rolling/Express upgrade " "and performing a Downgrade.") return current_version = get_current_version() atlas_hive_hook_dir = format("{stack_root}/{current_version}/atlas/hook/hive/") if not os.path.exists(atlas_hive_hook_dir): Logger.error(format("ERROR. Atlas is installed in cluster but this Oozie server doesn't " "contain directory {atlas_hive_hook_dir}")) return atlas_hive_hook_impl_dir = os.path.join(atlas_hive_hook_dir, "atlas-hive-plugin-impl") num_files = len([name for name in os.listdir(atlas_hive_hook_impl_dir) if os.path.exists(os.path.join(atlas_hive_hook_impl_dir, name))]) Logger.info("Found %d files/directories inside Atlas Hive hook impl directory %s"% (num_files, atlas_hive_hook_impl_dir)) # This can return over 100 files, so take the first 5 lines after "Available ShareLib" # Use -oozie http(s):localhost:{oozie_server_admin_port}/oozie as oozie-env does not export OOZIE_URL command = format(r'source {conf_dir}/oozie-env.sh ; oozie admin -oozie {oozie_base_url} -shareliblist hive | grep "\[Available ShareLib\]" -A 5') code, out = checked_call(command, user=params.oozie_user, tries=10, try_sleep=5, logoutput=True) hive_sharelib_dir = __parse_sharelib_from_output(out) if hive_sharelib_dir is None: raise Fail("Could not parse Hive sharelib from output.") Logger.info(format("Parsed Hive sharelib = {hive_sharelib_dir} and will attempt to copy/replace {num_files} files to it from {atlas_hive_hook_impl_dir}")) params.HdfsResource(hive_sharelib_dir, type="directory", action="create_on_execute", source=atlas_hive_hook_impl_dir, user=params.hdfs_user, owner=params.oozie_user, group=params.hdfs_user, mode=0755, recursive_chown=True, recursive_chmod=True, replace_existing_files=True ) Logger.info("Copying Atlas Hive hook properties file to Oozie Sharelib in DFS.") atlas_hook_filepath_source = os.path.join(params.hive_conf_dir, params.atlas_hook_filename) atlas_hook_file_path_dest_in_dfs = os.path.join(hive_sharelib_dir, params.atlas_hook_filename) params.HdfsResource(atlas_hook_file_path_dest_in_dfs, type="file", source=atlas_hook_filepath_source, action="create_on_execute", owner=params.oozie_user, group=params.hdfs_user, mode=0755, replace_existing_files=True ) params.HdfsResource(None, action="execute") # Update the sharelib after making any changes # Use -oozie http(s):localhost:{oozie_server_admin_port}/oozie as oozie-env does not export OOZIE_URL Execute(format("source {conf_dir}/oozie-env.sh ; oozie admin -oozie {oozie_base_url} -sharelibupdate"), user=params.oozie_user, tries=5, try_sleep=5, logoutput=True, ) def download_database_library_if_needed(target_directory = None): """ Downloads the library to use when connecting to the Oozie database, if necessary. The library will be downloaded to 'params.target' unless otherwise specified. :param target_directory: the location where the database library will be downloaded to. :return: """ import params jdbc_drivers = ["com.mysql.jdbc.Driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "oracle.jdbc.driver.OracleDriver","sap.jdbc4.sqlanywhere.IDriver"] # check to see if the JDBC driver name is in the list of ones that need to # be downloaded if params.jdbc_driver_name not in jdbc_drivers or not params.jdbc_driver_jar: return if params.previous_jdbc_jar and os.path.isfile(params.previous_jdbc_jar): File(params.previous_jdbc_jar, action='delete') # if the target directory is not specified if target_directory is None: target_jar_with_directory = params.target else: # create the full path using the supplied target directory and the JDBC JAR target_jar_with_directory = target_directory + os.path.sep + params.jdbc_driver_jar if not os.path.exists(target_jar_with_directory): File(params.downloaded_custom_connector, content = DownloadSource(params.driver_curl_source)) if params.sqla_db_used: untar_sqla_type2_driver = ('tar', '-xvf', params.downloaded_custom_connector, '-C', params.tmp_dir) Execute(untar_sqla_type2_driver, sudo = True) Execute(format("yes | {sudo} cp {jars_path_in_archive} {oozie_libext_dir}")) Directory(params.jdbc_libs_dir, create_parents = True) Execute(format("yes | {sudo} cp {libs_path_in_archive} {jdbc_libs_dir}")) Execute(format("{sudo} chown -R {oozie_user}:{user_group} {oozie_libext_dir}/*")) else: Execute(('cp', '--remove-destination', params.downloaded_custom_connector, target_jar_with_directory), path=["/bin", "/usr/bin/"], sudo = True) File(target_jar_with_directory, owner = params.oozie_user, group = params.user_group)
#!/usr/bin/env python # Copyright 2015 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import json import mmap import os import re import sys import argparse parser = argparse.ArgumentParser() parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*') parser.add_argument("-e", "--skip-exceptions", help="ignore hack/verify-flags/exceptions.txt and print all output", action="store_true") args = parser.parse_args() # Cargo culted from http://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python def is_binary(pathname): """Return true if the given filename is binary. @raise EnvironmentError: if the file does not exist or cannot be accessed. @attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010 @author: Trent Mick <TrentM@ActiveState.com> @author: Jorge Orpinel <jorge@orpinel.com>""" try: with open(pathname, 'r') as f: CHUNKSIZE = 1024 while 1: chunk = f.read(CHUNKSIZE) if '\0' in chunk: # found null byte return True if len(chunk) < CHUNKSIZE: break # done except: return True return False def get_all_files(rootdir): all_files = [] for root, dirs, files in os.walk(rootdir): # don't visit certain dirs if 'vendor' in dirs: dirs.remove('vendor') if '_output' in dirs: dirs.remove('_output') if '_gopath' in dirs: dirs.remove('_gopath') if 'third_party' in dirs: dirs.remove('third_party') if '.git' in dirs: dirs.remove('.git') if 'exceptions.txt' in files: files.remove('exceptions.txt') if 'known-flags.txt' in files: files.remove('known-flags.txt') for name in files: pathname = os.path.join(root, name) if is_binary(pathname): continue all_files.append(pathname) return all_files def normalize_files(rootdir, files): newfiles = [] a = ['Godeps', '_gopath', 'third_party', '.git', 'exceptions.txt', 'known-flags.txt'] for f in files: if any(x in f for x in a): continue if f.endswith(".svg"): continue if f.endswith(".gliffy"): continue if f.endswith(".md"): continue if f.endswith(".yaml"): continue newfiles.append(f) for i, f in enumerate(newfiles): if not os.path.isabs(f): newfiles[i] = os.path.join(rootdir, f) return newfiles def line_has_bad_flag(line, flagre): results = flagre.findall(line) for result in results: if not "_" in result: return False # this should exclude many cases where jinja2 templates use kube flags # as variables, except it uses _ for the variable name if "{% set" + result + "= \"" in line: return False if "pillar[" + result + "]" in line: return False if "grains" + result in line: return False # something common in juju variables... if "template_data[" + result + "]" in line: return False return True return False # The list of files might not be the whole repo. If someone only changed a # couple of files we don't want to run all of the golang files looking for # flags. Instead load the list of flags from hack/verify-flags/known-flags.txt # If running the golang files finds a new flag not in that file, return an # error and tell the user to add the flag to the flag list. def get_flags(rootdir, files): # preload the 'known' flags pathname = os.path.join(rootdir, "hack/verify-flags/known-flags.txt") f = open(pathname, 'r') flags = set(f.read().splitlines()) f.close() # preload the 'known' flags which don't follow the - standard pathname = os.path.join(rootdir, "hack/verify-flags/excluded-flags.txt") f = open(pathname, 'r') excluded_flags = set(f.read().splitlines()) f.close() regexs = [ re.compile('Var[P]?\([^,]*, "([^"]*)"'), re.compile('.String[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.Int[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.Bool[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.Duration[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.StringSlice[P]?\("([^"]*)",[^,]+,[^)]+\)') ] new_flags = set() new_excluded_flags = set() # walk all the files looking for any flags being declared for pathname in files: if not pathname.endswith(".go"): continue f = open(pathname, 'r') data = f.read() f.close() matches = [] for regex in regexs: matches = matches + regex.findall(data) for flag in matches: if any(x in flag for x in excluded_flags): continue if "_" in flag: new_excluded_flags.add(flag) if not "-" in flag: continue if flag not in flags: new_flags.add(flag) if len(new_excluded_flags) != 0: print("Found a flag declared with an _ but which is not explicitly listed as a valid flag name in hack/verify-flags/excluded-flags.txt") print("Are you certain this flag should not have been declared with an - instead?") l = list(new_excluded_flags) l.sort() print("%s" % "\n".join(l)) sys.exit(1) if len(new_flags) != 0: print("Found flags in golang files not in the list of known flags. Please add these to hack/verify-flags/known-flags.txt") l = list(new_flags) l.sort() print("%s" % "\n".join(l)) sys.exit(1) return list(flags) def flags_to_re(flags): """turn the list of all flags we found into a regex find both - and _ versions""" dashRE = re.compile('[-_]') flagREs = [] for flag in flags: # turn all flag names into regexs which will find both types newre = dashRE.sub('[-_]', flag) # only match if there is not a leading or trailing alphanumeric character flagREs.append("[^\w${]" + newre + "[^\w]") # turn that list of regex strings into a single large RE flagRE = "|".join(flagREs) flagRE = re.compile(flagRE) return flagRE def load_exceptions(rootdir): exceptions = set() if args.skip_exceptions: return exceptions exception_filename = os.path.join(rootdir, "hack/verify-flags/exceptions.txt") exception_file = open(exception_filename, 'r') for exception in exception_file.read().splitlines(): out = exception.split(":", 1) if len(out) != 2: print("Invalid line in exceptions file: %s" % exception) continue filename = out[0] line = out[1] exceptions.add((filename, line)) return exceptions def main(): rootdir = os.path.dirname(__file__) + "/../" rootdir = os.path.abspath(rootdir) exceptions = load_exceptions(rootdir) if len(args.filenames) > 0: files = args.filenames else: files = get_all_files(rootdir) files = normalize_files(rootdir, files) flags = get_flags(rootdir, files) flagRE = flags_to_re(flags) bad_lines = [] # walk all the file looking for any flag that was declared and now has an _ for pathname in files: relname = os.path.relpath(pathname, rootdir) f = open(pathname, 'r') for line in f.read().splitlines(): if line_has_bad_flag(line, flagRE): if (relname, line) not in exceptions: bad_lines.append((relname, line)) f.close() if len(bad_lines) != 0: if not args.skip_exceptions: print("Found illegal 'flag' usage. If these are false positives you should run `hack/verify-flags-underscore.py -e > hack/verify-flags/exceptions.txt` to update the list.") bad_lines.sort() for (relname, line) in bad_lines: print("%s:%s" % (relname, line)) return 1 if __name__ == "__main__": sys.exit(main())
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import mock from rally.common import sshutils from tests.unit import test class FakeParamikoException(Exception): pass class SSHTestCase(test.TestCase): """Test all small SSH methods.""" def setUp(self): super(SSHTestCase, self).setUp() self.ssh = sshutils.SSH("root", "example.net") @mock.patch("rally.common.sshutils.SSH._get_pkey") def test_construct(self, mock_ssh__get_pkey): mock_ssh__get_pkey.return_value = "pkey" ssh = sshutils.SSH("root", "example.net", port=33, pkey="key", key_filename="kf", password="secret") mock_ssh__get_pkey.assert_called_once_with("key") self.assertEqual("root", ssh.user) self.assertEqual("example.net", ssh.host) self.assertEqual(33, ssh.port) self.assertEqual("pkey", ssh.pkey) self.assertEqual("kf", ssh.key_filename) self.assertEqual("secret", ssh.password) def test_construct_default(self): self.assertEqual("root", self.ssh.user) self.assertEqual("example.net", self.ssh.host) self.assertEqual(22, self.ssh.port) self.assertIsNone(self.ssh.pkey) self.assertIsNone(self.ssh.key_filename) self.assertIsNone(self.ssh.password) @mock.patch("rally.common.sshutils.paramiko") def test__get_pkey_invalid(self, mock_paramiko): mock_paramiko.SSHException = FakeParamikoException rsa = mock_paramiko.rsakey.RSAKey dss = mock_paramiko.dsskey.DSSKey rsa.from_private_key.side_effect = mock_paramiko.SSHException dss.from_private_key.side_effect = mock_paramiko.SSHException self.assertRaises(sshutils.SSHError, self.ssh._get_pkey, "key") @mock.patch("rally.common.sshutils.six.moves.StringIO") @mock.patch("rally.common.sshutils.paramiko") def test__get_pkey_dss(self, mock_paramiko, mock_string_io): mock_paramiko.SSHException = FakeParamikoException mock_string_io.return_value = "string_key" mock_paramiko.dsskey.DSSKey.from_private_key.return_value = "dss_key" rsa = mock_paramiko.rsakey.RSAKey rsa.from_private_key.side_effect = mock_paramiko.SSHException key = self.ssh._get_pkey("key") dss_calls = mock_paramiko.dsskey.DSSKey.from_private_key.mock_calls self.assertEqual([mock.call("string_key")], dss_calls) self.assertEqual(key, "dss_key") mock_string_io.assert_called_once_with("key") @mock.patch("rally.common.sshutils.six.moves.StringIO") @mock.patch("rally.common.sshutils.paramiko") def test__get_pkey_rsa(self, mock_paramiko, mock_string_io): mock_paramiko.SSHException = FakeParamikoException mock_string_io.return_value = "string_key" mock_paramiko.rsakey.RSAKey.from_private_key.return_value = "rsa_key" dss = mock_paramiko.dsskey.DSSKey dss.from_private_key.side_effect = mock_paramiko.SSHException key = self.ssh._get_pkey("key") rsa_calls = mock_paramiko.rsakey.RSAKey.from_private_key.mock_calls self.assertEqual([mock.call("string_key")], rsa_calls) self.assertEqual(key, "rsa_key") mock_string_io.assert_called_once_with("key") @mock.patch("rally.common.sshutils.SSH._get_pkey") @mock.patch("rally.common.sshutils.paramiko") def test__get_client(self, mock_paramiko, mock_ssh__get_pkey): mock_ssh__get_pkey.return_value = "key" fake_client = mock.Mock() mock_paramiko.SSHClient.return_value = fake_client mock_paramiko.AutoAddPolicy.return_value = "autoadd" ssh = sshutils.SSH("admin", "example.net", pkey="key") client = ssh._get_client() self.assertEqual(fake_client, client) client_calls = [ mock.call.set_missing_host_key_policy("autoadd"), mock.call.connect("example.net", username="admin", port=22, pkey="key", key_filename=None, password=None, timeout=1), ] self.assertEqual(client_calls, client.mock_calls) def test_close(self): with mock.patch.object(self.ssh, "_client") as m_client: self.ssh.close() m_client.close.assert_called_once_with() self.assertFalse(self.ssh._client) @mock.patch("rally.common.sshutils.six.moves.StringIO") def test_execute(self, mock_string_io): mock_string_io.side_effect = stdio = [mock.Mock(), mock.Mock()] stdio[0].read.return_value = "stdout fake data" stdio[1].read.return_value = "stderr fake data" with mock.patch.object(self.ssh, "run", return_value=0) as mock_run: status, stdout, stderr = self.ssh.execute("cmd", stdin="fake_stdin", timeout=43) mock_run.assert_called_once_with( "cmd", stdin="fake_stdin", stdout=stdio[0], stderr=stdio[1], timeout=43, raise_on_error=False) self.assertEqual(0, status) self.assertEqual("stdout fake data", stdout) self.assertEqual("stderr fake data", stderr) @mock.patch("rally.common.sshutils.time") def test_wait_timeout(self, mock_time): mock_time.time.side_effect = [1, 50, 150] self.ssh.execute = mock.Mock(side_effect=[sshutils.SSHError, sshutils.SSHError, 0]) self.assertRaises(sshutils.SSHTimeout, self.ssh.wait) self.assertEqual([mock.call("uname")] * 2, self.ssh.execute.mock_calls) @mock.patch("rally.common.sshutils.time") def test_wait(self, mock_time): mock_time.time.side_effect = [1, 50, 100] self.ssh.execute = mock.Mock(side_effect=[sshutils.SSHError, sshutils.SSHError, 0]) self.ssh.wait() self.assertEqual([mock.call("uname")] * 3, self.ssh.execute.mock_calls) class SSHRunTestCase(test.TestCase): """Test SSH.run method in different aspects. Also tested method "execute". """ def setUp(self): super(SSHRunTestCase, self).setUp() self.fake_client = mock.Mock() self.fake_session = mock.Mock() self.fake_transport = mock.Mock() self.fake_transport.open_session.return_value = self.fake_session self.fake_client.get_transport.return_value = self.fake_transport self.fake_session.recv_ready.return_value = False self.fake_session.recv_stderr_ready.return_value = False self.fake_session.send_ready.return_value = False self.fake_session.exit_status_ready.return_value = True self.fake_session.recv_exit_status.return_value = 0 self.ssh = sshutils.SSH("admin", "example.net") self.ssh._get_client = mock.Mock(return_value=self.fake_client) @mock.patch("rally.common.sshutils.select") def test_execute(self, mock_select): mock_select.select.return_value = ([], [], []) self.fake_session.recv_ready.side_effect = [1, 0, 0] self.fake_session.recv_stderr_ready.side_effect = [1, 0] self.fake_session.recv.return_value = "ok" self.fake_session.recv_stderr.return_value = "error" self.fake_session.exit_status_ready.return_value = 1 self.fake_session.recv_exit_status.return_value = 127 self.assertEqual((127, "ok", "error"), self.ssh.execute("cmd")) self.fake_session.exec_command.assert_called_once_with("cmd") @mock.patch("rally.common.sshutils.select") def test_execute_args(self, mock_select): mock_select.select.return_value = ([], [], []) self.fake_session.recv_ready.side_effect = [1, 0, 0] self.fake_session.recv_stderr_ready.side_effect = [1, 0] self.fake_session.recv.return_value = "ok" self.fake_session.recv_stderr.return_value = "error" self.fake_session.exit_status_ready.return_value = 1 self.fake_session.recv_exit_status.return_value = 127 result = self.ssh.execute(["cmd", "arg1", "arg2 with space"]) self.assertEqual((127, "ok", "error"), result) self.fake_session.exec_command.assert_called_once_with( "cmd arg1 'arg2 with space'") @mock.patch("rally.common.sshutils.select") def test_run(self, mock_select): mock_select.select.return_value = ([], [], []) self.assertEqual(0, self.ssh.run("cmd")) @mock.patch("rally.common.sshutils.select") def test_run_nonzero_status(self, mock_select): mock_select.select.return_value = ([], [], []) self.fake_session.recv_exit_status.return_value = 1 self.assertRaises(sshutils.SSHError, self.ssh.run, "cmd") self.assertEqual(1, self.ssh.run("cmd", raise_on_error=False)) @mock.patch("rally.common.sshutils.select") def test_run_stdout(self, mock_select): mock_select.select.return_value = ([], [], []) self.fake_session.recv_ready.side_effect = [True, True, False] self.fake_session.recv.side_effect = ["ok1", "ok2"] stdout = mock.Mock() self.ssh.run("cmd", stdout=stdout) self.assertEqual([mock.call("ok1"), mock.call("ok2")], stdout.write.mock_calls) @mock.patch("rally.common.sshutils.select") def test_run_stderr(self, mock_select): mock_select.select.return_value = ([], [], []) self.fake_session.recv_stderr_ready.side_effect = [True, False] self.fake_session.recv_stderr.return_value = "error" stderr = mock.Mock() self.ssh.run("cmd", stderr=stderr) stderr.write.assert_called_once_with("error") @mock.patch("rally.common.sshutils.select") def test_run_stdin(self, mock_select): """Test run method with stdin. Third send call was called with "e2" because only 3 bytes was sent by second call. So remainig 2 bytes of "line2" was sent by third call. """ mock_select.select.return_value = ([], [], []) self.fake_session.exit_status_ready.side_effect = [0, 0, 0, True] self.fake_session.send_ready.return_value = True self.fake_session.send.side_effect = [5, 3, 2] fake_stdin = mock.Mock() fake_stdin.read.side_effect = ["line1", "line2", ""] fake_stdin.closed = False def close(): fake_stdin.closed = True fake_stdin.close = mock.Mock(side_effect=close) self.ssh.run("cmd", stdin=fake_stdin) call = mock.call send_calls = [call("line1"), call("line2"), call("e2")] self.assertEqual(send_calls, self.fake_session.send.mock_calls) @mock.patch("rally.common.sshutils.select") def test_run_select_error(self, mock_select): self.fake_session.exit_status_ready.return_value = False mock_select.select.return_value = ([], [], [True]) self.assertRaises(sshutils.SSHError, self.ssh.run, "cmd") @mock.patch("rally.common.sshutils.time") @mock.patch("rally.common.sshutils.select") def test_run_timemout(self, mock_select, mock_time): mock_time.time.side_effect = [1, 3700] mock_select.select.return_value = ([], [], []) self.fake_session.exit_status_ready.return_value = False self.assertRaises(sshutils.SSHTimeout, self.ssh.run, "cmd") @mock.patch("rally.common.sshutils.open", create=True) def test__put_file_shell(self, mock_open): self.ssh.run = mock.Mock() self.ssh._put_file_shell("localfile", "remotefile", 0o42) self.ssh.run.assert_called_once_with( "cat > remotefile; chmod 042 remotefile", stdin=mock_open.return_value.__enter__.return_value) @mock.patch("rally.common.sshutils.os.stat") def test__put_file_sftp(self, mock_stat): sftp = self.fake_client.open_sftp.return_value = mock.MagicMock() sftp.__enter__.return_value = sftp mock_stat.return_value = os.stat_result([0o753] + [0] * 9) self.ssh._put_file_sftp("localfile", "remotefile") sftp.put.assert_called_once_with("localfile", "remotefile") mock_stat.assert_called_once_with("localfile") sftp.chmod.assert_called_once_with("remotefile", 0o753) sftp.__exit__.assert_called_once_with(None, None, None) def test__put_file_sftp_mode(self): sftp = self.fake_client.open_sftp.return_value = mock.MagicMock() sftp.__enter__.return_value = sftp self.ssh._put_file_sftp("localfile", "remotefile", mode=0o753) sftp.put.assert_called_once_with("localfile", "remotefile") sftp.chmod.assert_called_once_with("remotefile", 0o753) sftp.__exit__.assert_called_once_with(None, None, None) def test_put_file(self): self.ssh._put_file_sftp = mock.Mock( side_effect=sshutils.paramiko.SSHException()) self.ssh._put_file_shell = mock.Mock() self.ssh.put_file("foo", "bar", 42) self.ssh._put_file_sftp.assert_called_once_with("foo", "bar", mode=42) self.ssh._put_file_shell.assert_called_once_with("foo", "bar", mode=42)
# -*- coding: utf-8 -*- import numpy as np import pytest import six import tensorflow as tf from tfsnippet.utils import TensorWrapper, register_tensor_wrapper_class from tests.utils._div_op import regular_div, floor_div from tests.utils._true_div_op import true_div class _SimpleTensor(TensorWrapper): def __init__(self, wrapped, flag=None): self._self_flag_ = flag self._self_tensor_ = wrapped super(_SimpleTensor, self).__init__() @property def tensor(self): return self._self_tensor_ @property def flag(self): return self._self_flag_ def get_flag(self): return self._self_flag_ register_tensor_wrapper_class(_SimpleTensor) class TensorWrapperArithTestCase(tf.test.TestCase): def test_prerequisite(self): if six.PY2: self.assertAlmostEqual(regular_div(3, 2), 1) self.assertAlmostEqual(regular_div(3.3, 1.6), 2.0625) else: self.assertAlmostEqual(regular_div(3, 2), 1.5) self.assertAlmostEqual(regular_div(3.3, 1.6), 2.0625) self.assertAlmostEqual(true_div(3, 2), 1.5) self.assertAlmostEqual(true_div(3.3, 1.6), 2.0625) self.assertAlmostEqual(floor_div(3, 2), 1) self.assertAlmostEqual(floor_div(3.3, 1.6), 2.0) def test_unary_op(self): def check_op(name, func, x): x_tensor = tf.convert_to_tensor(x) ans = func(x_tensor) res = tf.convert_to_tensor(func(_SimpleTensor(x_tensor))) self.assertEqual( res.dtype, ans.dtype, msg='Result dtype does not match answer after unary operator ' '{} is applied: {!r} vs {!r} (x is {!r})' .format(name, res.dtype, ans.dtype, x) ) res_val = res.eval() ans_val = ans.eval() np.testing.assert_equal( res_val, ans_val, err_msg='Result value does not match answer after unary ' 'operator {} is applied: {!r} vs {!r} (x is {!r})' .format(name, res_val, ans_val, x) ) with self.test_session(): int_data = np.asarray([1, -2, 3], dtype=np.int32) float_data = np.asarray([1.1, -2.2, 3.3], dtype=np.float32) bool_data = np.asarray([True, False, True], dtype=np.bool) check_op('abs', abs, int_data) check_op('abs', abs, float_data) check_op('neg', (lambda v: -v), int_data) check_op('neg', (lambda v: -v), float_data) check_op('invert', (lambda v: ~v), bool_data) def test_binary_op(self): def check_op(name, func, x, y): x_tensor = tf.convert_to_tensor(x) y_tensor = tf.convert_to_tensor(y) ans = func(x_tensor, y_tensor) res_1 = tf.convert_to_tensor( func(_SimpleTensor(x_tensor), y)) res_2 = tf.convert_to_tensor( func(x, _SimpleTensor(y_tensor))) res_3 = tf.convert_to_tensor( func(_SimpleTensor(x_tensor), y_tensor)) res_4 = tf.convert_to_tensor( func(x_tensor, _SimpleTensor(y_tensor))) res_5 = tf.convert_to_tensor( func(_SimpleTensor(x_tensor), _SimpleTensor(y_tensor))) for tag, res in [('TensorWrapper + np.ndarray', res_1), ('np.ndarray + TensorWrapper', res_2), ('TensorWrapper + Tensor', res_3), ('Tensor + TensorWrapper', res_4), ('TensorWrapper + TensorWrapper', res_5)]: self.assertEqual( res.dtype, ans.dtype, msg='Result dtype does not match answer after {} binary ' 'operator {} is applied: {!r} vs {!r} (x is {!r}, ' 'y is {!r})'. format(tag, name, res.dtype, ans.dtype, x, y) ) res_val = res.eval() ans_val = ans.eval() np.testing.assert_equal( res_val, ans_val, err_msg='Result value does not match answer after {} ' 'binary operator {} is applied: {!r} vs {!r} ' '(x is {!r}, y is {!r}).' .format(tag, name, res_val, ans_val, x, y) ) def run_ops(x, y, ops): for name, func in six.iteritems(ops): check_op(name, func, x, y) arith_ops = { 'add': lambda x, y: x + y, 'sub': lambda x, y: x - y, 'mul': lambda x, y: x * y, 'div': regular_div, 'truediv': true_div, 'floordiv': floor_div, 'mod': lambda x, y: x % y, } logical_ops = { 'and': lambda x, y: x & y, 'or': lambda x, y: x | y, 'xor': lambda x, y: x ^ y, } relation_ops = { 'lt': lambda x, y: x < y, 'le': lambda x, y: x <= y, 'gt': lambda x, y: x > y, 'ge': lambda x, y: x >= y, } with self.test_session(): # arithmetic operators run_ops(np.asarray([-4, 5, 6], dtype=np.int32), np.asarray([1, -2, 3], dtype=np.int32), arith_ops) run_ops(np.asarray([-4.4, 5.5, 6.6], dtype=np.float32), np.asarray([1.1, -2.2, 3.3], dtype=np.float32), arith_ops) # it seems that tf.pow(x, y) does not support negative integers # yet, so we individually test this operator here. check_op('pow', (lambda x, y: x ** y), np.asarray([-4, 5, 6], dtype=np.int32), np.asarray([1, 2, 3], dtype=np.int32)) check_op('pow', (lambda x, y: x ** y), np.asarray([-4.4, 5.5, 6.6], dtype=np.float32), np.asarray([1.1, -2.2, 3.3], dtype=np.float32)) # logical operators run_ops(np.asarray([True, False, True, False], dtype=np.bool), np.asarray([True, True, False, False], dtype=np.bool), logical_ops) # relation operators run_ops(np.asarray([1, -2, 3, -4, 5, 6, -4, 5, 6], dtype=np.int32), np.asarray([1, -2, 3, 1, -2, 3, -4, 5, 6], dtype=np.int32), relation_ops) run_ops( np.asarray([1.1, -2.2, 3.3, -4.4, 5.5, 6.6, -4.4, 5.5, 6.6], dtype=np.float32), np.asarray([1.1, -2.2, 3.3, 1.1, -2.2, 3.3, -4.4, 5.5, 6.6], dtype=np.float32), relation_ops ) def test_getitem(self): def check_getitem(x, y, xx, yy): ans = tf.convert_to_tensor(x[y]) res = xx[yy] self.assertEqual( res.dtype, ans.dtype, msg='Result dtype does not match answer after getitem ' 'is applied: {!r} vs {!r} (x is {!r}, y is {!r}, ' 'xx is {!r}, yy is {!r}).'. format(res.dtype, ans.dtype, x, y, xx, yy) ) res_val = res.eval() ans_val = ans.eval() np.testing.assert_equal( res_val, ans_val, err_msg='Result value does not match answer after ' 'getitem is applied: {!r} vs {!r} (x is {!r}, ' 'y is {!r}, xx is {!r}, yy is {!r}).' .format(res_val, ans_val, x, y, xx, yy) ) class _SliceGenerator(object): def __getitem__(self, item): return item sg = _SliceGenerator() with self.test_session(): data = np.asarray([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int32) indices_or_slices = [ 0, -1, # TensorFlow has not supported array index yet. # np.asarray([0, 3, 2, 6], dtype=np.int32), # np.asarray([-1, -2, -3], dtype=np.int32), sg[0:], sg[:1], sg[:: 2], sg[-1:], sg[: -1], sg[:: -1], ] for s in indices_or_slices: x_tensor = tf.convert_to_tensor(data) x_simple_tensor = _SimpleTensor(x_tensor) check_getitem(data, s, x_simple_tensor, s) if not isinstance(s, slice): y_tensor = tf.convert_to_tensor(s) y_simple_tensor = _SimpleTensor(y_tensor) check_getitem(data, s, x_simple_tensor, y_tensor) check_getitem(data, s, x_simple_tensor, y_simple_tensor) check_getitem(data, s, x_tensor, y_simple_tensor) class TensorWrapperInterfaceTestCase(tf.test.TestCase): def test_disallowed_op(self): with pytest.raises( TypeError, match='`_SimpleTensor` is not iterable'): _ = iter(_SimpleTensor(tf.constant(1))) with pytest.raises( TypeError, match='Using a `_SimpleTensor` as a Python `bool` ' 'is not allowed.*'): _ = not _SimpleTensor(tf.constant(1)) with pytest.raises( TypeError, match='Using a `_SimpleTensor` as a Python `bool` ' 'is not allowed.*'): if _SimpleTensor(tf.constant(1)): pass def test_convert_to_tensor(self): with self.test_session(): t = _SimpleTensor(tf.constant(1.)) self.assertIsInstance(tf.convert_to_tensor(t), tf.Tensor) self.assertNotIsInstance(tf.convert_to_tensor(t), _SimpleTensor) def test_error_convert_to_tensor(self): with pytest.raises( ValueError, match='Incompatible type conversion requested to ' 'type int32 for tensor of type float32'): _ = tf.convert_to_tensor( _SimpleTensor(tf.constant(1., dtype=tf.float32)), dtype=tf.int32 ) def test_session_run(self): with self.test_session() as sess: # test session run t = _SimpleTensor(tf.constant([1., 2., 3.])) np.testing.assert_equal(sess.run(t), [1., 2., 3.]) # test using in feed_dict np.testing.assert_equal( sess.run(tf.identity(t), feed_dict={ t: np.asarray([4., 5., 6.]) }), np.asarray([4., 5., 6.]) ) def test_get_attributes(self): t = _SimpleTensor(tf.constant([1., 2., 3.]), flag=123) self.assertEqual(t.flag, 123) self.assertEqual(t._self_flag_, 123) self.assertEqual(t.get_flag(), 123) members = dir(t) for member in ['flag', '_self_flag_', 'get_flag', '_self_tensor_', 'tensor']: self.assertIn( member, members, msg='{!r} should in dir(t), but not'.format(members) ) self.assertTrue( hasattr(t, member), msg='_SimpleTensor should has member {!r}, but not.'. format(member) ) for member in dir(t.tensor): if not member.startswith('_'): self.assertIn( member, members, msg='{!r} should in dir(t), but not'.format(members) ) self.assertTrue( hasattr(t, member), msg='_SimpleTensor should has member {!r}, but not.'. format(member,) ) self.assertEqual(getattr(t, member), getattr(t.tensor, member)) def test_set_attributes(self): t = _SimpleTensor(tf.constant([1., 2., 3.])) self.assertTrue(hasattr(t, '_self_flag_')) self.assertFalse(hasattr(t.tensor, '_self_flag_')) t._self_flag_ = 123 self.assertEqual(t._self_flag_, 123) self.assertFalse(hasattr(t.tensor, '_self_flag_')) self.assertTrue(hasattr(t, 'get_flag')) self.assertFalse(hasattr(t.tensor, 'get_flag')) t.get_flag = 456 self.assertEqual(t.get_flag, 456) self.assertTrue(hasattr(t, 'get_flag')) self.assertFalse(hasattr(t.tensor, 'get_flag')) self.assertTrue(hasattr(t, 'get_shape')) self.assertTrue(hasattr(t.tensor, 'get_shape')) t.get_shape = 789 self.assertEqual(t.get_shape, 789) self.assertEqual(t.tensor.get_shape, 789) self.assertTrue(hasattr(t, 'get_shape')) self.assertTrue(hasattr(t.tensor, 'get_shape')) t.abc = 1001 self.assertEqual(t.abc, 1001) self.assertEqual(t.tensor.abc, 1001) self.assertTrue(hasattr(t, 'abc')) self.assertTrue(hasattr(t.tensor, 'abc')) t.tensor.xyz = 2002 self.assertEqual(t.xyz, 2002) self.assertEqual(t.tensor.xyz, 2002) self.assertTrue(hasattr(t, 'xyz')) self.assertTrue(hasattr(t.tensor, 'xyz')) def test_del_attributes(self): t = _SimpleTensor(tf.constant([1., 2., 3.]), flag=123) del t._self_flag_ self.assertFalse(hasattr(t, '_self_flag_')) self.assertFalse(hasattr(t.tensor, '_self_flag_')) t.abc = 1001 del t.abc self.assertFalse(hasattr(t, 'abc')) self.assertFalse(hasattr(t.tensor, 'abc')) t.tensor.xyz = 2002 del t.xyz self.assertFalse(hasattr(t, 'xyz')) self.assertFalse(hasattr(t.tensor, 'xyz')) t.get_flag = 123 del t.get_flag self.assertFalse(hasattr(t.tensor, 'get_flag')) self.assertNotEqual(t.get_flag, 123) class _NonTensorWrapperClass(object): pass class RegisterTensorWrapperClassTestCase(tf.test.TestCase): def test_register_non_tensor_wrapper_class(self): with pytest.raises( TypeError, match='`.*_NonTensorWrapperClass.*` is not a type, ' 'or not a subclass of `TensorWrapper`'): register_tensor_wrapper_class(_NonTensorWrapperClass) with pytest.raises( TypeError, match='`123` is not a type, or not a subclass of ' '`TensorWrapper`'): register_tensor_wrapper_class(123)
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test recovery from a crash during chainstate writing. - 4 nodes * node0, node1, and node2 will have different dbcrash ratios, and different dbcache sizes * node3 will be a regular node, with no crashing. * The nodes will not connect to each other. - use default test framework starting chain. initialize starting_tip_height to tip height. - Main loop: * generate lots of transactions on node3, enough to fill up a block. * uniformly randomly pick a tip height from starting_tip_height to tip_height; with probability 1/(height_difference+4), invalidate this block. * mine enough blocks to overtake tip_height at start of loop. * for each node in [node0,node1,node2]: - for each mined block: * submit block to node * if node crashed on/after submitting: - restart until recovery succeeds - check that utxo matches node3 using gettxoutsetinfo""" import errno import http.client import random import sys import time from test_framework.mininode import * from test_framework.script import * from test_framework.test_framework import IoPTestFramework from test_framework.util import * HTTP_DISCONNECT_ERRORS = [http.client.CannotSendRequest] try: HTTP_DISCONNECT_ERRORS.append(http.client.RemoteDisconnected) except AttributeError: pass class ChainstateWriteCrashTest(IoPTestFramework): def set_test_params(self): self.num_nodes = 4 self.setup_clean_chain = False # Set -maxmempool=0 to turn off mempool memory sharing with dbcache # Set -rpcservertimeout=900 to reduce socket disconnects in this # long-running test self.base_args = ["-limitdescendantsize=0", "-maxmempool=0", "-rpcservertimeout=900", "-dbbatchsize=200000"] # Set different crash ratios and cache sizes. Note that not all of # -dbcache goes to pcoinsTip. self.node0_args = ["-dbcrashratio=8", "-dbcache=4"] + self.base_args self.node1_args = ["-dbcrashratio=16", "-dbcache=8"] + self.base_args self.node2_args = ["-dbcrashratio=24", "-dbcache=16"] + self.base_args # Node3 is a normal node with default args, except will mine full blocks self.node3_args = ["-blockmaxweight=4000000"] self.extra_args = [self.node0_args, self.node1_args, self.node2_args, self.node3_args] def setup_network(self): # Need a bit of extra time for the nodes to start up for this test self.add_nodes(self.num_nodes, extra_args=self.extra_args, timewait=90) self.start_nodes() # Leave them unconnected, we'll use submitblock directly in this test def restart_node(self, node_index, expected_tip): """Start up a given node id, wait for the tip to reach the given block hash, and calculate the utxo hash. Exceptions on startup should indicate node crash (due to -dbcrashratio), in which case we try again. Give up after 60 seconds. Returns the utxo hash of the given node.""" time_start = time.time() while time.time() - time_start < 120: try: # Any of these RPC calls could throw due to node crash self.start_node(node_index) self.nodes[node_index].waitforblock(expected_tip) utxo_hash = self.nodes[node_index].gettxoutsetinfo()['hash_serialized_2'] return utxo_hash except: # An exception here should mean the node is about to crash. # If iopd exits, then try again. wait_for_node_exit() # should raise an exception if iopd doesn't exit. self.wait_for_node_exit(node_index, timeout=10) self.crashed_on_restart += 1 time.sleep(1) # If we got here, iopd isn't coming back up on restart. Could be a # bug in iopd, or we've gotten unlucky with our dbcrash ratio -- # perhaps we generated a test case that blew up our cache? # TODO: If this happens a lot, we should try to restart without -dbcrashratio # and make sure that recovery happens. raise AssertionError("Unable to successfully restart node %d in allotted time", node_index) def submit_block_catch_error(self, node_index, block): """Try submitting a block to the given node. Catch any exceptions that indicate the node has crashed. Returns true if the block was submitted successfully; false otherwise.""" try: self.nodes[node_index].submitblock(block) return True except http.client.BadStatusLine as e: # Prior to 3.5 BadStatusLine('') was raised for a remote disconnect error. if sys.version_info[0] == 3 and sys.version_info[1] < 5 and e.line == "''": self.log.debug("node %d submitblock raised exception: %s", node_index, e) return False else: raise except tuple(HTTP_DISCONNECT_ERRORS) as e: self.log.debug("node %d submitblock raised exception: %s", node_index, e) return False except OSError as e: self.log.debug("node %d submitblock raised OSError exception: errno=%s", node_index, e.errno) if e.errno in [errno.EPIPE, errno.ECONNREFUSED, errno.ECONNRESET]: # The node has likely crashed return False else: # Unexpected exception, raise raise def sync_node3blocks(self, block_hashes): """Use submitblock to sync node3's chain with the other nodes If submitblock fails, restart the node and get the new utxo hash. If any nodes crash while updating, we'll compare utxo hashes to ensure recovery was successful.""" node3_utxo_hash = self.nodes[3].gettxoutsetinfo()['hash_serialized_2'] # Retrieve all the blocks from node3 blocks = [] for block_hash in block_hashes: blocks.append([block_hash, self.nodes[3].getblock(block_hash, 0)]) # Deliver each block to each other node for i in range(3): nodei_utxo_hash = None self.log.debug("Syncing blocks to node %d", i) for (block_hash, block) in blocks: # Get the block from node3, and submit to node_i self.log.debug("submitting block %s", block_hash) if not self.submit_block_catch_error(i, block): # TODO: more carefully check that the crash is due to -dbcrashratio # (change the exit code perhaps, and check that here?) self.wait_for_node_exit(i, timeout=30) self.log.debug("Restarting node %d after block hash %s", i, block_hash) nodei_utxo_hash = self.restart_node(i, block_hash) assert nodei_utxo_hash is not None self.restart_counts[i] += 1 else: # Clear it out after successful submitblock calls -- the cached # utxo hash will no longer be correct nodei_utxo_hash = None # Check that the utxo hash matches node3's utxo set # NOTE: we only check the utxo set if we had to restart the node # after the last block submitted: # - checking the utxo hash causes a cache flush, which we don't # want to do every time; so # - we only update the utxo cache after a node restart, since flushing # the cache is a no-op at that point if nodei_utxo_hash is not None: self.log.debug("Checking txoutsetinfo matches for node %d", i) assert_equal(nodei_utxo_hash, node3_utxo_hash) def verify_utxo_hash(self): """Verify that the utxo hash of each node matches node3. Restart any nodes that crash while querying.""" node3_utxo_hash = self.nodes[3].gettxoutsetinfo()['hash_serialized_2'] self.log.info("Verifying utxo hash matches for all nodes") for i in range(3): try: nodei_utxo_hash = self.nodes[i].gettxoutsetinfo()['hash_serialized_2'] except OSError: # probably a crash on db flushing nodei_utxo_hash = self.restart_node(i, self.nodes[3].getbestblockhash()) assert_equal(nodei_utxo_hash, node3_utxo_hash) def generate_small_transactions(self, node, count, utxo_list): FEE = 1000 # TODO: replace this with node relay fee based calculation num_transactions = 0 random.shuffle(utxo_list) while len(utxo_list) >= 2 and num_transactions < count: tx = CTransaction() input_amount = 0 for i in range(2): utxo = utxo_list.pop() tx.vin.append(CTxIn(COutPoint(int(utxo['txid'], 16), utxo['vout']))) input_amount += int(utxo['amount'] * COIN) output_amount = (input_amount - FEE) // 3 if output_amount <= 0: # Sanity check -- if we chose inputs that are too small, skip continue for i in range(3): tx.vout.append(CTxOut(output_amount, hex_str_to_bytes(utxo['scriptPubKey']))) # Sign and send the transaction to get into the mempool tx_signed_hex = node.signrawtransaction(ToHex(tx))['hex'] node.sendrawtransaction(tx_signed_hex) num_transactions += 1 def run_test(self): # Track test coverage statistics self.restart_counts = [0, 0, 0] # Track the restarts for nodes 0-2 self.crashed_on_restart = 0 # Track count of crashes during recovery # Start by creating a lot of utxos on node3 initial_height = self.nodes[3].getblockcount() utxo_list = create_confirmed_utxos(self.nodes[3].getnetworkinfo()['relayfee'], self.nodes[3], 5000) self.log.info("Prepped %d utxo entries", len(utxo_list)) # Sync these blocks with the other nodes block_hashes_to_sync = [] for height in range(initial_height + 1, self.nodes[3].getblockcount() + 1): block_hashes_to_sync.append(self.nodes[3].getblockhash(height)) self.log.debug("Syncing %d blocks with other nodes", len(block_hashes_to_sync)) # Syncing the blocks could cause nodes to crash, so the test begins here. self.sync_node3blocks(block_hashes_to_sync) starting_tip_height = self.nodes[3].getblockcount() # Main test loop: # each time through the loop, generate a bunch of transactions, # and then either mine a single new block on the tip, or some-sized reorg. for i in range(40): self.log.info("Iteration %d, generating 2500 transactions %s", i, self.restart_counts) # Generate a bunch of small-ish transactions self.generate_small_transactions(self.nodes[3], 2500, utxo_list) # Pick a random block between current tip, and starting tip current_height = self.nodes[3].getblockcount() random_height = random.randint(starting_tip_height, current_height) self.log.debug("At height %d, considering height %d", current_height, random_height) if random_height > starting_tip_height: # Randomly reorg from this point with some probability (1/4 for # tip, 1/5 for tip-1, ...) if random.random() < 1.0 / (current_height + 4 - random_height): self.log.debug("Invalidating block at height %d", random_height) self.nodes[3].invalidateblock(self.nodes[3].getblockhash(random_height)) # Now generate new blocks until we pass the old tip height self.log.debug("Mining longer tip") block_hashes = [] while current_height + 1 > self.nodes[3].getblockcount(): block_hashes.extend(self.nodes[3].generate(min(10, current_height + 1 - self.nodes[3].getblockcount()))) self.log.debug("Syncing %d new blocks...", len(block_hashes)) self.sync_node3blocks(block_hashes) utxo_list = self.nodes[3].listunspent() self.log.debug("Node3 utxo count: %d", len(utxo_list)) # Check that the utxo hashes agree with node3 # Useful side effect: each utxo cache gets flushed here, so that we # won't get crashes on shutdown at the end of the test. self.verify_utxo_hash() # Check the test coverage self.log.info("Restarted nodes: %s; crashes on restart: %d", self.restart_counts, self.crashed_on_restart) # If no nodes were restarted, we didn't test anything. assert self.restart_counts != [0, 0, 0] # Make sure we tested the case of crash-during-recovery. assert self.crashed_on_restart > 0 # Warn if any of the nodes escaped restart. for i in range(3): if self.restart_counts[i] == 0: self.log.warn("Node %d never crashed during utxo flush!", i) if __name__ == "__main__": ChainstateWriteCrashTest().main()
"""Event parser and human readable log generator.""" from datetime import timedelta from itertools import groupby import logging import voluptuous as vol from homeassistant.loader import bind_hass from homeassistant.components import sun from homeassistant.components.http import HomeAssistantView from homeassistant.const import ( ATTR_DOMAIN, ATTR_ENTITY_ID, ATTR_HIDDEN, ATTR_NAME, ATTR_SERVICE, CONF_EXCLUDE, CONF_INCLUDE, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, EVENT_LOGBOOK_ENTRY, EVENT_STATE_CHANGED, EVENT_AUTOMATION_TRIGGERED, EVENT_SCRIPT_STARTED, HTTP_BAD_REQUEST, STATE_NOT_HOME, STATE_OFF, STATE_ON) from homeassistant.core import ( DOMAIN as HA_DOMAIN, State, callback, split_entity_id) from homeassistant.components.alexa.smart_home import EVENT_ALEXA_SMART_HOME from homeassistant.components.homekit.const import ( ATTR_DISPLAY_NAME, ATTR_VALUE, DOMAIN as DOMAIN_HOMEKIT, EVENT_HOMEKIT_CHANGED) import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_MESSAGE = 'message' CONF_DOMAINS = 'domains' CONF_ENTITIES = 'entities' CONTINUOUS_DOMAINS = ['proximity', 'sensor'] DOMAIN = 'logbook' GROUP_BY_MINUTES = 15 CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ CONF_EXCLUDE: vol.Schema({ vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids, vol.Optional(CONF_DOMAINS, default=[]): vol.All(cv.ensure_list, [cv.string]), }), CONF_INCLUDE: vol.Schema({ vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids, vol.Optional(CONF_DOMAINS, default=[]): vol.All(cv.ensure_list, [cv.string]), }) }), }, extra=vol.ALLOW_EXTRA) ALL_EVENT_TYPES = [ EVENT_STATE_CHANGED, EVENT_LOGBOOK_ENTRY, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, EVENT_ALEXA_SMART_HOME, EVENT_HOMEKIT_CHANGED, EVENT_AUTOMATION_TRIGGERED, EVENT_SCRIPT_STARTED ] LOG_MESSAGE_SCHEMA = vol.Schema({ vol.Required(ATTR_NAME): cv.string, vol.Required(ATTR_MESSAGE): cv.template, vol.Optional(ATTR_DOMAIN): cv.slug, vol.Optional(ATTR_ENTITY_ID): cv.entity_id, }) @bind_hass def log_entry(hass, name, message, domain=None, entity_id=None): """Add an entry to the logbook.""" hass.add_job(async_log_entry, hass, name, message, domain, entity_id) @bind_hass def async_log_entry(hass, name, message, domain=None, entity_id=None): """Add an entry to the logbook.""" data = { ATTR_NAME: name, ATTR_MESSAGE: message } if domain is not None: data[ATTR_DOMAIN] = domain if entity_id is not None: data[ATTR_ENTITY_ID] = entity_id hass.bus.async_fire(EVENT_LOGBOOK_ENTRY, data) async def async_setup(hass, config): """Listen for download events to download files.""" @callback def log_message(service): """Handle sending notification message service calls.""" message = service.data[ATTR_MESSAGE] name = service.data[ATTR_NAME] domain = service.data.get(ATTR_DOMAIN) entity_id = service.data.get(ATTR_ENTITY_ID) message.hass = hass message = message.async_render() async_log_entry(hass, name, message, domain, entity_id) hass.http.register_view(LogbookView(config.get(DOMAIN, {}))) hass.components.frontend.async_register_built_in_panel( 'logbook', 'logbook', 'hass:format-list-bulleted-type') hass.services.async_register( DOMAIN, 'log', log_message, schema=LOG_MESSAGE_SCHEMA) return True class LogbookView(HomeAssistantView): """Handle logbook view requests.""" url = '/api/logbook' name = 'api:logbook' extra_urls = ['/api/logbook/{datetime}'] def __init__(self, config): """Initialize the logbook view.""" self.config = config async def get(self, request, datetime=None): """Retrieve logbook entries.""" if datetime: datetime = dt_util.parse_datetime(datetime) if datetime is None: return self.json_message('Invalid datetime', HTTP_BAD_REQUEST) else: datetime = dt_util.start_of_local_day() period = request.query.get('period') if period is None: period = 1 else: period = int(period) entity_id = request.query.get('entity') start_day = dt_util.as_utc(datetime) - timedelta(days=period - 1) end_day = start_day + timedelta(days=period) hass = request.app['hass'] def json_events(): """Fetch events and generate JSON.""" return self.json( _get_events(hass, self.config, start_day, end_day, entity_id)) return await hass.async_add_job(json_events) def humanify(hass, events): """Generate a converted list of events into Entry objects. Will try to group events if possible: - if 2+ sensor updates in GROUP_BY_MINUTES, show last - if home assistant stop and start happen in same minute call it restarted """ domain_prefixes = tuple('{}.'.format(dom) for dom in CONTINUOUS_DOMAINS) # Group events in batches of GROUP_BY_MINUTES for _, g_events in groupby( events, lambda event: event.time_fired.minute // GROUP_BY_MINUTES): events_batch = list(g_events) # Keep track of last sensor states last_sensor_event = {} # Group HA start/stop events # Maps minute of event to 1: stop, 2: stop + start start_stop_events = {} # Process events for event in events_batch: if event.event_type == EVENT_STATE_CHANGED: entity_id = event.data.get('entity_id') if entity_id.startswith(domain_prefixes): last_sensor_event[entity_id] = event elif event.event_type == EVENT_HOMEASSISTANT_STOP: if event.time_fired.minute in start_stop_events: continue start_stop_events[event.time_fired.minute] = 1 elif event.event_type == EVENT_HOMEASSISTANT_START: if event.time_fired.minute not in start_stop_events: continue start_stop_events[event.time_fired.minute] = 2 # Yield entries for event in events_batch: if event.event_type == EVENT_STATE_CHANGED: to_state = State.from_dict(event.data.get('new_state')) domain = to_state.domain # Skip all but the last sensor state if domain in CONTINUOUS_DOMAINS and \ event != last_sensor_event[to_state.entity_id]: continue # Don't show continuous sensor value changes in the logbook if domain in CONTINUOUS_DOMAINS and \ to_state.attributes.get('unit_of_measurement'): continue yield { 'when': event.time_fired, 'name': to_state.name, 'message': _entry_message_from_state(domain, to_state), 'domain': domain, 'entity_id': to_state.entity_id, 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_HOMEASSISTANT_START: if start_stop_events.get(event.time_fired.minute) == 2: continue yield { 'when': event.time_fired, 'name': "Home Assistant", 'message': "started", 'domain': HA_DOMAIN, 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_HOMEASSISTANT_STOP: if start_stop_events.get(event.time_fired.minute) == 2: action = "restarted" else: action = "stopped" yield { 'when': event.time_fired, 'name': "Home Assistant", 'message': action, 'domain': HA_DOMAIN, 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_LOGBOOK_ENTRY: domain = event.data.get(ATTR_DOMAIN) entity_id = event.data.get(ATTR_ENTITY_ID) if domain is None and entity_id is not None: try: domain = split_entity_id(str(entity_id))[0] except IndexError: pass yield { 'when': event.time_fired, 'name': event.data.get(ATTR_NAME), 'message': event.data.get(ATTR_MESSAGE), 'domain': domain, 'entity_id': entity_id, 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_ALEXA_SMART_HOME: data = event.data entity_id = data['request'].get('entity_id') if entity_id: state = hass.states.get(entity_id) name = state.name if state else entity_id message = "send command {}/{} for {}".format( data['request']['namespace'], data['request']['name'], name) else: message = "send command {}/{}".format( data['request']['namespace'], data['request']['name']) yield { 'when': event.time_fired, 'name': 'Amazon Alexa', 'message': message, 'domain': 'alexa', 'entity_id': entity_id, 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_HOMEKIT_CHANGED: data = event.data entity_id = data.get(ATTR_ENTITY_ID) value = data.get(ATTR_VALUE) value_msg = " to {}".format(value) if value else '' message = "send command {}{} for {}".format( data[ATTR_SERVICE], value_msg, data[ATTR_DISPLAY_NAME]) yield { 'when': event.time_fired, 'name': 'HomeKit', 'message': message, 'domain': DOMAIN_HOMEKIT, 'entity_id': entity_id, 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_AUTOMATION_TRIGGERED: yield { 'when': event.time_fired, 'name': event.data.get(ATTR_NAME), 'message': "has been triggered", 'domain': 'automation', 'entity_id': event.data.get(ATTR_ENTITY_ID), 'context_id': event.context.id, 'context_user_id': event.context.user_id } elif event.event_type == EVENT_SCRIPT_STARTED: yield { 'when': event.time_fired, 'name': event.data.get(ATTR_NAME), 'message': 'started', 'domain': 'script', 'entity_id': event.data.get(ATTR_ENTITY_ID), 'context_id': event.context.id, 'context_user_id': event.context.user_id } def _get_related_entity_ids(session, entity_filter): from homeassistant.components.recorder.models import States from homeassistant.components.recorder.util import \ RETRIES, QUERY_RETRY_WAIT from sqlalchemy.exc import SQLAlchemyError import time timer_start = time.perf_counter() query = session.query(States).with_entities(States.entity_id).distinct() for tryno in range(0, RETRIES): try: result = [ row.entity_id for row in query if entity_filter(row.entity_id)] if _LOGGER.isEnabledFor(logging.DEBUG): elapsed = time.perf_counter() - timer_start _LOGGER.debug( 'fetching %d distinct domain/entity_id pairs took %fs', len(result), elapsed) return result except SQLAlchemyError as err: _LOGGER.error("Error executing query: %s", err) if tryno == RETRIES - 1: raise time.sleep(QUERY_RETRY_WAIT) def _generate_filter_from_config(config): from homeassistant.helpers.entityfilter import generate_filter excluded_entities = [] excluded_domains = [] included_entities = [] included_domains = [] exclude = config.get(CONF_EXCLUDE) if exclude: excluded_entities = exclude.get(CONF_ENTITIES, []) excluded_domains = exclude.get(CONF_DOMAINS, []) include = config.get(CONF_INCLUDE) if include: included_entities = include.get(CONF_ENTITIES, []) included_domains = include.get(CONF_DOMAINS, []) return generate_filter(included_domains, included_entities, excluded_domains, excluded_entities) def _get_events(hass, config, start_day, end_day, entity_id=None): """Get events for a period of time.""" from homeassistant.components.recorder.models import Events, States from homeassistant.components.recorder.util import session_scope entities_filter = _generate_filter_from_config(config) def yield_events(query): """Yield Events that are not filtered away.""" for row in query.yield_per(500): event = row.to_native() if _keep_event(event, entities_filter): yield event with session_scope(hass=hass) as session: if entity_id is not None: entity_ids = [entity_id.lower()] else: entity_ids = _get_related_entity_ids(session, entities_filter) query = session.query(Events).order_by(Events.time_fired) \ .outerjoin(States, (Events.event_id == States.event_id)) \ .filter(Events.event_type.in_(ALL_EVENT_TYPES)) \ .filter((Events.time_fired > start_day) & (Events.time_fired < end_day)) \ .filter(((States.last_updated == States.last_changed) & States.entity_id.in_(entity_ids)) | (States.state_id.is_(None))) return list(humanify(hass, yield_events(query))) def _keep_event(event, entities_filter): domain, entity_id = None, None if event.event_type == EVENT_STATE_CHANGED: entity_id = event.data.get('entity_id') if entity_id is None: return False # Do not report on new entities if event.data.get('old_state') is None: return False new_state = event.data.get('new_state') # Do not report on entity removal if not new_state: return False attributes = new_state.get('attributes', {}) # If last_changed != last_updated only attributes have changed # we do not report on that yet. last_changed = new_state.get('last_changed') last_updated = new_state.get('last_updated') if last_changed != last_updated: return False domain = split_entity_id(entity_id)[0] # Also filter auto groups. if domain == 'group' and attributes.get('auto', False): return False # exclude entities which are customized hidden hidden = attributes.get(ATTR_HIDDEN, False) if hidden: return False elif event.event_type == EVENT_LOGBOOK_ENTRY: domain = event.data.get(ATTR_DOMAIN) entity_id = event.data.get(ATTR_ENTITY_ID) elif event.event_type == EVENT_AUTOMATION_TRIGGERED: domain = 'automation' entity_id = event.data.get(ATTR_ENTITY_ID) elif event.event_type == EVENT_SCRIPT_STARTED: domain = 'script' entity_id = event.data.get(ATTR_ENTITY_ID) elif event.event_type == EVENT_ALEXA_SMART_HOME: domain = 'alexa' elif event.event_type == EVENT_HOMEKIT_CHANGED: domain = DOMAIN_HOMEKIT if not entity_id and domain: entity_id = "%s." % (domain, ) return not entity_id or entities_filter(entity_id) def _entry_message_from_state(domain, state): """Convert a state to a message for the logbook.""" # We pass domain in so we don't have to split entity_id again if domain == 'device_tracker': if state.state == STATE_NOT_HOME: return 'is away' return 'is at {}'.format(state.state) if domain == 'sun': if state.state == sun.STATE_ABOVE_HORIZON: return 'has risen' return 'has set' if state.state == STATE_ON: # Future: combine groups and its entity entries ? return "turned on" if state.state == STATE_OFF: return "turned off" return "changed to {}".format(state.state)
# Copyright (c) 2011 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import hmac import unittest from hashlib import sha1 from StringIO import StringIO from time import time from swift.common.swob import Request, Response from swift.common.middleware import tempauth, formpost from swift.common.utils import split_path class FakeApp(object): def __init__(self, status_headers_body_iter=None, check_no_query_string=True): self.status_headers_body_iter = status_headers_body_iter if not self.status_headers_body_iter: self.status_headers_body_iter = iter([('404 Not Found', { 'x-test-header-one-a': 'value1', 'x-test-header-two-a': 'value2', 'x-test-header-two-b': 'value3'}, '')]) self.requests = [] self.check_no_query_string = check_no_query_string def __call__(self, env, start_response): if self.check_no_query_string and env.get('QUERY_STRING'): raise Exception('Query string %s should have been discarded!' % env['QUERY_STRING']) body = '' while True: chunk = env['wsgi.input'].read() if not chunk: break body += chunk env['wsgi.input'] = StringIO(body) self.requests.append(Request.blank('', environ=env)) if env.get('swift.authorize_override') and \ env.get('REMOTE_USER') != '.wsgi.pre_authed': raise Exception( 'Invalid REMOTE_USER %r with swift.authorize_override' % ( env.get('REMOTE_USER'),)) if 'swift.authorize' in env: resp = env['swift.authorize'](self.requests[-1]) if resp: return resp(env, start_response) status, headers, body = self.status_headers_body_iter.next() return Response(status=status, headers=headers, body=body)(env, start_response) class TestParseAttrs(unittest.TestCase): def test_basic_content_type(self): name, attrs = formpost._parse_attrs('text/plain') self.assertEquals(name, 'text/plain') self.assertEquals(attrs, {}) def test_content_type_with_charset(self): name, attrs = formpost._parse_attrs('text/plain; charset=UTF8') self.assertEquals(name, 'text/plain') self.assertEquals(attrs, {'charset': 'UTF8'}) def test_content_disposition(self): name, attrs = formpost._parse_attrs( 'form-data; name="somefile"; filename="test.html"') self.assertEquals(name, 'form-data') self.assertEquals(attrs, {'name': 'somefile', 'filename': 'test.html'}) class TestIterRequests(unittest.TestCase): def test_bad_start(self): it = formpost._iter_requests(StringIO('blah'), 'unique') exc = None try: it.next() except formpost.FormInvalid as err: exc = err self.assertEquals(str(exc), 'invalid starting boundary') def test_empty(self): it = formpost._iter_requests(StringIO('--unique'), 'unique') fp = it.next() self.assertEquals(fp.read(), '') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_basic(self): it = formpost._iter_requests( StringIO('--unique\r\nabcdefg\r\n--unique--'), 'unique') fp = it.next() self.assertEquals(fp.read(), 'abcdefg') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_basic2(self): it = formpost._iter_requests( StringIO('--unique\r\nabcdefg\r\n--unique\r\nhijkl\r\n--unique--'), 'unique') fp = it.next() self.assertEquals(fp.read(), 'abcdefg') fp = it.next() self.assertEquals(fp.read(), 'hijkl') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_tiny_reads(self): it = formpost._iter_requests( StringIO('--unique\r\nabcdefg\r\n--unique\r\nhijkl\r\n--unique--'), 'unique') fp = it.next() self.assertEquals(fp.read(2), 'ab') self.assertEquals(fp.read(2), 'cd') self.assertEquals(fp.read(2), 'ef') self.assertEquals(fp.read(2), 'g') self.assertEquals(fp.read(2), '') fp = it.next() self.assertEquals(fp.read(), 'hijkl') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_big_reads(self): it = formpost._iter_requests( StringIO('--unique\r\nabcdefg\r\n--unique\r\nhijkl\r\n--unique--'), 'unique') fp = it.next() self.assertEquals(fp.read(65536), 'abcdefg') self.assertEquals(fp.read(), '') fp = it.next() self.assertEquals(fp.read(), 'hijkl') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_broken_mid_stream(self): # We go ahead and accept whatever is sent instead of rejecting the # whole request, in case the partial form is still useful. it = formpost._iter_requests( StringIO('--unique\r\nabc'), 'unique') fp = it.next() self.assertEquals(fp.read(), 'abc') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_readline(self): it = formpost._iter_requests( StringIO('--unique\r\nab\r\ncd\ref\ng\r\n--unique\r\nhi\r\n\r\n' 'jkl\r\n\r\n--unique--'), 'unique') fp = it.next() self.assertEquals(fp.readline(), 'ab\r\n') self.assertEquals(fp.readline(), 'cd\ref\ng') self.assertEquals(fp.readline(), '') fp = it.next() self.assertEquals(fp.readline(), 'hi\r\n') self.assertEquals(fp.readline(), '\r\n') self.assertEquals(fp.readline(), 'jkl\r\n') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) def test_readline_with_tiny_chunks(self): orig_read_chunk_size = formpost.READ_CHUNK_SIZE try: formpost.READ_CHUNK_SIZE = 2 it = formpost._iter_requests( StringIO('--unique\r\nab\r\ncd\ref\ng\r\n--unique\r\nhi\r\n' '\r\njkl\r\n\r\n--unique--'), 'unique') fp = it.next() self.assertEquals(fp.readline(), 'ab\r\n') self.assertEquals(fp.readline(), 'cd\ref\ng') self.assertEquals(fp.readline(), '') fp = it.next() self.assertEquals(fp.readline(), 'hi\r\n') self.assertEquals(fp.readline(), '\r\n') self.assertEquals(fp.readline(), 'jkl\r\n') exc = None try: it.next() except StopIteration as err: exc = err self.assertTrue(exc is not None) finally: formpost.READ_CHUNK_SIZE = orig_read_chunk_size class TestCappedFileLikeObject(unittest.TestCase): def test_whole(self): self.assertEquals( formpost._CappedFileLikeObject(StringIO('abc'), 10).read(), 'abc') def test_exceeded(self): exc = None try: formpost._CappedFileLikeObject(StringIO('abc'), 2).read() except EOFError as err: exc = err self.assertEquals(str(exc), 'max_file_size exceeded') def test_whole_readline(self): fp = formpost._CappedFileLikeObject(StringIO('abc\ndef'), 10) self.assertEquals(fp.readline(), 'abc\n') self.assertEquals(fp.readline(), 'def') self.assertEquals(fp.readline(), '') def test_exceeded_readline(self): fp = formpost._CappedFileLikeObject(StringIO('abc\ndef'), 5) self.assertEquals(fp.readline(), 'abc\n') exc = None try: self.assertEquals(fp.readline(), 'def') except EOFError as err: exc = err self.assertEquals(str(exc), 'max_file_size exceeded') def test_read_sized(self): fp = formpost._CappedFileLikeObject(StringIO('abcdefg'), 10) self.assertEquals(fp.read(2), 'ab') self.assertEquals(fp.read(2), 'cd') self.assertEquals(fp.read(2), 'ef') self.assertEquals(fp.read(2), 'g') self.assertEquals(fp.read(2), '') class TestFormPost(unittest.TestCase): def setUp(self): self.app = FakeApp() self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) def _make_request(self, path, tempurl_keys=(), **kwargs): req = Request.blank(path, **kwargs) # Fake out the caching layer so that get_account_info() finds its # data. Include something that isn't tempurl keys to prove we skip it. meta = {'user-job-title': 'Personal Trainer', 'user-real-name': 'Jim Shortz'} for idx, key in enumerate(tempurl_keys): meta_name = 'temp-url-key' + (("-%d" % (idx + 1) if idx else "")) if key: meta[meta_name] = key _junk, account, _junk, _junk = split_path(path, 2, 4) req.environ['swift.account/' + account] = self._fake_cache_env( account, tempurl_keys) return req def _fake_cache_env(self, account, tempurl_keys=()): # Fake out the caching layer so that get_account_info() finds its # data. Include something that isn't tempurl keys to prove we skip it. meta = {'user-job-title': 'Personal Trainer', 'user-real-name': 'Jim Shortz'} for idx, key in enumerate(tempurl_keys): meta_name = 'temp-url-key' + ("-%d" % (idx + 1) if idx else "") if key: meta[meta_name] = key return {'status': 204, 'container_count': '0', 'total_object_count': '0', 'bytes': '0', 'meta': meta} def _make_sig_env_body(self, path, redirect, max_file_size, max_file_count, expires, key, user_agent=True): sig = hmac.new( key, '%s\n%s\n%s\n%s\n%s' % ( path, redirect, max_file_size, max_file_count, expires), sha1).hexdigest() body = [ '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="redirect"', '', redirect, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="expires"', '', str(expires), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="signature"', '', sig, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file1"; ' 'filename="testfile1.txt"', 'Content-Type: text/plain', '', 'Test File\nOne\n', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file2"; ' 'filename="testfile2.txt"', 'Content-Type: text/plain', '', 'Test\nFile\nTwo\n', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file3"; filename=""', 'Content-Type: application/octet-stream', '', '', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR--', '', ] wsgi_errors = StringIO() env = { 'CONTENT_TYPE': 'multipart/form-data; ' 'boundary=----WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'en-us', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,*/*;q=0.8', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'ubuntu:8080', 'HTTP_ORIGIN': 'file://', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X ' '10_7_2) AppleWebKit/534.52.7 (KHTML, like Gecko) ' 'Version/5.1.2 Safari/534.52.7', 'PATH_INFO': path, 'REMOTE_ADDR': '172.16.83.1', 'REQUEST_METHOD': 'POST', 'SCRIPT_NAME': '', 'SERVER_NAME': '172.16.83.128', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'wsgi.errors': wsgi_errors, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } if user_agent is False: del env['HTTP_USER_AGENT'] return sig, env, body def test_passthrough(self): for method in ('HEAD', 'GET', 'PUT', 'POST', 'DELETE'): resp = self._make_request( '/v1/a/c/o', environ={'REQUEST_METHOD': method}).get_response(self.formpost) self.assertEquals(resp.status_int, 401) self.assertTrue('FormPost' not in resp.body) def test_auth_scheme(self): # FormPost rejects key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, int(time() - 10), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') authenticate_v = None for h, v in headers: if h.lower() == 'www-authenticate': authenticate_v = v self.assertTrue('FormPost: Form Expired' in body) self.assertEquals('Swift realm="unknown"', authenticate_v) def test_safari(self): key = 'abc' path = '/v1/AUTH_test/container' redirect = 'http://brim.net' max_file_size = 1024 max_file_count = 10 expires = int(time() + 86400) sig = hmac.new( key, '%s\n%s\n%s\n%s\n%s' % ( path, redirect, max_file_size, max_file_count, expires), sha1).hexdigest() wsgi_input = StringIO('\r\n'.join([ '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="redirect"', '', redirect, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="expires"', '', str(expires), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="signature"', '', sig, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file1"; ' 'filename="testfile1.txt"', 'Content-Type: text/plain', '', 'Test File\nOne\n', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file2"; ' 'filename="testfile2.txt"', 'Content-Type: text/plain', '', 'Test\nFile\nTwo\n', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file3"; filename=""', 'Content-Type: application/octet-stream', '', '', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR--', '', ])) wsgi_errors = StringIO() env = { 'CONTENT_TYPE': 'multipart/form-data; ' 'boundary=----WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'en-us', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,*/*;q=0.8', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'ubuntu:8080', 'HTTP_ORIGIN': 'file://', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X ' '10_7_2) AppleWebKit/534.52.7 (KHTML, like Gecko) ' 'Version/5.1.2 Safari/534.52.7', 'PATH_INFO': path, 'REMOTE_ADDR': '172.16.83.1', 'REQUEST_METHOD': 'POST', 'SCRIPT_NAME': '', 'SERVER_NAME': '172.16.83.128', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'swift.account/AUTH_test': self._fake_cache_env( 'AUTH_test', [key]), 'wsgi.errors': wsgi_errors, 'wsgi.input': wsgi_input, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://brim.net?status=201&message=') self.assertEquals(exc_info, None) self.assertTrue('http://brim.net?status=201&message=' in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_firefox(self): key = 'abc' path = '/v1/AUTH_test/container' redirect = 'http://brim.net' max_file_size = 1024 max_file_count = 10 expires = int(time() + 86400) sig = hmac.new( key, '%s\n%s\n%s\n%s\n%s' % ( path, redirect, max_file_size, max_file_count, expires), sha1).hexdigest() wsgi_input = StringIO('\r\n'.join([ '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="redirect"', '', redirect, '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="expires"', '', str(expires), '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="signature"', '', sig, '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="file1"; ' 'filename="testfile1.txt"', 'Content-Type: text/plain', '', 'Test File\nOne\n', '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="file2"; ' 'filename="testfile2.txt"', 'Content-Type: text/plain', '', 'Test\nFile\nTwo\n', '-----------------------------168072824752491622650073', 'Content-Disposition: form-data; name="file3"; filename=""', 'Content-Type: application/octet-stream', '', '', '-----------------------------168072824752491622650073--', '' ])) wsgi_errors = StringIO() env = { 'CONTENT_TYPE': 'multipart/form-data; ' 'boundary=---------------------------168072824752491622650073', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,*/*;q=0.8', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'ubuntu:8080', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; ' 'rv:8.0.1) Gecko/20100101 Firefox/8.0.1', 'PATH_INFO': '/v1/AUTH_test/container', 'REMOTE_ADDR': '172.16.83.1', 'REQUEST_METHOD': 'POST', 'SCRIPT_NAME': '', 'SERVER_NAME': '172.16.83.128', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'swift.account/AUTH_test': self._fake_cache_env( 'AUTH_test', [key]), 'wsgi.errors': wsgi_errors, 'wsgi.input': wsgi_input, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://brim.net?status=201&message=') self.assertEquals(exc_info, None) self.assertTrue('http://brim.net?status=201&message=' in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_chrome(self): key = 'abc' path = '/v1/AUTH_test/container' redirect = 'http://brim.net' max_file_size = 1024 max_file_count = 10 expires = int(time() + 86400) sig = hmac.new( key, '%s\n%s\n%s\n%s\n%s' % ( path, redirect, max_file_size, max_file_count, expires), sha1).hexdigest() wsgi_input = StringIO('\r\n'.join([ '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="redirect"', '', redirect, '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="expires"', '', str(expires), '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="signature"', '', sig, '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="file1"; ' 'filename="testfile1.txt"', 'Content-Type: text/plain', '', 'Test File\nOne\n', '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="file2"; ' 'filename="testfile2.txt"', 'Content-Type: text/plain', '', 'Test\nFile\nTwo\n', '------WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'Content-Disposition: form-data; name="file3"; filename=""', 'Content-Type: application/octet-stream', '', '', '------WebKitFormBoundaryq3CFxUjfsDMu8XsA--', '' ])) wsgi_errors = StringIO() env = { 'CONTENT_TYPE': 'multipart/form-data; ' 'boundary=----WebKitFormBoundaryq3CFxUjfsDMu8XsA', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,*/*;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'ubuntu:8080', 'HTTP_ORIGIN': 'null', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X ' '10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) ' 'Chrome/16.0.912.63 Safari/535.7', 'PATH_INFO': '/v1/AUTH_test/container', 'REMOTE_ADDR': '172.16.83.1', 'REQUEST_METHOD': 'POST', 'SCRIPT_NAME': '', 'SERVER_NAME': '172.16.83.128', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'swift.account/AUTH_test': self._fake_cache_env( 'AUTH_test', [key]), 'wsgi.errors': wsgi_errors, 'wsgi.input': wsgi_input, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://brim.net?status=201&message=') self.assertEquals(exc_info, None) self.assertTrue('http://brim.net?status=201&message=' in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_explorer(self): key = 'abc' path = '/v1/AUTH_test/container' redirect = 'http://brim.net' max_file_size = 1024 max_file_count = 10 expires = int(time() + 86400) sig = hmac.new( key, '%s\n%s\n%s\n%s\n%s' % ( path, redirect, max_file_size, max_file_count, expires), sha1).hexdigest() wsgi_input = StringIO('\r\n'.join([ '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="redirect"', '', redirect, '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="expires"', '', str(expires), '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="signature"', '', sig, '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="file1"; ' 'filename="C:\\testfile1.txt"', 'Content-Type: text/plain', '', 'Test File\nOne\n', '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="file2"; ' 'filename="C:\\testfile2.txt"', 'Content-Type: text/plain', '', 'Test\nFile\nTwo\n', '-----------------------------7db20d93017c', 'Content-Disposition: form-data; name="file3"; filename=""', 'Content-Type: application/octet-stream', '', '', '-----------------------------7db20d93017c--', '' ])) wsgi_errors = StringIO() env = { 'CONTENT_TYPE': 'multipart/form-data; ' 'boundary=---------------------------7db20d93017c', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'en-US', 'HTTP_ACCEPT': 'text/html, application/xhtml+xml, */*', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_CONNECTION': 'Keep-Alive', 'HTTP_HOST': '172.16.83.128:8080', 'HTTP_USER_AGENT': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT ' '6.1; WOW64; Trident/5.0)', 'PATH_INFO': '/v1/AUTH_test/container', 'REMOTE_ADDR': '172.16.83.129', 'REQUEST_METHOD': 'POST', 'SCRIPT_NAME': '', 'SERVER_NAME': '172.16.83.128', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'swift.account/AUTH_test': self._fake_cache_env( 'AUTH_test', [key]), 'wsgi.errors': wsgi_errors, 'wsgi.input': wsgi_input, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://brim.net?status=201&message=') self.assertEquals(exc_info, None) self.assertTrue('http://brim.net?status=201&message=' in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_messed_up_start(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://brim.net', 5, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('XX' + '\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) def log_assert_int_status(env, response_status_int): self.assertTrue(isinstance(response_status_int, int)) self.formpost._log_request = log_assert_int_status status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '400 Bad Request') self.assertEquals(exc_info, None) self.assertTrue('FormPost: invalid starting boundary' in body) self.assertEquals(len(self.app.requests), 0) def test_max_file_size_exceeded(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://brim.net', 5, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '400 Bad Request') self.assertEquals(exc_info, None) self.assertTrue('FormPost: max_file_size exceeded' in body) self.assertEquals(len(self.app.requests), 0) def test_max_file_count_exceeded(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://brim.net', 1024, 1, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals( location, 'http://brim.net?status=400&message=max%20file%20count%20exceeded') self.assertEquals(exc_info, None) self.assertTrue( 'http://brim.net?status=400&message=max%20file%20count%20exceeded' in body) self.assertEquals(len(self.app.requests), 1) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') def test_subrequest_does_not_pass_query(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, int(time() + 86400), key) env['QUERY_STRING'] = 'this=should&not=get&passed' env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp( iter([('201 Created', {}, ''), ('201 Created', {}, '')]), check_no_query_string=True) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] # Make sure we 201 Created, which means we made the final subrequest # (and FakeApp verifies that no QUERY_STRING got passed). self.assertEquals(status, '201 Created') self.assertEquals(exc_info, None) self.assertTrue('201 Created' in body) self.assertEquals(len(self.app.requests), 2) def test_subrequest_fails(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://brim.net', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('404 Not Found', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://brim.net?status=404&message=') self.assertEquals(exc_info, None) self.assertTrue('http://brim.net?status=404&message=' in body) self.assertEquals(len(self.app.requests), 1) def test_truncated_attr_value(self): key = 'abc' redirect = 'a' * formpost.MAX_VALUE_LENGTH max_file_size = 1024 max_file_count = 10 expires = int(time() + 86400) sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', redirect, max_file_size, max_file_count, expires, key) # Tack on an extra char to redirect, but shouldn't matter since it # should get truncated off on read. redirect += 'b' env['wsgi.input'] = StringIO('\r\n'.join([ '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="redirect"', '', redirect, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="expires"', '', str(expires), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="signature"', '', sig, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file1"; ' 'filename="testfile1.txt"', 'Content-Type: text/plain', '', 'Test File\nOne\n', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file2"; ' 'filename="testfile2.txt"', 'Content-Type: text/plain', '', 'Test\nFile\nTwo\n', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="file3"; filename=""', 'Content-Type: application/octet-stream', '', '', '------WebKitFormBoundaryNcxTqxSlX7t4TDkR--', '', ])) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals( location, ('a' * formpost.MAX_VALUE_LENGTH) + '?status=201&message=') self.assertEquals(exc_info, None) self.assertTrue( ('a' * formpost.MAX_VALUE_LENGTH) + '?status=201&message=' in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_no_file_to_process(self): key = 'abc' redirect = 'http://brim.net' max_file_size = 1024 max_file_count = 10 expires = int(time() + 86400) sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', redirect, max_file_size, max_file_count, expires, key) env['wsgi.input'] = StringIO('\r\n'.join([ '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="redirect"', '', redirect, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_size"', '', str(max_file_size), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="max_file_count"', '', str(max_file_count), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="expires"', '', str(expires), '------WebKitFormBoundaryNcxTqxSlX7t4TDkR', 'Content-Disposition: form-data; name="signature"', '', sig, '------WebKitFormBoundaryNcxTqxSlX7t4TDkR--', '', ])) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals( location, 'http://brim.net?status=400&message=no%20files%20to%20process') self.assertEquals(exc_info, None) self.assertTrue( 'http://brim.net?status=400&message=no%20files%20to%20process' in body) self.assertEquals(len(self.app.requests), 0) def test_formpost_without_useragent(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://redirect', 1024, 10, int(time() + 86400), key, user_agent=False) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) def start_response(s, h, e=None): pass body = ''.join(self.formpost(env, start_response)) self.assertTrue('User-Agent' in self.app.requests[0].headers) self.assertEquals(self.app.requests[0].headers['User-Agent'], 'FormPost') def test_formpost_with_origin(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://redirect', 1024, 10, int(time() + 86400), key, user_agent=False) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) env['HTTP_ORIGIN'] = 'http://localhost:5000' self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {'Access-Control-Allow-Origin': 'http://localhost:5000'}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) headers = {} def start_response(s, h, e=None): for k, v in h: headers[k] = v pass body = ''.join(self.formpost(env, start_response)) self.assertEquals(headers['Access-Control-Allow-Origin'], 'http://localhost:5000') def test_formpost_with_multiple_keys(self): key = 'ernie' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://redirect', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) # Stick it in X-Account-Meta-Temp-URL-Key-2 and make sure we get it env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', ['bert', key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h body = ''.join(self.formpost(env, start_response)) print repr(headers) self.assertEqual('303 See Other', status[0]) self.assertEqual( 'http://redirect?status=201&message=', dict(headers[0]).get('Location')) def test_redirect(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://redirect', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://redirect?status=201&message=') self.assertEquals(exc_info, None) self.assertTrue(location in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_redirect_with_query(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', 'http://redirect?one=two', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '303 See Other') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, 'http://redirect?one=two&status=201&message=') self.assertEquals(exc_info, None) self.assertTrue(location in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_no_redirect(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '201 Created') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('201 Created' in body) self.assertEquals(len(self.app.requests), 2) self.assertEquals(self.app.requests[0].body, 'Test File\nOne\n') self.assertEquals(self.app.requests[1].body, 'Test\nFile\nTwo\n') def test_no_redirect_expired(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, int(time() - 10), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Form Expired' in body) def test_no_redirect_invalid_sig(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) # Change key to invalidate sig env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key + ' is bogus now']) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Invalid Signature' in body) def test_no_redirect_with_error(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('XX' + '\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '400 Bad Request') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: invalid starting boundary' in body) def test_no_v1(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v2/AUTH_test/container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Invalid Signature' in body) def test_empty_v1(self): key = 'abc' sig, env, body = self._make_sig_env_body( '//AUTH_test/container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Invalid Signature' in body) def test_empty_account(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1//container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Invalid Signature' in body) def test_wrong_account(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_tst/container', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([ ('200 Ok', {'x-account-meta-temp-url-key': 'def'}, ''), ('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Invalid Signature' in body) def test_no_container(self): key = 'abc' sig, env, body = self._make_sig_env_body( '/v1/AUTH_test', '', 1024, 10, int(time() + 86400), key) env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '401 Unauthorized') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: Invalid Signature' in body) def test_completely_non_int_expires(self): key = 'abc' expires = int(time() + 86400) sig, env, body = self._make_sig_env_body( '/v1/AUTH_test/container', '', 1024, 10, expires, key) for i, v in enumerate(body): if v == str(expires): body[i] = 'badvalue' break env['wsgi.input'] = StringIO('\r\n'.join(body)) env['swift.account/AUTH_test'] = self._fake_cache_env( 'AUTH_test', [key]) self.app = FakeApp(iter([('201 Created', {}, ''), ('201 Created', {}, '')])) self.auth = tempauth.filter_factory({})(self.app) self.formpost = formpost.filter_factory({})(self.auth) status = [None] headers = [None] exc_info = [None] def start_response(s, h, e=None): status[0] = s headers[0] = h exc_info[0] = e body = ''.join(self.formpost(env, start_response)) status = status[0] headers = headers[0] exc_info = exc_info[0] self.assertEquals(status, '400 Bad Request') location = None for h, v in headers: if h.lower() == 'location': location = v self.assertEquals(location, None) self.assertEquals(exc_info, None) self.assertTrue('FormPost: expired not an integer' in body) if __name__ == '__main__': unittest.main()
"""Astronomical observations calculations. """ import numpy as np from zcode.constants import PC, SPLC, JY # LOTS OF REFERENCE FLUXES: https://coolwiki.ipac.caltech.edu/index.php/Central_wavelengths_and_zero_points # VEGA/Johnson/Bessell: http://web.ipac.caltech.edu/staff/fmasci/home/astro_refs/magsystems.pdf # SDSS/AB/Fukugita: http://www.astronomy.ohio-state.edu/~martini/usefuldata.html # These wavelengths are in [cm] BAND_EFF_LOC = { # Vega/Johnson/Bessell "U": {"l": 366e-7}, "B": {"l": 438e-7}, "V": {"l": 545e-7}, "R": {"l": 641e-7}, "I": {"l": 798e-7}, # SDSS AB Magnitudes "u": {"l": 356e-7}, "g": {"l": 483e-7}, "r": {"l": 626e-7}, "i": {"l": 767e-7}, "z": {"l": 910e-7} } BAND_REF_FLUX = { # Vega/Johnson/Bessell "U": {"f": 1.790, "l": 417.5}, "B": {"f": 4.063, "l": 632.0}, "V": {"f": 2.636, "l": 363.1}, "R": {"f": 3.064, "l": 217.7}, "I": {"f": 2.416, "l": 112.6}, # SDSS AB Magnitudes "u": {"f": 3.631, "l": 859.5}, "g": {"f": 3.631, "l": 466.9}, "r": {"f": 3.631, "l": 278.0}, "i": {"f": 3.631, "l": 185.2}, "z": {"f": 3.631, "l": 131.5} } BAND_ZERO_POINT = { # Vega/Johnson/Bessell "U": {"f": +0.770, "l": -0.152}, "B": {"f": -0.120, "l": -0.602}, "V": {"f": +0.000, "l": +0.000}, "R": {"f": +0.186, "l": +0.555}, "I": {"f": +0.444, "l": +1.271}, # SDSS AB Magnitudes "u": {"f": 0.0, "l": 0.0}, "g": {"f": 0.0, "l": 0.0}, "r": {"f": 0.0, "l": 0.0}, "i": {"f": 0.0, "l": 0.0}, "z": {"f": 0.0, "l": 0.0} } UNITS = { "f": 1.0e-20, # erg/s/Hz/cm^2 "l": 1.0e-11 # erg/s/Angstrom/cm^2 } __all__ = ["ABmag_to_flux", "abs_mag_to_lum", "flux_to_mag", "mag_to_flux_zero", "lum_to_abs_mag", "mag_to_flux", "fnu_to_flambda", "flambda_to_fnu"] # _band_name = ['u', 'b', 'v', 'r', 'i'] # _band_wlen = [365, 445, 551, 658, 806] # nm # _band_color = ['violet', 'blue', 'green', 'red', 'darkred'] # Band = namedtuple('band', ['name', 'freq', 'wlen', 'color']) # # BANDS = {nn: Band(nn, SPLC/(ll*1e-7), ll*1e-7, cc) # for nn, ll, cc in zip(_band_name, _band_wlen, _band_color)} def _get_units_type(type): try: units = UNITS[type] except Exception: raise ValueError("Unrecognized `type` = '{}'".format(type)) return units, type def ABmag_to_flux(mag): """Convert from AB Magnitude to spectral-flux density. See: http://web.ipac.caltech.edu/staff/fmasci/home/astro_refs/magsystems.pdf Returns ------- fnu : () scalar Spectral-flux density in units of [erg/s/cm^2/Hz] """ fnu = np.power(10.0, (mag + 48.6)/-2.5) return fnu def mag_to_flux_zero(mag, zero_jansky=None): if zero_jansky is None: raise zero_point = zero_jansky * JY flux = np.power(10.0, mag / -2.5) * zero_point return flux def mag_to_flux(band, mag, type='f'): """Convert from broad-band filter magnitude (e.g. Johnson) to flux. Returns ------- flux : () scalar Flux in either [erg/s/cm^2/Hz] or [erg/s/cm^2/Angstrom] depending on `type`. """ mag = np.asarray(mag) units, type = _get_units_type(type) if band not in BAND_REF_FLUX.keys(): raise ValueError("Unrecognized `band` = '{}'".format(band)) ref_flux = BAND_REF_FLUX[band][type] * units # zero_point = BAND_ZERO_POINT[band][type] flux = ref_flux * np.power(10.0, mag/-2.5) return flux def flux_to_mag(band, flux, type='f'): """Convert from broad-band filter magnitude (e.g. Johnson) to flux. Arguments --------- band flux : () scalar Flux in either [erg/s/cm^2/Hz] or [erg/s/cm^2/Angstrom] depending on `type`. type Returns ------- mag """ flux = np.asarray(flux) units, type = _get_units_type(type) if band not in BAND_REF_FLUX.keys(): raise ValueError("Unrecognized `band` = '{}'".format(band)) ref_flux = BAND_REF_FLUX[band][type] * units # zero_point = BAND_ZERO_POINT[band][type] # flux = ref_flux * np.power(10.0, mag/-2.5) mag = -2.5 * np.log10(flux/ref_flux) return mag def abs_mag_to_lum(band, mag, type='f'): mag = np.asarray(mag) if type.lower().startswith('f'): type = 'f' units = 1.0e-20 # erg/s/Hz/cm^2 elif (type.lower().startswith('l') or type.lower().startswith('w')): type = 'l' units = 1.0e-11 # erg/s/Angstrom/cm^2 else: raise ValueError("Unrecognized `type` = '{}'".format(type)) if band not in BAND_REF_FLUX.keys(): raise ValueError("Unrecognized `band` = '{}'".format(band)) ref_flux = BAND_REF_FLUX[band][type] lum = 4.0 * np.pi * ref_flux * units * PC**2 * np.power(10.0, 2-mag/2.5) return lum def lum_to_abs_mag(band, lum, type='f'): lum = np.asarray(lum) if type.lower().startswith('f'): type = 'f' units = 1.0e-20 # erg/s/Hz/cm^2 elif (type.lower().startswith('l') or type.lower().startswith('w')): type = 'l' units = 1.0e-11 # erg/s/Angstrom/cm^2 else: raise ValueError("Unrecognized `type` = '{}'".format(type)) if band not in BAND_REF_FLUX.keys(): raise ValueError("Unrecognized `band` = '{}'".format(band)) ref_lum = BAND_REF_FLUX[band][type] * 4.0 * np.pi * units * (10*PC)**2 mag = lum/ref_lum mag = -2.5 * np.log10(mag) + 5 return mag def fnu_to_flambda(fnu, freq=None, wavelength=None): if freq is None: freq = SPLC / wavelength flambda = fnu * freq**2 / SPLC return flambda def flambda_to_fnu(flambda, freq=None, wavelength=None): if freq is None: freq = SPLC / wavelength fnu = flambda * SPLC / freq**2 return fnu
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # MIT License. See license.txt from __future__ import unicode_literals import webnotes from webnotes import msgprint import os from webnotes.utils import now, cint from webnotes.model import no_value_fields class DocType: def __init__(self, doc=None, doclist=[]): self.doc = doc self.doclist = doclist def change_modified_of_parent(self): if webnotes.in_import: return parent_list = webnotes.conn.sql("""SELECT parent from tabDocField where fieldtype="Table" and options="%s" """ % self.doc.name) for p in parent_list: webnotes.conn.sql('''UPDATE tabDocType SET modified="%s" WHERE `name`="%s"''' % (now(), p[0])) def scrub_field_names(self): restricted = ('name','parent','idx','owner','creation','modified','modified_by', 'parentfield','parenttype',"file_list") for d in self.doclist: if d.parent and d.fieldtype: if (not d.fieldname): if d.label: d.fieldname = d.label.strip().lower().replace(' ','_') if d.fieldname in restricted: d.fieldname = d.fieldname + '1' else: d.fieldname = d.fieldtype.lower().replace(" ","_") + "_" + str(d.idx) def set_version(self): self.doc.version = cint(self.doc.version) + 1 def validate_series(self, autoname=None, name=None): sql = webnotes.conn.sql if not autoname: autoname = self.doc.autoname if not name: name = self.doc.name if not autoname and self.doclist.get({"fieldname":"naming_series"}): self.doc.autoname = "naming_series:" if autoname and (not autoname.startswith('field:')) and (not autoname.startswith('eval:')) \ and (not autoname=='Prompt') and (not autoname.startswith('naming_series:')): prefix = autoname.split('.')[0] used_in = sql('select name from tabDocType where substring_index(autoname, ".", 1) = %s and name!=%s', (prefix, name)) if used_in: msgprint('<b>Series already in use:</b> The series "%s" is already used in "%s"' % (prefix, used_in[0][0]), raise_exception=1) def validate(self): for c in [".", "/", "#", "&", "=", ":", "'", '"']: if c in self.doc.name: webnotes.msgprint(c + " not allowed in name", raise_exception=1) self.validate_series() self.scrub_field_names() validate_fields(self.doclist.get({"doctype":"DocField"})) validate_permissions(self.doclist.get({"doctype":"DocPerm"})) self.set_version() self.make_amendable() self.check_link_replacement_error() def on_update(self): from webnotes.model.db_schema import updatedb updatedb(self.doc.name) self.change_modified_of_parent() import conf if (not webnotes.in_import) and getattr(conf, 'developer_mode', 0): self.export_doc() self.make_controller_template() # update index if not self.doc.custom: from webnotes.modules import scrub doctype = scrub(self.doc.name) module = __import__(scrub(self.doc.module) + ".doctype." + doctype + "." + doctype, fromlist=[""]) if hasattr(module, "on_doctype_update"): module.on_doctype_update() webnotes.clear_cache(doctype=self.doc.name) def check_link_replacement_error(self): for d in self.doclist.get({"doctype":"DocField", "fieldtype":"Select"}): if (webnotes.conn.get_value("DocField", d.name, "options") or "").startswith("link:") \ and not d.options.startswith("link:"): webnotes.msgprint("link: type Select fields are getting replaced. Please check for %s" % d.label, raise_exception=True) def on_trash(self): webnotes.conn.sql("delete from `tabCustom Field` where dt = %s", self.doc.name) webnotes.conn.sql("delete from `tabCustom Script` where dt = %s", self.doc.name) webnotes.conn.sql("delete from `tabProperty Setter` where doc_type = %s", self.doc.name) webnotes.conn.sql("delete from `tabReport` where ref_doctype=%s", self.doc.name) def on_rename(self, new, old, merge=False): if self.doc.issingle: webnotes.conn.sql("""\ update tabSingles set doctype=%s where doctype=%s""", (new, old)) else: webnotes.conn.sql("rename table `tab%s` to `tab%s`" % (old, new)) def export_doc(self): from webnotes.modules.export_file import export_to_files export_to_files(record_list=[['DocType', self.doc.name]]) def import_doc(self): from webnotes.modules.import_module import import_from_files import_from_files(record_list=[[self.doc.module, 'doctype', self.doc.name]]) def make_controller_template(self): from webnotes.modules import get_doc_path, get_module_path, scrub pypath = os.path.join(get_doc_path(self.doc.module, self.doc.doctype, self.doc.name), scrub(self.doc.name) + '.py') if not os.path.exists(pypath): with open(pypath, 'w') as pyfile: with open(os.path.join(get_module_path("core"), "doctype", "doctype", "doctype_template.py"), 'r') as srcfile: pyfile.write(srcfile.read()) def make_amendable(self): """ if is_submittable is set, add amended_from docfields """ if self.doc.is_submittable: if not webnotes.conn.sql("""select name from tabDocField where fieldname = 'amended_from' and parent = %s""", self.doc.name): new = self.doc.addchild('fields', 'DocField', self.doclist) new.label = 'Amended From' new.fieldtype = 'Link' new.fieldname = 'amended_from' new.options = self.doc.name new.permlevel = 0 new.read_only = 1 new.print_hide = 1 new.no_copy = 1 new.idx = self.get_max_idx() + 1 def get_max_idx(self): max_idx = webnotes.conn.sql("""select max(idx) from `tabDocField` where parent = %s""", self.doc.name) return max_idx and max_idx[0][0] or 0 def validate_fields_for_doctype(doctype): from webnotes.model.doctype import get validate_fields(get(doctype, cached=False).get({"parent":doctype, "doctype":"DocField"})) def validate_fields(fields): def check_illegal_characters(fieldname): for c in ['.', ',', ' ', '-', '&', '%', '=', '"', "'", '*', '$', '(', ')', '[', ']', '/']: if c in fieldname: webnotes.msgprint("'%s' not allowed in fieldname (%s)" % (c, fieldname)) def check_unique_fieldname(fieldname): duplicates = filter(None, map(lambda df: df.fieldname==fieldname and str(df.idx) or None, fields)) if len(duplicates) > 1: webnotes.msgprint('Fieldname <b>%s</b> appears more than once in rows (%s). Please rectify' \ % (fieldname, ', '.join(duplicates)), raise_exception=1) def check_illegal_mandatory(d): if d.fieldtype in ('HTML', 'Button', 'Section Break', 'Column Break') and d.reqd: webnotes.msgprint('%(label)s [%(fieldtype)s] cannot be mandatory' % d.fields, raise_exception=1) def check_link_table_options(d): if d.fieldtype in ("Link", "Table"): if not d.options: webnotes.msgprint("""#%(idx)s %(label)s: Options must be specified for Link and Table type fields""" % d.fields, raise_exception=1) if d.options=="[Select]": return if not webnotes.conn.exists("DocType", d.options): webnotes.msgprint("""#%(idx)s %(label)s: Options %(options)s must be a valid "DocType" for Link and Table type fields""" % d.fields, raise_exception=1) def check_hidden_and_mandatory(d): if d.hidden and d.reqd: webnotes.msgprint("""#%(idx)s %(label)s: Cannot be hidden and mandatory (reqd)""" % d.fields, raise_exception=True) def check_max_items_in_list(fields): count = 0 for d in fields: if d.in_list_view: count+=1 if count > 5: webnotes.msgprint("""Max 5 Fields can be set as 'In List View', please unselect a field before selecting a new one.""") def check_width(d): if d.fieldtype == "Currency" and cint(d.width) < 100: webnotes.msgprint("Minimum width for FieldType 'Currency' is 100px", raise_exception=1) def check_in_list_view(d): if d.in_list_view and d.fieldtype!="Image" and (d.fieldtype in no_value_fields): webnotes.msgprint("'In List View' not allowed for field of type '%s'" % d.fieldtype, raise_exception=1) for d in fields: if not d.permlevel: d.permlevel = 0 if not d.fieldname: webnotes.msgprint("Fieldname is mandatory in row %s" % d.idx, raise_exception=1) check_illegal_characters(d.fieldname) check_unique_fieldname(d.fieldname) check_illegal_mandatory(d) check_link_table_options(d) check_hidden_and_mandatory(d) check_in_list_view(d) def validate_permissions_for_doctype(doctype, for_remove=False): from webnotes.model.doctype import get validate_permissions(get(doctype, cached=False).get({"parent":doctype, "doctype":"DocPerm"}), for_remove) def validate_permissions(permissions, for_remove=False): doctype = permissions and permissions[0].parent issingle = issubmittable = False if doctype: issingle = cint(webnotes.conn.get_value("DocType", doctype, "issingle")) issubmittable = cint(webnotes.conn.get_value("DocType", doctype, "is_submittable")) def get_txt(d): return "For %s (level %s) in %s row %s:" % (d.role, d.permlevel, d.parent, d.idx) def check_atleast_one_set(d): if not d.read and not d.write and not d.submit and not d.cancel and not d.create: webnotes.msgprint(get_txt(d) + " Atleast one of Read, Write, Create, Submit, Cancel must be set.", raise_exception=True) def check_double(d): similar = permissions.get({ "role":d.role, "permlevel":d.permlevel, "match": d.match }) if len(similar) > 1: webnotes.msgprint(get_txt(d) + " Only one rule allowed for a particular Role and Level.", raise_exception=True) def check_level_zero_is_set(d): if cint(d.permlevel) > 0 and d.role != 'All': if not permissions.get({"role": d.role, "permlevel": 0}): webnotes.msgprint(get_txt(d) + " Higher level permissions are meaningless if level 0 permission is not set.", raise_exception=True) if d.create or d.submit or d.cancel or d.amend or d.match: webnotes.msgprint("Create, Submit, Cancel, Amend, Match has no meaning at level " + d.permlevel, raise_exception=True) def check_permission_dependency(d): if d.write and not d.read: webnotes.msgprint(get_txt(d) + " Cannot set Write permission if Read is not set.", raise_exception=True) if (d.submit or d.cancel or d.amend) and not d.write: webnotes.msgprint(get_txt(d) + " Cannot set Submit, Cancel, Amend permission if Write is not set.", raise_exception=True) if d.amend and not d.write: webnotes.msgprint(get_txt(d) + " Cannot set Amend if Cancel is not set.", raise_exception=True) def remove_report_if_single(d): if d.report and issingle: webnotes.msgprint(doctype + " is a single DocType, permission of type Report is meaningless.") def check_if_submittable(d): if d.submit and not issubmittable: webnotes.msgprint(doctype + " is not Submittable, cannot assign submit rights.", raise_exception=True) elif d.amend and not issubmittable: webnotes.msgprint(doctype + " is not Submittable, cannot assign amend rights.", raise_exception=True) for d in permissions: if not d.permlevel: d.permlevel=0 check_atleast_one_set(d) if not for_remove: check_double(d) check_permission_dependency(d) check_if_submittable(d) check_level_zero_is_set(d) remove_report_if_single(d)
# Licensed under a 3-clause BSD style license - see PYFITS.rst import gzip import bz2 import io import mmap import os import pathlib import warnings import zipfile import pytest import numpy as np from . import FitsTestCase from ..convenience import _getext from ..diff import FITSDiff from ..file import _File, GZIP_MAGIC from ....io import fits from ....tests.helper import raises, catch_warnings, ignore_warnings from ....utils.data import conf, get_pkg_data_filename from ....utils import data class TestCore(FitsTestCase): def test_with_statement(self): with fits.open(self.data('ascii.fits')) as f: pass @raises(OSError) def test_missing_file(self): fits.open(self.temp('does-not-exist.fits')) def test_filename_is_bytes_object(self): with pytest.raises(TypeError): fits.open(self.data('ascii.fits').encode()) def test_naxisj_check(self): hdulist = fits.open(self.data('o4sp040b0_raw.fits')) hdulist[1].header['NAXIS3'] = 500 assert 'NAXIS3' in hdulist[1].header hdulist.verify('silentfix') assert 'NAXIS3' not in hdulist[1].header def test_byteswap(self): p = fits.PrimaryHDU() l = fits.HDUList() n = np.zeros(3, dtype='i2') n[0] = 1 n[1] = 60000 n[2] = 2 c = fits.Column(name='foo', format='i2', bscale=1, bzero=32768, array=n) t = fits.BinTableHDU.from_columns([c]) l.append(p) l.append(t) l.writeto(self.temp('test.fits'), overwrite=True) with fits.open(self.temp('test.fits')) as p: assert p[1].data[1]['foo'] == 60000.0 def test_fits_file_path_object(self): """ Testing when fits file is passed as pathlib.Path object #4412. """ fpath = pathlib.Path(get_pkg_data_filename('data/tdim.fits')) hdulist = fits.open(fpath) assert hdulist[0].filebytes() == 2880 assert hdulist[1].filebytes() == 5760 hdulist2 = fits.open(self.data('tdim.fits')) assert FITSDiff(hdulist2, hdulist).identical is True def test_add_del_columns(self): p = fits.ColDefs([]) p.add_col(fits.Column(name='FOO', format='3J')) p.add_col(fits.Column(name='BAR', format='1I')) assert p.names == ['FOO', 'BAR'] p.del_col('FOO') assert p.names == ['BAR'] def test_add_del_columns2(self): hdulist = fits.open(self.data('tb.fits')) table = hdulist[1] assert table.data.dtype.names == ('c1', 'c2', 'c3', 'c4') assert table.columns.names == ['c1', 'c2', 'c3', 'c4'] table.columns.del_col(str('c1')) assert table.data.dtype.names == ('c2', 'c3', 'c4') assert table.columns.names == ['c2', 'c3', 'c4'] table.columns.del_col(str('c3')) assert table.data.dtype.names == ('c2', 'c4') assert table.columns.names == ['c2', 'c4'] table.columns.add_col(fits.Column(str('foo'), str('3J'))) assert table.data.dtype.names == ('c2', 'c4', 'foo') assert table.columns.names == ['c2', 'c4', 'foo'] hdulist.writeto(self.temp('test.fits'), overwrite=True) with ignore_warnings(): # TODO: The warning raised by this test is actually indication of a # bug and should *not* be ignored. But as it is a known issue we # hide it for now. See # https://github.com/spacetelescope/PyFITS/issues/44 with fits.open(self.temp('test.fits')) as hdulist: table = hdulist[1] assert table.data.dtype.names == ('c2', 'c4', 'foo') assert table.columns.names == ['c2', 'c4', 'foo'] def test_update_header_card(self): """A very basic test for the Header.update method--I'd like to add a few more cases to this at some point. """ header = fits.Header() comment = 'number of bits per data pixel' header['BITPIX'] = (16, comment) assert 'BITPIX' in header assert header['BITPIX'] == 16 assert header.comments['BITPIX'] == comment header.update(BITPIX=32) assert header['BITPIX'] == 32 assert header.comments['BITPIX'] == '' def test_set_card_value(self): """Similar to test_update_header_card(), but tests the the `header['FOO'] = 'bar'` method of updating card values. """ header = fits.Header() comment = 'number of bits per data pixel' card = fits.Card.fromstring('BITPIX = 32 / {}'.format(comment)) header.append(card) header['BITPIX'] = 32 assert 'BITPIX' in header assert header['BITPIX'] == 32 assert header.cards[0].keyword == 'BITPIX' assert header.cards[0].value == 32 assert header.cards[0].comment == comment def test_uint(self): hdulist_f = fits.open(self.data('o4sp040b0_raw.fits'), uint=False) hdulist_i = fits.open(self.data('o4sp040b0_raw.fits'), uint=True) assert hdulist_f[1].data.dtype == np.float32 assert hdulist_i[1].data.dtype == np.uint16 assert np.all(hdulist_f[1].data == hdulist_i[1].data) def test_fix_missing_card_append(self): hdu = fits.ImageHDU() errs = hdu.req_cards('TESTKW', None, None, 'foo', 'silentfix', []) assert len(errs) == 1 assert 'TESTKW' in hdu.header assert hdu.header['TESTKW'] == 'foo' assert hdu.header.cards[-1].keyword == 'TESTKW' def test_fix_invalid_keyword_value(self): hdu = fits.ImageHDU() hdu.header['TESTKW'] = 'foo' errs = hdu.req_cards('TESTKW', None, lambda v: v == 'foo', 'foo', 'ignore', []) assert len(errs) == 0 # Now try a test that will fail, and ensure that an error will be # raised in 'exception' mode errs = hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar', 'exception', []) assert len(errs) == 1 assert errs[0][1] == "'TESTKW' card has invalid value 'foo'." # See if fixing will work hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar', 'silentfix', []) assert hdu.header['TESTKW'] == 'bar' @raises(fits.VerifyError) def test_unfixable_missing_card(self): class TestHDU(fits.hdu.base.NonstandardExtHDU): def _verify(self, option='warn'): errs = super()._verify(option) hdu.req_cards('TESTKW', None, None, None, 'fix', errs) return errs @classmethod def match_header(cls, header): # Since creating this HDU class adds it to the registry we # don't want the file reader to possibly think any actual # HDU from a file should be handled by this class return False hdu = TestHDU(header=fits.Header()) hdu.verify('fix') @raises(fits.VerifyError) def test_exception_on_verification_error(self): hdu = fits.ImageHDU() del hdu.header['XTENSION'] hdu.verify('exception') def test_ignore_verification_error(self): hdu = fits.ImageHDU() # The default here would be to issue a warning; ensure that no warnings # or exceptions are raised with catch_warnings(): warnings.simplefilter('error') del hdu.header['NAXIS'] try: hdu.verify('ignore') except Exception as exc: self.fail('An exception occurred when the verification error ' 'should have been ignored: {}'.format(exc)) # Make sure the error wasn't fixed either, silently or otherwise assert 'NAXIS' not in hdu.header @raises(ValueError) def test_unrecognized_verify_option(self): hdu = fits.ImageHDU() hdu.verify('foobarbaz') def test_errlist_basic(self): # Just some tests to make sure that _ErrList is setup correctly. # No arguments error_list = fits.verify._ErrList() assert error_list == [] # Some contents - this is not actually working, it just makes sure they # are kept. error_list = fits.verify._ErrList([1, 2, 3]) assert error_list == [1, 2, 3] def test_combined_verify_options(self): """ Test verify options like fix+ignore. """ def make_invalid_hdu(): hdu = fits.ImageHDU() # Add one keyword to the header that contains a fixable defect, and one # with an unfixable defect c1 = fits.Card.fromstring("test = ' test'") c2 = fits.Card.fromstring("P.I. = ' Hubble'") hdu.header.append(c1) hdu.header.append(c2) return hdu # silentfix+ignore should be completely silent hdu = make_invalid_hdu() with catch_warnings(): warnings.simplefilter('error') try: hdu.verify('silentfix+ignore') except Exception as exc: self.fail('An exception occurred when the verification error ' 'should have been ignored: {}'.format(exc)) # silentfix+warn should be quiet about the fixed HDU and only warn # about the unfixable one hdu = make_invalid_hdu() with catch_warnings() as w: hdu.verify('silentfix+warn') assert len(w) == 4 assert 'Illegal keyword name' in str(w[2].message) # silentfix+exception should only mention the unfixable error in the # exception hdu = make_invalid_hdu() try: hdu.verify('silentfix+exception') except fits.VerifyError as exc: assert 'Illegal keyword name' in str(exc) assert 'not upper case' not in str(exc) else: self.fail('An exception should have been raised.') # fix+ignore is not too useful, but it should warn about the fixed # problems while saying nothing about the unfixable problems hdu = make_invalid_hdu() with catch_warnings() as w: hdu.verify('fix+ignore') assert len(w) == 4 assert 'not upper case' in str(w[2].message) # fix+warn hdu = make_invalid_hdu() with catch_warnings() as w: hdu.verify('fix+warn') assert len(w) == 6 assert 'not upper case' in str(w[2].message) assert 'Illegal keyword name' in str(w[4].message) # fix+exception hdu = make_invalid_hdu() try: hdu.verify('fix+exception') except fits.VerifyError as exc: assert 'Illegal keyword name' in str(exc) assert 'not upper case' in str(exc) else: self.fail('An exception should have been raised.') def test_getext(self): """ Test the various different ways of specifying an extension header in the convenience functions. """ hl, ext = _getext(self.data('test0.fits'), 'readonly', 1) assert ext == 1 pytest.raises(ValueError, _getext, self.data('test0.fits'), 'readonly', 1, 2) pytest.raises(ValueError, _getext, self.data('test0.fits'), 'readonly', (1, 2)) pytest.raises(ValueError, _getext, self.data('test0.fits'), 'readonly', 'sci', 'sci') pytest.raises(TypeError, _getext, self.data('test0.fits'), 'readonly', 1, 2, 3) hl, ext = _getext(self.data('test0.fits'), 'readonly', ext=1) assert ext == 1 hl, ext = _getext(self.data('test0.fits'), 'readonly', ext=('sci', 2)) assert ext == ('sci', 2) pytest.raises(TypeError, _getext, self.data('test0.fits'), 'readonly', 1, ext=('sci', 2), extver=3) pytest.raises(TypeError, _getext, self.data('test0.fits'), 'readonly', ext=('sci', 2), extver=3) hl, ext = _getext(self.data('test0.fits'), 'readonly', 'sci') assert ext == ('sci', 1) hl, ext = _getext(self.data('test0.fits'), 'readonly', 'sci', 1) assert ext == ('sci', 1) hl, ext = _getext(self.data('test0.fits'), 'readonly', ('sci', 1)) assert ext == ('sci', 1) hl, ext = _getext(self.data('test0.fits'), 'readonly', 'sci', extver=1, do_not_scale_image_data=True) assert ext == ('sci', 1) pytest.raises(TypeError, _getext, self.data('test0.fits'), 'readonly', 'sci', ext=1) pytest.raises(TypeError, _getext, self.data('test0.fits'), 'readonly', 'sci', 1, extver=2) hl, ext = _getext(self.data('test0.fits'), 'readonly', extname='sci') assert ext == ('sci', 1) hl, ext = _getext(self.data('test0.fits'), 'readonly', extname='sci', extver=1) assert ext == ('sci', 1) pytest.raises(TypeError, _getext, self.data('test0.fits'), 'readonly', extver=1) def test_extension_name_case_sensitive(self): """ Tests that setting fits.conf.extension_name_case_sensitive at runtime works. """ hdu = fits.ImageHDU() hdu.name = 'sCi' assert hdu.name == 'SCI' assert hdu.header['EXTNAME'] == 'SCI' with fits.conf.set_temp('extension_name_case_sensitive', True): hdu = fits.ImageHDU() hdu.name = 'sCi' assert hdu.name == 'sCi' assert hdu.header['EXTNAME'] == 'sCi' hdu.name = 'sCi' assert hdu.name == 'SCI' assert hdu.header['EXTNAME'] == 'SCI' def test_hdu_fromstring(self): """ Tests creating a fully-formed HDU object from a string containing the bytes of the HDU. """ dat = open(self.data('test0.fits'), 'rb').read() offset = 0 with fits.open(self.data('test0.fits')) as hdul: hdulen = hdul[0]._data_offset + hdul[0]._data_size hdu = fits.PrimaryHDU.fromstring(dat[:hdulen]) assert isinstance(hdu, fits.PrimaryHDU) assert hdul[0].header == hdu.header assert hdu.data is None hdu.header['TEST'] = 'TEST' hdu.writeto(self.temp('test.fits')) with fits.open(self.temp('test.fits')) as hdul: assert isinstance(hdu, fits.PrimaryHDU) assert hdul[0].header[:-1] == hdu.header[:-1] assert hdul[0].header['TEST'] == 'TEST' assert hdu.data is None with fits.open(self.data('test0.fits'))as hdul: for ext_hdu in hdul[1:]: offset += hdulen hdulen = len(str(ext_hdu.header)) + ext_hdu._data_size hdu = fits.ImageHDU.fromstring(dat[offset:offset + hdulen]) assert isinstance(hdu, fits.ImageHDU) assert ext_hdu.header == hdu.header assert (ext_hdu.data == hdu.data).all() def test_nonstandard_hdu(self): """ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/157 Tests that "Nonstandard" HDUs with SIMPLE = F are read and written without prepending a superfluous and unwanted standard primary HDU. """ data = np.arange(100, dtype=np.uint8) hdu = fits.PrimaryHDU(data=data) hdu.header['SIMPLE'] = False hdu.writeto(self.temp('test.fits')) info = [(0, '', 1, 'NonstandardHDU', 5, (), '', '')] with fits.open(self.temp('test.fits')) as hdul: assert hdul.info(output=False) == info # NonstandardHDUs just treat the data as an unspecified array of # bytes. The first 100 bytes should match the original data we # passed in...the rest should be zeros padding out the rest of the # FITS block assert (hdul[0].data[:100] == data).all() assert (hdul[0].data[100:] == 0).all() def test_extname(self): """Test getting/setting the EXTNAME of an HDU.""" h1 = fits.PrimaryHDU() assert h1.name == 'PRIMARY' # Normally a PRIMARY HDU should not have an EXTNAME, though it should # have a default .name attribute assert 'EXTNAME' not in h1.header # The current version of the FITS standard does allow PRIMARY HDUs to # have an EXTNAME, however. h1.name = 'NOTREAL' assert h1.name == 'NOTREAL' assert h1.header.get('EXTNAME') == 'NOTREAL' # Updating the EXTNAME in the header should update the .name h1.header['EXTNAME'] = 'TOOREAL' assert h1.name == 'TOOREAL' # If we delete an EXTNAME keyword from a PRIMARY HDU it should go back # to the default del h1.header['EXTNAME'] assert h1.name == 'PRIMARY' # For extension HDUs the situation is a bit simpler: h2 = fits.ImageHDU() assert h2.name == '' assert 'EXTNAME' not in h2.header h2.name = 'HELLO' assert h2.name == 'HELLO' assert h2.header.get('EXTNAME') == 'HELLO' h2.header['EXTNAME'] = 'GOODBYE' assert h2.name == 'GOODBYE' def test_extver_extlevel(self): """Test getting/setting the EXTVER and EXTLEVEL of and HDU.""" # EXTVER and EXTNAME work exactly the same; their semantics are, for # now, to be inferred by the user. Although they should never be less # than 1, the standard does not explicitly forbid any value so long as # it's an integer h1 = fits.PrimaryHDU() assert h1.ver == 1 assert h1.level == 1 assert 'EXTVER' not in h1.header assert 'EXTLEVEL' not in h1.header h1.ver = 2 assert h1.header.get('EXTVER') == 2 h1.header['EXTVER'] = 3 assert h1.ver == 3 del h1.header['EXTVER'] h1.ver == 1 h1.level = 2 assert h1.header.get('EXTLEVEL') == 2 h1.header['EXTLEVEL'] = 3 assert h1.level == 3 del h1.header['EXTLEVEL'] assert h1.level == 1 pytest.raises(TypeError, setattr, h1, 'ver', 'FOO') pytest.raises(TypeError, setattr, h1, 'level', 'BAR') def test_consecutive_writeto(self): """ Regression test for an issue where calling writeto twice on the same HDUList could write a corrupted file. https://github.com/spacetelescope/PyFITS/issues/40 is actually a particular instance of this problem, though isn't unique to sys.stdout. """ with fits.open(self.data('test0.fits')) as hdul1: # Add a bunch of header keywords so that the data will be forced to # new offsets within the file: for idx in range(40): hdul1[1].header['TEST{}'.format(idx)] = 'test' hdul1.writeto(self.temp('test1.fits')) hdul1.writeto(self.temp('test2.fits')) # Open a second handle to the original file and compare it to hdul1 # (We only compare part of the one header that was modified) # Compare also with the second writeto output with fits.open(self.data('test0.fits')) as hdul2: with fits.open(self.temp('test2.fits')) as hdul3: for hdul in (hdul1, hdul3): for idx, hdus in enumerate(zip(hdul2, hdul)): hdu2, hdu = hdus if idx != 1: assert hdu.header == hdu2.header else: assert (hdu2.header == hdu.header[:len(hdu2.header)]) assert np.all(hdu.data == hdu2.data) class TestConvenienceFunctions(FitsTestCase): def test_writeto(self): """ Simple test for writing a trivial header and some data to a file with the `writeto()` convenience function. """ data = np.zeros((100, 100)) header = fits.Header() fits.writeto(self.temp('array.fits'), data, header=header, overwrite=True) hdul = fits.open(self.temp('array.fits')) assert len(hdul) == 1 assert (data == hdul[0].data).all() def test_writeto_2(self): """ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/107 Test of `writeto()` with a trivial header containing a single keyword. """ data = np.zeros((100, 100)) header = fits.Header() header.set('CRPIX1', 1.) fits.writeto(self.temp('array.fits'), data, header=header, overwrite=True, output_verify='silentfix') hdul = fits.open(self.temp('array.fits')) assert len(hdul) == 1 assert (data == hdul[0].data).all() assert 'CRPIX1' in hdul[0].header assert hdul[0].header['CRPIX1'] == 1.0 class TestFileFunctions(FitsTestCase): """ Tests various basic I/O operations, specifically in the astropy.io.fits.file._File class. """ def test_open_nonexistent(self): """Test that trying to open a non-existent file results in an OSError (and not some other arbitrary exception). """ try: fits.open(self.temp('foobar.fits')) except OSError as e: assert 'No such file or directory' in str(e) # But opening in ostream or append mode should be okay, since they # allow writing new files for mode in ('ostream', 'append'): with fits.open(self.temp('foobar.fits'), mode=mode) as h: pass assert os.path.exists(self.temp('foobar.fits')) os.remove(self.temp('foobar.fits')) def test_open_file_handle(self): # Make sure we can open a FITS file from an open file handle with open(self.data('test0.fits'), 'rb') as handle: with fits.open(handle) as fitsfile: pass with open(self.temp('temp.fits'), 'wb') as handle: with fits.open(handle, mode='ostream') as fitsfile: pass # Opening without explicitly specifying binary mode should fail with pytest.raises(ValueError): with open(self.data('test0.fits')) as handle: with fits.open(handle) as fitsfile: pass # All of these read modes should fail for mode in ['r', 'rt', 'r+', 'rt+', 'a', 'at', 'a+', 'at+']: with pytest.raises(ValueError): with open(self.data('test0.fits'), mode=mode) as handle: with fits.open(handle) as fitsfile: pass # These write modes should fail as well for mode in ['w', 'wt', 'w+', 'wt+']: with pytest.raises(ValueError): with open(self.temp('temp.fits'), mode=mode) as handle: with fits.open(handle) as fitsfile: pass def test_fits_file_handle_mode_combo(self): # This should work fine since no mode is given with open(self.data('test0.fits'), 'rb') as handle: with fits.open(handle) as fitsfile: pass # This should work fine since the modes are compatible with open(self.data('test0.fits'), 'rb') as handle: with fits.open(handle, mode='readonly') as fitsfile: pass # This should not work since the modes conflict with pytest.raises(ValueError): with open(self.data('test0.fits'), 'rb') as handle: with fits.open(handle, mode='ostream') as fitsfile: pass def test_open_from_url(self): import urllib.request file_url = "file:///" + self.data('test0.fits') with urllib.request.urlopen(file_url) as urlobj: with fits.open(urlobj) as fits_handle: pass # It will not be possible to write to a file that is from a URL object for mode in ('ostream', 'append', 'update'): with pytest.raises(ValueError): with urllib.request.urlopen(file_url) as urlobj: with fits.open(urlobj, mode=mode) as fits_handle: pass @pytest.mark.remote_data(source='astropy') def test_open_from_remote_url(self): import urllib.request for dataurl in (conf.dataurl, conf.dataurl_mirror): remote_url = '{}/{}'.format(dataurl, 'allsky/allsky_rosat.fits') try: with urllib.request.urlopen(remote_url) as urlobj: with fits.open(urlobj) as fits_handle: assert len(fits_handle) == 1 for mode in ('ostream', 'append', 'update'): with pytest.raises(ValueError): with urllib.request.urlopen(remote_url) as urlobj: with fits.open(urlobj, mode=mode) as fits_handle: assert len(fits_handle) == 1 except (urllib.error.HTTPError, urllib.error.URLError): continue else: break else: raise Exception("Could not download file") def test_open_gzipped(self): gzip_file = self._make_gzip_file() with ignore_warnings(): with fits.open(gzip_file) as fits_handle: assert fits_handle._file.compression == 'gzip' assert len(fits_handle) == 5 with fits.open(gzip.GzipFile(gzip_file)) as fits_handle: assert fits_handle._file.compression == 'gzip' assert len(fits_handle) == 5 def test_open_gzipped_from_handle(self): with open(self._make_gzip_file(), 'rb') as handle: with fits.open(handle) as fits_handle: assert fits_handle._file.compression == 'gzip' def test_detect_gzipped(self): """Test detection of a gzip file when the extension is not .gz.""" with ignore_warnings(): with fits.open(self._make_gzip_file('test0.fz')) as fits_handle: assert fits_handle._file.compression == 'gzip' assert len(fits_handle) == 5 def test_writeto_append_mode_gzip(self): """Regression test for https://github.com/spacetelescope/PyFITS/issues/33 Check that a new GzipFile opened in append mode can be used to write out a new FITS file. """ # Note: when opening a GzipFile the 'b+' is superfluous, but this was # still how the original test case looked # Note: with statement not supported on GzipFile in older Python # versions fileobj = gzip.GzipFile(self.temp('test.fits.gz'), 'ab+') h = fits.PrimaryHDU() try: h.writeto(fileobj) finally: fileobj.close() with fits.open(self.temp('test.fits.gz')) as hdul: assert hdul[0].header == h.header def test_open_bzipped(self): bzip_file = self._make_bzip2_file() with ignore_warnings(): with fits.open(bzip_file) as fits_handle: assert fits_handle._file.compression == 'bzip2' assert len(fits_handle) == 5 with fits.open(bz2.BZ2File(bzip_file)) as fits_handle: assert fits_handle._file.compression == 'bzip2' assert len(fits_handle) == 5 def test_open_bzipped_from_handle(self): with open(self._make_bzip2_file(), 'rb') as handle: with fits.open(handle) as fits_handle: assert fits_handle._file.compression == 'bzip2' assert len(fits_handle) == 5 def test_detect_bzipped(self): """Test detection of a bzip2 file when the extension is not .bz2.""" with ignore_warnings(): with fits.open(self._make_bzip2_file('test0.xx')) as fits_handle: assert fits_handle._file.compression == 'bzip2' assert len(fits_handle) == 5 def test_writeto_bzip2_fileobj(self): """Test writing to a bz2.BZ2File file like object""" fileobj = bz2.BZ2File(self.temp('test.fits.bz2'), 'w') h = fits.PrimaryHDU() try: h.writeto(fileobj) finally: fileobj.close() with fits.open(self.temp('test.fits.bz2')) as hdul: assert hdul[0].header == h.header def test_writeto_bzip2_filename(self): """Test writing to a bzip2 file by name""" filename = self.temp('testname.fits.bz2') h = fits.PrimaryHDU() h.writeto(filename) with fits.open(self.temp('testname.fits.bz2')) as hdul: assert hdul[0].header == h.header def test_open_zipped(self): zip_file = self._make_zip_file() with ignore_warnings(): with fits.open(zip_file) as fits_handle: assert fits_handle._file.compression == 'zip' assert len(fits_handle) == 5 with fits.open(zipfile.ZipFile(zip_file)) as fits_handle: assert fits_handle._file.compression == 'zip' assert len(fits_handle) == 5 def test_open_zipped_from_handle(self): with open(self._make_zip_file(), 'rb') as handle: with fits.open(handle) as fits_handle: assert fits_handle._file.compression == 'zip' assert len(fits_handle) == 5 def test_detect_zipped(self): """Test detection of a zip file when the extension is not .zip.""" zf = self._make_zip_file(filename='test0.fz') with ignore_warnings(): assert len(fits.open(zf)) == 5 def test_open_zipped_writeable(self): """Opening zipped files in a writeable mode should fail.""" zf = self._make_zip_file() pytest.raises(OSError, fits.open, zf, 'update') pytest.raises(OSError, fits.open, zf, 'append') zf = zipfile.ZipFile(zf, 'a') pytest.raises(OSError, fits.open, zf, 'update') pytest.raises(OSError, fits.open, zf, 'append') def test_read_open_astropy_gzip_file(self): """ Regression test for https://github.com/astropy/astropy/issues/2774 This tests reading from a ``GzipFile`` object from Astropy's compatibility copy of the ``gzip`` module. """ gf = gzip.GzipFile(self._make_gzip_file()) try: assert len(fits.open(gf)) == 5 finally: gf.close() @raises(OSError) def test_open_multiple_member_zipfile(self): """ Opening zip files containing more than one member files should fail as there's no obvious way to specify which file is the FITS file to read. """ zfile = zipfile.ZipFile(self.temp('test0.zip'), 'w') zfile.write(self.data('test0.fits')) zfile.writestr('foo', 'bar') zfile.close() fits.open(zfile.filename) def test_read_open_file(self): """Read from an existing file object.""" with open(self.data('test0.fits'), 'rb') as f: assert len(fits.open(f)) == 5 def test_read_closed_file(self): """Read from an existing file object that's been closed.""" f = open(self.data('test0.fits'), 'rb') f.close() assert len(fits.open(f)) == 5 def test_read_open_gzip_file(self): """Read from an open gzip file object.""" gf = gzip.GzipFile(self._make_gzip_file()) try: assert len(fits.open(gf)) == 5 finally: gf.close() def test_open_gzip_file_for_writing(self): """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/195.""" gf = self._make_gzip_file() with fits.open(gf, mode='update') as h: h[0].header['EXPFLAG'] = 'ABNORMAL' h[1].data[0, 0] = 1 with fits.open(gf) as h: # Just to make sur ethe update worked; if updates work # normal writes should work too... assert h[0].header['EXPFLAG'] == 'ABNORMAL' assert h[1].data[0, 0] == 1 def test_write_read_gzip_file(self): """ Regression test for https://github.com/astropy/astropy/issues/2794 Ensure files written through gzip are readable. """ data = np.arange(100) hdu = fits.PrimaryHDU(data=data) hdu.writeto(self.temp('test.fits.gz')) with open(self.temp('test.fits.gz'), 'rb') as f: assert f.read(3) == GZIP_MAGIC with fits.open(self.temp('test.fits.gz')) as hdul: assert np.all(hdul[0].data == data) def test_read_file_like_object(self): """Test reading a FITS file from a file-like object.""" filelike = io.BytesIO() with open(self.data('test0.fits'), 'rb') as f: filelike.write(f.read()) filelike.seek(0) with ignore_warnings(): assert len(fits.open(filelike)) == 5 def test_updated_file_permissions(self): """ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/79 Tests that when a FITS file is modified in update mode, the file permissions are preserved. """ filename = self.temp('test.fits') hdul = [fits.PrimaryHDU(), fits.ImageHDU()] hdul = fits.HDUList(hdul) hdul.writeto(filename) old_mode = os.stat(filename).st_mode hdul = fits.open(filename, mode='update') hdul.insert(1, fits.ImageHDU()) hdul.flush() hdul.close() assert old_mode == os.stat(filename).st_mode def test_fileobj_mode_guessing(self): """Tests whether a file opened without a specified io.fits mode ('readonly', etc.) is opened in a mode appropriate for the given file object. """ self.copy_file('test0.fits') # Opening in text mode should outright fail for mode in ('r', 'w', 'a'): with open(self.temp('test0.fits'), mode) as f: pytest.raises(ValueError, fits.HDUList.fromfile, f) # Need to re-copy the file since opening it in 'w' mode blew it away self.copy_file('test0.fits') with open(self.temp('test0.fits'), 'rb') as f: with fits.HDUList.fromfile(f) as h: assert h.fileinfo(0)['filemode'] == 'readonly' for mode in ('wb', 'ab'): with open(self.temp('test0.fits'), mode) as f: with fits.HDUList.fromfile(f) as h: # Basically opening empty files for output streaming assert len(h) == 0 # Need to re-copy the file since opening it in 'w' mode blew it away self.copy_file('test0.fits') with open(self.temp('test0.fits'), 'wb+') as f: with fits.HDUList.fromfile(f) as h: # wb+ still causes an existing file to be overwritten so there # are no HDUs assert len(h) == 0 # Need to re-copy the file since opening it in 'w' mode blew it away self.copy_file('test0.fits') with open(self.temp('test0.fits'), 'rb+') as f: with fits.HDUList.fromfile(f) as h: assert h.fileinfo(0)['filemode'] == 'update' with open(self.temp('test0.fits'), 'ab+') as f: with fits.HDUList.fromfile(f) as h: assert h.fileinfo(0)['filemode'] == 'append' def test_mmap_unwriteable(self): """Regression test for https://github.com/astropy/astropy/issues/968 Temporarily patches mmap.mmap to exhibit platform-specific bad behavior. """ class MockMmap(mmap.mmap): def flush(self): raise OSError('flush is broken on this platform') old_mmap = mmap.mmap mmap.mmap = MockMmap # Force the mmap test to be rerun _File.__dict__['_mmap_available']._cache.clear() try: self.copy_file('test0.fits') with catch_warnings() as w: with fits.open(self.temp('test0.fits'), mode='update', memmap=True) as h: h[1].data[0, 0] = 999 assert len(w) == 1 assert 'mmap.flush is unavailable' in str(w[0].message) # Double check that writing without mmap still worked with fits.open(self.temp('test0.fits')) as h: assert h[1].data[0, 0] == 999 finally: mmap.mmap = old_mmap _File.__dict__['_mmap_available']._cache.clear() def test_mmap_closing(self): """ Tests that the mmap reference is closed/removed when there aren't any HDU data references left. """ if not _File._mmap_available: pytest.xfail('not expected to work on platforms without mmap ' 'support') with fits.open(self.data('test0.fits'), memmap=True) as hdul: assert hdul._file._mmap is None hdul[1].data assert hdul._file._mmap is not None del hdul[1].data # Should be no more references to data in the file so close the # mmap assert hdul._file._mmap is None hdul[1].data hdul[2].data del hdul[1].data # hdul[2].data is still references so keep the mmap open assert hdul._file._mmap is not None del hdul[2].data assert hdul._file._mmap is None assert hdul._file._mmap is None with fits.open(self.data('test0.fits'), memmap=True) as hdul: hdul[1].data # When the only reference to the data is on the hdu object, and the # hdulist it belongs to has been closed, the mmap should be closed as # well assert hdul._file._mmap is None with fits.open(self.data('test0.fits'), memmap=True) as hdul: data = hdul[1].data # also make a copy data_copy = data.copy() # The HDUList is closed; in fact, get rid of it completely del hdul # The data array should still work though... assert np.all(data == data_copy) def test_uncloseable_file(self): """ Regression test for https://github.com/astropy/astropy/issues/2356 Demonstrates that FITS files can still be read from "file-like" objects that don't have an obvious "open" or "closed" state. """ class MyFileLike: def __init__(self, foobar): self._foobar = foobar def read(self, n): return self._foobar.read(n) def seek(self, offset, whence=os.SEEK_SET): self._foobar.seek(offset, whence) def tell(self): return self._foobar.tell() with open(self.data('test0.fits'), 'rb') as f: fileobj = MyFileLike(f) with fits.open(fileobj) as hdul1: with fits.open(self.data('test0.fits')) as hdul2: assert hdul1.info(output=False) == hdul2.info(output=False) for hdu1, hdu2 in zip(hdul1, hdul2): assert hdu1.header == hdu2.header if hdu1.data is not None and hdu2.data is not None: assert np.all(hdu1.data == hdu2.data) def test_write_bytesio_discontiguous(self): """ Regression test related to https://github.com/astropy/astropy/issues/2794#issuecomment-55441539 Demonstrates that writing an HDU containing a discontiguous Numpy array should work properly. """ data = np.arange(100)[::3] hdu = fits.PrimaryHDU(data=data) fileobj = io.BytesIO() hdu.writeto(fileobj) fileobj.seek(0) with fits.open(fileobj) as h: assert np.all(h[0].data == data) def test_write_bytesio(self): """ Regression test for https://github.com/astropy/astropy/issues/2463 Test againt `io.BytesIO`. `io.StringIO` is not supported. """ self._test_write_string_bytes_io(io.BytesIO()) @pytest.mark.skipif(str('sys.platform.startswith("win32")')) def test_filename_with_colon(self): """ Test reading and writing a file with a colon in the filename. Regression test for https://github.com/astropy/astropy/issues/3122 """ # Skip on Windows since colons in filenames makes NTFS sad. filename = 'APEXHET.2014-04-01T15:18:01.000.fits' hdu = fits.PrimaryHDU(data=np.arange(10)) hdu.writeto(self.temp(filename)) with fits.open(self.temp(filename)) as hdul: assert np.all(hdul[0].data == hdu.data) def test_writeto_full_disk(self, monkeypatch): """ Test that it gives a readable error when trying to write an hdulist to a full disk. """ def _writeto(self, array): raise OSError("Fake error raised when writing file.") def get_free_space_in_dir(path): return 0 with pytest.raises(OSError) as exc: monkeypatch.setattr(fits.hdu.base._BaseHDU, "_writeto", _writeto) monkeypatch.setattr(data, "get_free_space_in_dir", get_free_space_in_dir) n = np.arange(0, 1000, dtype='int64') hdu = fits.PrimaryHDU(n) hdulist = fits.HDUList(hdu) filename = self.temp('test.fits') with open(filename, mode='wb') as fileobj: hdulist.writeto(fileobj) assert ("Not enough space on disk: requested 8000, available 0. " "Fake error raised when writing file.") == exc.value.args[0] def test_flush_full_disk(self, monkeypatch): """ Test that it gives a readable error when trying to update an hdulist to a full disk. """ filename = self.temp('test.fits') hdul = [fits.PrimaryHDU(), fits.ImageHDU()] hdul = fits.HDUList(hdul) hdul[0].data = np.arange(0, 1000, dtype='int64') hdul.writeto(filename) def _writedata(self, fileobj): raise OSError("Fake error raised when writing file.") def get_free_space_in_dir(path): return 0 monkeypatch.setattr(fits.hdu.base._BaseHDU, "_writedata", _writedata) monkeypatch.setattr(data, "get_free_space_in_dir", get_free_space_in_dir) with pytest.raises(OSError) as exc: with fits.open(filename, mode='update') as hdul: hdul[0].data = np.arange(0, 1000, dtype='int64') hdul.insert(1, fits.ImageHDU()) hdul.flush() assert ("Not enough space on disk: requested 8000, available 0. " "Fake error raised when writing file.") == exc.value.args[0] def _test_write_string_bytes_io(self, fileobj): """ Implemented for both test_write_stringio and test_write_bytesio. """ with fits.open(self.data('test0.fits')) as hdul: hdul.writeto(fileobj) hdul2 = fits.HDUList.fromstring(fileobj.getvalue()) assert FITSDiff(hdul, hdul2).identical def _make_gzip_file(self, filename='test0.fits.gz'): gzfile = self.temp(filename) with open(self.data('test0.fits'), 'rb') as f: gz = gzip.open(gzfile, 'wb') gz.write(f.read()) gz.close() return gzfile def _make_zip_file(self, mode='copyonwrite', filename='test0.fits.zip'): zfile = zipfile.ZipFile(self.temp(filename), 'w') zfile.write(self.data('test0.fits')) zfile.close() return zfile.filename def _make_bzip2_file(self, filename='test0.fits.bz2'): bzfile = self.temp(filename) with open(self.data('test0.fits'), 'rb') as f: bz = bz2.BZ2File(bzfile, 'w') bz.write(f.read()) bz.close() return bzfile class TestStreamingFunctions(FitsTestCase): """Test functionality of the StreamingHDU class.""" def test_streaming_hdu(self): shdu = self._make_streaming_hdu(self.temp('new.fits')) assert isinstance(shdu.size, int) assert shdu.size == 100 @raises(ValueError) def test_streaming_hdu_file_wrong_mode(self): """ Test that streaming an HDU to a file opened in the wrong mode fails as expected. """ with open(self.temp('new.fits'), 'wb') as f: header = fits.Header() fits.StreamingHDU(f, header) def test_streaming_hdu_write_file(self): """Test streaming an HDU to an open file object.""" arr = np.zeros((5, 5), dtype=np.int32) with open(self.temp('new.fits'), 'ab+') as f: shdu = self._make_streaming_hdu(f) shdu.write(arr) assert shdu.writecomplete assert shdu.size == 100 hdul = fits.open(self.temp('new.fits')) assert len(hdul) == 1 assert (hdul[0].data == arr).all() def test_streaming_hdu_write_file_like(self): """Test streaming an HDU to an open file-like object.""" arr = np.zeros((5, 5), dtype=np.int32) # The file-like object underlying a StreamingHDU must be in binary mode sf = io.BytesIO() shdu = self._make_streaming_hdu(sf) shdu.write(arr) assert shdu.writecomplete assert shdu.size == 100 sf.seek(0) hdul = fits.open(sf) assert len(hdul) == 1 assert (hdul[0].data == arr).all() def test_streaming_hdu_append_extension(self): arr = np.zeros((5, 5), dtype=np.int32) with open(self.temp('new.fits'), 'ab+') as f: shdu = self._make_streaming_hdu(f) shdu.write(arr) # Doing this again should update the file with an extension with open(self.temp('new.fits'), 'ab+') as f: shdu = self._make_streaming_hdu(f) shdu.write(arr) def test_fix_invalid_extname(self, capsys): phdu = fits.PrimaryHDU() ihdu = fits.ImageHDU() ihdu.header['EXTNAME'] = 12345678 hdul = fits.HDUList([phdu, ihdu]) pytest.raises(fits.VerifyError, hdul.writeto, self.temp('temp.fits'), output_verify='exception') hdul.writeto(self.temp('temp.fits'), output_verify='fix') with fits.open(self.temp('temp.fits')): assert hdul[1].name == '12345678' assert hdul[1].header['EXTNAME'] == '12345678' def _make_streaming_hdu(self, fileobj): hd = fits.Header() hd['SIMPLE'] = (True, 'conforms to FITS standard') hd['BITPIX'] = (32, 'array data type') hd['NAXIS'] = (2, 'number of array dimensions') hd['NAXIS1'] = 5 hd['NAXIS2'] = 5 hd['EXTEND'] = True return fits.StreamingHDU(fileobj, hd) def test_blank_ignore(self): with fits.open(self.data('blank.fits'), ignore_blank=True) as f: assert f[0].data.flat[0] == 2 def test_error_if_memmap_impossible(self): pth = self.data('blank.fits') with pytest.raises(ValueError): fits.open(pth, memmap=True)[0].data # However, it should not fail if do_not_scale_image_data was used: # See https://github.com/astropy/astropy/issues/3766 hdul = fits.open(pth, memmap=True, do_not_scale_image_data=True) hdul[0].data # Just make sure it doesn't crash
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import time from django.conf import settings from .intervals import Interval, IntervalSet from .carbonlink import CarbonLink from .logger import log try: import whisper except ImportError: whisper = False try: import rrdtool except ImportError: rrdtool = False try: import gzip except ImportError: gzip = False class FetchInProgress(object): def __init__(self, wait_callback): self.wait_callback = wait_callback def waitForResults(self): return self.wait_callback() class MultiReader(object): __slots__ = ('nodes',) def __init__(self, nodes): self.nodes = nodes def get_intervals(self): interval_sets = [] for node in self.nodes: interval_sets.extend(node.intervals.intervals) return IntervalSet(sorted(interval_sets)) def fetch(self, startTime, endTime): # Start the fetch on each node results = [n.fetch(startTime, endTime) for n in self.nodes] # Wait for any asynchronous operations to complete for i, result in enumerate(results): if isinstance(result, FetchInProgress): try: results[i] = result.waitForResults() except: log.exception("Failed to complete subfetch") results[i] = None results = [r for r in results if r is not None] if not results: raise Exception("All sub-fetches failed") return reduce(self.merge, results) def merge(self, results1, results2): # Ensure results1 is finer than results2 if results1[0][2] > results2[0][2]: results1, results2 = results2, results1 time_info1, values1 = results1 time_info2, values2 = results2 start1, end1, step1 = time_info1 start2, end2, step2 = time_info2 step = step1 # finest step start = min(start1, start2) # earliest start end = max(end1, end2) # latest end time_info = (start, end, step) values = [] t = start while t < end: # Look for the finer precision value first if available i1 = (t - start1) / step1 if len(values1) > i1: v1 = values1[i1] else: v1 = None if v1 is None: i2 = (t - start2) / step2 if len(values2) > i2: v2 = values2[i2] else: v2 = None values.append(v2) else: values.append(v1) t += step return (time_info, values) class CeresReader(object): __slots__ = ('ceres_node', 'real_metric_path') supported = True def __init__(self, ceres_node, real_metric_path): self.ceres_node = ceres_node self.real_metric_path = real_metric_path def get_intervals(self): intervals = [] for info in self.ceres_node.slice_info: (start, end, step) = info intervals.append(Interval(start, end)) return IntervalSet(intervals) def fetch(self, startTime, endTime): data = self.ceres_node.read(startTime, endTime) time_info = (data.startTime, data.endTime, data.timeStep) values = list(data.values) # Merge in data from carbon's cache try: cached_datapoints = CarbonLink.query(self.real_metric_path) except: log.exception("Failed CarbonLink query '%s'" % self.real_metric_path) cached_datapoints = [] for (timestamp, value) in cached_datapoints: interval = timestamp - (timestamp % data.timeStep) try: i = int(interval - data.startTime) / data.timeStep values[i] = value except: pass return (time_info, values) class WhisperReader(object): __slots__ = ('fs_path', 'real_metric_path') supported = bool(whisper) def __init__(self, fs_path, real_metric_path): self.fs_path = fs_path self.real_metric_path = real_metric_path def get_intervals(self): start = time.time() - whisper.info(self.fs_path)['maxRetention'] end = max(os.stat(self.fs_path).st_mtime, start) return IntervalSet([Interval(start, end)]) def fetch(self, startTime, endTime): data = whisper.fetch(self.fs_path, startTime, endTime) if not data: return None time_info, values = data (start, end, step) = time_info meta_info = whisper.info(self.fs_path) lowest_step = min([i['secondsPerPoint'] for i in meta_info['archives']]) # Merge in data from carbon's cache cached_datapoints = [] try: if step == lowest_step: cached_datapoints = CarbonLink.query(self.real_metric_path) except: log.exception("Failed CarbonLink query '%s'" % self.real_metric_path) cached_datapoints = [] if isinstance(cached_datapoints, dict): cached_datapoints = cached_datapoints.items() for (timestamp, value) in cached_datapoints: interval = timestamp - (timestamp % step) try: i = int(interval - start) / step values[i] = value except: pass return (time_info, values) class GzippedWhisperReader(WhisperReader): supported = bool(whisper and gzip) def get_intervals(self): fh = gzip.GzipFile(self.fs_path, 'rb') try: info = whisper.__readHeader(fh) # evil, but necessary. finally: fh.close() start = time.time() - info['maxRetention'] end = max(os.stat(self.fs_path).st_mtime, start) return IntervalSet([Interval(start, end)]) def fetch(self, startTime, endTime): fh = gzip.GzipFile(self.fs_path, 'rb') try: return whisper.file_fetch(fh, startTime, endTime) finally: fh.close() class RRDReader: supported = bool(rrdtool) def __init__(self, fs_path, datasource_name): self.fs_path = fs_path self.datasource_name = datasource_name def get_intervals(self): start = time.time() - self.get_retention(self.fs_path) end = max(os.stat(self.fs_path).st_mtime, start) return IntervalSet([Interval(start, end)]) def fetch(self, startTime, endTime): startString = time.strftime("%H:%M_%Y%m%d+%Ss", time.localtime(startTime)) endString = time.strftime("%H:%M_%Y%m%d+%Ss", time.localtime(endTime)) if settings.FLUSHRRDCACHED: rrdtool.flushcached(self.fs_path, '--daemon', settings.FLUSHRRDCACHED) (timeInfo, columns, rows) = rrdtool.fetch(self.fs_path, settings.RRD_CF, '-s' + startString, '-e' + endString) colIndex = list(columns).index(self.datasource_name) rows.pop() # chop off the latest value because RRD returns crazy last values sometimes values = (row[colIndex] for row in rows) return (timeInfo, values) @staticmethod def get_datasources(fs_path): info = rrdtool.info(fs_path) if 'ds' in info: return [datasource_name for datasource_name in info['ds']] else: ds_keys = [key for key in info if key.startswith('ds[')] datasources = set(key[3:].split(']')[0] for key in ds_keys) return list(datasources) @staticmethod def get_retention(fs_path): info = rrdtool.info(fs_path) if 'rra' in info: rras = info['rra'] else: # Ugh, I like the old python-rrdtool api better.. rra_count = max([int(key[4]) for key in info if key.startswith('rra[')]) + 1 rras = [{}] * rra_count for i in range(rra_count): rras[i]['pdp_per_row'] = info['rra[%d].pdp_per_row' % i] rras[i]['rows'] = info['rra[%d].rows' % i] retention_points = 0 for rra in rras: points = rra['pdp_per_row'] * rra['rows'] if points > retention_points: retention_points = points return retention_points * info['step']
from sympy.core.assumptions import StdFactKB from sympy.core import S, Pow, Symbol from sympy.core.expr import AtomicExpr from sympy.core.compatibility import range from sympy import diff as df, sqrt, ImmutableMatrix as Matrix from sympy.vector.coordsysrect import CoordSysCartesian from sympy.vector.basisdependent import BasisDependent, \ BasisDependentAdd, BasisDependentMul, BasisDependentZero from sympy.vector.dyadic import BaseDyadic, Dyadic, DyadicAdd from sympy.core.compatibility import u class Vector(BasisDependent): """ Super class for all Vector classes. Ideally, neither this class nor any of its subclasses should be instantiated by the user. """ is_Vector = True _op_priority = 12.0 @property def components(self): """ Returns the components of this vector in the form of a Python dictionary mapping BaseVector instances to the corresponding measure numbers. Examples ======== >>> from sympy.vector import CoordSysCartesian >>> C = CoordSysCartesian('C') >>> v = 3*C.i + 4*C.j + 5*C.k >>> v.components {C.i: 3, C.j: 4, C.k: 5} """ #The '_components' attribute is defined according to the #subclass of Vector the instance belongs to. return self._components def magnitude(self): """ Returns the magnitude of this vector. """ return sqrt(self & self) def normalize(self): """ Returns the normalized version of this vector. """ return self / self.magnitude() def dot(self, other): """ Returns the dot product of this Vector, either with another Vector, or a Dyadic, or a Del operator. If 'other' is a Vector, returns the dot product scalar (Sympy expression). If 'other' is a Dyadic, the dot product is returned as a Vector. If 'other' is an instance of Del, returns the directional derivate operator as a Python function. If this function is applied to a scalar expression, it returns the directional derivative of the scalar field wrt this Vector. Parameters ========== other: Vector/Dyadic/Del The Vector or Dyadic we are dotting with, or a Del operator . Examples ======== >>> from sympy.vector import CoordSysCartesian >>> C = CoordSysCartesian('C') >>> C.i.dot(C.j) 0 >>> C.i & C.i 1 >>> v = 3*C.i + 4*C.j + 5*C.k >>> v.dot(C.k) 5 >>> (C.i & C.delop)(C.x*C.y*C.z) C.y*C.z >>> d = C.i.outer(C.i) >>> C.i.dot(d) C.i """ from sympy.vector.functions import express #Check special cases if isinstance(other, Dyadic): if isinstance(self, VectorZero): return Vector.zero outvec = Vector.zero for k, v in other.components.items(): vect_dot = k.args[0].dot(self) outvec += vect_dot * v * k.args[1] return outvec from sympy.vector.deloperator import Del if not isinstance(other, Vector) and not isinstance(other, Del): raise TypeError(str(other) + " is not a vector, dyadic or " + "del operator") #Check if the other is a del operator if isinstance(other, Del): def directional_derivative(field): field = express(field, other.system, variables = True) out = self.dot(other._i) * df(field, other._x) out += self.dot(other._j) * df(field, other._y) out += self.dot(other._k) * df(field, other._z) if out == 0 and isinstance(field, Vector): out = Vector.zero return out return directional_derivative if isinstance(self, VectorZero) or isinstance(other, VectorZero): return S(0) v1 = express(self, other._sys) v2 = express(other, other._sys) dotproduct = S(0) for x in other._sys.base_vectors(): dotproduct += (v1.components.get(x, 0) * v2.components.get(x, 0)) return dotproduct def __and__(self, other): return self.dot(other) __and__.__doc__ = dot.__doc__ def cross(self, other): """ Returns the cross product of this Vector with another Vector or Dyadic instance. The cross product is a Vector, if 'other' is a Vector. If 'other' is a Dyadic, this returns a Dyadic instance. Parameters ========== other: Vector/Dyadic The Vector or Dyadic we are crossing with. Examples ======== >>> from sympy.vector import CoordSysCartesian >>> C = CoordSysCartesian('C') >>> C.i.cross(C.j) C.k >>> C.i ^ C.i 0 >>> v = 3*C.i + 4*C.j + 5*C.k >>> v ^ C.i 5*C.j + (-4)*C.k >>> d = C.i.outer(C.i) >>> C.j.cross(d) (-1)*(C.k|C.i) """ #Check special cases if isinstance(other, Dyadic): if isinstance(self, VectorZero): return Dyadic.zero outdyad = Dyadic.zero for k, v in other.components.items(): cross_product = self.cross(k.args[0]) outer = cross_product.outer(k.args[1]) outdyad += v * outer return outdyad elif not isinstance(other, Vector): raise TypeError(str(other) + " is not a vector") elif (isinstance(self, VectorZero) or isinstance(other, VectorZero)): return Vector.zero #Compute cross product def _det(mat): """This is needed as a little method for to find the determinant of a list in python. SymPy's Matrix won't take in Vector, so need a custom function. The user shouldn't be calling this. """ return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) + mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] * mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0])) outvec = Vector.zero for system, vect in other.separate().items(): tempi = system.i tempj = system.j tempk = system.k tempm = [[tempi, tempj, tempk], [self & tempi, self & tempj, self & tempk], [vect & tempi, vect & tempj, vect & tempk]] outvec += _det(tempm) return outvec def __xor__(self, other): return self.cross(other) __xor__.__doc__ = cross.__doc__ def outer(self, other): """ Returns the outer product of this vector with another, in the form of a Dyadic instance. Parameters ========== other : Vector The Vector with respect to which the outer product is to be computed. Examples ======== >>> from sympy.vector import CoordSysCartesian >>> N = CoordSysCartesian('N') >>> N.i.outer(N.j) (N.i|N.j) """ #Handle the special cases if not isinstance(other, Vector): raise TypeError("Invalid operand for outer product") elif (isinstance(self, VectorZero) or isinstance(other, VectorZero)): return Dyadic.zero #Iterate over components of both the vectors to generate #the required Dyadic instance args = [] for k1, v1 in self.components.items(): for k2, v2 in other.components.items(): args.append((v1*v2) * BaseDyadic(k1, k2)) return DyadicAdd(*args) def projection(self, other, scalar=False): """ Returns the vector or scalar projection of the 'other' on 'self'. Examples ======== >>> from sympy.vector.coordsysrect import CoordSysCartesian >>> from sympy.vector.vector import Vector, BaseVector >>> C = CoordSysCartesian('C') >>> i, j, k = C.base_vectors() >>> v1 = i + j + k >>> v2 = 3*i + 4*j >>> v1.projection(v2) 7/3*C.i + 7/3*C.j + 7/3*C.k >>> v1.projection(v2, scalar=True) 7/3 """ if self.equals(Vector.zero): return S.zero if scalar else Vector.zero if scalar: return self.dot(other) / self.dot(self) else: return self.dot(other) / self.dot(self) * self def __or__(self, other): return self.outer(other) __or__.__doc__ = outer.__doc__ def to_matrix(self, system): """ Returns the matrix form of this vector with respect to the specified coordinate system. Parameters ========== system : CoordSysCartesian The system wrt which the matrix form is to be computed Examples ======== >>> from sympy.vector import CoordSysCartesian >>> C = CoordSysCartesian('C') >>> from sympy.abc import a, b, c >>> v = a*C.i + b*C.j + c*C.k >>> v.to_matrix(C) Matrix([ [a], [b], [c]]) """ return Matrix([self.dot(unit_vec) for unit_vec in system.base_vectors()]) def separate(self): """ The constituents of this vector in different coordinate systems, as per its definition. Returns a dict mapping each CoordSysCartesian to the corresponding constituent Vector. Examples ======== >>> from sympy.vector import CoordSysCartesian >>> R1 = CoordSysCartesian('R1') >>> R2 = CoordSysCartesian('R2') >>> v = R1.i + R2.i >>> v.separate() == {R1: R1.i, R2: R2.i} True """ parts = {} for vect, measure in self.components.items(): parts[vect.system] = (parts.get(vect.system, Vector.zero) + vect*measure) return parts class BaseVector(Vector, AtomicExpr): """ Class to denote a base vector. """ def __new__(cls, name, index, system, pretty_str, latex_str): name = str(name) pretty_str = str(pretty_str) latex_str = str(latex_str) #Verify arguments if not index in range(0, 3): raise ValueError("index must be 0, 1 or 2") if not isinstance(system, CoordSysCartesian): raise TypeError("system should be a CoordSysCartesian") #Initialize an object obj = super(BaseVector, cls).__new__(cls, Symbol(name), S(index), system, Symbol(pretty_str), Symbol(latex_str)) #Assign important attributes obj._base_instance = obj obj._components = {obj: S(1)} obj._measure_number = S(1) obj._name = name obj._pretty_form = u(pretty_str) obj._latex_form = latex_str obj._system = system assumptions = {} assumptions['commutative'] = True obj._assumptions = StdFactKB(assumptions) #This attr is used for re-expression to one of the systems #involved in the definition of the Vector. Applies to #VectorMul and VectorAdd too. obj._sys = system return obj @property def system(self): return self._system def __str__(self, printer=None): return self._name @property def free_symbols(self): return set([self]) __repr__ = __str__ _sympystr = __str__ class VectorAdd(BasisDependentAdd, Vector): """ Class to denote sum of Vector instances. """ def __new__(cls, *args, **options): obj = BasisDependentAdd.__new__(cls, *args, **options) return obj def __str__(self, printer=None): ret_str = '' items = list(self.separate().items()) items.sort(key = lambda x: x[0].__str__()) for system, vect in items: base_vects = system.base_vectors() for x in base_vects: if x in vect.components: temp_vect = self.components[x]*x ret_str += temp_vect.__str__(printer) + " + " return ret_str[:-3] __repr__ = __str__ _sympystr = __str__ class VectorMul(BasisDependentMul, Vector): """ Class to denote products of scalars and BaseVectors. """ def __new__(cls, *args, **options): obj = BasisDependentMul.__new__(cls, *args, **options) return obj @property def base_vector(self): """ The BaseVector involved in the product. """ return self._base_instance @property def measure_number(self): """ The scalar expression involved in the defition of this VectorMul. """ return self._measure_number class VectorZero(BasisDependentZero, Vector): """ Class to denote a zero vector """ _op_priority = 12.1 _pretty_form = u('0') _latex_form = '\mathbf{\hat{0}}' def __new__(cls): obj = BasisDependentZero.__new__(cls) return obj def _vect_div(one, other): """ Helper for division involving vectors. """ if isinstance(one, Vector) and isinstance(other, Vector): raise TypeError("Cannot divide two vectors") elif isinstance(one, Vector): if other == S.Zero: raise ValueError("Cannot divide a vector by zero") return VectorMul(one, Pow(other, S.NegativeOne)) else: raise TypeError("Invalid division involving a vector") Vector._expr_type = Vector Vector._mul_func = VectorMul Vector._add_func = VectorAdd Vector._zero_func = VectorZero Vector._base_func = BaseVector Vector._div_helper = _vect_div Vector.zero = VectorZero()
""" nbtattr """ from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging import uuid from mceditlib import nbt from mceditlib.geometry import Vector log = logging.getLogger(__name__) class NBTAttr(object): """ NBT Attributes can be added to any class whose instances have a 'rootTag' attribute, usually an EntityRef or TileEntityRef. Adding the attribute exposes one subtag of the rootTag as an attribute of the instance, allowing you to use shorter code for accessing the subtag's value. The attribute accepts a tag type and default value to use for creating the tag if it is not found. Changing the attribute's values sets the 'dirty' attribute of the instance to True. This is used by EntityRef and TileEntityRef to mark the containing chunk dirty. Specialized NBT Attributes are also provided for UUIDs (`NBTUUIDAttr`), Vectors such as an entity's Position (`NBTVectorAttr`), lists with a fixed type (`NBTListAttr`), and lists of compounds (`NBTCompoundListAttr`). The function SetNBTDefaults can be used to initialize all subtags of an instance's rootTag to their defaults, creating them if needed. Without NBTAttr:: # getting if "Dimension" not in rootTag: return 0 return rootTag["Dimension"].value # setting if "Dimension" not in rootTag: rootTag["Dimension"] = nbt.TAG_Int() rootTag["Dimension"].value = 1 With NBTAttr:: class PlayerRef(object): Dimension = NBTAttr("Dimension", nbt.TAG_Int, 0) ref = PlayerRef() ref.rootTag = rootTag # getting return ref.Dimension # setting ref.Dimension = 1 """ def __repr__(self): return "NBTAttr('%s', %s, %r)" % (self.name, self.tagType, self.default) def __init__(self, name, tagType, default=None, doc=""): self.name = name self.tagType = tagType self.default = default self.__doc__ = doc def __get__(self, instance, owner): if instance is None: return self # attribute access on class returns the NBTAttr, like property() tag = instance.rootTag if self.name not in tag: if self.default is None: raise ValueError("No default value set for tag %r.", self.name) tag[self.name] = self.tagType(value=self.default) return tag[self.name].value def __set__(self, instance, value): tag = instance.rootTag if self.name not in tag: tag[self.name] = self.tagType(value) else: tag[self.name].value = value instance.dirty = True class NBTUUIDAttr(object): """ This attribute gets the entity's UUID from its `UUIDLeast` and `UUIDMost` tags and returns it as a `uuid.UUID` """ def __repr__(self): return "NBTUUIDAttr()" def __get__(self, instance, owner): if instance is None: return self tag = instance.rootTag if 'UUIDLeast' not in tag or 'UUIDMost' not in tag: return None least = tag["UUIDLeast"].value & 0xffffffffffffffffL most = tag["UUIDMost"].value & 0xffffffffffffffffL uuidInt = (most << 64 | least) & 0xffffffffffffffffffffffffffffffffL UUID = uuid.UUID(int=uuidInt) return UUID def __set__(self, instance, value): uuidInt = value.int least = uuidInt & 0xffffffffffffffffL most = (uuidInt >> 64) & 0xffffffffffffffffL tag = instance.rootTag tag["UUIDLeast"].value = least tag["UUIDMost"].value = most instance.dirty = True class NBTCompoundRef(object): def __init__(self, rootTag, parent): """ A reference object wrapping a TAG_Compound, with a pointer back to the parent reference object. Intended to be subclassed and used with NBTAttrs. The `dirty` and `blockTypes` attributes on an NBTCompoundRef are aliases for the parent object's attribute. :param rootTag: :type rootTag: nbt.TAG_Compound :param parent: :type parent: NBTCompoundRef | WorldEditorChunk :return: :rtype: """ super(NBTCompoundRef, self).__init__() self.parent = parent self.rootTag = rootTag @property def dirty(self): if self.parent: return self.parent.dirty return True @dirty.setter def dirty(self, value): if self.parent: self.parent.dirty = value @property def blockTypes(self): return self.parent.blockTypes def copy(self): tag = self.rootTag.copy() return self.__class__(tag, None) class NBTListProxy(collections.MutableSequence): """ A proxy returned by NBTListAttr and NBTCompoundListAttr that allows the elements of a TAG_List to be accessed as instances of its refClass, or as plain values if refClass is not given (in the case of a list containing tags other than TAG_List or TAG_Compound). If refClass is given, objects inserted into a list are checked for a rootTag attribute, which is inserted into the list if present. Otherwise, the object itself is inserted, possibly raising a TypeError if it is not an NBT tag or not the proper tag type for the list. """ def __init__(self, parent, tagName, refClass=None): self.tagName = tagName self.refClass = refClass self.parent = parent def __getitem__(self, key): if self.refClass: return self.refClass(self.parent.rootTag[self.tagName][key], self.parent) else: return self.parent.rootTag[self.tagName][key].value def __setitem__(self, key, value): if getattr(value, 'parent') is not None: raise ValueError("Adding a ref that has a parent (use ref.copy() to make a new ref)") if hasattr(value, 'rootTag'): tag = value.rootTag elif isinstance(value, nbt.TAG_Value): tag = value else: tag = self.parent self.parent.rootTag[self.tagName][key] = tag def __delitem__(self, key): del self.parent.rootTag[self.tagName][key] def __len__(self): return len(self.parent.rootTag[self.tagName]) def insert(self, index, value): if hasattr(value, 'rootTag'): tag = value.rootTag else: tag = value self.parent.rootTag[self.tagName].insert(index, tag) @property def blockTypes(self): return self.parent.blockTypes class NBTCompoundListAttr(object): """ An attribute for accessing a list of compound tags, possibly wrapped by a subclass of NBTCompoundRef passed to the constructor. """ def __init__(self, name, compoundRefClass, doc=""): self.name = name self.compoundRefClass = compoundRefClass self.listProxyClass = NBTListProxy self.__doc__ = doc def __repr__(self): return "NBTListAttr(%s, %s)" % (self.name, self.compoundRefClass) def __get__(self, instance, owner): if instance is None: return self tag = instance.rootTag if self.name not in tag: tag[self.name] = nbt.TAG_List() return self.listProxyClass(instance, self.name, self.compoundRefClass) class NBTListAttr(object): def __repr__(self): return "NBTListAttr(%s, %s, %s)" % (self.name, self.listType, self.default) def __init__(self, name, listType, default=(), doc=""): self.name = name self.listType = listType self.default = default self.__doc__ = doc def __get__(self, instance, owner): if instance is None: return self tag = instance.rootTag if self.name not in tag: tag[self.name] = nbt.TAG_List() return NBTListProxy(instance, self.name) def __set__(self, instance, value): rootTag = instance.rootTag if self.name not in rootTag: if self.listType is None: raise ValueError("Tried to initialize list with values without setting listType first!") rootTag[self.name] = nbt.TAG_List([self.listType(i) for i in value]) else: tag = rootTag[self.name] for i, v in enumerate(tag): v.value = value[i] instance.dirty = True class NBTCompoundAttr(NBTAttr): def __repr__(self): return "NBTCompoundAttr(%s, %s)" % (self.name, self.compoundRefClass) def __init__(self, name, compoundRefClass, doc=""): super(NBTCompoundAttr, self).__init__(name, nbt.TAG_Compound, doc=doc) self.compoundRefClass = compoundRefClass def __get__(self, instance, owner): if instance is None: return self tag = instance.rootTag if self.name not in tag: tag[self.name] = self.tagType(value=self.default) return self.compoundRefClass(tag[self.name], instance) def __set__(self, instance, value): """ Should accept a dict of name:value pairs """ raise NotImplementedError("Cannot replace entire compound through NBTCompoundAttr (yet)") # tag = instance.rootTag # if self.name not in tag: # tag[self.name] = self.tagType(value) # else: # tag[self.name].value = value class NBTVectorAttr(NBTListAttr): def __get__(self, instance, owner): if instance is None: return self val = super(NBTVectorAttr, self).__get__(instance, owner) return Vector(*val) class KeyedVectorAttr(object): """ This attr is useful when a Vector is represented as a trio of named tags in a compound instead of as a list of tags. For example, the world spawn position (SpawnX, SpawnY, SpawnZ) and a TileEntity's position (x, y, z). """ def __init__(self, xKey, yKey, zKey, tagType, default=None, doc=""): self.tagType = tagType self.default = default self.keys = xKey, yKey, zKey self.__doc__ = doc def __get__(self, instance, owner): if instance is None: return self tag = instance.rootTag for key in self.keys: if key not in tag: tag[key] = self.tagType(value=self.default) return Vector(*[tag[k].value for k in self.keys]) def __set__(self, instance, value): tag = instance.rootTag for key, val in zip(self.keys, value): if key not in tag: tag[key] = self.tagType(val) else: tag[key].value = val instance.dirty = True def SetNBTDefaults(ref): """ Given an object whose class has several members of type `NBT[*]Attr`, sets those attributes to their default values. """ cls = ref.__class__ for k, v in cls.__dict__.iteritems(): if isinstance(v, NBTCompoundAttr): ref.rootTag[k] = nbt.TAG_Compound() SetNBTDefaults(getattr(ref, k)) elif isinstance(v, (NBTAttr, NBTListAttr)): if v.default is not None: setattr(ref, k, v.default)
# BSD 3-Clause License # # Copyright (c) 2017, Thomas Pointhuber # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import argparse import sys import mx import mx_sulong import mx_testsuites _suite = mx.suite('irbuilder') class Tool(object): def supports(self, language): return language in self.supportedLanguages def runTool(self, args, errorMsg=None, verbose=None, **kwargs): try: if not mx.get_opts().verbose and not verbose: f = open(os.devnull, 'w') ret = mx.run(args, out=f, err=f, **kwargs) else: f = None ret = mx.run(args, **kwargs) except SystemExit: ret = -1 if errorMsg is None: mx.log_error() mx.log_error('Error: Cannot run {}'.format(args)) else: mx.log_error() mx.log_error('Error: {}'.format(errorMsg)) mx.log_error(' '.join(args)) if f is not None: f.close() return ret class LlvmAS(Tool): def __init__(self, supportedVersions): self.supportedVersions = supportedVersions def find_tool(self): return mx_sulong.findLLVMProgram('llvm-as', self.supportedVersions) def run(self, inputFile, flags=None): if flags is None: flags = [] tool = self.find_tool() return self.runTool([tool] + flags + [inputFile], errorMsg='Cannot assemble %s with %s' % (inputFile, tool), verbose=True) class LlvmLLI(Tool): def __init__(self, supportedVersions): self.supportedVersions = supportedVersions def find_tool(self): return mx_sulong.findLLVMProgram('lli', self.supportedVersions) def run(self, inputFile, flags=None): if flags is None: flags = [] tool = self.find_tool() return self.runTool([tool] + flags + [inputFile], nonZeroIsFatal=False, timeout=30, errorMsg='Cannot run %s with %s' % (inputFile, tool)) LlvmAS_32 = LlvmAS(['3.2', '3.3']) LlvmAS_38 = LlvmAS(['3.8', '3.9', '4.0', '5.0']) LlvmLLI_32 = LlvmLLI(['3.2', '3.3']) LlvmLLI_38 = LlvmLLI(['3.8', '3.9', '4.0', '5.0']) def getIRWriterClasspathOptions(): """gets the classpath of the IRWRITER distributions""" return mx.get_runtime_jvm_args('IRWRITER') def runIRBuilderOut(args=None, out=None): """uses java-llvm-ir-builder to parse a LLVM Bitcode file and outputs it's LLVM IR""" vmArgs, irbuilderArgs = mx_sulong.truffle_extract_VM_args(args) return mx.run_java(mx_sulong.getCommonOptions(False) + vmArgs + getIRWriterClasspathOptions() + ["at.pointhi.irbuilder.irwriter.SourceParser"] + irbuilderArgs) irBuilderTests32 = { 'gcc_c' : ['gcc_c', "at.pointhi.irbuilder.test.GCCGeneratorSuite", os.path.join(mx_testsuites._cacheDir, 'gcc'), ['-Dsulongtest.fileExtensionFilter=.c']], } irBuilderTests38 = { 'llvm' : ['llvm', "at.pointhi.irbuilder.test.LLVMGeneratorSuite", os.path.join(mx_testsuites._cacheDir, 'llvm'), []], 'gcc_c' : ['gcc_c', "at.pointhi.irbuilder.test.GCCGeneratorSuite", os.path.join(mx_testsuites._cacheDir, 'gcc'), ['-Dsulongtest.fileExtensionFilter=.c']], 'gcc_cpp' : ['gcc_cpp', "at.pointhi.irbuilder.test.GCCGeneratorSuite", os.path.join(mx_testsuites._cacheDir, 'gcc'), ['-Dsulongtest.fileExtensionFilter=.cpp:.C:.cc']], 'nwcc' : ['nwcc', "at.pointhi.irbuilder.test.NWCCGeneratorSuite", os.path.join(mx_testsuites._cacheDir, 'nwcc'), []], 'assembly' : ['assembly', "at.pointhi.irbuilder.test.InlineAssemblyGeneratorSuite", os.path.join(mx_testsuites._cacheDir, 'inlineassemblytests'), []], } irBuilderTestsGen38 = { 'binary_vector' : ["at.pointhi.irbuilder.testgenerator.BinaryVectorOperatorTest", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'vector')], 'binary_i1' : ["at.pointhi.irbuilder.testgenerator.BinaryI1Operations", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'binaryI1')], 'binary_i1_assembly' : ["at.pointhi.irbuilder.testgenerator.BinaryI1AssemblyOperations", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'binaryI1Assembly')], 'binary_i1_vector' : ["at.pointhi.irbuilder.testgenerator.BinaryI1VectorOperations", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'binaryI1Vector')], 'cast_integer' : ["at.pointhi.irbuilder.testgenerator.VarICasts", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'VarICasts')], 'cast_integer_assembly' : ["at.pointhi.irbuilder.testgenerator.IntegerAssemblyCasts", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'IAssemblyCasts')], 'cast_vector' : ["at.pointhi.irbuilder.testgenerator.VectorBitcastTest", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'castVector')], 'fibonacci' : ["at.pointhi.irbuilder.testgenerator.FibonacciFunctionCallTest", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'fibonacci')], 'float_compare' : ["at.pointhi.irbuilder.testgenerator.FloatCompareOperators", os.path.join(mx_testsuites._cacheDir, 'irbuilder', 'FloatCompareOperator')], } def runIRBuilderTest32(vmArgs): """test ir-writer with llvm 3.2 bitcode files (see -h or --help)""" vmArgs, otherArgs = mx_sulong.truffle_extract_VM_args(vmArgs) parser = argparse.ArgumentParser(description="Compiles all or selected test suites.") parser.add_argument('suite', nargs='*', help=' '.join(irBuilderTests32.keys()), default=irBuilderTests32.keys()) parser.add_argument('--skip-compilation', help='skip suite compilation', action='store_true') # TODO: makefile parsedArgs = parser.parse_args(otherArgs) # test if we have the required tools installed LlvmAS_32.find_tool() LlvmLLI_32.find_tool() returnCode = 0 for testSuiteName in parsedArgs.suite: suite = irBuilderTests32[testSuiteName] """runs the test suite""" if parsedArgs.skip_compilation is False: mx_sulong.mx_testsuites.compileSuite([suite[0]]) try: mx_sulong.mx_testsuites.run(vmArgs + suite[3] + ['-Dpolyglot.irwriter.LLVMVersion=3.2'], suite[1], []) except KeyboardInterrupt: sys.exit(-1) except: mx.log_error("unexpected exception thrown, continue...") testSuite = IRGeneratorSuite(LlvmAS_32, LlvmLLI_32) testSuite.run(suite[2]) if not testSuite.wasSuccessfull(): returnCode = 1 return returnCode def runIRBuilderTest38(vmArgs): """test ir-writer with llvm 3.8 bitcode files (see -h or --help)""" vmArgs, otherArgs = mx_sulong.truffle_extract_VM_args(vmArgs) parser = argparse.ArgumentParser(description="Compiles all or selected test suites.") parser.add_argument('suite', nargs='*', help=' '.join(irBuilderTests38.keys()), default=irBuilderTests38.keys()) parser.add_argument('--skip-compilation', help='skip suite compilation', action='store_true') # TODO: makefile parsedArgs = parser.parse_args(otherArgs) # test if we have the required tools installed LlvmAS_38.find_tool() LlvmLLI_38.find_tool() returnCode = 0 for testSuiteName in parsedArgs.suite: suite = irBuilderTests38[testSuiteName] """runs the test suite""" if parsedArgs.skip_compilation is False: mx_sulong.mx_testsuites.compileSuite([suite[0]]) try: mx_sulong.mx_testsuites.run(vmArgs + suite[3] + ['-Dpolyglot.irwriter.LLVMVersion=3.8'], suite[1], []) except KeyboardInterrupt: sys.exit(-1) except: mx.log_error("unexpected exception thrown, continue...") testSuite = IRGeneratorSuite(LlvmAS_38, LlvmLLI_38) testSuite.run(suite[2]) if not testSuite.wasSuccessfull(): returnCode = 1 return returnCode def runIRBuilderTestGen38(vmArgs): """create llvm-ir testcases which are then run against llvm as well as Sulong (see -h or --help)""" vmArgs, otherArgs = mx_sulong.truffle_extract_VM_args(vmArgs) parser = argparse.ArgumentParser(description="Compiles all or selected test suites.") parser.add_argument('suite', nargs='*', help=' '.join(irBuilderTestsGen38.keys()), default=irBuilderTestsGen38.keys()) parsedArgs = parser.parse_args(otherArgs) returnCode = 0 for testSuiteName in parsedArgs.suite: suite = irBuilderTestsGen38[testSuiteName] """runs the test suite""" # remove old files inside build directory if os.path.isdir(suite[1]): for _file in os.listdir(suite[1]): if _file.endswith(".ll") or _file.endswith(".bc"): os.remove(os.path.join(suite[1], _file)) try: mx_sulong.mx_testsuites.run(vmArgs + ['-Dirwriter.LLVMVersion=3.8'], suite[0], []) except KeyboardInterrupt: sys.exit(-1) except: mx.log_error("unexpected exception thrown, continue...") testSuite = IRGeneratorBuilderSuite(LlvmAS_38, LlvmLLI_38) testSuite.run(suite[1]) if not testSuite.wasSuccessfull(): returnCode = 1 return returnCode class CompareFileResult(object): PASSED = 0 FAILED = 1 FAILED_REFERENCE = 2 def testFiles(assembler, lli, lliReference, lliFiles, sulongFiles, expectedExitVal=None): # test Files which need to be run with lli for srcFile in lliReference: # run file using lli exitVal = lli.run(srcFile) # test for errrors if expectedExitVal is None: if exitVal == -6 or exitVal == -11: # there was either a segfault or a abort return CompareFileResult.FAILED_REFERENCE expectedExitVal = exitVal elif expectedExitVal is not None and exitVal != expectedExitVal: return CompareFileResult.FAILED_REFERENCE for srcFile in lliFiles: # run file using lli exitVal = lli.run(srcFile) # test for errrors if expectedExitVal is None: expectedExitVal = exitVal elif expectedExitVal is not None and exitVal != expectedExitVal: return CompareFileResult.FAILED # test Files which need to be run with sulong for srcFile in sulongFiles: # assemble file if required if srcFile.endswith('.ll'): if assembler.run(srcFile) == 0: srcFile = srcFile[:-3] + ".bc" else: return CompareFileResult.FAILED # run file using sulong exitVal = mx_sulong.runLLVM([srcFile]) # test for errrors if expectedExitVal is None: expectedExitVal = exitVal elif expectedExitVal is not None and exitVal != expectedExitVal: return CompareFileResult.FAILED return CompareFileResult.PASSED class IRTestSuite(object): def __init__(self, assembler, lli): self.assembler = assembler self.lli = lli self.passed = [] self.failed = [] self.failed_references = [] def run(self, cacheDir): mx.log('Testing Reassembly') mx.log(cacheDir) for root, _, files in os.walk(cacheDir): for fileName in files: inputFile = os.path.join(cacheDir, root, fileName) if self.isTestFile(inputFile): try: ret = self.invoke(inputFile) except SystemExit: sys.stdout.write('E') sys.stdout.flush() self.failed.append(inputFile) else: self.handleInvokeResult(inputFile, ret) self.printStats() def isTestFile(self, inputFile): raise NotImplementedError("this method requires to be overloaded by the child class") def invoke(self, inputFile): raise NotImplementedError("his method requires to be overloaded by the child class") def handleInvokeResult(self, inputFile, ret): if ret is CompareFileResult.PASSED: sys.stdout.write('.') sys.stdout.flush() self.passed.append(inputFile) elif ret is CompareFileResult.FAILED: sys.stdout.write('E') sys.stdout.flush() self.failed.append(inputFile) elif ret is CompareFileResult.FAILED_REFERENCE: sys.stdout.write('W') sys.stdout.flush() self.failed_references.append(inputFile) def printStats(self): passed_len = len(self.passed) failed_len = len(self.failed) failed_references_len = len(self.failed_references) total_len = failed_len + passed_len mx.log() if len(self.failed_references): mx.log_error('{0} compiled reference Tests failed!'.format(failed_references_len)) for x in range(0, failed_references_len): mx.log_error(str(x) + ') ' + self.failed_references[x]) mx.log() if failed_len != 0: mx.log_error('Failed {0} of {1} Tests!'.format(failed_len, total_len)) for x in range(0, len(self.failed)): mx.log_error('{0}) {1}'.format(x, self.failed[x])) elif total_len == 0: mx.log_error('There is something odd with the testsuite, {0} Tests executed!'.format(total_len)) else: mx.log('Passed all {0} Tests!'.format(total_len)) def wasSuccessfull(self): if len(self.failed) != 0: return False elif len(self.passed) == 0: return False else: return True class IRGeneratorSuite(IRTestSuite): def __init__(self, assembler, lli): IRTestSuite.__init__(self, assembler, lli) def isTestFile(self, inputFile): return inputFile.endswith('.out.ll') def invoke(self, inputFile): ref_file = inputFile[:-7] + ".bc" return testFiles(self.assembler, self.lli, [ref_file], [inputFile], []) class IRGeneratorBuilderSuite(IRTestSuite): def __init__(self, assembler, lli): IRTestSuite.__init__(self, assembler, lli) def isTestFile(self, inputFile): return inputFile.endswith('.ll') def invoke(self, inputFile): return testFiles(self.assembler, self.lli, [inputFile], [], [inputFile], 0) mx.update_commands(_suite, { 'irbuilder-out' : [runIRBuilderOut, ''], 'irbuilder-test32' : [runIRBuilderTest32, ''], 'irbuilder-test38' : [runIRBuilderTest38, ''], 'irbuilder-testgen38' : [runIRBuilderTestGen38, ''], })
# Natural Language Toolkit - Feature Select # The command line entry point for feature selection # # Author: Sumukh Ghodke <sumukh dot ghodke at gmail dot com> # # URL: <http://nltk.sf.net> # This software is distributed under GPL, for license information see LICENSE.TXT from nltk_contrib.classifier import split_ignore_space from nltk_contrib.classifier import format, cfile, commandline as cl, attribute as attr, classify as cy from nltk_contrib.classifier.exceptions import invaliddataerror as inv import copy import sys a_help = "Selects the feature selection algorithm " \ + "Options: RNK for Ranking(Filter method of Feature " \ + " Selection) " \ + " FS for Forward Selection(Wrapper) " \ + " BE for Backward Eliminiation(Wrapper) " \ + "Default: RNK. " f_help = "Base name of attribute, klass, training, test and gold " \ + " files. " t_help = "Base name of training file for feature selection. " T_help = "Base name of test file for feature selection. " g_help = "Base name of gold file for feature selection. " o_help = "Algorithm specific options " \ + " " \ + "For RNK based feature selection the options should " \ + "include the method to calculate the rank: " \ + " IG: for Information gain " \ + " GR: for Gain ratio " \ + "followed by a number which indicates the number of " \ + "attributes which should be chosen. " \ + " " \ + "For FS and BE based feature selection the options should" \ + "compulsorily include the induction algorithm as the first" \ + "parameter. The second and third parameters are the fold " \ + "and delta respectively. The default value of fold is 10." \ + "The default value of delta is 0. " R_help = "Ranking algorithm. " INFORMATION_GAIN = 'IG' GAIN_RATIO = 'GR' OPTION_MAPPINGS = {INFORMATION_GAIN: 'information_gain', GAIN_RATIO: 'gain_ratio'} RANK='RNK' FORWARD_SELECTION='FS' BACKWARD_ELIMINATION='BE' ALGORITHM_MAPPINGS = {RANK:'by_rank', FORWARD_SELECTION:'forward_selection', BACKWARD_ELIMINATION:'backward_elimination'} DEFAULT_FOLD=10 MIN_FOLD=2 class FeatureSelect(cl.CommandLineInterface): def __init__(self): cl.CommandLineInterface.__init__(self, ALGORITHM_MAPPINGS.keys(), RANK, a_help, f_help, t_help, T_help, g_help, o_help) def execute(self): cl.CommandLineInterface.execute(self) self.validate_basic_arguments_are_present() self.validate_files_arg_is_exclusive() if self.options is None: self.required_arguments_not_present_error() self.split_options = split_ignore_space(self.options) if OPTIONS_TEST[self.algorithm](self.split_options): self.error("Invalid options for Feature selection.") self.select_features_and_write_to_file() def select_features_and_write_to_file(self): ignore_missing = False #duplicate code and not tested!! if self.files is not None: self.training_path, self.test_path, self.gold_path = [self.files] * 3 ignore_missing = True training, attributes, klass, test, gold = self.get_instances(self.training_path, self.test_path, self.gold_path, ignore_missing) self.log_common_params('FeatureSelection') feature_sel = FeatureSelection(training, attributes, klass, test, gold, self.split_options) getattr(feature_sel, ALGORITHM_MAPPINGS[self.algorithm])() files_written = self.write_to_file(self.get_suffix(), training, attributes, klass, test, gold, False) self.log_created_files(files_written, 'The following files were created after feature selection...') def get_suffix(self): if self.options is None: return '-' + self.algorithm suf = '-f_' + self.algorithm for option in self.split_options: suf += '_' + option.replace('.','-') return suf class FeatureSelection: def __init__(self, training, attributes, klass, test, gold, options): self.training, self.attributes, self.klass, self.test, self.gold = training, attributes, klass, test, gold self.options = options def by_rank(self): if self.attributes.has_continuous(): raise inv.InvalidDataError("Rank based feature selection cannot be performed on continuous attributes.") if rank_options_invalid(self.options): raise inv.InvalidDataError("Invalid options for Rank based Feature selection.")#Additional validation when not used from command prompt rem_attributes = self.find_attributes_by_ranking(OPTION_MAPPINGS[self.options[0]], int(self.options[1])) self.remove(rem_attributes) def find_attributes_by_ranking(self, method, number): decision_stumps = self.attributes.empty_decision_stumps([], self.klass) for decision_stump in decision_stumps: for instance in self.training: decision_stump.update_count(instance) decision_stumps.sort(lambda x, y: cmp(getattr(x, method)(), getattr(y, method)())) if number > len(decision_stumps): number = len(decision_stumps) to_remove = decision_stumps[:number * -1] return [stump.attribute for stump in to_remove] def forward_selection(self): if wrapper_options_invalid(self.options): raise inv.InvalidDataError("Invalid options for Forward Select Feature selection.")#Additional validation when not used from command prompt selected = self.__select_attributes(-1, [], self.attributes[:], self.get_delta()) self.remove(self.invert_attribute_selection(selected)) def backward_elimination(self): if wrapper_options_invalid(self.options): raise inv.InvalidDataError("Invalid options for Backward Select Feature selection.") fold = self.get_fold() avg_acc = self.avg_accuracy_by_cross_validation(self.training.cross_validation_datasets(fold), fold, self.attributes) selected = self.__eliminate_attributes(avg_acc, self.attributes[:], self.get_delta()) self.remove(self.invert_attribute_selection(selected)) def __eliminate_attributes(self, max, selected, delta): if selected is None or len(selected) == 0 or len(selected) == 1: return selected max_at_level, selections_with_max_acc, fold = -1, None, self.get_fold() datasets = self.training.cross_validation_datasets(fold) selected_for_iter = selected[:] for attribute in selected_for_iter: selected.remove(attribute) avg_accuracy = self.avg_accuracy_by_cross_validation(datasets, fold, attr.Attributes(selected)) if avg_accuracy > max_at_level: max_at_level = avg_accuracy selections_with_max_acc = selected[:] selected.append(attribute) if max_at_level - max < delta: return selected return self.__eliminate_attributes(max_at_level, selections_with_max_acc, delta) def get_delta(self): if len(self.options) != 3: return 0 return float(self.options[2]) def invert_attribute_selection(self, selected): not_selected = [] for attribute in self.attributes: if not selected.__contains__(attribute): not_selected.append(attribute) return not_selected def __select_attributes(self, max, selected, others, delta): if others is None or len(others) == 0: return selected max_at_level, attr_with_max_acc, fold = -1, None, self.get_fold() datasets = self.training.cross_validation_datasets(fold) for attribute in others: selected.append(attribute) avg_accuracy = self.avg_accuracy_by_cross_validation(datasets, fold, attr.Attributes(selected)) if avg_accuracy > max_at_level: max_at_level = avg_accuracy attr_with_max_acc = attribute selected.remove(attribute) if max_at_level - max < delta: return selected selected.append(attr_with_max_acc) others.remove(attr_with_max_acc) return self.__select_attributes(max_at_level, selected, others, delta) def get_fold(self): if len(self.options) == 1: specified_fold = DEFAULT_FOLD else: specified_fold = int(self.options[1]) if specified_fold >= len(self.training): specified_fold = len(self.training) / 2 return specified_fold def avg_accuracy_by_cross_validation(self, datasets, fold, attributes): total_accuracy = 0 for index in range(fold): training, gold = datasets[index] classifier = cy.ALGORITHM_MAPPINGS[self.options[0]](training, attributes, self.klass) classifier.do_not_validate = True classifier.train() cm = classifier.verify(gold) total_accuracy += cm.accuracy() return total_accuracy / len(datasets) def remove(self, attributes): self.training.remove_attributes(attributes) if self.test is not None: self.test.remove_attributes(attributes) if self.gold is not None: self.gold.remove_attributes(attributes) self.attributes.remove_attributes(attributes) def rank_options_invalid(options): return len(options) != 2 or not options[0] in OPTION_MAPPINGS or not options[1].isdigit() def wrapper_options_invalid(options): return (len(options) < 1 or len(options) > 3) \ or \ (not options[0] in cy.ALGORITHM_MAPPINGS \ or \ ( (len(options) == 2 or len(options) == 3) \ and \ (not options[1].isdigit() or int(options[1]) < MIN_FOLD) ) or \ len(options) == 3 and not isfloat(options[2]) ) OPTIONS_TEST = {RANK : rank_options_invalid, FORWARD_SELECTION : wrapper_options_invalid, BACKWARD_ELIMINATION : wrapper_options_invalid} def isfloat(stringval): try: float(stringval) return True except (ValueError, TypeError), e: return False def batch_filter_select(base_path, suffixes, number_of_attributes, log_path, has_continuous): filter_suffixes = [] for each in suffixes: for selection_criteria in [INFORMATION_GAIN, GAIN_RATIO]: feat_sel = FeatureSelect() params = ['-a', RANK, '-f', base_path + each, '-o', selection_criteria + ',' + str(number_of_attributes), '-l', log_path] print "Params " + str(params) feat_sel.run(params) filter_suffixes.append(each + feat_sel.get_suffix()) return filter_suffixes def batch_wrapper_select(base_path, suffixes, classifier, fold, delta, log_path): wrapper_suffixes = [] for each in suffixes: for alg in [FORWARD_SELECTION, BACKWARD_ELIMINATION]: feat_sel = FeatureSelect() params = ['-a', alg, '-f', base_path + each, '-o', classifier + ',' + str(fold) + ',' + str(delta), '-l', log_path] print "Params " + str(params) feat_sel.run(params) wrapper_suffixes.append(each + feat_sel.get_suffix()) return wrapper_suffixes if __name__ == "__main__": FeatureSelect().run(sys.argv[1:])
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for message_parser.""" import difflib import json import unittest import test_util from endpoints import message_parser from endpoints import message_types from endpoints import messages package = 'TestPackage' class ModuleInterfaceTest(test_util.ModuleInterfaceTest, unittest.TestCase): MODULE = message_parser def _assertSchemaEqual(expected, actual, testcase): """Utility method to dump diffs if the schema aren't equal. Args: expected: object, the expected results. actual: object, the actual results. testcase: unittest.TestCase, the test case this assertion is used within. """ if expected != actual: expected_text = json.dumps(expected, indent=2, sort_keys=True) actual_text = json.dumps(actual, indent=2, sort_keys=True) diff = difflib.unified_diff(expected_text.splitlines(True), actual_text.splitlines(True), fromfile='expected.schema', tofile='actual.schema') diff_text = ''.join(list(diff)) testcase.fail('Schema differs from expected:\n%s' % diff_text) class SelfReference(messages.Message): """This must be at top level to be found by MessageField.""" self = messages.MessageField('SelfReference', 1) class MessageTypeToJsonSchemaTest(unittest.TestCase): def testSelfReferenceMessageField(self): """MessageFields should be recursively parsed.""" parser = message_parser.MessageTypeToJsonSchema() parser.add_message(SelfReference) schemas = parser.schemas() self.assertEquals(1, len(schemas)) self.assertTrue(package + 'SelfReference' in schemas) def testRecursiveDescent(self): """MessageFields should be recursively parsed.""" class C(messages.Message): text = messages.StringField(1, required=True) class B(messages.Message): c = messages.MessageField(C, 1) class A(messages.Message): b = messages.MessageField(B, 1, repeated=True) parser = message_parser.MessageTypeToJsonSchema() parser.add_message(A) schemas = parser.schemas() self.assertEquals(3, len(schemas)) self.assertTrue(package + 'A' in schemas) self.assertTrue(package + 'B' in schemas) self.assertTrue(package + 'C' in schemas) def testRepeatedAndRequired(self): """Repeated and required fields should show up as such in the schema.""" class AllFields(messages.Message): """Documentation for AllFields.""" string = messages.StringField(1) string_required = messages.StringField(2, required=True) string_default_required = messages.StringField(3, required=True, default='Foo') string_repeated = messages.StringField(4, repeated=True) class SimpleEnum(messages.Enum): """Simple enumeration type.""" VAL1 = 1 VAL2 = 2 enum_value = messages.EnumField(SimpleEnum, 5, default=SimpleEnum.VAL2) parser = message_parser.MessageTypeToJsonSchema() parser.add_message(AllFields) schemas = parser.schemas() expected = { package + 'AllFields': { 'type': 'object', 'id': package + 'AllFields', 'description': 'Documentation for AllFields.', 'properties': { 'string': { 'type': 'string' }, 'string_required': { 'type': 'string', 'required': True }, 'string_default_required': { 'type': 'string', 'required': True, 'default': 'Foo' }, 'string_repeated': { 'items': { 'type': 'string', }, 'type': 'array' }, 'enum_value': { 'default': 'VAL2', 'type': 'string', 'enum': ['VAL1', 'VAL2'] }, } } } _assertSchemaEqual(expected, schemas, self) def testAllFieldTypes(self): """Test all the Field types that ProtoRPC supports.""" class AllTypes(messages.Message): """Contains all field types.""" class SimpleEnum(messages.Enum): """Simple enumeration type.""" VAL1 = 1 VAL2 = 2 bool_value = messages.BooleanField(1, variant=messages.Variant.BOOL) bytes_value = messages.BytesField(2, variant=messages.Variant.BYTES) double_value = messages.FloatField(3, variant=messages.Variant.DOUBLE) enum_value = messages.EnumField(SimpleEnum, 4) float_value = messages.FloatField(5, variant=messages.Variant.FLOAT) int32_value = messages.IntegerField(6, variant=messages.Variant.INT32) int64_value = messages.IntegerField(7, variant=messages.Variant.INT64) string_value = messages.StringField(8, variant=messages.Variant.STRING) uint32_value = messages.IntegerField(9, variant=messages.Variant.UINT32) uint64_value = messages.IntegerField(10, variant=messages.Variant.UINT64) int_value = messages.IntegerField(11) # Default variant is INT64. datetime_value = message_types.DateTimeField(12) repeated_datetime_value = message_types.DateTimeField(13, repeated=True) parser = message_parser.MessageTypeToJsonSchema() parser.add_message(AllTypes) schemas = parser.schemas() expected = { package + 'AllTypes': { 'type': 'object', 'id': package + 'AllTypes', 'description': 'Contains all field types.', 'properties': { 'bool_value': {'type': 'boolean'}, 'bytes_value': {'type': 'string', 'format': 'byte'}, 'double_value': {'type': 'number', 'format': 'double'}, 'enum_value': {'type': 'string', 'enum': ['VAL1', 'VAL2']}, 'float_value': {'type': 'number', 'format': 'float'}, 'int32_value': {'type': 'integer', 'format': 'int32'}, 'int64_value': {'type': 'string', 'format': 'int64'}, 'string_value': {'type': 'string'}, 'uint32_value': {'type': 'integer', 'format': 'uint32'}, 'uint64_value': {'type': 'string', 'format': 'uint64'}, 'int_value': {'type': 'string', 'format': 'int64'}, 'datetime_value': {'type': 'string', 'format': 'date-time'}, 'repeated_datetime_value': {'items': {'type': 'string', 'format': 'date-time'}, 'type': 'array'} } } } _assertSchemaEqual(expected, schemas, self) def testLargeEnum(self): """Test that an enum with lots of values works.""" class MyMessage(messages.Message): """Documentation for MyMessage.""" class LargeEnum(messages.Enum): """Large enumeration type, in a strange order.""" ALL = 1000 AND = 1050 BAR = 4 BIND = 3141 DARKNESS = 2123 FOO = 3 IN = 1200 ONE = 5 RING = 6 RULE = 8 THE = 1500 THEM1 = 9 THEM2 = 10000 TO = 7 VAL1 = 1 VAL2 = 2 enum_value = messages.EnumField(LargeEnum, 1) parser = message_parser.MessageTypeToJsonSchema() parser.add_message(MyMessage) schemas = parser.schemas() expected = { package + 'MyMessage': { 'type': 'object', 'id': package + 'MyMessage', 'description': 'Documentation for MyMessage.', 'properties': { 'enum_value': { 'type': 'string', 'enum': ['VAL1', 'VAL2', 'FOO', 'BAR', 'ONE', 'RING', 'TO', 'RULE', 'THEM1', 'ALL', 'AND', 'IN', 'THE', 'DARKNESS', 'BIND', 'THEM2'] }, } } } _assertSchemaEqual(expected, schemas, self) def testEmptyMessage(self): """Test the empty edge case.""" class NoFields(messages.Message): pass parser = message_parser.MessageTypeToJsonSchema() parser.add_message(NoFields) schemas = parser.schemas() expected = { package + 'NoFields': { 'type': 'object', 'id': package + 'NoFields', 'properties': { } } } _assertSchemaEqual(expected, schemas, self) def testRefForMessage(self): class NoFields(messages.Message): pass parser = message_parser.MessageTypeToJsonSchema() self.assertRaises(KeyError, parser.ref_for_message_type, NoFields) parser.add_message(NoFields) self.assertEqual(package + 'NoFields', parser.ref_for_message_type(NoFields)) def testMessageFieldDocsAndArrayRef(self): """Descriptions for MessageFields and a reference in an array.""" class B(messages.Message): """A description of B.""" pass class A(messages.Message): b = messages.MessageField(B, 1, repeated=True) parser = message_parser.MessageTypeToJsonSchema() parser.add_message(A) schemas = parser.schemas() expected = { package + 'A': { 'type': 'object', 'id': package + 'A', 'properties': { 'b': { 'type': 'array', 'description': 'A description of B.', 'items': { '$ref': package + 'B' } } } }, package + 'B': { 'type': 'object', 'id': package + 'B', 'description': 'A description of B.', 'properties': {} } } _assertSchemaEqual(expected, schemas, self) def testNormalizeSchemaName(self): class _1_lower_case_name_(messages.Message): pass parser = message_parser.MessageTypeToJsonSchema() # Test _, numbers, and case fixing. self.assertEqual( package + '1LowerCaseName', parser.add_message(_1_lower_case_name_)) def testNormalizeSchemaNameCollision(self): class A(messages.Message): pass class A_(messages.Message): pass parser = message_parser.MessageTypeToJsonSchema() parser.add_message(A) self.assertRaises(KeyError, parser.add_message, A_) if __name__ == '__main__': unittest.main()
"""Test functions for 1D array set operations. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_raises, assert_raises_regex) from numpy.lib.arraysetops import ( ediff1d, intersect1d, setxor1d, union1d, setdiff1d, unique, in1d, isin ) import pytest class TestSetOps(object): def test_intersect1d(self): # unique inputs a = np.array([5, 7, 1, 2]) b = np.array([2, 4, 3, 1, 5]) ec = np.array([1, 2, 5]) c = intersect1d(a, b, assume_unique=True) assert_array_equal(c, ec) # non-unique inputs a = np.array([5, 5, 7, 1, 2]) b = np.array([2, 1, 4, 3, 3, 1, 5]) ed = np.array([1, 2, 5]) c = intersect1d(a, b) assert_array_equal(c, ed) assert_array_equal([], intersect1d([], [])) def test_intersect1d_array_like(self): # See gh-11772 class Test(object): def __array__(self): return np.arange(3) a = Test() res = intersect1d(a, a) assert_array_equal(res, a) res = intersect1d([1, 2, 3], [1, 2, 3]) assert_array_equal(res, [1, 2, 3]) def test_intersect1d_indices(self): # unique inputs a = np.array([1, 2, 3, 4]) b = np.array([2, 1, 4, 6]) c, i1, i2 = intersect1d(a, b, assume_unique=True, return_indices=True) ee = np.array([1, 2, 4]) assert_array_equal(c, ee) assert_array_equal(a[i1], ee) assert_array_equal(b[i2], ee) # non-unique inputs a = np.array([1, 2, 2, 3, 4, 3, 2]) b = np.array([1, 8, 4, 2, 2, 3, 2, 3]) c, i1, i2 = intersect1d(a, b, return_indices=True) ef = np.array([1, 2, 3, 4]) assert_array_equal(c, ef) assert_array_equal(a[i1], ef) assert_array_equal(b[i2], ef) # non1d, unique inputs a = np.array([[2, 4, 5, 6], [7, 8, 1, 15]]) b = np.array([[3, 2, 7, 6], [10, 12, 8, 9]]) c, i1, i2 = intersect1d(a, b, assume_unique=True, return_indices=True) ui1 = np.unravel_index(i1, a.shape) ui2 = np.unravel_index(i2, b.shape) ea = np.array([2, 6, 7, 8]) assert_array_equal(ea, a[ui1]) assert_array_equal(ea, b[ui2]) # non1d, not assumed to be uniqueinputs a = np.array([[2, 4, 5, 6, 6], [4, 7, 8, 7, 2]]) b = np.array([[3, 2, 7, 7], [10, 12, 8, 7]]) c, i1, i2 = intersect1d(a, b, return_indices=True) ui1 = np.unravel_index(i1, a.shape) ui2 = np.unravel_index(i2, b.shape) ea = np.array([2, 7, 8]) assert_array_equal(ea, a[ui1]) assert_array_equal(ea, b[ui2]) def test_setxor1d(self): a = np.array([5, 7, 1, 2]) b = np.array([2, 4, 3, 1, 5]) ec = np.array([3, 4, 7]) c = setxor1d(a, b) assert_array_equal(c, ec) a = np.array([1, 2, 3]) b = np.array([6, 5, 4]) ec = np.array([1, 2, 3, 4, 5, 6]) c = setxor1d(a, b) assert_array_equal(c, ec) a = np.array([1, 8, 2, 3]) b = np.array([6, 5, 4, 8]) ec = np.array([1, 2, 3, 4, 5, 6]) c = setxor1d(a, b) assert_array_equal(c, ec) assert_array_equal([], setxor1d([], [])) def test_ediff1d(self): zero_elem = np.array([]) one_elem = np.array([1]) two_elem = np.array([1, 2]) assert_array_equal([], ediff1d(zero_elem)) assert_array_equal([0], ediff1d(zero_elem, to_begin=0)) assert_array_equal([0], ediff1d(zero_elem, to_end=0)) assert_array_equal([-1, 0], ediff1d(zero_elem, to_begin=-1, to_end=0)) assert_array_equal([], ediff1d(one_elem)) assert_array_equal([1], ediff1d(two_elem)) assert_array_equal([7,1,9], ediff1d(two_elem, to_begin=7, to_end=9)) assert_array_equal([5,6,1,7,8], ediff1d(two_elem, to_begin=[5,6], to_end=[7,8])) assert_array_equal([1,9], ediff1d(two_elem, to_end=9)) assert_array_equal([1,7,8], ediff1d(two_elem, to_end=[7,8])) assert_array_equal([7,1], ediff1d(two_elem, to_begin=7)) assert_array_equal([5,6,1], ediff1d(two_elem, to_begin=[5,6])) @pytest.mark.parametrize("ary, prepend, append", [ # should fail because trying to cast # np.nan standard floating point value # into an integer array: (np.array([1, 2, 3], dtype=np.int64), None, np.nan), # should fail because attempting # to downcast to smaller int type: (np.array([1, 2, 3], dtype=np.int16), np.array([5, 1<<20, 2], dtype=np.int32), None), # should fail because attempting to cast # two special floating point values # to integers (on both sides of ary): (np.array([1., 3., 9.], dtype=np.int8), np.nan, np.nan), ]) def test_ediff1d_forbidden_type_casts(self, ary, prepend, append): # verify resolution of gh-11490 # specifically, raise an appropriate # Exception when attempting to append or # prepend with an incompatible type msg = 'cannot convert' with assert_raises_regex(ValueError, msg): ediff1d(ary=ary, to_end=append, to_begin=prepend) @pytest.mark.parametrize("ary," "prepend," "append," "expected", [ (np.array([1, 2, 3], dtype=np.int16), 0, None, np.array([0, 1, 1], dtype=np.int16)), (np.array([1, 2, 3], dtype=np.int32), 0, 0, np.array([0, 1, 1, 0], dtype=np.int32)), (np.array([1, 2, 3], dtype=np.int64), 3, -9, np.array([3, 1, 1, -9], dtype=np.int64)), ]) def test_ediff1d_scalar_handling(self, ary, prepend, append, expected): # maintain backwards-compatibility # of scalar prepend / append behavior # in ediff1d following fix for gh-11490 actual = np.ediff1d(ary=ary, to_end=append, to_begin=prepend) assert_equal(actual, expected) def test_isin(self): # the tests for in1d cover most of isin's behavior # if in1d is removed, would need to change those tests to test # isin instead. def _isin_slow(a, b): b = np.asarray(b).flatten().tolist() return a in b isin_slow = np.vectorize(_isin_slow, otypes=[bool], excluded={1}) def assert_isin_equal(a, b): x = isin(a, b) y = isin_slow(a, b) assert_array_equal(x, y) #multidimensional arrays in both arguments a = np.arange(24).reshape([2, 3, 4]) b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]]) assert_isin_equal(a, b) #array-likes as both arguments c = [(9, 8), (7, 6)] d = (9, 7) assert_isin_equal(c, d) #zero-d array: f = np.array(3) assert_isin_equal(f, b) assert_isin_equal(a, f) assert_isin_equal(f, f) #scalar: assert_isin_equal(5, b) assert_isin_equal(a, 6) assert_isin_equal(5, 6) #empty array-like: x = [] assert_isin_equal(x, b) assert_isin_equal(a, x) assert_isin_equal(x, x) def test_in1d(self): # we use two different sizes for the b array here to test the # two different paths in in1d(). for mult in (1, 10): # One check without np.array to make sure lists are handled correct a = [5, 7, 1, 2] b = [2, 4, 3, 1, 5] * mult ec = np.array([True, False, True, True]) c = in1d(a, b, assume_unique=True) assert_array_equal(c, ec) a[0] = 8 ec = np.array([False, False, True, True]) c = in1d(a, b, assume_unique=True) assert_array_equal(c, ec) a[0], a[3] = 4, 8 ec = np.array([True, False, True, False]) c = in1d(a, b, assume_unique=True) assert_array_equal(c, ec) a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5]) b = [2, 3, 4] * mult ec = [False, True, False, True, True, True, True, True, True, False, True, False, False, False] c = in1d(a, b) assert_array_equal(c, ec) b = b + [5, 5, 4] * mult ec = [True, True, True, True, True, True, True, True, True, True, True, False, True, True] c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5, 7, 1, 2]) b = np.array([2, 4, 3, 1, 5] * mult) ec = np.array([True, False, True, True]) c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5, 7, 1, 1, 2]) b = np.array([2, 4, 3, 3, 1, 5] * mult) ec = np.array([True, False, True, True, True]) c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5, 5]) b = np.array([2, 2] * mult) ec = np.array([False, False]) c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5]) b = np.array([2]) ec = np.array([False]) c = in1d(a, b) assert_array_equal(c, ec) assert_array_equal(in1d([], []), []) def test_in1d_char_array(self): a = np.array(['a', 'b', 'c', 'd', 'e', 'c', 'e', 'b']) b = np.array(['a', 'c']) ec = np.array([True, False, True, False, False, True, False, False]) c = in1d(a, b) assert_array_equal(c, ec) def test_in1d_invert(self): "Test in1d's invert parameter" # We use two different sizes for the b array here to test the # two different paths in in1d(). for mult in (1, 10): a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5]) b = [2, 3, 4] * mult assert_array_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) def test_in1d_ravel(self): # Test that in1d ravels its input arrays. This is not documented # behavior however. The test is to ensure consistentency. a = np.arange(6).reshape(2, 3) b = np.arange(3, 9).reshape(3, 2) long_b = np.arange(3, 63).reshape(30, 2) ec = np.array([False, False, False, True, True, True]) assert_array_equal(in1d(a, b, assume_unique=True), ec) assert_array_equal(in1d(a, b, assume_unique=False), ec) assert_array_equal(in1d(a, long_b, assume_unique=True), ec) assert_array_equal(in1d(a, long_b, assume_unique=False), ec) def test_in1d_first_array_is_object(self): ar1 = [None] ar2 = np.array([1]*10) expected = np.array([False]) result = np.in1d(ar1, ar2) assert_array_equal(result, expected) def test_in1d_second_array_is_object(self): ar1 = 1 ar2 = np.array([None]*10) expected = np.array([False]) result = np.in1d(ar1, ar2) assert_array_equal(result, expected) def test_in1d_both_arrays_are_object(self): ar1 = [None] ar2 = np.array([None]*10) expected = np.array([True]) result = np.in1d(ar1, ar2) assert_array_equal(result, expected) def test_in1d_both_arrays_have_structured_dtype(self): # Test arrays of a structured data type containing an integer field # and a field of dtype `object` allowing for arbitrary Python objects dt = np.dtype([('field1', int), ('field2', object)]) ar1 = np.array([(1, None)], dtype=dt) ar2 = np.array([(1, None)]*10, dtype=dt) expected = np.array([True]) result = np.in1d(ar1, ar2) assert_array_equal(result, expected) def test_union1d(self): a = np.array([5, 4, 7, 1, 2]) b = np.array([2, 4, 3, 3, 2, 1, 5]) ec = np.array([1, 2, 3, 4, 5, 7]) c = union1d(a, b) assert_array_equal(c, ec) # Tests gh-10340, arguments to union1d should be # flattened if they are not already 1D x = np.array([[0, 1, 2], [3, 4, 5]]) y = np.array([0, 1, 2, 3, 4]) ez = np.array([0, 1, 2, 3, 4, 5]) z = union1d(x, y) assert_array_equal(z, ez) assert_array_equal([], union1d([], [])) def test_setdiff1d(self): a = np.array([6, 5, 4, 7, 1, 2, 7, 4]) b = np.array([2, 4, 3, 3, 2, 1, 5]) ec = np.array([6, 7]) c = setdiff1d(a, b) assert_array_equal(c, ec) a = np.arange(21) b = np.arange(19) ec = np.array([19, 20]) c = setdiff1d(a, b) assert_array_equal(c, ec) assert_array_equal([], setdiff1d([], [])) a = np.array((), np.uint32) assert_equal(setdiff1d(a, []).dtype, np.uint32) def test_setdiff1d_unique(self): a = np.array([3, 2, 1]) b = np.array([7, 5, 2]) expected = np.array([3, 1]) actual = setdiff1d(a, b, assume_unique=True) assert_equal(actual, expected) def test_setdiff1d_char_array(self): a = np.array(['a', 'b', 'c']) b = np.array(['a', 'b', 's']) assert_array_equal(setdiff1d(a, b), np.array(['c'])) def test_manyways(self): a = np.array([5, 7, 1, 2, 8]) b = np.array([9, 8, 2, 4, 3, 1, 5]) c1 = setxor1d(a, b) aux1 = intersect1d(a, b) aux2 = union1d(a, b) c2 = setdiff1d(aux2, aux1) assert_array_equal(c1, c2) class TestUnique(object): def test_unique_1d(self): def check_all(a, b, i1, i2, c, dt): base_msg = 'check {0} failed for type {1}' msg = base_msg.format('values', dt) v = unique(a) assert_array_equal(v, b, msg) msg = base_msg.format('return_index', dt) v, j = unique(a, True, False, False) assert_array_equal(v, b, msg) assert_array_equal(j, i1, msg) msg = base_msg.format('return_inverse', dt) v, j = unique(a, False, True, False) assert_array_equal(v, b, msg) assert_array_equal(j, i2, msg) msg = base_msg.format('return_counts', dt) v, j = unique(a, False, False, True) assert_array_equal(v, b, msg) assert_array_equal(j, c, msg) msg = base_msg.format('return_index and return_inverse', dt) v, j1, j2 = unique(a, True, True, False) assert_array_equal(v, b, msg) assert_array_equal(j1, i1, msg) assert_array_equal(j2, i2, msg) msg = base_msg.format('return_index and return_counts', dt) v, j1, j2 = unique(a, True, False, True) assert_array_equal(v, b, msg) assert_array_equal(j1, i1, msg) assert_array_equal(j2, c, msg) msg = base_msg.format('return_inverse and return_counts', dt) v, j1, j2 = unique(a, False, True, True) assert_array_equal(v, b, msg) assert_array_equal(j1, i2, msg) assert_array_equal(j2, c, msg) msg = base_msg.format(('return_index, return_inverse ' 'and return_counts'), dt) v, j1, j2, j3 = unique(a, True, True, True) assert_array_equal(v, b, msg) assert_array_equal(j1, i1, msg) assert_array_equal(j2, i2, msg) assert_array_equal(j3, c, msg) a = [5, 7, 1, 2, 1, 5, 7]*10 b = [1, 2, 5, 7] i1 = [2, 3, 0, 1] i2 = [2, 3, 0, 1, 0, 2, 3]*10 c = np.multiply([2, 1, 2, 2], 10) # test for numeric arrays types = [] types.extend(np.typecodes['AllInteger']) types.extend(np.typecodes['AllFloat']) types.append('datetime64[D]') types.append('timedelta64[D]') for dt in types: aa = np.array(a, dt) bb = np.array(b, dt) check_all(aa, bb, i1, i2, c, dt) # test for object arrays dt = 'O' aa = np.empty(len(a), dt) aa[:] = a bb = np.empty(len(b), dt) bb[:] = b check_all(aa, bb, i1, i2, c, dt) # test for structured arrays dt = [('', 'i'), ('', 'i')] aa = np.array(list(zip(a, a)), dt) bb = np.array(list(zip(b, b)), dt) check_all(aa, bb, i1, i2, c, dt) # test for ticket #2799 aa = [1. + 0.j, 1 - 1.j, 1] assert_array_equal(np.unique(aa), [1. - 1.j, 1. + 0.j]) # test for ticket #4785 a = [(1, 2), (1, 2), (2, 3)] unq = [1, 2, 3] inv = [0, 1, 0, 1, 1, 2] a1 = unique(a) assert_array_equal(a1, unq) a2, a2_inv = unique(a, return_inverse=True) assert_array_equal(a2, unq) assert_array_equal(a2_inv, inv) # test for chararrays with return_inverse (gh-5099) a = np.chararray(5) a[...] = '' a2, a2_inv = np.unique(a, return_inverse=True) assert_array_equal(a2_inv, np.zeros(5)) # test for ticket #9137 a = [] a1_idx = np.unique(a, return_index=True)[1] a2_inv = np.unique(a, return_inverse=True)[1] a3_idx, a3_inv = np.unique(a, return_index=True, return_inverse=True)[1:] assert_equal(a1_idx.dtype, np.intp) assert_equal(a2_inv.dtype, np.intp) assert_equal(a3_idx.dtype, np.intp) assert_equal(a3_inv.dtype, np.intp) def test_unique_axis_errors(self): assert_raises(TypeError, self._run_axis_tests, object) assert_raises(TypeError, self._run_axis_tests, [('a', int), ('b', object)]) assert_raises(np.AxisError, unique, np.arange(10), axis=2) assert_raises(np.AxisError, unique, np.arange(10), axis=-2) def test_unique_axis_list(self): msg = "Unique failed on list of lists" inp = [[0, 1, 0], [0, 1, 0]] inp_arr = np.asarray(inp) assert_array_equal(unique(inp, axis=0), unique(inp_arr, axis=0), msg) assert_array_equal(unique(inp, axis=1), unique(inp_arr, axis=1), msg) def test_unique_axis(self): types = [] types.extend(np.typecodes['AllInteger']) types.extend(np.typecodes['AllFloat']) types.append('datetime64[D]') types.append('timedelta64[D]') types.append([('a', int), ('b', int)]) types.append([('a', int), ('b', float)]) for dtype in types: self._run_axis_tests(dtype) msg = 'Non-bitwise-equal booleans test failed' data = np.arange(10, dtype=np.uint8).reshape(-1, 2).view(bool) result = np.array([[False, True], [True, True]], dtype=bool) assert_array_equal(unique(data, axis=0), result, msg) msg = 'Negative zero equality test failed' data = np.array([[-0.0, 0.0], [0.0, -0.0], [-0.0, 0.0], [0.0, -0.0]]) result = np.array([[-0.0, 0.0]]) assert_array_equal(unique(data, axis=0), result, msg) def test_unique_masked(self): # issue 8664 x = np.array([64, 0, 1, 2, 3, 63, 63, 0, 0, 0, 1, 2, 0, 63, 0], dtype='uint8') y = np.ma.masked_equal(x, 0) v = np.unique(y) v2, i, c = np.unique(y, return_index=True, return_counts=True) msg = 'Unique returned different results when asked for index' assert_array_equal(v.data, v2.data, msg) assert_array_equal(v.mask, v2.mask, msg) def test_unique_sort_order_with_axis(self): # These tests fail if sorting along axis is done by treating subarrays # as unsigned byte strings. See gh-10495. fmt = "sort order incorrect for integer type '%s'" for dt in 'bhilq': a = np.array([[-1],[0]], dt) b = np.unique(a, axis=0) assert_array_equal(a, b, fmt % dt) def _run_axis_tests(self, dtype): data = np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0]]).astype(dtype) msg = 'Unique with 1d array and axis=0 failed' result = np.array([0, 1]) assert_array_equal(unique(data), result.astype(dtype), msg) msg = 'Unique with 2d array and axis=0 failed' result = np.array([[0, 1, 0, 0], [1, 0, 0, 0]]) assert_array_equal(unique(data, axis=0), result.astype(dtype), msg) msg = 'Unique with 2d array and axis=1 failed' result = np.array([[0, 0, 1], [0, 1, 0], [0, 0, 1], [0, 1, 0]]) assert_array_equal(unique(data, axis=1), result.astype(dtype), msg) msg = 'Unique with 3d array and axis=2 failed' data3d = np.dstack([data] * 3) result = data3d[..., :1] assert_array_equal(unique(data3d, axis=2), result, msg) uniq, idx, inv, cnt = unique(data, axis=0, return_index=True, return_inverse=True, return_counts=True) msg = "Unique's return_index=True failed with axis=0" assert_array_equal(data[idx], uniq, msg) msg = "Unique's return_inverse=True failed with axis=0" assert_array_equal(uniq[inv], data) msg = "Unique's return_counts=True failed with axis=0" assert_array_equal(cnt, np.array([2, 2]), msg) uniq, idx, inv, cnt = unique(data, axis=1, return_index=True, return_inverse=True, return_counts=True) msg = "Unique's return_index=True failed with axis=1" assert_array_equal(data[:, idx], uniq) msg = "Unique's return_inverse=True failed with axis=1" assert_array_equal(uniq[:, inv], data) msg = "Unique's return_counts=True failed with axis=1" assert_array_equal(cnt, np.array([2, 1, 1]), msg)
import logging import random import requests import urllib import pyjokes import sys import threading from asq.initiators import * import json logger = logging.getLogger(__name__) class Messenger(object): def __init__(self, slackClients): self.clients = slackClients self.lock = threading.RLock() def sendMessage(self, channelId, msg): self.lock.acquire() # in the case of Group and Private channels, RTM channel payload is a complex dictionary if isinstance(channelId, dict): channelId = channelId['id'] logger.debug('Sending msg: {} to channel: {}'.format(msg, channelId)) channel = self.clients.rtm.server.channels.find(channelId) channel.send_message("{}".format(msg)) self.lock.release() def printIssues(self, channelId, issues): for issue in issues: try: phabIssue = self.clients.findPhabIssue(int(issue)) creator = self.clients.findPhabUsersToSlack([phabIssue.authorPHID]) if creator and len(creator) > 0: creator = "<@" + creator[0] + ">" else: creator = "_unknown_" assignee = self.clients.findPhabUsersToSlack([phabIssue.ownerPHID]) if assignee and len(assignee) > 0: assignee = "<@" + assignee[0] + ">" else: assignee = "_unasigned_" attachment = { "fallback": "T{} - {}".format(issue, phabIssue.title), "title": "T{} - {}".format(issue, phabIssue.title), "title_link": phabIssue.uri, "color": "good", "mrkdwn_in": ["fields"], "fields": [ { "title": "Priority", "value": phabIssue.priority, "short": True }, { "title": "Status", "value": phabIssue.status, "short": True }, { "title": "Assignee", "value": assignee, "short": True }, { "title": "Creator", "value": creator, "short": True } ] } self.clients.web.chat.post_message(channelId, "", attachments=[attachment], as_user='true') except Exception as e: self.clients.logExceptionToSlack(e) def makeTransactionAttachment(self, transaction, phabIssue): transactionType = transaction['transactionType'] if transactionType == 'core:comment' : attachment = { "text": "Comments: {}".format( transaction['comments'] ), "mrkdwn_in": ["text"], "color": "good" } elif transactionType == 'core:columns' : columnUpdates = transaction['newValue'] oldColumnPHID = list(columnUpdates[0].get('fromColumnPHIDs').items())[0][0] newColumnPHID = columnUpdates[0].get('columnPHID') oldColumn = self.clients.findWorkboardColumn(oldColumnPHID).get('name') newColumn = self.clients.findWorkboardColumn(newColumnPHID).get('name') attachment = { "text": "Moved from ~{}~ to _{}_.".format(oldColumn, newColumn), "mrkdwn_in": ["text"], "color": "good" } elif transactionType == 'reassign' : oldValue = transaction['oldValue'] newValue = "<@{}>".format(self.clients.findPhabUsersToSlack( [transaction['newValue']] )[0]) if oldValue != None: oldValue = "<@{}>".format(self.clients.findPhabUsersToSlack( [oldValue] )[0]) attachment = { "text": "*Reassigned* from ~{}~ to _{}_.".format( oldValue, newValue ), "mrkdwn_in": ["text"], "color": "good" } else: attachment = { "text": "*Assigned* to _{}_.".format( newValue ), "mrkdwn_in": ["text"], "color" : "good" } else: oldValue = transaction['oldValue'] newValue = transaction['newValue'] textFormat = "Changed *{}* from ~{}~ to _{}_." if oldValue == None or oldValue == "": textFormat = "Changed *{}*{} to _{}_." if transactionType == 'priority': oldValue = self.clients.getPriorityLabelByValue(oldValue) if oldValue != None else None newValue = self.clients.getPriorityLabelByValue(newValue) attachment = { "text": textFormat.format( transactionType, oldValue, newValue ), "mrkdwn_in": ["text"], "color": "good" } if transaction['comments'] != None: attachment["text"] = attachment["text"] + "\nComments: {}".format( transaction['comments'] ) return attachment def printTaskUpdate(self, channelId, authors, taskPHID, transactionPHIDs): try: phabIssue = self.clients.findPhabIssueByPHID(taskPHID) if phabIssue is None: return None phabProjects = self.clients.findPhabProjectsByPHID(phabIssue.get('projectPHIDs')) if len(phabProjects) > 0: channels = self.clients.findChannelId( phabProjects[0]['name'] ) if len(channels) > 0: channelId = channels[0] if authors and len(authors) > 0: authors = "<@" + authors[0] + ">" else: authors = "_unknown_" transactions = self.clients.findManiphestTransactions( int(phabIssue.get('id')), transactionPHIDs ) if len(transactions) > 1 or (len(transactions) > 0 and transactions[0]["transactionType"] != "core:create"): attachments = query(transactions).select(lambda transaction: self.makeTransactionAttachment(transaction, phabIssue)).where(lambda k: k != None).to_list() pretext = "<{}|T{} - {}> updated by {}".format(phabIssue.get('uri'), phabIssue.get('id'), phabIssue.get('title'), authors) self.clients.web.chat.post_message(channelId, pretext, attachments=attachments, as_user='true') else: auxiliary = phabIssue['auxiliary'] if authors == "_unknown_" and 'std:maniphest:zefiros:isFromSlack' in auxiliary and auxiliary['std:maniphest:zefiros:isFromSlack']: authors = self.clients.findPhabUsersToSlack( json.loads(auxiliary['std:maniphest:zefiros:creators']) ) authors = "<@{}>".format( authors[0] ) pretext = "<{}|T{} - {}> created by {}".format(phabIssue.get('uri'), phabIssue.get('id'), phabIssue.get('title'), authors) self.clients.web.chat.post_message(channelId, pretext, as_user='true') except Exception as e: self.clients.logExceptionToSlack(e) def writeHelpMessage(self, channelId): botUid = self.clients.botUserId() txt = '{}\n{}\n{}\n{}\n{}'.format( "I'm your friendly Zefiros Slack bot written. I'll *_respond_* to the following commands:", "> `hi <@" + botUid + ">` - I'll respond with a randomized greeting mentioning your user. :wave:", "> `<@" + botUid + "> joke` - I'll tell you one of my finest jokes. :laughing:", "> `@$ latex` - I'll convert everyting after @$ to latex'", "> `$latex$` - I'll convert everyting in this string to latex'") self.sendMessage(channelId, txt) def writeGreeting(self, channelId, userId): greetings = ['Hi', 'Hello', 'Nice to meet you', 'Howdy', 'Salutations'] txt = '{}, <@{}>!'.format(random.choice(greetings), userId) self.sendMessage(channelId, txt) def getLatexLink(self, txt): data = { 'formula': txt, 'fsize': '20px', 'fcolor': '000000', 'mode': '0', 'out': '1', 'remhost': 'quicklatex.com', 'preamble': "\\usepackage{amsmath,amsfonts,amsthm,amssymb}", } data = urllib.parse.urlencode(data).replace("%26amp%3B", "%26").replace('+', '%20').replace( '%3D', '=' ) response = requests.post("http://quicklatex.com/latex3.f",data=data) if response.status_code != 200: return imageUrl = response.text.split()[1] response = requests.get(imageUrl, stream=True) if response.status_code != 200: return return imageUrl def writeLatex(self, channelId, txt): imageUrl = getLatexLink(txt) attachment = { "fallback": "Latex image.", "title": "Latex at your command", "image_url": imageUrl, "color": "#7CD197", } self.clients.web.chat.post_message(channelId, "", attachments=[attachment], as_user='true') def writePrompt(self, channelId): botUid = self.clients.botUserId() txt = "I'm sorry, I didn't quite understand... Can I help you? (e.g. `<@" + botUid + "> help`)" self.sendMessage(channelId, txt) def writeJoke(self, channelId): self.sendMessage(channelId, pyjokes.get_joke()) def writeError(self, channelId, err_msg): txt = ":face_with_head_bandage: my maker didn't handle this error very well:\n>```{}```".format(err_msg) self.sendMessage(channelId, txt)
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Gradient checker for any ops, graphs. The gradient checker verifies numerically that an op/graph properly computes the gradients """ import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import indexed_slices from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients from tensorflow.python.ops import math_ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export def _product(t): if isinstance(t, int): return t else: y = 1 for x in t: y *= x return y def _extra_feeds(extra_feed_dict, new_feeds): if not extra_feed_dict: return new_feeds r = {} r.update(extra_feed_dict) r.update(new_feeds) return r def _compute_theoretical_jacobian(x, x_shape, x_data, dy, dy_shape, dx, extra_feed_dict): """Computes the theoretical Jacobian for dy/dx. Computes the theoretical Jacobian using the ops generated by compute_gradient(). Args: x: the tensor "x". x_shape: the dimensions of x as a tuple or an array of ints. x_data: a numpy parray as the input data for x dy: the tensor "dy". dy_shape: the dimensions of dy as a tuple or an array of ints. dx: Tensor or IndexedSlices representing dx extra_feed_dict: dict that allows fixing specified tensor values during the jacobian calculation. Returns: A 2-d numpy array representing the Jacobian for dy/dx. It has "x_size" rows and "dy_size" columns where "x_size" is the number of elements in x and "dy_size" is the number of elements in dy. Raises: ValueError: If `dy` is empty but the gradient is nonzero. """ # Complex vectors are treated as vectors of twice as many reals. if x.dtype.is_complex: x_shape = tuple(x_shape) + (2,) dy_factor = 2 if dy.dtype.is_complex else 1 # To compute the jacobian, we treat x and y as one-dimensional vectors. x_size = _product(x_shape) x_val_size = _product(x_shape[1:]) # This is used for sparse gradients dy_size = _product(dy_shape) * dy_factor # Allocate 2-D Jacobian, with x dimensions smashed into the first # dimension and y dimensions smashed into the second. jacobian = np.zeros((x_size, dy_size), dtype=x.dtype.real_dtype.as_numpy_dtype) # For each of the entry of dy, we set this to be 1 and # everything else to be 0 and compute the backprop -- this will give us one # one column of the Jacobian matrix. dy_data = np.zeros(dy_shape, dtype=dy.dtype.as_numpy_dtype) dy_data_flat = dy_data.ravel().view(dy.dtype.real_dtype.as_numpy_dtype) sess = ops.get_default_session() for col in range(dy_size): dy_data_flat[col] = 1 if isinstance(dx, indexed_slices.IndexedSlices): backprop_indices, backprop_values = sess.run( [dx.indices, dx.values], feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data})) for i, v in zip(backprop_indices, backprop_values): r_begin = i * x_val_size r_end = r_begin + x_val_size jacobian[r_begin:r_end, col] += v.flat else: assert isinstance(dx, ops.Tensor), "dx = " + str(dx) backprop = sess.run( dx, feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data})) jacobian[:, col] = backprop.ravel().view(jacobian.dtype) dy_data_flat[col] = 0 # If the output is empty, run the gradients at least once and make sure # they produce zeros. if not dy_size: backprop = sess.run( dx, feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data})) if backprop.shape != x_data.shape: raise ValueError("Empty gradient has wrong shape: expected %s, got %s" % (x_data.shape, backprop.shape)) if np.any(backprop): raise ValueError("Empty tensor with nonzero gradients") logging.vlog(1, "Theoretical Jacobian =\n%s", jacobian) return jacobian def _compute_numeric_jacobian(x, x_shape, x_data, y, y_shape, delta, extra_feed_dict): """Computes the numeric Jacobian for dy/dx. Computes the numeric Jacobian by slightly perturbing the inputs and measuring the differences on the output. Args: x: the tensor "x". x_shape: the dimensions of x as a tuple or an array of ints. x_data: a numpy array as the input data for x y: the tensor "y". y_shape: the dimensions of y as a tuple or an array of ints. delta: the amount of perturbation we give to the input extra_feed_dict: dict that allows fixing specified tensor values during the jacobian calculation. Returns: A 2-d numpy array representing the Jacobian for dy/dx. It has "x_size" rows and "y_size" columns where "x_size" is the number of elements in x and "y_size" is the number of elements in y. """ # bfloat16 doesn't have enough bits to represent high precision numbers such # as delta. Convert to float32 here. Since numeric_jacobian is expected to # be the groundtruth to compare against, it shouldn't lose any information. if x.dtype == dtypes.bfloat16: x = math_ops.cast(x, dtypes.float32) # TODO(wangpeng): Now that the new x # is an output of the old x, isn't feeding to the new x a mistake? if y.dtype == dtypes.bfloat16: y = math_ops.cast(y, dtypes.float32) if x_data.dtype == dtypes.bfloat16.as_numpy_dtype: x_data = x_data.astype(np.float32) # To compute the jacobian, we treat x and y as one-dimensional vectors x_size = _product(x_shape) * (2 if x.dtype.is_complex else 1) y_size = _product(y_shape) * (2 if y.dtype.is_complex else 1) x_dtype = x.dtype.real_dtype.as_numpy_dtype y_dtype = y.dtype.real_dtype.as_numpy_dtype # Make sure we have the right types x_data = np.asarray(x_data, dtype=x.dtype.as_numpy_dtype) scale = np.asarray(2 * delta, dtype=y_dtype)[()] jacobian = np.zeros((x_size, y_size), dtype=x_dtype) # For each of the entry of x, we slightly perturbs this by adding and # subtracting a delta and then compute difference between the outputs. This # will give us one row of the Jacobian matrix. for row in range(x_size): x_pos = x_data.copy() x_neg = x_data.copy() x_pos.ravel().view(x_dtype)[row] += delta y_pos = y.eval(feed_dict=_extra_feeds(extra_feed_dict, {x: x_pos})) x_neg.ravel().view(x_dtype)[row] -= delta y_neg = y.eval(feed_dict=_extra_feeds(extra_feed_dict, {x: x_neg})) diff = (y_pos - y_neg) / scale jacobian[row, :] = diff.ravel().view(y_dtype) logging.vlog(1, "Numeric Jacobian =\n%s", jacobian) return jacobian def _compute_dx_and_dy(x, y, y_shape): """Returns a node to compute gradient of y wrt x.""" # We make up a dy so that we can compute the gradients. We don't really use # the value of dy -- we will always feed it. We need to add an identity node # so that we can always feed it properly. Otherwise, for the Add operation, # dx is the same as dy and we cannot fetch the tensor that we are feeding. with x.graph.as_default(): dy_orig = constant_op.constant(1.0, shape=y_shape, dtype=y.dtype) dy = array_ops.identity(dy_orig) # We compute the gradients for y wrt. x grads = gradients.gradients(y, x, dy) assert len(grads) == 1 return grads[0], dy_orig def _compute_gradient(x, x_shape, dx, y, y_shape, dy, x_init_value=None, delta=1e-3, extra_feed_dict=None): """Computes the theoretical and numerical jacobian.""" t = dtypes.as_dtype(x.dtype) allowed_types = [dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128] assert t.base_dtype in allowed_types, "Don't support type %s for x" % t.name t2 = dtypes.as_dtype(y.dtype) assert t2.base_dtype in allowed_types, "Don't support type %s for y" % t2.name if x_init_value is not None: i_shape = list(x_init_value.shape) assert(list(x_shape) == i_shape), "x_shape = %s, init_data shape = %s" % ( x_shape, i_shape) x_data = x_init_value else: x_data = np.random.random_sample(x_shape).astype(t.as_numpy_dtype) if t.is_complex: x_data.imag = np.random.random_sample(x_shape) jacob_t = _compute_theoretical_jacobian( x, x_shape, x_data, dy, y_shape, dx, extra_feed_dict=extra_feed_dict) jacob_n = _compute_numeric_jacobian( x, x_shape, x_data, y, y_shape, delta, extra_feed_dict=extra_feed_dict) return jacob_t, jacob_n def _compute_gradient_list(x, x_shape, y, y_shape, x_init_value=None, delta=1e-3, init_targets=None, extra_feed_dict=None): """Compute gradients for a list of x values.""" assert isinstance(x, list) dx, dy = zip(*[_compute_dx_and_dy(xi, y, y_shape) for xi in x]) if init_targets is not None: assert isinstance(init_targets, (list, tuple)) for init in init_targets: init.run() if x_init_value is None: x_init_value = [None] * len(x) # pylint: disable=g-complex-comprehension ret = [_compute_gradient(xi, x_shapei, dxi, y, y_shape, dyi, x_init_valuei, delta, extra_feed_dict=extra_feed_dict) for xi, x_shapei, dxi, dyi, x_init_valuei in zip(x, x_shape, dx, dy, x_init_value)] return ret @tf_export(v1=["test.compute_gradient"]) @deprecation.deprecated( date=None, instructions="Use tf.test.compute_gradient in 2.0, which has better " "support for functions. Note that the two versions have different usage, " "so code change is needed.") def compute_gradient(x, x_shape, y, y_shape, x_init_value=None, delta=1e-3, init_targets=None, extra_feed_dict=None): """Computes and returns the theoretical and numerical Jacobian. If `x` or `y` is complex, the Jacobian will still be real but the corresponding Jacobian dimension(s) will be twice as large. This is required even if both input and output is complex since TensorFlow graphs are not necessarily holomorphic, and may have gradients not expressible as complex numbers. For example, if `x` is complex with shape `[m]` and `y` is complex with shape `[n]`, each Jacobian `J` will have shape `[m * 2, n * 2]` with J[:m, :n] = d(Re y)/d(Re x) J[:m, n:] = d(Im y)/d(Re x) J[m:, :n] = d(Re y)/d(Im x) J[m:, n:] = d(Im y)/d(Im x) Args: x: a tensor or list of tensors x_shape: the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. y: a tensor y_shape: the dimensions of y as a tuple or an array of ints. x_init_value: (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. delta: (optional) the amount of perturbation. init_targets: list of targets to run to initialize model params. extra_feed_dict: dict that allows fixing specified tensor values during the Jacobian calculation. Returns: Two 2-d numpy arrays representing the theoretical and numerical Jacobian for dy/dx. Each has "x_size" rows and "y_size" columns where "x_size" is the number of elements in x and "y_size" is the number of elements in y. If x is a list, returns a list of two numpy arrays. """ # TODO(mrry): remove argument `init_targets` if extra_feed_dict is None: extra_feed_dict = {} if isinstance(x, list): return _compute_gradient_list(x, x_shape, y, y_shape, x_init_value, delta, init_targets, extra_feed_dict=extra_feed_dict) else: if init_targets is not None: assert isinstance(init_targets, (list, tuple)) for init in init_targets: init.run() dx, dy = _compute_dx_and_dy(x, y, y_shape) ret = _compute_gradient(x, x_shape, dx, y, y_shape, dy, x_init_value, delta, extra_feed_dict=extra_feed_dict) return ret def _compute_error(grad): if isinstance(grad, tuple): grad = [grad] error = 0 for j_t, j_n in grad: if j_t.size or j_n.size: # Handle zero size tensors correctly error = np.maximum(error, np.fabs(j_t - j_n).max()) return error @tf_export(v1=["test.compute_gradient_error"]) @deprecation.deprecated( date=None, instructions="Use tf.test.compute_gradient in 2.0, which has better " "support for functions. Note that the two versions have different usage, " "so code change is needed.") def compute_gradient_error(x, x_shape, y, y_shape, x_init_value=None, delta=1e-3, init_targets=None, extra_feed_dict=None): """Computes the gradient error. Computes the maximum error for dy/dx between the computed Jacobian and the numerically estimated Jacobian. This function will modify the tensors passed in as it adds more operations and hence changing the consumers of the operations of the input tensors. This function adds operations to the current session. To compute the error using a particular device, such as a GPU, use the standard methods for setting a device (e.g. using with sess.graph.device() or setting a device function in the session constructor). Args: x: a tensor or list of tensors x_shape: the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. y: a tensor y_shape: the dimensions of y as a tuple or an array of ints. x_init_value: (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. delta: (optional) the amount of perturbation. init_targets: list of targets to run to initialize model params. extra_feed_dict: dict that allows fixing specified tensor values during the Jacobian calculation. Returns: The maximum error in between the two Jacobians. """ grad = compute_gradient(x, x_shape, y, y_shape, x_init_value, delta, init_targets, extra_feed_dict=extra_feed_dict) return _compute_error(grad)
from __future__ import print_function from fontTools.misc.py23 import * """ This implements the WOFF specification dated September 16, 2009. The main object is the WOFFFont. It is a subclass for the FontTools TTFont object, so it has very similar functionality. The WOFFReader and WOFFWriter are also available for use outside of this module. Those objects are much faster than WOFFFont, but they require much more care. """ import zlib import struct from fontTools.misc import sstruct from xml.etree import ElementTree from fontTools.ttLib import TTFont, debugmsg, sortedTagList from fontTools.ttLib import getSearchRange from fontTools.ttLib.sfnt import calcChecksum, SFNTDirectoryEntry, \ sfntDirectoryFormat, sfntDirectorySize, sfntDirectoryEntryFormat, sfntDirectoryEntrySize # ----------- # Main Object # ----------- class WOFFFont(TTFont): """ This object represents a WOFF file. It is a subclass of the FontTools TTFont object, so the same API applies. For information about the arguments in __init__, refer to the TTFont documentation. This object has two special attributes: metadata and privateData. The metadata attribute returns an ElementTree Element object representing the metadata stored in the font. To set new metadata in the font, you must use this object. The privateData attribute returns the private data stored in the font. To set private data, set a string to font.privateData. """ def __init__(self, file=None, flavor=b"\000\001\000\000", checkChecksums=0, verbose=False, recalcBBoxes=True, allowVID=False, ignoreDecompileErrors=False): # can't use the TTFont __init__ because it goes directly to the SFNTReader. # see that method for details about all of this. self.verbose = verbose self.recalcBBoxes = recalcBBoxes self.tables = {} self.reader = None self.last_vid = 0xFFFE self.reverseVIDDict = {} self.VIDDict = {} self.allowVID = allowVID self.ignoreDecompileErrors = ignoreDecompileErrors self.flavor = flavor self.majorVersion = 0 self.minorVersion = 0 self._metadata = None self._tableOrder = None self._tableCache = None if file is not None: if not hasattr(file, "read"): file = open(file, "rb") self.reader = WOFFReader(file, checkChecksums=checkChecksums) self.flavor = self.reader.flavor self.majorVersion = self.reader.majorVersion self.minorVersion = self.reader.minorVersion self._tableOrder = self.reader.keys() else: self._metadata = ElementTree.Element("metadata", version="1.0") self.privateData = None def __getattr__(self, attr): if attr not in ("privateData", "metadata", "lazy"): raise AttributeError(attr) # metadata if attr == "metadata": if self._metadata is not None: return self._metadata if self.reader is not None: text = self.reader.metadata if text: metadata = ElementTree.fromstring(text) else: metadata = ElementTree.Element("metadata", version="1.0") self._metadata = metadata return self._metadata return None # private data elif attr == "privateData": if not hasattr(self, "privateData"): privateData = None if self.reader is not None: privateData = self.reader.privateData self.privateData = privateData return self.privateData elif attr == "lazy": return False # fallback to None return None def keys(self): """ Return a list of all tables in the font. If a table order has been set manually or as the result of opening an existing WOFF file, the set table order will be in the list first. Tables not defined in an existing order will be sorted following the suggested ordering in the OTF/OFF specification. The first table listed in all cases is the GlyphOrder pseudo table. """ tags = set(self.tables.keys()) if self.reader is not None: tags = tags | set(self.reader.keys()) tags = list(tags) if "GlyphOrder" in tags: tags.remove("GlyphOrder") return ["GlyphOrder"] + sortedTagList(tags, self._tableOrder) def setTableOrder(self, order): """ Set the order in which tables should be written into the font. This is required if a DSIG table is in the font. """ self._tableOrder = order def save(self, file, compressionLevel=9, recompressTables=False, reorderTables=True, recalculateHeadChecksum=True): """ Save a WOFF into file a file object specifified by the file argument.. Optionally, file can be a path and a new file will be created at that location. compressionLevel is the compression level to be used with zlib. This must be an int between 1 and 9. The default is 9, the highest compression, but slowest compression time. Set recompressTables to True if you want any already compressed tables to be decompressed and then recompressed using the level specified by compressionLevel. If you want the tables in the WOFF reordered following the suggested optimal table orderings described in the OTF/OFF sepecification, set reorderTables to True. Tables cannot be reordered if a DSIG table is in the font. If you change any of the SFNT data or reorder the tables, the head table checkSumAdjustment must be recalculated. If you are not changing any of the SFNT data, you can set recalculateHeadChecksum to False to prevent the recalculation. This must be set to False if the font contains a DSIG table. """ # if DSIG is to be written, the table order # must be completely specified. otherwise the # DSIG may not be valid after decoding the WOFF. tags = self.keys() if "GlyphOrder" in tags: tags.remove("GlyphOrder") if "DSIG" in tags: if self._tableOrder is None or (set(self._tableOrder) != set(tags)): raise WOFFLibError("A complete table order must be supplied when saving a font with a 'DSIG' table.") elif reorderTables: raise WOFFLibError("Tables can not be reordered when a 'DSIG' table is in the font. Set reorderTables to False.") elif recalculateHeadChecksum: raise WOFFLibError("The 'head' table checkSumAdjustment can not be recalculated when a 'DSIG' table is in the font.") # sort the tags if necessary if reorderTables: tags = sortedTagList(tags) # open a file if necessary closeStream = False if not hasattr(file, "write"): closeStream = True file = open(file, "wb") # write the table data if "GlyphOrder" in tags: tags.remove("GlyphOrder") numTables = len(tags) writer = WOFFWriter(file, numTables, flavor=self.flavor, majorVersion=self.majorVersion, minorVersion=self.minorVersion, compressionLevel=compressionLevel, recalculateHeadChecksum=recalculateHeadChecksum, verbose=self.verbose) for tag in tags: origData = None origLength = None origChecksum = None compLength = None # table is loaded if self.isLoaded(tag): origData = self.getTableData(tag) # table is in reader elif self.reader is not None: if recompressTables: origData = self.getTableData(tag) else: if self.verbose: debugmsg("Reading '%s' table from disk" % tag) origData, origLength, origChecksum, compLength = self.reader.getCompressedTableData(tag) # add to writer writer.setTable(tag, origData, origLength=origLength, origChecksum=origChecksum, compLength=compLength) # write the metadata metadata = None metaOrigLength = None metaLength = None if hasattr(self, "metadata"): declaration = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" tree = ElementTree.ElementTree(self.metadata) f = StringIO() tree.write(f, encoding="utf-8") metadata = f.getvalue() # make sure the metadata starts with the declaration if not metadata.startswith(declaration): metadata = declaration + metadata del f elif self.reader is not None: if recompressTables: metadata = self.reader.metadata else: metadata, metaOrigLength, metaLength = self.reader.getCompressedMetadata() if metadata: writer.setMetadata(metadata, metaOrigLength=metaOrigLength, metaLength=metaLength) # write the private data privData = self.privateData if privData: writer.setPrivateData(privData) # close the writer writer.close() # close the file if closeStream: file.close() def saveXML(self): raise NotImplementedError def importXML(self): raise NotImplementedError # ------ # Reader # ------ woffHeaderFormat = """ > # big endian signature: 4s flavor: 4s length: L numTables: H reserved: H totalSFNTSize: L majorVersion: H minorVersion: H metaOffset: L metaLength: L metaOrigLength: L privOffset: L privLength: L """ woffHeaderSize = sstruct.calcsize(woffHeaderFormat) class WOFFReader(object): def __init__(self, file, checkChecksums=1): self.file = file self.checkChecksums = checkChecksums # unpack the header self.file.seek(0) bytes = self.file.read(woffHeaderSize) if len(bytes) != woffHeaderSize: raise WOFFLibError("Not a properly formatted WOFF file.") sstruct.unpack(woffHeaderFormat, bytes, self) if self.signature != "wOFF": raise WOFFLibError("Not a properly formatted WOFF file.") # unpack the directory self.tables = {} for i in range(self.numTables): entry = WOFFDirectoryEntry() entry.fromFile(self.file) self.tables[entry.tag] = entry def close(self): self.file.close() def __contains__(self, tag): return tag in self.tables has_key = __contains__ def keys(self): """ This returns a list of all tables in the WOFF sorted in ascending order based on the offset of each table. """ sorter = [] for tag, entry in self.tables.items(): sorter.append((entry.offset, tag)) order = [tag for offset, tag in sorted(sorter)] return order def __getitem__(self, tag): entry = self.tables[tag] self.file.seek(entry.offset) data = self.file.read(entry.compLength) # decompress if necessary if entry.compLength < entry.origLength: data = zlib.decompress(data) else: data = data[:entry.origLength] # compare the checksums if self.checkChecksums: checksum = calcTableChecksum(tag, data) if self.checkChecksums > 1: assert checksum == entry.origChecksum, "bad checksum for '%s' table" % tag elif checksum != entry.origChecksum: print("bad checksum for '%s' table" % tag) print() return data def getCompressedTableData(self, tag): entry = self.tables[tag] self.file.seek(entry.offset) data = self.file.read(entry.compLength) return data, entry.origLength, entry.origChecksum, entry.compLength def getCompressedMetadata(self): self.file.seek(self.metaOffset) data = self.file.read(self.metaLength) return data, self.metaOrigLength, self.metaLength def __getattr__(self, attr): if attr not in ("privateData", "metadata"): raise AttributeError(attr) if attr == "privateData": self.file.seek(self.privOffset) return self.file.read(self.privLength) if attr == "metadata": self.file.seek(self.metaOffset) data = self.file.read(self.metaLength) if self.metaLength: data = zlib.decompress(data) assert len(data) == self.metaOrigLength return data def __delitem__(self, tag): del self.tables[tag] # ------ # Writer # ------ class WOFFWriter(object): def __init__(self, file, numTables, flavor="\000\001\000\000", majorVersion=0, minorVersion=0, compressionLevel=9, recalculateHeadChecksum=True, verbose=False): self.signature = "wOFF" self.flavor = flavor self.length = woffHeaderSize + (numTables * woffDirectoryEntrySize) self.totalSFNTSize = sfntDirectorySize + (numTables * sfntDirectoryEntrySize) self.numTables = numTables self.majorVersion = majorVersion self.minorVersion = minorVersion self.metaOffset = 0 self.metaOrigLength = 0 self.metaLength = 0 self.privOffset = 0 self.privLength = 0 self.reserved = 0 self.file = file self.compressionLevel = compressionLevel self.recalculateHeadChecksum = recalculateHeadChecksum self.verbose = verbose # the data is held to facilitate the # head checkSumAdjustment calculation. self.tables = {} self.metadata = None self.privateData = None self.tableDataEnd = 0 self.metadataEnd = 0 def _tableOrder(self): return [entry.tag for index, entry, data in sorted(self.tables.values())] def setTable(self, tag, data, origLength=None, origChecksum=None, compLength=None): # don't compress the head if the checkSumAdjustment needs to be recalculated # the compression will be handled later. if self.recalculateHeadChecksum and tag == "head": # decompress if compLength is not None and compLength < origLength: data = zlib.decompress(data) entry = self._prepTable(tag, data, origLength=len(data), entryOnly=True) # compress else: entry, data = self._prepTable(tag, data=data, origLength=origLength, origChecksum=origChecksum, compLength=compLength) # store self.tables[tag] = (len(self.tables), entry, data) def setMetadata(self, data, metaOrigLength=None, metaLength=None): if not data: return if metaLength is None: if self.verbose: debugmsg("compressing metadata") metaOrigLength = len(data) data = zlib.compress(data, self.compressionLevel) metaLength = len(data) # set the header values self.metaOrigLength = metaOrigLength self.metaLength = metaLength # store self.metadata = data def setPrivateData(self, data): if not data: return privLength = len(data) # set the header value self.privLength = privLength # store self.privateData = data def close(self): if self.numTables != len(self.tables): raise WOFFLibError("wrong number of tables; expected %d, found %d" % (self.numTables, len(self.tables))) # first, handle the checkSumAdjustment if self.recalculateHeadChecksum and "head" in self.tables: self._handleHeadChecksum() # check the table directory conformance for tag, (index, entry, data) in sorted(self.tables.items()): self._checkTableConformance(entry, data) # write the header header = sstruct.pack(woffHeaderFormat, self) self.file.seek(0) self.file.write(header) # update the directory offsets offset = woffHeaderSize + (woffDirectoryEntrySize * self.numTables) order = self._tableOrder() for tag in order: index, entry, data = self.tables[tag] entry.offset = offset offset += calc4BytePaddedLength(entry.compLength) # ensure byte alignment # write the directory self._writeTableDirectory() # write the table data self._writeTableData() # write the metadata self._writeMetadata() # write the private data self._writePrivateData() # write the header self._writeHeader() # go to the beginning of the file self.file.seek(0) # header support def _writeHeader(self): header = sstruct.pack(woffHeaderFormat, self) self.file.seek(0) self.file.write(header) # sfnt support def _prepTable(self, tag, data, origLength=None, origChecksum=None, compLength=None, entryOnly=False): # skip data prep if entryOnly: origLength = origLength origChecksum = calcTableChecksum(tag, data) compLength = 0 # prep the data else: # compress if compLength is None: origData = data origLength = len(origData) origChecksum = calcTableChecksum(tag, data) if self.verbose: debugmsg("compressing '%s' table" % tag) compData = zlib.compress(origData, self.compressionLevel) compLength = len(compData) if origLength <= compLength: data = origData compLength = origLength else: data = compData # make the directory entry entry = WOFFDirectoryEntry() entry.tag = tag entry.offset = 0 entry.origLength = origLength entry.origChecksum = origChecksum entry.compLength = compLength # return if entryOnly: return entry return entry, data def _checkTableConformance(self, entry, data): """ Check the conformance of the table directory entries. These must be checked because the origChecksum, origLength and compLength can be set by an outside caller. """ if self.verbose: debugmsg("checking conformance of '%s' table" % entry.tag) # origLength must be less than or equal to compLength if entry.origLength < entry.compLength: raise WOFFLibError("origLength and compLength are not correct in the '%s' table entry." % entry.tag) # unpack the data as needed if entry.origLength > entry.compLength: origData = zlib.decompress(data) compData = data else: origData = data compData = data # the origLength entry must match the actual length if entry.origLength != len(origData): raise WOFFLibError("origLength is not correct in the '%s' table entry." % entry.tag) # the checksum must be correct if entry.origChecksum != calcTableChecksum(entry.tag, origData): raise WOFFLibError("origChecksum is not correct in the '%s' table entry." % entry.tag) # the compLength must be correct if entry.compLength != len(compData): raise WOFFLibError("compLength is not correct in the '%s' table entry." % entry.tag) def _handleHeadChecksum(self): if self.verbose: debugmsg("updating head checkSumAdjustment") # get the value tables = {} offset = sfntDirectorySize + (sfntDirectoryEntrySize * self.numTables) for (index, entry, data) in sorted(self.tables.values()): tables[entry.tag] = dict(offset=offset, length=entry.origLength, checkSum=entry.origChecksum) offset += calc4BytePaddedLength(entry.origLength) checkSumAdjustment = calcHeadCheckSumAdjustment(self.flavor, tables) # set the value in the head table index, entry, data = self.tables["head"] data = data[:8] + struct.pack(">L", checkSumAdjustment) + data[12:] # compress the data newEntry, data = self._prepTable("head", data) # update the entry data assert entry.origChecksum == newEntry.origChecksum entry.origLength = newEntry.origLength entry.compLength = newEntry.compLength # store self.tables["head"] = (index, entry, data) def _writeTableDirectory(self): if self.verbose: debugmsg("writing table directory") self.file.seek(woffHeaderSize) for tag, (index, entry, data) in sorted(self.tables.items()): entry = sstruct.pack(woffDirectoryEntryFormat, entry) self.file.write(entry) def _writeTableData(self): d = woffHeaderSize + (woffDirectoryEntrySize * self.numTables) offset = woffHeaderSize + (woffDirectoryEntrySize * self.numTables) self.file.seek(offset) for tag in self._tableOrder(): if self.verbose: debugmsg("writing '%s' table" % tag) index, entry, data = self.tables[tag] data += "\0" * (calc4BytePaddedLength(entry.compLength) - entry.compLength ) # ensure byte alignment self.file.write(data) self.length += calc4BytePaddedLength(entry.compLength) # ensure byte alignment self.totalSFNTSize += calc4BytePaddedLength(entry.origLength) # ensure byte alignment # store the end for use by metadata or private data self.tableDataEnd = self.length # metadata support def _writeMetadata(self): if self.metadata is None: return if self.verbose: debugmsg("writing metadata") self.length += self.metaLength self.metaOffset = self.tableDataEnd self.file.seek(self.metaOffset) self.file.write(self.metadata) # store the end for use by private data self.metadataEnd = self.metaOffset + self.metaLength # if private data exists, pad to a four byte boundary if self.privateData is not None: padding = calc4BytePaddedLength(self.metaLength) - self.metaLength self.metadataEnd += padding self.length += padding padding = "\0" * padding if padding: self.file.write(padding) # private data support def _writePrivateData(self): if self.privateData is None: return if self.verbose: debugmsg("writing private data") if self.metadata is not None: self.privOffset = self.metadataEnd else: self.privOffset = self.tableDataEnd self.length += self.privLength self.file.seek(self.privOffset) self.file.write(self.privateData) # --------- # Directory # --------- woffDirectoryEntryFormat = """ > # big endian tag: 4s offset: L compLength: L origLength: L origChecksum: L """ woffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat) class WOFFDirectoryEntry(object): def fromFile(self, file): sstruct.unpack(woffDirectoryEntryFormat, file.read(woffDirectoryEntrySize), self) def fromString(self, str): sstruct.unpack(woffDirectoryEntryFormat, str, self) def toString(self): return sstruct.pack(woffDirectoryEntryFormat, self) def __repr__(self): if hasattr(self, "tag"): return "<WOFFDirectoryEntry '%s' at %x>" % (self.tag, id(self)) else: return "<WOFFDirectoryEntry at %x>" % id(self) # ------- # Helpers # ------- class WOFFLibError(Exception): pass def calc4BytePaddedLength(length): return (length + 3) & ~3 def calcTableChecksum(tag, data): if tag == "head": checksum = calcChecksum(data[:8] + '\0\0\0\0' + data[12:]) else: checksum = calcChecksum(data) checksum = checksum & 0xffffffff return checksum def calcHeadCheckSumAdjustment(flavor, tables): numTables = len(tables) # build the sfnt header searchRange, entrySelector, rangeShift = getSearchRange(numTables) sfntDirectoryData = dict( sfntVersion=flavor, numTables=numTables, searchRange=searchRange, entrySelector=entrySelector, rangeShift=rangeShift ) # build the sfnt directory directory = sstruct.pack(sfntDirectoryFormat, sfntDirectoryData) for tag, entry in sorted(tables.items()): entry = tables[tag] sfntEntry = SFNTDirectoryEntry() sfntEntry.tag = tag sfntEntry.checkSum = entry["checkSum"] sfntEntry.offset = entry["offset"] sfntEntry.length = entry["length"] directory += sfntEntry.toString() # calculate the checkSumAdjustment checkSums = [entry["checkSum"] for entry in tables.values()] checkSums.append(calcChecksum(directory)) checkSumAdjustment = sum(checkSums) checkSumAdjustment = (0xB1B0AFBA - checkSumAdjustment) & 0xffffffff # done return checkSumAdjustment # ---------------- # SFNT Conformance # ---------------- def checkSFNTConformance(file): """ This function checks a SFNT file to see if it meets the conformance recomendations in the WOFF specification. This includes: - searchRange must be correct. - entrySelector must be correct. - rangeShift must be correct. - offset to each table must be after the table directory and before the end of the file. - offset + length of each table must not extend past the end of the file. - the table directory must be in ascending order. - tables must be padded to 4 byte boundaries. - the final table must be padded to a 4 byte boundary. - the gaps between table data blocks must not be more than necessary to pad the table to a 4 byte boundary. - the gap between the end of the final table and the end of the file must not be more than necessary to pad the table to a four byte boundary. - the checksums for each table in the table directory must be correct. - the head checkSumAdjustment must be correct. - the padding bytes must be null. The returned value of this function will be a list. If any errors were found, they will be represented as strings in the list. """ # load the data closeFile = False if not hasattr(file, "read"): file = open(file, "rb") closeFile = True data = file.read() if closeFile: file.close() # storage errors = [] # unpack the header headerData = data[:sfntDirectorySize] header = sstruct.unpack(sfntDirectoryFormat, headerData) # unpack the table directory numTables = header["numTables"] directoryData = data[sfntDirectorySize : sfntDirectorySize + (sfntDirectoryEntrySize * numTables)] tableDirectory = [] for index in range(numTables): entry = sstruct.unpack(sfntDirectoryEntryFormat, directoryData[:sfntDirectoryEntrySize]) tableDirectory.append(entry) directoryData = directoryData[sfntDirectoryEntrySize:] # sanity testing errors += _testOffsetBoundaryValidity(len(data), tableDirectory) errors += _testLengthBoundaryValidity(len(data), tableDirectory) # if one or more errors have already been found, something # is very wrong and this should come to a screeching halt. if errors: return errors # junk at the beginning of the file errors += _testJunkAtTheBeginningOfTheFile(header) # test directory order errors += _testDirectoryOrder(tableDirectory) # load the table data for entry in tableDirectory: offset = entry["offset"] length = entry["length"] entry["data"] = data[offset:offset+length] # test for overlaps errors += _testOverlaps(tableDirectory) # test for padding errors += _testOffsets(tableDirectory) # test the final table padding errors += _testFinalTablePadding(len(data), numTables, tableDirectory[-1]["tag"]) # test for gaps errors += _testGaps(tableDirectory) # test for a gap at the end of the file errors += _testGapAfterFinalTable(len(data), tableDirectory) # test padding value errors += _testPaddingValue(tableDirectory, data) # validate checksums errors += _testCheckSums(tableDirectory) errors += _testHeadCheckSum(header, tableDirectory) # done. return errors def _testOffsetBoundaryValidity(dataLength, tableDirectory): """ >>> test = [ ... dict(tag="test", offset=44) ... ] >>> bool(_testOffsetBoundaryValidity(45, test)) False >>> test = [ ... dict(tag="test", offset=1) ... ] >>> bool(_testOffsetBoundaryValidity(45, test)) True >>> test = [ ... dict(tag="test", offset=46) ... ] >>> bool(_testOffsetBoundaryValidity(45, test)) True """ errors = [] numTables = len(tableDirectory) minOffset = sfntDirectorySize + (sfntDirectoryEntrySize * numTables) for entry in tableDirectory: offset = entry["offset"] tag = entry["tag"] if offset < minOffset: errors.append("The offset to the %s table is not valid." % tag) if offset > dataLength: errors.append("The offset to the %s table is not valid." % tag) return errors def _testLengthBoundaryValidity(dataLength, tableDirectory): """ >>> test = [ ... dict(tag="test", offset=44, length=1) ... ] >>> bool(_testLengthBoundaryValidity(45, test)) False >>> test = [ ... dict(tag="test", offset=44, length=2) ... ] >>> bool(_testLengthBoundaryValidity(45, test)) True """ errors = [] entries = [(entry["offset"], entry) for entry in tableDirectory] for o, entry in sorted(entries): offset = entry["offset"] length = entry["length"] tag = entry["tag"] end = offset + length if end > dataLength: errors.append("The length of the %s table is not valid." % tag) return errors def _testJunkAtTheBeginningOfTheFile(header): """ >>> test = dict(numTables=5, searchRange=64, entrySelector=2, rangeShift=16) >>> bool(_testJunkAtTheBeginningOfTheFile(test)) False >>> test = dict(numTables=5, searchRange=0, entrySelector=2, rangeShift=16) >>> bool(_testJunkAtTheBeginningOfTheFile(test)) True >>> test = dict(numTables=5, searchRange=64, entrySelector=0, rangeShift=16) >>> bool(_testJunkAtTheBeginningOfTheFile(test)) True >>> test = dict(numTables=5, searchRange=64, entrySelector=2, rangeShift=0) >>> bool(_testJunkAtTheBeginningOfTheFile(test)) True """ errors = [] numTables = header["numTables"] searchRange, entrySelector, rangeShift = getSearchRange(numTables) if header["searchRange"] != searchRange: errors.append("The searchRange value is incorrect.") if header["entrySelector"] != entrySelector: errors.append("The entrySelector value is incorrect.") if header["rangeShift"] != rangeShift: errors.append("The rangeShift value is incorrect.") return errors def _testDirectoryOrder(tableDirectory): """ >>> test = [ ... dict(tag="aaaa"), ... dict(tag="bbbb") ... ] >>> bool(_testDirectoryOrder(test)) False >>> test = [ ... dict(tag="bbbb"), ... dict(tag="aaaa") ... ] >>> bool(_testDirectoryOrder(test)) True """ order = [entry["tag"] for entry in tableDirectory] if order != list(sorted(order)): return ["The table directory is not in ascending order."] return [] def _testOverlaps(tableDirectory): """ >>> test = [ ... dict(tag="aaaa", offset=0, length=100), ... dict(tag="bbbb", offset=1000, length=100), ... ] >>> bool(_testOverlaps(test)) False >>> test = [ ... dict(tag="aaaa", offset=0, length=100), ... dict(tag="bbbb", offset=50, length=100), ... ] >>> bool(_testOverlaps(test)) True >>> test = [ ... dict(tag="aaaa", offset=0, length=100), ... dict(tag="bbbb", offset=0, length=100), ... ] >>> bool(_testOverlaps(test)) True >>> test = [ ... dict(tag="aaaa", offset=0, length=100), ... dict(tag="bbbb", offset=0, length=150), ... ] >>> bool(_testOverlaps(test)) True """ # gather the edges edges = {} for entry in tableDirectory: start = entry["offset"] end = start + entry["length"] edges[entry["tag"]] = (start, end) # look for overlaps overlaps = set() for tag, (start, end) in edges.items(): for otherTag, (otherStart, otherEnd) in edges.items(): tag = tag.strip() otherTag = otherTag.strip() if tag == otherTag: continue if start >= otherStart and start < otherEnd: l = sorted((tag, otherTag)) overlaps.add(tuple(l)) if end > otherStart and end <= otherEnd: l = sorted((tag, otherTag)) overlaps.add(tuple(l)) # report errors = [] if overlaps: for t1, t2 in sorted(overlaps): errors.append("The tables %s and %s overlap." % (t1, t2)) return errors def _testOffsets(tableDirectory): """ >>> test = [ ... dict(tag="test", offset=1) ... ] >>> bool(_testOffsets(test)) True >>> test = [ ... dict(tag="test", offset=2) ... ] >>> bool(_testOffsets(test)) True >>> test = [ ... dict(tag="test", offset=3) ... ] >>> bool(_testOffsets(test)) True >>> test = [ ... dict(tag="test", offset=4) ... ] >>> bool(_testOffsets(test)) False """ errors = [] # make the entries sortable entries = [(entry["offset"], entry) for entry in tableDirectory] for o, entry in sorted(entries): offset = entry["offset"] if offset % 4: errors.append("The %s table does not begin on a 4-byte boundary." % entry["tag"].strip()) return errors def _testFinalTablePadding(dataLength, numTables, finalTableTag): """ >>> bool(_testFinalTablePadding( ... sfntDirectorySize + sfntDirectoryEntrySize + 1, ... 1, ... "test" ... )) True >>> bool(_testFinalTablePadding( ... sfntDirectorySize + sfntDirectoryEntrySize + 2, ... 1, ... "test" ... )) True >>> bool(_testFinalTablePadding( ... sfntDirectorySize + sfntDirectoryEntrySize + 3, ... 1, ... "test" ... )) True >>> bool(_testFinalTablePadding( ... sfntDirectorySize + sfntDirectoryEntrySize + 4, ... 1, ... "test" ... )) False """ errors = [] if (dataLength - (sfntDirectorySize + (sfntDirectoryEntrySize * numTables))) % 4: errors.append("The final table (%s) is not properly padded." % finalTableTag) return errors def _testGaps(tableDirectory): """ >>> start = sfntDirectorySize + (sfntDirectoryEntrySize * 2) >>> test = [ ... dict(offset=start, length=4, tag="test1"), ... dict(offset=start+4, length=4, tag="test2"), ... ] >>> bool(_testGaps(test)) False >>> test = [ ... dict(offset=start, length=4, tag="test1"), ... dict(offset=start+5, length=4, tag="test2"), ... ] >>> bool(_testGaps(test)) True >>> test = [ ... dict(offset=start, length=4, tag="test1"), ... dict(offset=start+8, length=4, tag="test2"), ... ] >>> bool(_testGaps(test)) True """ errors = [] sorter = [] for entry in tableDirectory: sorter.append((entry["offset"], entry)) prevTag = None prevEnd = None for offset, entry in sorted(sorter): length = entry["length"] length = calc4BytePaddedLength(length) tag = entry["tag"] if prevEnd is None: prevEnd = offset + length prevTag = tag else: if offset - prevEnd != 0: errors.append("Improper padding between the %s and %s tables." % (prevTag, tag)) prevEnd = offset + length prevTag = tag return errors def _testGapAfterFinalTable(dataLength, tableDirectory): """ >>> start = sfntDirectorySize + (sfntDirectoryEntrySize * 2) >>> test = [ ... dict(offset=start, length=1, tag="test") ... ] >>> bool(_testGapAfterFinalTable(start + 4, test)) False >>> test = [ ... dict(offset=start, length=1, tag="test") ... ] >>> bool(_testGapAfterFinalTable(start + 5, test)) True >>> test = [ ... dict(offset=start, length=1, tag="test") ... ] >>> bool(_testGapAfterFinalTable(start + 8, test)) True """ errors = [] sorter = [] for entry in tableDirectory: sorter.append((entry["offset"], entry)) entry = sorted(sorter)[-1] offset = entry[-1]["offset"] length = entry[-1]["length"] length = calc4BytePaddedLength(length) lastPosition = offset + length if dataLength - lastPosition > 0: errors.append("Improper padding at the end of the file.") return errors def _testCheckSums(tableDirectory): """ >>> data = "0" * 44 >>> checkSum = calcTableChecksum("test", data) >>> test = [ ... dict(data=data, checkSum=checkSum, tag="test") ... ] >>> bool(_testCheckSums(test)) False >>> test = [ ... dict(data=data, checkSum=checkSum+1, tag="test") ... ] >>> bool(_testCheckSums(test)) True """ errors = [] for entry in tableDirectory: tag = entry["tag"] checkSum = entry["checkSum"] data = entry["data"] shouldBe = calcTableChecksum(tag, data) if checkSum != shouldBe: errors.append("Invalid checksum for the %s table." % tag) return errors def _testHeadCheckSum(header, tableDirectory): """ >>> header = dict(sfntVersion="OTTO") >>> tableDirectory = [ ... dict(tag="head", offset=100, length=100, checkSum=123, data="00000000"+struct.pack(">L", 925903070)), ... dict(tag="aaab", offset=200, length=100, checkSum=456), ... dict(tag="aaac", offset=300, length=100, checkSum=789), ... ] >>> bool(_testHeadCheckSum(header, tableDirectory)) """ flavor = header["sfntVersion"] tables = {} for entry in tableDirectory: tables[entry["tag"]] = entry data = tables["head"]["data"][8:12] checkSumAdjustment = struct.unpack(">L", data)[0] shouldBe = calcHeadCheckSumAdjustment(flavor, tables) if checkSumAdjustment != shouldBe: return ["The head checkSumAdjustment value is incorrect."] return [] def _testPaddingValue(tableDirectory, data): """ # before first table >>> testDirectory = [dict(tag="aaaa", offset=28, length=4)] >>> bool(_testPaddingValue(testDirectory, "\x01" * 32)) False >>> testDirectory = [dict(tag="aaaa", offset=32, length=4)] >>> bool(_testPaddingValue(testDirectory, "\x01" * 36)) True # between tables >>> testDirectory = [dict(tag="aaaa", offset=44, length=4), dict(tag="bbbb", offset=48, length=4)] >>> bool(_testPaddingValue(testDirectory, "\x01" * 52)) False >>> testDirectory = [dict(tag="aaaa", offset=44, length=4), dict(tag="bbbb", offset=52, length=4)] >>> bool(_testPaddingValue(testDirectory, "\x01" * 56)) True # after final table >>> testDirectory = [dict(tag="aaaa", offset=28, length=4)] >>> bool(_testPaddingValue(testDirectory, "\x01" * 32)) False >>> testDirectory = [dict(tag="aaaa", offset=28, length=4)] >>> bool(_testPaddingValue(testDirectory, "\x01" * 36)) True """ errors = [] # check between directory and first table # check between all tables entries = [(entry["offset"], entry) for entry in tableDirectory] prev = "table directory" prevEnd = sfntDirectorySize + (sfntDirectoryEntrySize * len(tableDirectory)) for o, entry in sorted(entries): tag = entry["tag"] offset = entry["offset"] length = entry["length"] # slice the bytes between the previous and the current if offset > prevEnd: bytes = data[prevEnd:offset] # replace \0 with nothing bytes = bytes.replace("\0", "") if bytes: errors.append("Bytes between %s and %s are not null." % (prev, tag)) # shift for teh next table prev = tag prevEnd = offset + length # check last table entry = sorted(entries)[-1][1] end = entry["offset"] + entry["length"] bytes = data[end:] bytes = bytes.replace("\0", "") if bytes: errors.append("Bytes after final table (%s) are not null." % entry["tag"]) return errors if __name__ == "__main__": import doctest doctest.testmod(verbose=False)
#!/usr/bin/env python # # trans_tests.py: testing eol conversion and keyword substitution # # Subversion is a tool for revision control. # See http://subversion.apache.org for more information. # # ==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. ###################################################################### # General modules import os, re, logging logger = logging.getLogger() # Our testing module import svntest from svntest import wc # (abbreviation) Skip = svntest.testcase.Skip_deco SkipUnless = svntest.testcase.SkipUnless_deco XFail = svntest.testcase.XFail_deco Issues = svntest.testcase.Issues_deco Issue = svntest.testcase.Issue_deco Wimp = svntest.testcase.Wimp_deco Item = svntest.wc.StateItem ###################################################################### # THINGS TO TEST # # *** Perhaps something like commit_tests.py:make_standard_slew_of_changes # is in order here in this file as well. *** # # status level 1: # enable translation, status # (now throw local text mods into the picture) # # commit level 1: # enable translation, commit # (now throw local text mods into the picture) # # checkout: # checkout stuff with translation enabled # # status level 2: # disable translation, status # change newline conversion to different style, status # (now throw local text mods into the picture) # # commit level 2: # disable translation, commit # change newline conversion to different style, commit # (now throw local text mods into the picture) # (now throw local text mods with tortured line endings into the picture) # # update: # update files from disabled translation to enabled translation # update files from enabled translation to disabled translation # update files with newline conversion style changes # (now throw local text mods into the picture) # (now throw conflicting local property mods into the picture) # #### # Paths that the tests test. author_rev_unexp_path = '' author_rev_exp_path = '' bogus_keywords_path = '' embd_author_rev_unexp_path = '' embd_author_rev_exp_path = '' embd_bogus_keywords_path = '' def check_keywords(actual_kw, expected_kw, name): """A Helper function to compare two keyword lists""" if len(actual_kw) != len(expected_kw): logger.warn("Keyword lists are different by size") raise svntest.Failure for i in range(0,len(actual_kw)): if actual_kw[i] != expected_kw[i]: logger.warn('%s item %s, Expected: %s', name, i, expected_kw[i][:-1]) logger.warn('%s item %s, Got: %s', name, i, actual_kw[i][:-1]) raise svntest.Failure def setup_working_copy(wc_dir, value_len): """Setup a standard test working copy, then create (but do not add) various files for testing translation.""" global author_rev_unexp_path global author_rev_exp_path global url_unexp_path global url_exp_path global id_unexp_path global id_exp_path global header_unexp_path global header_exp_path global bogus_keywords_path global embd_author_rev_unexp_path global embd_author_rev_exp_path global embd_bogus_keywords_path global fixed_length_keywords_path global id_with_space_path global id_exp_with_dollar_path # NOTE: Only using author and revision keywords in tests for now, # since they return predictable substitutions. # Unexpanded, expanded, and bogus keywords; sometimes as the only # content of the files, sometimes embedded in non-keyword content. author_rev_unexp_path = os.path.join(wc_dir, 'author_rev_unexp') author_rev_exp_path = os.path.join(wc_dir, 'author_rev_exp') url_unexp_path = os.path.join(wc_dir, 'url_unexp') url_exp_path = os.path.join(wc_dir, 'url_exp') id_unexp_path = os.path.join(wc_dir, 'id_unexp') id_exp_path = os.path.join(wc_dir, 'id_exp') header_unexp_path = os.path.join(wc_dir, 'header_unexp') header_exp_path = os.path.join(wc_dir, 'header_exp') bogus_keywords_path = os.path.join(wc_dir, 'bogus_keywords') embd_author_rev_unexp_path = os.path.join(wc_dir, 'embd_author_rev_unexp') embd_author_rev_exp_path = os.path.join(wc_dir, 'embd_author_rev_exp') embd_bogus_keywords_path = os.path.join(wc_dir, 'embd_bogus_keywords') fixed_length_keywords_path = os.path.join(wc_dir, 'fixed_length_keywords') id_with_space_path = os.path.join(wc_dir, 'id with space') id_exp_with_dollar_path = os.path.join(wc_dir, 'id_exp with_$_sign') svntest.main.file_append(author_rev_unexp_path, "$Author$\n$Rev$") svntest.main.file_append(author_rev_exp_path, "$Author: blah $\n$Rev: 0 $") svntest.main.file_append(url_unexp_path, "$URL$") svntest.main.file_append(url_exp_path, "$URL: blah $") svntest.main.file_append(id_unexp_path, "$Id$") svntest.main.file_append(id_exp_path, "$Id: blah $") svntest.main.file_append(header_unexp_path, "$Header$") svntest.main.file_append(header_exp_path, "$Header: blah $") svntest.main.file_append(bogus_keywords_path, "$Arthur$\n$Rev0$") svntest.main.file_append(embd_author_rev_unexp_path, "one\nfish\n$Author$ two fish\n red $Rev$\n fish") svntest.main.file_append(embd_author_rev_exp_path, "blue $Author: blah $ fish$Rev: 0 $\nI fish") svntest.main.file_append(embd_bogus_keywords_path, "you fish $Arthur$then\n we$Rev0$ \n\nchew fish") keyword_test_targets = [ # User tries to shoot him or herself on the foot "$URL::$\n", "$URL:: $\n", "$URL:: $\n", # Following are valid entries "$URL:: $\n", "$URL:: %s $\n" % (' ' * (value_len-1)), "$URL:: %s $\n" % (' ' * value_len), # Check we will clean the truncate marker when the value fits exactly "$URL:: %s#$\n" % ('a' * value_len), "$URL:: %s $\n" % (' ' * (value_len+1)), # These are syntactically wrong "$URL::x%s $\n" % (' ' * value_len), "$URL:: %sx$\n" % (' ' * value_len), "$URL::x%sx$\n" % (' ' * value_len) ] for i in keyword_test_targets: svntest.main.file_append(fixed_length_keywords_path, i) svntest.main.file_append(id_with_space_path, "$Id$") svntest.main.file_append(id_exp_with_dollar_path, "$Id: id_exp with_$_sign 1 2006-06-10 11:10:00Z jrandom $") ### Helper functions for setting/removing properties # Set the property keyword for PATH. Turn on all possible keywords. ### todo: Later, take list of keywords to set. def keywords_on(path): svntest.actions.run_and_verify_svn(None, None, [], 'propset', "svn:keywords", "Author Rev Date URL Id Header", path) # Delete property NAME from versioned PATH in the working copy. ### todo: Later, take list of keywords to remove from the propval? def keywords_off(path): svntest.actions.run_and_verify_svn(None, None, [], 'propdel', "svn:keywords", path) ###################################################################### # Tests # # Each test must return on success or raise on failure. #---------------------------------------------------------------------- ### This test is know to fail when Subversion is built in very deep ### directory structures, caused by SVN_KEYWORD_MAX_LEN being defined ### as 255. def keywords_from_birth(sbox): "commit new files with keywords active from birth" sbox.build() wc_dir = sbox.wc_dir canonical_repo_url = svntest.main.canonicalize_url(sbox.repo_url) if canonical_repo_url[-1:] != '/': url_expand_test_data = canonical_repo_url + '/fixed_length_keywords' else: url_expand_test_data = canonical_repo_url + 'fixed_length_keywords' setup_working_copy(wc_dir, len(url_expand_test_data)) # Add all the files expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'author_rev_unexp' : Item(status='A ', wc_rev=0), 'author_rev_exp' : Item(status='A ', wc_rev=0), 'url_unexp' : Item(status='A ', wc_rev=0), 'url_exp' : Item(status='A ', wc_rev=0), 'id_unexp' : Item(status='A ', wc_rev=0), 'id_exp' : Item(status='A ', wc_rev=0), 'header_unexp' : Item(status='A ', wc_rev=0), 'header_exp' : Item(status='A ', wc_rev=0), 'bogus_keywords' : Item(status='A ', wc_rev=0), 'embd_author_rev_unexp' : Item(status='A ', wc_rev=0), 'embd_author_rev_exp' : Item(status='A ', wc_rev=0), 'embd_bogus_keywords' : Item(status='A ', wc_rev=0), 'fixed_length_keywords' : Item(status='A ', wc_rev=0), 'id with space' : Item(status='A ', wc_rev=0), 'id_exp with_$_sign' : Item(status='A ', wc_rev=0), }) svntest.main.run_svn(None, 'add', author_rev_unexp_path) svntest.main.run_svn(None, 'add', author_rev_exp_path) svntest.main.run_svn(None, 'add', url_unexp_path) svntest.main.run_svn(None, 'add', url_exp_path) svntest.main.run_svn(None, 'add', id_unexp_path) svntest.main.run_svn(None, 'add', id_exp_path) svntest.main.run_svn(None, 'add', header_unexp_path) svntest.main.run_svn(None, 'add', header_exp_path) svntest.main.run_svn(None, 'add', bogus_keywords_path) svntest.main.run_svn(None, 'add', embd_author_rev_unexp_path) svntest.main.run_svn(None, 'add', embd_author_rev_exp_path) svntest.main.run_svn(None, 'add', embd_bogus_keywords_path) svntest.main.run_svn(None, 'add', fixed_length_keywords_path) svntest.main.run_svn(None, 'add', id_with_space_path) svntest.main.run_svn(None, 'add', id_exp_with_dollar_path) svntest.actions.run_and_verify_status(wc_dir, expected_status) # Add the keyword properties. keywords_on(author_rev_unexp_path) keywords_on(url_unexp_path) keywords_on(url_exp_path) keywords_on(id_unexp_path) keywords_on(id_exp_path) keywords_on(header_unexp_path) keywords_on(header_exp_path) keywords_on(embd_author_rev_exp_path) keywords_on(fixed_length_keywords_path) keywords_on(id_with_space_path) keywords_on(id_exp_with_dollar_path) # Commit. expected_output = svntest.wc.State(wc_dir, { 'author_rev_unexp' : Item(verb='Adding'), 'author_rev_exp' : Item(verb='Adding'), 'url_unexp' : Item(verb='Adding'), 'url_exp' : Item(verb='Adding'), 'id_unexp' : Item(verb='Adding'), 'id_exp' : Item(verb='Adding'), 'header_unexp' : Item(verb='Adding'), 'header_exp' : Item(verb='Adding'), 'bogus_keywords' : Item(verb='Adding'), 'embd_author_rev_unexp' : Item(verb='Adding'), 'embd_author_rev_exp' : Item(verb='Adding'), 'embd_bogus_keywords' : Item(verb='Adding'), 'fixed_length_keywords' : Item(verb='Adding'), 'id with space' : Item(verb='Adding'), 'id_exp with_$_sign' : Item(verb='Adding'), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, None, None, wc_dir) # Make sure the unexpanded URL keyword got expanded correctly. fp = open(url_unexp_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$URL: (http|https|file|svn|svn\\+ssh)://", lines[0]))): logger.warn("URL expansion failed for %s", url_unexp_path) raise svntest.Failure fp.close() # Make sure the preexpanded URL keyword got reexpanded correctly. fp = open(url_exp_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$URL: (http|https|file|svn|svn\\+ssh)://", lines[0]))): logger.warn("URL expansion failed for %s", url_exp_path) raise svntest.Failure fp.close() # Make sure the unexpanded Id keyword got expanded correctly. fp = open(id_unexp_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$Id: id_unexp", lines[0]))): logger.warn("Id expansion failed for %s", id_exp_path) raise svntest.Failure fp.close() # Make sure the preexpanded Id keyword got reexpanded correctly. fp = open(id_exp_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$Id: id_exp", lines[0]))): logger.warn("Id expansion failed for %s", id_exp_path) raise svntest.Failure fp.close() # Make sure the unexpanded Header keyword got expanded correctly. fp = open(header_unexp_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$Header: (https?|file|svn|svn\\+ssh)://.* jrandom", lines[0]))): logger.warn("Header expansion failed for %s", header_unexp_path) raise svntest.Failure fp.close() # Make sure the preexpanded Header keyword got reexpanded correctly. fp = open(header_exp_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$Header: (https?|file|svn|svn\\+ssh)://.* jrandom", lines[0]))): logger.warn("Header expansion failed for %s", header_exp_path) raise svntest.Failure fp.close() # Check fixed length keywords. kw_workingcopy = [ '$URL::$\n', '$URL:: $\n', '$URL:: $\n', '$URL:: %s#$\n' % url_expand_test_data[0:1], '$URL:: %s#$\n' % url_expand_test_data[:-1], '$URL:: %s $\n' % url_expand_test_data, '$URL:: %s $\n' % url_expand_test_data, '$URL:: %s $\n'% url_expand_test_data, '$URL::x%s $\n' % (' ' * len(url_expand_test_data)), '$URL:: %sx$\n' % (' ' * len(url_expand_test_data)), '$URL::x%sx$\n' % (' ' * len(url_expand_test_data)) ] fp = open(fixed_length_keywords_path, 'r') actual_workingcopy_kw = fp.readlines() fp.close() check_keywords(actual_workingcopy_kw, kw_workingcopy, "working copy") # Check text base for fixed length keywords. kw_textbase = [ '$URL::$\n', '$URL:: $\n', '$URL:: $\n', '$URL:: $\n', '$URL:: %s $\n' % (' ' * len(url_expand_test_data[:-1])), '$URL:: %s $\n' % (' ' * len(url_expand_test_data)), '$URL:: %s $\n' % (' ' * len(url_expand_test_data)), '$URL:: %s $\n'% (' ' * len(url_expand_test_data)), '$URL::x%s $\n' % (' ' * len(url_expand_test_data)), '$URL:: %sx$\n' % (' ' * len(url_expand_test_data)), '$URL::x%sx$\n' % (' ' * len(url_expand_test_data)) ] fp = open(svntest.wc.text_base_path(fixed_length_keywords_path), 'r') actual_textbase_kw = fp.readlines() fp.close() check_keywords(actual_textbase_kw, kw_textbase, "text base") # Check the Id keyword for filename with spaces. fp = open(id_with_space_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$Id: .*id with space", lines[0]))): logger.warn("Id expansion failed for %s", id_with_space_path) raise svntest.Failure fp.close() # Check the Id keyword for filename with_$_signs. fp = open(id_exp_with_dollar_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$Id: .*id_exp with_\$_sign [^$]* jrandom \$", lines[0]))): logger.warn("Id expansion failed for %s", id_exp_with_dollar_path) raise svntest.Failure fp.close() #---------------------------------------------------------------------- #def enable_translation(sbox): # "enable translation, check status, commit" # TODO: Turn on newline conversion and/or keyword substitution for all # sorts of files, with and without local mods, and verify that # status shows the right stuff. The, commit those mods. #---------------------------------------------------------------------- #def checkout_translated(): # "checkout files that have translation enabled" # TODO: Checkout a tree which contains files with translation # enabled. #---------------------------------------------------------------------- #def disable_translation(): # "disable translation, check status, commit" # TODO: Disable translation on files which have had it enabled, # with and without local mods, check status, and commit. #---------------------------------------------------------------------- # Regression test for bug discovered by Vladmir Prus <ghost@cs.msu.csu>. # This is a slight rewrite of his test, to use the run_and_verify_* API. # This is for issue #631. def do_nothing(x, y): return 0 @Issue(631) def update_modified_with_translation(sbox): "update modified file with eol-style 'native'" sbox.build() wc_dir = sbox.wc_dir # Replace contents of rho and set eol translation to 'native' rho_path = os.path.join(wc_dir, 'A', 'D', 'G', 'rho') svntest.main.file_write(rho_path, "1\n2\n3\n4\n5\n6\n7\n8\n9\n") svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:eol-style', 'native', rho_path) # Create expected output and status trees of a commit. expected_output = svntest.wc.State(wc_dir, { 'A/D/G/rho' : Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) # rho has props expected_status.tweak('A/D/G/rho', wc_rev=2, status=' ') # Commit revision 2: it has the new rho. svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, rho_path) # Change rho again svntest.main.file_write(rho_path, "1\n2\n3\n4\n4.5\n5\n6\n7\n8\n9\n") # Commit revision 3 expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/D/G/rho', wc_rev=3, status=' ') svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, rho_path) # Locally modify rho again. svntest.main.file_write(rho_path, "1\n2\n3\n4\n4.5\n5\n6\n7\n8\n9\n10\n") # Prepare trees for an update to rev 1. expected_output = svntest.wc.State(wc_dir, { 'A/D/G/rho' : Item(status='CU'), }) expected_disk = svntest.main.greek_state.copy() expected_disk.tweak('A/D/G/rho', contents="\n".join(["<<<<<<< .mine", "1", "2", "3", "4", "4.5", "5", "6", "7", "8", "9", "10", "=======", "This is the file 'rho'.", ">>>>>>> .r1", ""])) # Updating back to revision 1 should not error; the merge should # work, with eol-translation turned on. svntest.actions.run_and_verify_update(wc_dir, expected_output, expected_disk, None, None, do_nothing, None, None, None, 0, '-r', '1', wc_dir) #---------------------------------------------------------------------- # Regression test for issue #1085, whereby setting the eol-style to a # fixed platform-incorrect value on a file whose line endings are # platform-correct causes repository insanity (the eol-style prop # claims one line ending style, the file is in another). This test # assumes that this can be testing by verifying that a) new file # contents are transmitted to the server during commit, and b) that # after the commit, the file and its text-base have been changed to # have the new line-ending style. @Issue(1085) def eol_change_is_text_mod(sbox): "committing eol-style change forces text send" sbox.build() wc_dir = sbox.wc_dir # add a new file to the working copy. foo_path = os.path.join(wc_dir, 'foo') f = open(foo_path, 'wb') if svntest.main.windows: f.write("1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n") else: f.write("1\n2\n3\n4\n5\n6\n7\n8\n9\n") f.close() # commit the file svntest.actions.run_and_verify_svn(None, None, [], 'add', foo_path) svntest.actions.run_and_verify_svn(None, None, [], 'ci', '-m', 'log msg', foo_path) if svntest.main.windows: svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:eol-style', 'LF', foo_path) else: svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:eol-style', 'CRLF', foo_path) # check 1: did new contents get transmitted? expected_output = ["Sending " + foo_path + "\n", "Transmitting file data .\n", "Committed revision 3.\n"] svntest.actions.run_and_verify_svn(None, expected_output, [], 'ci', '-m', 'log msg', foo_path) # check 2: do the files have the right contents now? contents = open(foo_path, 'rb').read() if svntest.main.windows: if contents != "1\n2\n3\n4\n5\n6\n7\n8\n9\n": raise svntest.Failure else: if contents != "1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n": raise svntest.Failure foo_base_path = svntest.wc.text_base_path(foo_path) base_contents = open(foo_base_path, 'rb').read() if contents != base_contents: raise svntest.Failure #---------------------------------------------------------------------- # Regression test for issue #1151. A single file in a directory # didn't get keywords expanded on checkout. @Issue(1151) def keyword_expanded_on_checkout(sbox): "keyword expansion for lone file in directory" sbox.build() wc_dir = sbox.wc_dir # The bug didn't occur if there were multiple files in the # directory, so setup an empty directory. Z_path = os.path.join(wc_dir, 'Z') svntest.actions.run_and_verify_svn(None, None, [], 'mkdir', Z_path) # Add the file that has the keyword to be expanded url_path = os.path.join(Z_path, 'url') svntest.main.file_append(url_path, "$URL$") svntest.actions.run_and_verify_svn(None, None, [], 'add', url_path) keywords_on(url_path) svntest.actions.run_and_verify_svn(None, None, [], 'ci', '-m', 'log msg', wc_dir) other_wc_dir = sbox.add_wc_path('other') other_url_path = os.path.join(other_wc_dir, 'Z', 'url') svntest.actions.run_and_verify_svn(None, None, [], 'checkout', sbox.repo_url, other_wc_dir) # Check keyword got expanded (and thus the mkdir, add, ps, commit # etc. worked) fp = open(other_url_path, 'r') lines = fp.readlines() if not ((len(lines) == 1) and (re.match("\$URL: (http|https|file|svn|svn\\+ssh)://", lines[0]))): logger.warn("URL expansion failed for %s", other_url_path) raise svntest.Failure fp.close() #---------------------------------------------------------------------- def cat_keyword_expansion(sbox): "keyword expanded on cat" sbox.build() wc_dir = sbox.wc_dir mu_path = os.path.join(wc_dir, 'A', 'mu') lambda_path = os.path.join(wc_dir, 'A', 'B', 'lambda') # Set up A/mu to do $Rev$ keyword expansion svntest.main.file_append(mu_path , "$Rev$\n$Author$") svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:keywords', 'Rev Author', mu_path) expected_output = wc.State(wc_dir, { 'A/mu' : Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/mu', wc_rev=2) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Change the author to value which will get truncated on expansion full_author = "x" * 400 key_author = "x" * 244 svntest.actions.enable_revprop_changes(sbox.repo_dir) svntest.actions.run_and_verify_svn(None, None, [], 'propset', '--revprop', '-r2', 'svn:author', full_author, sbox.wc_dir) svntest.actions.run_and_verify_svn(None, [ full_author ], [], 'propget', '--revprop', '-r2', 'svn:author', '--strict', sbox.wc_dir) # Make another commit so that the last changed revision for A/mu is # not HEAD. svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'foo', 'bar', lambda_path) expected_output = wc.State(wc_dir, { 'A/B/lambda' : Item(verb='Sending'), }) expected_status.tweak('A/B/lambda', wc_rev=3) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # At one stage the keywords were expanded to values for the requested # revision, not to those committed revision svntest.actions.run_and_verify_svn(None, [ "This is the file 'mu'.\n", "$Rev: 2 $\n", "$Author: " + key_author + " $"], [], 'cat', '-r', 'HEAD', mu_path) #---------------------------------------------------------------------- def copy_propset_commit(sbox): "copy, propset svn:eol-style, commit" sbox.build() wc_dir = sbox.wc_dir mu_path = os.path.join(wc_dir, 'A', 'mu') mu2_path = os.path.join(wc_dir, 'A', 'mu2') # Copy and propset svntest.actions.run_and_verify_svn(None, None, [], 'copy', mu_path, mu2_path) svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:eol-style', 'native', mu2_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'A/mu2' : Item(status='A ', wc_rev='-', copied='+') }) svntest.actions.run_and_verify_status(wc_dir, expected_status) # Commit, at one stage this dumped core expected_output = wc.State(wc_dir, { 'A/mu2' : Item(verb='Adding'), }) expected_status.tweak('A/mu2', status=' ', wc_rev=2, copied=None) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) #---------------------------------------------------------------------- # Create a greek tree, commit a keyword into one file, # then commit a keyword property (i.e., turn on keywords), then # try to check out head somewhere else. # This should not cause seg fault def propset_commit_checkout_nocrash(sbox): "propset, commit, check out into another wc" sbox.build() wc_dir = sbox.wc_dir mu_path = os.path.join(wc_dir, 'A', 'mu') # Put a keyword in A/mu, commit svntest.main.file_append(mu_path, "$Rev$") expected_output = wc.State(wc_dir, { 'A/mu' : Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/mu', wc_rev=2) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Set property to do keyword expansion on A/mu, commit. svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:keywords', 'Rev', mu_path) expected_output = wc.State(wc_dir, { 'A/mu' : Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/mu', wc_rev=3) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Check out into another wc dir other_wc_dir = sbox.add_wc_path('other') mu_other_path = os.path.join(other_wc_dir, 'A', 'mu') svntest.actions.run_and_verify_svn(None, None, [], 'checkout', sbox.repo_url, other_wc_dir) mu_other_contents = open(mu_other_path).read() if mu_other_contents != "This is the file 'mu'.\n$Rev: 3 $": logger.warn("'%s' does not have the expected contents", mu_other_path) raise svntest.Failure #---------------------------------------------------------------------- # Add the keyword property to a file, svn revert the file # This should not display any error message def propset_revert_noerror(sbox): "propset, revert" sbox.build() wc_dir = sbox.wc_dir mu_path = os.path.join(wc_dir, 'A', 'mu') # Set the Rev keyword for the mu file # could use the keywords_on()/keywords_off() functions to # set/del all svn:keywords svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:keywords', 'Rev', mu_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/mu', status=' M') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Revert the propset svntest.actions.run_and_verify_svn(None, None, [], 'revert', mu_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) svntest.actions.run_and_verify_status(wc_dir, expected_status) def props_only_file_update(sbox): "retranslation occurs on a props-only update" sbox.build() wc_dir = sbox.wc_dir iota_path = os.path.join(wc_dir, 'iota') content = ["This is the file 'iota'.\n", "$Author$\n", ] content_expanded = ["This is the file 'iota'.\n", "$Author: jrandom $\n", ] # Create r2 with iota's contents and svn:keywords modified open(iota_path, 'w').writelines(content) svntest.main.run_svn(None, 'propset', 'svn:keywords', 'Author', iota_path) expected_output = wc.State(wc_dir, { 'iota' : Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('iota', wc_rev=2) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Create r3 that drops svn:keywords # put the content back to its untranslated form open(iota_path, 'w').writelines(content) svntest.main.run_svn(None, 'propdel', 'svn:keywords', iota_path) expected_status.tweak('iota', wc_rev=3) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Now, go back to r2. iota should have the Author keyword expanded. expected_disk = svntest.main.greek_state.copy() expected_disk.tweak('iota', contents=''.join(content_expanded)) expected_status = svntest.actions.get_virginal_state(wc_dir, 2) svntest.actions.run_and_verify_update(wc_dir, None, None, expected_status, None, None, None, None, None, False, wc_dir, '-r', '2') if open(iota_path).read() != ''.join(content_expanded): raise svntest.Failure("$Author$ is not expanded in 'iota'") # Update to r3. this should retranslate iota, dropping the keyword expansion expected_disk = svntest.main.greek_state.copy() expected_disk.tweak('iota', contents=''.join(content)) expected_status = svntest.actions.get_virginal_state(wc_dir, 3) svntest.actions.run_and_verify_update(wc_dir, None, expected_disk, expected_status, None, None, None, None, None, False, wc_dir) if open(iota_path).read() != ''.join(content): raise svntest.Failure("$Author$ is not contracted in 'iota'") # We used to leave some temporary files around. Make sure that we don't. temps = os.listdir(os.path.join(wc_dir, svntest.main.get_admin_name(), 'tmp')) if os.path.exists(os.path.join(wc_dir, svntest.main.get_admin_name(), 'tmp', 'props')): temps.remove('prop-base') temps.remove('props') if temps: logger.warn('Temporary files leftover: %s', (', '.join(temps),)) raise svntest.Failure ######################################################################## # Run the tests # list all tests here, starting with None: test_list = [ None, keywords_from_birth, # enable_translation, # checkout_translated, # disable_translation, update_modified_with_translation, eol_change_is_text_mod, keyword_expanded_on_checkout, cat_keyword_expansion, copy_propset_commit, propset_commit_checkout_nocrash, propset_revert_noerror, props_only_file_update, ] if __name__ == '__main__': svntest.main.run_tests(test_list) # NOTREACHED ### End of file.
from __future__ import absolute_import, print_function, division import time import numpy as np import multiprocessing as mp import threading as thr import GPy import os def timeprintit(f): class TpRecord: i = 1 times = [] if not hasattr(timeprintit, 'records'): timeprintit.records = dict() timeprintit.records[f.__name__] = TpRecord() def _timeprintit(*args, **kwargs): c1 = time.time() ret = f(*args, **kwargs) c2 = time.time() print("[{}][{}][{}] {} sec.".format(os.getpid(), f.__name__, timeprintit.records[f.__name__].i, (c2-c1))) timeprintit.records[f.__name__].i += 1 return ret return _timeprintit @timeprintit def __opt(gp, args): gp.optimize_restarts(*args) def _opt(gp, args): print("Optimize params ({} samples)".format(len(gp.X))) __opt(gp, args) return gp.optimizer_array def _sync_opt(m): def _sync_opt_gp(opt): print("Sync opt") with m.gp_lock: m.apply_hparams(opt) m.opt_pending -= 1 return _sync_opt_gp class MapPredictor: GP = None X = None y = None gp_lock = None optimize_restarts = None optimize_every = None optimize_every_min = None optimize_last = None opt_pending = 0 pool = None old_hparams = None eps_ch =None def __del__(self): self.stop() def stop(self): self.pool.close() self.pool.join() def __init__(self, dims, optimize_restarts=10, optimize_every=None, optimize_async=False, max_samples=None, parameters_array=None): self.parameters_array = parameters_array self.optimize_restarts = optimize_restarts self.optimize_every = optimize_every self.optimize_every_min = optimize_every self.optimize_async = optimize_async self.optimize_last = 0 self.eps_ch = 0.01 self.gp_lock = thr.RLock() self.pool = mp.Pool(processes=1) dims = np.atleast_1d(dims).flatten() assert(len(dims) == 2) self.X = np.ndarray((0, dims[0])) self.y = np.ndarray((0, dims[1])) self.max_samples = max_samples if max_samples is None: self.max_samples = np.inf #@timeprintit def __call__(self, x): return self.predict(x) #@timeprintit def update_observations(self, X, y): assert(len(X) == len(y)) with self.gp_lock: #print("X has shape {}, self {}".format(X.shape, self.X.shape)) #print("y has shape {}, self {}".format(y.shape, self.y.shape)) self.update_xy(X, y) if self.GP is None: self.GP = self._init_gp() self.GP.set_XY(self.X, self.y) if self.optimize_every is not None \ and len(self.X) - self.optimize_last >= self.optimize_every: self.optimize_hyperparameters(async=self.optimize_async) def optimize_hyperparameters(self, async=False): print("optimize_hyperparameters(async={})".format(async)) with self.gp_lock: self.old_hparams = self.GP.param_array.copy() if not async: opt = _opt(self.GP.copy(), (self.optimize_restarts,)) self.apply_hparams(opt) self.optimize_last = len(self.X) return if self.opt_pending > 0: print("Already pending") return self.opt_pending += 1 self.optimize_last = len(self.X) self.pool.apply_async(_opt, args=(self.GP, (self.optimize_restarts,)), callback=_sync_opt(self)) def apply_hparams(self, opt): with self.gp_lock: self.GP.optimizer_array = opt new_hparams = self.GP.param_array.copy() chrate = np.abs(1 - new_hparams/self.old_hparams) maxch = chrate.max() if self.optimize_every is not None \ and maxch < self.eps_ch: self.optimize_every *= 2 elif self.optimize_every >= 2*self.optimize_every_min: self.optimize_every /= 2 print("Optimize every {}".format(self.optimize_every)) def _init_gp(self): #kernel = GPy.kern.Matern32(input_dim=self.X[0].shape[0], ARD=True) kernel = GPy.kern.RBF(input_dim=self.X[0].shape[0], ARD=True) #kernel += GPy.kern.White(input_dim=self.X[0].shape[0]) gp = GPy.models.GPRegression(self.X, self.y, kernel) gp.preferred_optimizer = 'bfgs' if self.parameters_array is not None: gp.param_array[:] = self.parameters_array return gp #@timeprintit def predict(self, x): with self.gp_lock: assert(self.GP is not None) y_pred, var = self.GP.predict(x) return y_pred, var def update_xy(self, X, y): self.X = np.concatenate((self.X, X)) self.y = np.concatenate((self.y, y)) if self.GP is None: return else: ker = self.GP.kern ker_min_val = -ker.K(X[0].reshape(1, -1), X[0].reshape(1, -1)).squeeze() lenX = len(self.X) mdist = np.full(lenX, np.inf) nz = 0 for i in range(lenX-1): dist = -ker.K(self.X[i+1:], self.X[i].reshape(1, -1)).squeeze() dmin = dist.min() mdist[i] = dmin if dmin == ker_min_val: nz += 1 ndel = nz + max(0, lenX-nz-self.max_samples) if ndel > 0: asort = np.argsort(mdist) del_rows = asort[0:ndel] self.X = np.delete(self.X, del_rows, axis=0) self.y = np.delete(self.y, del_rows, axis=0) self.optimize_last -= ndel print("{} samples in model (deleted {})".format(self.X.shape[0], ndel)) def get_gp_parameters(self): return self.GP.param_array.copy() def set_gp_parameters(self, parameters): if parameters is None: return self.parameters_array = np.array(parameters) if self.GP is not None: self.GP.param_array[:] = parameters @property def covf(self): return self.GP.kern.K @property def gaussian_noise_variance(self): return self.GP['Gaussian_noise.variance'][0] @property def K(self): return self.GP.posterior._K @property def K_inv(self): return self.GP.posterior.woodbury_inv class EnvModel: models = None def __init__(self, optimize_restarts=10, optimize_every=1, optimize_async=False, max_samples=300): n_dim = 4 n_var = 3 mp_args = ((n_dim, 1), optimize_restarts, optimize_every, optimize_async, max_samples) self.models = np.array([MapPredictor(*mp_args) for _ in range(n_var)]) def predict_wind(self, X): # (component, value and error, coord) w_pred = np.array([w.predict(X) for w in self.models]) return w_pred # (value and error, coord, component # return w_pred.swapaxes(0, 1).swapaxes(1, 2) def update_wind(self, X, w): X = np.atleast_2d(X) w = np.atleast_2d(w) w_t = w for i in range(len(self.models)): self.models[i]\ .update_observations(X, w_t[i].reshape(len(w_t[i]), -1)) def get_params(self): return np.array([m.get_gp_parameters() for m in self.models]) def set_params(self, parameters): for (m, p) in zip(self.models, parameters): m.set_gp_parameters(p) m.optimize_every = None def mappredictor_test(): freq = 1.0/5 Tmax = 20 x = np.arange(start=0, stop=Tmax, step=1./(20*freq)) noise = np.random.normal(0, 0.3, len(x)) #noise = 0 f = np.sin(2 * np.pi * freq * x) + noise from matplotlib import pyplot as plt for k in range(1): print("{}-th iteration".format(k)) pred = None pred = MapPredictor((1, 1), optimize_restarts=10, optimize_every=50, var = None) for x_i, f_i in zip(x, f): pred.update_observations([[x_i]], [[f_i]]) #time.sleep(0.1) pred.optimize_hyperparameters(process=True) pred.stop() p = pred.GP.plot() Xt = np.arange(start=0, stop=Tmax, step=1./(100*freq)) plt.plot(Xt, np.sin(2 * np.pi * freq * Xt), 'r--') plt.ylim(-1.5, 1.5) plt.show(block=True) #plt.plot(x,f,'o') #plt.show(block=True) print("Stop") #input("Press Enter to continue...") if __name__ == '__main__': mappredictor_test()
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. #-*- python -*- import logging import json from datetime import datetime from cStringIO import StringIO # Non-stdlib imports from pylons import tmpl_context as c from ming.orm.ormsession import ThreadLocalORMSession # Pyforge-specific imports from allura import model as M from allura.lib import helpers as h from allura.lib.plugin import ImportIdConverter # Local imports from forgetracker import model as TM try: from forgeimporters.base import ProjectExtractor urlopen = ProjectExtractor.urlopen except ImportError: urlopen = h.urlopen log = logging.getLogger(__name__) class ImportException(Exception): pass class ResettableStream(object): '''Class supporting seeks within a header of otherwise unseekable stream.''' # Seeks are supported with header of this size HEADER_BUF_SIZE = 8192 def __init__(self, fp, header_size=-1): self.fp = fp self.buf = None self.buf_size = header_size if header_size >= 0 else self.HEADER_BUF_SIZE self.buf_pos = 0 self.stream_pos = 0 def _read_header(self): if self.buf is None: data = self.fp.read(self.buf_size) self.buf = StringIO(data) self.buf_len = len(data) self.stream_pos = self.buf_len def read(self, size=-1): self._read_header() data = '' if self.buf_pos < self.stream_pos: data = self.buf.read(size) self.buf_pos += len(data) if len(data) == size: return data size -= len(data) data += self.fp.read(size) self.stream_pos += len(data) return data def seek(self, pos): self._read_header() if self.stream_pos > self.buf_len: assert False, 'Started reading stream body, cannot reset pos' self.buf.seek(pos) self.buf_pos = pos def tell(self): if self.buf_pos < self.stream_pos: return self.buf_pos else: return self.stream_pos class ImportSupport(object): ATTACHMENT_SIZE_LIMIT = 1024 * 1024 def __init__(self): # Map JSON interchange format fields to Ticket fields # key is JSON's field name, value is: # None - drop # True - map as is # (new_field_name, value_convertor(val)) - use new field name and convert JSON's value # handler(ticket, field, val) - arbitrary transform, expected to modify # ticket in-place self.FIELD_MAP = { 'assigned_to': ('assigned_to_id', self.get_user_id), 'class': None, 'date': ('created_date', self.parse_date), 'date_updated': ('mod_date', self.parse_date), 'description': True, 'id': None, # default way of handling, see below for overrides 'keywords': ('labels', lambda s: s.split()), 'status': True, 'submitter': ('reported_by_id', self.get_user_id), 'summary': True, 'cc': None, } self.user_map = {} self.warnings = [] self.errors = [] self.options = {} def init_options(self, options_json): self.options = json.loads(options_json) opt_keywords = self.option('keywords_as', 'split_labels') if opt_keywords == 'single_label': self.FIELD_MAP['keywords'] = ('labels', lambda s: [s]) elif opt_keywords == 'custom': del self.FIELD_MAP['keywords'] def option(self, name, default=None): return self.options.get(name, False) # # Field/value convertors # @staticmethod def parse_date(date_string): return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%SZ') def get_user_id(self, username): def _get_user_id(username): u = M.User.by_username(username) return u._id if u else None if self.options.get('usernames_match'): return _get_user_id(username) mapped_username = self.options['user_map'].get(username) if mapped_username: return _get_user_id(mapped_username) return None def check_custom_field(self, field, value, ticket_status): field = c.app.globals.get_custom_field(field) if (field['type'] == 'select') and value: field_options = h.split_select_field_options( h.really_unicode(field['options'])) if value not in field_options: field['options'] = ' '.join([field['options'], value]) elif (field['type'] == 'milestone') and value: milestones = field['milestones'] for milestone in milestones: if milestone['name'] == value: if ticket_status in c.app.globals.open_status_names: milestone['complete'] = False break else: milestone = {'due_date': '', 'complete': not ticket_status in c.app.globals.open_status_names, 'description': '', 'name': value, 'old_name': value} field['milestones'].append(milestone) ThreadLocalORMSession.flush_all() def custom(self, ticket, field, value, ticket_status): field = '_' + field if not c.app.has_custom_field(field): log.warning( 'Custom field %s is not defined, defining as string', field) c.app.globals.custom_fields.append( dict(name=field, label=field[1:].capitalize(), type='string')) ThreadLocalORMSession.flush_all() if 'custom_fields' not in ticket: ticket['custom_fields'] = {} self.check_custom_field(field, value, ticket_status) ticket['custom_fields'][field] = value def make_artifact(self, ticket_dict): remapped = {} for f, v in ticket_dict.iteritems(): transform = self.FIELD_MAP.get(f, ()) if transform is None: continue elif transform is True: remapped[f] = v elif callable(transform): transform(remapped, f, v) elif transform is (): self.custom(remapped, f, v, ticket_dict.get('status')) else: new_f, conv = transform remapped[new_f] = conv(v) description = h.really_unicode( self.description_processing(remapped['description'])) creator = owner = '' if ticket_dict.get('submitter') and not remapped.get('reported_by_id'): creator = u'*Originally created by:* {0}\n'.format( h.really_unicode(ticket_dict['submitter'])) if ticket_dict.get('assigned_to') and not remapped.get('assigned_to_id'): owner = u'*Originally owned by:* {0}\n'.format( h.really_unicode(ticket_dict['assigned_to'])) remapped['description'] = u'{0}{1}{2}{3}'.format(creator, owner, '\n' if creator or owner else '', description) ticket_num = ticket_dict['id'] existing_ticket = TM.Ticket.query.get(app_config_id=c.app.config._id, ticket_num=ticket_num) if existing_ticket: ticket_num = c.app.globals.next_ticket_num() self.warnings.append( 'Ticket #%s: Ticket with this id already exists, using next available id: %s' % (ticket_dict['id'], ticket_num)) else: if c.app.globals.last_ticket_num < ticket_num: c.app.globals.last_ticket_num = ticket_num ThreadLocalORMSession.flush_all() ticket = TM.Ticket( app_config_id=c.app.config._id, custom_fields=dict(), ticket_num=ticket_num, import_id=ImportIdConverter.get().expand(ticket_dict['id'], c.app)) ticket.update(remapped) return ticket def comment_processing(self, comment_text): """Modify comment text before comment is created.""" return comment_text def description_processing(self, description_text): """Modify ticket description before ticket is created.""" return description_text def make_comment(self, thread, comment_dict): ts = self.parse_date(comment_dict['date']) author_id = self.get_user_id(comment_dict['submitter']) text = h.really_unicode( self.comment_processing(comment_dict['comment'])) if not author_id and comment_dict['submitter']: text = u'*Originally posted by:* {0}\n\n{1}'.format( h.really_unicode(comment_dict['submitter']), text) comment = thread.post(text=text, timestamp=ts) comment.author_id = author_id def make_attachment(self, org_ticket_id, ticket_id, att_dict): if att_dict['size'] > self.ATTACHMENT_SIZE_LIMIT: self.errors.append( 'Ticket #%s: Attachment %s (@ %s) is too large, skipping' % (org_ticket_id, att_dict['filename'], att_dict['url'])) return f = urlopen(att_dict['url']) TM.TicketAttachment.save_attachment( att_dict['filename'], ResettableStream(f), artifact_id=ticket_id) # # User handling # def collect_users(self, artifacts): users = set() for a in artifacts: users.add(a['submitter']) users.add(a['assigned_to']) for c in a['comments']: users.add(c['submitter']) return users def find_unknown_users(self, users): unknown = set() for u in users: if u and not u in self.options['user_map'] and not M.User.by_username(u): unknown.add(u) return unknown def make_user_placeholders(self, usernames): for username in usernames: allura_username = username if self.option('create_users') != '_unprefixed': allura_username = c.project.shortname + '-' + username M.User.register(dict(username=allura_username, display_name=username), False) self.options['user_map'][username] = allura_username ThreadLocalORMSession.flush_all() log.info('Created %d user placeholders', len(usernames)) def validate_user_mapping(self): if 'user_map' not in self.options: self.options['user_map'] = {} for foreign_user, allura_user in self.options['user_map'].iteritems(): u = M.User.by_username(allura_user) if not u: raise ImportException( 'User mapping %s:%s - target user does not exist' % (foreign_user, allura_user)) # # Main methods # def validate_import(self, doc, options, **post_data): log.info('validate_migration called: %s', doc) self.init_options(options) log.info('options: %s', self.options) self.validate_user_mapping() project_doc = json.loads(doc) tracker_names = project_doc['trackers'].keys() if len(tracker_names) > 1: self.errors.append('Only single tracker import is supported') return self.errors, self.warnings artifacts = project_doc['trackers'][tracker_names[0]]['artifacts'] users = self.collect_users(artifacts) unknown_users = self.find_unknown_users(users) unknown_users = sorted(list(unknown_users)) if unknown_users: self.warnings.append('''Document references unknown users. You should provide option user_map to avoid losing username information. Unknown users: %s''' % unknown_users) return {'status': True, 'errors': self.errors, 'warnings': self.warnings} def perform_import(self, doc, options, **post_data): log.info('import called: %s', options) self.init_options(options) self.validate_user_mapping() project_doc = json.loads(doc) tracker_names = project_doc['trackers'].keys() if len(tracker_names) > 1: self.errors.append('Only single tracker import is supported') return self.errors, self.warnings artifacts = project_doc['trackers'][tracker_names[0]]['artifacts'] if self.option('create_users'): users = self.collect_users(artifacts) unknown_users = self.find_unknown_users(users) self.make_user_placeholders(unknown_users) M.session.artifact_orm_session._get().skip_mod_date = True for a in artifacts: comments = a.pop('comments', []) attachments = a.pop('attachments', []) t = self.make_artifact(a) for c_entry in comments: self.make_comment(t.discussion_thread, c_entry) for a_entry in attachments: try: self.make_attachment(a['id'], t._id, a_entry) except Exception, e: self.warnings.append( 'Could not import attachment, skipped: %s' % e) log.info('Imported ticket: %d', t.ticket_num) c.app.globals.invalidate_bin_counts() return {'status': True, 'errors': self.errors, 'warnings': self.warnings}
# Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The volumes api.""" import webob from webob import exc from xml.dom import minidom from cinder.api import common from cinder.api.openstack import wsgi from cinder.api.v2.views import volumes as volume_views from cinder.api import xmlutil from cinder import exception from cinder import flags from cinder.openstack.common import log as logging from cinder.openstack.common import uuidutils from cinder import volume from cinder.volume import volume_types LOG = logging.getLogger(__name__) FLAGS = flags.FLAGS def make_attachment(elem): elem.set('id') elem.set('server_id') elem.set('volume_id') elem.set('device') def make_volume(elem): elem.set('id') elem.set('status') elem.set('size') elem.set('availability_zone') elem.set('created_at') elem.set('name') elem.set('display_description') elem.set('volume_type') elem.set('snapshot_id') elem.set('source_volid') attachments = xmlutil.SubTemplateElement(elem, 'attachments') attachment = xmlutil.SubTemplateElement(attachments, 'attachment', selector='attachments') make_attachment(attachment) # Attach metadata node elem.append(common.MetadataTemplate()) volume_nsmap = {None: xmlutil.XMLNS_VOLUME_V2, 'atom': xmlutil.XMLNS_ATOM} class VolumeTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('volume', selector='volume') make_volume(root) return xmlutil.MasterTemplate(root, 1, nsmap=volume_nsmap) class VolumesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('volumes') elem = xmlutil.SubTemplateElement(root, 'volume', selector='volumes') make_volume(elem) return xmlutil.MasterTemplate(root, 1, nsmap=volume_nsmap) class CommonDeserializer(wsgi.MetadataXMLDeserializer): """Common deserializer to handle xml-formatted volume requests. Handles standard volume attributes as well as the optional metadata attribute """ metadata_deserializer = common.MetadataXMLDeserializer() def _extract_volume(self, node): """Marshal the volume attribute of a parsed request.""" volume = {} volume_node = self.find_first_child_named(node, 'volume') attributes = ['name', 'display_description', 'size', 'volume_type', 'availability_zone'] for attr in attributes: if volume_node.getAttribute(attr): volume[attr] = volume_node.getAttribute(attr) metadata_node = self.find_first_child_named(volume_node, 'metadata') if metadata_node is not None: volume['metadata'] = self.extract_metadata(metadata_node) return volume class CreateDeserializer(CommonDeserializer): """Deserializer to handle xml-formatted create volume requests. Handles standard volume attributes as well as the optional metadata attribute """ def default(self, string): """Deserialize an xml-formatted volume create request.""" dom = minidom.parseString(string) volume = self._extract_volume(dom) return {'body': {'volume': volume}} class VolumeController(wsgi.Controller): """The Volumes API controller for the OpenStack API.""" _view_builder_class = volume_views.ViewBuilder def __init__(self, ext_mgr): self.volume_api = volume.API() self.ext_mgr = ext_mgr super(VolumeController, self).__init__() @wsgi.serializers(xml=VolumeTemplate) def show(self, req, id): """Return data about the given volume.""" context = req.environ['cinder.context'] try: vol = self.volume_api.get(context, id) except exception.NotFound: raise exc.HTTPNotFound() return self._view_builder.detail(req, vol) def delete(self, req, id): """Delete a volume.""" context = req.environ['cinder.context'] LOG.audit(_("Delete volume with id: %s"), id, context=context) try: volume = self.volume_api.get(context, id) self.volume_api.delete(context, volume) except exception.NotFound: raise exc.HTTPNotFound() return webob.Response(status_int=202) @wsgi.serializers(xml=VolumesTemplate) def index(self, req): """Returns a summary list of volumes.""" return self._get_volumes(req, is_detail=False) @wsgi.serializers(xml=VolumesTemplate) def detail(self, req): """Returns a detailed list of volumes.""" return self._get_volumes(req, is_detail=True) def _get_volumes(self, req, is_detail): """Returns a list of volumes, transformed through view builder.""" context = req.environ['cinder.context'] params = req.params.copy() marker = params.pop('marker', None) limit = params.pop('limit', None) sort_key = params.pop('sort_key', 'created_at') sort_dir = params.pop('sort_dir', 'desc') filters = params remove_invalid_options(context, filters, self._get_volume_filter_options()) # NOTE(thingee): v2 API allows name instead of display_name if 'name' in filters: filters['display_name'] = filters['name'] del filters['name'] volumes = self.volume_api.get_all(context, marker, limit, sort_key, sort_dir, filters) limited_list = common.limited(volumes, req) if is_detail: volumes = self._view_builder.detail_list(req, limited_list) else: volumes = self._view_builder.summary_list(req, limited_list) return volumes def _image_uuid_from_href(self, image_href): # If the image href was generated by nova api, strip image_href # down to an id. try: image_uuid = image_href.split('/').pop() except (TypeError, AttributeError): msg = _("Invalid imageRef provided.") raise exc.HTTPBadRequest(explanation=msg) if not uuidutils.is_uuid_like(image_uuid): msg = _("Invalid imageRef provided.") raise exc.HTTPBadRequest(explanation=msg) return image_uuid @wsgi.serializers(xml=VolumeTemplate) @wsgi.deserializers(xml=CreateDeserializer) def create(self, req, body): """Creates a new volume.""" if not self.is_valid_body(body, 'volume'): raise exc.HTTPUnprocessableEntity() context = req.environ['cinder.context'] volume = body['volume'] kwargs = {} # NOTE(thingee): v2 API allows name instead of display_name if volume.get('name'): volume['display_name'] = volume.get('name') del volume['name'] req_volume_type = volume.get('volume_type', None) if req_volume_type: try: kwargs['volume_type'] = volume_types.get_volume_type_by_name( context, req_volume_type) except exception.VolumeTypeNotFound: explanation = 'Volume type not found.' raise exc.HTTPNotFound(explanation=explanation) kwargs['metadata'] = volume.get('metadata', None) snapshot_id = volume.get('snapshot_id') if snapshot_id is not None: kwargs['snapshot'] = self.volume_api.get_snapshot(context, snapshot_id) else: kwargs['snapshot'] = None source_volid = volume.get('source_volid') if source_volid is not None: kwargs['source_volume'] = self.volume_api.get_volume(context, source_volid) else: kwargs['source_volume'] = None size = volume.get('size', None) if size is None and kwargs['snapshot'] is not None: size = kwargs['snapshot']['volume_size'] elif size is None and kwargs['source_volume'] is not None: size = kwargs['source_volume']['size'] LOG.audit(_("Create volume of %s GB"), size, context=context) image_href = None image_uuid = None if self.ext_mgr.is_loaded('os-image-create'): image_href = volume.get('imageRef') if snapshot_id and image_href: msg = _("Snapshot and image cannot be specified together.") raise exc.HTTPBadRequest(explanation=msg) if image_href: image_uuid = self._image_uuid_from_href(image_href) kwargs['image_id'] = image_uuid kwargs['availability_zone'] = volume.get('availability_zone', None) new_volume = self.volume_api.create(context, size, volume.get('display_name'), volume.get('display_description'), **kwargs) # TODO(vish): Instance should be None at db layer instead of # trying to lazy load, but for now we turn it into # a dict to avoid an error. retval = self._view_builder.summary(req, dict(new_volume.iteritems())) return retval def _get_volume_filter_options(self): """Return volume search options allowed by non-admin.""" return ('name', 'status') @wsgi.serializers(xml=VolumeTemplate) def update(self, req, id, body): """Update a volume.""" context = req.environ['cinder.context'] if not body: raise exc.HTTPUnprocessableEntity() if 'volume' not in body: raise exc.HTTPUnprocessableEntity() volume = body['volume'] update_dict = {} valid_update_keys = ( 'name', 'display_description', 'metadata', ) for key in valid_update_keys: if key in volume: update_dict[key] = volume[key] # NOTE(thingee): v2 API allows name instead of display_name if 'name' in update_dict: update_dict['display_name'] = update_dict['name'] del update_dict['name'] try: volume = self.volume_api.get(context, id) self.volume_api.update(context, volume, update_dict) except exception.NotFound: raise exc.HTTPNotFound() volume.update(update_dict) return self._view_builder.detail(req, volume) def create_resource(ext_mgr): return wsgi.Resource(VolumeController(ext_mgr)) def remove_invalid_options(context, filters, allowed_search_options): """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in filters if opt not in allowed_search_options] bad_options = ", ".join(unknown_options) log_msg = _("Removing options '%s' from query") % bad_options LOG.debug(log_msg) for opt in unknown_options: del filters[opt]
from __future__ import absolute_import, division, print_function import pytest import sys from _pytest.skipping import MarkEvaluator, folded_skips, pytest_runtest_setup from _pytest.runner import runtestprotocol class TestEvaluator(object): def test_no_marker(self, testdir): item = testdir.getitem("def test_func(): pass") evalskipif = MarkEvaluator(item, 'skipif') assert not evalskipif assert not evalskipif.istrue() def test_marked_no_args(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xyz def test_func(): pass """) ev = MarkEvaluator(item, 'xyz') assert ev assert ev.istrue() expl = ev.getexplanation() assert expl == "" assert not ev.get("run", False) def test_marked_one_arg(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xyz("hasattr(os, 'sep')") def test_func(): pass """) ev = MarkEvaluator(item, 'xyz') assert ev assert ev.istrue() expl = ev.getexplanation() assert expl == "condition: hasattr(os, 'sep')" @pytest.mark.skipif('sys.version_info[0] >= 3') def test_marked_one_arg_unicode(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xyz(u"hasattr(os, 'sep')") def test_func(): pass """) ev = MarkEvaluator(item, 'xyz') assert ev assert ev.istrue() expl = ev.getexplanation() assert expl == "condition: hasattr(os, 'sep')" def test_marked_one_arg_with_reason(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xyz("hasattr(os, 'sep')", attr=2, reason="hello world") def test_func(): pass """) ev = MarkEvaluator(item, 'xyz') assert ev assert ev.istrue() expl = ev.getexplanation() assert expl == "hello world" assert ev.get("attr") == 2 def test_marked_one_arg_twice(self, testdir): lines = [ '''@pytest.mark.skipif("not hasattr(os, 'murks')")''', '''@pytest.mark.skipif("hasattr(os, 'murks')")''' ] for i in range(0, 2): item = testdir.getitem(""" import pytest %s %s def test_func(): pass """ % (lines[i], lines[(i + 1) % 2])) ev = MarkEvaluator(item, 'skipif') assert ev assert ev.istrue() expl = ev.getexplanation() assert expl == "condition: not hasattr(os, 'murks')" def test_marked_one_arg_twice2(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.skipif("hasattr(os, 'murks')") @pytest.mark.skipif("not hasattr(os, 'murks')") def test_func(): pass """) ev = MarkEvaluator(item, 'skipif') assert ev assert ev.istrue() expl = ev.getexplanation() assert expl == "condition: not hasattr(os, 'murks')" def test_marked_skip_with_not_string(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.skipif(False) def test_func(): pass """) ev = MarkEvaluator(item, 'skipif') exc = pytest.raises(pytest.fail.Exception, ev.istrue) assert """Failed: you need to specify reason=STRING when using booleans as conditions.""" in exc.value.msg def test_skipif_class(self, testdir): item, = testdir.getitems(""" import pytest class TestClass(object): pytestmark = pytest.mark.skipif("config._hackxyz") def test_func(self): pass """) item.config._hackxyz = 3 ev = MarkEvaluator(item, 'skipif') assert ev.istrue() expl = ev.getexplanation() assert expl == "condition: config._hackxyz" class TestXFail(object): @pytest.mark.parametrize('strict', [True, False]) def test_xfail_simple(self, testdir, strict): item = testdir.getitem(""" import pytest @pytest.mark.xfail(strict=%s) def test_func(): assert 0 """ % strict) reports = runtestprotocol(item, log=False) assert len(reports) == 3 callreport = reports[1] assert callreport.skipped assert callreport.wasxfail == "" def test_xfail_xpassed(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xfail(reason="this is an xfail") def test_func(): assert 1 """) reports = runtestprotocol(item, log=False) assert len(reports) == 3 callreport = reports[1] assert callreport.passed assert callreport.wasxfail == "this is an xfail" def test_xfail_xpassed_strict(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xfail(strict=True, reason="nope") def test_func(): assert 1 """) reports = runtestprotocol(item, log=False) assert len(reports) == 3 callreport = reports[1] assert callreport.failed assert callreport.longrepr == "[XPASS(strict)] nope" assert not hasattr(callreport, "wasxfail") def test_xfail_run_anyway(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.xfail def test_func(): assert 0 def test_func2(): pytest.xfail("hello") """) result = testdir.runpytest("--runxfail") result.stdout.fnmatch_lines([ "*def test_func():*", "*assert 0*", "*1 failed*1 pass*", ]) def test_xfail_evalfalse_but_fails(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.xfail('False') def test_func(): assert 0 """) reports = runtestprotocol(item, log=False) callreport = reports[1] assert callreport.failed assert not hasattr(callreport, "wasxfail") assert 'xfail' in callreport.keywords def test_xfail_not_report_default(self, testdir): p = testdir.makepyfile(test_one=""" import pytest @pytest.mark.xfail def test_this(): assert 0 """) testdir.runpytest(p, '-v') # result.stdout.fnmatch_lines([ # "*HINT*use*-r*" # ]) def test_xfail_not_run_xfail_reporting(self, testdir): p = testdir.makepyfile(test_one=""" import pytest @pytest.mark.xfail(run=False, reason="noway") def test_this(): assert 0 @pytest.mark.xfail("True", run=False) def test_this_true(): assert 0 @pytest.mark.xfail("False", run=False, reason="huh") def test_this_false(): assert 1 """) result = testdir.runpytest(p, '-rx', ) result.stdout.fnmatch_lines([ "*test_one*test_this*", "*NOTRUN*noway", "*test_one*test_this_true*", "*NOTRUN*condition:*True*", "*1 passed*", ]) def test_xfail_not_run_no_setup_run(self, testdir): p = testdir.makepyfile(test_one=""" import pytest @pytest.mark.xfail(run=False, reason="hello") def test_this(): assert 0 def setup_module(mod): raise ValueError(42) """) result = testdir.runpytest(p, '-rx', ) result.stdout.fnmatch_lines([ "*test_one*test_this*", "*NOTRUN*hello", "*1 xfailed*", ]) def test_xfail_xpass(self, testdir): p = testdir.makepyfile(test_one=""" import pytest @pytest.mark.xfail def test_that(): assert 1 """) result = testdir.runpytest(p, '-rX') result.stdout.fnmatch_lines([ "*XPASS*test_that*", "*1 xpassed*" ]) assert result.ret == 0 def test_xfail_imperative(self, testdir): p = testdir.makepyfile(""" import pytest def test_this(): pytest.xfail("hello") """) result = testdir.runpytest(p) result.stdout.fnmatch_lines([ "*1 xfailed*", ]) result = testdir.runpytest(p, "-rx") result.stdout.fnmatch_lines([ "*XFAIL*test_this*", "*reason:*hello*", ]) result = testdir.runpytest(p, "--runxfail") result.stdout.fnmatch_lines("*1 pass*") def test_xfail_imperative_in_setup_function(self, testdir): p = testdir.makepyfile(""" import pytest def setup_function(function): pytest.xfail("hello") def test_this(): assert 0 """) result = testdir.runpytest(p) result.stdout.fnmatch_lines([ "*1 xfailed*", ]) result = testdir.runpytest(p, "-rx") result.stdout.fnmatch_lines([ "*XFAIL*test_this*", "*reason:*hello*", ]) result = testdir.runpytest(p, "--runxfail") result.stdout.fnmatch_lines(""" *def test_this* *1 fail* """) def xtest_dynamic_xfail_set_during_setup(self, testdir): p = testdir.makepyfile(""" import pytest def setup_function(function): pytest.mark.xfail(function) def test_this(): assert 0 def test_that(): assert 1 """) result = testdir.runpytest(p, '-rxX') result.stdout.fnmatch_lines([ "*XFAIL*test_this*", "*XPASS*test_that*", ]) def test_dynamic_xfail_no_run(self, testdir): p = testdir.makepyfile(""" import pytest @pytest.fixture def arg(request): request.applymarker(pytest.mark.xfail(run=False)) def test_this(arg): assert 0 """) result = testdir.runpytest(p, '-rxX') result.stdout.fnmatch_lines([ "*XFAIL*test_this*", "*NOTRUN*", ]) def test_dynamic_xfail_set_during_funcarg_setup(self, testdir): p = testdir.makepyfile(""" import pytest @pytest.fixture def arg(request): request.applymarker(pytest.mark.xfail) def test_this2(arg): assert 0 """) result = testdir.runpytest(p) result.stdout.fnmatch_lines([ "*1 xfailed*", ]) @pytest.mark.parametrize('expected, actual, matchline', [('TypeError', 'TypeError', "*1 xfailed*"), ('(AttributeError, TypeError)', 'TypeError', "*1 xfailed*"), ('TypeError', 'IndexError', "*1 failed*"), ('(AttributeError, TypeError)', 'IndexError', "*1 failed*"), ]) def test_xfail_raises(self, expected, actual, matchline, testdir): p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(raises=%s) def test_raises(): raise %s() """ % (expected, actual)) result = testdir.runpytest(p) result.stdout.fnmatch_lines([ matchline, ]) def test_strict_sanity(self, testdir): """sanity check for xfail(strict=True): a failing test should behave exactly like a normal xfail. """ p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(reason='unsupported feature', strict=True) def test_foo(): assert 0 """) result = testdir.runpytest(p, '-rxX') result.stdout.fnmatch_lines([ '*XFAIL*', '*unsupported feature*', ]) assert result.ret == 0 @pytest.mark.parametrize('strict', [True, False]) def test_strict_xfail(self, testdir, strict): p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(reason='unsupported feature', strict=%s) def test_foo(): with open('foo_executed', 'w'): pass # make sure test executes """ % strict) result = testdir.runpytest(p, '-rxX') if strict: result.stdout.fnmatch_lines([ '*test_foo*', '*XPASS(strict)*unsupported feature*', ]) else: result.stdout.fnmatch_lines([ '*test_strict_xfail*', 'XPASS test_strict_xfail.py::test_foo unsupported feature', ]) assert result.ret == (1 if strict else 0) assert testdir.tmpdir.join('foo_executed').isfile() @pytest.mark.parametrize('strict', [True, False]) def test_strict_xfail_condition(self, testdir, strict): p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(False, reason='unsupported feature', strict=%s) def test_foo(): pass """ % strict) result = testdir.runpytest(p, '-rxX') result.stdout.fnmatch_lines('*1 passed*') assert result.ret == 0 @pytest.mark.parametrize('strict', [True, False]) def test_xfail_condition_keyword(self, testdir, strict): p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(condition=False, reason='unsupported feature', strict=%s) def test_foo(): pass """ % strict) result = testdir.runpytest(p, '-rxX') result.stdout.fnmatch_lines('*1 passed*') assert result.ret == 0 @pytest.mark.parametrize('strict_val', ['true', 'false']) def test_strict_xfail_default_from_file(self, testdir, strict_val): testdir.makeini(''' [pytest] xfail_strict = %s ''' % strict_val) p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(reason='unsupported feature') def test_foo(): pass """) result = testdir.runpytest(p, '-rxX') strict = strict_val == 'true' result.stdout.fnmatch_lines('*1 failed*' if strict else '*1 xpassed*') assert result.ret == (1 if strict else 0) class TestXFailwithSetupTeardown(object): def test_failing_setup_issue9(self, testdir): testdir.makepyfile(""" import pytest def setup_function(func): assert 0 @pytest.mark.xfail def test_func(): pass """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*1 xfail*", ]) def test_failing_teardown_issue9(self, testdir): testdir.makepyfile(""" import pytest def teardown_function(func): assert 0 @pytest.mark.xfail def test_func(): pass """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*1 xfail*", ]) class TestSkip(object): def test_skip_class(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip class TestSomething(object): def test_foo(self): pass def test_bar(self): pass def test_baz(): pass """) rec = testdir.inline_run() rec.assertoutcome(skipped=2, passed=1) def test_skips_on_false_string(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip('False') def test_foo(): pass """) rec = testdir.inline_run() rec.assertoutcome(skipped=1) def test_arg_as_reason(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip('testing stuff') def test_bar(): pass """) result = testdir.runpytest('-rs') result.stdout.fnmatch_lines([ "*testing stuff*", "*1 skipped*", ]) def test_skip_no_reason(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip def test_foo(): pass """) result = testdir.runpytest('-rs') result.stdout.fnmatch_lines([ "*unconditional skip*", "*1 skipped*", ]) def test_skip_with_reason(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip(reason="for lolz") def test_bar(): pass """) result = testdir.runpytest('-rs') result.stdout.fnmatch_lines([ "*for lolz*", "*1 skipped*", ]) def test_only_skips_marked_test(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip def test_foo(): pass @pytest.mark.skip(reason="nothing in particular") def test_bar(): pass def test_baz(): assert True """) result = testdir.runpytest('-rs') result.stdout.fnmatch_lines([ "*nothing in particular*", "*1 passed*2 skipped*", ]) def test_strict_and_skip(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skip def test_hello(): pass """) result = testdir.runpytest("-rs") result.stdout.fnmatch_lines([ "*unconditional skip*", "*1 skipped*", ]) class TestSkipif(object): def test_skipif_conditional(self, testdir): item = testdir.getitem(""" import pytest @pytest.mark.skipif("hasattr(os, 'sep')") def test_func(): pass """) x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item)) assert x.value.msg == "condition: hasattr(os, 'sep')" @pytest.mark.parametrize('params', [ '"hasattr(sys, \'platform\')"', 'True, reason="invalid platform"', ]) def test_skipif_reporting(self, testdir, params): p = testdir.makepyfile(test_foo=""" import pytest @pytest.mark.skipif(%(params)s) def test_that(): assert 0 """ % dict(params=params)) result = testdir.runpytest(p, '-s', '-rs') result.stdout.fnmatch_lines([ "*SKIP*1*test_foo.py*platform*", "*1 skipped*" ]) assert result.ret == 0 @pytest.mark.parametrize('marker, msg1, msg2', [ ('skipif', 'SKIP', 'skipped'), ('xfail', 'XPASS', 'xpassed'), ]) def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2): testdir.makepyfile(test_foo=""" import pytest @pytest.mark.{marker}(False, reason='first_condition') @pytest.mark.{marker}(True, reason='second_condition') def test_foobar(): assert 1 """.format(marker=marker)) result = testdir.runpytest('-s', '-rsxX') result.stdout.fnmatch_lines([ "*{msg1}*test_foo.py*second_condition*".format(msg1=msg1), "*1 {msg2}*".format(msg2=msg2), ]) assert result.ret == 0 def test_skip_not_report_default(testdir): p = testdir.makepyfile(test_one=""" import pytest def test_this(): pytest.skip("hello") """) result = testdir.runpytest(p, '-v') result.stdout.fnmatch_lines([ # "*HINT*use*-r*", "*1 skipped*", ]) def test_skipif_class(testdir): p = testdir.makepyfile(""" import pytest class TestClass(object): pytestmark = pytest.mark.skipif("True") def test_that(self): assert 0 def test_though(self): assert 0 """) result = testdir.runpytest(p) result.stdout.fnmatch_lines([ "*2 skipped*" ]) def test_skip_reasons_folding(): path = "xyz" lineno = 3 message = "justso" longrepr = (path, lineno, message) class X(object): pass ev1 = X() ev1.when = "execute" ev1.skipped = True ev1.longrepr = longrepr ev2 = X() ev2.when = "execute" ev2.longrepr = longrepr ev2.skipped = True # ev3 might be a collection report ev3 = X() ev3.longrepr = longrepr ev3.skipped = True values = folded_skips([ev1, ev2, ev3]) assert len(values) == 1 num, fspath, lineno, reason = values[0] assert num == 3 assert fspath == path assert lineno == lineno assert reason == message def test_skipped_reasons_functional(testdir): testdir.makepyfile( test_one=""" from conftest import doskip def setup_function(func): doskip() def test_func(): pass class TestClass(object): def test_method(self): doskip() """, conftest=""" import pytest def doskip(): pytest.skip('test') """ ) result = testdir.runpytest('-rs') result.stdout.fnmatch_lines([ "*SKIP*2*conftest.py:4: test", ]) assert result.ret == 0 def test_skipped_folding(testdir): testdir.makepyfile( test_one=""" import pytest pytestmark = pytest.mark.skip("Folding") def setup_function(func): pass def test_func(): pass class TestClass(object): def test_method(self): pass """, ) result = testdir.runpytest('-rs') result.stdout.fnmatch_lines([ "*SKIP*2*test_one.py: Folding" ]) assert result.ret == 0 def test_reportchars(testdir): testdir.makepyfile(""" import pytest def test_1(): assert 0 @pytest.mark.xfail def test_2(): assert 0 @pytest.mark.xfail def test_3(): pass def test_4(): pytest.skip("four") """) result = testdir.runpytest("-rfxXs") result.stdout.fnmatch_lines([ "FAIL*test_1*", "XFAIL*test_2*", "XPASS*test_3*", "SKIP*four*", ]) def test_reportchars_error(testdir): testdir.makepyfile( conftest=""" def pytest_runtest_teardown(): assert 0 """, test_simple=""" def test_foo(): pass """) result = testdir.runpytest('-rE') result.stdout.fnmatch_lines([ 'ERROR*test_foo*', ]) def test_reportchars_all(testdir): testdir.makepyfile(""" import pytest def test_1(): assert 0 @pytest.mark.xfail def test_2(): assert 0 @pytest.mark.xfail def test_3(): pass def test_4(): pytest.skip("four") """) result = testdir.runpytest("-ra") result.stdout.fnmatch_lines([ "FAIL*test_1*", "SKIP*four*", "XFAIL*test_2*", "XPASS*test_3*", ]) def test_reportchars_all_error(testdir): testdir.makepyfile( conftest=""" def pytest_runtest_teardown(): assert 0 """, test_simple=""" def test_foo(): pass """) result = testdir.runpytest('-ra') result.stdout.fnmatch_lines([ 'ERROR*test_foo*', ]) @pytest.mark.xfail("hasattr(sys, 'pypy_version_info')") def test_errors_in_xfail_skip_expressions(testdir): testdir.makepyfile(""" import pytest @pytest.mark.skipif("asd") def test_nameerror(): pass @pytest.mark.xfail("syntax error") def test_syntax(): pass def test_func(): pass """) result = testdir.runpytest() markline = " ^" if sys.platform.startswith("java"): # XXX report this to java markline = "*" + markline[8:] result.stdout.fnmatch_lines([ "*ERROR*test_nameerror*", "*evaluating*skipif*expression*", "*asd*", "*ERROR*test_syntax*", "*evaluating*xfail*expression*", " syntax error", markline, "SyntaxError: invalid syntax", "*1 pass*2 error*", ]) def test_xfail_skipif_with_globals(testdir): testdir.makepyfile(""" import pytest x = 3 @pytest.mark.skipif("x == 3") def test_skip1(): pass @pytest.mark.xfail("x == 3") def test_boolean(): assert 0 """) result = testdir.runpytest("-rsx") result.stdout.fnmatch_lines([ "*SKIP*x == 3*", "*XFAIL*test_boolean*", "*x == 3*", ]) def test_direct_gives_error(testdir): testdir.makepyfile(""" import pytest @pytest.mark.skipif(True) def test_skip1(): pass """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*1 error*", ]) def test_default_markers(testdir): result = testdir.runpytest("--markers") result.stdout.fnmatch_lines([ "*skipif(*condition)*skip*", "*xfail(*condition, reason=None, run=True, raises=None, strict=False)*expected failure*", ]) def test_xfail_test_setup_exception(testdir): testdir.makeconftest(""" def pytest_runtest_setup(): 0 / 0 """) p = testdir.makepyfile(""" import pytest @pytest.mark.xfail def test_func(): assert 0 """) result = testdir.runpytest(p) assert result.ret == 0 assert 'xfailed' in result.stdout.str() assert 'xpassed' not in result.stdout.str() def test_imperativeskip_on_xfail_test(testdir): testdir.makepyfile(""" import pytest @pytest.mark.xfail def test_that_fails(): assert 0 @pytest.mark.skipif("True") def test_hello(): pass """) testdir.makeconftest(""" import pytest def pytest_runtest_setup(item): pytest.skip("abc") """) result = testdir.runpytest("-rsxX") result.stdout.fnmatch_lines_random(""" *SKIP*abc* *SKIP*condition: True* *2 skipped* """) class TestBooleanCondition(object): def test_skipif(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skipif(True, reason="True123") def test_func1(): pass @pytest.mark.skipif(False, reason="True123") def test_func2(): pass """) result = testdir.runpytest() result.stdout.fnmatch_lines(""" *1 passed*1 skipped* """) def test_skipif_noreason(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.skipif(True) def test_func(): pass """) result = testdir.runpytest("-rs") result.stdout.fnmatch_lines(""" *1 error* """) def test_xfail(self, testdir): testdir.makepyfile(""" import pytest @pytest.mark.xfail(True, reason="True123") def test_func(): assert 0 """) result = testdir.runpytest("-rxs") result.stdout.fnmatch_lines(""" *XFAIL* *True123* *1 xfail* """) def test_xfail_item(testdir): # Ensure pytest.xfail works with non-Python Item testdir.makeconftest(""" import pytest class MyItem(pytest.Item): nodeid = 'foo' def runtest(self): pytest.xfail("Expected Failure") def pytest_collect_file(path, parent): return MyItem("foo", parent) """) result = testdir.inline_run() passed, skipped, failed = result.listoutcomes() assert not failed xfailed = [r for r in skipped if hasattr(r, 'wasxfail')] assert xfailed def test_module_level_skip_error(testdir): """ Verify that using pytest.skip at module level causes a collection error """ testdir.makepyfile(""" import pytest @pytest.skip def test_func(): assert True """) result = testdir.runpytest() result.stdout.fnmatch_lines( "*Using pytest.skip outside of a test is not allowed*" ) def test_module_level_skip_with_allow_module_level(testdir): """ Verify that using pytest.skip(allow_module_level=True) is allowed """ testdir.makepyfile(""" import pytest pytest.skip("skip_module_level", allow_module_level=True) def test_func(): assert 0 """) result = testdir.runpytest("-rxs") result.stdout.fnmatch_lines( "*SKIP*skip_module_level" ) def test_invalid_skip_keyword_parameter(testdir): """ Verify that using pytest.skip() with unknown parameter raises an error """ testdir.makepyfile(""" import pytest pytest.skip("skip_module_level", unknown=1) def test_func(): assert 0 """) result = testdir.runpytest() result.stdout.fnmatch_lines( "*TypeError:*['unknown']*" ) def test_mark_xfail_item(testdir): # Ensure pytest.mark.xfail works with non-Python Item testdir.makeconftest(""" import pytest class MyItem(pytest.Item): nodeid = 'foo' def setup(self): marker = pytest.mark.xfail(True, reason="Expected failure") self.add_marker(marker) def runtest(self): assert False def pytest_collect_file(path, parent): return MyItem("foo", parent) """) result = testdir.inline_run() passed, skipped, failed = result.listoutcomes() assert not failed xfailed = [r for r in skipped if hasattr(r, 'wasxfail')] assert xfailed
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for dtype_util.""" import collections # Dependency imports from absl.testing import parameterized import numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import test_util JAX_MODE = False @test_util.test_all_tf_execution_regimes class DtypeUtilTest(test_util.TestCase): def testIsInteger(self): self.assertFalse(dtype_util.is_integer(np.float64)) def testNoModifyArgsList(self): x = tf.ones(3, tf.float32) y = tf.zeros(4, tf.float32) lst = [x, y] self.assertEqual(tf.float32, dtype_util.common_dtype(lst)) self.assertLen(lst, 2) def testCommonDtypeAcceptsNone(self): self.assertEqual( tf.float16, dtype_util.common_dtype( [None], dtype_hint=tf.float16)) x = tf.ones(3, tf.float16) self.assertEqual( tf.float16, dtype_util.common_dtype( [x, None], dtype_hint=tf.float32)) fake_tensor = collections.namedtuple('fake_tensor', ['dtype']) self.assertEqual( tf.float16, dtype_util.common_dtype( [fake_tensor(dtype=None), None, x], dtype_hint=tf.float32)) def testCommonDtypeFromLinop(self): x = tf.linalg.LinearOperatorDiag(tf.ones(3, tf.float16)) self.assertEqual( tf.float16, dtype_util.common_dtype([x], dtype_hint=tf.float32)) @parameterized.named_parameters( dict(testcase_name='Float32', dtype=tf.float32, expected_minval=np.float32(-3.4028235e+38)), dict(testcase_name='Float64', dtype=tf.float64, expected_minval=np.float64(-1.7976931348623157e+308)), ) def testMin(self, dtype, expected_minval): self.assertEqual(dtype_util.min(dtype), expected_minval) @parameterized.named_parameters( dict(testcase_name='Float32', dtype=tf.float32, expected_maxval=np.float32(3.4028235e+38)), dict(testcase_name='Float64', dtype=tf.float64, expected_maxval=np.float64(1.7976931348623157e+308)), ) def testMax(self, dtype, expected_maxval): self.assertEqual(dtype_util.max(dtype), expected_maxval) @parameterized.parameters( ([1], None, None), ([1], tf.float32, None), ([1], None, tf.float32), ([1], tf.float32, tf.float64), (np.int64, None, None), (np.int64, None, tf.float32), (np.int64, tf.float32, None), (np.int64, tf.float32, tf.float64), (tf.int64, None, None), (tf.int64, None, tf.float32), (tf.float32, tf.float32, None), (tf.float32, tf.float32, tf.float64)) @test_util.disable_test_for_backend( disable_numpy=True, reason='`convert_to_tensor` respects array dtypes in numpy backend.') def testConvertToDtype(self, tensor_or_dtype, dtype, dtype_hint): if np.issctype(tensor_or_dtype): example_tensor = np.zeros([], tensor_or_dtype) elif isinstance(tensor_or_dtype, tf.DType): example_tensor = tf.zeros([], tensor_or_dtype) else: example_tensor = tensor_or_dtype # Try with the original argument. self.assertEqual( tf.convert_to_tensor(example_tensor, dtype, dtype_hint).dtype, dtype_util.convert_to_dtype(tensor_or_dtype, dtype, dtype_hint)) # Try with a concrete value. self.assertEqual( tf.convert_to_tensor(example_tensor, dtype, dtype_hint).dtype, dtype_util.convert_to_dtype(example_tensor, dtype, dtype_hint)) @parameterized.parameters( (tf.int64, tf.float32, None), (tf.int64, tf.float32, tf.float64)) @test_util.disable_test_for_backend( disable_numpy=True, disable_jax=True, reason='`convert_to_tensor` only raises in TF mode.') def testConvertToDTypeRaises(self, tensor_or_dtype, dtype, dtype_hint): if np.issctype(tensor_or_dtype): example_tensor = np.zeros([], tensor_or_dtype) elif isinstance(tensor_or_dtype, tf.DType): example_tensor = tf.zeros([], tensor_or_dtype) else: example_tensor = tensor_or_dtype with self.assertRaisesRegex(TypeError, 'Found incompatible dtypes'): dtype_util.convert_to_dtype(tensor_or_dtype, dtype, dtype_hint) with self.assertRaisesRegex(TypeError, 'Found incompatible dtypes'): dtype_util.convert_to_dtype(example_tensor, dtype, dtype_hint) @parameterized.parameters(np.float16, np.float32, np.float64, tf.float16, tf.float32, tf.float64) def testEps(self, dtype): self.assertEqual( dtype_util.eps(dtype).dtype, dtype_util.as_numpy_dtype(dtype)) @test_util.test_all_tf_execution_regimes class FloatDTypeTest(test_util.TestCase): def test_assert_same_float_dtype(self): self.assertIs(tf.float32, dtype_util.assert_same_float_dtype(None, None)) self.assertIs(tf.float32, dtype_util.assert_same_float_dtype([], None)) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype([], tf.float32)) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype(None, tf.float32)) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype([None, None], None)) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype([None, None], tf.float32)) const_float = tf.constant(3.0, dtype=tf.float32) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype([const_float], tf.float32)) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [const_float], tf.int32) if not hasattr(tf, 'SparseTensor'): # No SparseTensor in numpy/jax mode. return sparse_float = tf.SparseTensor( tf.constant([[111], [232]], tf.int64), tf.constant([23.4, -43.2], tf.float32), tf.constant([500], tf.int64)) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype([sparse_float], tf.float32)) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [sparse_float], tf.int32) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [const_float, None, sparse_float], tf.float64) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype([const_float, sparse_float])) self.assertIs( tf.float32, dtype_util.assert_same_float_dtype( [const_float, sparse_float], tf.float32)) const_int = tf.constant(3, dtype=tf.int32) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [sparse_float, const_int]) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [sparse_float, const_int], tf.int32) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [sparse_float, const_int], tf.float32) self.assertRaises(ValueError, dtype_util.assert_same_float_dtype, [const_int]) def test_size(self): self.assertEqual(dtype_util.size(tf.int32), 4) self.assertEqual(dtype_util.size(tf.int64), 8) self.assertEqual(dtype_util.size(tf.float32), 4) self.assertEqual(dtype_util.size(tf.float64), 8) self.assertEqual(dtype_util.size(np.int32), 4) self.assertEqual(dtype_util.size(np.int64), 8) self.assertEqual(dtype_util.size(np.float32), 4) self.assertEqual(dtype_util.size(np.float64), 8) if __name__ == '__main__': test_util.main()
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from logging import getLogger import operator as op import re from ..common.compat import string_types, zip, zip_longest, text_type from ..exceptions import CondaValueError, InvalidVersionSpecError try: from cytoolz.functoolz import excepts except ImportError: # pragma: no cover from .._vendor.toolz.functoolz import excepts log = getLogger(__name__) # normalized_version() is needed by conda-env # It is currently being pulled from resolve instead, but # eventually it ought to come from here def normalized_version(version): return VersionOrder(version) def ver_eval(vtest, spec): return VersionSpec(spec).match(vtest) version_check_re = re.compile(r'^[\*\.\+!_0-9a-z]+$') version_split_re = re.compile('([0-9]+|[*]+|[^0-9*]+)') version_cache = {} class VersionOrder(object): """ This class implements an order relation between version strings. Version strings can contain the usual alphanumeric characters (A-Za-z0-9), separated into components by dots and underscores. Empty segments (i.e. two consecutive dots, a leading/trailing underscore) are not permitted. An optional epoch number - an integer followed by '!' - can preceed the actual version string (this is useful to indicate a change in the versioning scheme itself). Version comparison is case-insensitive. Conda supports six types of version strings: * Release versions contain only integers, e.g. '1.0', '2.3.5'. * Pre-release versions use additional letters such as 'a' or 'rc', for example '1.0a1', '1.2.beta3', '2.3.5rc3'. * Development versions are indicated by the string 'dev', for example '1.0dev42', '2.3.5.dev12'. * Post-release versions are indicated by the string 'post', for example '1.0post1', '2.3.5.post2'. * Tagged versions have a suffix that specifies a particular property of interest, e.g. '1.1.parallel'. Tags can be added to any of the preceding four types. As far as sorting is concerned, tags are treated like strings in pre-release versions. * An optional local version string separated by '+' can be appended to the main (upstream) version string. It is only considered in comparisons when the main versions are equal, but otherwise handled in exactly the same manner. To obtain a predictable version ordering, it is crucial to keep the version number scheme of a given package consistent over time. Specifically, * version strings should always have the same number of components (except for an optional tag suffix or local version string), * letters/strings indicating non-release versions should always occur at the same position. Before comparison, version strings are parsed as follows: * They are first split into epoch, version number, and local version number at '!' and '+' respectively. If there is no '!', the epoch is set to 0. If there is no '+', the local version is empty. * The version part is then split into components at '.' and '_'. * Each component is split again into runs of numerals and non-numerals * Subcomponents containing only numerals are converted to integers. * Strings are converted to lower case, with special treatment for 'dev' and 'post'. * When a component starts with a letter, the fillvalue 0 is inserted to keep numbers and strings in phase, resulting in '1.1.a1' == 1.1.0a1'. * The same is repeated for the local version part. Examples: 1.2g.beta15.rc => [[0], [1], [2, 'g'], [0, 'beta', 15], [0, 'rc']] 1!2.15.1_ALPHA => [[1], [2], [15], [1, '_alpha']] The resulting lists are compared lexicographically, where the following rules are applied to each pair of corresponding subcomponents: * integers are compared numerically * strings are compared lexicographically, case-insensitive * strings are smaller than integers, except * 'dev' versions are smaller than all corresponding versions of other types * 'post' versions are greater than all corresponding versions of other types * if a subcomponent has no correspondent, the missing correspondent is treated as integer 0 to ensure '1.1' == '1.1.0'. The resulting order is: 0.4 < 0.4.0 < 0.4.1.rc == 0.4.1.RC # case-insensitive comparison < 0.4.1 < 0.5a1 < 0.5b3 < 0.5C1 # case-insensitive comparison < 0.5 < 0.9.6 < 0.960923 < 1.0 < 1.1dev1 # special case 'dev' < 1.1a1 < 1.1.0dev1 # special case 'dev' == 1.1.dev1 # 0 is inserted before string < 1.1.a1 < 1.1.0rc1 < 1.1.0 == 1.1 < 1.1.0post1 # special case 'post' == 1.1.post1 # 0 is inserted before string < 1.1post1 # special case 'post' < 1996.07.12 < 1!0.4.1 # epoch increased < 1!3.1.1.6 < 2!0.4.1 # epoch increased again Some packages (most notably openssl) have incompatible version conventions. In particular, openssl interprets letters as version counters rather than pre-release identifiers. For openssl, the relation 1.0.1 < 1.0.1a => True # for openssl holds, whereas conda packages use the opposite ordering. You can work-around this problem by appending a dash to plain version numbers: 1.0.1a => 1.0.1post.a # ensure correct ordering for openssl """ def __new__(cls, vstr): if isinstance(vstr, cls): return vstr self = version_cache.get(vstr) if self is not None: return self message = "Malformed version string '%s': " % vstr # version comparison is case-insensitive version = vstr.strip().rstrip().lower() # basic validity checks if version == '': raise CondaValueError("Empty version string.") invalid = not version_check_re.match(version) if invalid and '-' in version and '_' not in version: # Allow for dashes as long as there are no underscores # as well, by converting the former to the latter. version = version.replace('-', '_') invalid = not version_check_re.match(version) if invalid: raise CondaValueError(message + "invalid character(s).") self = version_cache.get(version) if self is not None: version_cache[vstr] = self return self # when fillvalue == 0 => 1.1 == 1.1.0 # when fillvalue == -1 => 1.1 < 1.1.0 self = version_cache[vstr] = version_cache[version] = object.__new__(cls) self.norm_version = version self.fillvalue = 0 # find epoch version = version.split('!') if len(version) == 1: # epoch not given => set it to '0' epoch = ['0'] elif len(version) == 2: # epoch given, must be an integer if not version[0].isdigit(): raise CondaValueError(message + "epoch must be an integer.") epoch = [version[0]] else: raise CondaValueError(message + "duplicated epoch separator '!'.") # find local version string version = version[-1].split('+') if len(version) == 1: # no local version self.local = [] elif len(version) == 2: # local version given self.local = version[1].replace('_', '.').split('.') else: raise CondaValueError(message + "duplicated local version separator '+'.") # split version self.version = epoch + version[0].replace('_', '.').split('.') # split components into runs of numerals and non-numerals, # convert numerals to int, handle special strings for v in (self.version, self.local): for k in range(len(v)): c = version_split_re.findall(v[k]) if not c: raise CondaValueError(message + "empty version component.") for j in range(len(c)): if c[j].isdigit(): c[j] = int(c[j]) elif c[j] == 'post': # ensure number < 'post' == infinity c[j] = float('inf') elif c[j] == 'dev': # ensure '*' < 'DEV' < '_' < 'a' < number # by upper-casing (all other strings are lower case) c[j] = 'DEV' if v[k][0].isdigit(): v[k] = c else: # components shall start with a number to keep numbers and # strings in phase => prepend fillvalue v[k] = [self.fillvalue] + c return self def __str__(self): return self.norm_version def _eq(self, t1, t2): for v1, v2 in zip_longest(t1, t2, fillvalue=[]): for c1, c2 in zip_longest(v1, v2, fillvalue=self.fillvalue): if c1 != c2: return False return True def __eq__(self, other): return (self._eq(self.version, other.version) and self._eq(self.local, other.local)) def startswith(self, other): # Tests if the version lists match up to the last element in "other". if other.local: if not self._eq(self.version, other.version): return False t1 = self.local t2 = other.local else: t1 = self.version t2 = other.version nt = len(t2) - 1 if not self._eq(t1[:nt], t2[:nt]): return False v1 = [] if len(t1) <= nt else t1[nt] v2 = t2[nt] nt = len(v2) - 1 if not self._eq([v1[:nt]], [v2[:nt]]): return False c1 = self.fillvalue if len(v1) <= nt else v1[nt] c2 = v2[nt] if isinstance(c2, string_types): return isinstance(c1, string_types) and c1.startswith(c2) return c1 == c2 def __ne__(self, other): return not (self == other) def __lt__(self, other): for t1, t2 in zip([self.version, self.local], [other.version, other.local]): for v1, v2 in zip_longest(t1, t2, fillvalue=[]): for c1, c2 in zip_longest(v1, v2, fillvalue=self.fillvalue): if c1 == c2: continue elif isinstance(c1, string_types): if not isinstance(c2, string_types): # str < int return True elif isinstance(c2, string_types): # not (int < str) return False # c1 and c2 have the same type return c1 < c2 # self == other return False def __gt__(self, other): return other < self def __le__(self, other): return not (other < self) def __ge__(self, other): return not (self < other) # each token slurps up leading whitespace, which we strip out. VSPEC_TOKENS = (r'\s*\^[^$]*[$]|' # regexes r'\s*[()|,]|' # parentheses, logical and, logical or r'[^()|,]+') # everything else def treeify(spec_str): """ Examples: >>> treeify("1.2.3") '1.2.3' >>> treeify("1.2.3,>4.5.6") (',', '1.2.3', '>4.5.6') >>> treeify("1.2.3,4.5.6|<=7.8.9") ('|', (',', '1.2.3', '4.5.6'), '<=7.8.9') >>> treeify("(1.2.3|4.5.6),<=7.8.9") (',', ('|', '1.2.3', '4.5.6'), '<=7.8.9') >>> treeify("((1.5|((1.6|1.7), 1.8), 1.9 |2.0))|2.1") ('|', '1.5', (',', ('|', '1.6', '1.7'), '1.8', '1.9'), '2.0', '2.1') >>> treeify("1.5|(1.6|1.7),1.8,1.9|2.0|2.1") ('|', '1.5', (',', ('|', '1.6', '1.7'), '1.8', '1.9'), '2.0', '2.1') """ # Converts a VersionSpec expression string into a tuple-based # expression tree. assert isinstance(spec_str, string_types) tokens = re.findall(VSPEC_TOKENS, '(%s)' % spec_str) output = [] stack = [] def apply_ops(cstop): # cstop: operators with lower precedence while stack and stack[-1] not in cstop: if len(output) < 2: raise InvalidVersionSpecError(spec_str) c = stack.pop() r = output.pop() # Fuse expressions with the same operator; e.g., # ('|', ('|', a, b), ('|', c, d))becomes # ('|', a, b, c d) # We're playing a bit of a trick here. Instead of checking # if the left or right entries are tuples, we're counting # on the fact that if we _do_ see a string instead, its # first character cannot possibly be equal to the operator. r = r[1:] if r[0] == c else (r,) left = output.pop() left = left[1:] if left[0] == c else (left,) output.append((c,)+left+r) for item in tokens: item = item.strip() if item == '|': apply_ops('(') stack.append('|') elif item == ',': apply_ops('|(') stack.append(',') elif item == '(': stack.append('(') elif item == ')': apply_ops('(') if not stack or stack[-1] != '(': raise InvalidVersionSpecError(spec_str) stack.pop() else: output.append(item) if stack: raise InvalidVersionSpecError(spec_str) return output[0] def untreeify(spec, _inand=False): """ Examples: >>> untreeify('1.2.3') '1.2.3' >>> untreeify((',', '1.2.3', '>4.5.6')) '1.2.3,>4.5.6' >>> untreeify(('|', (',', '1.2.3', '4.5.6'), '<=7.8.9')) '1.2.3,4.5.6|<=7.8.9' >>> untreeify((',', ('|', '1.2.3', '4.5.6'), '<=7.8.9')) '(1.2.3|4.5.6),<=7.8.9' >>> untreeify(('|', '1.5', (',', ('|', '1.6', '1.7'), '1.8', '1.9'), '2.0', '2.1')) '1.5|(1.6|1.7),1.8,1.9|2.0|2.1' """ if isinstance(spec, tuple): if spec[0] == '|': res = '|'.join(map(untreeify, spec[1:])) if _inand: res = '(%s)' % res else: res = ','.join(map(lambda x: untreeify(x, _inand=True), spec[1:])) return res return spec # This RE matches the operators '==', '!=', '<=', '>=', '<', '>' # followed by a version string. It rejects expressions like # '<= 1.2' (space after operator), '<>1.2' (unknown operator), # and '<=!1.2' (nonsensical operator). version_relation_re = re.compile(r'(==|!=|<=|>=|<|>)(?![=<>!])(\S+)$') regex_split_re = re.compile(r'.*[()|,^$]') opdict = {'==': op.__eq__, '!=': op.__ne__, '<=': op.__le__, '>=': op.__ge__, '<': op.__lt__, '>': op.__gt__} class VersionSpec(object): def exact_match_(self, vspec): return self.spec == vspec def regex_match_(self, vspec): return bool(self.regex.match(vspec)) def veval_match_(self, vspec): return self.op(VersionOrder(vspec), self.cmp) def all_match_(self, vspec): return all(s.match(vspec) for s in self.tup) def any_match_(self, vspec): return any(s.match(vspec) for s in self.tup) def triv_match_(self, vspec): return True def __new__(cls, spec): if isinstance(spec, cls): return spec if isinstance(spec, string_types) and regex_split_re.match(spec): spec = treeify(spec) self = object.__new__(cls) if isinstance(spec, tuple): self.tup = tup = tuple(VersionSpec(s) for s in spec[1:]) self.match = self.any_match_ if spec[0] == '|' else self.all_match_ self.spec = untreeify((spec[0],) + tuple(t.spec for t in tup)) self.depth = 2 return self self.depth = 0 self.spec = spec = text_type(spec).strip() if spec.startswith('^') or spec.endswith('$'): if not spec.startswith('^') or not spec.endswith('$'): raise InvalidVersionSpecError(spec) self.regex = re.compile(spec) self.match = self.regex_match_ elif spec.startswith(('=', '<', '>', '!')): m = version_relation_re.match(spec) if m is None: raise InvalidVersionSpecError(spec) op, b = m.groups() self.op = opdict[op] self.cmp = VersionOrder(b) self.match = self.veval_match_ elif spec == '*': self.match = self.triv_match_ elif '*' in spec.rstrip('*'): self.spec = spec rx = spec.replace('.', r'\.') rx = rx.replace('+', r'\+') rx = rx.replace('*', r'.*') rx = r'^(?:%s)$' % rx self.regex = re.compile(rx) self.match = self.regex_match_ elif spec.endswith('*'): if not spec.endswith('.*'): self.spec = spec = spec[:-1] + '.*' self.op = VersionOrder.startswith self.cmp = VersionOrder(spec.rstrip('*').rstrip('.')) self.match = self.veval_match_ elif '@' not in spec: self.op = opdict["=="] self.cmp = VersionOrder(spec) self.match = self.veval_match_ else: self.match = self.exact_match_ return self def is_exact(self): return (self.match == self.exact_match_ or self.match == self.veval_match_ and self.op == op.__eq__) def __eq__(self, other): try: other = VersionSpec(other) return self.spec == other.spec except Exception as e: log.debug('%r', e) return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.spec) def __str__(self): return self.spec def __repr__(self): return "VersionSpec('%s')" % self.spec @property def raw_value(self): return self.spec @property def exact_value(self): return self.is_exact() and self.spec or None def merge(self, other): assert isinstance(other, self.__class__) return self.__class__('%s,%s' % (self.raw_value, other.raw_value)) class BuildNumberMatch(object): def __new__(cls, spec): if isinstance(spec, cls): return spec self = object.__new__(cls) try: spec = int(spec) except ValueError: pass else: self.spec = spec self.match = self.exact_match_ return self _spec = spec self.spec = spec = text_type(spec).strip() if spec == '*': self.match = self.triv_match_ elif spec.startswith(('=', '<', '>', '!')): m = version_relation_re.match(spec) if m is None: raise InvalidVersionSpecError(spec) op, b = m.groups() self.op = opdict[op] self.cmp = VersionOrder(b) self.match = self.veval_match_ elif spec.startswith('^') or spec.endswith('$'): if not spec.startswith('^') or not spec.endswith('$'): raise InvalidVersionSpecError(spec) self.regex = re.compile(spec) self.match = self.regex_match_ elif hasattr(spec, 'match'): self.spec = _spec self.match = spec.match else: self.match = self.exact_match_ return self def exact_match_(self, vspec): try: return int(self.spec) == int(vspec) except ValueError: return False def veval_match_(self, vspec): return self.op(VersionOrder(text_type(vspec)), self.cmp) def triv_match_(self, vspec): return True def regex_match_(self, vspec): return bool(self.regex.match(vspec)) def is_exact(self): return self.match == self.exact_match_ def __eq__(self, other): if isinstance(other, BuildNumberMatch): return self.spec == other.spec return False def __ne__(self, other): if isinstance(other, BuildNumberMatch): return self.spec != other.spec return True def __hash__(self): return hash(self.spec) def __str__(self): return text_type(self.spec) def __repr__(self): # return "BuildNumberSpec('%s')" % self.spec return text_type(self.spec) @property def raw_value(self): return self.spec @property def exact_value(self): return excepts(ValueError, int(self.raw_value)) def merge(self, other): if self.raw_value != other.raw_value: raise ValueError("Incompatible component merge:\n - %r\n - %r" % (self.raw_value, other.raw_value)) return self.raw_value
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """AppInfo tools Library for working with AppInfo records in memory, store and load from configuration files. """ import re from drydrop.app.meta import appinfo_errors from drydrop.app.meta import validation from drydrop.app.meta import yaml_listener from drydrop.app.meta import yaml_builder from drydrop.app.meta import yaml_object _URL_REGEX = r'(?!\^)/|\.|(\(.).*(?!\$).' _FILES_REGEX = r'(?!\^).*(?!\$).' _DELTA_REGEX = r'([1-9][0-9]*)([DdHhMm]|[sS]?)' _EXPIRATION_REGEX = r'\s*(%s)(\s+%s)*\s*' % (_DELTA_REGEX, _DELTA_REGEX) _EXPIRATION_CONVERSIONS = { 'd': 60 * 60 * 24, 'h': 60 * 60, 'm': 60, 's': 1, } APP_ID_MAX_LEN = 100 MAJOR_VERSION_ID_MAX_LEN = 100 MAX_URL_MAPS = 100 APPLICATION_RE_STRING = r'(?!-)[a-z\d\-]{1,%d}' % APP_ID_MAX_LEN VERSION_RE_STRING = r'(?!-)[a-z\d\-]{1,%d}' % MAJOR_VERSION_ID_MAX_LEN HANDLER_STATIC_FILES = 'static_files' HANDLER_STATIC_DIR = 'static_dir' HANDLER_SCRIPT = 'script' LOGIN_OPTIONAL = 'optional' LOGIN_REQUIRED = 'required' LOGIN_ADMIN = 'admin' SECURE_HTTP = 'never' SECURE_HTTPS = 'always' SECURE_HTTP_OR_HTTPS = 'optional' RUNTIME_PYTHON = 'python' DEFAULT_SKIP_FILES = (r"^(.*/)?(" r"(app\.yaml)|" r"(app\.yml)|" r"(index\.yaml)|" r"(index\.yml)|" r"(#.*#)|" r"(.*~)|" r"(.*\.py[co])|" r"(.*/RCS/.*)|" r"(\..*)|" r")$") LOGIN = 'login' SECURE = 'secure' URL = 'url' STATIC_FILES = 'static_files' UPLOAD = 'upload' STATIC_DIR = 'static_dir' MIME_TYPE = 'mime_type' SCRIPT = 'script' EXPIRATION = 'expiration' APPLICATION = 'application' VERSION = 'version' RUNTIME = 'runtime' API_VERSION = 'api_version' HANDLERS = 'handlers' DEFAULT_EXPIRATION = 'default_expiration' SKIP_FILES = 'skip_files' class URLMap(validation.Validated): """Mapping from URLs to handlers. This class acts like something of a union type. Its purpose is to describe a mapping between a set of URLs and their handlers. What handler type a given instance has is determined by which handler-id attribute is used. Each mapping can have one and only one handler type. Attempting to use more than one handler-id attribute will cause an UnknownHandlerType to be raised during validation. Failure to provide any handler-id attributes will cause MissingHandlerType to be raised during validation. The regular expression used by the url field will be used to match against the entire URL path and query string of the request. This means that partial maps will not be matched. Specifying a url, say /admin, is the same as matching against the regular expression '^/admin$'. Don't begin your matching url with ^ or end them with $. These regular expressions won't be accepted and will raise ValueError. Attributes: login: Whether or not login is required to access URL. Defaults to 'optional'. secure: Restriction on the protocol which can be used to serve this URL/handler (HTTP, HTTPS or either). url: Regular expression used to fully match against the request URLs path. See Special Cases for using static_dir. static_files: Handler id attribute that maps URL to the appropriate file. Can use back regex references to the string matched to url. upload: Regular expression used by the application configuration program to know which files are uploaded as blobs. It's very difficult to determine this using just the url and static_files so this attribute must be included. Required when defining a static_files mapping. A matching file name must fully match against the upload regex, similar to how url is matched against the request path. Do not begin upload with ^ or end it with $. static_dir: Handler id that maps the provided url to a sub-directory within the application directory. See Special Cases. mime_type: When used with static_files and static_dir the mime-type of files served from those directories are overridden with this value. script: Handler id that maps URLs to scipt handler within the application directory that will run using CGI. expiration: When used with static files and directories, the time delta to use for cache expiration. Has the form '4d 5h 30m 15s', where each letter signifies days, hours, minutes, and seconds, respectively. The 's' for seconds may be omitted. Only one amount must be specified, combining multiple amounts is optional. Example good values: '10', '1d 6h', '1h 30m', '7d 7d 7d', '5m 30'. Special cases: When defining a static_dir handler, do not use a regular expression in the url attribute. Both the url and static_dir attributes are automatically mapped to these equivalents: <url>/(.*) <static_dir>/\1 For example: url: /images static_dir: images_folder Is the same as this static_files declaration: url: /images/(.*) static_files: images/\1 upload: images/(.*) """ ATTRIBUTES = { URL: validation.Optional(_URL_REGEX), LOGIN: validation.Options(LOGIN_OPTIONAL, LOGIN_REQUIRED, LOGIN_ADMIN, default=LOGIN_OPTIONAL), SECURE: validation.Options(SECURE_HTTP, SECURE_HTTPS, SECURE_HTTP_OR_HTTPS, default=SECURE_HTTP), HANDLER_STATIC_FILES: validation.Optional(_FILES_REGEX), UPLOAD: validation.Optional(_FILES_REGEX), HANDLER_STATIC_DIR: validation.Optional(_FILES_REGEX), MIME_TYPE: validation.Optional(str), EXPIRATION: validation.Optional(_EXPIRATION_REGEX), HANDLER_SCRIPT: validation.Optional(_FILES_REGEX), } COMMON_FIELDS = set([URL, LOGIN, SECURE]) ALLOWED_FIELDS = { HANDLER_STATIC_FILES: (MIME_TYPE, UPLOAD, EXPIRATION), HANDLER_STATIC_DIR: (MIME_TYPE, EXPIRATION), HANDLER_SCRIPT: (), } def GetHandler(self): """Get handler for mapping. Returns: Value of the handler (determined by handler id attribute). """ return getattr(self, self.GetHandlerType()) def GetHandlerType(self): """Get handler type of mapping. Returns: Handler type determined by which handler id attribute is set. Raises: UnknownHandlerType when none of the no handler id attributes are set. UnexpectedHandlerAttribute when an unexpected attribute is set for the discovered handler type. HandlerTypeMissingAttribute when the handler is missing a required attribute for its handler type. """ for id_field in URLMap.ALLOWED_FIELDS.iterkeys(): if getattr(self, id_field) is not None: mapping_type = id_field break else: raise appinfo_errors.UnknownHandlerType( 'Unknown url handler type.\n%s' % str(self)) allowed_fields = URLMap.ALLOWED_FIELDS[mapping_type] for attribute in self.ATTRIBUTES.iterkeys(): if (getattr(self, attribute) is not None and not (attribute in allowed_fields or attribute in URLMap.COMMON_FIELDS or attribute == mapping_type)): raise appinfo_errors.UnexpectedHandlerAttribute( 'Unexpected attribute "%s" for mapping type %s.' % (attribute, mapping_type)) if mapping_type == HANDLER_STATIC_FILES and not self.upload: raise appinfo_errors.MissingHandlerAttribute( 'Missing "%s" attribute for URL "%s".' % (UPLOAD, self.url)) return mapping_type def CheckInitialized(self): """Adds additional checking to make sure handler has correct fields. In addition to normal ValidatedCheck calls GetHandlerType which validates all the handler fields are configured properly. Raises: UnknownHandlerType when none of the no handler id attributes are set. UnexpectedHandlerAttribute when an unexpected attribute is set for the discovered handler type. HandlerTypeMissingAttribute when the handler is missing a required attribute for its handler type. """ super(URLMap, self).CheckInitialized() self.GetHandlerType() class AppInfoExternal(validation.Validated): """Class representing users application info. This class is passed to a yaml_object builder to provide the validation for the application information file format parser. Attributes: application: Unique identifier for application. version: Application's major version number. runtime: Runtime used by application. api_version: Which version of APIs to use. handlers: List of URL handlers. default_expiration: Default time delta to use for cache expiration for all static files, unless they have their own specific 'expiration' set. See the URLMap.expiration field's documentation for more information. skip_files: An re object. Files that match this regular expression will not be uploaded by appcfg.py. For example: skip_files: | .svn.*| #.*# """ ATTRIBUTES = { # APPLICATION: APPLICATION_RE_STRING, # VERSION: VERSION_RE_STRING, # RUNTIME: validation.Options(RUNTIME_PYTHON), # # # API_VERSION: validation.Options('1', 'beta'), HANDLERS: validation.Optional(validation.Repeated(URLMap)), DEFAULT_EXPIRATION: validation.Optional(_EXPIRATION_REGEX), SKIP_FILES: validation.RegexStr(default=DEFAULT_SKIP_FILES) } def CheckInitialized(self): """Ensures that at least one url mapping is provided. Raises: MissingURLMapping when no URLMap objects are present in object. TooManyURLMappings when there are too many URLMap entries. """ super(AppInfoExternal, self).CheckInitialized() if not self.handlers: raise appinfo_errors.MissingURLMapping( 'No URLMap entries found in application configuration') if len(self.handlers) > MAX_URL_MAPS: raise appinfo_errors.TooManyURLMappings( 'Found more than %d URLMap entries in application configuration' % MAX_URL_MAPS) def LoadSingleAppInfo(app_info): """Load a single AppInfo object where one and only one is expected. Args: app_info: A file-like object or string. If it is a string, parse it as a configuration file. If it is a file-like object, read in data and parse. Returns: An instance of AppInfoExternal as loaded from a YAML file. Raises: EmptyConfigurationFile when there are no documents in YAML file. MultipleConfigurationFile when there is more than one document in YAML file. """ builder = yaml_object.ObjectBuilder(AppInfoExternal) handler = yaml_builder.BuilderHandler(builder) listener = yaml_listener.EventListener(handler) listener.Parse(app_info) app_infos = handler.GetResults() if len(app_infos) < 1: raise appinfo_errors.EmptyConfigurationFile() if len(app_infos) > 1: raise appinfo_errors.MultipleConfigurationFile() return app_infos[0] def ParseExpiration(expiration): """Parses an expiration delta string. Args: expiration: String that matches _DELTA_REGEX. Returns: Time delta in seconds. """ delta = 0 for match in re.finditer(_DELTA_REGEX, expiration): amount = int(match.group(1)) units = _EXPIRATION_CONVERSIONS.get(match.group(2).lower(), 1) delta += amount * units return delta _file_path_positive_re = re.compile(r'^[ 0-9a-zA-Z\._\+/\$-]{1,256}$') _file_path_negative_1_re = re.compile(r'\.\.|^\./|\.$|/\./|^-') _file_path_negative_2_re = re.compile(r'//|/$') _file_path_negative_3_re = re.compile(r'^ | $|/ | /') def ValidFilename(filename): """Determines if filename is valid. filename must be a valid pathname. - It must contain only letters, numbers, _, +, /, $, ., and -. - It must be less than 256 chars. - It must not contain "/./", "/../", or "//". - It must not end in "/". - All spaces must be in the middle of a directory or file name. Args: filename: The filename to validate. Returns: An error string if the filename is invalid. Returns '' if the filename is valid. """ if _file_path_positive_re.match(filename) is None: return 'Invalid character in filename: %s' % filename if _file_path_negative_1_re.search(filename) is not None: return ('Filename cannot contain "." or ".." or start with "-": %s' % filename) if _file_path_negative_2_re.search(filename) is not None: return 'Filename cannot have trailing / or contain //: %s' % filename if _file_path_negative_3_re.search(filename) is not None: return 'Any spaces must be in the middle of a filename: %s' % filename return ''
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ') >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> from decimal import Decimal >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError(repr(o) + " is not JSON serializable") ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.6.2' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'OrderedDict', 'simple_first', ] __author__ = 'Bob Ippolito <bob@redivi.com>' from decimal import Decimal from decoder import JSONDecoder, JSONDecodeError from encoder import JSONEncoder, JSONEncoderForHTML from ordered_dict import OrderedDict def _import_c_make_encoder(): return None _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If *indent* is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``True``) then decimal.Decimal will be natively serialized to JSON with full precision. If *namedtuple_as_object* is true (default: ``True``), :class:`tuple` subclasses with ``_asdict()`` methods will be encoded as JSON objects. If *tuple_as_array* is true (default: ``True``), :class:`tuple` (and subclasses) will be encoded as JSON arrays. If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. Note that this is still a lossy operation that will not round-trip correctly and should be used sparingly. If specified, *item_sort_key* is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. This option takes precedence over *sort_keys*. If *sort_keys* is true (default: ``False``), the output of dictionaries will be sorted by item. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not bigint_as_string and not item_sort_key and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``True``) then decimal.Decimal will be natively serialized to JSON with full precision. If *namedtuple_as_object* is true (default: ``True``), :class:`tuple` subclasses with ``_asdict()`` methods will be encoded as JSON objects. If *tuple_as_array* is true (default: ``True``), :class:`tuple` (and subclasses) will be encoded as JSON arrays. If *bigint_as_string* is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. If specified, *item_sort_key* is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. This option takes precendence over *sort_keys*. If *sort_keys* is true (default: ``False``), the output of dictionaries will be sorted by item. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not bigint_as_string and not sort_keys and not item_sort_key and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None, object_pairs_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, use_decimal=use_decimal, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not use_decimal and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant if use_decimal: if parse_float is not None: raise TypeError("use_decimal=True implies parse_float=Decimal") kw['parse_float'] = Decimal return cls(encoding=encoding, **kw).decode(s) def _toggle_speedups(enabled): pass def simple_first(kv): """Helper function to pass to item_sort_key to sort simple elements to the top, then container elements. """ return (isinstance(kv[1], (list, dict, tuple)), kv[0])
########################################################################## # # Copyright 2012 VMware, Inc. # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ##########################################################################/ from dxgi import * D3D10_DEBUG_FEATURE = Flags(UINT, [ "D3D10_DEBUG_FEATURE_FLUSH_PER_RENDER_OP", "D3D10_DEBUG_FEATURE_FINISH_PER_RENDER_OP", "D3D10_DEBUG_FEATURE_PRESENT_PER_RENDER_OP", ]) ID3D10Debug = Interface("ID3D10Debug", IUnknown) ID3D10Debug.methods += [ StdMethod(HRESULT, "SetFeatureMask", [(D3D10_DEBUG_FEATURE, "Mask")]), StdMethod(D3D10_DEBUG_FEATURE, "GetFeatureMask", [], sideeffects=False), StdMethod(HRESULT, "SetPresentPerRenderOpDelay", [(UINT, "Milliseconds")]), StdMethod(UINT, "GetPresentPerRenderOpDelay", [], sideeffects=False), StdMethod(HRESULT, "SetSwapChain", [(ObjPointer(IDXGISwapChain), "pSwapChain")]), StdMethod(HRESULT, "GetSwapChain", [Out(Pointer(ObjPointer(IDXGISwapChain)), "ppSwapChain")]), StdMethod(HRESULT, "Validate", []), ] ID3D10SwitchToRef = Interface("ID3D10SwitchToRef", IUnknown) ID3D10SwitchToRef.methods += [ StdMethod(BOOL, "SetUseRef", [(BOOL, "UseRef")]), StdMethod(BOOL, "GetUseRef", [], sideeffects=False), ] D3D10_MESSAGE_CATEGORY = Enum("D3D10_MESSAGE_CATEGORY", [ "D3D10_MESSAGE_CATEGORY_APPLICATION_DEFINED", "D3D10_MESSAGE_CATEGORY_MISCELLANEOUS", "D3D10_MESSAGE_CATEGORY_INITIALIZATION", "D3D10_MESSAGE_CATEGORY_CLEANUP", "D3D10_MESSAGE_CATEGORY_COMPILATION", "D3D10_MESSAGE_CATEGORY_STATE_CREATION", "D3D10_MESSAGE_CATEGORY_STATE_SETTING", "D3D10_MESSAGE_CATEGORY_STATE_GETTING", "D3D10_MESSAGE_CATEGORY_RESOURCE_MANIPULATION", "D3D10_MESSAGE_CATEGORY_EXECUTION", ]) D3D10_MESSAGE_SEVERITY = Enum("D3D10_MESSAGE_SEVERITY", [ "D3D10_MESSAGE_SEVERITY_CORRUPTION", "D3D10_MESSAGE_SEVERITY_ERROR", "D3D10_MESSAGE_SEVERITY_WARNING", "D3D10_MESSAGE_SEVERITY_INFO", ]) D3D10_MESSAGE_ID = Enum("D3D10_MESSAGE_ID", [ "D3D10_MESSAGE_ID_UNKNOWN", "D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_HAZARD", "D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_HAZARD", "D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_HAZARD", "D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_HAZARD", "D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_HAZARD", "D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_HAZARD", "D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD", "D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_HAZARD", "D3D10_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD", "D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_HAZARD", "D3D10_MESSAGE_ID_STRING_FROM_APPLICATION", "D3D10_MESSAGE_ID_CORRUPTED_THIS", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER1", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER2", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER3", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER4", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER5", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER6", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER7", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER8", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER9", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER10", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER11", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER12", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER13", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER14", "D3D10_MESSAGE_ID_CORRUPTED_PARAMETER15", "D3D10_MESSAGE_ID_CORRUPTED_MULTITHREADING", "D3D10_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY", "D3D10_MESSAGE_ID_IASETINPUTLAYOUT_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_IASETINDEXBUFFER_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_VSSETSHADER_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_VSSETSHADERRESOURCES_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_VSSETSAMPLERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_GSSETSHADER_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_GSSETSHADERRESOURCES_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_GSSETSAMPLERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_SOSETTARGETS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_PSSETSHADER_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_PSSETSHADERRESOURCES_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_PSSETSAMPLERS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_RSSETSTATE_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_OMSETBLENDSTATE_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_OMSETDEPTHSTENCILSTATE_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_OMSETRENDERTARGETS_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_SETPREDICATION_UNBINDDELETINGOBJECT", "D3D10_MESSAGE_ID_GETPRIVATEDATA_MOREDATA", "D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA", "D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN", "D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS", "D3D10_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS", "D3D10_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY", "D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDSAMPLES", "D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDUSAGE", "D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDBINDFLAGS", "D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDMISCFLAGS", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDBINDFLAGS", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDINITIALDATA", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMIPLEVELS", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMISCFLAGS", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATEBUFFER_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATEBUFFER_NULLDESC", "D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCONSTANTBUFFERBINDINGS", "D3D10_MESSAGE_ID_CREATEBUFFER_LARGEALLOCATION", "D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATETEXTURE1D_UNSUPPORTEDFORMAT", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDSAMPLES", "D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDUSAGE", "D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDBINDFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDMISCFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDBINDFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDINITIALDATA", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMIPLEVELS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMISCFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATETEXTURE1D_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATETEXTURE1D_NULLDESC", "D3D10_MESSAGE_ID_CREATETEXTURE1D_LARGEALLOCATION", "D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATETEXTURE2D_UNSUPPORTEDFORMAT", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDSAMPLES", "D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDUSAGE", "D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDBINDFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDMISCFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDBINDFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDINITIALDATA", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMIPLEVELS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMISCFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATETEXTURE2D_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATETEXTURE2D_NULLDESC", "D3D10_MESSAGE_ID_CREATETEXTURE2D_LARGEALLOCATION", "D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATETEXTURE3D_UNSUPPORTEDFORMAT", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDSAMPLES", "D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDUSAGE", "D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDBINDFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDMISCFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDCPUACCESSFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDBINDFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDINITIALDATA", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMIPLEVELS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMISCFLAGS", "D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATETEXTURE3D_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATETEXTURE3D_NULLDESC", "D3D10_MESSAGE_ID_CREATETEXTURE3D_LARGEALLOCATION", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLDESC", "D3D10_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY", "D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE", "D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE", "D3D10_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY", "D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE", "D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_TOOMANYOBJECTS", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC", "D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDQUERY", "D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDMISCFLAGS", "D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_UNEXPECTEDMISCFLAG", "D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_NULLDESC", "D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED", "D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED", "D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_INVALIDBUFFER", "D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_OFFSET_TOO_LARGE", "D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_IASETINDEXBUFFER_INVALIDBUFFER", "D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_FORMAT_INVALID", "D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_TOO_LARGE", "D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_UNALIGNED", "D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_VIEWS_EMPTY", "D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_INVALIDBUFFER", "D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_VSSETSAMPLERS_SAMPLERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_VIEWS_EMPTY", "D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_INVALIDBUFFER", "D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_GSSETSAMPLERS_SAMPLERS_EMPTY", "D3D10_MESSAGE_ID_SOSETTARGETS_INVALIDBUFFER", "D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_OFFSET_UNALIGNED", "D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_VIEWS_EMPTY", "D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_INVALIDBUFFER", "D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_PSSETSAMPLERS_SAMPLERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT", "D3D10_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR", "D3D10_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH", "D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH", "D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID", "D3D10_MESSAGE_ID_DEVICE_IAGETVERTEXBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_VSGETSHADERRESOURCES_VIEWS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_VSGETCONSTANTBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_VSGETSAMPLERS_SAMPLERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_GSGETSHADERRESOURCES_VIEWS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_GSGETCONSTANTBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_GSGETSAMPLERS_SAMPLERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_SOGETTARGETS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_PSGETSHADERRESOURCES_VIEWS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_PSGETCONSTANTBUFFERS_BUFFERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_PSGETSAMPLERS_SAMPLERS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_RSGETVIEWPORTS_VIEWPORTS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_RSGETSCISSORRECTS_RECTS_EMPTY", "D3D10_MESSAGE_ID_DEVICE_GENERATEMIPS_RESOURCE_INVALID", "D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSUBRESOURCE", "D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESUBRESOURCE", "D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCEBOX", "D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCE", "D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSTATE", "D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESTATE", "D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE", "D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE", "D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE", "D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE", "D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX", "D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE", "D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID", "D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID", "D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID", "D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID", "D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID", "D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE", "D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS", "D3D10_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED", "D3D10_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN", "D3D10_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED", "D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE", "D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE", "D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS", "D3D10_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED", "D3D10_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN", "D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE", "D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED", "D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE", "D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE", "D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS", "D3D10_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED", "D3D10_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN", "D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE", "D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED", "D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE", "D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE", "D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS", "D3D10_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED", "D3D10_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN", "D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE", "D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED", "D3D10_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED", "D3D10_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED", "D3D10_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS", "D3D10_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN", "D3D10_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE", "D3D10_MESSAGE_ID_REF_THREADING_MODE", "D3D10_MESSAGE_ID_REF_UMDRIVER_EXCEPTION", "D3D10_MESSAGE_ID_REF_KMDRIVER_EXCEPTION", "D3D10_MESSAGE_ID_REF_HARDWARE_EXCEPTION", "D3D10_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE", "D3D10_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER", "D3D10_MESSAGE_ID_REF_OUT_OF_MEMORY", "D3D10_MESSAGE_ID_REF_INFO", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW", "D3D10_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW", "D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW", "D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW", "D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW", "D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND", "D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX", "D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE", "D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK", "D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE", "D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_INPUTLAYOUT_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_TOO_SMALL", "D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_SHADERRESOURCEVIEW_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_VIEW_DIMENSION_MISMATCH", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL", "D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_FORMAT_INVALID", "D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_TOO_SMALL", "D3D10_MESSAGE_ID_DEVICE_DRAW_GS_INPUT_PRIMITIVE_MISMATCH", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_RETURN_TYPE_MISMATCH", "D3D10_MESSAGE_ID_DEVICE_DRAW_POSITION_NOT_PRESENT", "D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_NOT_SET", "D3D10_MESSAGE_ID_DEVICE_DRAW_BOUND_RESOURCE_MAPPED", "D3D10_MESSAGE_ID_DEVICE_DRAW_INVALID_PRIMITIVETOPOLOGY", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_OFFSET_UNALIGNED", "D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_STRIDE_UNALIGNED", "D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_OFFSET_UNALIGNED", "D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED", "D3D10_MESSAGE_ID_DEVICE_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE", "D3D10_MESSAGE_ID_DEVICE_DRAW_SO_STRIDE_LARGER_THAN_BUFFER", "D3D10_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING", "D3D10_MESSAGE_ID_DEVICE_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0", "D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT", "D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT", "D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT", "D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN", "D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN", "D3D10_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC", "D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC", "D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH", "D3D10_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW", "D3D10_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS", "D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH", "D3D10_MESSAGE_ID_BLENDSTATE_GETDESC_LEGACY", "D3D10_MESSAGE_ID_SHADERRESOURCEVIEW_GETDESC_LEGACY", "D3D10_MESSAGE_ID_CREATEQUERY_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATEPREDICATE_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATECOUNTER_OUTOFRANGE_COUNTER", "D3D10_MESSAGE_ID_CREATECOUNTER_SIMULTANEOUS_ACTIVE_COUNTERS_EXHAUSTED", "D3D10_MESSAGE_ID_CREATECOUNTER_UNSUPPORTED_WELLKNOWN_COUNTER", "D3D10_MESSAGE_ID_CREATECOUNTER_OUTOFMEMORY_RETURN", "D3D10_MESSAGE_ID_CREATECOUNTER_NONEXCLUSIVE_RETURN", "D3D10_MESSAGE_ID_CREATECOUNTER_NULLDESC", "D3D10_MESSAGE_ID_CHECKCOUNTER_OUTOFRANGE_COUNTER", "D3D10_MESSAGE_ID_CHECKCOUNTER_UNSUPPORTED_WELLKNOWN_COUNTER", "D3D10_MESSAGE_ID_SETPREDICATION_INVALID_PREDICATE_STATE", "D3D10_MESSAGE_ID_QUERY_BEGIN_UNSUPPORTED", "D3D10_MESSAGE_ID_PREDICATE_BEGIN_DURING_PREDICATION", "D3D10_MESSAGE_ID_QUERY_BEGIN_DUPLICATE", "D3D10_MESSAGE_ID_QUERY_BEGIN_ABANDONING_PREVIOUS_RESULTS", "D3D10_MESSAGE_ID_PREDICATE_END_DURING_PREDICATION", "D3D10_MESSAGE_ID_QUERY_END_ABANDONING_PREVIOUS_RESULTS", "D3D10_MESSAGE_ID_QUERY_END_WITHOUT_BEGIN", "D3D10_MESSAGE_ID_QUERY_GETDATA_INVALID_DATASIZE", "D3D10_MESSAGE_ID_QUERY_GETDATA_INVALID_FLAGS", "D3D10_MESSAGE_ID_QUERY_GETDATA_INVALID_CALL", "D3D10_MESSAGE_ID_DEVICE_DRAW_PS_OUTPUT_TYPE_MISMATCH", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_GATHER_UNSUPPORTED", "D3D10_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN", "D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_STRIDE_TOO_LARGE", "D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_INVALIDRANGE", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_EMPTY_LAYOUT", "D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_SAMPLE_COUNT_MISMATCH", "D3D10_MESSAGE_ID_D3D10_MESSAGES_END", "D3D10_MESSAGE_ID_D3D10L9_MESSAGES_START", "D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_STENCIL_NO_TWO_SIDED", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_DepthBiasClamp_NOT_SUPPORTED", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_NO_COMPARISON_SUPPORT", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_EXCESSIVE_ANISOTROPY", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_BORDER_OUT_OF_RANGE", "D3D10_MESSAGE_ID_VSSETSAMPLERS_NOT_SUPPORTED", "D3D10_MESSAGE_ID_VSSETSAMPLERS_TOO_MANY_SAMPLERS", "D3D10_MESSAGE_ID_PSSETSAMPLERS_TOO_MANY_SAMPLERS", "D3D10_MESSAGE_ID_CREATERESOURCE_NO_ARRAYS", "D3D10_MESSAGE_ID_CREATERESOURCE_NO_VB_AND_IB_BIND", "D3D10_MESSAGE_ID_CREATERESOURCE_NO_TEXTURE_1D", "D3D10_MESSAGE_ID_CREATERESOURCE_DIMENSION_OUT_OF_RANGE", "D3D10_MESSAGE_ID_CREATERESOURCE_NOT_BINDABLE_AS_SHADER_RESOURCE", "D3D10_MESSAGE_ID_OMSETRENDERTARGETS_TOO_MANY_RENDER_TARGETS", "D3D10_MESSAGE_ID_OMSETRENDERTARGETS_NO_DIFFERING_BIT_DEPTHS", "D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_BAD_BUFFER_INDEX", "D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_TOO_MANY_VIEWPORTS", "D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_ADJACENCY_UNSUPPORTED", "D3D10_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_TOO_MANY_SCISSORS", "D3D10_MESSAGE_ID_COPYRESOURCE_ONLY_TEXTURE_2D_WITHIN_GPU_MEMORY", "D3D10_MESSAGE_ID_COPYRESOURCE_NO_TEXTURE_3D_READBACK", "D3D10_MESSAGE_ID_COPYRESOURCE_NO_TEXTURE_ONLY_READBACK", "D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_UNSUPPORTED_FORMAT", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_NO_ALPHA_TO_COVERAGE", "D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_DepthClipEnable_MUST_BE_TRUE", "D3D10_MESSAGE_ID_DRAWINDEXED_STARTINDEXLOCATION_MUST_BE_POSITIVE", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_MUST_USE_LOWEST_LOD", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_MINLOD_MUST_NOT_BE_FRACTIONAL", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_MAXLOD_MUST_BE_FLT_MAX", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_FIRSTARRAYSLICE_MUST_BE_ZERO", "D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_CUBES_MUST_HAVE_6_SIDES", "D3D10_MESSAGE_ID_CREATERESOURCE_NOT_BINDABLE_AS_RENDER_TARGET", "D3D10_MESSAGE_ID_CREATERESOURCE_NO_DWORD_INDEX_BUFFER", "D3D10_MESSAGE_ID_CREATERESOURCE_MSAA_PRECLUDES_SHADER_RESOURCE", "D3D10_MESSAGE_ID_CREATERESOURCE_PRESENTATION_PRECLUDES_SHADER_RESOURCE", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_NO_INDEPENDENT_BLEND_ENABLE", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_NO_INDEPENDENT_WRITE_MASKS", "D3D10_MESSAGE_ID_CREATERESOURCE_NO_STREAM_OUT", "D3D10_MESSAGE_ID_CREATERESOURCE_ONLY_VB_IB_FOR_BUFFERS", "D3D10_MESSAGE_ID_CREATERESOURCE_NO_AUTOGEN_FOR_VOLUMES", "D3D10_MESSAGE_ID_CREATERESOURCE_DXGI_FORMAT_R8G8B8A8_CANNOT_BE_SHARED", "D3D10_MESSAGE_ID_VSSHADERRESOURCES_NOT_SUPPORTED", "D3D10_MESSAGE_ID_GEOMETRY_SHADER_NOT_SUPPORTED", "D3D10_MESSAGE_ID_STREAM_OUT_NOT_SUPPORTED", "D3D10_MESSAGE_ID_TEXT_FILTER_NOT_SUPPORTED", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_NO_SEPARATE_ALPHA_BLEND", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_NO_MRT_BLEND", "D3D10_MESSAGE_ID_CREATEBLENDSTATE_OPERATION_NOT_SUPPORTED", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_NO_MIRRORONCE", "D3D10_MESSAGE_ID_DRAWINSTANCED_NOT_SUPPORTED", "D3D10_MESSAGE_ID_DRAWINDEXEDINSTANCED_NOT_SUPPORTED_BELOW_9_3", "D3D10_MESSAGE_ID_DRAWINDEXED_POINTLIST_UNSUPPORTED", "D3D10_MESSAGE_ID_SETBLENDSTATE_SAMPLE_MASK_CANNOT_BE_ZERO", "D3D10_MESSAGE_ID_CREATERESOURCE_DIMENSION_EXCEEDS_FEATURE_LEVEL_DEFINITION", "D3D10_MESSAGE_ID_CREATERESOURCE_ONLY_SINGLE_MIP_LEVEL_DEPTH_STENCIL_SUPPORTED", "D3D10_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_NEGATIVESCISSOR", "D3D10_MESSAGE_ID_SLOT_ZERO_MUST_BE_D3D10_INPUT_PER_VERTEX_DATA", "D3D10_MESSAGE_ID_CREATERESOURCE_NON_POW_2_MIPMAP", "D3D10_MESSAGE_ID_CREATESAMPLERSTATE_BORDER_NOT_SUPPORTED", "D3D10_MESSAGE_ID_OMSETRENDERTARGETS_NO_SRGB_MRT", "D3D10_MESSAGE_ID_D3D10L9_MESSAGES_END", ]) D3D10_MESSAGE = Struct("D3D10_MESSAGE", [ (D3D10_MESSAGE_CATEGORY, "Category"), (D3D10_MESSAGE_SEVERITY, "Severity"), (D3D10_MESSAGE_ID, "ID"), (ConstCString, "pDescription"), (SIZE_T, "DescriptionByteLength"), ]) D3D10_INFO_QUEUE_FILTER_DESC = Struct("D3D10_INFO_QUEUE_FILTER_DESC", [ (UINT, "NumCategories"), (Array(D3D10_MESSAGE_CATEGORY, "{self}.NumCategories"), "pCategoryList"), (UINT, "NumSeverities"), (Array(D3D10_MESSAGE_SEVERITY, "{self}.NumSeverities"), "pSeverityList"), (UINT, "NumIDs"), (Array(D3D10_MESSAGE_ID, "{self}.NumIDs"), "pIDList"), ]) D3D10_INFO_QUEUE_FILTER = Struct("D3D10_INFO_QUEUE_FILTER", [ (D3D10_INFO_QUEUE_FILTER_DESC, "AllowList"), (D3D10_INFO_QUEUE_FILTER_DESC, "DenyList"), ]) ID3D10InfoQueue = Interface("ID3D10InfoQueue", IUnknown) ID3D10InfoQueue.methods += [ StdMethod(HRESULT, "SetMessageCountLimit", [(UINT64, "MessageCountLimit")], sideeffects=False), StdMethod(Void, "ClearStoredMessages", [], sideeffects=False), StdMethod(HRESULT, "GetMessage", [(UINT64, "MessageIndex"), Out(Pointer(D3D10_MESSAGE), "pMessage"), Out(Pointer(SIZE_T), "pMessageByteLength")], sideeffects=False), StdMethod(UINT64, "GetNumMessagesAllowedByStorageFilter", [], sideeffects=False), StdMethod(UINT64, "GetNumMessagesDeniedByStorageFilter", [], sideeffects=False), StdMethod(UINT64, "GetNumStoredMessages", [], sideeffects=False), StdMethod(UINT64, "GetNumStoredMessagesAllowedByRetrievalFilter", [], sideeffects=False), StdMethod(UINT64, "GetNumMessagesDiscardedByMessageCountLimit", [], sideeffects=False), StdMethod(UINT64, "GetMessageCountLimit", [], sideeffects=False), StdMethod(HRESULT, "AddStorageFilterEntries", [(Pointer(D3D10_INFO_QUEUE_FILTER), "pFilter")], sideeffects=False), StdMethod(HRESULT, "GetStorageFilter", [Out(Pointer(D3D10_INFO_QUEUE_FILTER), "pFilter"), Out(Pointer(SIZE_T), "pFilterByteLength")], sideeffects=False), StdMethod(Void, "ClearStorageFilter", [], sideeffects=False), StdMethod(HRESULT, "PushEmptyStorageFilter", [], sideeffects=False), StdMethod(HRESULT, "PushCopyOfStorageFilter", [], sideeffects=False), StdMethod(HRESULT, "PushStorageFilter", [(Pointer(D3D10_INFO_QUEUE_FILTER), "pFilter")], sideeffects=False), StdMethod(Void, "PopStorageFilter", [], sideeffects=False), StdMethod(UINT, "GetStorageFilterStackSize", [], sideeffects=False), StdMethod(HRESULT, "AddRetrievalFilterEntries", [(Pointer(D3D10_INFO_QUEUE_FILTER), "pFilter")], sideeffects=False), StdMethod(HRESULT, "GetRetrievalFilter", [Out(Pointer(D3D10_INFO_QUEUE_FILTER), "pFilter"), Out(Pointer(SIZE_T), "pFilterByteLength")], sideeffects=False), StdMethod(Void, "ClearRetrievalFilter", [], sideeffects=False), StdMethod(HRESULT, "PushEmptyRetrievalFilter", [], sideeffects=False), StdMethod(HRESULT, "PushCopyOfRetrievalFilter", [], sideeffects=False), StdMethod(HRESULT, "PushRetrievalFilter", [(Pointer(D3D10_INFO_QUEUE_FILTER), "pFilter")], sideeffects=False), StdMethod(Void, "PopRetrievalFilter", [], sideeffects=False), StdMethod(UINT, "GetRetrievalFilterStackSize", [], sideeffects=False), StdMethod(HRESULT, "AddMessage", [(D3D10_MESSAGE_CATEGORY, "Category"), (D3D10_MESSAGE_SEVERITY, "Severity"), (D3D10_MESSAGE_ID, "ID"), (LPCSTR, "pDescription")], sideeffects=False), StdMethod(HRESULT, "AddApplicationMessage", [(D3D10_MESSAGE_SEVERITY, "Severity"), (LPCSTR, "pDescription")], sideeffects=False), StdMethod(HRESULT, "SetBreakOnCategory", [(D3D10_MESSAGE_CATEGORY, "Category"), (BOOL, "bEnable")], sideeffects=False), StdMethod(HRESULT, "SetBreakOnSeverity", [(D3D10_MESSAGE_SEVERITY, "Severity"), (BOOL, "bEnable")], sideeffects=False), StdMethod(HRESULT, "SetBreakOnID", [(D3D10_MESSAGE_ID, "ID"), (BOOL, "bEnable")], sideeffects=False), StdMethod(BOOL, "GetBreakOnCategory", [(D3D10_MESSAGE_CATEGORY, "Category")], sideeffects=False), StdMethod(BOOL, "GetBreakOnSeverity", [(D3D10_MESSAGE_SEVERITY, "Severity")], sideeffects=False), StdMethod(BOOL, "GetBreakOnID", [(D3D10_MESSAGE_ID, "ID")], sideeffects=False), StdMethod(Void, "SetMuteDebugOutput", [(BOOL, "bMute")], sideeffects=False), StdMethod(BOOL, "GetMuteDebugOutput", [], sideeffects=False), ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # periodsearch.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Feb 2019 ''' This contains functions to run period-finding in a parallelized manner on large collections of light curves. ''' ############# ## LOGGING ## ############# import logging from astrobase import log_sub, log_fmt, log_date_fmt DEBUG = False if DEBUG: level = logging.DEBUG else: level = logging.INFO LOGGER = logging.getLogger(__name__) logging.basicConfig( level=level, style=log_sub, format=log_fmt, datefmt=log_date_fmt, ) LOGDEBUG = LOGGER.debug LOGINFO = LOGGER.info LOGWARNING = LOGGER.warning LOGERROR = LOGGER.error LOGEXCEPTION = LOGGER.exception ############# ## IMPORTS ## ############# import pickle import os import os.path import glob import multiprocessing as mp from concurrent.futures import ProcessPoolExecutor from tornado.escape import squeeze # to turn a list of keys into a dict address # from https://stackoverflow.com/a/14692747 from functools import reduce from operator import getitem def _dict_get(datadict, keylist): return reduce(getitem, keylist, datadict) import numpy as np ################### ## LOCAL IMPORTS ## ################### from astrobase.lcmath import normalize_magseries from astrobase import periodbase from astrobase.periodbase.kbls import bls_snr from astrobase.lcproc import get_lcformat ############ ## CONFIG ## ############ NCPUS = mp.cpu_count() # used to figure out which period finder to run given a list of methods PFMETHODS = {'bls':periodbase.bls_parallel_pfind, 'gls':periodbase.pgen_lsp, 'aov':periodbase.aov_periodfind, 'mav':periodbase.aovhm_periodfind, 'pdm':periodbase.stellingwerf_pdm, 'acf':periodbase.macf_period_find, 'win':periodbase.specwindow_lsp} PFMETHOD_NAMES = { 'gls':'Generalized Lomb-Scargle periodogram', 'pdm':'Stellingwerf phase-dispersion minimization', 'aov':'Schwarzenberg-Czerny AoV', 'mav':'Schwarzenberg-Czerny AoV multi-harmonic', 'bls':'Box Least-squared Search', 'acf':'McQuillan+ ACF Period Search', 'win':'Timeseries Sampling Lomb-Scargle periodogram' } ############################# ## RUNNING PERIOD SEARCHES ## ############################# def runpf(lcfile, outdir, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, pfmethods=('gls','pdm','mav','win'), pfkwargs=({},{},{},{}), sigclip=10.0, getblssnr=False, nworkers=NCPUS, minobservations=500, excludeprocessed=False, raiseonfail=False): '''This runs the period-finding for a single LC. Parameters ---------- lcfile : str The light curve file to run period-finding on. outdir : str The output directory where the result pickle will go. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. pfmethods : list of str This is a list of period finding methods to run. Each element is a string matching the keys of the `PFMETHODS` dict above. By default, this runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram. pfkwargs : list of dicts This is used to provide any special kwargs as dicts to each period-finding method function specified in `pfmethods`. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. getblssnr : bool If this is True and BLS is one of the methods specified in `pfmethods`, will also calculate the stats for each best period in the BLS results: transit depth, duration, ingress duration, refit period and epoch, and the SNR of the transit. nworkers : int The number of parallel period-finding workers to launch. minobservations : int The minimum number of finite LC points required to process a light curve. excludeprocessed : bool If this is True, light curves that have existing period-finding result pickles in `outdir` will not be processed. FIXME: currently, this uses a dumb method of excluding already-processed files. A smarter way to do this is to (i) generate a SHA512 cachekey based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols', 'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make sure all list kwargs in the dict are sorted, (iii) check if the output file has the same cachekey in its filename (last 8 chars of cachekey should work), so the result was processed in exactly the same way as specifed in the input to this function, and can therefore be ignored. Will implement this later. raiseonfail : bool If something fails and this is True, will raise an Exception instead of returning None at the end. Returns ------- str The path to the output period-finding result pickle. ''' try: formatinfo = get_lcformat(lcformat, use_lcformat_dir=lcformatdir) if formatinfo: (dfileglob, readerfunc, dtimecols, dmagcols, derrcols, magsarefluxes, normfunc) = formatinfo else: LOGERROR("can't figure out the light curve format") return None except Exception: LOGEXCEPTION("can't figure out the light curve format") return None # override the default timecols, magcols, and errcols # using the ones provided to the function if timecols is None: timecols = dtimecols if magcols is None: magcols = dmagcols if errcols is None: errcols = derrcols try: # get the LC into a dict lcdict = readerfunc(lcfile) # this should handle lists/tuples being returned by readerfunc # we assume that the first element is the actual lcdict # FIXME: figure out how to not need this assumption if ( (isinstance(lcdict, (list, tuple))) and (isinstance(lcdict[0], dict)) ): lcdict = lcdict[0] outfile = os.path.join(outdir, 'periodfinding-%s.pkl' % squeeze(lcdict['objectid']).replace(' ', '-')) # if excludeprocessed is True, return the output file if it exists and # has a size that is at least 100 kilobytes (this should be enough to # contain the minimal results of this function). if excludeprocessed: test_outfile = os.path.exists(outfile) test_outfile_gz = os.path.exists(outfile+'.gz') if (test_outfile and os.stat(outfile).st_size > 102400): LOGWARNING('periodfinding result for %s already exists at %s, ' 'skipping because excludeprocessed=True' % (lcfile, outfile)) return outfile elif (test_outfile_gz and os.stat(outfile+'.gz').st_size > 102400): LOGWARNING( 'gzipped periodfinding result for %s already ' 'exists at %s, skipping because excludeprocessed=True' % (lcfile, outfile+'.gz') ) return outfile+'.gz' # this is the final returndict resultdict = { 'objectid':lcdict['objectid'], 'lcfbasename':os.path.basename(lcfile), 'kwargs':{'timecols':timecols, 'magcols':magcols, 'errcols':errcols, 'lcformat':lcformat, 'lcformatdir':lcformatdir, 'pfmethods':pfmethods, 'pfkwargs':pfkwargs, 'sigclip':sigclip, 'getblssnr':getblssnr} } # normalize using the special function if specified if normfunc is not None: lcdict = normfunc(lcdict) for tcol, mcol, ecol in zip(timecols, magcols, errcols): # dereference the columns and get them from the lcdict if '.' in tcol: tcolget = tcol.split('.') else: tcolget = [tcol] times = _dict_get(lcdict, tcolget) if '.' in mcol: mcolget = mcol.split('.') else: mcolget = [mcol] mags = _dict_get(lcdict, mcolget) if '.' in ecol: ecolget = ecol.split('.') else: ecolget = [ecol] errs = _dict_get(lcdict, ecolget) # normalize here if not using special normalization if normfunc is None: ntimes, nmags = normalize_magseries( times, mags, magsarefluxes=magsarefluxes ) times, mags, errs = ntimes, nmags, errs # run each of the requested period-finder functions resultdict[mcol] = {} # check if we have enough non-nan observations to proceed finmags = mags[np.isfinite(mags)] if finmags.size < minobservations: LOGERROR('not enough non-nan observations for ' 'this LC. have: %s, required: %s, ' 'magcol: %s, skipping...' % (finmags.size, minobservations, mcol)) continue pfmkeys = [] for pfmind, pfm, pfkw in zip(range(len(pfmethods)), pfmethods, pfkwargs): pf_func = PFMETHODS[pfm] # get any optional kwargs for this function pf_kwargs = pfkw pf_kwargs.update({'verbose':False, 'nworkers':nworkers, 'magsarefluxes':magsarefluxes, 'sigclip':sigclip}) # we'll always prefix things with their index to allow multiple # invocations and results from the same period-finder (for # different period ranges, for example). pfmkey = '%s-%s' % (pfmind, pfm) pfmkeys.append(pfmkey) # run this period-finder and save its results to the output dict resultdict[mcol][pfmkey] = pf_func( times, mags, errs, **pf_kwargs ) # # done with running the period finders # # append the pfmkeys list to the magcol dict resultdict[mcol]['pfmethods'] = pfmkeys # check if we need to get the SNR from any BLS pfresults if 'bls' in pfmethods and getblssnr: # we need to scan thru the pfmethods to get to any BLS pfresults for pfmk in resultdict[mcol]['pfmethods']: if 'bls' in pfmk: try: bls = resultdict[mcol][pfmk] # calculate the SNR for the BLS as well blssnr = bls_snr(bls, times, mags, errs, magsarefluxes=magsarefluxes, verbose=False) # add the SNR results to the BLS result dict resultdict[mcol][pfmk].update({ 'snr':blssnr['snr'], 'transitdepth':blssnr['transitdepth'], 'transitduration':blssnr['transitduration'], }) # update the BLS result dict with the refit periods # and epochs using the results from bls_snr resultdict[mcol][pfmk].update({ 'nbestperiods':blssnr['period'], 'epochs':blssnr['epoch'] }) except Exception: LOGEXCEPTION('could not calculate BLS SNR for %s' % lcfile) # add the SNR null results to the BLS result dict resultdict[mcol][pfmk].update({ 'snr':[np.nan,np.nan,np.nan,np.nan,np.nan], 'transitdepth':[np.nan,np.nan,np.nan, np.nan,np.nan], 'transitduration':[np.nan,np.nan,np.nan, np.nan,np.nan], }) elif 'bls' in pfmethods: # we need to scan thru the pfmethods to get to any BLS pfresults for pfmk in resultdict[mcol]['pfmethods']: if 'bls' in pfmk: # add the SNR null results to the BLS result dict resultdict[mcol][pfmk].update({ 'snr':[np.nan,np.nan,np.nan,np.nan,np.nan], 'transitdepth':[np.nan,np.nan,np.nan, np.nan,np.nan], 'transitduration':[np.nan,np.nan,np.nan, np.nan,np.nan], }) # once all mag cols have been processed, write out the pickle with open(outfile, 'wb') as outfd: pickle.dump(resultdict, outfd, protocol=pickle.HIGHEST_PROTOCOL) return outfile except Exception as e: LOGEXCEPTION('failed to run for %s, because: %s' % (lcfile, e)) if raiseonfail: raise return None def _runpf_worker(task): ''' This runs the runpf function. ''' (lcfile, outdir, timecols, magcols, errcols, lcformat, lcformatdir, pfmethods, pfkwargs, getblssnr, sigclip, nworkers, minobservations, excludeprocessed) = task if os.path.exists(lcfile): pfresult = runpf(lcfile, outdir, timecols=timecols, magcols=magcols, errcols=errcols, lcformat=lcformat, lcformatdir=lcformatdir, pfmethods=pfmethods, pfkwargs=pfkwargs, getblssnr=getblssnr, sigclip=sigclip, nworkers=nworkers, minobservations=minobservations, excludeprocessed=excludeprocessed) return pfresult else: LOGERROR('LC does not exist for requested file %s' % lcfile) return None def parallel_pf(lclist, outdir, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, pfmethods=('gls','pdm','mav','win'), pfkwargs=({},{},{},{}), sigclip=10.0, getblssnr=False, nperiodworkers=NCPUS, ncontrolworkers=1, liststartindex=None, listmaxobjects=None, minobservations=500, excludeprocessed=True): '''This drives the overall parallel period processing for a list of LCs. As a rough benchmark, 25000 HATNet light curves with up to 50000 points per LC take about 26 days in total for an invocation of this function using GLS+PDM+BLS, 10 periodworkers, and 4 controlworkers (so all 40 'cores') on a 2 x Xeon E5-2660v3 machine. Parameters ---------- lclist : list of str The list of light curve file to process. outdir : str The output directory where the period-finding result pickles will go. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. pfmethods : list of str This is a list of period finding methods to run. Each element is a string matching the keys of the `PFMETHODS` dict above. By default, this runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram. pfkwargs : list of dicts This is used to provide any special kwargs as dicts to each period-finding method function specified in `pfmethods`. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. getblssnr : bool If this is True and BLS is one of the methods specified in `pfmethods`, will also calculate the stats for each best period in the BLS results: transit depth, duration, ingress duration, refit period and epoch, and the SNR of the transit. nperiodworkers : int The number of parallel period-finding workers to launch per object task. ncontrolworkers : int The number of controlling processes to launch. This effectively sets how many objects from `lclist` will be processed in parallel. liststartindex : int or None This sets the index from where to start in `lclist`. listmaxobjects : int or None This sets the maximum number of objects in `lclist` to run period-finding for in this invocation. Together with `liststartindex`, `listmaxobjects` can be used to distribute processing over several independent machines if the number of light curves is very large. minobservations : int The minimum number of finite LC points required to process a light curve. excludeprocessed : bool If this is True, light curves that have existing period-finding result pickles in `outdir` will not be processed. FIXME: currently, this uses a dumb method of excluding already-processed files. A smarter way to do this is to (i) generate a SHA512 cachekey based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols', 'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make sure all list kwargs in the dict are sorted, (iii) check if the output file has the same cachekey in its filename (last 8 chars of cachekey should work), so the result was processed in exactly the same way as specifed in the input to this function, and can therefore be ignored. Will implement this later. Returns ------- list of str A list of the period-finding pickles created for all of input LCs processed. ''' # make the output directory if it doesn't exist if not os.path.exists(outdir): os.makedirs(outdir) if (liststartindex is not None) and (listmaxobjects is None): lclist = lclist[liststartindex:] elif (liststartindex is None) and (listmaxobjects is not None): lclist = lclist[:listmaxobjects] elif (liststartindex is not None) and (listmaxobjects is not None): lclist = lclist[liststartindex:liststartindex+listmaxobjects] tasklist = [(x, outdir, timecols, magcols, errcols, lcformat, lcformatdir, pfmethods, pfkwargs, getblssnr, sigclip, nperiodworkers, minobservations, excludeprocessed) for x in lclist] with ProcessPoolExecutor(max_workers=ncontrolworkers) as executor: resultfutures = executor.map(_runpf_worker, tasklist) results = list(resultfutures) return results def parallel_pf_lcdir(lcdir, outdir, fileglob=None, recursive=True, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, pfmethods=('gls','pdm','mav','win'), pfkwargs=({},{},{},{}), sigclip=10.0, getblssnr=False, nperiodworkers=NCPUS, ncontrolworkers=1, liststartindex=None, listmaxobjects=None, minobservations=500, excludeprocessed=True): '''This runs parallel light curve period finding for directory of LCs. Parameters ---------- lcdir : str The directory containing the LCs to process. outdir : str The directory where the resulting period-finding pickles will go. fileglob : str or None The UNIX file glob to use to search for LCs in `lcdir`. If None, the default file glob associated with the registered LC format will be used instead. recursive : bool If True, will search recursively in `lcdir` for light curves to process. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. pfmethods : list of str This is a list of period finding methods to run. Each element is a string matching the keys of the `PFMETHODS` dict above. By default, this runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram. pfkwargs : list of dicts This is used to provide any special kwargs as dicts to each period-finding method function specified in `pfmethods`. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. getblssnr : bool If this is True and BLS is one of the methods specified in `pfmethods`, will also calculate the stats for each best period in the BLS results: transit depth, duration, ingress duration, refit period and epoch, and the SNR of the transit. nperiodworkers : int The number of parallel period-finding workers to launch per object task. ncontrolworkers : int The number of controlling processes to launch. This effectively sets how many objects from `lclist` will be processed in parallel. liststartindex : int or None This sets the index from where to start in `lclist`. listmaxobjects : int or None This sets the maximum number of objects in `lclist` to run period-finding for in this invocation. Together with `liststartindex`, `listmaxobjects` can be used to distribute processing over several independent machines if the number of light curves is very large. minobservations : int The minimum number of finite LC points required to process a light curve. excludeprocessed : bool If this is True, light curves that have existing period-finding result pickles in `outdir` will not be processed. FIXME: currently, this uses a dumb method of excluding already-processed files. A smarter way to do this is to (i) generate a SHA512 cachekey based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols', 'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make sure all list kwargs in the dict are sorted, (iii) check if the output file has the same cachekey in its filename (last 8 chars of cachekey should work), so the result was processed in exactly the same way as specifed in the input to this function, and can therefore be ignored. Will implement this later. Returns ------- list of str A list of the period-finding pickles created for all of input LCs processed. ''' try: formatinfo = get_lcformat(lcformat, use_lcformat_dir=lcformatdir) if formatinfo: (dfileglob, readerfunc, dtimecols, dmagcols, derrcols, magsarefluxes, normfunc) = formatinfo else: LOGERROR("can't figure out the light curve format") return None except Exception: LOGEXCEPTION("can't figure out the light curve format") return None if not fileglob: fileglob = dfileglob # now find the files LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir)) if recursive is False: matching = glob.glob(os.path.join(lcdir, fileglob)) else: matching = glob.glob(os.path.join(lcdir, '**', fileglob),recursive=True) # now that we have all the files, process them if matching and len(matching) > 0: # this helps us process things in deterministic order when we distribute # processing over several machines matching = sorted(matching) LOGINFO('found %s light curves, running pf...' % len(matching)) return parallel_pf(matching, outdir, timecols=timecols, magcols=magcols, errcols=errcols, lcformat=lcformat, lcformatdir=lcformatdir, pfmethods=pfmethods, pfkwargs=pfkwargs, getblssnr=getblssnr, sigclip=sigclip, nperiodworkers=nperiodworkers, ncontrolworkers=ncontrolworkers, liststartindex=liststartindex, listmaxobjects=listmaxobjects, minobservations=minobservations, excludeprocessed=excludeprocessed) else: LOGERROR('no light curve files in %s format found in %s' % (lcformat, lcdir)) return None
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import nest from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import test class DatasetConstructorTest(test.TestCase): def testFromTensors(self): """Test a dataset that represents a single tuple of tensors.""" components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) iterator = (dataset_ops.Dataset.from_tensors(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([c.shape for c in components], [t.shape for t in get_next]) with self.test_session() as sess: sess.run(init_op) results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def assertSparseValuesEqual(self, a, b): self.assertAllEqual(a.indices, b.indices) self.assertAllEqual(a.values, b.values) self.assertAllEqual(a.dense_shape, b.dense_shape) def testFromTensorsSparse(self): """Test a dataset that represents a single tuple of tensors.""" components = (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 1]]), values=np.array([-1, 1]), dense_shape=np.array([2, 2]))) iterator = ( dataset_ops.Dataset.from_tensors(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual( [tensor_shape.TensorShape(c.dense_shape) for c in components], [shape for shape in iterator.output_shapes]) with self.test_session() as sess: sess.run(init_op) results = sess.run(get_next) for component, result_component in zip(components, results): self.assertSparseValuesEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testFromTensorsMixed(self): """Test an dataset that represents a single tuple of tensors.""" components = (np.array(1), np.array([1, 2, 3]), np.array(37.0), sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 1]]), values=np.array([-1, 1]), dense_shape=np.array([2, 2]))) iterator = ( dataset_ops.Dataset.from_tensors(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([ tensor_shape.TensorShape(c.dense_shape) if sparse_tensor.is_sparse(c) else c.shape for c in components ], [shape for shape in iterator.output_shapes]) with self.test_session() as sess: sess.run(init_op) results = sess.run(get_next) for component, result_component in zip(components, results): if sparse_tensor.is_sparse(component): self.assertSparseValuesEqual(component, result_component) else: self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testFromTensorSlices(self): """Test a dataset that represents the slices from a tuple of tensors.""" components = ( np.tile(np.array([[1], [2], [3], [4]]), 20), np.tile( np.array([[12], [13], [14], [15]]), 22), np.array([37.0, 38.0, 39.0, 40.0]) ) iterator = (dataset_ops.Dataset.from_tensor_slices(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([c.shape[1:] for c in components], [t.shape for t in get_next]) with self.test_session() as sess: sess.run(init_op) for i in range(4): results = sess.run(get_next) for component, result_component in zip(components, results): self.assertAllEqual(component[i], result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testFromTensorSlicesSparse(self): """Test a dataset that represents the slices from a tuple of tensors.""" components = (sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 0], [2, 0]]), values=np.array([0, 0, 0]), dense_shape=np.array([3, 1])), sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 1], [2, 2]]), values=np.array([1, 2, 3]), dense_shape=np.array([3, 3]))) iterator = ( dataset_ops.Dataset.from_tensor_slices(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual( [tensor_shape.TensorShape(c.dense_shape[1:]) for c in components], [shape for shape in iterator.output_shapes]) with self.test_session() as sess: sess.run(init_op) expected = [ (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([1]), dense_shape=np.array([3]))), (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[1]]), values=np.array([2]), dense_shape=np.array([3]))), (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[2]]), values=np.array([3]), dense_shape=np.array([3]))), ] for i in range(3): results = sess.run(get_next) for component, result_component in zip(expected[i], results): self.assertSparseValuesEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testFromTensorSlicesMixed(self): """Test a dataset that represents the slices from a tuple of tensors.""" components = (np.tile(np.array([[1], [2], [3]]), 20), np.tile(np.array([[12], [13], [14]]), 22), np.array([37.0, 38.0, 39.0]), sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 0], [2, 0]]), values=np.array([0, 0, 0]), dense_shape=np.array([3, 1])), sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 1], [2, 2]]), values=np.array([1, 2, 3]), dense_shape=np.array([3, 3]))) iterator = ( dataset_ops.Dataset.from_tensor_slices(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual([ tensor_shape.TensorShape(c.dense_shape[1:]) if sparse_tensor.is_sparse(c) else c.shape[1:] for c in components ], [shape for shape in iterator.output_shapes]) with self.test_session() as sess: sess.run(init_op) expected = [ (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([1]), dense_shape=np.array([3]))), (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[1]]), values=np.array([2]), dense_shape=np.array([3]))), (sparse_tensor.SparseTensorValue( indices=np.array([[0]]), values=np.array([0]), dense_shape=np.array([1])), sparse_tensor.SparseTensorValue( indices=np.array([[2]]), values=np.array([3]), dense_shape=np.array([3]))), ] for i in range(3): results = sess.run(get_next) for component, result_component in zip( (list(zip(*components[:3]))[i] + expected[i]), results): if sparse_tensor.is_sparse(component): self.assertSparseValuesEqual(component, result_component) else: self.assertAllEqual(component, result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testFromTensorSlicesWithDict(self): components = {"foo": [1, 2, 3], "bar": [[4.0], [5.0], [6.0]]} iterator = (dataset_ops.Dataset.from_tensor_slices(components) .make_initializable_iterator()) init_op = iterator.initializer get_next = iterator.get_next() self.assertEqual(dtypes.int32, iterator.output_types["foo"]) self.assertEqual(dtypes.float32, iterator.output_types["bar"]) self.assertEqual((), iterator.output_shapes["foo"]) self.assertEqual((1,), iterator.output_shapes["bar"]) with self.test_session() as sess: sess.run(init_op) for i in range(3): results = sess.run(get_next) self.assertEqual(components["foo"][i], results["foo"]) self.assertEqual(components["bar"][i], results["bar"]) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testFromSparseTensorSlices(self): """Test a dataset based on slices of a `tf.SparseTensor`.""" st = array_ops.sparse_placeholder(dtypes.float64) iterator = (dataset_ops.Dataset.from_sparse_tensor_slices(st) .make_initializable_iterator()) init_op = iterator.initializer get_next = sparse_tensor.SparseTensor(*iterator.get_next()) with self.test_session() as sess: slices = [[1., 2., 3.], [1.], [1.], [1., 2.], [], [1., 2.], [], [], []] # Test with sparse tensor in the appropriate order. indices = np.array( [[i, j] for i in range(len(slices)) for j in range(len(slices[i]))]) values = np.array([val for s in slices for val in s]) dense_shape = np.array([len(slices), max(len(s) for s in slices) + 1]) sparse_feed = sparse_tensor.SparseTensorValue(indices, values, dense_shape) sess.run(init_op, feed_dict={st: sparse_feed}) for i, s in enumerate(slices): results = sess.run(get_next) self.assertAllEqual(s, results.values) expected_indices = np.array( [[j] for j in range(len(slices[i]))]).reshape([-1, 1]) self.assertAllEqual(expected_indices, results.indices) self.assertAllEqual(dense_shape[1:], results.dense_shape) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # Test with sparse tensor in the reverse order, which is not # currently supported. reverse_order_indices = indices[::-1, :] reverse_order_values = values[::-1] sparse_feed = sparse_tensor.SparseTensorValue( reverse_order_indices, reverse_order_values, dense_shape) with self.assertRaises(errors.UnimplementedError): sess.run(init_op, feed_dict={st: sparse_feed}) # Test with an empty sparse tensor. empty_indices = np.empty((0, 4), dtype=np.int64) empty_values = np.empty((0,), dtype=np.float64) empty_dense_shape = [0, 4, 37, 9] sparse_feed = sparse_tensor.SparseTensorValue(empty_indices, empty_values, empty_dense_shape) sess.run(init_op, feed_dict={st: sparse_feed}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) # pylint: disable=g-long-lambda,unnecessary-lambda def testNestedStructure(self): components = (np.array([1, 2, 3], dtype=np.int64), (np.array([4., 5.]), np.array([6., 7.])), np.array([8, 9, 10], dtype=np.int64)) dataset = dataset_ops.Dataset.from_tensors(components) self.assertEquals((dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64), dataset.output_types) self.assertEquals(([3], ([2], [2]), [3]), dataset.output_shapes) dataset = dataset.shuffle(10, 10) self.assertEquals((dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64), dataset.output_types) self.assertEquals(([3], ([2], [2]), [3]), dataset.output_shapes) dataset = dataset.repeat(-1) self.assertEquals((dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64), dataset.output_types) self.assertEquals(([3], ([2], [2]), [3]), dataset.output_shapes) dataset = dataset.filter(lambda x, y, z: True) self.assertEquals((dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64), dataset.output_types) self.assertEquals(([3], ([2], [2]), [3]), dataset.output_shapes) dataset = dataset.take(5) self.assertEquals((dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64), dataset.output_types) self.assertEquals(([3], ([2], [2]), [3]), dataset.output_shapes) dataset = dataset.map(lambda x, y, z: ((x, z), (y[0], y[1]))) self.assertEquals(((dtypes.int64, dtypes.int64), (dtypes.float64, dtypes.float64)), dataset.output_types) self.assertEquals((([3], [3]), ([2], [2])), dataset.output_shapes) dataset = dataset.flat_map( lambda x, y: dataset_ops.Dataset.from_tensors(((x[0], x[1]), (y[0], y[1]))) ) self.assertEquals(((dtypes.int64, dtypes.int64), (dtypes.float64, dtypes.float64)), dataset.output_types) self.assertEquals((([3], [3]), ([2], [2])), dataset.output_shapes) dataset = dataset.batch(32) self.assertEquals(((dtypes.int64, dtypes.int64), (dtypes.float64, dtypes.float64)), dataset.output_types) self.assertEquals((([None, 3], [None, 3]), ([None, 2], [None, 2])), nest.pack_sequence_as(dataset.output_shapes, [ s.as_list() for s in nest.flatten(dataset.output_shapes) ])) iterator = dataset.make_one_shot_iterator() (w, x), (y, z) = iterator.get_next() self.assertEquals(dtypes.int64, w.dtype) self.assertEquals(dtypes.int64, x.dtype) self.assertEquals(dtypes.float64, y.dtype) self.assertEquals(dtypes.float64, z.dtype) self.assertEquals([None, 3], w.shape.as_list()) self.assertEquals([None, 3], x.shape.as_list()) self.assertEquals([None, 2], y.shape.as_list()) self.assertEquals([None, 2], z.shape.as_list()) iterator = dataset.make_initializable_iterator() (w, x), (y, z) = iterator.get_next() self.assertEquals(dtypes.int64, w.dtype) self.assertEquals(dtypes.int64, x.dtype) self.assertEquals(dtypes.float64, y.dtype) self.assertEquals(dtypes.float64, z.dtype) self.assertEquals([None, 3], w.shape.as_list()) self.assertEquals([None, 3], x.shape.as_list()) self.assertEquals([None, 2], y.shape.as_list()) self.assertEquals([None, 2], z.shape.as_list()) # Define a separate set of components with matching leading # dimension for the from-slices constructor. components_for_slices = (np.array([1, 2, 3], dtype=np.int64), (np.array([4., 5., 6.]), np.array([7., 8., 9.])), np.array([10, 11, 12], dtype=np.int64)) dataset = dataset_ops.Dataset.from_tensor_slices(components_for_slices) self.assertEquals((dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64), dataset.output_types) self.assertEquals(([], ([], []), []), dataset.output_shapes) def testNestedDict(self): components = {"a": {"aa": 1, "ab": [2.0, 2.0]}, "b": [3, 3, 3]} dataset = dataset_ops.Dataset.from_tensors(components) self.assertEquals(dtypes.int32, dataset.output_types["a"]["aa"]) self.assertEquals(dtypes.float32, dataset.output_types["a"]["ab"]) self.assertEquals(dtypes.int32, dataset.output_types["b"]) self.assertEquals([], dataset.output_shapes["a"]["aa"]) self.assertEquals([2], dataset.output_shapes["a"]["ab"]) self.assertEquals([3], dataset.output_shapes["b"]) def testNonSequenceNestedStructure(self): components = np.array([1, 2, 3], dtype=np.int64) dataset = dataset_ops.Dataset.from_tensors(components) self.assertEquals(dtypes.int64, dataset.output_types) self.assertEquals([3], dataset.output_shapes) dataset = dataset.filter( lambda x: math_ops.reduce_all(math_ops.equal(x, components))) self.assertEquals(dtypes.int64, dataset.output_types) self.assertEquals([3], dataset.output_shapes) dataset = dataset.map(lambda x: array_ops.stack([x, x])) self.assertEquals(dtypes.int64, dataset.output_types) self.assertEquals([2, 3], dataset.output_shapes) dataset = dataset.flat_map( lambda x: dataset_ops.Dataset.from_tensor_slices(x)) self.assertEquals(dtypes.int64, dataset.output_types) self.assertEquals([3], dataset.output_shapes) iterator = dataset.make_one_shot_iterator() get_next = iterator.get_next() self.assertEquals(dtypes.int64, get_next.dtype) self.assertEquals([3], get_next.shape) def testSplitPipelineFailsWithPlacementError(self): with session.Session( target="", config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess: dataset = dataset_ops.Dataset.from_tensors(0) # Define a pipeline that attempts to use variables on two # different devices. # # Initialize the variables before creating to iterator, to avoid the # placement algorithm overriding the DT_RESOURCE colocation constraints. with ops.device("/cpu:0"): var_0 = resource_variable_ops.ResourceVariable(initial_value=0) dataset = dataset.map(lambda x: x + var_0.read_value()) sess.run(var_0.initializer) with ops.device("/cpu:1"): var_1 = resource_variable_ops.ResourceVariable(initial_value=0) dataset = dataset.map(lambda x: x + var_1.read_value()) sess.run(var_1.initializer) iterator = dataset.make_initializable_iterator() sess.run(iterator.initializer) with self.assertRaisesRegexp( errors.FailedPreconditionError, "Error while reading resource variable Variable"): sess.run(iterator.get_next()) class DatasetConstructorBenchmark(test.Benchmark): def benchmarkSliceRepeatBatch(self): input_size = 10000 batch_size = 100 num_epochs = 100 input_data = np.random.randn(input_size) dataset = ( dataset_ops.Dataset.from_tensor_slices(input_data) .repeat(num_epochs + 1).batch(batch_size)) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() with session.Session() as sess: sess.run(iterator.initializer) # Run one whole epoch to burn in the computation. for _ in range(input_size // batch_size): sess.run(next_element) deltas = [] try: while True: start = time.time() sess.run(next_element) deltas.append(time.time() - start) except errors.OutOfRangeError: pass median_wall_time = np.median(deltas) print("Slice/repeat/batch with sess.run() input size: %d batch size: %d " "Median wall time per element: %f" % (input_size, batch_size, median_wall_time)) self.report_benchmark( iters=len(deltas), wall_time=median_wall_time, name="benchmark_slice_repeat_batch_input_%d_batch_%d" % (input_size, batch_size)) def benchmarkSliceRepeatBatchCallable(self): input_size = 10000 batch_size = 100 num_epochs = 100 input_data = np.random.randn(input_size) dataset = ( dataset_ops.Dataset.from_tensor_slices(input_data) .repeat(num_epochs + 1).batch(batch_size)) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() with session.Session() as sess: sess.run(iterator.initializer) get_next_element = sess.make_callable(next_element) # Run one whole epoch to burn in the computation. for _ in range(input_size // batch_size): get_next_element() deltas = [] try: while True: start = time.time() get_next_element() deltas.append(time.time() - start) except errors.OutOfRangeError: pass median_wall_time = np.median(deltas) print( "Slice/repeat/batch with callable input size: %d batch size: %d Median" " wall time per element: %f" % (input_size, batch_size, median_wall_time)) self.report_benchmark( iters=len(deltas), wall_time=median_wall_time, name="benchmark_slice_repeat_batch_callable_input_%d_batch_%d" % (input_size, batch_size)) def benchmarkReshapeSliceRepeatCallable(self): input_size = 10000 batch_size = 100 num_epochs = 100 input_data = np.random.randn(input_size) dataset = ( dataset_ops.Dataset.from_tensor_slices(input_data.reshape(100, 100)) .repeat(num_epochs + 1)) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() with session.Session() as sess: sess.run(iterator.initializer) get_next_element = sess.make_callable(next_element) # Run one whole epoch to burn in the computation. for _ in range(input_size // batch_size): get_next_element() deltas = [] try: while True: start = time.time() get_next_element() deltas.append(time.time() - start) except errors.OutOfRangeError: pass median_wall_time = np.median(deltas) print("Reshape/slice/repeat with callable input size: %d batch size: %d " "Median wall time per element: %f" % (input_size, batch_size, median_wall_time)) self.report_benchmark( iters=len(deltas), wall_time=median_wall_time, name="benchmark_reshape_slice_repeat_callable_input_%d_batch_%d" % (input_size, batch_size)) def benchmarkSliceBatchCacheRepeatCallable(self): input_size = 10000 batch_size = 100 num_epochs = 100 input_data = np.random.randn(input_size) dataset = ( dataset_ops.Dataset.from_tensor_slices(input_data).batch(batch_size) .cache().repeat(num_epochs + 1)) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() with session.Session() as sess: sess.run(iterator.initializer) get_next_element = sess.make_callable(next_element) # Run one whole epoch to burn in the computation. for _ in range(input_size // batch_size): get_next_element() deltas = [] try: while True: start = time.time() get_next_element() deltas.append(time.time() - start) except errors.OutOfRangeError: pass median_wall_time = np.median(deltas) print( "Slice/batch/cache/repeat with callable input size: %d batch size: %d " "Median wall time per element: %f" % (input_size, batch_size, median_wall_time)) self.report_benchmark( iters=len(deltas), wall_time=median_wall_time, name="benchmark_slice_batch_cache_repeat_callable_input_%d_batch_%d" % (input_size, batch_size)) if __name__ == "__main__": test.main()
""" MySQL database backend for Django. Requires MySQLdb: http://sourceforge.net/projects/mysql-python """ from __future__ import unicode_literals import datetime import re import sys import warnings try: import MySQLdb as Database except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) # We want version (1, 2, 1, 'final', 2) or later. We can't just use # lexicographic ordering in this check because then (1, 2, 1, 'gamma') # inadvertently passes the version test. version = Database.version_info if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and (len(version) < 5 or version[3] != 'final' or version[4] < 2))): from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__) from MySQLdb.converters import conversions, Thing2Literal from MySQLdb.constants import FIELD_TYPE, CLIENT try: import pytz except ImportError: pytz = None from django.conf import settings from django.db import utils from django.db.backends import (utils as backend_utils, BaseDatabaseFeatures, BaseDatabaseOperations, BaseDatabaseWrapper) from django.db.backends.mysql.client import DatabaseClient from django.db.backends.mysql.creation import DatabaseCreation from django.db.backends.mysql.introspection import DatabaseIntrospection from django.db.backends.mysql.validation import DatabaseValidation from django.utils.encoding import force_str, force_text from django.db.backends.mysql.schema import DatabaseSchemaEditor from django.utils.functional import cached_property from django.utils.safestring import SafeBytes, SafeText from django.utils import six from django.utils import timezone # Raise exceptions for database warnings if DEBUG is on if settings.DEBUG: warnings.filterwarnings("error", category=Database.Warning) DatabaseError = Database.DatabaseError IntegrityError = Database.IntegrityError # It's impossible to import datetime_or_None directly from MySQLdb.times parse_datetime = conversions[FIELD_TYPE.DATETIME] def parse_datetime_with_timezone_support(value): dt = parse_datetime(value) # Confirm that dt is naive before overwriting its tzinfo. if dt is not None and settings.USE_TZ and timezone.is_naive(dt): dt = dt.replace(tzinfo=timezone.utc) return dt def adapt_datetime_with_timezone_support(value, conv): # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL. if settings.USE_TZ: if timezone.is_naive(value): warnings.warn("MySQL received a naive datetime (%s)" " while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) value = value.astimezone(timezone.utc).replace(tzinfo=None) return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv) # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like # timedelta in terms of actual behavior as they are signed and include days -- # and Django expects time, so we still need to override that. We also need to # add special handling for SafeText and SafeBytes as MySQLdb's type # checking is too tight to catch those (see Django ticket #6052). # Finally, MySQLdb always returns naive datetime objects. However, when # timezone support is active, Django expects timezone-aware datetime objects. django_conversions = conversions.copy() django_conversions.update({ FIELD_TYPE.TIME: backend_utils.typecast_time, FIELD_TYPE.DECIMAL: backend_utils.typecast_decimal, FIELD_TYPE.NEWDECIMAL: backend_utils.typecast_decimal, FIELD_TYPE.DATETIME: parse_datetime_with_timezone_support, datetime.datetime: adapt_datetime_with_timezone_support, }) # This should match the numerical portion of the version numbers (we can treat # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version # at http://dev.mysql.com/doc/refman/4.1/en/news.html and # http://dev.mysql.com/doc/refman/5.0/en/news.html . server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})') # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the # point is to raise Warnings as exceptions, this can be done with the Python # warning module, and this is setup when the connection is created, and the # standard backend_utils.CursorDebugWrapper can be used. Also, using sql_mode # TRADITIONAL will automatically cause most warnings to be treated as errors. class CursorWrapper(object): """ A thin wrapper around MySQLdb's normal cursor class so that we can catch particular exception instances and reraise them with the right types. Implemented as a wrapper, rather than a subclass, so that we aren't stuck to the particular underlying representation returned by Connection.cursor(). """ codes_for_integrityerror = (1048,) def __init__(self, cursor): self.cursor = cursor def execute(self, query, args=None): try: # args is None means no string interpolation return self.cursor.execute(query, args) except Database.OperationalError as e: # Map some error codes to IntegrityError, since they seem to be # misclassified and Django would prefer the more logical place. if e.args[0] in self.codes_for_integrityerror: six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) raise def executemany(self, query, args): try: return self.cursor.executemany(query, args) except Database.OperationalError as e: # Map some error codes to IntegrityError, since they seem to be # misclassified and Django would prefer the more logical place. if e.args[0] in self.codes_for_integrityerror: six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) raise def __getattr__(self, attr): if attr in self.__dict__: return self.__dict__[attr] else: return getattr(self.cursor, attr) def __iter__(self): return iter(self.cursor) def __enter__(self): return self def __exit__(self, type, value, traceback): # Ticket #17671 - Close instead of passing thru to avoid backend # specific behavior. self.close() class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () update_can_self_select = False allows_group_by_pk = True related_fields_match_type = True allow_sliced_subqueries = False has_bulk_insert = True has_select_for_update = True has_select_for_update_nowait = False supports_forward_references = False supports_long_model_names = False supports_microsecond_precision = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True allows_auto_pk_0 = False uses_savepoints = True atomic_transactions = False supports_check_constraints = False def __init__(self, connection): super(DatabaseFeatures, self).__init__(connection) @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE INTROSPECT_TEST (X INT)') # This command is MySQL specific; the second column # will tell you the default table type of the created # table. Since all Django's test tables will have the same # table type, that's enough to evaluate the feature. cursor.execute("SHOW TABLE STATUS WHERE Name='INTROSPECT_TEST'") result = cursor.fetchone() cursor.execute('DROP TABLE INTROSPECT_TEST') return result[1] @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != 'MyISAM' @cached_property def has_zoneinfo_database(self): # MySQL accepts full time zones names (eg. Africa/Nairobi) but rejects # abbreviations (eg. EAT). When pytz isn't installed and the current # time zone is LocalTimezone (the only sensible value in this # context), the current time zone name will be an abbreviation. As a # consequence, MySQL cannot perform time zone conversions reliably. if pytz is None: return False # Test if the time zone definitions are installed. with self.connection.cursor() as cursor: cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1") return cursor.fetchone() is not None class DatabaseOperations(BaseDatabaseOperations): compiler_module = "django.db.backends.mysql.compiler" # MySQL stores positive fields as UNSIGNED ints. integer_field_ranges = dict(BaseDatabaseOperations.integer_field_ranges, PositiveSmallIntegerField=(0, 4294967295), PositiveIntegerField=(0, 18446744073709551615), ) def date_extract_sql(self, lookup_type, field_name): # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type == 'week_day': # DAYOFWEEK() returns an integer, 1-7, Sunday=1. # Note: WEEKDAY() returns 0-6, Monday=0. return "DAYOFWEEK(%s)" % field_name else: return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) def date_trunc_sql(self, lookup_type, field_name): fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields.index(lookup_type) + 1 except ValueError: sql = field_name else: format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) return sql def datetime_extract_sql(self, lookup_type, field_name, tzname): if settings.USE_TZ: field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name params = [tzname] else: params = [] # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type == 'week_day': # DAYOFWEEK() returns an integer, 1-7, Sunday=1. # Note: WEEKDAY() returns 0-6, Monday=0. sql = "DAYOFWEEK(%s)" % field_name else: sql = "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) return sql, params def datetime_trunc_sql(self, lookup_type, field_name, tzname): if settings.USE_TZ: field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name params = [tzname] else: params = [] fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields.index(lookup_type) + 1 except ValueError: sql = field_name else: format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) return sql, params def date_interval_sql(self, sql, connector, timedelta): return "(%s %s INTERVAL '%d 0:0:%d:%d' DAY_MICROSECOND)" % (sql, connector, timedelta.days, timedelta.seconds, timedelta.microseconds) def drop_foreignkey_sql(self): return "DROP FOREIGN KEY" def force_no_ordering(self): """ "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on. """ return ["NULL"] def fulltext_search_sql(self, field_name): return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name def last_executed_query(self, cursor, sql, params): # With MySQLdb, cursor objects have an (undocumented) "_last_executed" # attribute where the exact query sent to the database is saved. # See MySQLdb/cursors.py in the source distribution. return force_text(getattr(cursor, '_last_executed', None), errors='replace') def no_limit_value(self): # 2**64 - 1, as recommended by the MySQL documentation return 18446744073709551615 def quote_name(self, name): if name.startswith("`") and name.endswith("`"): return name # Quoting once is enough. return "`%s`" % name def random_function_sql(self): return 'RAND()' def sql_flush(self, style, tables, sequences, allow_cascade=False): # NB: The generated SQL below is specific to MySQL # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements # to clear all tables of all data if tables: sql = ['SET FOREIGN_KEY_CHECKS = 0;'] for table in tables: sql.append('%s %s;' % ( style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(self.quote_name(table)), )) sql.append('SET FOREIGN_KEY_CHECKS = 1;') sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql else: return [] def sequence_reset_by_name_sql(self, style, sequences): # Truncate already resets the AUTO_INCREMENT field from # MySQL version 5.0.13 onwards. Refs #16961. if self.connection.mysql_version < (5, 0, 13): return [ "%s %s %s %s %s;" % ( style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('TABLE'), style.SQL_TABLE(self.quote_name(sequence['table'])), style.SQL_KEYWORD('AUTO_INCREMENT'), style.SQL_FIELD('= 1'), ) for sequence in sequences ] else: return [] def validate_autopk_value(self, value): # MySQLism: zero in AUTO_INCREMENT field does not work. Refs #17653. if value == 0: raise ValueError('The database backend does not accept 0 as a ' 'value for AutoField.') return value def value_to_db_datetime(self, value): if value is None: return None # MySQL doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = value.astimezone(timezone.utc).replace(tzinfo=None) else: raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.") # MySQL doesn't support microseconds return six.text_type(value.replace(microsecond=0)) def value_to_db_time(self, value): if value is None: return None # MySQL doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("MySQL backend does not support timezone-aware times.") # MySQL doesn't support microseconds return six.text_type(value.replace(microsecond=0)) def year_lookup_bounds_for_datetime_field(self, value): # Again, no microseconds first, second = super(DatabaseOperations, self).year_lookup_bounds_for_datetime_field(value) return [first.replace(microsecond=0), second.replace(microsecond=0)] def max_name_length(self): return 64 def bulk_insert_sql(self, fields, num_values): items_sql = "(%s)" % ", ".join(["%s"] * len(fields)) return "VALUES " + ", ".join([items_sql] * num_values) def combine_expression(self, connector, sub_expressions): """ MySQL requires special cases for ^ operators in query expressions """ if connector == '^': return 'POW(%s)' % ','.join(sub_expressions) return super(DatabaseOperations, self).combine_expression(connector, sub_expressions) class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'mysql' operators = { 'exact': '= %s', 'iexact': 'LIKE %s', 'contains': 'LIKE BINARY %s', 'icontains': 'LIKE %s', 'regex': 'REGEXP BINARY %s', 'iregex': 'REGEXP %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE BINARY %s', 'endswith': 'LIKE BINARY %s', 'istartswith': 'LIKE %s', 'iendswith': 'LIKE %s', } Database = Database def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = DatabaseValidation(self) def get_connection_params(self): kwargs = { 'conv': django_conversions, 'charset': 'utf8', } if six.PY2: kwargs['use_unicode'] = True settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = force_str(settings_dict['PASSWORD']) if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs['client_flag'] = CLIENT.FOUND_ROWS kwargs.update(settings_dict['OPTIONS']) return kwargs def get_new_connection(self, conn_params): conn = Database.connect(**conn_params) conn.encoders[SafeText] = conn.encoders[six.text_type] conn.encoders[SafeBytes] = conn.encoders[bytes] return conn def init_connection_state(self): with self.cursor() as cursor: # SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column # on a recently-inserted row will return when the field is tested for # NULL. Disabling this value brings this aspect of MySQL in line with # SQL standards. cursor.execute('SET SQL_AUTO_IS_NULL = 0') def create_cursor(self): cursor = self.connection.cursor() return CursorWrapper(cursor) def _rollback(self): try: BaseDatabaseWrapper._rollback(self) except Database.NotSupportedError: pass def _set_autocommit(self, autocommit): with self.wrap_database_errors: self.connection.autocommit(autocommit) def disable_constraint_checking(self): """ Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True, to indicate constraint checks need to be re-enabled. """ self.cursor().execute('SET foreign_key_checks=0') return True def enable_constraint_checking(self): """ Re-enable foreign key checks after they have been disabled. """ # Override needs_rollback in case constraint_checks_disabled is # nested inside transaction.atomic. self.needs_rollback, needs_rollback = False, self.needs_rollback try: self.cursor().execute('SET foreign_key_checks=1') finally: self.needs_rollback = needs_rollback def check_constraints(self, table_names=None): """ Checks each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows with invalid references were entered while constraint checks were off. Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides detailed information about the invalid reference in the error message. Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE") """ cursor = self.cursor() if table_names is None: table_names = self.introspection.table_names(cursor) for table_name in table_names: primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name) if not primary_key_column_name: continue key_columns = self.introspection.get_key_columns(cursor, table_name) for column_name, referenced_table_name, referenced_column_name in key_columns: cursor.execute(""" SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING LEFT JOIN `%s` as REFERRED ON (REFERRING.`%s` = REFERRED.`%s`) WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL""" % (primary_key_column_name, column_name, table_name, referenced_table_name, column_name, referenced_column_name, column_name, referenced_column_name)) for bad_row in cursor.fetchall(): raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid " "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s." % (table_name, bad_row[0], table_name, column_name, bad_row[1], referenced_table_name, referenced_column_name)) def schema_editor(self, *args, **kwargs): "Returns a new instance of this backend's SchemaEditor" return DatabaseSchemaEditor(self, *args, **kwargs) def is_usable(self): try: self.connection.ping() except Database.Error: return False else: return True @cached_property def mysql_version(self): with self.temporary_connection(): server_info = self.connection.get_server_info() match = server_version_re.match(server_info) if not match: raise Exception('Unable to determine MySQL version from version string %r' % server_info) return tuple(int(x) for x in match.groups())
#! /usr/bin/python ''' Alessandro Bacchini (allebacco@gmail.com) This file contains debug dumpers / helpers / visualizers so OpenCV classes can be more easily inspected by gdb and QtCreator. To install in gdb, add these lines to ~/.gdbinit ``` python exec(open('<path to opencv_dumper.py>').read()) end ``` ''' import math import numpy as np DEPTH_NAMES = ['CV_8U', 'CV_8S', 'CV_16U', 'CV_16S', 'CV_32S', 'CV_32F', 'CV_64F', 'undefined'] DEPTH_TYPE = ['unsigned char', 'char', 'unsigned short', 'short', 'int', 'float', 'double', 'void'] DEPTH_NP_TYPE = [np.uint8, np.int8, np.uint16, np.int16, np.int32, np.float32, np.float64, np.uint8] DEPTH_PY_TYPE = ['B', 'b', 'H', 'h', 'i', 'f', 'd', 'i'] DEPTH_BYTE_SIZE = [1, 1, 2, 2, 4, 4, 8, 1] def qdump__cv__Mat(self, value): ''' Pretty printer function for cv::Mat class ''' self.putNumChild(1) flags = int(value['flags']) depth = flags & 7 channels = 1 + (flags >> 3) & 63 depth = min(depth, 7) cv_type_name = DEPTH_NAMES[depth] cv_type = DEPTH_TYPE[depth] data_byte_size = DEPTH_BYTE_SIZE[depth] np_dtype = DEPTH_NP_TYPE[depth] cv_type_name += 'C%d' % channels rows = int(value['rows']) cols = int(value['cols']) value_str = '%dx%d %s' % (cols, rows, cv_type_name) refcount = int(value['refcount'].dereference()) if refcount <= 0: value_str = 'unistantiated' elif refcount == 1: value_str += ' unique' else: value_str += ' shared' #self.putValue('%dx%d %s' % (cols, rows, cv_type_name)) self.putValue(value_str) line_step = int(value['step']['p'][0]) if self.isExpanded(): with Children(self): with SubItem(self, 'flags'): self.putValue('%s (0x%X)' % (cv_type_name, flags)) self.putType("int") self.putNumChild(0) self.putSubItem('rows', value['rows']) self.putSubItem('cols', value['cols']) self.putSubItem('allocator', value['allocator']) self.putSubItem('dims', value['dims']) self.putSubItem('refcount', value['refcount']) self.putSubItem('size', value['size']) self.putSubItem('step', value['step']) # Put data array image_data_start = int(value['data']) with SubItem(self, 'data'): vals_type = self.lookupType(cv_type) p = value['data'].cast(vals_type.pointer()) size = cols*rows self.putValue(r'%dx%d (%d, 0x%X)' % (cols, rows, size, int(p)), encoding=0) self.putType(cv_type+'*') size = min(size, 1000) if cols > 0 and rows > 0: self.putNumChild(size) else: self.putNumChild(0) if self.isExpanded(): with Children(self, size, childType=vals_type): s = 0 for i in range(0, rows): for j in range(0, cols): # Limit output to improve performance if s > size: break v = (p + i * cols * channels + j * channels) d = self.readRawMemory(v, channels*data_byte_size) array = np.frombuffer(d, dtype=np_dtype, count=channels) array = np.array_str(array) with SubItem(self, s): self.putName("[%3d,%3d]" % (i, j)) self.putValue(array) s = s + 1 # Limit output to improve performance if s > size: break dataend = 0 with SubItem(self, 'dataend'): p = value['dataend'].cast(self.lookupType('unsigned char').pointer()) dataend = int(p) self.putValue('0x%X' % dataend) self.putType('unsigned char*') self.putNumChild(0) datastart = 0 with SubItem(self, 'datastart'): p = value['datastart'].cast(self.lookupType('unsigned char').pointer()) datastart = int(p) self.putValue('0x%X' % datastart) self.putType('unsigned char*') self.putNumChild(0) with SubItem(self, 'datalimit'): p = value['datalimit'].cast(self.lookupType('unsigned char').pointer()) datalimit = int(p) self.putValue('0x%X' % datalimit) self.putType('unsigned char*') self.putNumChild(0) # Put metadata to improve output informations with SubItem(self, 'stride'): self.putValue(str(line_step)) self.putNumChild(0) # Evaluate the ROI initial_stride = image_data_start-datastart first_row = 0 first_col = 0 if initial_stride > 0: first_row = initial_stride / line_step first_col = int((initial_stride % line_step) / (data_byte_size*channels)) with SubItem(self, 'roi'): self.putValue('[%d,%d][%dx%d]' % (first_col, first_row, cols, rows)) self.putNumChild(4) if self.isExpanded(): with Children(self): with SubItem(self, 'x'): self.putName("x") self.putValue(str(int(first_col))) with SubItem(self, 'y'): self.putName("y") self.putValue(str(int(first_row))) with SubItem(self, 'width'): self.putName("width") self.putValue(str(cols)) with SubItem(self, 'height'): self.putName("height") self.putValue(str(rows)) def qdump__cv__RotatedRect(self, value): ''' Pretty printer function for cv::RotatedRect class ''' self.putNumChild(1) angle = float(value['angle']) x = float(value['center']['x']) y = float(value['center']['y']) width = float(value['size']['width']) height = float(value['size']['height']) self.putValue('[%.2f, %.2f][%.2fx%.2f, %.2f]' % (x, y, width, height, angle)) if self.isExpanded(): with Children(self): self.putSubItem('angle', value['angle']) self.putSubItem('center', value['center']) self.putSubItem('size', value['size']) with SubItem(self, 'area'): self.putValue('%.2f' % (width*height)) self.putNumChild(0) # Put metadata to improve output informations angle_rad = angle * math.pi / 180. b = math.cos(angle_rad) * 0.5 a = math.sin(angle_rad) * 0.5 p0 = (x - a*height - b*width, y + b*height - a*width) p1 = (x + a*height - b*width, y - b*height - a*width) p2 = (2*x - p0[0], 2*y - p0[1]) p3 = (2*x - p1[0], 2*y - p1[1]) points = [p0, p1, p2, p3] with SubItem(self, 'points'): self.putValue('[x, y]') self.putNumChild(1) if self.isExpanded(): with Children(self): for i, p in enumerate(points): name = '[%d]' % i with SubItem(self, name): #self.putName(name) self.putValue(str('[%.2f, %.2f]' % p)) self.putType('cv::Point2f') self.putNumChild(0) with SubItem(self, 'boundingrect'): tl = (min(p0[0], p1[0], p2[0], p3[0]), min(p0[1], p1[1], p2[1], p3[1])) br = (max(p0[0], p1[0], p2[0], p3[0]), max(p0[1], p1[1], p2[1], p3[1])) rWidth = br[0] - tl[0] rHeight = br[1] - tl[1] self.putValue('[%.2f, %.2f][%.2fx%.2f]' % (tl[0], tl[1], rWidth, rHeight)) self.putNumChild(1) if self.isExpanded(): with Children(self): with SubItem(self, 'top left'): self.putValue(str('[%.2f, %.2f]' % tl)) self.putType('cv::Point2f') self.putNumChild(0) with SubItem(self, 'bottom right'): self.putValue(str('[%.2f, %.2f]' % br)) self.putType('cv::Point2f') self.putNumChild(0) with SubItem(self, 'size'): self.putValue(str('[%.2f, %.2f]' % (rWidth, rHeight))) self.putType('cv::Sizef') self.putNumChild(0) with SubItem(self, 'area'): self.putValue('%.2f' % (rWidth*rHeight)) self.putNumChild(0) def qdump__cv__Point_(self, value): ''' Pretty printer function for cv::Point_<Tp> class ''' self.putNumChild(2) try: x = float(value['x']) y = float(value['y']) outValue = '[%.2f, %.2f]' % (x, y) except: x = int(value['x']) y = int(value['y']) outValue = '[%d, %d]' % (x, y) innerType = self.templateArgument(value.type, 0) self.putValue(outValue) if self.isExpanded(): with Children(self): self.putSubItem('x', value['x'].cast(innerType)) self.putSubItem('y', value['y'].cast(innerType)) with SubItem(self, 'module'): self.putValue('%.2f' % (math.sqrt(x*x+y*y))) self.putNumChild(0) with SubItem(self, 'angle'): x = float(x) y = float(y) anglestr = '%.2f' % (math.degrees(math.atan2(y, x))) self.putValue(anglestr) self.putNumChild(0) def qdump__cv__Rect_(self, value): ''' Pretty printer function for cv::Rect_<Tp> class ''' self.putNumChild(2) try: x = float(value['x']) y = float(value['y']) width = float(value['width']) height = float(value['height']) outValue = '[%.2f, %.2f][%.2fx%.2f]' % (x, y, width, height) except: x = int(value['x']) y = int(value['y']) width = int(value['width']) height = int(value['height']) outValue = '[%d, %d][%dx%d]' % (x, y, width, height) innerType = self.templateArgument(value.type, 0) self.putValue(outValue) if self.isExpanded(): with Children(self): self.putSubItem('x', value['x'].cast(innerType)) self.putSubItem('y', value['y'].cast(innerType)) self.putSubItem('width', value['width'].cast(innerType)) self.putSubItem('height', value['height'].cast(innerType)) self.putSubItem('area', '%.2f' % (width*height)) with SubItem(self, 'area'): self.putValue('%.2f' % (width*height)) self.putNumChild(0) def qdump__cv__Size_(self, value): ''' Pretty printer function for cv::Size_<Tp> class ''' self.putNumChild(2) try: width = float(value['width']) height = float(value['height']) outValue = '%.2fx%.2f' % (width, height) except: width = int(value['width']) height = int(value['height']) outValue = '%dx%d' % (width, height) innerType = self.templateArgument(value.type, 0) self.putValue(outValue) if self.isExpanded(): with Children(self): self.putSubItem('width', value['width'].cast(innerType)) self.putSubItem('height', value['height'].cast(innerType))
# basis classes for ccsnmultivar from sklearn.decomposition import FastICA, SparsePCA, DictionaryLearning import numpy as np class PCA(object): """ Performs SVD: Y = USV^\dagger PCA has 4 methods: - fit(waveforms) update class instance with pca fit, done via svd - fit_transform() do what fit() does, but additionally return the projection onto PC space i.e. returns A = U*S - inverse_transform(A) inverses the decomposition, returns waveforms for an input A, using Z returns Y = A*Z^\dagger - get_params() returns metadata used for fits. Number of components (pcs), name of fit ('PCA'), waveform catalog used (if provided) """ def __init__(self, num_components=10,catalog_name='unknown'): self._decomposition = 'PCA' self._num_components = num_components self._catalog_name = catalog_name def fit(self, waveforms): # TODO make sure there are more columns than rows (transpose if not) self._waveforms = waveforms self._do_pca() def fit_transform(self, waveforms): # TODO make sure there are more columns than rows (transpose if not) self._waveforms = waveforms self._do_pca() return self._A def inverse_transform(self,A): # convert basis back to waveforms using fit Z = self._Z # for PCA, (linear) transform just matrix multiplication new_waveforms = np.dot(A,(self._Z).T) return new_waveforms def get_params(self): # return a dictionary with the pca instance metadata params = {} params['Decomposition'] = self._decomposition params['num_components'] = self._num_components return params def get_basis(self): """ Return the PCA basis vectors (Z^\dagger)""" return self._Z def _do_pca(self): U,s,V = np.linalg.svd(self._waveforms,full_matrices=False) Z = V[0:self._num_components,:] Z = np.array(Z.T) A = np.array(np.matrix(U)*np.matrix(np.diag(s))) A = A[:,0:self._num_components] self._A = A self._Z = Z class ICA(object): """ Wrapper for sklearn package. Performs fast ICA (Independent Component Analysis) ICA has 4 methods: - fit(waveforms) update class instance with ICA fit - fit_transform() do what fit() does, but additionally return the projection onto ICA space - inverse_transform(A) inverses the decomposition, returns waveforms for an input A, using Z - get_params() returns metadata used for fits. """ def __init__(self, num_components=10, catalog_name='unknown', whiten=True, fun = 'logcosh', fun_args = None, max_iter = 600, tol = .00001, w_init = None, random_state = None, algorithm = 'parallel'): self._decomposition = 'Fast ICA' self._num_components = num_components self._catalog_name = catalog_name self._whiten = whiten self._fun = fun self._fun_args = fun_args self._max_iter = max_iter self._tol = tol self._w_init = w_init self._random_state = random_state self._algorithm = algorithm self._ICA = FastICA(n_components=self._num_components, whiten = self._whiten, fun = self._fun, fun_args = self._fun_args, max_iter = self._max_iter, tol = self._tol, w_init = self._w_init, random_state = self._random_state, algorithm = self._algorithm) def fit(self,waveforms): # TODO make sure there are more columns than rows (transpose if not) # normalize waveforms self._waveforms = waveforms self._ICA.fit(self._waveforms) def fit_transform(self,waveforms): # TODO make sure there are more columns than rows (transpose if not) # normalize waveforms self._waveforms = waveforms self._A = self._ICA.fit_transform(self._waveforms) return self._A def inverse_transform(self,A): # convert basis back to waveforms using fit new_waveforms = self._ICA.inverse_transform(A) return new_waveforms def get_params(self): # TODO know what catalog was used! (include waveform metadata) params = self._ICA.get_params() params['num_components'] = params.pop('n_components') params['Decompositon'] = self._decomposition return params def get_basis(self): """ Return the ICA basis vectors (Z^\dagger)""" return self._ICA.get_mixing_matrix() class SPCA(object): """ Wrapper for sklearn package. Performs sparse PCA SPCA has 5 methods: - fit(waveforms) update class instance with ICA fit - fit_transform() do what fit() does, but additionally return the projection onto ICA space - inverse_transform(A) inverses the decomposition, returns waveforms for an input A, using Z - get_basis() returns the basis vectors Z^\dagger - get_params() returns metadata used for fits. """ def __init__(self, num_components=10, catalog_name='unknown', alpha = 0.1, ridge_alpha = 0.01, max_iter = 2000, tol = 1e-9, n_jobs = 1, random_state = None): self._decomposition = 'Sparse PCA' self._num_components = num_components self._catalog_name = catalog_name self._alpha = alpha self._ridge_alpha = ridge_alpha self._n_jobs = n_jobs self._max_iter = max_iter self._tol = tol self._random_state = random_state self._SPCA = SparsePCA(n_components=self._num_components, alpha = self._alpha, ridge_alpha = self._ridge_alpha, n_jobs = self._n_jobs, max_iter = self._max_iter, tol = self._tol, random_state = self._random_state) def fit(self,waveforms): # TODO make sure there are more columns than rows (transpose if not) # normalize waveforms self._waveforms = waveforms self._SPCA.fit(self._waveforms) def fit_transform(self,waveforms): # TODO make sure there are more columns than rows (transpose if not) # normalize waveforms self._waveforms = waveforms self._A = self._SPCA.fit_transform(self._waveforms) return self._A def inverse_transform(self,A): # convert basis back to waveforms using fit new_waveforms = self._SPCA.inverse_transform(A) return new_waveforms def get_params(self): # TODO know what catalog was used! (include waveform metadata) params = self._SPCA.get_params() params['num_components'] = params.pop('n_components') params['Decompositon'] = self._decomposition return params def get_basis(self): """ Return the SPCA basis vectors (Z^\dagger)""" Zt = self._SPCA.components_ return Zt class SC(object): """ Wrapper for sklearn package. Performs sparse coding Sparse Coding, or Dictionary Learning has 5 methods: - fit(waveforms) update class instance with Sparse Coding fit - fit_transform() do what fit() does, but additionally return the projection onto new basis space - inverse_transform(A) inverses the decomposition, returns waveforms for an input A, using Z^\dagger - get_basis() returns the basis vectors Z^\dagger - get_params() returns metadata used for fits. """ def __init__(self, num_components=10, catalog_name='unknown', alpha = 0.001, transform_alpha = 0.01, max_iter = 2000, tol = 1e-9, n_jobs = 1, verbose = True, random_state = None): self._decomposition = 'Sparse Coding' self._num_components = num_components self._catalog_name = catalog_name self._alpha = alpha self._transform_alpha = 0.001 self._n_jobs = n_jobs self._random_state = random_state self._DL = DictionaryLearning(n_components=self._num_components, alpha = self._alpha, transform_alpha = self._transform_alpha, n_jobs = self._n_jobs, verbose = verbose, random_state = self._random_state) def fit(self,waveforms): # TODO make sure there are more columns than rows (transpose if not) # normalize waveforms self._waveforms = waveforms self._DL.fit(self._waveforms) def fit_transform(self,waveforms): # TODO make sure there are more columns than rows (transpose if not) # normalize waveforms self._waveforms = waveforms self._A = self._DL.fit_transform(self._waveforms) return self._A def inverse_transform(self,A): # convert basis back to waveforms using fit new_waveforms = self._DL.inverse_transform(A) return new_waveforms def get_params(self): # TODO know what catalog was used! (include waveform metadata) params = self._DL.get_params() params['num_components'] = params.pop('n_components') params['Decompositon'] = self._decomposition return params def get_basis(self): """ Return the SPCA basis vectors (Z^\dagger)""" return self._DL.components_
#!/usr/bin/python # pose related functions import csv import fileinput import fnmatch import math import os import re import navpy from props import getNode from . import camera from . import exif from . import image from .logger import log from . import transformations from props import getNode import props_json # this should really be a parameter. Any aircraft poses that exceed # this value for either roll or pitch will be ignored. Oblique photos # combined with lens distortion become really difficult for the # optimizer to resolve (especially when it puts points off near the # horizon.) # a helpful constant d2r = math.pi / 180.0 r2d = 180.0 / math.pi # quaternions represent a rotation from one coordinate system to # another (i.e. from NED space to aircraft body space). You can # back translate a vector against this quaternion to project a camera # vector into NED space. # # body angles represent the aircraft orientation # camera angles represent the fixed mounting offset of the camera # relative to the body # +x axis = forward, +roll = left wing down # +y axis = right, +pitch = nose down # +z axis = up, +yaw = nose right # return a sorted list of images def gen_image_list(image_dir): images = [] for file in os.listdir(image_dir): if fnmatch.fnmatch(file, '*.jpg') or fnmatch.fnmatch(file, '*.JPG'): images.append(file) return sorted(images) # define the image aircraft poses from Sentera meta data file def set_aircraft_poses(proj, posefile="", order='ypr', max_angle=25.0): log("Setting aircraft poses") #analysis_dir = os.path.join(proj.project_dir, 'ImageAnalysis') meta_dir = os.path.join(proj.analysis_dir, 'meta') images_node = getNode("/images", True) by_index = False f = fileinput.input(posefile) for line in f: line.strip() if re.match('^\s*#', line): #print("skipping comment ", line) continue if re.match('^\s*File', line): #print("skipping header ", line) continue if re.match('^\s*Image', line): #print("skipping header ", line) by_index = True file_list = gen_image_list(proj.project_dir) continue field = line.split(',') if not by_index: name = field[0] else: index = int(field[0]) - 1 name = file_list[index] lat_deg = float(field[1]) lon_deg = float(field[2]) alt_m = float(field[3]) if order == 'ypr': yaw_deg = float(field[4]) pitch_deg = float(field[5]) roll_deg = float(field[6]) elif order == 'rpy': roll_deg = float(field[4]) pitch_deg = float(field[5]) yaw_deg = float(field[6]) if len(field) >= 8: flight_time = float(field[7]) else: flight_time = -1.0 found_dir = '' if not os.path.isfile( os.path.join(proj.project_dir, name) ): log("No image file:", name, "skipping ...") continue if camera.camera_node.getString("make") == "DJI" or camera.camera_node.getString("make") == "Hasselblad": # camera is on a gimbal so check if pitch is nearly nadir (-90) if pitch_deg > -45: log("gimbal not looking down:", name, "roll:", roll_deg, "pitch:", pitch_deg) continue elif abs(roll_deg) > max_angle or abs(pitch_deg) > max_angle: # fairly 'extreme' attitude, skip image log("extreme attitude:", name, "roll:", roll_deg, "pitch:", pitch_deg) continue base, ext = os.path.splitext(name) i1 = image.Image(proj.analysis_dir, base) i1.set_aircraft_pose(lat_deg, lon_deg, alt_m, yaw_deg, pitch_deg, roll_deg, flight_time) image_node = images_node.getChild(base, True) image_path = os.path.join(meta_dir, base + '.json') props_json.save(image_path, image_node) log("pose:", name, "yaw=%.1f pitch=%.1f roll=%.1f" % (yaw_deg, pitch_deg, roll_deg)) # for each image, compute the estimated camera pose in NED space from # the aircraft body pose and the relative camera orientation def compute_camera_poses(proj): log("Setting camera poses (offset from aircraft pose.)") images_node = getNode("/images", True) ref_node = getNode("/config/ned_reference", True) ref_lat = ref_node.getFloat("lat_deg") ref_lon = ref_node.getFloat("lon_deg") ref_alt = ref_node.getFloat("alt_m") body2cam = camera.get_body2cam() for image in proj.image_list: print("camera pose:", image.name) ac_pose_node = image.node.getChild("aircraft_pose", True) #cam_pose_node = images_node.getChild(name + "/camera_pose", True) aircraft_lat = ac_pose_node.getFloat("lat_deg") aircraft_lon = ac_pose_node.getFloat("lon_deg") aircraft_alt = ac_pose_node.getFloat("alt_m") ned2body = [] for i in range(4): ned2body.append( ac_pose_node.getFloatEnum("quat", i) ) ned2cam = transformations.quaternion_multiply(ned2body, body2cam) (yaw_rad, pitch_rad, roll_rad) = transformations.euler_from_quaternion(ned2cam, "rzyx") ned = navpy.lla2ned( aircraft_lat, aircraft_lon, aircraft_alt, ref_lat, ref_lon, ref_alt ) image.set_camera_pose(ned, yaw_rad*r2d, pitch_rad*r2d, roll_rad*r2d) # make a pix4d pose file from project image metadata def make_pix4d(image_dir, force_altitude=None, force_heading=None, yaw_from_groundtrack=False): if not force_altitude and camera.camera_node.getString("make") == "DJI" and camera.camera_node.getString("model") in ["FC330", "FC6310", "FC6310S"]: # test for Phantom 4 Pro v2.0 camera which lies about it's altitude log("Detected these images are from a Phantom 4 which lies about it's") log("altitude. Please rerun the script with the --force-altitude option to") log("override the incorrect goetag altitude with your best estimate of the") log("true gps altitude of the flight altitude (in meters).") log("Sorry for the inconvenience!") quit() # load list of images files = [] for file in os.listdir(image_dir): if fnmatch.fnmatch(file, "*.jpg") or fnmatch.fnmatch(file, "*.JPG"): files.append(file) files.sort() # save some work if true images_have_yaw = False images = [] # read image exif timestamp (and convert to unix seconds) for file in files: full_name = os.path.join(image_dir, file) # print(full_name) lon_deg, lat_deg, alt_m, unixtime, yaw_deg, pitch_deg, roll_deg = exif.get_pose(full_name) line = [file, lat_deg, lon_deg] if not force_altitude: line.append(alt_m) else: line.append(force_altitude) if roll_deg is None: line.append(0) # assume zero roll else: line.append(roll_deg) if pitch_deg is None: line.append(0) # assume zero pitch else: line.append(pitch_deg) if force_heading is not None: line.append(force_heading) elif yaw_deg is not None: images_have_yaw = True line.append(yaw_deg) else: # no yaw info found in metadata line.append(0) images.append(line) if (not force_heading and not images_have_yaw) or yaw_from_groundtrack: print("do yaw from ground track") # do extra work to estimate yaw heading from gps ground track from rcUAS import wgs84 for i in range(len(images)): if i > 0: prev = images[i-1] else: prev = None cur = images[i] if i < len(images)-1: next = images[i+1] else: next = None if not prev is None: (prev_hdg, rev_course, prev_dist) = \ wgs84.geo_inverse( prev[1], prev[2], cur[1], cur[2] ) else: prev_hdg = 0.0 prev_dist = 0.0 if not next is None: (next_hdg, rev_course, next_dist) = \ wgs84.geo_inverse( cur[1], cur[2], next[1], next[2] ) else: next_hdg = 0.0 next_dist = 0.0 prev_hdgx = math.cos(prev_hdg*d2r) prev_hdgy = math.sin(prev_hdg*d2r) next_hdgx = math.cos(next_hdg*d2r) next_hdgy = math.sin(next_hdg*d2r) avg_hdgx = (prev_hdgx*prev_dist + next_hdgx*next_dist) / (prev_dist + next_dist) avg_hdgy = (prev_hdgy*prev_dist + next_hdgy*next_dist) / (prev_dist + next_dist) avg_hdg = math.atan2(avg_hdgy, avg_hdgx)*r2d if avg_hdg < 0: avg_hdg += 360.0 #print("%d %.2f %.1f %.2f %.1f %.2f" % (i, prev_hdg, prev_dist, next_hdg, next_dist, avg_hdg)) images[i][6] = avg_hdg # sanity check output_file = os.path.join(image_dir, "pix4d.csv") if os.path.exists(output_file): log(output_file, "exists, please rename it and rerun this script.") quit() log("Creating pix4d image pose file:", output_file, "images:", len(files)) # traverse the image list and create output csv file with open(output_file, 'w') as csvfile: writer = csv.DictWriter( csvfile, fieldnames=["File Name", "Lat (decimal degrees)", "Lon (decimal degrees)", "Alt (meters MSL)", "Roll (decimal degrees)", "Pitch (decimal degrees)", "Yaw (decimal degrees)"] ) writer.writeheader() for line in images: image = line[0] lat_deg = line[1] lon_deg = line[2] alt_m = line[3] roll_deg = line[4] pitch_deg = line[5] yaw_deg = line[6] writer.writerow( { "File Name": os.path.basename(image), "Lat (decimal degrees)": "%.10f" % lat_deg, "Lon (decimal degrees)": "%.10f" % lon_deg, "Alt (meters MSL)": "%.2f" % alt_m, "Roll (decimal degrees)": "%.2f" % roll_deg, "Pitch (decimal degrees)": "%.2f" % pitch_deg, "Yaw (decimal degrees)": "%.2f" % yaw_deg } )
# -*- coding: utf-8 -*- """ >>> pingpong = thriftpy2.load("pingpong.thrift") >>> >>> class Dispatcher(object): >>> def ping(self): >>> return "pong" >>> server = make_server(pingpong.PingPong, Dispatcher()) >>> server.listen(6000) >>> client = ioloop.IOLoop.current().run_sync( lambda: make_client(pingpong.PingPong, '127.0.0.1', 6000)) >>> ioloop.IOLoop.current().run_sync(client.ping) 'pong' """ from __future__ import absolute_import from contextlib import contextmanager from tornado import tcpserver, iostream, gen from tornado import version as tornado_version from io import BytesIO from datetime import timedelta from .transport import TTransportException, TTransportBase from .transport.memory import TMemoryBuffer from .thrift import TApplicationException, TProcessor, TClient # TODO need TCyTornadoStreamTransport to work with cython binary protocol from .protocol.binary import TBinaryProtocolFactory from ._compat import PY3 if PY3: import urllib else: import urllib2 as urllib import urlparse urllib.parse = urlparse urllib.parse.quote = urllib.quote import logging import socket import struct try: from tornado.locks import Lock except ImportError: try: from toro import Lock except ImportError: raise RuntimeError('With tornado {}, you need to install ' '"toro"'.format(tornado_version)) logger = logging.getLogger(__name__) class TTornadoStreamTransport(TTransportBase): """a framed, buffered transport over a Tornado stream""" DEFAULT_CONNECT_TIMEOUT = timedelta(seconds=1) DEFAULT_READ_TIMEOUT = timedelta(seconds=1) def __init__(self, host, port, stream=None, io_loop=None, ssl_options=None, read_timeout=DEFAULT_READ_TIMEOUT): self.host = host self.port = port self.io_loop = io_loop self.read_timeout = read_timeout self.is_queuing_reads = False self.read_queue = [] self.__wbuf = BytesIO() self._read_lock = Lock() self.ssl_options = ssl_options # servers provide a ready-to-go stream self.stream = stream if self.stream is not None: self._set_close_callback() if tornado_version >= '5.0': def with_timeout(self, timeout, future): return gen.with_timeout(timeout, future) else: def with_timeout(self, timeout, future): return gen.with_timeout(timeout, future, self.io_loop) @gen.coroutine def open(self, timeout=DEFAULT_CONNECT_TIMEOUT): logger.debug('socket connecting') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) if self.ssl_options is None: self.stream = iostream.IOStream(sock) else: self.stream = iostream.SSLIOStream( sock, ssl_options=self.ssl_options) try: yield self.with_timeout(timeout, self.stream.connect( (self.host, self.port))) except (socket.error, OSError, IOError): message = 'could not connect to {}:{}'.format(self.host, self.port) raise TTransportException( type=TTransportException.NOT_OPEN, message=message) self._set_close_callback() raise gen.Return(self) def _set_close_callback(self): self.stream.set_close_callback(self.close) def close(self): # don't raise if we intend to close self.stream.set_close_callback(None) self.stream.close() def read(self, _): # The generated code for Tornado shouldn't do individual reads -- only # frames at a time assert False, "you're doing it wrong" @contextmanager def io_exception_context(self): try: yield except (socket.error, OSError, IOError) as e: raise TTransportException( type=TTransportException.END_OF_FILE, message=str(e)) except iostream.StreamBufferFullError as e: raise TTransportException( type=TTransportException.UNKNOWN, message=str(e)) except gen.TimeoutError as e: raise TTransportException( type=TTransportException.TIMED_OUT, message=str(e)) @gen.coroutine def read_frame(self): # IOStream processes reads one at a time with (yield self._read_lock.acquire()): with self.io_exception_context(): frame_header = yield self._read_bytes(4) if len(frame_header) == 0: raise iostream.StreamClosedError( 'Read zero bytes from stream') frame_length, = struct.unpack('!i', frame_header) logger.debug('received frame header, frame length = %d', frame_length) frame = yield self._read_bytes(frame_length) logger.debug('received frame payload: %r', frame) raise gen.Return(frame) def _read_bytes(self, n): return self.with_timeout(self.read_timeout, self.stream.read_bytes(n)) def write(self, buf): self.__wbuf.write(buf) def flush(self): frame = self.__wbuf.getvalue() # reset wbuf before write/flush to preserve state on underlying failure frame_length = struct.pack('!i', len(frame)) self.__wbuf = BytesIO() with self.io_exception_context(): return self.stream.write(frame_length + frame) class TTornadoServer(tcpserver.TCPServer): def __init__(self, processor, iprot_factory, oprot_factory=None, transport_read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT, # noqa *args, **kwargs): super(TTornadoServer, self).__init__(*args, **kwargs) self._processor = processor self._iprot_factory = iprot_factory self._oprot_factory = (oprot_factory if oprot_factory is not None else iprot_factory) self.transport_read_timeout = transport_read_timeout # `io_loop` has been deprecated since tornado 4.1 and removed in 5.0 self.__io_loop = getattr(self, 'io_loop', None) @gen.coroutine def handle_stream(self, stream, address): host, port = address trans = TTornadoStreamTransport( host=host, port=port, stream=stream, io_loop=self.__io_loop, read_timeout=self.transport_read_timeout) try: oprot = self._oprot_factory.get_protocol(trans) iprot = self._iprot_factory.get_protocol(TMemoryBuffer()) while not trans.stream.closed(): # TODO: maybe read multiple frames in advance for concurrency try: frame = yield trans.read_frame() except TTransportException as e: if e.type == TTransportException.END_OF_FILE: break else: raise iprot.trans.setvalue(frame) api, seqid, result, call = self._processor.process_in(iprot) if isinstance(result, TApplicationException): self._processor.send_exception(oprot, api, result, seqid) else: try: result.success = yield gen.maybe_future(call()) except Exception as e: # raise if api don't have throws if not self._processor.handle_exception(e, result): raise self._processor.send_result(oprot, api, result, seqid) except Exception: logger.exception('thrift exception in handle_stream') trans.close() logger.info('client disconnected %s:%d', host, port) class TTornadoClient(TClient): @gen.coroutine def _recv(self, api): frame = yield self._oprot.trans.read_frame() self._iprot.trans.setvalue(frame) result = super(TTornadoClient, self)._recv(api) raise gen.Return(result) def close(self): self._oprot.trans.close() def make_server( service, handler, proto_factory=TBinaryProtocolFactory(), io_loop=None, ssl_options=None, transport_read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT): processor = TProcessor(service, handler) if tornado_version >= '5.0': server = TTornadoServer(processor, iprot_factory=proto_factory, transport_read_timeout=transport_read_timeout, ssl_options=ssl_options) else: server = TTornadoServer(processor, iprot_factory=proto_factory, transport_read_timeout=transport_read_timeout, io_loop=io_loop, ssl_options=ssl_options) return server @gen.coroutine def make_client( service, host='localhost', port=9090, proto_factory=TBinaryProtocolFactory(), io_loop=None, ssl_options=None, connect_timeout=TTornadoStreamTransport.DEFAULT_CONNECT_TIMEOUT, read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT, url=''): if url: parsed_url = urllib.parse.urlparse(url) host = parsed_url.hostname or host port = parsed_url.port or port transport = TTornadoStreamTransport( host, port, io_loop=io_loop, ssl_options=ssl_options, read_timeout=read_timeout) iprot = proto_factory.get_protocol(TMemoryBuffer()) oprot = proto_factory.get_protocol(transport) yield transport.open(connect_timeout) client = TTornadoClient(service, iprot, oprot) raise gen.Return(client)
import numpy as np import pickle from sklearn.isotonic import check_increasing, isotonic_regression,\ IsotonicRegression from sklearn.utils.testing import assert_raises, assert_array_equal,\ assert_true, assert_false, assert_equal from sklearn.utils.testing import assert_warns_message, assert_no_warnings def test_check_increasing_up(): x = [0, 1, 2, 3, 4, 5] y = [0, 1.5, 2.77, 8.99, 8.99, 50] # Check that we got increasing=True and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_true(is_increasing) def test_check_increasing_up_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5] # Check that we got increasing=True and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_true(is_increasing) def test_check_increasing_down(): x = [0, 1, 2, 3, 4, 5] y = [0, -1.5, -2.77, -8.99, -8.99, -50] # Check that we got increasing=False and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_false(is_increasing) def test_check_increasing_down_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, -1, -2, -3, -4, -5] # Check that we got increasing=False and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_false(is_increasing) def test_check_ci_warn(): x = [0, 1, 2, 3, 4, 5] y = [0, -1, 2, -3, 4, -5] # Check that we got increasing=False and CI interval warning is_increasing = assert_warns_message(UserWarning, "interval", check_increasing, x, y) assert_false(is_increasing) def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(y_min=0., y_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) # check that it is immune to permutation perm = np.random.permutation(len(y)) ir = IsotonicRegression(y_min=0., y_max=1.) assert_array_equal(ir.fit_transform(x[perm], y[perm]), ir.fit_transform(x, y)[perm]) assert_array_equal(ir.transform(x[perm]), ir.transform(x)[perm]) # check it doesn't change y when all x are equal: ir = IsotonicRegression() assert_array_equal(ir.fit_transform(np.ones(len(x)), y), y) def test_isotonic_regression_reversed(): y = np.array([10, 9, 10, 7, 6, 6.1, 5]) y_ = IsotonicRegression(increasing=False).fit_transform( np.arange(len(y)), y) assert_array_equal(np.ones(y_[:-1].shape), ((y_[:-1] - y_[1:]) >= 0)) def test_isotonic_regression_auto_decreasing(): # Set y and x for decreasing y = np.array([10, 9, 10, 7, 6, 6.1, 5]) x = np.arange(len(y)) # Create model and fit_transform ir = IsotonicRegression(increasing='auto') y_ = assert_no_warnings(ir.fit_transform, x, y) # Check that relationship decreases is_increasing = y_[0] < y_[-1] assert_false(is_increasing) def test_isotonic_regression_auto_increasing(): # Set y and x for decreasing y = np.array([5, 6.1, 6, 7, 10, 9, 10]) x = np.arange(len(y)) # Create model and fit_transform ir = IsotonicRegression(increasing='auto') y_ = assert_no_warnings(ir.fit_transform, x, y) # Check that relationship increases is_increasing = y_[0] < y_[-1] assert_true(is_increasing) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10)) def test_isotonic_sample_weight_parameter_default_value(): # check if default value of sample_weight parameter is one ir = IsotonicRegression() # random test data rng = np.random.RandomState(42) n = 100 x = np.arange(n) y = rng.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n)) # check if value is correctly used weights = np.ones(n) y_set_value = ir.fit_transform(x, y, sample_weight=weights) y_default_value = ir.fit_transform(x, y) assert_array_equal(y_set_value, y_default_value) def test_isotonic_min_max_boundaries(): # check if min value is used correctly ir = IsotonicRegression(y_min=2, y_max=4) n = 6 x = np.arange(n) y = np.arange(n) y_test = [2, 2, 2, 3, 4, 4] y_result = np.round(ir.fit_transform(x, y)) assert_array_equal(y_result, y_test) def test_isotonic_sample_weight(): ir = IsotonicRegression() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 41, 51, 1, 2, 5, 24] sample_weight = [1, 2, 3, 4, 5, 6, 7] expected_y = [1, 13.95, 13.95, 13.95, 13.95, 13.95, 24] received_y = ir.fit_transform(x, y, sample_weight=sample_weight) assert_array_equal(expected_y, received_y) def test_isotonic_regression_oob_raise(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") ir.fit(x, y) # Check that an exception is thrown assert_raises(ValueError, ir.predict, [min(x)-10, max(x)+10]) def test_isotonic_regression_oob_clip(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") ir.fit(x, y) # Predict from training and test x and check that min/max match. y1 = ir.predict([min(x) - 10, max(x) + 10]) y2 = ir.predict(x) assert_equal(max(y1), max(y2)) assert_equal(min(y1), min(y2)) def test_isotonic_regression_oob_nan(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="nan") ir.fit(x, y) # Predict from training and test x and check that we have two NaNs. y1 = ir.predict([min(x)-10, max(x)+10]) assert_equal(sum(np.isnan(y1)), 2) def test_isotonic_regression_oob_bad(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="xyz") # Make sure that we throw an error for bad out_of_bounds value assert_raises(ValueError, ir.fit, x, y) def test_isotonic_regression_oob_bad_after(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") # Make sure that we throw an error for bad out_of_bounds value in transform ir.fit(x, y) ir.out_of_bounds = "xyz" assert_raises(ValueError, ir.transform, x) def test_isotonic_regression_pickle(): y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") ir.fit(x, y) ir_ser = pickle.dumps(ir, pickle.HIGHEST_PROTOCOL) ir2 = pickle.loads(ir_ser) np.testing.assert_array_equal(ir.predict(x), ir2.predict(x)) def test_isotonic_duplicate_min_entry(): x = [0, 0, 1] y = [0, 0, 1] ir = IsotonicRegression(increasing=True, out_of_bounds="clip") ir.fit(x, y) all_predictions_finite = np.all(np.isfinite(ir.predict(x))) assert_true(all_predictions_finite) if __name__ == "__main__": import nose nose.run(argv=['', __file__])
# PyVision License # # Copyright (c) 2006-2008 David S. Bolme # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither name of copyright holders nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from os.path import join import unittest import random from math import pi import os.path import pyvision as pv import numpy as np from pyvision.face.CascadeDetector import CascadeDetector from pyvision.analysis.face import EyesFile from pyvision.point.PointLocator import SVMLocator,KRRLocator from pyvision.analysis.FaceAnalysis.FaceDetectionTest import face_from_eyes, is_success from pyvision.analysis.FaceAnalysis.EyeDetectionTest import EyeDetectionTest from pyvision.vector import VectorClassifier from pyvision.vector import SVM class SVMEyeDetector: ''' This class detects faces and then returns the detection rectangles and the eye coordinates. ''' def __init__(self, face_detector=CascadeDetector(), tile_size=(128,128), validate=None, n_iter=1, annotate=False,**kwargs): ''' Create an eye locator. This default implentation uses a cascade classifier for face detection and then SVR for eye location. ''' self.face_detector = face_detector self.left_eye = None self.right_eye = None self.tile_size = tile_size self.validate = validate self.n_iter = n_iter self.annotate = annotate self.perturbations = True # this object handles pca normalization self.normalize = VectorClassifier.VectorClassifier( VectorClassifier.TYPE_REGRESSION, reg_norm=VectorClassifier.REG_NORM_NONE) # point locators that learn to find the eyes. self.left_locator = SVMLocator(type=SVM.TYPE_NU_SVR ,normalization=VectorClassifier.NORM_NONE) self.right_locator = SVMLocator(type=SVM.TYPE_NU_SVR ,normalization=VectorClassifier.NORM_NONE) # Number of training images where the face detection did not work. self.detection_failures = 0 self.training_labels = [] def addTraining(self, left_eye, right_eye, im): '''Train an eye detector givin a full image and the eye coordinates.''' # determine the face rect true_rect = face_from_eyes(left_eye,right_eye) # run the face detector rects = self.face_detector.detect(im) # find the best detection if there is one for pred_rect in rects: if is_success(pred_rect,true_rect): # Transform the face affine = pv.AffineFromRect(pred_rect,self.tile_size) w,h = self.tile_size if self.perturbations: # Randomly rotate, translate and scale the images center = pv.AffineTranslate(-0.5*w,-0.5*h,self.tile_size) rotate = pv.AffineRotate(random.uniform(-pi/8,pi/8),self.tile_size) scale = pv.AffineScale(random.uniform(0.9,1.1),self.tile_size) translate = pv.AffineTranslate(random.uniform(-0.05*w,0.05*w), random.uniform(-0.05*h,0.05*h), self.tile_size) inv_center = pv.AffineTranslate(0.5*w,0.5*h,self.tile_size) affine = inv_center*translate*scale*rotate*center*affine #affine = affine*center*rotate*scale*translate*inv_center cropped = affine.transformImage(im) cropped = pv.meanStd(cropped) # Mark the eyes leye = affine.transformPoint(left_eye) reye = affine.transformPoint(right_eye) # Add training data to locators self.training_labels.append((leye,reye)) self.normalize.addTraining(0.0,cropped) #self.left_locator.addTraining(cropped,leye) #self.right_locator.addTraining(cropped,reye) # Just use the first success return # The face was not detected self.detection_failures += 1 def train(self,**kwargs): ''' Train the eye locators. ''' self.normalize.trainNormalization() vectors = self.normalize.vectors #print len(self.training_labels) #print vectors.shape for i in range(len(self.training_labels)): leye,reye = self.training_labels[i] vec = vectors[i] self.left_locator.addTraining(vec,leye) self.right_locator.addTraining(vec,reye) self.left_locator.train(**kwargs) self.right_locator.train(**kwargs) self.left_eye = self.left_locator.mean self.right_eye = self.right_locator.mean del self.normalize.labels del self.normalize.vectors del self.training_labels def detect(self, im): ''' @returns: a list of tuples where each tuple contains (registered_image, detection_rect, left_eye, right_eye) ''' result = [] rects = self.face_detector.detect(im) # Anotate Faces for rect in rects: # Transform the face affine = pv.AffineFromRect(rect,self.tile_size) cropped = affine.transformImage(im) for p in range(self.n_iter): cropped = pv.meanStd(cropped) # Find the eyes data = cropped.asMatrix2D().flatten() data = np.array(data,'d').flatten() data = self.normalize.normalizeVector(data) pleye = self.left_locator.predict(data) preye = self.right_locator.predict(data) pleye = affine.invertPoint(pleye) preye = affine.invertPoint(preye) # Seccond Pass affine = pv.AffineFromPoints(pleye,preye,self.left_eye,self.right_eye,self.tile_size) cropped = affine.transformImage(im) #affine = AffineFromPoints(pleye,preye,self.left_eye,self.right_eye,self.tile_size) #reg = affine.transformImage(im) reg = cropped if self.validate != None and not self.validate(reg): # Validate the face. if self.annotate: im.annotateRect(rect,color='red') im.annotatePoint(pleye,color='red') im.annotatePoint(preye,color='red') continue if self.annotate: reg.annotatePoint(self.left_eye,color='green') reg.annotatePoint(self.right_eye,color='green') im.annotatePoint(pleye,color='green') im.annotatePoint(preye,color='green') im.annotateRect(rect,color='green') result.append((reg,rect,pleye,preye)) return result class RegressionEyeLocator2: ''' This class detects faces and then returns the detection rectangles and the eye coordinates. ''' def __init__(self, face_detector=CascadeDetector(), tile_size=(128,128), subtile_size=(32,32), left_center=pv.Point(39.325481787836871,50.756936769089975), right_center=pv.Point(91.461135538006289,50.845357457309881), validate=None, n_iter=1, annotate=False,**kwargs): ''' Create an eye locator. This default implentation uses a cascade classifier for face detection and then SVR for eye location. ''' #TODO: Learn the mean eye locations durring training. self.face_detector = face_detector self.left_center = left_center self.right_center = right_center self.tile_size = tile_size self.subtile_size = subtile_size self.validate = validate self.n_iter = n_iter self.annotate = annotate self.perturbations = True # Number of training images where the face detection did not work. self.detection_failures = 0 # point locators that learn to find the eyes. self.createLocators(**kwargs) def createLocators(self,**kwargs): ''' Create two point locators that use the methods of interest ''' raise NotImplementedError def generateTransforms(self,detection): # Transform the face affine = pv.AffineFromRect(detection,self.tile_size) w,h = self.tile_size if self.perturbations: # Randomly rotate, translate and scale the images center = pv.AffineTranslate(-0.5*w,-0.5*h,self.tile_size) rotate = pv.AffineRotate(random.uniform(-pi/8,pi/8),self.tile_size) scale = pv.AffineScale(random.uniform(0.9,1.1),self.tile_size) translate = pv.AffineTranslate(random.uniform(-0.05*w,0.05*w), random.uniform(-0.05*h,0.05*h), self.tile_size) inv_center = pv.AffineTranslate(0.5*w,0.5*h,self.tile_size) affine = inv_center*translate*scale*rotate*center*affine #affine = affine*center*rotate*scale*translate*inv_center lx=self.left_center.X()-self.subtile_size[0]/2 ly=self.left_center.Y()-self.subtile_size[1]/2 rx=self.right_center.X()-self.subtile_size[0]/2 ry=self.right_center.Y()-self.subtile_size[1]/2 laffine = pv.AffineFromRect(pv.Rect(lx,ly,self.subtile_size[0],self.subtile_size[1]),self.subtile_size)*affine raffine = pv.AffineFromRect(pv.Rect(rx,ry,self.subtile_size[0],self.subtile_size[1]),self.subtile_size)*affine return laffine,raffine def addTraining(self, left_eye, right_eye, im): '''Train an eye detector givin a full image and the eye coordinates.''' # determine the face rect true_rect = face_from_eyes(left_eye,right_eye) # run the face detector rects = self.face_detector.detect(im) # find the best detection if there is one for pred_rect in rects: if is_success(pred_rect,true_rect): laffine,raffine = self.generateTransforms(pred_rect) lcropped = laffine.transformImage(im) rcropped = raffine.transformImage(im) #Normalize the images lcropped = pv.meanStd(lcropped) rcropped = pv.meanStd(rcropped) # Mark the eyes leye = laffine.transformPoint(left_eye) reye = raffine.transformPoint(right_eye) # Add training data to locators self.left_locator.addTraining(lcropped,leye) self.right_locator.addTraining(rcropped,reye) # Just use the first success return # The face was not detected self.detection_failures += 1 def train(self,**kwargs): ''' Train the eye locators. ''' self.left_locator.train(**kwargs) self.right_locator.train(**kwargs) self.left_eye = self.left_locator.mean self.right_eye = self.right_locator.mean self.perturbations=False def detect(self, im): ''' @returns: a list of tuples where each tuple contains (registered_image, detection_rect, left_eye, right_eye) ''' result = [] rects = self.face_detector.detect(im) # Anotate Faces for rect in rects: # Transform the face laffine,raffine = self.generateTransforms(rect) lcropped = laffine.transformImage(im) rcropped = raffine.transformImage(im) #Normalize the images lcropped = pv.meanStd(lcropped) rcropped = pv.meanStd(rcropped) pleye = self.left_locator.predict(lcropped) preye = self.right_locator.predict(rcropped) pleye = laffine.invertPoint(pleye) preye = raffine.invertPoint(preye) affine = pv.AffineFromPoints(pleye,preye,self.left_eye,self.right_eye,self.tile_size) reg = affine.transformImage(im) if self.validate != None and not self.validate(reg): # Validate the face. if self.annotate: im.annotateRect(rect,color='red') im.annotatePoint(pleye,color='red') im.annotatePoint(preye,color='red') continue if self.annotate: reg.annotatePoint(self.left_eye,color='green') reg.annotatePoint(self.right_eye,color='green') im.annotatePoint(pleye,color='green') im.annotatePoint(preye,color='green') im.annotateRect(rect,color='green') result.append((reg,rect,pleye,preye)) return result class SVMEyeLocator2(RegressionEyeLocator2): ''' This class detects faces and then returns the detection rectangles and the eye coordinates. ''' def createLocators(self,**kwargs): ''' Create two point locators that use the methods of interest ''' self.left_locator = SVMLocator(type=SVM.TYPE_NU_SVR ,normalization=VectorClassifier.NORM_VALUE) self.right_locator = SVMLocator(type=SVM.TYPE_NU_SVR ,normalization=VectorClassifier.NORM_VALUE) class KRREyeLocator2(RegressionEyeLocator2): ''' This class detects faces and then returns the detection rectangles and the eye coordinates. ''' def createLocators(self,**kwargs): ''' Create two point locators that use the methods of interest ''' self.left_locator = KRRLocator(**kwargs) self.right_locator = KRRLocator(**kwargs) def SVMEyeDetectorFromDatabase(eyes_file, image_dir, training_set = None, training_size=1000, image_ext='.jpg', **kwargs): ''' Train a face finder using an Eye Coordanates file and a face dataset. ''' # Create a face finder face_finder = SVMEyeDetector(**kwargs) if training_set == None: training_set = eyes_file.files() if training_size == None or training_size > len(training_set): training_size = len(training_set) for filename in training_set[:training_size]: #print "Processing file:",filename im_name = join(image_dir,filename+image_ext) # Detect faces im = pv.Image(im_name) eyes = eyes_file.getEyes(filename) for left,right in eyes: face_finder.addTraining(left,right,im) face_finder.train() return face_finder ############################################################################# # Unit Tests ############################################################################# class _TestSVMEyeDetector(unittest.TestCase): def setUp(self): self.images = [] self.names = [] SCRAPS_FACE_DATA = os.path.join(pv.__path__[0],"data","csuScrapShots") self.eyes = EyesFile(os.path.join(SCRAPS_FACE_DATA,"coords.txt")) for filename in self.eyes.files(): img = pv.Image(os.path.join(SCRAPS_FACE_DATA, filename + ".pgm")) self.images.append(img) self.names.append(filename) self.assert_( len(self.images) == 173 ) def test_training(self): ''' This trains the FaceFinder on the scraps database. ''' #import cProfile # Load an eyes file eyes_filename = join(pv.__path__[0],'data','csuScrapShots','coords.txt') #print "Creating eyes File." eyes_file = EyesFile(eyes_filename) # Create a face detector cascade_file = join(pv.__path__[0],'config','facedetector_celebdb2.xml') #print "Creating a face detector from:",cascade_file face_detector = CascadeDetector(cascade_file) image_dir = join(pv.__path__[0],'data','csuScrapShots') ed = SVMEyeDetectorFromDatabase(eyes_file, image_dir, image_ext=".pgm", face_detector=face_detector,random_seed=0) edt = EyeDetectionTest(name='scraps') #print "Testing..." for img in self.images: #print img.filename faces = ed.detect(img) #faces = ed.detect(img) pred_eyes = [] for _,_,pleye,preye in faces: #detections.append(rect) pred_eyes.append((pleye,preye)) truth_eyes = self.eyes.getEyes(img.filename) edt.addSample(truth_eyes, pred_eyes, im=img, annotate=False) #print edt.createSummary() self.assertAlmostEqual( edt.face_rate , 0.924855491329, places = 3 ) #TODO: Randomization is causing issues with getting the eye detector to perform consistently #self.assertAlmostEqual( edt.both25_rate , 0.907514450867, places = 3 ) #self.assertAlmostEqual( edt.both10_rate , 0.745664739884, places = 3 ) #self.assertAlmostEqual( edt.both05_rate , 0.277456647399, places = 3 )
#! /usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2007-2010 (ita) """ Debugging helper for parallel compilation, outputs a file named pdebug.svg in the source directory:: def options(opt): opt.load('parallel_debug') def configure(conf): conf.load('parallel_debug') def build(bld): ... """ import os, time, sys try: from Queue import Queue except: from queue import Queue from waflib import Runner, Options, Utils, Task, Logs, Errors #import random #random.seed(100) def options(opt): opt.add_option('--dtitle', action='store', default='Parallel build representation for %r' % ' '.join(sys.argv), help='title for the svg diagram', dest='dtitle') opt.add_option('--dwidth', action='store', type='int', help='diagram width', default=800, dest='dwidth') opt.add_option('--dtime', action='store', type='float', help='recording interval in seconds', default=0.009, dest='dtime') opt.add_option('--dband', action='store', type='int', help='band width', default=22, dest='dband') opt.add_option('--dmaxtime', action='store', type='float', help='maximum time, for drawing fair comparisons', default=0, dest='dmaxtime') def configure(conf): conf.find_program('convert', var='CONVERT_BIN') # red #ff4d4d # green #4da74d # lila #a751ff color2code = { 'GREEN' : '#4da74d', 'YELLOW' : '#fefe44', 'PINK' : '#a751ff', 'RED' : '#cc1d1d', 'BLUE' : '#6687bb', 'CYAN' : '#34e2e2', } mp = {} info = [] # list of (text,color) def map_to_color(name): if name in mp: return mp[name] try: cls = Task.classes[name] except KeyError: return color2code['RED'] if cls.color in mp: return mp[cls.color] if cls.color in color2code: return color2code[cls.color] return color2code['RED'] def process(self): m = self.master if m.stop: m.out.put(self) return self.master.set_running(1, id(Utils.threading.currentThread()), self) # remove the task signature immediately before it is executed # in case of failure the task will be executed again try: del self.generator.bld.task_sigs[self.uid()] except: pass try: self.generator.bld.returned_tasks.append(self) self.log_display(self.generator.bld) ret = self.run() except Exception: self.err_msg = Utils.ex_stack() self.hasrun = Task.EXCEPTION # TODO cleanup m.error_handler(self) m.out.put(self) return if ret: self.err_code = ret self.hasrun = Task.CRASHED else: try: self.post_run() except Errors.WafError: pass except Exception: self.err_msg = Utils.ex_stack() self.hasrun = Task.EXCEPTION else: self.hasrun = Task.SUCCESS if self.hasrun != Task.SUCCESS: m.error_handler(self) self.master.set_running(-1, id(Utils.threading.currentThread()), self) m.out.put(self) Task.TaskBase.process_back = Task.TaskBase.process Task.TaskBase.process = process old_start = Runner.Parallel.start def do_start(self): try: Options.options.dband except AttributeError: self.bld.fatal('use def options(opt): opt.load("parallel_debug")!') self.taskinfo = Queue() old_start(self) if self.dirty: process_colors(self) Runner.Parallel.start = do_start def set_running(self, by, i, tsk): self.taskinfo.put( (i, id(tsk), time.time(), tsk.__class__.__name__, self.processed, self.count, by) ) Runner.Parallel.set_running = set_running def name2class(name): return name.replace(' ', '_').replace('.', '_') def process_colors(producer): # first, cast the parameters if not hasattr(producer.bld, 'path'): return tmp = [] try: while True: tup = producer.taskinfo.get(False) tmp.append(list(tup)) except: pass try: ini = float(tmp[0][2]) except: return if not info: seen = [] for x in tmp: name = x[3] if not name in seen: seen.append(name) else: continue info.append((name, map_to_color(name))) info.sort(key=lambda x: x[0]) thread_count = 0 acc = [] for x in tmp: thread_count += x[6] acc.append("%d %d %f %r %d %d %d" % (x[0], x[1], x[2] - ini, x[3], x[4], x[5], thread_count)) data_node = producer.bld.path.make_node('pdebug.dat') data_node.write('\n'.join(acc)) tmp = [lst[:2] + [float(lst[2]) - ini] + lst[3:] for lst in tmp] st = {} for l in tmp: if not l[0] in st: st[l[0]] = len(st.keys()) tmp = [ [st[lst[0]]] + lst[1:] for lst in tmp ] THREAD_AMOUNT = len(st.keys()) st = {} for l in tmp: if not l[1] in st: st[l[1]] = len(st.keys()) tmp = [ [lst[0]] + [st[lst[1]]] + lst[2:] for lst in tmp ] BAND = Options.options.dband seen = {} acc = [] for x in range(len(tmp)): line = tmp[x] id = line[1] if id in seen: continue seen[id] = True begin = line[2] thread_id = line[0] for y in range(x + 1, len(tmp)): line = tmp[y] if line[1] == id: end = line[2] #print id, thread_id, begin, end #acc.append( ( 10*thread_id, 10*(thread_id+1), 10*begin, 10*end ) ) acc.append( (BAND * begin, BAND*thread_id, BAND*end - BAND*begin, BAND, line[3]) ) break if Options.options.dmaxtime < 0.1: gwidth = 1 for x in tmp: m = BAND * x[2] if m > gwidth: gwidth = m else: gwidth = BAND * Options.options.dmaxtime ratio = float(Options.options.dwidth) / gwidth gwidth = Options.options.dwidth gheight = BAND * (THREAD_AMOUNT + len(info) + 1.5) out = [] out.append("""<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\"> <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.0\" x=\"%r\" y=\"%r\" width=\"%r\" height=\"%r\" id=\"svg602\" xml:space=\"preserve\"> <style type='text/css' media='screen'> g.over rect { stroke:#FF0000; fill-opacity:0.4 } </style> <script type='text/javascript'><![CDATA[ var svg = document.getElementsByTagName('svg')[0]; svg.addEventListener('mouseover', function(e) { var g = e.target.parentNode; var x = document.getElementById('r_' + g.id); if (x) { g.setAttribute('class', g.getAttribute('class') + ' over'); x.setAttribute('class', x.getAttribute('class') + ' over'); showInfo(e, g.id); } }, false); svg.addEventListener('mouseout', function(e) { var g = e.target.parentNode; var x = document.getElementById('r_' + g.id); if (x) { g.setAttribute('class', g.getAttribute('class').replace(' over', '')); x.setAttribute('class', x.getAttribute('class').replace(' over', '')); hideInfo(e); } }, false); function showInfo(evt, txt) { tooltip = document.getElementById('tooltip'); var t = document.getElementById('tooltiptext'); t.firstChild.data = txt; var x = evt.clientX + 9; if (x > 250) { x -= t.getComputedTextLength() + 16; } var y = evt.clientY + 20; tooltip.setAttribute("transform", "translate(" + x + "," + y + ")"); tooltip.setAttributeNS(null, "visibility", "visible"); var r = document.getElementById('tooltiprect'); r.setAttribute('width', t.getComputedTextLength() + 6); } function hideInfo(evt) { var tooltip = document.getElementById('tooltip'); tooltip.setAttributeNS(null,"visibility","hidden"); } ]]></script> <!-- inkscape requires a big rectangle or it will not export the pictures properly --> <rect x='%r' y='%r' width='%r' height='%r' style=\"font-size:10;fill:#ffffff;fill-opacity:0.01;fill-rule:evenodd;stroke:#ffffff;\" />\n """ % (0, 0, gwidth + 4, gheight + 4, 0, 0, gwidth + 4, gheight + 4)) # main title if Options.options.dtitle: out.append("""<text x="%d" y="%d" style="font-size:15px; text-anchor:middle; font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans">%s</text> """ % (gwidth/2, gheight - 5, Options.options.dtitle)) # the rectangles groups = {} for (x, y, w, h, clsname) in acc: try: groups[clsname].append((x, y, w, h)) except: groups[clsname] = [(x, y, w, h)] for cls in groups: out.append("<g id='%s'>\n" % name2class(cls)) for (x, y, w, h) in groups[cls]: out.append("""<rect x='%r' y='%r' width='%r' height='%r' style=\"font-size:10;fill:%s;fill-rule:evenodd;stroke:#000000;stroke-width:0.4;\" />\n""" % (2 + x*ratio, 2 + y, w*ratio, h, map_to_color(cls))) out.append("</g>\n") # output the caption cnt = THREAD_AMOUNT for (text, color) in info: # caption box b = BAND/2 out.append("""<g id='r_%s'><rect x='%r' y='%r' width='%r' height='%r' style=\"font-size:10;fill:%s;fill-rule:evenodd;stroke:#000000;stroke-width:0.4;\" />\n""" % (name2class(text), 2 + BAND, 5 + (cnt + 0.5) * BAND, b, b, color)) # caption text out.append("""<text style="font-size:12px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans" x="%r" y="%d">%s</text></g>\n""" % (2 + 2 * BAND, 5 + (cnt + 0.5) * BAND + 10, text)) cnt += 1 out.append(""" <g transform="translate(0,0)" visibility="hidden" id="tooltip"> <rect id="tooltiprect" y="-15" x="-3" width="1" height="20" style="stroke:black;fill:#edefc2;stroke-width:1"/> <text id="tooltiptext" style="font-family:Arial; font-size:12;fill:black;"> </text> </g>""") out.append("\n</svg>") node = producer.bld.path.make_node('pdebug.svg') node.write("".join(out)) Logs.warn('Created the diagram %r' % node.abspath()) p = node.parent.abspath() producer.bld.exec_command([producer.bld.env.CONVERT_BIN or 'convert', p + os.sep + 'pdebug.svg', p + os.sep + 'pdebug.png'])
import sys import time import zmq import json from zmq.eventloop import ioloop ioloop.install() from zmq.eventloop.zmqstream import ZMQStream import tornado.ioloop import tornado.gen import tornado.web import tornado.websocket import threading import session_ipc def tprint(msg): """like print, but won't get newlines confused with multiple threads""" sys.stdout.write(msg + '\n') sys.stdout.flush() class SendHandler(tornado.web.RequestHandler): def initialize(self): self.context = zmq.Context() self.send_socket = self.context.socket(zmq.PUB) self.send_socket.connect('tcp://house-nas:10901') def get(self,arg,value): self.send_socket.send_multipart(["WebServer/"+str(arg),"*","1",str(value)]) self.write("done") class ZMQPubSub(object): def __init__(self, callback): self.callback = callback def connect(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.SUB) self.socket.connect('tcp://house-nas:10900') print("socket connect:",self.socket) self.stream = ZMQStream(self.socket) self.stream.on_recv(self.callback) def subscribe(self, channel_id): self.socket.setsockopt(zmq.SUBSCRIBE, channel_id) def close(self): self.stream.close() print self.socket.close() class MultiplexPubSub(object): def __init__(self): self.callbacks = set() def add_callback(self,callback): self.callbacks.add(callback) def remove_callback(self,callback): self.callbacks.remove(callback) @tornado.gen.coroutine def on_recv(self,data): data[2] = json.loads(data[2]) if data[2]==1: data[2]= {"value":data[3]} if not "timestamp" in data[2]: data[2]['timestamp'] = time.time() # print("callback:",data,self.callbacks) for callback in self.callbacks: try: callback(data) except WebSocketClosedError: print("Closed by WebSocketClosedError!") self.callbacks.remove(callback) data.on_close() def connect(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.SUB) self.socket.connect('tcp://house-nas:10900') self.send_socket = self.context.socket(zmq.PUB) self.send_socket.connect('tcp://house-nas:10901') print("socket connect:",self.socket,self.on_recv) self.stream = ZMQStream(self.socket) self.stream.on_recv(self.on_recv) def send(self,data): self.send_socket.send_multipart([str(i) for i in json.loads(data)]) def subscribe(self, channel_id): print("subscribe:",channel_id) self.socket.setsockopt(zmq.SUBSCRIBE, channel_id) def close(self): self.stream.close() print self.socket.close() class RelayEventSource(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.session_ipc = None self.pubsub = None print(self.request.remote_ip) if (self.request.remote_ip == '127.0.0.1'): self.authenticated = True return(self.init_pubsub()) else: self.session_ipc = session_ipc.SessionIPC(context,self.on_data) self.session_ipc.retrieve_session(self.on_session_data,self.get_cookie("sessionid")) def on_session_data(self,data): self.authenticated = False #print(data) if (data[0] == 'OK'): args = json.loads(data[1]) if "authenticated" in args and args["authenticated"] == True: self.authenticated = True if (self.session_ipc): self.session_ipc.close() self.init_pubsub() def init_pubsub(self): #self.pubsub = ZMQPubSub(self.on_data) #self.pubsub.connect() # #if self.authenticated: # self.pubsub.subscribe("") #else: # self.pubsub.subscribe("Temp/28-031600af4bff") pubsub.add_callback(self.on_data) self.set_header("Content-Type", 'text/event-stream') self.set_header("Cache-Control", 'no-cache') print(self.get_cookie("sessionid")) def on_data(self, data): # data[2] = json.loads(data[2]) self.write(u"data: " + json.dumps(data)+ "\n\n") self.flush() def close(self): pubsub.remove_callback(self.on_data) print "on_close" if (self.session_ipc): self.session_ipc.close() #if (self.pubsub): # self.pubsub.close() self.finish() class RelayWebSocket(tornado.websocket.WebSocketHandler): def __init__(self,a,b): super(RelayWebSocket,self).__init__(a,b) self.pubsub = None self.session_ipc = None def check_origin(self, origin): print("origin:",origin) return True def open(self): print(self.request.remote_ip) if (self.request.remote_ip == '127.0.0.1'): self.authenticated = True return(self._init_pubsub()) else: self.session_ipc = session_ipc.SessionIPC(context,self.on_data) self.session_ipc.retrieve_session(self.on_session_data,self.get_cookie("sessionid")) def on_session_data(self,data): self.authenticated = False #print(data) if (data[0] == 'OK'): args = json.loads(data[1]) if "authenticated" in args and args["authenticated"] == True: self.authenticated = True if (self.session_ipc): self.session_ipc.close() self._init_pubsub() def _init_pubsub(self): #self.pubsub = ZMQPubSub(self.on_data) #print "connect!" #self.pubsub.connect() #if self.authenticated: # self.pubsub.subscribe("") #else: # self.pubsub.subscribe("Temp/28-031600af4bff") #self.context = zmq.Context() #self.send_socket = self.context.socket(zmq.PUB) #self.send_socket.connect('tcp://house-nas:10901') pubsub.add_callback(self.on_data) print 'ws opened' def on_message(self, message): if self.authenticated: print("Message received:",message) #self.send_socket.send_multipart([str(i) for i in json.loads(message)]) pubsub.send(message) def on_close(self): pubsub.remove_callback(self.on_data) #if (self.pubsub): # self.pubsub.close() if (self.session_ipc): self.session_ipc.close() print("WebSocket closed") def on_data(self, data): #print data if not self.authenticated: if not is_valid(data): return self.write_message(json.dumps(data)) def is_valid(data): valid = False valid = valid | data[0].startswith("Temp/28-031600af4bff") valid = valid | data[0].startswith("mqtt/octoprint/temperature/") valid = valid | data[0].startswith("mqtt/octoprint/progress/") return valid def filter(values): for item in values: if is_valid(item): yield item def load_last_messages(filename): lines = open("last_readings","r").readlines() last_readings_dict = {} last_readings = json.loads(lines[0]) for item in last_readings: last_msg[item[0]] = item def save_last_messages(): last_msg_file = open("last_readings","w") vals = last_msg.values() last_msg_file.write(json.dumps(vals)) last_msg_file.close() class LastMessages(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): if (self.request.remote_ip == '127.0.0.1'): self.authenticated = True return(self._process()) else: self.session_ipc = session_ipc.SessionIPC(context,None) self.session_ipc.retrieve_session(self.on_session_data,self.get_cookie("sessionid")) def on_session_data(self,data): self.authenticated = False print(data) if (data[0] == 'OK'): args = json.loads(data[1]) if "authenticated" in args and args["authenticated"] == True: self.authenticated = True if (self.session_ipc): self.session_ipc.close() self._process() def _process(self): if not self.authenticated: vals = list(filter(last_msg.values())) else: vals = last_msg.values() self.write(json.dumps(vals)) self.finish() def close(self): print "on_close" if (self.session_ipc): self.session_ipc.close() self.finish() context = zmq.Context() last_msg = {} def PubSubCallback(data): last_msg[data[0]] = data application = tornado.web.Application([ (r"/weather_ws/send/([^/]*)/([^/]*)", SendHandler), (r"/weather_ws/event", RelayWebSocket), (r"/weather_ws/event_src", RelayEventSource), (r"/weather_ws/last", LastMessages), ], cookie_secret="<secret-key>") # Cookie secret is not used here. This should also be loaded in from a config file if needed. if __name__ == "__main__": def main(): load_last_messages("last_msgs.json") global pubsub pubsub = MultiplexPubSub() pubsub.connect() pubsub.subscribe("") pubsub.add_callback(PubSubCallback) try: print("Start event loop") application.listen(8889) zmq.eventloop.IOLoop.current().run_sync(main) last_msg_callback = ioloop.PeriodicCallback(save_last_messages,60000*60) last_msg_callback.start() zmq.eventloop.IOLoop.instance().start() except KeyboardInterrupt: router.close() pubsub.close()
from __future__ import absolute_import, division from collections import defaultdict import numpy as np import pandas as pd from six import iteritems from bokeh.charts import DEFAULT_PALETTE from bokeh.core.enums import DashPattern from bokeh.models.glyphs import Rect, Segment, Line, Patches from bokeh.models.renderers import GlyphRenderer from bokeh.core.properties import (Float, String, Datetime, Bool, Instance, List, Either, Int, Enum, Color, Override, Any) from .models import CompositeGlyph from .properties import Column, EitherColumn from .stats import Stat, Quantile, Sum, Min, Max, Bins, stats from .data_source import ChartDataSource from .utils import marker_types, generate_patch_base, label_from_index_dict class NestedCompositeGlyph(CompositeGlyph): """A composite glyph that consists of other composite glyphs. An important responsibility of any `CompositeGlyph` is to understand the bounds of the glyph renderers that make it up. This class is used to provide convenient properties that return the bounds from the child `CompositeGlyphs`. """ children = List(Instance(CompositeGlyph)) @property def y_max(self): return max([renderer.y_max for renderer in self.children]) @property def y_min(self): return min([renderer.y_min for renderer in self.children]) @property def x_min(self): return min([renderer.x_min for renderer in self.children]) @property def x_max(self): return max([renderer.x_max for renderer in self.children]) class XyGlyph(CompositeGlyph): """Composite glyph that plots in cartesian coordinates.""" x = EitherColumn(String, Column(Float), Column(String), Column(Datetime), Column(Bool)) y = EitherColumn(String, Column(Float), Column(String), Column(Datetime), Column(Bool)) def build_source(self): labels = self._build_label_array(('x', 'y'), self.label) str_labels = [str(label) for label in labels] if self.x is None: data = dict(x_values=str_labels, y_values=self.y) elif self.y is None: data = dict(x_values=self.x, y_values=str_labels) else: data = dict(x_values=self.x, y_values=self.y) return data def _build_label_array(self, props, value): for prop in props: if getattr(self, prop) is not None: return [value] * len(getattr(self, prop)) @property def x_max(self): # TODO(fpliger): since CompositeGlyphs are not exposed in general we # should expect to always have a Series but in case # it's not we just use the default min/max instead # of just failing. When/If we end up exposing # CompositeGlyphs we should consider making this # more robust (either enforcing data or checking) try: return self.source.data['x_values'].max() except AttributeError: return max(self.source.data['x_values']) @property def x_min(self): try: return self.source.data['x_values'].min() except AttributeError: return min(self.source.data['x_values']) @property def y_max(self): try: return self.source.data['y_values'].max() except AttributeError: return max(self.source.data['y_values']) @property def y_min(self): try: return self.source.data['y_values'].min() except AttributeError: return min(self.source.data['y_values']) class PointGlyph(XyGlyph): """A set of glyphs placed in x,y coordinates with the same attributes.""" fill_color = Override(default=DEFAULT_PALETTE[1]) fill_alpha = Override(default=0.7) marker = String(default='circle') size = Float(default=8) def __init__(self, x=None, y=None, color=None, line_color=None, fill_color=None, marker=None, size=None, **kwargs): kwargs['x'] = x kwargs['y'] = y if marker is not None: kwargs['marker'] = marker if size is not None: kwargs['size'] = size if color: line_color = color fill_color = color kwargs['line_color'] = line_color kwargs['fill_color'] = fill_color super(PointGlyph, self).__init__(**kwargs) self.setup() def get_glyph(self): return marker_types[self.marker] def build_renderers(self): glyph_type = self.get_glyph() glyph = glyph_type(x='x_values', y='y_values', line_color=self.line_color, fill_color=self.fill_color, size=self.size, fill_alpha=self.fill_alpha, line_alpha=self.line_alpha) yield GlyphRenderer(glyph=glyph) class LineGlyph(XyGlyph): """Represents a group of data as a line.""" width = Int(default=2) dash = Enum(DashPattern, default='solid') def __init__(self, x=None, y=None, color=None, line_color=None, width=None, dash=None, **kwargs): kwargs['x'] = x kwargs['y'] = y if color is not None and line_color is None: line_color = color if dash is not None: kwargs['dash'] = dash if width is not None: kwargs['width'] = width if line_color is not None: kwargs['line_color'] = line_color super(LineGlyph, self).__init__(**kwargs) self.setup() def build_source(self): if self.x is None: x = self.y.index data = dict(x_values=x, y_values=self.y) elif self.y is None: y = self.x.index data = dict(x_values=self.x, y_values=y) else: data = dict(x_values=self.x, y_values=self.y) return data def build_renderers(self): """Yield a `GlyphRenderer` for the group of data.""" glyph = Line(x='x_values', y='y_values', line_color=self.line_color, line_alpha=self.line_alpha, line_width=self.width, line_dash=self.dash) yield GlyphRenderer(glyph=glyph) class AreaGlyph(LineGlyph): # ToDo: should these be added to composite glyph? stack = Bool(default=False) dodge = Bool(default=False) base = Float(default=0.0, help="""Lower bound of area.""") def __init__(self, **kwargs): line_color = kwargs.get('line_color', None) fill_color = kwargs.get('fill_color', None) color = kwargs.get('color', None) if color is not None: # apply color to line and fill kwargs['fill_color'] = color kwargs['line_color'] = color elif line_color is not None and fill_color is None: # apply line color to fill color by default kwargs['fill_color'] = line_color super(AreaGlyph, self).__init__(**kwargs) self.setup() def build_source(self): data = super(AreaGlyph, self).build_source() x0, y0 = generate_patch_base(pd.Series(list(data['x_values'])), pd.Series(list(data['y_values']))) data['x_values'] = [x0] data['y_values'] = [y0] return data def build_renderers(self): # parse all series. We exclude the first attr as it's the x values # added for the index glyph = Patches( xs='x_values', ys='y_values', fill_alpha=self.fill_alpha, fill_color=self.fill_color, line_color=self.line_color ) renderer = GlyphRenderer(data_source=self.source, glyph=glyph) yield renderer def __stack__(self, glyphs): # ToDo: need to handle case of non-aligned indices, see pandas concat # ToDo: need to address how to aggregate on an index when required # build a list of series areas = [] for glyph in glyphs: areas.append(pd.Series(glyph.source.data['y_values'][0], index=glyph.source.data['x_values'][0])) # concat the list of indexed y values into dataframe df = pd.concat(areas, axis=1) # calculate stacked values along the rows stacked_df = df.cumsum(axis=1) # lower bounds of each area series are diff between stacked and orig values lower_bounds = stacked_df - df # reverse the df so the patch is drawn in correct order lower_bounds = lower_bounds.iloc[::-1] # concat the upper and lower bounds together stacked_df = pd.concat([stacked_df, lower_bounds]) # update the data in the glyphs for i, glyph in enumerate(glyphs): glyph.source.data['x_values'] = [stacked_df.index.values] glyph.source.data['y_values'] = [stacked_df.ix[:, i].values] def get_nested_extent(self, col, func): return [getattr(arr, func)() for arr in self.source.data[col]] @property def x_max(self): return max(self.get_nested_extent('x_values', 'max')) @property def x_min(self): return min(self.get_nested_extent('x_values', 'min')) @property def y_max(self): return max(self.get_nested_extent('y_values', 'max')) @property def y_min(self): return min(self.get_nested_extent('y_values', 'min')) class HorizonGlyph(AreaGlyph): num_folds = Int(default=3, help="""The count of times the data is overlapped.""") series = Int(default=0, help="""The id of the series as the order it will appear, starting from 0.""") series_count = Int() fold_height = Float(help="""The height of one fold.""") bins = List(Float, help="""The binedges calculated from the number of folds, and the maximum value of the entire source data.""") graph_ratio = Float(help="""Scales heights of each series based on number of folds and the number of total series being plotted. """) pos_color = Color("#006400", help="""The color used for positive values.""") neg_color = Color("#6495ed", help="""The color used for negative values.""") flip_neg = Bool(default=True, help="""When True, the negative values will be plotted as their absolute value, then their individual axes is flipped. If False, then the negative values will still be taken as their absolute value, but the base of their shape will start from the same origin as the positive values. """) def __init__(self, bins=None, **kwargs): # fill alpha depends on how many folds will be layered kwargs['fill_alpha'] = 1.0/kwargs['num_folds'] if bins is not None: kwargs['bins'] = bins # each series is shifted up to a synthetic y-axis kwargs['base'] = kwargs['series'] * max(bins) / kwargs['series_count'] kwargs['graph_ratio'] = float(kwargs['num_folds'])/float(kwargs['series_count']) super(HorizonGlyph, self).__init__(**kwargs) def build_source(self): data = {} # Build columns for the positive values pos_y = self.y.copy() pos_y[pos_y < 0] = 0 xs, ys = self._build_dims(self.x, pos_y) # list of positive colors and alphas colors = [self.pos_color] * len(ys) alphas = [(bin_idx * self.fill_alpha) for bin_idx in range(0, len(self.bins))] # If we have negative values at all, add the values for those as well if self.y.min() < 0: neg_y = self.y.copy() neg_y[neg_y > 0] = 0 neg_y = abs(neg_y) neg_xs, neg_ys = self._build_dims(self.x, neg_y, self.flip_neg) xs += neg_xs ys += neg_ys colors += ([self.neg_color] * len(neg_ys)) alphas += alphas # create clipped representation of each band data['x_values'] = xs data['y_values'] = ys data['fill_color'] = colors data['fill_alpha'] = colors data['line_color'] = colors return data def _build_dims(self, x, y, flip=False): """ Creates values needed to plot each fold of the horizon glyph. Bins the data based on the binning passed into the glyph, then copies and clips the values for each bin. Args: x (`pandas.Series`): array of x values y (`pandas.Series`): array of y values flip (bool): whether to flip values, used when handling negative values Returns: tuple(list(`numpy.ndarray`), list(`numpy.ndarray`)): returns a list of arrays for the x values and list of arrays for the y values. The data has been folded and transformed so the patches glyph presents the data in a way that looks like an area chart. """ # assign bins to each y value bin_idx = pd.cut(y, bins=self.bins, labels=False, include_lowest=True) xs, ys = [], [] for idx, bin in enumerate(self.bins[0:-1]): # subtract off values associated with lower bins, to get into this bin temp_vals = y.copy() - (idx * self.fold_height) # clip the values between the fold range and zero temp_vals[bin_idx > idx] = self.fold_height * self.graph_ratio temp_vals[bin_idx < idx] = 0 temp_vals[bin_idx == idx] = self.graph_ratio * temp_vals[bin_idx == idx] # if flipping, we must start the values from the top of each fold's range if flip: temp_vals = (self.fold_height * self.graph_ratio) - temp_vals base = self.base + (self.fold_height * self.graph_ratio) else: base = self.base # shift values up based on index of series temp_vals += self.base val_idx = temp_vals > 0 if pd.Series.any(val_idx): ys.append(temp_vals) xs.append(x) # transform clipped data so it always starts and ends at its base value if len(ys) > 0: xs, ys = map(list, zip(*[generate_patch_base(x, y, base=base) for x, y in zip(xs, ys)])) return xs, ys def build_renderers(self): # parse all series. We exclude the first attr as it's the x values # added for the index glyph = Patches( xs='x_values', ys='y_values', fill_alpha=self.fill_alpha, fill_color='fill_color', line_color='line_color' ) renderer = GlyphRenderer(data_source=self.source, glyph=glyph) yield renderer class StepGlyph(LineGlyph): """Represents a group of data as a stepped line.""" def build_source(self): x = self.x y = self.y if self.x is None: x = self.y.index elif self.y is None: y = self.x.index xs = np.empty(2*len(x)-1, dtype=np.int) xs[::2] = x[:] xs[1::2] = x[1:] ys = np.empty(2*len(y)-1) ys[::2] = y[:] ys[1::2] = y[:-1] data = dict(x_values=xs, y_values=ys) return data class AggregateGlyph(NestedCompositeGlyph): """A base composite glyph for aggregating an array. Implements default stacking and dodging behavior that other composite glyphs can inherit. """ x_label = String() x_label_value = Any() stack_label = String() stack_shift = Float(default=0.0) dodge_label = String(help="""Where on the scale the glyph should be placed.""") dodge_shift = Float(default=None) agg = Instance(Stat, default=Sum()) span = Float(help="""The range of values represented by the aggregate.""") def __init__(self, x_label=None, **kwargs): label = kwargs.get('label') if x_label is not None: kwargs['x_label_value'] = x_label if not isinstance(x_label, str): x_label = str(x_label) kwargs['x_label'] = x_label elif label is not None: kwargs['x_label'] = str(label) super(AggregateGlyph, self).__init__(**kwargs) def get_dodge_label(self, shift=0.0): """Generate the label defining an offset in relation to a position on a scale.""" if self.dodge_shift is None: shift_str = ':' + str(0.5 + shift) elif self.dodge_shift is not None: shift_str = ':' + str(self.dodge_shift + shift) else: shift_str = '' return str(label_from_index_dict(self.x_label)) + shift_str def filter_glyphs(self, glyphs): """Return only the glyphs that are of the same class.""" return [glyph for glyph in glyphs if isinstance(glyph, self.__class__)] @staticmethod def groupby(glyphs, prop): """Returns a dict of `CompositeGlyph`s, grouped by unique values of prop. For example, if all glyphs had a value of 'a' or 'b' for glyph.prop, the dict would contain two keys, 'a' and 'b', where each value is a list of the glyphs that had each of the values. """ grouped = defaultdict(list) labels = [getattr(glyph, prop) for glyph in glyphs] labels = [tuple(label.values()) if isinstance(label, dict) else label for label in labels] [grouped[label].append(glyph) for label, glyph in zip(labels, glyphs)] labels = pd.Series(labels).drop_duplicates().values return labels, grouped def __stack__(self, glyphs): """Apply relative shifts to the composite glyphs for stacking.""" filtered_glyphs = self.filter_glyphs(glyphs) labels, grouped = self.groupby(filtered_glyphs, 'x_label') for label in labels: group = grouped[label] # separate the negative and positive aggregates into separate groups neg_group = [glyph for glyph in group if glyph.span < 0] pos_group = [glyph for glyph in group if glyph.span >= 0] # apply stacking to each group separately for group in [neg_group, pos_group]: shift = [] for i, glyph in enumerate(group): # save off the top of each rect's height shift.append(glyph.span) if i > 0: glyph.stack_shift = sum(shift[0:i]) glyph.refresh() def __dodge__(self, glyphs): """Apply relative shifts to the composite glyphs for dodging.""" if self.dodge_label is not None: filtered_glyphs = self.filter_glyphs(glyphs) labels, grouped = self.groupby(filtered_glyphs, 'dodge_label') # calculate transformations step = np.linspace(0, 1.0, len(grouped.keys()) + 1, endpoint=False) width = min(0.2, (1. / len(grouped.keys())) ** 1.1) # set bar attributes and re-aggregate for i, label in enumerate(labels): group = grouped[label] for glyph in group: glyph.dodge_shift = step[i + 1] glyph.width = width glyph.refresh() class Interval(AggregateGlyph): """A rectangle representing aggregated values. The interval is a rect glyph where two of the parallel sides represent a summary of values. Each of the two sides is derived from a separate aggregation of the values provided to the interval. .. note:: A bar is a special case interval where one side is pinned and used to communicate a value relative to it. """ width = Float(default=0.8) start_agg = Either(Instance(Stat), Enum(*list(stats.keys())), default=Min(), help=""" The stat used to derive the starting point of the composite glyph.""") end_agg = Either(Instance(Stat), Enum(*list(stats.keys())), default=Max(), help=""" The stat used to derive the end point of the composite glyph.""") start = Float(default=0.0) end = Float() def __init__(self, label, values, **kwargs): kwargs['label'] = label kwargs['values'] = values super(Interval, self).__init__(**kwargs) self.setup() def get_start(self): """Get the value for the start of the glyph.""" if len(self.values.index) == 1: self.start_agg = None return self.values[0] elif isinstance(self.start_agg, str): self.start_agg = stats[self.start_agg]() self.start_agg.set_data(self.values) return self.start_agg.value def get_end(self): """Get the value for the end of the glyph.""" if isinstance(self.end_agg, str): self.end_agg = stats[self.end_agg]() self.end_agg.set_data(self.values) return self.end_agg.value def get_span(self): """The total range between the start and end.""" return self.end - self.start def build_source(self): # ToDo: Handle rotation self.start = self.get_start() self.end = self.get_end() self.span = self.get_span() width = [self.width] if self.dodge_shift is not None: x = [self.get_dodge_label()] else: x = [self.x_label] height = [self.span] y = [self.stack_shift + (self.span / 2.0) + self.start] color = [self.color] fill_alpha = [self.fill_alpha] line_color = [self.line_color] line_alpha = [self.line_alpha] return dict(x=x, y=y, width=width, height=height, color=color, fill_alpha=fill_alpha, line_color=line_color, line_alpha=line_alpha) @property def x_max(self): """The maximum extent of the glyph in x. .. note:: Dodging the glyph can affect the value. """ return (self.dodge_shift or self.x_label_value) + (self.width / 2.0) @property def x_min(self): """The maximum extent of the glyph in y. .. note:: Dodging the glyph can affect the value. """ return (self.dodge_shift or self.x_label_value) - (self.width / 2.0) @property def y_max(self): """Maximum extent of all `Glyph`s. How much we are stacking + the height of the interval + the base of the interval .. note:: the start and end of the glyph can swap between being associated with the min and max when the glyph end represents a negative value. """ return max(self.bottom, self.top) @property def y_min(self): """The minimum extent of all `Glyph`s in y. .. note:: the start and end of the glyph can swap between being associated with the min and max when the glyph end represents a negative value. """ return min(self.bottom, self.top) @property def bottom(self): """The value associated with the start of the stacked glyph.""" return self.stack_shift + self.start @property def top(self): """The value associated with the end of the stacked glyph.""" return self.stack_shift + self.span + self.start def build_renderers(self): """Yields a `GlyphRenderer` associated with a `Rect` glyph.""" glyph = Rect(x='x', y='y', width='width', height='height', fill_color='color', fill_alpha='fill_alpha', line_color='line_color') yield GlyphRenderer(glyph=glyph) class BarGlyph(Interval): """Special case of Interval where the span represents a value. A bar always begins from 0, or the value that is being compared to, and extends to some positive or negative value. """ def __init__(self, label, values, agg='sum', **kwargs): kwargs['end_agg'] = agg kwargs['start_agg'] = None super(BarGlyph, self).__init__(label, values, **kwargs) self.setup() def get_start(self): return 0.0 class DotGlyph(Interval): """Special case of Interval where the span represents a value. A bar always begins from 0, or the value that is being compared to, and extends to some positive or negative value. """ marker = String(default='circle') size = Float(default=8) stem = Bool(False, help=""" Whether to draw a stem from each do to the axis. """) stem_line_width = Float(default=1) stem_color = String(default='black') def __init__(self, label, values, agg='sum', **kwargs): kwargs['end_agg'] = agg super(DotGlyph, self).__init__(label, values, **kwargs) self.setup() def get_start(self): return 0.0 def get_glyph(self): return marker_types[self.marker] def build_renderers(self): if self.stem: yield GlyphRenderer(glyph=Segment( x0='x', y0=0, x1='x', y1='height', line_width=self.stem_line_width, line_color=self.stem_color, line_alpha='fill_alpha') ) glyph_type = self.get_glyph() glyph = glyph_type(x='x', y='height', line_color=self.line_color, fill_color=self.color, size=self.size, fill_alpha='fill_alpha', line_alpha='line_alpha' ) yield GlyphRenderer(glyph=glyph) class QuartileGlyph(Interval): """An interval that has start and end aggregations of quartiles.""" def __init__(self, label, values, interval1, interval2, **kwargs): kwargs['label'] = label kwargs['values'] = values kwargs['start_agg'] = Quantile(interval=interval1) kwargs['end_agg'] = Quantile(interval=interval2) super(QuartileGlyph, self).__init__(**kwargs) self.setup() class BoxGlyph(AggregateGlyph): """Summarizes the distribution with a collection of glyphs. A box glyph produces one "box" for a given array of vales. The box is made up of multiple other child composite glyphs (intervals, scatter) and directly produces glyph renderers for the whiskers, as well. """ q1 = Float(help="""Derived value for 25% of all values.""") q2 = Float(help="""Derived value for 50% of all values.""") q3 = Float(help="""Derived value for 75% of all values.""") iqr = Float() w0 = Float(help='Lower whisker') w1 = Float(help='Upper whisker') q2_glyph = Instance(QuartileGlyph) q3_glyph = Instance(QuartileGlyph) whisker_glyph = Instance(GlyphRenderer) outliers = Either(Bool, Instance(PointGlyph)) marker = String(default='circle') whisker_width = Float(default=0.3) whisker_line_width = Float(default=2) whisker_span_line_width = Float(default=2) whisker_color = String(default='black') outlier_fill_color = String(default='red') outlier_line_color = String(default='red') outlier_size = Float(default=5) bar_color = String(default='DimGrey') def __init__(self, label, values, outliers=True, **kwargs): width = kwargs.pop('width', None) bar_color = kwargs.pop('color', None) or kwargs.get('bar_color', None) or self.lookup('bar_color').class_default() kwargs['outliers'] = kwargs.pop('outliers', None) or outliers kwargs['label'] = label kwargs['values'] = values x_label = kwargs.get('x_label') kwargs['q2_glyph'] = QuartileGlyph(label=label, x_label=x_label, values=values, interval1=0.25, interval2=0.5, width=width, color=bar_color) kwargs['q3_glyph'] = QuartileGlyph(label=label, x_label=x_label, values=values, interval1=0.5, interval2=0.75, width=width, color=bar_color) super(BoxGlyph, self).__init__(**kwargs) self.setup() def build_renderers(self): """Yields all renderers that make up the BoxGlyph.""" self.calc_quartiles() outlier_values = self.values[((self.values < self.w0) | (self.values > self.w1))] self.whisker_glyph = GlyphRenderer(glyph=Segment(x0='x0s', y0='y0s', x1='x1s', y1='y1s', line_width=self.whisker_line_width, line_color=self.whisker_color)) if len(outlier_values) > 0 and self.outliers: self.outliers = PointGlyph(label=self.label, y=outlier_values, x=[self.get_dodge_label()] * len(outlier_values), line_color=self.outlier_line_color, fill_color=self.outlier_fill_color, size=self.outlier_size, marker=self.marker) for comp_glyph in self.composite_glyphs: for renderer in comp_glyph.renderers: yield renderer yield self.whisker_glyph def calc_quartiles(self): """Sets all derived stat properties of the BoxGlyph.""" self.q1 = self.q2_glyph.start self.q2 = self.q2_glyph.end self.q3 = self.q3_glyph.end self.iqr = self.q3 - self.q1 mx = Max() mx.set_data(self.values) mn = Min() mn.set_data(self.values) self.w0 = max(self.q1 - (1.5 * self.iqr), mn.value) self.w1 = min(self.q3 + (1.5 * self.iqr), mx.value) def build_source(self): """Calculate stats and builds and returns source for whiskers.""" self.calc_quartiles() x_label = self.get_dodge_label() x_w0_label = self.get_dodge_label(shift=(self.whisker_width / 2.0)) x_w1_label = self.get_dodge_label(shift=-(self.whisker_width / 2.0)) # span0, whisker bar0, span1, whisker bar1 x0s = [x_label, x_w0_label, x_label, x_w0_label] y0s = [self.w0, self.w0, self.q3, self.w1] x1s = [x_label, x_w1_label, x_label, x_w1_label] y1s = [self.q1, self.w0, self.w1, self.w1] return dict(x0s=x0s, y0s=y0s, x1s=x1s, y1s=y1s) def _set_sources(self): """Set the column data source on the whisker glyphs.""" self.whisker_glyph.data_source = self.source def get_extent(self, func, prop_name): return func([getattr(renderer, prop_name) for renderer in self.composite_glyphs]) @property def composite_glyphs(self): """Returns list of composite glyphs, excluding the regular glyph renderers.""" comp_glyphs = [self.q2_glyph, self.q3_glyph] if isinstance(self.outliers, PointGlyph): comp_glyphs.append(self.outliers) return comp_glyphs @property def x_max(self): return self.get_extent(max, 'x_max') + self.right_buffer @property def x_min(self): return self.get_extent(min, 'x_min') - self.left_buffer @property def y_max(self): return max(self.w1, self.get_extent(max, 'y_max')) + self.top_buffer @property def y_min(self): return min(self.w0, self.get_extent(min, 'y_min')) - self.bottom_buffer class HistogramGlyph(AggregateGlyph): """Depicts the distribution of values using rectangles created by binning. The histogram represents a distribution, so will likely include other options for displaying it, such as KDE and cumulative density. """ # input properties bin_width = Float() bin_count = Float(help="""Provide a manually specified number of bins to use.""") # derived models bins = Instance(Bins, help="""A stat used to calculate the bins. The bins stat includes attributes about each composite bin.""") bars = List(Instance(BarGlyph), help="""The histogram is comprised of many BarGlyphs that are derived from the values.""") def __init__(self, values, label=None, color=None, bin_count=None, **kwargs): if label is not None: kwargs['label'] = label kwargs['values'] = values kwargs['bin_count'] = bin_count if color is not None: kwargs['color'] = color # remove width, since this is handled automatically kwargs.pop('width', None) super(HistogramGlyph, self).__init__(**kwargs) self.setup() def _set_sources(self): # No need to set sources, since composite glyphs handle this pass def build_source(self): # No need to build source, since composite glyphs handle this return None def build_renderers(self): """Yield a bar glyph for each bin.""" self.bins = Bins(values=self.values, bin_count=self.bin_count) centers = [bin.center for bin in self.bins.bins] self.bin_width = centers[1] - centers[0] bars = [] for bin in self.bins.bins: bars.append(BarGlyph(label=self.label, x_label=bin.center, values=bin.values, color=self.color, fill_alpha=self.fill_alpha, agg=bin.stat, width=self.bin_width)) # provide access to bars as children for bounds properties self.bars = bars self.children = self.bars for comp_glyph in self.bars: for renderer in comp_glyph.renderers: yield renderer @property def y_min(self): return 0.0 class BinGlyph(XyGlyph): """Represents a group of data that was aggregated and is represented by a glyph. """ bins = Instance(Bins) column = String() stat = String() glyph_name = String() width = Float() height = Float() def __init__(self, x, y, values, column=None, stat='count', glyph='rect', width=1, height=1, **kwargs): df = pd.DataFrame(dict(x_vals=x, y_vals=y, values_vals=values)) df.drop_duplicates(inplace=True) kwargs['x'] = df.x_vals kwargs['y'] = df.y_vals kwargs['values'] = df.values_vals kwargs['column'] = column kwargs['stat'] = stat kwargs['glyph_name'] = glyph kwargs['height'] = height kwargs['width'] = width if 'glyphs' not in kwargs: kwargs['glyphs'] = {'rect': Rect} super(XyGlyph, self).__init__(**kwargs) self.setup() def build_source(self): return {'x': self.x, 'y': self.y, 'values': self.values} def build_renderers(self): glyph_class = self.glyphs[self.glyph_name] glyph = glyph_class(x='x', y='y', height=self.height, width=self.width, fill_color=self.fill_color, line_color=self.line_color, dilate=True) yield GlyphRenderer(glyph=glyph) @property def x_max(self): return self.get_data_range('x')[1] + self.width / 2.0 @property def x_min(self): return self.get_data_range('x')[0] - self.width / 2.0 @property def y_max(self): return self.get_data_range('y')[1] + self.height / 2.0 @property def y_min(self): return self.get_data_range('y')[0] - self.height / 2.0 def get_data_range(self, col): data = self.source.data[col] if ChartDataSource.is_number(data): return min(data), max(data) else: return 1, len(data.drop_duplicates())
"""Symbolic primitives + unicode/ASCII abstraction for pretty.py""" from __future__ import print_function, division import sys import warnings unicode_warnings = '' from sympy.core.compatibility import u, unicode, range # first, setup unicodedate environment try: import unicodedata def U(name): """unicode character by name or None if not found""" try: u = unicodedata.lookup(name) except KeyError: u = None global unicode_warnings unicode_warnings += 'No \'%s\' in unicodedata\n' % name return u except ImportError: unicode_warnings += 'No unicodedata available\n' U = lambda name: None from sympy.printing.conventions import split_super_sub from sympy.core.alphabets import greeks # prefix conventions when constructing tables # L - LATIN i # G - GREEK beta # D - DIGIT 0 # S - SYMBOL + __all__ = ['greek_unicode', 'sub', 'sup', 'xsym', 'vobj', 'hobj', 'pretty_symbol', 'annotated'] _use_unicode = False def pretty_use_unicode(flag=None): """Set whether pretty-printer should use unicode by default""" global _use_unicode global unicode_warnings if flag is None: return _use_unicode if flag and unicode_warnings: # print warnings (if any) on first unicode usage warnings.warn(unicode_warnings) unicode_warnings = '' use_unicode_prev = _use_unicode _use_unicode = flag return use_unicode_prev def pretty_try_use_unicode(): """See if unicode output is available and leverage it if possible""" try: symbols = [] # see, if we can represent greek alphabet symbols.extend(greek_unicode.values()) # and atoms symbols += atoms_table.values() for s in symbols: if s is None: return # common symbols not present! encoding = getattr(sys.stdout, 'encoding', None) # this happens when e.g. stdout is redirected through a pipe, or is # e.g. a cStringIO.StringO if encoding is None: return # sys.stdout has no encoding # try to encode s.encode(encoding) except UnicodeEncodeError: pass else: pretty_use_unicode(True) def xstr(*args): """call str or unicode depending on current mode""" if _use_unicode: return unicode(*args) else: return str(*args) # GREEK g = lambda l: U('GREEK SMALL LETTER %s' % l.upper()) G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper()) greek_letters = list(greeks) # make a copy # deal with Unicode's funny spelling of lambda greek_letters[greek_letters.index('lambda')] = 'lamda' # {} greek letter -> (g,G) greek_unicode = dict([(l, (g(l), G(l))) for l in greek_letters]) greek_unicode = dict((L, g(L)) for L in greek_letters) greek_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_letters) # aliases greek_unicode['lambda'] = greek_unicode['lamda'] greek_unicode['Lambda'] = greek_unicode['Lamda'] greek_unicode['varsigma'] = u('\N{GREEK SMALL LETTER FINAL SIGMA}') digit_2txt = { '0': 'ZERO', '1': 'ONE', '2': 'TWO', '3': 'THREE', '4': 'FOUR', '5': 'FIVE', '6': 'SIX', '7': 'SEVEN', '8': 'EIGHT', '9': 'NINE', } symb_2txt = { '+': 'PLUS SIGN', '-': 'MINUS', '=': 'EQUALS SIGN', '(': 'LEFT PARENTHESIS', ')': 'RIGHT PARENTHESIS', '[': 'LEFT SQUARE BRACKET', ']': 'RIGHT SQUARE BRACKET', '{': 'LEFT CURLY BRACKET', '}': 'RIGHT CURLY BRACKET', # non-std '{}': 'CURLY BRACKET', 'sum': 'SUMMATION', 'int': 'INTEGRAL', } # SUBSCRIPT & SUPERSCRIPT LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper()) GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper()) DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit]) SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb]) LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper()) DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit]) SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb]) sub = {} # symb -> subscript symbol sup = {} # symb -> superscript symbol # latin subscripts for l in 'aeioruvx': sub[l] = LSUB(l) for l in 'in': sup[l] = LSUP(l) for gl in ['beta', 'gamma', 'rho', 'phi', 'chi']: sub[gl] = GSUB(gl) for d in [str(i) for i in range(10)]: sub[d] = DSUB(d) sup[d] = DSUP(d) for s in '+-=()': sub[s] = SSUB(s) sup[s] = SSUP(s) # Variable modifiers # TODO: Is it worth trying to handle faces with, e.g., 'MATHEMATICAL BOLD CAPITAL A'? # TODO: Make brackets adjust to height of contents modifier_dict = { # Accents 'mathring': lambda s: s+u('\N{COMBINING RING ABOVE}'), 'ddddot': lambda s: s+u('\N{COMBINING DIAERESIS}\N{COMBINING DIAERESIS}'), 'dddot': lambda s: s+u('\N{COMBINING DIAERESIS}\N{COMBINING DOT ABOVE}'), 'ddot': lambda s: s+u('\N{COMBINING DIAERESIS}'), 'dot': lambda s: s+u('\N{COMBINING DOT ABOVE}'), 'check': lambda s: s+u('\N{COMBINING CARON}'), 'breve': lambda s: s+u('\N{COMBINING BREVE}'), 'acute': lambda s: s+u('\N{COMBINING ACUTE ACCENT}'), 'grave': lambda s: s+u('\N{COMBINING GRAVE ACCENT}'), 'tilde': lambda s: s+u('\N{COMBINING TILDE}'), 'hat': lambda s: s+u('\N{COMBINING CIRCUMFLEX ACCENT}'), 'bar': lambda s: s+u('\N{COMBINING OVERLINE}'), 'vec': lambda s: s+u('\N{COMBINING RIGHT ARROW ABOVE}'), 'prime': lambda s: s+u(' \N{COMBINING VERTICAL LINE ABOVE}'), 'prm': lambda s: s+u(' \N{COMBINING VERTICAL LINE ABOVE}'), # # Faces -- these are here for some compatibility with latex printing # 'bold': lambda s: s, # 'bm': lambda s: s, # 'cal': lambda s: s, # 'scr': lambda s: s, # 'frak': lambda s: s, # Brackets 'norm': lambda s: u('\N{DOUBLE VERTICAL LINE}')+s+u('\N{DOUBLE VERTICAL LINE}'), 'avg': lambda s: u('\N{MATHEMATICAL LEFT ANGLE BRACKET}')+s+u('\N{MATHEMATICAL RIGHT ANGLE BRACKET}'), 'abs': lambda s: u('\N{VERTICAL LINE}')+s+u('\N{VERTICAL LINE}'), 'mag': lambda s: u('\N{VERTICAL LINE}')+s+u('\N{VERTICAL LINE}'), } # VERTICAL OBJECTS HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb]) CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb]) MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb]) EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb]) HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb]) CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb]) TOP = lambda symb: U('%s TOP' % symb_2txt[symb]) BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb]) # {} '(' -> (extension, start, end, middle) 1-character _xobj_unicode = { # vertical symbols # (( ext, top, bot, mid ), c1) '(': (( EXT('('), HUP('('), HLO('(') ), '('), ')': (( EXT(')'), HUP(')'), HLO(')') ), ')'), '[': (( EXT('['), CUP('['), CLO('[') ), '['), ']': (( EXT(']'), CUP(']'), CLO(']') ), ']'), '{': (( EXT('{}'), HUP('{'), HLO('{'), MID('{') ), '{'), '}': (( EXT('{}'), HUP('}'), HLO('}'), MID('}') ), '}'), '|': U('BOX DRAWINGS LIGHT VERTICAL'), '<': ((U('BOX DRAWINGS LIGHT VERTICAL'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')), '<'), '>': ((U('BOX DRAWINGS LIGHT VERTICAL'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), '>'), 'lfloor': (( EXT('['), EXT('['), CLO('[') ), U('LEFT FLOOR')), 'rfloor': (( EXT(']'), EXT(']'), CLO(']') ), U('RIGHT FLOOR')), 'lceil': (( EXT('['), CUP('['), EXT('[') ), U('LEFT CEILING')), 'rceil': (( EXT(']'), CUP(']'), EXT(']') ), U('RIGHT CEILING')), 'int': (( EXT('int'), U('TOP HALF INTEGRAL'), U('BOTTOM HALF INTEGRAL') ), U('INTEGRAL')), 'sum': (( U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), '_', U('OVERLINE'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), U('N-ARY SUMMATION')), # horizontal objects #'-': '-', '-': U('BOX DRAWINGS LIGHT HORIZONTAL'), '_': U('LOW LINE'), # We used to use this, but LOW LINE looks better for roots, as it's a # little lower (i.e., it lines up with the / perfectly. But perhaps this # one would still be wanted for some cases? # '_': U('HORIZONTAL SCAN LINE-9'), # diagonal objects '\' & '/' ? '/': U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'), '\\': U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), } _xobj_ascii = { # vertical symbols # (( ext, top, bot, mid ), c1) '(': (( '|', '/', '\\' ), '('), ')': (( '|', '\\', '/' ), ')'), # XXX this looks ugly # '[': (( '|', '-', '-' ), '['), # ']': (( '|', '-', '-' ), ']'), # XXX not so ugly :( '[': (( '[', '[', '[' ), '['), ']': (( ']', ']', ']' ), ']'), '{': (( '|', '/', '\\', '<' ), '{'), '}': (( '|', '\\', '/', '>' ), '}'), '|': '|', '<': (( '|', '/', '\\' ), '<'), '>': (( '|', '\\', '/' ), '>'), 'int': ( ' | ', ' /', '/ ' ), # horizontal objects '-': '-', '_': '_', # diagonal objects '\' & '/' ? '/': '/', '\\': '\\', } def xobj(symb, length): """Construct spatial object of given length. return: [] of equal-length strings """ if length <= 0: raise ValueError("Length should be greater than 0") # TODO robustify when no unicodedat available if _use_unicode: _xobj = _xobj_unicode else: _xobj = _xobj_ascii vinfo = _xobj[symb] c1 = top = bot = mid = None if not isinstance(vinfo, tuple): # 1 entry ext = vinfo else: if isinstance(vinfo[0], tuple): # (vlong), c1 vlong = vinfo[0] c1 = vinfo[1] else: # (vlong), c1 vlong = vinfo ext = vlong[0] try: top = vlong[1] bot = vlong[2] mid = vlong[3] except IndexError: pass if c1 is None: c1 = ext if top is None: top = ext if bot is None: bot = ext if mid is not None: if (length % 2) == 0: # even height, but we have to print it somehow anyway... # XXX is it ok? length += 1 else: mid = ext if length == 1: return c1 res = [] next = (length - 2)//2 nmid = (length - 2) - next*2 res += [top] res += [ext]*next res += [mid]*nmid res += [ext]*next res += [bot] return res def vobj(symb, height): """Construct vertical object of a given height see: xobj """ return '\n'.join( xobj(symb, height) ) def hobj(symb, width): """Construct horizontal object of a given width see: xobj """ return ''.join( xobj(symb, width) ) # RADICAL # n -> symbol root = { 2: U('SQUARE ROOT'), # U('RADICAL SYMBOL BOTTOM') 3: U('CUBE ROOT'), 4: U('FOURTH ROOT'), } # RATIONAL VF = lambda txt: U('VULGAR FRACTION %s' % txt) # (p,q) -> symbol frac = { (1, 2): VF('ONE HALF'), (1, 3): VF('ONE THIRD'), (2, 3): VF('TWO THIRDS'), (1, 4): VF('ONE QUARTER'), (3, 4): VF('THREE QUARTERS'), (1, 5): VF('ONE FIFTH'), (2, 5): VF('TWO FIFTHS'), (3, 5): VF('THREE FIFTHS'), (4, 5): VF('FOUR FIFTHS'), (1, 6): VF('ONE SIXTH'), (5, 6): VF('FIVE SIXTHS'), (1, 8): VF('ONE EIGHTH'), (3, 8): VF('THREE EIGHTHS'), (5, 8): VF('FIVE EIGHTHS'), (7, 8): VF('SEVEN EIGHTHS'), } # atom symbols _xsym = { '==': ('=', '='), '<': ('<', '<'), '>': ('>', '>'), '<=': ('<=', U('LESS-THAN OR EQUAL TO')), '>=': ('>=', U('GREATER-THAN OR EQUAL TO')), '!=': ('!=', U('NOT EQUAL TO')), '*': ('*', U('DOT OPERATOR')), '-->': ('-->', U('EM DASH') + U('EM DASH') + U('BLACK RIGHT-POINTING TRIANGLE') if U('EM DASH') and U('BLACK RIGHT-POINTING TRIANGLE') else None), '==>': ('==>', U('BOX DRAWINGS DOUBLE HORIZONTAL') + U('BOX DRAWINGS DOUBLE HORIZONTAL') + U('BLACK RIGHT-POINTING TRIANGLE') if U('BOX DRAWINGS DOUBLE HORIZONTAL') and U('BOX DRAWINGS DOUBLE HORIZONTAL') and U('BLACK RIGHT-POINTING TRIANGLE') else None), '.': ('*', U('RING OPERATOR')), } def xsym(sym): """get symbology for a 'character'""" op = _xsym[sym] if _use_unicode: return op[1] else: return op[0] # SYMBOLS atoms_table = { # class how-to-display 'Exp1': U('SCRIPT SMALL E'), 'Pi': U('GREEK SMALL LETTER PI'), 'Infinity': U('INFINITY'), 'NegativeInfinity': U('INFINITY') and ('-' + U('INFINITY')), # XXX what to do here #'ImaginaryUnit': U('GREEK SMALL LETTER IOTA'), #'ImaginaryUnit': U('MATHEMATICAL ITALIC SMALL I'), 'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'), 'EmptySet': U('EMPTY SET'), 'Naturals': U('DOUBLE-STRUCK CAPITAL N'), 'Integers': U('DOUBLE-STRUCK CAPITAL Z'), 'Reals': U('DOUBLE-STRUCK CAPITAL R'), 'Union': U('UNION'), 'SymmetricDifference': U('INCREMENT'), 'Intersection': U('INTERSECTION'), 'Ring': U('RING OPERATOR') } def pretty_atom(atom_name, default=None): """return pretty representation of an atom""" if _use_unicode: return atoms_table[atom_name] else: if default is not None: return default raise KeyError('only unicode') # send it default printer def pretty_symbol(symb_name): """return pretty representation of a symbol""" # let's split symb_name into symbol + index # UC: beta1 # UC: f_beta if not _use_unicode: return symb_name name, sups, subs = split_super_sub(symb_name) def translate(s) : gG = greek_unicode.get(s) if gG is not None: return gG for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) : if s.lower().endswith(key) and len(s)>len(key): return modifier_dict[key](translate(s[:-len(key)])) return s name = translate(name) # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are # not used at all. def pretty_list(l, mapping): result = [] for s in l: pretty = mapping.get(s) if pretty is None: try: # match by separate characters pretty = ''.join([mapping[c] for c in s]) except KeyError: return None result.append(pretty) return result pretty_sups = pretty_list(sups, sup) if pretty_sups is not None: pretty_subs = pretty_list(subs, sub) else: pretty_subs = None # glue the results into one string if pretty_subs is None: # nice formatting of sups/subs did not work if subs: name += '_'+'_'.join([translate(s) for s in subs]) if sups: name += '__'+'__'.join([translate(s) for s in sups]) return name else: sups_result = ' '.join(pretty_sups) subs_result = ' '.join(pretty_subs) return ''.join([name, sups_result, subs_result]) def annotated(letter): """ Return a stylised drawing of the letter ``letter``, together with information on how to put annotations (super- and subscripts to the left and to the right) on it. See pretty.py functions _print_meijerg, _print_hyper on how to use this information. """ ucode_pics = { 'F': (2, 0, 2, 0, u('\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n' '\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n' '\N{BOX DRAWINGS LIGHT UP}')), 'G': (3, 0, 3, 1, u('\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n' '\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n' '\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}')) } ascii_pics = { 'F': (3, 0, 3, 0, ' _\n|_\n|\n'), 'G': (3, 0, 3, 1, ' __\n/__\n\_|') } if _use_unicode: return ucode_pics[letter] else: return ascii_pics[letter]
import os import re import shutil from ...workspace_factory import workspace_factory from ....utils import in_temporary_directory, temporary_directory from ....utils import assert_cmd_success from ....utils import assert_cmd_failure from ....utils import assert_files_exist from ....utils import catkin_success from ....utils import catkin_failure from ....utils import redirected_stdio from ....workspace_assertions import assert_workspace_initialized from ....workspace_assertions import assert_no_warnings TEST_DIR = os.path.dirname(__file__) RESOURCES_DIR = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') BUILD = ['build', '--no-notify', '--no-status'] CLEAN = ['clean', '--yes'] BUILD_TYPES = ['cmake', 'catkin'] def create_flat_workspace(wf, build_type, n_pkgs): """Create a bunch of packages with no interdependencies""" for i in range(n_pkgs): wf.create_package('pkg_{}'.format(i)) def create_chain_workspace(wf, build_type, n_pkgs): """Create a bunch of packages, each of which depends on one other in the workspace except for the root.""" for i in range(n_pkgs): wf.create_package( 'pkg_{}'.format(i), depends=(['pkg_{}'.format(i - 1)] if i > 0 else [])) def create_tree_workspace(wf, build_type, n_pkg_layers, n_children=2): """Create a bunch of packages which form a balanced dependency tree""" n_pkgs = pow(n_children, n_pkg_layers + 1) - 1 for i in range(n_pkgs): wf.create_package( 'pkg_{}'.format(i), build_type=build_type, depends=(['pkg_{}'.format(int((i - 1) / n_children))] if i > 0 else [])) return n_pkgs @in_temporary_directory def test_build_no_src(): """Calling catkin build without a source space should fail.""" assert catkin_failure(BUILD) def test_build_auto_init_no_pkgs(): """Test automatically initializing a workspace with no packages.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: wf.build() assert catkin_success(BUILD) assert_workspace_initialized('.') assert_no_warnings(out) def test_build_auto_init_with_pkg(): """Test automatically initializing a workspace.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: wf.create_package('pkg_a') wf.build() assert catkin_success(BUILD) assert_workspace_initialized('.') assert_no_warnings(out) def test_build_dry_run(): """Test showing the build jobs without doing anything.""" with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_tree_workspace(wf, build_type, 3) wf.build() assert catkin_success(BUILD + ['--dry-run']) assert not os.path.exists('build') assert not os.path.exists('devel') def test_build_all_isolate_install(): """Test building dependent catkin packages with isolated installspace.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: n_pkgs = create_tree_workspace(wf, 'catkin', 2) wf.create_package('pkg_dep', build_type='catkin', build_depends=['pkg_{}'.format(n) for n in range(n_pkgs)]) wf.build() assert catkin_success(['config', '--isolate-install', '--install']) assert catkin_success(BUILD) assert os.path.exists('install/pkg_dep') assert_no_warnings(out) def test_build_all_isolate_devel(): """Test building dependent catkin packages with isolated develspace.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: n_pkgs = create_tree_workspace(wf, 'catkin', 2) wf.create_package('pkg_dep', build_type='catkin', build_depends=['pkg_{}'.format(n) for n in range(n_pkgs)]) wf.build() assert catkin_success(['config', '--isolate-devel']) assert catkin_success(BUILD) assert os.path.exists('devel/pkg_dep') assert not os.path.exists('install') assert_no_warnings(out) def test_build_all_merged(): """Test building all packages in a merged workspace""" pass # TODO: Implement test def test_build_pkg(): """Test building a package by name. """ with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_chain_workspace(wf, build_type, 4) wf.build() assert catkin_failure(BUILD + ['pkg_nil']) assert catkin_success(BUILD + ['pkg_2']) assert os.path.exists(os.path.join('build', 'pkg_0')) assert os.path.exists(os.path.join('build', 'pkg_1')) assert os.path.exists(os.path.join('build', 'pkg_2')) assert not os.path.exists(os.path.join('build', 'pkg_3')) def test_build_no_deps(): """Test building a package by name without deps.""" with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_chain_workspace(wf, build_type, 3) wf.build() # --no-deps needs an argument assert catkin_failure(BUILD + ['--no-deps']) # only pkg_2 shuold be built assert catkin_success(BUILD + ['pkg_2', '--no-deps']) assert os.path.exists(os.path.join('build', 'pkg_2')) assert not os.path.exists(os.path.join('build', 'pkg_1')) assert not os.path.exists(os.path.join('build', 'pkg_0')) def test_build_start_with(): """Test building all packages starting with a specific one.""" with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_chain_workspace(wf, build_type, 4) wf.build() # --start-with needs an argument assert catkin_failure(BUILD + ['--start-with']) # --start-with needs a valid package assert catkin_failure(BUILD + ['--start-with', 'pkg_nil']) # this should build all packages assert catkin_success(BUILD + ['--start-with', 'pkg_0']) for i in range(4): assert os.path.exists(os.path.join('build', 'pkg_{}'.format(i))) assert catkin_success(CLEAN) # this should skip pkg_2's deps assert catkin_success(BUILD + ['--start-with', 'pkg_2']) assert not os.path.exists(os.path.join('build', 'pkg_0')) assert not os.path.exists(os.path.join('build', 'pkg_1')) assert os.path.exists(os.path.join('build', 'pkg_2')) assert os.path.exists(os.path.join('build', 'pkg_3')) assert catkin_success(CLEAN) def test_unbuilt_linked(): """Test building packages which have yet to be built""" with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_chain_workspace(wf, build_type, 2) wf.build() # only pkg_0 shuold be built assert catkin_success(BUILD + ['pkg_0', '--no-deps']) # the rest should be built, but pkg_0 shouldn't be rebuilt assert os.path.exists(os.path.join('build', 'pkg_0')) assert not os.path.exists(os.path.join('build', 'pkg_1')) pkg_0_log_path = os.path.join('logs', 'pkg_0') # build the unbuilt packages (rebuild deps) pkg_0_log_files = os.listdir(pkg_0_log_path) assert catkin_success(BUILD + ['--unbuilt']) assert os.path.exists(os.path.join('build', 'pkg_0')) assert os.path.exists(os.path.join('build', 'pkg_1')) # make sure pkg_0 has been rebuilt assert pkg_0_log_files != os.listdir(pkg_0_log_path) # build the unbuilt packages (don't rebuild deps) pkg_0_log_files = os.listdir(pkg_0_log_path) assert catkin_success(['clean', 'pkg_1']) assert catkin_success(BUILD + ['--unbuilt', '--no-deps']) assert os.path.exists(os.path.join('build', 'pkg_0')) assert os.path.exists(os.path.join('build', 'pkg_1')) # make sure pkg_0 hasn't been rebuilt assert pkg_0_log_files == os.listdir(pkg_0_log_path) def test_unbuilt_isolated(): """Test building unbuilt packages with an isolated develspace.""" pass # TODO: This should succeed, but isn't implemented for isolated develspaces def test_unbuilt_merged(): """Test building unbuilt packages with a merged develspace.""" pass # TODO: This should fail, but the check hsan't been tested def test_continue_on_failure(): """Test behavior when some packages fail to build.""" pass # TODO: Write test def test_preclean(): """Test pre-cleaning packages in a workspace.""" pass # TODO: Write test def test_force_cmake(): """Test forcing cmake to run on packages in a workspace.""" pass # TODO: Write test def test_install(): """Test building and installing catkin packages without DESTDIR""" with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_chain_workspace(wf, build_type, 2) wf.build() assert catkin_success(['config', '--install']) assert catkin_success(BUILD) assert os.path.exists(os.path.join('install')) def test_install_cmake(): """Test building and installing cmake packages without DESTDIR.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: print(os.getcwd()) wf.build() shutil.copytree( os.path.join(RESOURCES_DIR, 'cmake_pkgs'), os.path.join('src/cmake_pkgs')) assert catkin_success(['config', '--install']) assert catkin_success(BUILD) assert os.path.exists(os.path.join('install')) def test_install_cmake_destdir(): """Test building and installing cmake packages with DESTDIR.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: print(os.getcwd()) wf.build() shutil.copytree( os.path.join(RESOURCES_DIR, 'cmake_pkgs'), os.path.join('src/cmake_pkgs')) tmpinstall_path = os.path.join(os.getcwd(), 'tmpinstall') env = {'DESTDIR': tmpinstall_path} assert catkin_success(['config', '--install', '--install-space', '/opt/foo'], env) assert catkin_success(BUILD, env) assert os.path.exists(tmpinstall_path) assert not os.path.exists(os.path.join('install')) def test_install_catkin_destdir(): """Test building and installing catkin packages with DESTDIR.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: print(os.getcwd()) wf.build() shutil.copytree( os.path.join(RESOURCES_DIR, 'catkin_pkgs', 'products_0'), os.path.join('src', 'products_0')) tmpinstall_path = os.path.join(os.getcwd(), 'tmpinstall') env = {'DESTDIR': tmpinstall_path} install_space = os.path.abspath(os.path.join('opt', 'foo')) assert catkin_success(['config', '--install', '--install-space', install_space], env) assert catkin_success(BUILD, env) assert os.path.exists(tmpinstall_path) assert not os.path.exists(os.path.join('install')) # check for _CATKIN_SETUP_DIR setup_sh_path = os.path.join(tmpinstall_path, install_space.lstrip(os.sep), 'setup.sh') print(setup_sh_path) assert os.path.exists(setup_sh_path) setup_dir_correct = False with open(setup_sh_path, "r") as setup_sh: for line in setup_sh: if re.search('_CATKIN_SETUP_DIR:={}'.format(install_space), line): setup_dir_correct = True break assert setup_dir_correct is True def test_pkg_with_unicode_names(): """Test building a package with unicode file names.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: print(os.getcwd()) wf.build() shutil.copytree( os.path.join(RESOURCES_DIR, 'catkin_pkgs', 'products_unicode'), os.path.join('src/products_unicode')) assert catkin_success(['config', '--link-devel']) assert catkin_success(BUILD) def test_glob_pattern_build(): """Test building multiple packages given as glob pattern""" with redirected_stdio() as (out, err): for build_type in BUILD_TYPES: with workspace_factory() as wf: create_flat_workspace(wf, build_type, 11) wf.build() assert catkin_success(BUILD + ['pkg_1*']) assert not os.path.exists(os.path.join('build', 'pkg_0')) assert os.path.exists(os.path.join('build', 'pkg_1')) assert os.path.exists(os.path.join('build', 'pkg_10')) assert not os.path.exists(os.path.join('build', 'pkg_2')) assert not os.path.exists(os.path.join('build', 'pkg_3')) assert not os.path.exists(os.path.join('build', 'pkg_4')) assert not os.path.exists(os.path.join('build', 'pkg_5')) assert not os.path.exists(os.path.join('build', 'pkg_6')) assert not os.path.exists(os.path.join('build', 'pkg_7')) assert not os.path.exists(os.path.join('build', 'pkg_8')) assert not os.path.exists(os.path.join('build', 'pkg_9')) def test_pkg_with_conditional_build_type(): """Test building a dual catkin/ament package.""" with redirected_stdio() as (out, err): with workspace_factory() as wf: print(os.getcwd()) wf.build() shutil.copytree( os.path.join(RESOURCES_DIR, 'catkin_pkgs', 'build_type_condition'), os.path.join('src/build_type_condition')) assert catkin_success(['config', '--merge-devel']) assert catkin_success(BUILD) # Currently the build verb skips over packages it doesn't know how to build. # So we have to infer this skipping by checking the build directory. msg = "Package with ROS 2 conditional build_type was skipped." assert os.path.exists(os.path.join('build', 'build_type_condition')), msg def test_pkg_with_conditional_depend(): """Test building a package with a condition attribute in the depend tag""" with redirected_stdio() as (out, err): with workspace_factory() as wf: wf.create_package('ros1_pkg') wf.create_package('ros2_pkg') wf.build() shutil.copytree( os.path.join(RESOURCES_DIR, 'catkin_pkgs', 'depend_condition'), os.path.join('src/depend_condition')) assert catkin_success(BUILD + ['depend_condition'], env={'ROS_VERSION': '1'}) assert os.path.exists(os.path.join('build', 'depend_condition')) assert os.path.exists(os.path.join('build', 'ros1_pkg')) assert not os.path.exists(os.path.join('build', 'ros2_pkg')) def test_symlinked_workspace(): """Test building from a symlinked workspace""" with redirected_stdio() as (out, err): with workspace_factory() as wf: wf.create_package('pkg') wf.build() assert catkin_success(BUILD) with temporary_directory() as t: os.symlink(wf.workspace, os.path.join(t, 'ws')) assert catkin_success(BUILD + ['-w', os.path.join(t, 'ws')]) def test_generate_setup_util(): """Test generation of setup utilities in a linked devel space""" with redirected_stdio() as (out, err): with workspace_factory() as wf: wf.create_package('pkg') wf.build() # Test that the files are generated in a clean workspace assert catkin_success(['config', '--install']) assert catkin_success(BUILD) assert os.path.exists(os.path.join(wf.workspace, 'devel', '_setup_util.py')) assert os.path.exists(os.path.join(wf.workspace, 'install', '_setup_util.py')) # Test that the files are regenerated after clean assert catkin_success(['clean', '--yes']) assert catkin_success(BUILD) assert os.path.exists(os.path.join(wf.workspace, 'devel', '_setup_util.py')) assert os.path.exists(os.path.join(wf.workspace, 'install', '_setup_util.py')) # Test that the files are regenerated after cleaning the install space assert catkin_success(['clean', '--yes', '--install']) assert catkin_success(BUILD) assert os.path.exists(os.path.join(wf.workspace, 'devel', '_setup_util.py')) assert os.path.exists(os.path.join(wf.workspace, 'install', '_setup_util.py'))
"""The tests for the geolocation trigger.""" import pytest from homeassistant.components import automation, zone from homeassistant.core import Context from homeassistant.setup import async_setup_component from tests.common import async_mock_service, mock_component from tests.components.automation import common @pytest.fixture def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation") @pytest.fixture(autouse=True) def setup_comp(hass): """Initialize components.""" mock_component(hass, "group") hass.loop.run_until_complete( async_setup_component( hass, zone.DOMAIN, { "zone": { "name": "test", "latitude": 32.880837, "longitude": -117.237561, "radius": 250, } }, ) ) async def test_if_fires_on_zone_enter(hass, calls): """Test for firing on zone enter.""" context = Context() hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758, "source": "test_source"}, ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "enter", }, "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "zone.name", ) ) }, }, } }, ) hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564}, context=context, ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].context.parent_id == context.id assert ( calls[0].data["some"] == "geo_location - geo_location.entity - hello - hello - test" ) # Set out of zone again so we can trigger call hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758}, ) await hass.async_block_till_done() await common.async_turn_off(hass) await hass.async_block_till_done() hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564}, ) await hass.async_block_till_done() assert len(calls) == 1 async def test_if_not_fires_for_enter_on_zone_leave(hass, calls): """Test for not firing on zone leave.""" hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564, "source": "test_source"}, ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "enter", }, "action": {"service": "test.automation"}, } }, ) hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758}, ) await hass.async_block_till_done() assert len(calls) == 0 async def test_if_fires_on_zone_leave(hass, calls): """Test for firing on zone leave.""" hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564, "source": "test_source"}, ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "leave", }, "action": {"service": "test.automation"}, } }, ) hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758, "source": "test_source"}, ) await hass.async_block_till_done() assert len(calls) == 1 async def test_if_not_fires_for_leave_on_zone_enter(hass, calls): """Test for not firing on zone enter.""" hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.881011, "longitude": -117.234758, "source": "test_source"}, ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "leave", }, "action": {"service": "test.automation"}, } }, ) hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564}, ) await hass.async_block_till_done() assert len(calls) == 0 async def test_if_fires_on_zone_appear(hass, calls): """Test for firing if entity appears in zone.""" assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "enter", }, "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "zone.name", ) ) }, }, } }, ) # Entity appears in zone without previously existing outside the zone. context = Context() hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564, "source": "test_source"}, context=context, ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].context.parent_id == context.id assert ( calls[0].data["some"] == "geo_location - geo_location.entity - - hello - test" ) async def test_if_fires_on_zone_disappear(hass, calls): """Test for firing if entity disappears from zone.""" hass.states.async_set( "geo_location.entity", "hello", {"latitude": 32.880586, "longitude": -117.237564, "source": "test_source"}, ) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "leave", }, "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "zone.name", ) ) }, }, } }, ) # Entity disappears from zone without new coordinates outside the zone. hass.states.async_remove("geo_location.entity") await hass.async_block_till_done() assert len(calls) == 1 assert ( calls[0].data["some"] == "geo_location - geo_location.entity - hello - - test" )
"""Generic (shallow and deep) copying operations. Interface summary: import copy x = copy.copy(y) # make a shallow copy of y x = copy.deepcopy(y) # make a deep copy of y For module specific errors, copy.Error is raised. The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances). - A shallow copy constructs a new compound object and then (to the extent possible) inserts *the same objects* into it that the original contains. - A deep copy constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original. Two problems often exist with deep copy operations that don't exist with shallow copy operations: a) recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop b) because deep copy copies *everything* it may copy too much, e.g. administrative data structures that should be shared even between copies Python's deep copy operation avoids these problems by: a) keeping a table of objects already copied during the current copying pass b) letting user-defined classes override the copying operation or the set of components copied This version does not copy types like module, class, function, method, nor stack trace, stack frame, nor file, socket, window, nor array, nor any similar types. Classes can use the same interfaces to control copying that they use to control pickling: they can define methods called __getinitargs__(), __getstate__() and __setstate__(). See the documentation for module "pickle" for information on these methods. """ import types import weakref from copyreg import dispatch_table class Error(Exception): pass error = Error # backward compatibility try: from org.python.core import PyStringMap except ImportError: PyStringMap = None __all__ = ["Error", "copy", "deepcopy"] def copy(x): """Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ cls = type(x) copier = _copy_dispatch.get(cls) if copier: return copier(x) if issubclass(cls, type): # treat it as a regular class: return _copy_immutable(x) copier = getattr(cls, "__copy__", None) if copier is not None: return copier(x) reductor = dispatch_table.get(cls) if reductor is not None: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor is not None: rv = reductor(4) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: raise Error("un(shallow)copyable object of type %s" % cls) if isinstance(rv, str): return x return _reconstruct(x, None, *rv) _copy_dispatch = d = {} def _copy_immutable(x): return x for t in (type(None), int, float, bool, complex, str, tuple, bytes, frozenset, type, range, slice, types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented), types.FunctionType, weakref.ref): d[t] = _copy_immutable t = getattr(types, "CodeType", None) if t is not None: d[t] = _copy_immutable d[list] = list.copy d[dict] = dict.copy d[set] = set.copy d[bytearray] = bytearray.copy if PyStringMap is not None: d[PyStringMap] = PyStringMap.copy del d, t def deepcopy(x, memo=None, _nil=[]): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) y = memo.get(d, _nil) if y is not _nil: return y cls = type(x) copier = _deepcopy_dispatch.get(cls) if copier is not None: y = copier(x, memo) else: if issubclass(cls, type): y = _deepcopy_atomic(x, memo) else: copier = getattr(x, "__deepcopy__", None) if copier is not None: y = copier(memo) else: reductor = dispatch_table.get(cls) if reductor: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor is not None: rv = reductor(4) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: raise Error( "un(deep)copyable object of type %s" % cls) if isinstance(rv, str): y = x else: y = _reconstruct(x, memo, *rv) # If is its own copy, don't memoize. if y is not x: memo[d] = y _keep_alive(x, memo) # Make sure x lives at least as long as d return y _deepcopy_dispatch = d = {} def _deepcopy_atomic(x, memo): return x d[type(None)] = _deepcopy_atomic d[type(Ellipsis)] = _deepcopy_atomic d[type(NotImplemented)] = _deepcopy_atomic d[int] = _deepcopy_atomic d[float] = _deepcopy_atomic d[bool] = _deepcopy_atomic d[complex] = _deepcopy_atomic d[bytes] = _deepcopy_atomic d[str] = _deepcopy_atomic d[types.CodeType] = _deepcopy_atomic d[type] = _deepcopy_atomic d[types.BuiltinFunctionType] = _deepcopy_atomic d[types.FunctionType] = _deepcopy_atomic d[weakref.ref] = _deepcopy_atomic def _deepcopy_list(x, memo, deepcopy=deepcopy): y = [] memo[id(x)] = y append = y.append for a in x: append(deepcopy(a, memo)) return y d[list] = _deepcopy_list def _deepcopy_tuple(x, memo, deepcopy=deepcopy): y = [deepcopy(a, memo) for a in x] # We're not going to put the tuple in the memo, but it's still important we # check for it, in case the tuple contains recursive mutable structures. try: return memo[id(x)] except KeyError: pass for k, j in zip(x, y): if k is not j: y = tuple(y) break else: y = x return y d[tuple] = _deepcopy_tuple def _deepcopy_dict(x, memo, deepcopy=deepcopy): y = {} memo[id(x)] = y for key, value in x.items(): y[deepcopy(key, memo)] = deepcopy(value, memo) return y d[dict] = _deepcopy_dict if PyStringMap is not None: d[PyStringMap] = _deepcopy_dict def _deepcopy_method(x, memo): # Copy instance methods return type(x)(x.__func__, deepcopy(x.__self__, memo)) d[types.MethodType] = _deepcopy_method del d def _keep_alive(x, memo): """Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself... """ try: memo[id(memo)].append(x) except KeyError: # aha, this is the first one :-) memo[id(memo)]=[x] def _reconstruct(x, memo, func, args, state=None, listiter=None, dictiter=None, deepcopy=deepcopy): deep = memo is not None if deep and args: args = (deepcopy(arg, memo) for arg in args) y = func(*args) if deep: memo[id(x)] = y if state is not None: if deep: state = deepcopy(state, memo) if hasattr(y, '__setstate__'): y.__setstate__(state) else: if isinstance(state, tuple) and len(state) == 2: state, slotstate = state else: slotstate = None if state is not None: y.__dict__.update(state) if slotstate is not None: for key, value in slotstate.items(): setattr(y, key, value) if listiter is not None: if deep: for item in listiter: item = deepcopy(item, memo) y.append(item) else: for item in listiter: y.append(item) if dictiter is not None: if deep: for key, value in dictiter: key = deepcopy(key, memo) value = deepcopy(value, memo) y[key] = value else: for key, value in dictiter: y[key] = value return y del types, weakref, PyStringMap
# # plots.py -- Utility functions for plotting. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import numpy as np import matplotlib as mpl from matplotlib.figure import Figure from ginga.util import iqcalc as _iqcalc # Prevent namespace confusion below from ginga.misc import Callback, Bunch # fix issue of negative numbers rendering incorrectly with default font mpl.rcParams['axes.unicode_minus'] = False class Plot(Callback.Callbacks): def __init__(self, figure=None, logger=None, width=500, height=500): Callback.Callbacks.__init__(self) if figure is None: figure = Figure() dpi = figure.get_dpi() if dpi is None or dpi < 0.1: dpi = 100 wd_in, ht_in = float(width) / dpi, float(height) / dpi figure.set_size_inches(wd_in, ht_in) self.fig = figure if hasattr(self.fig, 'set_tight_layout'): self.fig.set_tight_layout(True) self.logger = logger self.fontsize = 10 self.ax = None self.logx = False self.logy = False self.xdata = [] self.ydata = [] # for interactive features self.can = Bunch.Bunch(zoom=False, pan=False) # For callbacks for name in ['draw-canvas', 'limits-set', 'motion', 'button-press', 'key-press', 'scroll']: self.enable_callback(name) def get_figure(self): return self.fig def get_widget(self): return self.fig.canvas def add_axis(self, **kwdargs): self.ax = self.fig.add_subplot(111, **kwdargs) return self.ax def get_axis(self): return self.ax def set_axis(self, ax): self.ax = ax def set_titles(self, xtitle=None, ytitle=None, title=None, rtitle=None): if xtitle is not None: self.ax.set_xlabel(xtitle) if ytitle is not None: self.ax.set_ylabel(ytitle) if title is not None: self.ax.set_title(title) if rtitle is not None: pass ax = self.ax for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(self.fontsize) def set_bg(self, color, ax=None): if ax is None: ax = self.ax ax.set_facecolor(color) def clear(self): self.logger.debug('clearing canvas...') self.ax.cla() self.xdata = [] self.ydata = [] self.draw() def draw(self): self.fig.canvas.draw() self.make_callback('draw-canvas') def plot(self, xarr, yarr, xtitle=None, ytitle=None, title=None, rtitle=None, show_legend=False, **kwdargs): if self.ax is None: self.add_axis() if self.logx: self.ax.set_xscale('log') if self.logy: self.ax.set_yscale('log') self.xdata = xarr self.ydata = yarr self.set_titles(xtitle=xtitle, ytitle=ytitle, title=title, rtitle=rtitle) self.ax.grid(True) lines = self.ax.plot(xarr, yarr, **kwdargs) for item in self.ax.get_xticklabels() + self.ax.get_yticklabels(): item.set_fontsize(self.fontsize) # Make x axis labels a little more readable lbls = self.ax.xaxis.get_ticklabels() for lbl in lbls: lbl.set(rotation=45, horizontalalignment='right') if show_legend: self.ax.legend() self.draw() return lines def get_data(self): return self.fig, self.xdata, self.ydata def autoscale(self, axis): self.ax.autoscale(enable=True, axis=axis) self.draw() self.ax.autoscale(enable=False, axis=axis) x1, x2 = self.ax.get_xlim() y1, y2 = self.ax.get_ylim() self.make_callback('limits-set', dict(x_lim=(x1, x2), y_lim=(y1, y2))) def connect_ui(self): canvas = self.fig.canvas if canvas is None: raise ValueError("matplotlib canvas is not yet created") connect = canvas.mpl_connect connect("motion_notify_event", self._plot_motion_notify) connect("button_press_event", self._plot_button_press) connect("scroll_event", self._plot_scroll) connect("key_press_event", self._plot_key_press) def enable(self, pan=False, zoom=False): """If `pan` is True, enable interactive panning in the plot by a middle click. If `zoom` is True , enable interactive zooming in the plot by scrolling. """ self.can.update(dict(pan=pan, zoom=zoom)) if pan or zoom: self.connect_ui() if pan: self.add_callback('button-press', self.plot_do_pan) if zoom: self.add_callback('scroll', self.plot_do_zoom) def _plot_scroll(self, event): self.make_callback('scroll', event) def _plot_button_press(self, event): self.make_callback('button-press', event) def _plot_motion_notify(self, event): self.make_callback('motion', event) def _plot_key_press(self, event): self.make_callback('key-press', event) def plot_do_zoom(self, cb_obj, event): """Can be set as the callback function for the 'scroll' event to zoom the plot. """ if not self.can.zoom: return # Matplotlib only gives us the number of steps of the scroll, # positive for up and negative for down. if event.step > 0: delta = 0.9 elif event.step < 0: delta = 1.1 x1, x2 = self.ax.get_xlim() xrng = x2 - x1 xinc = (delta * xrng - xrng) * 0.5 x1, x2 = x1 - xinc, x2 + xinc y1, y2 = self.ax.get_ylim() yrng = y2 - y1 yinc = (delta * yrng - yrng) * 0.5 y1, y2 = y1 - yinc, y2 + yinc self.ax.set_xlim(x1, x2) self.ax.set_ylim(y1, y2) self.make_callback('limits-set', dict(x_lim=(x1, x2), y_lim=(y1, y2))) self.draw() return True def get_axes_size_in_px(self): bbox = self.ax.get_window_extent().transformed(self.fig.dpi_scale_trans.inverted()) width, height = bbox.width, bbox.height width *= self.fig.dpi height *= self.fig.dpi return (width, height) def plot_do_pan(self, cb_obj, event): """Can be set as the callback function for the 'button-press' event to pan the plot with middle-click. """ if event.button == 2: if not self.can.pan: return self.pan_plot(event.xdata, event.ydata) return True def pan_plot(self, xnew, ynew): x1, x2 = self.ax.get_xlim() xrng = x2 - x1 xinc = xrng * 0.5 x1, x2 = xnew - xinc, xnew + xinc y1, y2 = self.ax.get_ylim() yrng = y2 - y1 yinc = yrng * 0.5 y1, y2 = ynew - yinc, ynew + yinc self.ax.set_xlim(x1, x2) self.ax.set_ylim(y1, y2) self.make_callback('limits-set', dict(x_lim=(x1, x2), y_lim=(y1, y2))) self.draw() class HistogramPlot(Plot): def histogram(self, data, numbins=2048, xtitle=None, ytitle=None, title=None, rtitle=None): minval = np.nanmin(data) maxval = np.nanmax(data) substval = (minval + maxval) * 0.5 data[np.isnan(data)] = substval dist, bins = np.histogram(data, bins=numbins, density=False) # used with 'steps-post' drawstyle, this gives correct histogram-steps x = bins y = np.append(dist, dist[-1]) self.clear() self.plot(x, y, alpha=1.0, linewidth=1.0, linestyle='-', xtitle=xtitle, ytitle=ytitle, title=title, rtitle=rtitle, drawstyle='steps-post') class CutsPlot(Plot): def cuts(self, data, xtitle=None, ytitle=None, title=None, rtitle=None, color=None): """data: pixel values along a line. """ y = data x = np.arange(len(data)) self.plot(x, y, color=color, drawstyle='steps-mid', xtitle=xtitle, ytitle=ytitle, title=title, rtitle=rtitle, alpha=1.0, linewidth=1.0, linestyle='-') class ContourPlot(Plot): def __init__(self, *args, **kwargs): super(ContourPlot, self).__init__(*args, **kwargs) self.num_contours = 8 self.cmap = "RdYlGn_r" # decent choices: { bicubic | bilinear | nearest } self.interpolation = "bilinear" self.cbar = None def _plot_contours(self, x, y, x1, y1, x2, y2, data, num_contours=None): # Make a contour plot if num_contours is None: num_contours = self.num_contours # TEMP: until we figure out a more reliable way to remove # the color bar on all recent versions of matplotlib self.fig.clf() self.ax = self.cbar = None if self.ax is None: self.add_axis() ht, wd = data.shape self.ax.set_aspect('equal', adjustable='box') self.set_titles(title='Contours') # Set pan position in contour plot self.plot_panx = float(x) / wd self.plot_pany = float(y) / ht ## # SEE TEMP, above ## # Seems remove() method is not supported for some recent ## # versions of matplotlib ## if self.cbar is not None: ## self.cbar.remove() self.ax.cla() self.ax.set_facecolor('#303030') try: im = self.ax.imshow(data, interpolation=self.interpolation, origin='lower', cmap=self.cmap) # Create a contour plot self.xdata = np.arange(x1, x2, 1) self.ydata = np.arange(y1, y2, 1) colors = ['black'] * num_contours self.ax.contour(self.xdata, self.ydata, data, num_contours, colors=colors) # cmap=self.cmap ## self.ax.clabel(cs, inline=1, fontsize=10, ## fmt='%5.3f', color='cyan') # Mark the center of the object self.ax.plot([x], [y], marker='x', ms=20.0, color='cyan') if self.cbar is None: self.cbar = self.fig.colorbar(im, orientation='horizontal', shrink=0.8, pad=0.07) else: self.cbar.update_bruteforce(im) # Make x axis labels a little more readable lbls = self.cbar.ax.xaxis.get_ticklabels() for lbl in lbls: lbl.set(rotation=45, horizontalalignment='right') # Set the pan and zoom position & redraw self.draw() except Exception as e: self.logger.error("Error making contour plot: %s" % ( str(e))) def plot_contours_data(self, x, y, data, num_contours=None): ht, wd = data.shape self._plot_contours(x, y, 0, 0, wd, ht, data, num_contours=num_contours) def plot_contours(self, x, y, radius, image, num_contours=None): img_data, x1, y1, x2, y2 = image.cutout_radius(x, y, radius) ## self._plot_contours(x, y, x1, y1, x2, y2, img_data, ## num_contours=num_contours) cx, cy = x - x1, y - y1 self.plot_contours_data(cx, cy, img_data, num_contours=num_contours) class RadialPlot(Plot): def plot_radial(self, x, y, radius, image): x, y, radius = int(round(x)), int(round(y)), int(round(radius)) img_data, x1, y1, x2, y2 = image.cutout_radius(x, y, radius) self.ax.cla() # Make a radial plot self.ax.set_xlim(-0.1, radius) self.set_titles(title="Radial plot", xtitle='Radius [pixels]', ytitle='Pixel Value (ADU)') self.ax.grid(True) try: ht, wd = img_data.shape off_x, off_y = x1, y1 #maxval = np.nanmax(img_data) # create arrays of radius and value r = [] v = [] for i in range(0, wd): for j in range(0, ht): r.append(np.sqrt((off_x + i - x) ** 2 + (off_y + j - y) ** 2)) v.append(img_data[j, i]) r, v = np.array(r), np.array(v) # compute and plot radial fitting # note: you might wanna change `deg` here. coefficients = np.polyfit(x=r, y=v, deg=9) polynomial = np.poly1d(coefficients) x_curve = np.linspace(np.min(r), np.max(r), len(r)) y_curve = polynomial(x_curve) yerror = 0 # for now, no error bars self.ax.errorbar(r, v, yerr=yerror, marker='s', ls='none', mfc='none', mec='#7570b3') self.ax.plot(x_curve, y_curve, '-', color='#1b9e77', lw=2) self.draw() except Exception as e: self.logger.error("Error making radial plot: %s" % ( str(e))) class FWHMPlot(Plot): def __init__(self, *args, **kwargs): super(FWHMPlot, self).__init__(*args, **kwargs) self.iqcalc = _iqcalc.IQCalc(self.logger) def _plot_fwhm_axis(self, arr, iqcalc, skybg, color1, color2, color3, fwhm_method='gaussian'): N = len(arr) X = np.array(list(range(N))) Y = arr # subtract sky background Y = Y - skybg maxv = Y.max() # clamp to 0..max Y = Y.clip(0, maxv) self.logger.debug("Y=%s" % (str(Y))) self.ax.plot(X, Y, color=color1, marker='.') res = iqcalc.calc_fwhm(arr, medv=skybg, method_name=fwhm_method) fwhm, mu = res.fwhm, res.mu # Make a little smoother fitted curve by plotting intermediate # points XN = np.linspace(0.0, float(N), N * 10) Z = np.array([res.fit_fn(x, res.fit_args) for x in XN]) self.ax.plot(XN, Z, color=color1, linestyle=':') self.ax.axvspan(mu - fwhm * 0.5, mu + fwhm * 0.5, facecolor=color3, alpha=0.25) return fwhm def plot_fwhm(self, x, y, radius, image, cutout_data=None, iqcalc=None, fwhm_method='gaussian'): x, y, radius = int(round(x)), int(round(y)), int(round(radius)) x0, y0, xarr, yarr = image.cutout_cross(x, y, radius) if iqcalc is None: iqcalc = self.iqcalc self.ax.cla() #self.ax.set_aspect('equal', adjustable='box') self.set_titles(ytitle='Brightness', xtitle='Pixels', title='FWHM') self.ax.grid(True) # Make a FWHM plot try: # get median value from the cutout area if cutout_data is None: cutout_data, x1, y1, x2, y2 = image.cutout_radius(x, y, radius) skybg = np.ma.median(cutout_data) self.logger.debug("cutting x=%d y=%d r=%d med=%f" % ( x, y, radius, skybg)) self.logger.debug("xarr=%s" % (str(xarr))) fwhm_x = self._plot_fwhm_axis(xarr, iqcalc, skybg, '#7570b3', '#7570b3', 'purple', fwhm_method=fwhm_method) self.logger.debug("yarr=%s" % (str(yarr))) fwhm_y = self._plot_fwhm_axis(yarr, iqcalc, skybg, '#1b9e77', '#1b9e77', 'seagreen', fwhm_method=fwhm_method) falg = fwhm_method self.ax.legend(('data x', '%s x' % falg, 'data y', '%s y' % falg), loc='upper right', shadow=False, fancybox=False, prop={'size': 8}, labelspacing=0.2) self.set_titles(title="FWHM X: %.2f Y: %.2f" % (fwhm_x, fwhm_y)) self.draw() except Exception as e: self.logger.error("Error making fwhm plot: %s" % ( str(e))) def plot_fwhm_data(self, x, y, radius, arr_data, iqcalc=None, fwhm_method='gaussian'): x, y, radius = int(round(x)), int(round(y)), int(round(radius)) if iqcalc is None: iqcalc = self.iqcalc x0, y0, xarr, yarr = iqcalc.cut_cross(x, y, radius, arr_data) self.ax.cla() self.set_titles(ytitle='Brightness', xtitle='Pixels', title='FWHM') self.ax.grid(True) # Make a FWHM plot try: # get median value from the cutout area skybg = np.ma.median(arr_data) self.logger.debug("cutting x=%d y=%d r=%d med=%f" % ( x, y, radius, skybg)) self.logger.debug("xarr=%s" % (str(xarr))) fwhm_x = self._plot_fwhm_axis(xarr, iqcalc, skybg, '#7570b3', '#7570b3', 'purple', fwhm_method=fwhm_method) self.logger.debug("yarr=%s" % (str(yarr))) fwhm_y = self._plot_fwhm_axis(yarr, iqcalc, skybg, '#1b9e77', '#1b9e77', 'seagreen', fwhm_method=fwhm_method) falg = fwhm_method self.ax.legend(('data x', '%s x' % falg, 'data y', '%s y' % falg), loc='upper right', shadow=False, fancybox=False, prop={'size': 8}, labelspacing=0.2) self.set_titles(title="FWHM X: %.2f Y: %.2f" % (fwhm_x, fwhm_y)) self.draw() except Exception as e: self.logger.error("Error making fwhm plot: {}".format(e)) class EEPlot(Plot): """Class to handle plotting of encircled and ensquared energy (EE) values.""" def plot_ee(self, encircled_energy_function=None, ensquared_energy_function=None, sampling_radius=None, total_radius=None): """ Parameters ---------- encircled_energy_function, ensquared_energy_function : obj or `None` Interpolation function from ``scipy.interpolate.interp1d`` for encircled and ensquared energy (EE) values, respectively. If not given, will skip plotting but at least one needs to be given. sampling_radius : float or `None` Show radius for sampling of EE, if desired. total_radius : float or `None` Show radius where EE is expected to be 1, if desired. """ if (encircled_energy_function is None and ensquared_energy_function is None): raise ValueError('At least one EE function must be provided') self.ax.cla() self.ax.grid(True) x_max = 0 title = '' d = {} if encircled_energy_function: d['Encircled Energy'] = {'func': encircled_energy_function, 'color': '#7570b3', 'marker': 's', 'title_pfx': 'EE(circ)'} if ensquared_energy_function: d['Ensquared Energy'] = {'func': ensquared_energy_function, 'color': '#1b9e77', 'marker': 'x', 'title_pfx': 'EE(sq)'} for key, val in d.items(): func = val['func'] color = val['color'] x = func.x y = func.y x_max = max(x.max(), x_max) self.ax.plot(x, y, color=color, marker=val['marker'], mfc='none', mec=color, label=key) if total_radius and not title: self.ax.axvline(total_radius, color='k', ls='--') if sampling_radius: if title: title += ', ' else: self.ax.axvline(sampling_radius, color='k', ls='--') ys = func(sampling_radius) title += f"{val['title_pfx']}={ys:.3f}" self.ax.plot(sampling_radius, ys, marker='o', ls='none', mfc=color, mec=color, label=None) self.set_titles(title=title, xtitle='Radius [pixels]', ytitle='EE') self.ax.set_xlim(-0.1, x_max) self.ax.legend(loc='lower right', shadow=False, fancybox=False, prop={'size': 8}, labelspacing=0.2) self.draw() class SurfacePlot(Plot): def __init__(self, *args, **kwargs): super(SurfacePlot, self).__init__(*args, **kwargs) self.dx = 21 self.dy = 21 self.floor = None self.ceiling = None self.stride = 1 self.cmap = "RdYlGn_r" def plot_surface(self, x, y, radius, image, cutout_data=None): Z, x1, y1, x2, y2 = image.cutout_radius(x, y, radius) X = np.arange(x1, x2, 1) Y = np.arange(y1, y2, 1) X, Y = np.meshgrid(X, Y) try: from mpl_toolkits.mplot3d import Axes3D # noqa from matplotlib.ticker import LinearLocator, FormatStrFormatter self.ax = self.fig.gca(projection='3d', facecolor='#808080') self.set_titles(ytitle='Y', xtitle='X', title='Surface Plot') self.ax.grid(True) zmin = np.min(Z) if self.floor is None else self.floor zmax = np.max(Z) if self.ceiling is None else self.ceiling sfc = self.ax.plot_surface(X, Y, Z, rstride=self.stride, cstride=self.stride, cmap=self.cmap, linewidth=0, antialiased=False) # TODO: need to determine sensible defaults for these based # on the data self.ax.zaxis.set_major_locator(LinearLocator(10)) self.ax.zaxis.set_major_formatter(FormatStrFormatter('%.0f')) self.ax.set_zlim(zmin, zmax) self.ax.xaxis.set_ticks(np.arange(x1, x2, 10)) self.ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) self.ax.yaxis.set_ticks(np.arange(y1, y2, 10)) self.ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) self.ax.view_init(elev=20.0, azim=30.0) self.fig.colorbar(sfc, orientation='horizontal', shrink=0.9, pad=0.01) self.draw() except Exception as e: self.logger.error("Error making surface plot: %s" % ( str(e))) # END
# Copyright 2014 Google Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenHTF module responsible for managing records of tests.""" import collections import hashlib import inspect import logging import os from enum import Enum import mutablerecords from openhtf import util from openhtf.util import data from openhtf.util import logs _LOG = logging.getLogger(__name__) class InvalidMeasurementDimensions(Exception): """Raised when a measurement is taken with the wrong number of dimensions.""" OutcomeDetails = collections.namedtuple( 'OutcomeDetails', 'code description') Outcome = Enum('Outcome', ['PASS', 'FAIL', 'ERROR', 'TIMEOUT', 'ABORTED']) # pylint: disable=invalid-name # LogRecord is in openhtf.util.logs.LogRecord. class Attachment(collections.namedtuple('Attachment', 'data mimetype')): """Encapsulate attachment data and guessed MIME type.""" @property def sha1(self): return hashlib.sha1(self.data).hexdigest() def _asdict(self): # Don't include the attachment data when converting to dict. return { 'mimetype': self.mimetype, 'sha1': self.sha1, } class TestRecord( # pylint: disable=no-init mutablerecords.Record( 'TestRecord', ['dut_id', 'station_id'], {'start_time_millis': int, 'end_time_millis': None, 'outcome': None, 'outcome_details': list, 'code_info': None, 'metadata': dict, 'phases': list, 'log_records': list, '_cached_record': dict, '_cached_phases': list, '_cached_log_records': list, '_cached_config_from_metadata': dict, })): """The record of a single run of a test.""" def __init__(self, *args, **kwargs): super(TestRecord, self).__init__(*args, **kwargs) # Cache data that does not change during execution. # Cache the metadata config so it does not recursively copied over and over # again. self._cached_config_from_metadata = self.metadata.get('config') self._cached_record = { 'station_id': data.convert_to_base_types(self.station_id), 'code_info': data.convert_to_base_types(self.code_info), } def add_outcome_details(self, code, description=''): """Adds a code with optional description to this record's outcome_details. Args: code: A code name or number. description: A string providing more details about the outcome code. """ self.outcome_details.append(OutcomeDetails(code, description)) def add_phase_record(self, phase_record): self.phases.append(phase_record) self._cached_phases.append(phase_record.as_base_types()) def add_log_record(self, log_record): self.log_records.append(log_record) self._cached_log_records.append(log_record._asdict()) def as_base_types(self): """Convert to a dict representation composed exclusively of base types.""" metadata = data.convert_to_base_types(self.metadata, ignore_keys=('config',)) metadata['config'] = self._cached_config_from_metadata ret = { 'dut_id': data.convert_to_base_types(self.dut_id), 'start_time_millis': self.start_time_millis, 'end_time_millis': self.end_time_millis, 'outcome': data.convert_to_base_types(self.outcome), 'outcome_details': data.convert_to_base_types(self.outcome_details), 'metadata': metadata, 'phases': self._cached_phases, 'log_records': self._cached_log_records, } ret.update(self._cached_record) return ret # PhaseResult enumerations are converted to these outcomes by the PhaseState. PhaseOutcome = Enum( # pylint: disable=invalid-name 'PhaseOutcome', [ 'PASS', # CONTINUE with allowed measurement outcomes. 'FAIL', # CONTINUE with failed measurements or FAIL_AND_CONTINUE. 'SKIP', # SKIP or REPEAT when under the phase's repeat limit. 'ERROR', # Any terminal result. ]) class PhaseRecord( # pylint: disable=no-init mutablerecords.Record( 'PhaseRecord', ['descriptor_id', 'name', 'codeinfo'], {'measurements': None, 'options': None, 'start_time_millis': int, 'end_time_millis': None, 'attachments': dict, 'result': None, 'outcome': None})): """The record of a single run of a phase. Measurement metadata (declarations) and values are stored in separate dictionaries, each of which map measurement name to the respective object. In the case of the measurements field, those objects are measurements.Measurement instances. The 'value' attribute of each of those instances is an instance of measurments.MeasuredValue, which contains either a single value, or a list of values in the case of a dimensioned measurement. See measurements.Record.GetValues() for more information. The 'result' attribute contains a phase_executor.PhaseExecutionOutcome instance, which wraps the openhtf.PhaseResult returned by the phase or an error condition that terminated the phase. The 'outcome' attribute is a PhaseOutcome, which caches the pass/fail outcome of the phase's measurements or indicates that the verification was skipped. """ @classmethod def from_descriptor(cls, phase_desc): return cls(id(phase_desc), phase_desc.name, phase_desc.code_info) def as_base_types(self): """Convert to a dict representation composed exclusively of base types.""" base_types_dict = { k: data.convert_to_base_types(getattr(self, k)) for k in self.optional_attributes } base_types_dict.update( descriptor_id=self.descriptor_id, name=self.name, codeinfo=data.convert_to_base_types(self.codeinfo), ) return base_types_dict def record_start_time(self): """Record the phase start time and return it.""" self.start_time_millis = util.time_millis() return self.start_time_millis def finalize_phase(self, options): self.end_time_millis = util.time_millis() self.options = options def _get_source_safely(obj): try: return inspect.getsource(obj) except Exception: # pylint: disable=broad-except logs.log_once( _LOG.warning, 'Unable to load source code for %s. Only logging this once.', obj) return '' class CodeInfo(mutablerecords.HashableRecord( 'CodeInfo', ['name', 'docstring', 'sourcecode'])): """Information regarding the running tester code.""" @classmethod def for_module_from_stack(cls, levels_up=1): # levels_up is how many frames up to go: # 0: This function (useless). # 1: The function calling this (likely). # 2+: The function calling 'you' (likely in the framework). frame, filename = inspect.stack(context=0)[levels_up][:2] module = inspect.getmodule(frame) source = _get_source_safely(frame) return cls(os.path.basename(filename), inspect.getdoc(module), source) @classmethod def for_function(cls, func): source = _get_source_safely(func) return cls(func.__name__, inspect.getdoc(func), source) @classmethod def uncaptured(cls): return cls('', None, '')
#from seq2seq import ngramlm, neurallm import cPickle, pickle import numpy as np import os from collections import defaultdict import dynet as dy from dynet import * import numpy import random from nltk.tokenize import RegexpTokenizer class Attention: def __init__(self, vocab_size, model, lookup): self.model = model #self.trainer = dy.SimpleSGDTrainer(self.model) self.layers = 1 self.embed_size = 50 self.hidden_size = 128 self.state_size = 128 self.src_vocab_size = vocab_size self.tgt_vocab_size = vocab_size self.attention_size = 32 self.enc_fwd_lstm = dy.LSTMBuilder(self.layers, self.embed_size, self.state_size, model) self.enc_bwd_lstm = dy.LSTMBuilder(self.layers, self.embed_size,self.state_size, model) self.dec_lstm = dy.LSTMBuilder(self.layers, self.state_size*2 + self.embed_size, self.state_size, model) self.input_lookup = lookup self.attention_w1 = model.add_parameters( (self.attention_size, self.state_size*2)) self.attention_w2 = model.add_parameters( (self.attention_size , self.state_size * self.layers* 2)) self.attention_v = model.add_parameters( (1, self.attention_size)) self.decoder_w = model.add_parameters( (self.src_vocab_size , self.state_size )) self.decoder_b = model.add_parameters( ( self.src_vocab_size )) self.output_lookup = lookup self.duration_weight = model.add_parameters(( 1, self.state_size )) self.duration_bias = model.add_parameters( ( 1 )) def run_lstm(self, init_state, input_vecs): s = init_state out_vectors = [] for vector in input_vecs: x_t = lookup(self.input_lookup, int(vector)) s = s.add_input(x_t) out_vector = s.output() out_vectors.append(out_vector) return out_vectors def embed_sentence(self, sentence): sentence = [EOS] + list(sentence) + [EOS] sentence = [char2int[c] for c in sentence] global input_lookup return [input_lookup[char] for char in sentence] def attend(self, input_mat, state, w1dt): #global self.attention_w2 #global self.attention_v w2 = dy.parameter(self.attention_w2) v = dy.parameter(self.attention_v) w2dt = w2*dy.concatenate(list(state.s())) unnormalized = dy.transpose(v * dy.tanh(dy.colwise_add(w1dt, w2dt))) att_weights = dy.softmax(unnormalized) context = input_mat * att_weights return context def test_duration(self, state, idx): dw = dy.parameter(self.duration_weight) db = dy.parameter(self.duration_bias) duration = dy.rectify(dw * state.output() + db) return dy.squared_norm(duration - float(idx)) def decode(self, vectors, output, end_token,durs): #output = [EOS] + list(output) + [EOS] #output = [char2int[c] for c in output] w = dy.parameter(self.decoder_w) b = dy.parameter(self.decoder_b) w1 = dy.parameter(self.attention_w1) input_mat = dy.concatenate_cols(vectors) w1dt = None last_output_embeddings = self.output_lookup[2] s = self.dec_lstm.initial_state().add_input(dy.concatenate([dy.vecInput(self.state_size *2), last_output_embeddings])) loss = [] dur_loss = [] c = 1 for word,dur in zip(output,durs): c += 1 # w1dt can be computed and cached once for the entire decoding phase w1dt = w1dt or w1 * input_mat vector = dy.concatenate([self.attend(input_mat, s, w1dt), last_output_embeddings]) s = s.add_input(vector) k = s #print "Going" dloss = self.test_duration(k, dur) #print "Back" dur_loss.append(dloss) out_vector = w * s.output() + b probs = dy.softmax(out_vector) last_output_embeddings = self.output_lookup[word] loss.append(-dy.log(dy.pick(probs, word))) loss = dy.esum(loss) return loss, dy.esum(dur_loss) def generate(self, sentence): #embedded = embed_sentence(in_seq) encoded = self.encode_sentence(sentence) w = dy.parameter(self.decoder_w) b = dy.parameter(self.decoder_b) w1 = dy.parameter(self.attention_w1) dw = dy.parameter(self.duration_weight) db = dy.parameter(self.duration_bias) #duration = dw * state.output() + db input_mat = dy.concatenate_cols(encoded) w1dt = None last_output_embeddings = self.output_lookup[2] s = self.dec_lstm.initial_state().add_input(dy.concatenate([dy.vecInput(self.state_size * 2), last_output_embeddings])) out = '' res = [] dur_g = [] count_EOS = 0 for i in range(len(sentence)): if count_EOS == 2: break # w1dt can be computed and cached once for the entire decoding phase w1dt = w1dt or w1 * input_mat vector = dy.concatenate([self.attend(input_mat, s, w1dt), last_output_embeddings]) s = s.add_input(vector) #k = s #dloss = self.test_duration(k, i, b) out_vector = w * s.output() + b dur_pred = dw * s.output() + db probs = dy.softmax(out_vector).vec_value() next_word = probs.index(max(probs)) last_output_embeddings = self.output_lookup[next_word] if next_word == 2: count_EOS += 1 continue res.append(next_word) dur_g.append(dy.rectify(dur_pred)) #out += int2char[next_word] return res, dur_g def get_loss(self, sentence,durs): dy.renew_cg() #embedded = self.embed_sentence(sentence) encoded = self.encode_sentence(sentence) end_token = '</s>' return self.decode(encoded, sentence, end_token,durs) def encode_sentence(self, sentence): sentence_rev = list(reversed(sentence)) fwd_vectors = self.run_lstm(self.enc_fwd_lstm.initial_state(), sentence) bwd_vectors = self.run_lstm(self.enc_bwd_lstm.initial_state(), sentence_rev) bwd_vectors = list(reversed(bwd_vectors)) vectors = [dy.concatenate(list(p)) for p in zip(fwd_vectors, bwd_vectors)] return vectors class EncoderDecoder: def __init__(self, vocab_size): self.model = Model() self.trainer = SimpleSGDTrainer(self.model) self.layers = 2 self.embed_size = 128 self.hidden_size = 128 self.src_vocab_size = vocab_size self.tgt_vocab_size = vocab_size self.enc_builder = LSTMBuilder(self.layers, self.embed_size, self.hidden_size, self.model) self.dec_builder = LSTMBuilder(self.layers, self.embed_size, self.hidden_size, self.model) self.src_lookup = self.model.add_lookup_parameters((self.src_vocab_size, self.embed_size)) self.tgt_lookup = self.model.add_lookup_parameters((self.tgt_vocab_size, self.embed_size)) self.W_y = self.model.add_parameters((self.tgt_vocab_size, self.hidden_size)) self.b_y = self.model.add_parameters((self.tgt_vocab_size)) def encode(self, instance, wids): dy.renew_cg() W_y = dy.parameter(self.W_y) b_y = dy.parameter(self.b_y) # print "chceking wids here",wids["about"] src_sent = instance.split() #print "printing src sentnce length", len(src_sent) losses = [] total_words = 0 # Encoder enc_state = self.enc_builder.initial_state() #for current_word in src_sent: for (cw, nw) in zip(src_sent, src_sent[1:]): state = enc_state.add_input(self.src_lookup[wids[cw]]) encoded = (W_y * state.output()) + b_y err = pickneglogsoftmax(encoded, int(wids[nw])) losses.append(err) return dy.esum(losses) dec_state = self.dec_builder.initial_state() dec_state = self.dec_builder.initial_state(encoded) errs = [] # Calculate losses for decoding for (cw, nw) in zip(src_sent, src_sent[1:]): dec_state = dec_state.add_input(self.tgt_lookup[wids[current_word]]) decoded = dec_state.output() ystar = (W_y * dec_state.output()) + b_y #print "current word is >>>>>>>", cw #print "next word shud be", nw loss = dy.pickneglogsoftmax(ystar, wids[nw]) losses.append(loss) ''' total_words += 1 dist_array = [] for i in range(0,len(ystar.value())): dist = numpy.linalg.norm(self.tgt_lookup[wids[nw]].value() - ystar.value()[i]) dist_array.append(dist) #print " predicted next_word ========>", src_sent[dist_array.index(min(dist_array))] ''' return dy.esum(losses) #, total_words, src_sent[dist_array.index(min(dist_array))] class EncoderDecoder_debug: def __init__(self, vocab_size): self.model = dy.Model() self.trainer = dy.SimpleSGDTrainer(self.model) self.layers = 2 self.embed_size = 1 self.hidden_size = 1 self.src_vocab_size = vocab_size self.tgt_vocab_size = vocab_size self.enc_builder = dy.LSTMBuilder(self.layers, self.embed_size, self.hidden_size, self.model) self.dec_builder = dy.LSTMBuilder(self.layers, self.embed_size, self.hidden_size, self.model) self.src_lookup = self.model.add_lookup_parameters((self.src_vocab_size, self.embed_size)) self.tgt_lookup = self.model.add_lookup_parameters((self.tgt_vocab_size, self.embed_size)) self.W_y = self.model.add_parameters((self.tgt_vocab_size, self.hidden_size)) self.b_y = self.model.add_parameters((self.tgt_vocab_size)) def encode(self, instance, wids): dy.renew_cg() W_y = dy.parameter(self.W_y) b_y = dy.parameter(self.b_y) # print "chceking wids here",wids["about"] src_sent = instance.split() #print "printing src sentnce length", len(src_sent) losses = [] total_words = 0 # Encoder enc_state = self.enc_builder.initial_state() for current_word in src_sent: state = enc_state.add_input(self.src_lookup[wids[current_word]]) encoded = (W_y * state.output()) + b_y dec_state = self.dec_builder.initial_state() dec_state = self.dec_builder.initial_state(encoded) errs = [] # Calculate losses for decoding for (cw, nw) in zip(src_sent, src_sent[1:]): dec_state = dec_state.add_input(self.tgt_lookup[wids[current_word]]) decoded = dec_state.output() ystar = (W_y * dec_state.output()) + b_y print "current word is >>>>>>>", cw print "next word shud be", nw #loss = dy.pickneglogsoftmax(ystar, wids[nw]) for wid in wids: loss = dy.pickneglogsoftmax(ystar, wids[wid]) print "Loss for ", wid, " w.r.t ", nw, " is ", loss.value() from collections import defaultdict from itertools import count import sys class RNNLanguageModel: def __init__(self, model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=SimpleRNNBuilder): self.builder = builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) self.lookup = model.add_lookup_parameters((VOCAB_SIZE, INPUT_DIM)) self.R = model.add_parameters((VOCAB_SIZE, HIDDEN_DIM)) self.bias = model.add_parameters((VOCAB_SIZE)) def save_to_disk(self, filename): model.save(filename, [self.builder, self.lookup, self.R, self.bias]) def load_from_disk(self, filename): (self.builder, self.lookup, self.R, self.bias) = model.load(filename) def build_lm_graph(self, sent): renew_cg() init_state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) errs = [] # will hold expressions es=[] state = init_state for (cw,nw) in zip(sent,sent[1:]): # assume word is already a word-id x_t = lookup(self.lookup, int(cw)) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) err = pickneglogsoftmax(r_t, int(nw)) errs.append(err) nerr = esum(errs) return nerr def predict_next_word(self, sentence): renew_cg() init_state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) state = init_state for cw in sentence: # assume word is already a word-id x_t = lookup(self.lookup, int(cw)) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) prob = softmax(r_t) return prob def sample(self, first=1, nchars=0, stop=-1): res = [first] renew_cg() state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) cw = first while True: x_t = lookup(self.lookup, cw) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) ydist = softmax(r_t) dist = ydist.vec_value() rnd = random.random() for i,p in enumerate(dist): rnd -= p if rnd <= 0: break res.append(i) cw = i if cw == stop: break if nchars and len(res) > nchars: break return res class RNNEncoderDecoder: def __init__(self, model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, lookup, builder=SimpleRNNBuilder): self.builder = builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) self.lookup = lookup self.R = model.add_parameters((VOCAB_SIZE, HIDDEN_DIM)) self.bias = model.add_parameters((VOCAB_SIZE)) def save_to_disk(self, filename): model.save(filename, [self.builder, self.lookup, self.R, self.bias]) def load_from_disk(self, filename): (self.builder, self.lookup, self.R, self.bias) = model.load(filename) def build_lm_graph(self, sent): renew_cg() init_state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) errs = [] # will hold expressions es=[] state = init_state for (cw,nw) in zip(sent,sent[1:]): # assume word is already a word-id x_t = lookup(self.lookup, int(cw)) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) err = pickneglogsoftmax(r_t, int(nw)) errs.append(err) nerr = esum(errs) #return nerr encoded = r_t dec_state = self.builder.initial_state() dec_state = self.builder.initial_state(encoded) decoder_errs = [] # Calculate losses for decoding for (cw, nw) in zip(sent, sent[1:]): x_t = lookup(self.lookup, int(cw)) dec_state = dec_state.add_input(x_t) y_t = dec_state.output() ystar = (R * y_t) + bias err = pickneglogsoftmax(r_t, int(nw)) decoder_errs.append(err) derr = esum(decoder_errs) return derr def predict_next_word(self, sentence): renew_cg() init_state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) state = init_state for cw in sentence: # assume word is already a word-id x_t = lookup(self.lookup, int(cw)) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) prob = softmax(r_t) return prob def resynth(self, sent): renew_cg() init_state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) errs = [] # will hold expressions es=[] state = init_state for cw in sent: # assume word is already a word-id x_t = lookup(self.lookup, int(cw)) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) err = pickneglogsoftmax(r_t, int(nw)) errs.append(err) nerr = esum(errs) #return nerr encoded = r_t dec_state = self.builder.initial_state() dec_state = self.builder.initial_state(encoded) decoder_errs = [] # Calculate losses for decoding for (cw, nw) in zip(sent, sent[1:]): x_t = lookup(self.lookup, int(cw)) dec_state = dec_state.add_input(x_t) y_t = dec_state.output() ystar = (R * y_t) + bias err = pickneglogsoftmax(r_t, int(nw)) decoder_errs.append(err) derr = esum(decoder_errs) return derr def sample(self, first=1, nchars=0, stop=-1): res = [first] renew_cg() state = self.builder.initial_state() R = parameter(self.R) bias = parameter(self.bias) cw = first while True: x_t = lookup(self.lookup, cw) state = state.add_input(x_t) y_t = state.output() r_t = bias + (R * y_t) ydist = softmax(r_t) dist = ydist.vec_value() rnd = random.random() for i,p in enumerate(dist): rnd -= p if rnd <= 0: break res.append(i) cw = i if cw == stop: break if nchars and len(res) > nchars: break return res class nnlm: def __init__(self): self.feats_and_values ={} self.wids = defaultdict(lambda: len(self.wids)) self.unigrams = {} self.model = dy.Model() self.EMB_SIZE = 1 self.HID_SIZE = 1 self.N = 3 M = self.model.add_lookup_parameters((len(self.wids), self.EMB_SIZE)) W_mh = self.model.add_parameters((self.HID_SIZE, self.EMB_SIZE * (self.N-1))) b_hh = self.model.add_parameters((self.HID_SIZE)) W_hs = self.model.add_parameters((len(self.wids), self.HID_SIZE)) b_s = self.model.add_parameters((len(self.wids))) def read_corpus(self, file): print file tokenizer = RegexpTokenizer(r'\w+') f = open(file) self.data_array_train = [] for line in f: line = '<s> ' + line.split('\n')[0] + ' </s>' words = line.split() for word in words: if word == '<s>' or '</s>': pass else: word = tokenizer.tokenize(word)[0] if word in self.unigrams: self.unigrams[word] = self.unigrams[word] + 1 else: self.unigrams[word] = 1 f.close() self.assign_ids() self.create_data(file) self.save_wids() return self.trigramfeaturedict, self.wids def save_wids(self): f = open('wids.txt','w') for w in self.wids: f.write(w + ' ' + str(self.wids[w]) + '\n') f.close() ''' from nltk.tokenize import RegexpTokenizer def read_corpus(self, file): print file f = open(file) tokenizer = RegexpTokenizer(r'\w+') self.data_array_train = [] for line in f: line = line.split('\n')[0] line = ['<s>'] + tokenizer.tokenize(line) + ['</s>'] words = [w.lower() for w in line] for word in words: if word in self.unigrams: self.unigrams[word] = self.unigrams[word] + 1 else: self.unigrams[word] = 1 f.close() self.assign_ids() self.create_data(file) self.save_wids() return self.trigramfeaturedict, self.wids def save_wids(self): f = open('wids.txt','w') for w in self.wids: f.write(w + ' ' + str(self.wids[w]) + '\n') f.close() ''' def assign_ids(self): self.wids["<unk>"] = 0 self.wids["<s>"] = 1 self.wids["</s>"] = 2 for w in self.unigrams: # if self.unigrams[w] > 3: self.wids[w] # else: # self.wids[w] = 0 #print "prinitn wids frm nnlm--------------", self.wids return def create_data(self, file): self.accumulate_trigramfeatures(file) def build_nnlm_graph(self, dictionary): dy.renew_cg() M = self.model.add_lookup_parameters((len(self.wids), self.EMB_SIZE)) W_mh = self.model.add_parameters((self.HID_SIZE, self.EMB_SIZE * (self.N-1))) b_hh = self.model.add_parameters((self.HID_SIZE)) W_hs = self.model.add_parameters((len(self.wids), self.HID_SIZE)) b_s = self.model.add_parameters((len(self.wids))) w_xh = dy.parameter(W_mh) b_h = dy.parameter(b_hh) W_hy = dy.parameter(W_hs) b_y = dy.parameter(b_s) errs = [] for context, next_word in dictionary: #print context, next_word k = M[self.wids[context.split()[0]]] kk = M[self.wids[context.split()[1]]] #print k , kk #print k.value() x = k.value() + kk.value() #print x h_val = dy.tanh(w_xh * dy.inputVector(x) + b_h) y_val = W_hy * h_val + b_y err = dy.pickneglogsoftmax(y_val,self.wids[next_word]) errs.append(err) gen_err = dy.esum(errs) return gen_err def accumulate_trigramfeatures(self, file): self.trigramfeaturedict = {} g = open(file) for line in g: line = '<s> ' + line.split('\n')[0] + ' </s>' line = line.split() contexts = zip(line[0:len(line)-2], line[1:len(line)-1], line[2:]) for prev_2, prev_1, current in contexts: #print prev_2, prev_1, current context = prev_2 + ' ' + prev_1 self.trigramfeaturedict[context] = current g.close() return class loglinearlm: def __init__(self): self.feats_and_values ={} self.wids = defaultdict(lambda: len(self.wids)) def read_corpus(self, file): print file f = open(file) self.data_array_train = [] for line in f: line = '<s> ' + line.split('\n')[0] + ' </s>' self.data_array_train.append(line) words = line.split() for word in words: wid = self.wids[word] f.close() #self.get_feature_vectors(file) def accumulate_trigramfeatures(self, file): self.trigramfeaturedict = {} g = open(file) for line in g: line = '<s> ' + line.split('\n')[0] + ' </s>' line = line.split() contexts = zip(line[0:len(line)-2], line[1:len(line)-1], line[2:]) for prev_2, prev_1, current in contexts: #print prev_2, prev_1, current context = prev_2 + ' ' + prev_1 self.trigramfeaturedict[context] = current g.close() def print_words(self): for wid in self.wids: print wid, self.wids[wid] def get_vocab_size(self): return len(self.wids) def calculate_feature_F1(self, file): # This is a trigram context feature local_features = [] local_words = [] feature_vector_prime = np.zeros(self.get_vocab_size()) g = open(file) for line in g: line = '<s> ' + line.split('\n')[0] + ' </s>' #print line line = line.split() contexts = zip(line[0:len(line)-2], line[1:len(line)-1], line[2:]) for prev_2, prev_1, current in contexts: feature_vector = feature_vector_prime #print prev_2, prev_1, current, self.get_vocab_size() #print prev_2, self.wids[prev_2], feature_vector prev_2_id = self.wids[prev_2] feature_vector[prev_2_id] = 1.0 prev_1_id = self.wids[prev_1] feature_vector[prev_1_id] = 1.0 local_features.append(feature_vector) local_words.append(current) #print feature_vector #print features[0] g.close() return local_features, local_words def sparse_features_to_dense_features(self, features): ret = np.zeros(len(features)) #print ret for f in features: #print f ret[f] += 1 return ret def get_feature_vectors(self, file): features = [] #features.append(self.sparse_features_to_dense_features(self.calculate_feature_F1(file))) feats,words = self.calculate_feature_F1(file) features.append(feats) #features.append(calculate_feature_F2()) #features.append(calculate_feature_F3()) #features.append(calculate_feature_F4()) #return zip(features, words) return zip(feats, words) class ngramlm: def __init__(self, order): self.order = order self.unigrams = {} self.bigrams = {} self.alpha_unk = 0.02 self.alpha_1 = 0.245 self.alpha_2 = 0.735 self.wids = defaultdict(lambda: len(self.wids)) def get_vocab_size(self): return len(self.wids) def store_counts(self, file): self.get_ngrams(file, self.order) if self.print_flag == 1: print "Unique Unigrams like :", list(self.unigrams)[0], " are ", len(self.unigrams) print "Unique Bigrams like :", list(self.bigrams)[0], " are ", len(self.bigrams) def get_features_v1(self): # This is a basic version which returns wid of every word as feature and its likelihood as target self.training_data = [] self.num_features = 1 c = 1 feature_vector = np.zeros(int(self.get_vocab_size())) # One hot k print feature_vector for line in self.data_array_train: line = line.split() for word in line: feature_vector = np.zeros(int(self.get_vocab_size())) # One hot k c = c + 1 wid = self.wids[word] feature_vector[wid] = 1 if c % 1000 == 1: print word, wid, feature_vector[wid] self.training_data.append(feature_vector) return def feature_function(self, ctxt): features = [] features.append(self.calculate_wid(ctxt)) return features #def get_likelihood(self, word): def calculate_wid(self, ctxt): return wids[ctxt] def read_corpus(self, file): # for each line in the file, split the words and turn them into IDs like this: print file f = open(file) self.data_array_train = [] for line in f: line = line.split('\n')[0] self.data_array_train.append(line) words = line.split() for word in words: wid = self.wids[word] def print_words(self): for wid in self.wids: print wid, self.wids[wid] def print_dicts(self): print "Printing unigrams" for k in self.unigrams: print k,self.unigrams[k] print "Printing bigrams" for k in self.bigrams: print k, self.bigrams[k] def save_dicts(self): with open('unigrams.pkl', 'wb') as f: pickle.dump(self.unigrams, f, pickle.HIGHEST_PROTOCOL) with open('bigrams.pkl', 'wb') as f: pickle.dump(self.bigrams, f, pickle.HIGHEST_PROTOCOL) def load_dicts(self): with open('unigrams.pkl', 'rb') as f: self.unigrams = pickle.load(f) with open('bigrams.pkl', 'rb') as f: self.bigrams = pickle.load(f) def get_counts(self, file): self.print_flag = 1 self.store_counts(file) # Calcuates n grams from a line def ngrams(self,line, n): lst = line.split() output = {} for i in range(len(lst) -n + 1): g = ' '.join(lst[i:i+n]) output.setdefault(g, 0) output[g] += 1 return output def combine_dicts(self, base_dict, small_dict): for key in small_dict: if base_dict.has_key(key): base_dict[key] = int(base_dict[key]) + int(small_dict[key]) else: base_dict[key] = int(small_dict[key]) return base_dict # Calculates n grams from a file def get_ngrams(self, file, count): f = open(file) for line in f: line = '<s> ' + line.split('\n')[0] + ' </s>' bigrams = self.ngrams(line,2) self.bigrams = self.combine_dicts(self.bigrams,bigrams) unigrams = self.ngrams(line,1) self.unigrams = self.combine_dicts(self.unigrams,unigrams) self.remove_singletons(self.unigrams) def remove_singletons(self, base_dict): for key in base_dict: #print key, base_dict[key] if base_dict[key] < 2: #print key base_dict[key] = 0 return def eqn8(self, strng, print_flag): l = len(strng.split()) if l == 1: estimate = (1 - self.alpha_1) * (float(self.unigrams[strng]) / sum(self.unigrams.values())) + self.alpha_unk * np.exp(1e-7) return estimate else: c = strng #strng = strng.split()[:-1] #p = ' '.join(tk for tk in strng) p = c.split()[-1] if print_flag ==1: print "Bigram is ", c print "Unigram is ", p #print (1 - self.alpha_2) * (float(self.bigrams[c]) / self.bigrams.values())) #print estimate = (1 - self.alpha_2) * (float(self.bigrams[c]) / sum(self.bigrams.values())) + (1 - self.alpha_1) * (float(self.unigrams[p]) / sum(self.unigrams.values())) + self.alpha_unk * np.exp(1e-7) return estimate def get_file_perplexity(self, file): f = open(file) print_flag = 0 self.num_sentences = 0 self.num_oovs = 0 self.num_words = 0 self.logprob = 0 arr = [] for line in f: line = line.split('\n')[0].lower() #line = '<s> ' + line.split('\n')[0] + ' </s>' ppl_sentence = self.get_sentence_perplexity(line,0) if print_flag ==1: print line, ppl_sentence, '\n' arr.append(ppl_sentence) #print np.mean(arr) log_arr = np.log(arr) print log_arr ml_corpus = -1.0 * np.sum(log_arr) * 1.0/len(arr) print np.exp(ml_corpus) print 'Sentences: ', self.num_sentences print 'Words: ', self.num_words print 'OOVs: ' , self.num_oovs print 'Log probability: ', self.logprob self.perplexity = np.exp( -1.0 * self.logprob / ( self.num_words + self.num_sentences - self.num_oovs) * 2.71) # SRILM constant print "Perplexity over corpus is: ", self.perplexity def get_sentence_perplexity(self, string, print_flag): #print len(string) num_tokens = 0 num_oovs = 0 if len(string.split()) < 2: print "The Sentence you gave me is very short" return -1.0 * np.log(self.eqn8(string,0) / 2) else: mle_sentence = np.log(1.0) line = string.split('\n')[0] + ' </s>' length_line = len(string.split()) line = line.split() b = 0 while b < len(line) - 1: if print_flag ==1: print "The value of b is ", b kv = line[b] + ' ' + line[b+1] if print_flag ==1: print "I am looking for ", kv if line[b+1] == '</s>': kv = line[b] if print_flag ==1: print "I am looking for ", kv if kv in self.bigrams and self.bigrams[kv] > 0: if print_flag ==1: print "Found ",kv , " in bigrams" mle = self.eqn8(kv,0) length_gram = 2 else: if print_flag ==1: print "I did not find ", kv, " in bigrams" kv = line[b] if print_flag ==1: print "Now, I am searching for ", kv if kv in self.unigrams and self.unigrams[kv] > 0: if print_flag ==1: print "Found ",kv , " in unigrams" mle = self.eqn8(kv,0) length_gram = 1 else: if print_flag ==1: print "I did not find ", kv, " in unigrams or it was a singleton. I think its an UNK" kv = line[b] mle = self.alpha_unk * np.exp(1e-7) length_gram = 1 num_oovs = num_oovs + 1 b = b + length_gram num_tokens = num_tokens + 1 mle_sentence = mle_sentence + np.log(mle) self.num_oovs += num_oovs self.num_sentences += 1 self.num_words += length_line self.logprob += mle_sentence print_flag = 0 mle_sentence_old = mle_sentence mle_sentence = mle_sentence * (- 1.0 / (length_line + 1 +1 - num_oovs ) ) ppl_sentence = np.exp(mle_sentence * 2.3) if print_flag ==1: print "MLE of sentence is ", mle_sentence_old, " and PPL of sentence is ", ppl_sentence, " number of words: ", length_line, " number of OOVs: " , num_oovs g = open('t','w') g.write(string + '\n') g.close() cmd = 'ngram -lm ../data/en-de/01_srilm_bigram.model -ppl t' os.system(cmd) print '\n\n' print_flag = 0 return ppl_sentence
# Copyright 2015 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_utils import uuidutils from osprofiler import profiler from mistral import exceptions as exc from mistral.lang import types from mistral.lang.v2 import base from mistral.lang.v2 import task_defaults from mistral.lang.v2 import tasks from mistral_lib import utils NOOP_COMMAND = 'noop' FAIL_COMMAND = 'fail' SUCCEED_COMMAND = 'succeed' PAUSE_COMMAND = 'pause' ENGINE_COMMANDS = [ NOOP_COMMAND, FAIL_COMMAND, SUCCEED_COMMAND, PAUSE_COMMAND ] class WorkflowSpec(base.BaseSpec): # See http://json-schema.org _polymorphic_key = ('type', 'direct') _meta_schema = { "type": "object", "properties": { "type": types.WORKFLOW_TYPE, "task-defaults": types.NONEMPTY_DICT, "input": types.UNIQUE_STRING_OR_ONE_KEY_DICT_LIST, "output": types.NONEMPTY_DICT, "output-on-error": types.NONEMPTY_DICT, "vars": types.NONEMPTY_DICT, "tags": types.UNIQUE_STRING_LIST }, "required": ["tasks"], "additionalProperties": False } def __init__(self, data, validate): super(WorkflowSpec, self).__init__(data, validate) self._name = data['name'] self._description = data.get('description') self._tags = data.get('tags', []) self._type = data['type'] if 'type' in data else 'direct' self._input = utils.get_dict_from_entries(data.get('input', [])) self._output = data.get('output', {}) self._output_on_error = data.get('output-on-error', {}) self._vars = data.get('vars', {}) self._task_defaults = self._spec_property( 'task-defaults', task_defaults.TaskDefaultsSpec ) # Inject 'type' here, so instantiate_spec function can recognize the # specific subclass of TaskSpec. for task in self._data.get('tasks').values(): task['type'] = self._type self._tasks = self._spec_property('tasks', tasks.TaskSpecList) def validate_schema(self): super(WorkflowSpec, self).validate_schema() if not self._data.get('tasks'): raise exc.InvalidModelException( "Workflow doesn't have any tasks [data=%s]" % self._data ) # Validate expressions. self.validate_expr(self._data.get('output', {})) self.validate_expr(self._data.get('vars', {})) def validate_semantics(self): super(WorkflowSpec, self).validate_semantics() # Distinguish workflow name from workflow UUID. if uuidutils.is_uuid_like(self._name): raise exc.InvalidModelException( "Workflow name cannot be in the format of UUID." ) def _validate_task_link(self, task_name, allow_engine_cmds=True): valid_task = self._task_exists(task_name) if allow_engine_cmds: valid_task |= task_name in ENGINE_COMMANDS if not valid_task: raise exc.InvalidModelException( "Task '%s' not found." % task_name ) def _task_exists(self, task_name): return self.get_tasks()[task_name] is not None def get_name(self): return self._name def get_description(self): return self._description def get_tags(self): return self._tags def get_type(self): return self._type def get_input(self): return self._input def get_output(self): return self._output def get_output_on_error(self): return self._output_on_error def get_vars(self): return self._vars def get_task_defaults(self): return self._task_defaults def get_tasks(self): return self._tasks def get_task(self, name): return self._tasks[name] class DirectWorkflowSpec(WorkflowSpec): _polymorphic_value = 'direct' _schema = { "properties": { "tasks": { "type": "object", "minProperties": 1, "patternProperties": { r"^\w+$": types.NONEMPTY_DICT } }, } } def __init__(self, data, validate): super(DirectWorkflowSpec, self).__init__(data, validate) # Init simple dictionary based caches for inbound and # outbound task specifications. In fact, we don't need # any special cache implementations here because these # structures can't grow indefinitely. self.inbound_tasks_cache = {} self.outbound_tasks_cache = {} @profiler.trace('direct-wf-spec-validate-semantics', hide_args=True) def validate_semantics(self): super(DirectWorkflowSpec, self).validate_semantics() # Check if there are start tasks. if not self.find_start_tasks(): raise exc.DSLParsingException( 'Failed to find start tasks in direct workflow. ' 'There must be at least one task without inbound transition.' '[workflow_name=%s]' % self._name ) self._check_workflow_integrity() self._check_join_tasks() @profiler.trace('direct-wf-spec-check-workflow-integrity', hide_args=True) def _check_workflow_integrity(self): for t_s in self.get_tasks(): out_task_names = self.find_outbound_task_names(t_s.get_name()) for out_t_name in out_task_names: self._validate_task_link(out_t_name) def _check_join_tasks(self): join_tasks = [t for t in self.get_tasks() if t.get_join()] err_msgs = [] for join_t in join_tasks: t_name = join_t.get_name() join_val = join_t.get_join() in_tasks = self.find_inbound_task_specs(join_t) if join_val == 'all': if len(in_tasks) == 0: err_msgs.append( "No inbound tasks for task with 'join: all'" " [task_name=%s]" % t_name ) continue if join_val == 'one': join_val = 1 if len(in_tasks) < join_val: err_msgs.append( "Not enough inbound tasks for task with 'join'" " [task_name=%s, join=%s, inbound_tasks=%s]" % (t_name, join_val, len(in_tasks)) ) if len(err_msgs) > 0: raise exc.InvalidModelException('\n'.join(err_msgs)) def find_start_tasks(self): return [ t_s for t_s in self.get_tasks() if not self.has_inbound_transitions(t_s) ] def find_inbound_task_specs(self, task_spec): task_name = task_spec.get_name() specs = self.inbound_tasks_cache.get(task_name) if specs is not None: return specs specs = [ t_s for t_s in self.get_tasks() if self.transition_exists(t_s.get_name(), task_name) ] self.inbound_tasks_cache[task_name] = specs return specs def find_outbound_task_specs(self, task_spec): task_name = task_spec.get_name() specs = self.outbound_tasks_cache.get(task_name) if specs is not None: return specs specs = [ t_s for t_s in self.get_tasks() if self.transition_exists(task_name, t_s.get_name()) ] self.outbound_tasks_cache[task_name] = specs return specs def has_inbound_transitions(self, task_spec): return len(self.find_inbound_task_specs(task_spec)) > 0 def has_outbound_transitions(self, task_spec): return len(self.find_outbound_task_specs(task_spec)) > 0 def find_outbound_task_names(self, task_name): t_names = set() for tup in self.get_on_error_clause(task_name): t_names.add(tup[0]) for tup in self.get_on_success_clause(task_name): t_names.add(tup[0]) for tup in self.get_on_complete_clause(task_name): t_names.add(tup[0]) return t_names def transition_exists(self, from_task_name, to_task_name): t_names = self.find_outbound_task_names(from_task_name) return to_task_name in t_names def get_on_error_clause(self, t_name): result = [] on_clause = self.get_task(t_name).get_on_error() if on_clause: result = on_clause.get_next() if not result: t_defaults = self.get_task_defaults() if t_defaults and t_defaults.get_on_error(): result = self._remove_task_from_clause( t_defaults.get_on_error().get_next(), t_name ) return result def get_on_success_clause(self, t_name): result = [] on_clause = self.get_task(t_name).get_on_success() if on_clause: result = on_clause.get_next() if not result: t_defaults = self.get_task_defaults() if t_defaults and t_defaults.get_on_success(): result = self._remove_task_from_clause( t_defaults.get_on_success().get_next(), t_name ) return result def get_on_complete_clause(self, t_name): result = [] on_clause = self.get_task(t_name).get_on_complete() if on_clause: result = on_clause.get_next() if not result: t_defaults = self.get_task_defaults() if t_defaults and t_defaults.get_on_complete(): result = self._remove_task_from_clause( t_defaults.get_on_complete().get_next(), t_name ) return result @staticmethod def _remove_task_from_clause(on_clause, t_name): return list([tup for tup in on_clause if tup[0] != t_name]) class ReverseWorkflowSpec(WorkflowSpec): _polymorphic_value = 'reverse' _schema = { "properties": { "tasks": { "type": "object", "minProperties": 1, "patternProperties": { r"^\w+$": types.NONEMPTY_DICT } }, } } def validate_semantics(self): super(ReverseWorkflowSpec, self).validate_semantics() self._check_workflow_integrity() def _check_workflow_integrity(self): for t_s in self.get_tasks(): for req in self.get_task_requires(t_s): self._validate_task_link(req, allow_engine_cmds=False) def get_task_requires(self, task_spec): requires = set(task_spec.get_requires()) defaults = self.get_task_defaults() if defaults: requires |= set(defaults.get_requires()) requires.discard(task_spec.get_name()) return list(requires) class WorkflowSpecList(base.BaseSpecList): item_class = WorkflowSpec class WorkflowListSpec(base.BaseListSpec): item_class = WorkflowSpec def get_workflows(self): return self.get_items()
### Task Serializers ### from datetime import timedelta from django.utils import timezone from django.core.urlresolvers import reverse from rest_framework import serializers from task.models import Task, TaskDirectory, Assignment from item.models import Item from slave.settings import * class AssignmentSerializer(serializers.ModelSerializer): task_name = serializers.SerializerMethodField(read_only=True) task_workflow = serializers.SerializerMethodField(read_only=True) task_type = serializers.SerializerMethodField(read_only=True) date_assigned = serializers.SerializerMethodField(read_only=True) date_released = serializers.SerializerMethodField(read_only=True) # FIXME Add filter by owner and same for Slave selector. task = serializers.PrimaryKeyRelatedField(queryset=Task.objects.filter(_retrieved=False)) class Meta: model = Assignment fields = ('id', 'task', 'task_name', 'task_workflow', 'task_type', 'slave', 'date_assigned', 'date_released') def get_task_name(self, object): """ Get task name. """ return str(object.task) def get_task_workflow(self, object): """ Get task workflow. """ return object.task.type.id def get_task_type(self, object): """ Get task type. """ return object.task.type.get_type_readable() def get_date_assigned(self, object): """ Get date. """ return object.get_date_assigned() def get_date_released(self, object): """ Get date. """ return object.get_date_released() def validate_slave(self, slave): """ Game logic and some authorization is checked here. """ #print("Slave and Game Logic validation") # We make both validation for Slave and Game Logic in this # method, to avoid Task and Slave objects move here and there # many times. # We also assume that Task ownership was checked in POST # validation earlier and we consider Task owner to be the # current User. task = Task.objects.get(pk=self.initial_data['task']) # Verify that Slave and Task have the same owner. if slave.get_owner() != task.get_owner(): #print("Owner of slave {0} is {1}, but owner of task {2} is {3}. Failed to assign!" \ # .format(slave, slave.get_owner(), task, task.get_owner())) raise serializers.ValidationError("Authorization error for this Slave.") # Verify that Task is running. if task.is_retrieved(): raise serializers.ValidationError("Assignment error. Task is finished and retrieved.") # Verify that Task has open vacancy. if not task.has_open_vacancy(): raise serializers.ValidationError("Assignment error. The maximum slaves are working on this task already.") # Verify that Task location has free space. if not task.has_free_space_in_location(): raise serializers.ValidationError("Assignment error. The Task Location is overcrowded.") # Verify that Slave and Task are currently in the same Region. if not slave.get_location().get_region() == task.get_location().get_region(): raise serializers.ValidationError("Region error. Slave is in wrong region.") # Verify that Slave is idle. if slave.get_assignments(active=True).count() > 0: raise serializers.ValidationError("Assignment error. Slave is busy.") # Verify that Slave is of appropriate age. if not slave.is_alive(): raise serializers.ValidationError("Assignment error. Slave is dead.") if slave.is_baby(): raise serializers.ValidationError("Assignment error. Slave is too young.") # Verify that Slave is qualified for this Task. slave_skills = slave.get_trained_skills() # Required primary and secondary skills. ps = task.get_primary_skill() if ps in list(slave_skills.keys()) and slave_skills[ps] > 0: print("The slave posesses primary skill.") else: raise serializers.ValidationError("Assignment error. Slave is not qualified for the task.") return slave class TaskSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) percent_completed = serializers.SerializerMethodField(read_only=True) active_assignments_count = serializers.SerializerMethodField(read_only=True) date_start = serializers.DateTimeField(read_only=True) date_finish = serializers.DateTimeField(read_only=True) class Meta: model = Task fields = ('id', 'name', 'type', 'percent_completed', 'active_assignments_count', 'is_retrieved', 'location', 'owner', 'date_start', 'date_finish') def get_name(self, object): """ Get readable name for Task. """ return object.get_name_readable() def get_percent_completed(self, object): """ Calculate the percentage of finished. """ # Farming tasks (time fixed) if object.get_type().is_time_fixed(): # Return time delta (now-start)/(finish-start) return 100 if timezone.now() > object.get_date_finish() else \ int((timezone.now() - object.get_date_start()) * 100 / \ (object.get_date_finish() - object.get_date_start())) # Crafting, building tasks (work fixed) # Return work required - (fulfilled + current_work_per_day * timedelta(estimated_finish - last_update) elif object.get_type().is_work_fixed(): work_units = object.get_type().get_param('work_units') fulfilled = object.get_fulfilled() # We get a result of actually fulfilled and saved amount of work result = 100.0 if fulfilled > work_units else \ fulfilled * 100.0 / work_units # WARNING! The following can cause high loads. Monitor! # Check if somebody is working on this task now. running_assignments = object.get_assignments(running=True) if running_assignments.count() > 0: # Predict estimate of work done since last Task update. last_update = object.get_date_updated() current_work_per_day = 0 for a in running_assignments: current_work_per_day += a.get_work_per_day() result += ((timezone.now() - last_update).seconds / GAME_DAY) * current_work_per_day #print("Task {0} is actually {1}% completed.".format(object, result)) # We return floored int to avoid float number problems in API. return int(result) else: # In case some new task types appear. return 0 def get_active_assignments_count(self, object): """ Shows the number of active assignments for the task. """ return object.get_assignments(running=True).count() def validate(self, data): """ A little gameplay logic validation. """ # FIXME! Move this AWAY from serializer to Controller!!! # Verify sufficient materials. # print(data) # A little sleepy now to use cooler search in ordered dictionary # As long as data is OrderedDict we convert it to list and take # the required params only. We need location to determine the region # and the TaskWorkflow to get the recipe. for i in list(data.items()): if i[0] == 'type': type = i[1] elif i[0] == 'location': location = i[1] ingredients = type.get_param('ingredients') #print("INGREDIENTS, SELF:", ingredients, self) # As long as there might be no ingredient required, it might be False. # Otherwise we check if there are sufficient materials in storage. # This will be checked again later while saving. if ingredients: hq = location.region.get_locations('hq').first() for i in ingredients: if not Item.objects.exists(item=i.ingredient, location=hq, amount=i.amount): raise serializers.ValidationError( "Not enough ingredient {0}".format(i.ingredient)) return data class TaskDetailSerializer(TaskSerializer): _yield = serializers.FloatField(default=0.0, read_only=True) _fulfilled = serializers.FloatField(default=0.0, read_only=True) date_updated = serializers.DateTimeField(read_only=True) assignments = AssignmentSerializer(many=True, read_only=True) class Meta: model = Task fields = ('id', 'name', 'type', 'percent_completed', 'active_assignments_count','is_retrieved', 'location', 'owner', '_fulfilled', '_yield', 'date_start', 'date_finish', 'date_updated', 'assignments') # FIXME! # This fucks the task on PUT request. :))) # Never use PUT method to update anything in Task. # Task interface should accept only "action". def validate__yield(self, value): """ Reset yield to zero if new Task posted. """ # This is not critical if something is specified. # Simply reset it to zero according to Game logic. # Though this might not be RESTful. if not self.instance: return 0.0 def validate__fulfilled(self, value): """ Reset fulfilled to zero if new Task posted. """ # This is not critical if something is specified. # Simply reset it to zero according to Game logic. # Though this might not be RESTful. if not self.instance: return 0.0 def validate_location(self, location): """ Location must be of correct type and have minimum free space. """ task_type = TaskDirectory.objects.get(pk=self.initial_data.get('type')) # print(task_type) # Authorize location. # This validation moved to VIEW class as we do not longer pass owner manually. #if not location.get_owner().id == int(self.initial_data.get('owner')): #print("Location owner: {0}, you are: {1}".format(location.get_owner(), self.initial_data.get('owner'))) #raise serializers.ValidationError("You are not authorized for this location.") # Verify location type. if not location.get_type() == task_type.get_location_type(): #print (location.get_type()) raise serializers.ValidationError("Wrong type of location for the task.") # Verify free space in location. # The actual USE (reservation) of area will happen later on a # per Slave (per Assignment) basis. Still we check for some minimum. #print("Location required: {0}, free: {1}".format(task_type.get_area_per_worker(), location.get_free_area())) if not location.get_free_area() >= task_type.get_area_per_worker(): raise serializers.ValidationError("Not enough minimum free space in location.") # Succeeded with Location verification. return location def create(self, validated_data): return Task.objects.create(**validated_data) # WHAT IS THIS????? # def update(self, instance, validated_data): # instance._fulfilled = validated_data.get('_fulfilled', instance._fulfilled) # instance._yield = validated_data.get('_yield', instance._yield) # instance.save() # return instance class TaskDirectorySerializer(serializers.ModelSerializer): """ Serialize TaskDirectory items for interface forms. """ class Meta: model = TaskDirectory fields = ('id', 'name', 'location_type', 'area_per_worker', 'max_slaves')
import os import timeit from collections import deque import numpy as np import simplejson as json from ghx.borehole import BoreholeClass from ghx.my_print import PrintClass class BaseGHXClass: """ Base class for GHXArray """ def __init__(self, json_data, loads_path, output_path, print_output=True): """ Class constructor """ self.timer_start = timeit.default_timer() errors_found = False self.output_path = output_path if not os.path.exists(self.output_path): os.makedirs(self.output_path) with open(os.path.join(self.output_path, 'in.json'), 'w') as outfile: json.dump(json_data, outfile, indent=4, sort_keys=True) # load data into data structs PrintClass.my_print("....Loading GHX data") try: self.name = json_data['Name'] except: # pragma: no cover PrintClass.my_print("....'Name' key not found", 'warn') errors_found = True try: self.sim_years = json_data['Simulation Configuration']['Simulation Years'] except: # pragma: no cover PrintClass.my_print("....'Simulation Years' key not found", 'warn') errors_found = True try: self.aggregation_type = json_data['Simulation Configuration']['Aggregation Type'] except: # pragma: no cover PrintClass.my_print("....'Aggregation Type' key not found", 'warn') errors_found = True try: self.g_func_lntts = [] self.g_func_val = [] for pair in json_data['G-func Pairs']: self.g_func_lntts.append(pair[0]) self.g_func_val.append(pair[1]) self.g_func_present = True except: # pragma: no cover PrintClass.my_print("....'G-func Pairs' key not found", 'warn') self.g_func_present = False self.total_bh_length = 0 self.ghx_list = [] ghx_dict_list = [] for json_data_bh in json_data['GHXs']: ghx_dict_list.append(json_data_bh) this_bh = BoreholeClass(json_data_bh, print_output) self.total_bh_length += this_bh.depth self.ghx_list.append(this_bh) self.borehole = BoreholeClass( self.merge_dicts(ghx_dict_list), print_output) try: PrintClass.my_print("....Importing flow rates and loads") load_pairs = np.genfromtxt( loads_path, delimiter=',', skip_header=1) self.sim_hours = [] self.sim_loads = [] self.total_flow_rate = [] for pair in load_pairs: self.sim_hours.append(pair[0]) self.sim_loads.append(pair[1]) self.total_flow_rate.append(pair[2]) except: # pragma: no cover PrintClass.fatal_error(message="Error importing loads") if errors_found: # pragma: no cover PrintClass.fatal_error(message="Error initializing BaseGHXClass") self.ts = self.calc_ts() self.temp_bh = deque() self.temp_mft = deque() self.agg_load_objects = [] self.agg_loads_flag = True def merge_dicts(self, list_of_dicts): """ Merges two-level dictionaries into a single identical dictionary. For non-int/floats arguments, the first item in the list will remain in place. For int/float arguments, the mean value of the parent dictionaries will calculated. """ z = {} for this_dict in list_of_dicts: for key in this_dict.keys(): if key not in z: z[key] = this_dict[key] continue try: for sub_key in this_dict[key].keys(): if isinstance(this_dict[key][sub_key], (float, int)): z[key][sub_key] += this_dict[key][sub_key] else: z[key][sub_key] = this_dict[key][sub_key] except: if isinstance(this_dict[key], (float, int)): z[key] += this_dict[key] num_dicts = len(list_of_dicts) for key in z.keys(): try: for sub_key in z[key].keys(): if isinstance(z[key][sub_key], (float, int)): z[key][sub_key] /= num_dicts except: if isinstance(z[key], int) or isinstance(z[key], float): z[key] /= num_dicts return z def calc_ts(self): """ Calculates non-dimensional time. """ try: ts = self.borehole.depth ** 2 / (9 * self.borehole.soil.thermal_diffusivity) return ts except: # pragma: no cover PrintClass.fatal_error( message="Error calculating simulation time scale \"ts\"") def calc_g_func(self): """ Calculate g-functions for given ground heat exchangers. """ try: PrintClass.my_print("Calculating g-functions") self.g_func_present = True PrintClass.my_print("....Success") except: # pragma: no cover PrintClass.fatal_error(message="Error calculating g-functions") def g_func(self, ln_t_ts): """ Interpolates to the correct g-function value """ num = len(self.g_func_lntts) lower_index = 0 upper_index = num - 1 if ln_t_ts < self.g_func_lntts[lower_index]: # if value is below range, extrapolate down return ((ln_t_ts - self.g_func_lntts[lower_index]) / ( self.g_func_lntts[lower_index + 1] - self.g_func_lntts[lower_index])) * ( self.g_func_val[lower_index + 1] - self.g_func_val[lower_index]) + self.g_func_val[lower_index] elif ln_t_ts > self.g_func_lntts[upper_index]: # if value is above range, extrapolate up return ((ln_t_ts - self.g_func_lntts[upper_index]) / ( self.g_func_lntts[upper_index - 1] - self.g_func_lntts[upper_index])) * ( self.g_func_val[upper_index - 1] - self.g_func_val[upper_index]) + self.g_func_val[upper_index] else: # value is in range return np.interp(ln_t_ts, self.g_func_lntts, self.g_func_val) def generate_output_reports(self): # pragma: no cover """ Generates output results """ try: PrintClass.my_print("Writing output results") cwd = os.getcwd() path_to_output_dir = os.path.join(cwd, self.output_path) if not os.path.exists(path_to_output_dir): os.makedirs(path_to_output_dir) # open files out_file = open(os.path.join(path_to_output_dir, "GHX.csv"), 'w') # write headers out_file.write("Hour, BH Temp [C], MFT [C]\n") for i in range(len(self.temp_bh)): out_file.write("%d, %0.4f, %0.4f\n" % (i + 1, self.temp_bh[i], self.temp_mft[i])) # close file out_file.close() PrintClass.my_print("....Success") except: # pragma: no cover PrintClass.fatal_error(message="Error writing output results")
"""The tests for hls streams.""" from datetime import timedelta from io import BytesIO import os from unittest.mock import patch import av import pytest from homeassistant.components.stream import create_stream from homeassistant.components.stream.const import HLS_PROVIDER, RECORDER_PROVIDER from homeassistant.components.stream.core import Part from homeassistant.components.stream.fmp4utils import find_box from homeassistant.components.stream.recorder import recorder_save_worker from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from tests.common import async_fire_time_changed from tests.components.stream.common import ( DefaultSegment as Segment, generate_h264_video, remux_with_audio, ) MAX_ABORT_SEGMENTS = 20 # Abort test to avoid looping forever async def test_record_stream(hass, hass_client, record_worker_sync): """ Test record stream. Tests full integration with the stream component, and captures the stream worker and save worker to allow for clean shutdown of background threads. The actual save logic is tested in test_recorder_save below. """ await async_setup_component(hass, "stream", {"stream": {}}) # Setup demo track source = generate_h264_video() stream = create_stream(hass, source, {}) with patch.object(hass.config, "is_allowed_path", return_value=True): await stream.async_record("/example/path") # After stream decoding finishes, the record worker thread starts segments = await record_worker_sync.get_segments() assert len(segments) >= 1 # Verify that the save worker was invoked, then block until its # thread completes and is shutdown completely to avoid thread leaks. await record_worker_sync.join() stream.stop() async def test_record_lookback( hass, hass_client, stream_worker_sync, record_worker_sync ): """Exercise record with loopback.""" await async_setup_component(hass, "stream", {"stream": {}}) source = generate_h264_video() stream = create_stream(hass, source, {}) # Start an HLS feed to enable lookback stream.add_provider(HLS_PROVIDER) stream.start() with patch.object(hass.config, "is_allowed_path", return_value=True): await stream.async_record("/example/path", lookback=4) # This test does not need recorder cleanup since it is not fully exercised stream.stop() async def test_recorder_timeout(hass, hass_client, stream_worker_sync): """ Test recorder timeout. Mocks out the cleanup to assert that it is invoked after a timeout. This test does not start the recorder save thread. """ await async_setup_component(hass, "stream", {"stream": {}}) stream_worker_sync.pause() with patch("homeassistant.components.stream.IdleTimer.fire") as mock_timeout: # Setup demo track source = generate_h264_video() stream = create_stream(hass, source, {}) with patch.object(hass.config, "is_allowed_path", return_value=True): await stream.async_record("/example/path") recorder = stream.add_provider(RECORDER_PROVIDER) await recorder.recv() # Wait a minute future = dt_util.utcnow() + timedelta(minutes=1) async_fire_time_changed(hass, future) await hass.async_block_till_done() assert mock_timeout.called stream_worker_sync.resume() stream.stop() await hass.async_block_till_done() await hass.async_block_till_done() async def test_record_path_not_allowed(hass, hass_client): """Test where the output path is not allowed by home assistant configuration.""" await async_setup_component(hass, "stream", {"stream": {}}) # Setup demo track source = generate_h264_video() stream = create_stream(hass, source, {}) with patch.object( hass.config, "is_allowed_path", return_value=False ), pytest.raises(HomeAssistantError): await stream.async_record("/example/path") def add_parts_to_segment(segment, source): """Add relevant part data to segment for testing recorder.""" moof_locs = list(find_box(source.getbuffer(), b"moof")) + [len(source.getbuffer())] segment.init = source.getbuffer()[: moof_locs[0]].tobytes() segment.parts = [ Part( duration=None, has_keyframe=None, data=source.getbuffer()[moof_locs[i] : moof_locs[i + 1]], ) for i in range(len(moof_locs) - 1) ] async def test_recorder_save(tmpdir): """Test recorder save.""" # Setup source = generate_h264_video() filename = f"{tmpdir}/test.mp4" # Run segment = Segment(sequence=1) add_parts_to_segment(segment, source) segment.duration = 4 recorder_save_worker(filename, [segment]) # Assert assert os.path.exists(filename) async def test_recorder_discontinuity(tmpdir): """Test recorder save across a discontinuity.""" # Setup source = generate_h264_video() filename = f"{tmpdir}/test.mp4" # Run segment_1 = Segment(sequence=1, stream_id=0) add_parts_to_segment(segment_1, source) segment_1.duration = 4 segment_2 = Segment(sequence=2, stream_id=1) add_parts_to_segment(segment_2, source) segment_2.duration = 4 recorder_save_worker(filename, [segment_1, segment_2]) # Assert assert os.path.exists(filename) async def test_recorder_no_segments(tmpdir): """Test recorder behavior with a stream failure which causes no segments.""" # Setup filename = f"{tmpdir}/test.mp4" # Run recorder_save_worker("unused-file", []) # Assert assert not os.path.exists(filename) async def test_record_stream_audio( hass, hass_client, stream_worker_sync, record_worker_sync ): """ Test treatment of different audio inputs. Record stream output should have an audio channel when input has a valid codec and audio packets and no audio channel otherwise. """ await async_setup_component(hass, "stream", {"stream": {}}) # Generate source video with no audio orig_source = generate_h264_video(container_format="mov") for a_codec, expected_audio_streams in ( ("aac", 1), # aac is a valid mp4 codec ("pcm_mulaw", 0), # G.711 is not a valid mp4 codec ("empty", 0), # audio stream with no packets (None, 0), # no audio stream ): # Remux source video with new audio source = remux_with_audio(orig_source, "mov", a_codec) # mov can store PCM record_worker_sync.reset() stream_worker_sync.pause() stream = create_stream(hass, source, {}) with patch.object(hass.config, "is_allowed_path", return_value=True): await stream.async_record("/example/path") recorder = stream.add_provider(RECORDER_PROVIDER) while True: await recorder.recv() if not (segment := recorder.last_segment): break last_segment = segment stream_worker_sync.resume() result = av.open( BytesIO(last_segment.init + last_segment.get_data()), "r", format="mp4", ) assert len(result.streams.audio) == expected_audio_streams result.close() stream.stop() await hass.async_block_till_done() # Verify that the save worker was invoked, then block until its # thread completes and is shutdown completely to avoid thread leaks. await record_worker_sync.join() async def test_recorder_log(hass, caplog): """Test starting a stream to record logs the url without username and password.""" await async_setup_component(hass, "stream", {"stream": {}}) stream = create_stream(hass, "https://abcd:efgh@foo.bar", {}) with patch.object(hass.config, "is_allowed_path", return_value=True): await stream.async_record("/example/path") assert "https://abcd:efgh@foo.bar" not in caplog.text assert "https://****:****@foo.bar" in caplog.text
import functools import sys import threading import warnings from collections import Counter, OrderedDict, defaultdict from functools import partial from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured from .config import AppConfig class Apps: """ A registry that stores the configuration of installed applications. It also keeps track of models, e.g. to provide reverse relations. """ def __init__(self, installed_apps=()): # installed_apps is set to None when creating the master registry # because it cannot be populated at that point. Other registries must # provide a list of installed apps and are populated immediately. if installed_apps is None and hasattr(sys.modules[__name__], 'apps'): raise RuntimeError("You must supply an installed_apps argument.") # Mapping of app labels => model names => model classes. Every time a # model is imported, ModelBase.__new__ calls apps.register_model which # creates an entry in all_models. All imported models are registered, # regardless of whether they're defined in an installed application # and whether the registry has been populated. Since it isn't possible # to reimport a module safely (it could reexecute initialization code) # all_models is never overridden or reset. self.all_models = defaultdict(OrderedDict) # Mapping of labels to AppConfig instances for installed apps. self.app_configs = OrderedDict() # Stack of app_configs. Used to store the current state in # set_available_apps and set_installed_apps. self.stored_app_configs = [] # Whether the registry is populated. self.apps_ready = self.models_ready = self.ready = False # For the autoreloader. self.ready_event = threading.Event() # Lock for thread-safe population. self._lock = threading.RLock() self.loading = False # Maps ("app_label", "modelname") tuples to lists of functions to be # called when the corresponding model is ready. Used by this class's # `lazy_model_operation()` and `do_pending_operations()` methods. self._pending_operations = defaultdict(list) # Populate apps and models, unless it's the master registry. if installed_apps is not None: self.populate(installed_apps) def populate(self, installed_apps=None): """ Load application configurations and models. Import each application module and then each model module. It is thread-safe and idempotent, but not reentrant. """ if self.ready: return # populate() might be called by two threads in parallel on servers # that create threads before initializing the WSGI callable. with self._lock: if self.ready: return # An RLock prevents other threads from entering this section. The # compare and set operation below is atomic. if self.loading: # Prevent reentrant calls to avoid running AppConfig.ready() # methods twice. raise RuntimeError("populate() isn't reentrant") self.loading = True # Phase 1: initialize app configs and import app modules. for entry in installed_apps: if isinstance(entry, AppConfig): app_config = entry else: app_config = AppConfig.create(entry) if app_config.label in self.app_configs: raise ImproperlyConfigured( "Application labels aren't unique, " "duplicates: %s" % app_config.label) self.app_configs[app_config.label] = app_config app_config.apps = self # Check for duplicate app names. counts = Counter( app_config.name for app_config in self.app_configs.values()) duplicates = [ name for name, count in counts.most_common() if count > 1] if duplicates: raise ImproperlyConfigured( "Application names aren't unique, " "duplicates: %s" % ", ".join(duplicates)) self.apps_ready = True # Phase 2: import models modules. for app_config in self.app_configs.values(): app_config.import_models() self.clear_cache() self.models_ready = True # Phase 3: run ready() methods of app configs. for app_config in self.get_app_configs(): app_config.ready() self.ready = True self.ready_event.set() def check_apps_ready(self): """Raise an exception if all apps haven't been imported yet.""" if not self.apps_ready: from django.conf import settings # If "not ready" is due to unconfigured settings, accessing # INSTALLED_APPS raises a more helpful ImproperlyConfigured # exception. settings.INSTALLED_APPS raise AppRegistryNotReady("Apps aren't loaded yet.") def check_models_ready(self): """Raise an exception if all models haven't been imported yet.""" if not self.models_ready: raise AppRegistryNotReady("Models aren't loaded yet.") def get_app_configs(self): """Import applications and return an iterable of app configs.""" self.check_apps_ready() return self.app_configs.values() def get_app_config(self, app_label): """ Import applications and returns an app config for the given label. Raise LookupError if no application exists with this label. """ self.check_apps_ready() try: return self.app_configs[app_label] except KeyError: message = "No installed app with label '%s'." % app_label for app_config in self.get_app_configs(): if app_config.name == app_label: message += " Did you mean '%s'?" % app_config.label break raise LookupError(message) # This method is performance-critical at least for Django's test suite. @functools.lru_cache(maxsize=None) def get_models(self, include_auto_created=False, include_swapped=False): """ Return a list of all installed models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models that have been swapped out. Set the corresponding keyword argument to True to include such models. """ self.check_models_ready() result = [] for app_config in self.app_configs.values(): result.extend(app_config.get_models(include_auto_created, include_swapped)) return result def get_model(self, app_label, model_name=None, require_ready=True): """ Return the model matching the given app_label and model_name. As a shortcut, app_label may be in the form <app_label>.<model_name>. model_name is case-insensitive. Raise LookupError if no application exists with this label, or no model exists with this name in the application. Raise ValueError if called with a single argument that doesn't contain exactly one dot. """ if require_ready: self.check_models_ready() else: self.check_apps_ready() if model_name is None: app_label, model_name = app_label.split('.') app_config = self.get_app_config(app_label) if not require_ready and app_config.models is None: app_config.import_models() return app_config.get_model(model_name, require_ready=require_ready) def register_model(self, app_label, model): # Since this method is called when models are imported, it cannot # perform imports because of the risk of import loops. It mustn't # call get_app_config(). model_name = model._meta.model_name app_models = self.all_models[app_label] if model_name in app_models: if (model.__name__ == app_models[model_name].__name__ and model.__module__ == app_models[model_name].__module__): warnings.warn( "Model '%s.%s' was already registered. " "Reloading models is not advised as it can lead to inconsistencies, " "most notably with related models." % (app_label, model_name), RuntimeWarning, stacklevel=2) else: raise RuntimeError( "Conflicting '%s' models in application '%s': %s and %s." % (model_name, app_label, app_models[model_name], model)) app_models[model_name] = model self.do_pending_operations(model) self.clear_cache() def is_installed(self, app_name): """ Check whether an application with this name exists in the registry. app_name is the full name of the app e.g. 'django.contrib.admin'. """ self.check_apps_ready() return any(ac.name == app_name for ac in self.app_configs.values()) def get_containing_app_config(self, object_name): """ Look for an app config containing a given object. object_name is the dotted Python path to the object. Return the app config for the inner application in case of nesting. Return None if the object isn't in any registered app config. """ self.check_apps_ready() candidates = [] for app_config in self.app_configs.values(): if object_name.startswith(app_config.name): subpath = object_name[len(app_config.name):] if subpath == '' or subpath[0] == '.': candidates.append(app_config) if candidates: return sorted(candidates, key=lambda ac: -len(ac.name))[0] def get_registered_model(self, app_label, model_name): """ Similar to get_model(), but doesn't require that an app exists with the given app_label. It's safe to call this method at import time, even while the registry is being populated. """ model = self.all_models[app_label].get(model_name.lower()) if model is None: raise LookupError( "Model '%s.%s' not registered." % (app_label, model_name)) return model @functools.lru_cache(maxsize=None) def get_swappable_settings_name(self, to_string): """ For a given model string (e.g. "auth.User"), return the name of the corresponding settings name if it refers to a swappable model. If the referred model is not swappable, return None. This method is decorated with lru_cache because it's performance critical when it comes to migrations. Since the swappable settings don't change after Django has loaded the settings, there is no reason to get the respective settings attribute over and over again. """ for model in self.get_models(include_swapped=True): swapped = model._meta.swapped # Is this model swapped out for the model given by to_string? if swapped and swapped == to_string: return model._meta.swappable # Is this model swappable and the one given by to_string? if model._meta.swappable and model._meta.label == to_string: return model._meta.swappable return None def set_available_apps(self, available): """ Restrict the set of installed apps used by get_app_config[s]. available must be an iterable of application names. set_available_apps() must be balanced with unset_available_apps(). Primarily used for performance optimization in TransactionTestCase. This method is safe in the sense that it doesn't trigger any imports. """ available = set(available) installed = {app_config.name for app_config in self.get_app_configs()} if not available.issubset(installed): raise ValueError( "Available apps isn't a subset of installed apps, extra apps: %s" % ", ".join(available - installed) ) self.stored_app_configs.append(self.app_configs) self.app_configs = OrderedDict( (label, app_config) for label, app_config in self.app_configs.items() if app_config.name in available) self.clear_cache() def unset_available_apps(self): """Cancel a previous call to set_available_apps().""" self.app_configs = self.stored_app_configs.pop() self.clear_cache() def set_installed_apps(self, installed): """ Enable a different set of installed apps for get_app_config[s]. installed must be an iterable in the same format as INSTALLED_APPS. set_installed_apps() must be balanced with unset_installed_apps(), even if it exits with an exception. Primarily used as a receiver of the setting_changed signal in tests. This method may trigger new imports, which may add new models to the registry of all imported models. They will stay in the registry even after unset_installed_apps(). Since it isn't possible to replay imports safely (e.g. that could lead to registering listeners twice), models are registered when they're imported and never removed. """ if not self.ready: raise AppRegistryNotReady("App registry isn't ready yet.") self.stored_app_configs.append(self.app_configs) self.app_configs = OrderedDict() self.apps_ready = self.models_ready = self.loading = self.ready = False self.clear_cache() self.populate(installed) def unset_installed_apps(self): """Cancel a previous call to set_installed_apps().""" self.app_configs = self.stored_app_configs.pop() self.apps_ready = self.models_ready = self.ready = True self.clear_cache() def clear_cache(self): """ Clear all internal caches, for methods that alter the app registry. This is mostly used in tests. """ # Call expire cache on each model. This will purge # the relation tree and the fields cache. self.get_models.cache_clear() if self.ready: # Circumvent self.get_models() to prevent that the cache is refilled. # This particularly prevents that an empty value is cached while cloning. for app_config in self.app_configs.values(): for model in app_config.get_models(include_auto_created=True): model._meta._expire_cache() def lazy_model_operation(self, function, *model_keys): """ Take a function and a number of ("app_label", "modelname") tuples, and when all the corresponding models have been imported and registered, call the function with the model classes as its arguments. The function passed to this method must accept exactly n models as arguments, where n=len(model_keys). """ # Base case: no arguments, just execute the function. if not model_keys: function() # Recursive case: take the head of model_keys, wait for the # corresponding model class to be imported and registered, then apply # that argument to the supplied function. Pass the resulting partial # to lazy_model_operation() along with the remaining model args and # repeat until all models are loaded and all arguments are applied. else: next_model, *more_models = model_keys # This will be executed after the class corresponding to next_model # has been imported and registered. The `func` attribute provides # duck-type compatibility with partials. def apply_next_model(model): next_function = partial(apply_next_model.func, model) self.lazy_model_operation(next_function, *more_models) apply_next_model.func = function # If the model has already been imported and registered, partially # apply it to the function now. If not, add it to the list of # pending operations for the model, where it will be executed with # the model class as its sole argument once the model is ready. try: model_class = self.get_registered_model(*next_model) except LookupError: self._pending_operations[next_model].append(apply_next_model) else: apply_next_model(model_class) def do_pending_operations(self, model): """ Take a newly-prepared model and pass it to each function waiting for it. This is called at the very end of Apps.register_model(). """ key = model._meta.app_label, model._meta.model_name for function in self._pending_operations.pop(key, []): function(model) apps = Apps(installed_apps=None)
#!/usr/bin/env python # Copyright 2015 Google, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Google Author(s): Doug Felt import argparse import codecs import os.path import re import sys from xml.parsers import expat from xml.sax import saxutils # Expat doesn't allow me to identify empty tags (in particular, with an # empty tag the parse location for the start and end is not the same) so I # have to take a dom-like approach if I want to identify them. There are a # lot of empty tags in svg. This way I can do some other kinds of cleanup # as well (remove unnecessary 'g' elements, for instance). # Use nodes instead of tuples and strings because it's easier to mutate # a tree of these, and cleaner will want to do this. class _Elem_Node(object): def __init__(self, name, attrs, contents): self.name = name self.attrs = attrs self.contents = contents def __repr__(self): line = ["elem(name: '%s'" % self.name] if self.attrs: line.append(" attrs: '%s'" % self.attrs) if self.contents: line.append(" contents[%s]: '%s'" % (len(self.contents), self.contents)) line.append(')') return ''.join(line) class _Text_Node(object): def __init__(self, text): self.text = text def __repr__(self): return "text('%s')" % self.text class SvgCleaner(object): """Strip out unwanted parts of an svg file, primarily the xml declaration and doctype lines, comments, and some attributes of the outermost <svg> element. The id will be replaced when it is inserted into the font. viewBox causes unwanted scaling when used in a font and its effect is difficult to predict. version is unneeded, xml:space is ignored (we're processing spaces so a request to maintain them has no effect). enable-background appears to have no effect. x and y on the outermost svg element have no effect. We keep width and height, and will elsewhere assume these are the dimensions used for the character box.""" def __init__(self): self.reader = SvgCleaner._Reader() self.cleaner = SvgCleaner._Cleaner() self.writer = SvgCleaner._Writer() class _Reader(object): """Loosely based on fonttools's XMLReader. This generates a tree of nodes, either element nodes or text nodes. Successive text content is merged into one node, so contents will never contain more than one _Text_Node in a row. This drops comments, xml declarations, and doctypes.""" def _reset(self, parser): self._stack = [] self._textbuf = [] def _start_element(self, name, attrs): self._flush_textbuf() node = _Elem_Node(name, attrs, []) if len(self._stack): self._stack[-1].contents.append(node) self._stack.append(node) def _end_element(self, name): self._flush_textbuf() if len(self._stack) > 1: self._stack = self._stack[:-1] def _character_data(self, data): if len(self._stack): self._textbuf.append(data) def _flush_textbuf(self): if self._textbuf: node = _Text_Node(''.join(self._textbuf)) self._stack[-1].contents.append(node) self._textbuf = [] def from_text(self, data): """Return the root node of a tree representing the svg data.""" parser = expat.ParserCreate() parser.StartElementHandler = self._start_element parser.EndElementHandler = self._end_element parser.CharacterDataHandler = self._character_data self._reset(parser) parser.Parse(data) return self._stack[0] class _Cleaner(object): def _clean_elem(self, node): nattrs = {} for k, v in node.attrs.items(): if node.name == 'svg' and k in [ 'x', 'y', 'id', 'version', 'viewBox', 'width', 'height', 'enable-background', 'xml:space']: continue v = re.sub('\s+', ' ', v) nattrs[k] = v node.attrs = nattrs # scan contents. remove any empty text nodes, or empty 'g' element nodes. # if a 'g' element has no attrs and only one subnode, replace it with the # subnode. wpos = 0 for n in node.contents: if isinstance(n, _Text_Node): if not n.text: continue elif n.name == 'g': if not n.contents: continue if not n.attrs and len(n.contents) == 1: n = n.contents[0] node.contents[wpos] = n wpos += 1 if wpos < len(node.contents): node.contents = node.contents[:wpos] def _clean_text(self, node): text = node.text.strip() # common case is text is empty (line endings between elements) if text: text = re.sub(r'\s+', ' ', text) node.text = text def clean(self, node): if isinstance(node, _Text_Node): self._clean_text(node) else: # do contents first, so we can check for empty subnodes after for n in node.contents: self.clean(n) self._clean_elem(node) class _Writer(object): """For text nodes, replaces sequences of whitespace with a single space. For elements, replaces sequences of whitespace in attributes, and removes unwanted attributes from <svg> elements.""" def _write_node(self, node, lines, indent): """Node is a node generated by _Reader, either a TextNode or an ElementNode. Lines is a list to collect the lines of output. Indent is the indentation level for this node.""" if isinstance(node, _Text_Node): if node.text: lines.append(node.text) else: margin = ' ' * indent line = [margin] line.append('<%s' % node.name) for k in sorted(node.attrs.keys()): v = node.attrs[k] line.append(' %s=%s' % (k, saxutils.quoteattr(v))) if node.contents: line.append('>') lines.append(''.join(line)) for elem in node.contents: self._write_node(elem, lines, indent + 1) line = [margin] line.append('</%s>' % node.name) lines.append(''.join(line)) else: line.append('/>') lines.append(''.join(line)) def to_text(self, root): # set up lines for recursive calls, let them append lines, then return # the result. lines = [] self._write_node(root, lines, 0) return '\n'.join(lines) def tree_from_text(self, svg_text): return self.reader.from_text(svg_text) def clean_tree(self, svg_tree): self.cleaner.clean(svg_tree) def tree_to_text(self, svg_tree): return self.writer.to_text(svg_tree) def clean_svg(self, svg_text): """Return the cleaned svg_text.""" tree = self.tree_from_text(svg_text) self.clean_tree(tree) return self.tree_to_text(tree) def clean_svg_files(in_dir, out_dir, match_pat=None, quiet=False): regex = re.compile(match_pat) if match_pat else None count = 0 if not os.path.isdir(out_dir): os.makedirs(out_dir) if not quiet: print 'created output directory: %s' % out_dir cleaner = SvgCleaner() for file_name in os.listdir(in_dir): if regex and not regex.match(file_name): continue in_path = os.path.join(in_dir, file_name) with open(in_path) as in_fp: result = cleaner.clean_svg(in_fp.read()) out_path = os.path.join(out_dir, file_name) with codecs.open(out_path, 'w', 'utf-8') as out_fp: if not quiet: print 'wrote: %s' % out_path out_fp.write(result) count += 1 if not count: print 'failed to match any files' else: print 'processed %s files to %s' % (count, out_dir) def main(): parser = argparse.ArgumentParser( description="Generate 'cleaned' svg files.") parser.add_argument('in_dir', help='Input directory.') parser.add_argument('out_dir', help='Output directory.') parser.add_argument('regex', help='Regex to select files, default matches all files.', default=None) parser.add_argument('--quiet', '-q', help='Quiet operation.', action='store_true') args = parser.parse_args() clean_svg_files(args.in_dir, args.out_dir, match_pat=args.regex, quiet=args.quiet) if __name__ == '__main__': main()
import mxnet as mx import numpy as np import cv2 from tools.rand_sampler import RandSampler class DetRecordIter(mx.io.DataIter): """ The new detection iterator wrapper for mx.io.ImageDetRecordIter which is written in C++, it takes record file as input and runs faster. Supports various augment operations for object detection. Parameters: ----------- path_imgrec : str path to the record file path_imglist : str path to the list file to replace the labels in record batch_size : int batch size data_shape : tuple (3, height, width) label_width : int specify the label width, use -1 for variable length label_pad_width : int labels must have same shape in batches, use -1 for automatic estimation in each record, otherwise force padding to width in case you want t rain/validation to match the same width label_pad_value : float label padding value resize_mode : str force - resize to data_shape regardless of aspect ratio fit - try fit to data_shape preserving aspect ratio shrink - shrink to data_shape only, preserving aspect ratio mean_pixels : list or tuple mean values for red/green/blue kwargs : dict see mx.io.ImageDetRecordIter Returns: ---------- """ def __init__(self, path_imgrec, batch_size, data_shape, path_imglist="", label_width=-1, label_pad_width=-1, label_pad_value=-1, resize_mode='force', mean_pixels=[123.68, 116.779, 103.939], **kwargs): super(DetRecordIter, self).__init__() self.rec = mx.io.ImageDetRecordIter( path_imgrec = path_imgrec, path_imglist = path_imglist, label_width = label_width, label_pad_width = label_pad_width, label_pad_value = label_pad_value, batch_size = batch_size, data_shape = data_shape, mean_r = mean_pixels[0], mean_g = mean_pixels[1], mean_b = mean_pixels[2], resize_mode = resize_mode, **kwargs) self.provide_label = None self._get_batch() if not self.provide_label: raise RuntimeError("Invalid ImageDetRecordIter: " + path_imgrec) self.reset() @property def provide_data(self): return self.rec.provide_data def reset(self): self.rec.reset() def iter_next(self): return self._get_batch() def next(self): if self.iter_next(): return self._batch else: raise StopIteration def _get_batch(self): self._batch = self.rec.next() if not self._batch: return False if self.provide_label is None: # estimate the label shape for the first batch, always reshape to n*5 first_label = self._batch.label[0][0].asnumpy() self.batch_size = self._batch.label[0].shape[0] self.label_header_width = int(first_label[4]) self.label_object_width = int(first_label[5]) assert self.label_object_width >= 5, "object width must >=5" self.label_start = 4 + self.label_header_width self.max_objects = (first_label.size - self.label_start) // self.label_object_width self.label_shape = (self.batch_size, self.max_objects, self.label_object_width) self.label_end = self.label_start + self.max_objects * self.label_object_width self.provide_label = [('label', self.label_shape)] # modify label label = self._batch.label[0].asnumpy() label = label[:, self.label_start:self.label_end].reshape( (self.batch_size, self.max_objects, self.label_object_width)) self._batch.label = [mx.nd.array(label)] return True class DetIter(mx.io.DataIter): """ Detection Iterator, which will feed data and label to network Optional data augmentation is performed when providing batch Parameters: ---------- imdb : Imdb image database batch_size : int batch size data_shape : int or (int, int) image shape to be resized mean_pixels : float or float list [R, G, B], mean pixel values rand_samplers : list random cropping sampler list, if not specified, will use original image only rand_mirror : bool whether to randomly mirror input images, default False shuffle : bool whether to shuffle initial image list, default False rand_seed : int or None whether to use fixed random seed, default None max_crop_trial : bool if random crop is enabled, defines the maximum trial time if trial exceed this number, will give up cropping is_train : bool whether in training phase, default True, if False, labels might be ignored """ def __init__(self, imdb, batch_size, data_shape, \ mean_pixels=[128, 128, 128], rand_samplers=[], \ rand_mirror=False, shuffle=False, rand_seed=None, \ is_train=True, max_crop_trial=50): super(DetIter, self).__init__() self._imdb = imdb self.batch_size = batch_size if isinstance(data_shape, int): data_shape = (data_shape, data_shape) self._data_shape = data_shape self._mean_pixels = mx.nd.array(mean_pixels).reshape((3,1,1)) if not rand_samplers: self._rand_samplers = [] else: if not isinstance(rand_samplers, list): rand_samplers = [rand_samplers] assert isinstance(rand_samplers[0], RandSampler), "Invalid rand sampler" self._rand_samplers = rand_samplers self.is_train = is_train self._rand_mirror = rand_mirror self._shuffle = shuffle if rand_seed: np.random.seed(rand_seed) # fix random seed self._max_crop_trial = max_crop_trial self._current = 0 self._size = imdb.num_images self._index = np.arange(self._size) self._data = None self._label = None self._get_batch() @property def provide_data(self): return [(k, v.shape) for k, v in self._data.items()] @property def provide_label(self): if self.is_train: return [(k, v.shape) for k, v in self._label.items()] else: return [] def reset(self): self._current = 0 if self._shuffle: np.random.shuffle(self._index) def iter_next(self): return self._current < self._size def next(self): if self.iter_next(): self._get_batch() data_batch = mx.io.DataBatch(data=self._data.values(), label=self._label.values(), pad=self.getpad(), index=self.getindex()) self._current += self.batch_size return data_batch else: raise StopIteration def getindex(self): return self._current // self.batch_size def getpad(self): pad = self._current + self.batch_size - self._size return 0 if pad < 0 else pad def _get_batch(self): """ Load data/label from dataset """ batch_data = mx.nd.zeros((self.batch_size, 3, self._data_shape[0], self._data_shape[1])) batch_label = [] for i in range(self.batch_size): if (self._current + i) >= self._size: if not self.is_train: continue # use padding from middle in each epoch idx = (self._current + i + self._size // 2) % self._size index = self._index[idx] else: index = self._index[self._current + i] # index = self.debug_index im_path = self._imdb.image_path_from_index(index) with open(im_path, 'rb') as fp: img_content = fp.read() img = mx.img.imdecode(img_content) gt = self._imdb.label_from_index(index).copy() if self.is_train else None data, label = self._data_augmentation(img, gt) batch_data[i] = data if self.is_train: batch_label.append(label) self._data = {'data': batch_data} if self.is_train: self._label = {'label': mx.nd.array(np.array(batch_label))} else: self._label = {'label': None} def _data_augmentation(self, data, label): """ perform data augmentations: crop, mirror, resize, sub mean, swap channels... """ if self.is_train and self._rand_samplers: rand_crops = [] for rs in self._rand_samplers: rand_crops += rs.sample(label) num_rand_crops = len(rand_crops) # randomly pick up one as input data if num_rand_crops > 0: index = int(np.random.uniform(0, 1) * num_rand_crops) width = data.shape[1] height = data.shape[0] crop = rand_crops[index][0] xmin = int(crop[0] * width) ymin = int(crop[1] * height) xmax = int(crop[2] * width) ymax = int(crop[3] * height) if xmin >= 0 and ymin >= 0 and xmax <= width and ymax <= height: data = mx.img.fixed_crop(data, xmin, ymin, xmax-xmin, ymax-ymin) else: # padding mode new_width = xmax - xmin new_height = ymax - ymin offset_x = 0 - xmin offset_y = 0 - ymin data_bak = data data = mx.nd.full((new_height, new_width, 3), 128, dtype='uint8') data[offset_y:offset_y+height, offset_x:offset_x + width, :] = data_bak label = rand_crops[index][1] if self.is_train: interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, \ cv2.INTER_NEAREST, cv2.INTER_LANCZOS4] else: interp_methods = [cv2.INTER_LINEAR] interp_method = interp_methods[int(np.random.uniform(0, 1) * len(interp_methods))] data = mx.img.imresize(data, self._data_shape[1], self._data_shape[0], interp_method) if self.is_train and self._rand_mirror: if np.random.uniform(0, 1) > 0.5: data = mx.nd.flip(data, axis=1) valid_mask = np.where(label[:, 0] > -1)[0] tmp = 1.0 - label[valid_mask, 1] label[valid_mask, 1] = 1.0 - label[valid_mask, 3] label[valid_mask, 3] = tmp data = mx.nd.transpose(data, (2,0,1)) data = data.astype('float32') data = data - self._mean_pixels return data, label
#!/usr/bin/env python # # Copyright 2001 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Script that generates the build.ninja for ninja itself. Projects that use ninja themselves should either write a similar script or use a meta-build system that supports Ninja output.""" from __future__ import print_function from optparse import OptionParser import os import pipes import string import subprocess import sys sourcedir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(sourcedir, 'misc')) import ninja_syntax class Platform(object): """Represents a host/target platform and its specific build attributes.""" def __init__(self, platform): self._platform = platform if self._platform is not None: return self._platform = sys.platform if self._platform.startswith('linux'): self._platform = 'linux' elif self._platform.startswith('freebsd'): self._platform = 'freebsd' elif self._platform.startswith('gnukfreebsd'): self._platform = 'freebsd' elif self._platform.startswith('openbsd'): self._platform = 'openbsd' elif self._platform.startswith('solaris') or self._platform == 'sunos5': self._platform = 'solaris' elif self._platform.startswith('mingw'): self._platform = 'mingw' elif self._platform.startswith('win'): self._platform = 'msvc' elif self._platform.startswith('bitrig'): self._platform = 'bitrig' elif self._platform.startswith('netbsd'): self._platform = 'netbsd' elif self._platform.startswith('aix'): self._platform = 'aix' elif self._platform.startswith('dragonfly'): self._platform = 'dragonfly' @staticmethod def known_platforms(): return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5', 'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd', 'aix', 'dragonfly'] def platform(self): return self._platform def is_linux(self): return self._platform == 'linux' def is_mingw(self): return self._platform == 'mingw' def is_msvc(self): return self._platform == 'msvc' def msvc_needs_fs(self): popen = subprocess.Popen(['cl', '/nologo', '/?'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = popen.communicate() return b'/FS' in out def is_windows(self): return self.is_mingw() or self.is_msvc() def is_solaris(self): return self._platform == 'solaris' def is_aix(self): return self._platform == 'aix' def uses_usr_local(self): return self._platform in ('freebsd', 'openbsd', 'bitrig', 'dragonfly', 'netbsd') def supports_ppoll(self): return self._platform in ('freebsd', 'linux', 'openbsd', 'bitrig', 'dragonfly') def supports_ninja_browse(self): return (not self.is_windows() and not self.is_solaris() and not self.is_aix()) def can_rebuild_in_place(self): return not (self.is_windows() or self.is_aix()) class Bootstrap: """API shim for ninja_syntax.Writer that instead runs the commands. Used to bootstrap Ninja from scratch. In --bootstrap mode this class is used to execute all the commands to build an executable. It also proxies all calls to an underlying ninja_syntax.Writer, to behave like non-bootstrap mode. """ def __init__(self, writer, verbose=False): self.writer = writer self.verbose = verbose # Map of variable name => expanded variable value. self.vars = {} # Map of rule name => dict of rule attributes. self.rules = { 'phony': {} } def comment(self, text): return self.writer.comment(text) def newline(self): return self.writer.newline() def variable(self, key, val): # In bootstrap mode, we have no ninja process to catch /showIncludes # output. self.vars[key] = self._expand(val).replace('/showIncludes', '') return self.writer.variable(key, val) def rule(self, name, **kwargs): self.rules[name] = kwargs return self.writer.rule(name, **kwargs) def build(self, outputs, rule, inputs=None, **kwargs): ruleattr = self.rules[rule] cmd = ruleattr.get('command') if cmd is None: # A phony rule, for example. return # Implement just enough of Ninja variable expansion etc. to # make the bootstrap build work. local_vars = { 'in': self._expand_paths(inputs), 'out': self._expand_paths(outputs) } for key, val in kwargs.get('variables', []): local_vars[key] = ' '.join(ninja_syntax.as_list(val)) self._run_command(self._expand(cmd, local_vars)) return self.writer.build(outputs, rule, inputs, **kwargs) def default(self, paths): return self.writer.default(paths) def _expand_paths(self, paths): """Expand $vars in an array of paths, e.g. from a 'build' block.""" paths = ninja_syntax.as_list(paths) return ' '.join(map(self._shell_escape, (map(self._expand, paths)))) def _expand(self, str, local_vars={}): """Expand $vars in a string.""" return ninja_syntax.expand(str, self.vars, local_vars) def _shell_escape(self, path): """Quote paths containing spaces.""" return '"%s"' % path if ' ' in path else path def _run_command(self, cmdline): """Run a subcommand, quietly. Prints the full command on error.""" try: if self.verbose: print(cmdline) subprocess.check_call(cmdline, shell=True) except subprocess.CalledProcessError: print('when running: ', cmdline) raise parser = OptionParser() profilers = ['gmon', 'pprof'] parser.add_option('--bootstrap', action='store_true', help='bootstrap a ninja binary from nothing') parser.add_option('--verbose', action='store_true', help='enable verbose build') parser.add_option('--platform', help='target platform (' + '/'.join(Platform.known_platforms()) + ')', choices=Platform.known_platforms()) parser.add_option('--host', help='host platform (' + '/'.join(Platform.known_platforms()) + ')', choices=Platform.known_platforms()) parser.add_option('--debug', action='store_true', help='enable debugging extras',) parser.add_option('--profile', metavar='TYPE', choices=profilers, help='enable profiling (' + '/'.join(profilers) + ')',) parser.add_option('--with-gtest', metavar='PATH', help='ignored') parser.add_option('--with-python', metavar='EXE', help='use EXE as the Python interpreter', default=os.path.basename(sys.executable)) parser.add_option('--force-pselect', action='store_true', help='ppoll() is used by default where available, ' 'but some platforms may need to use pselect instead',) (options, args) = parser.parse_args() if args: print('ERROR: extra unparsed command-line arguments:', args) sys.exit(1) platform = Platform(options.platform) if options.host: host = Platform(options.host) else: host = platform BUILD_FILENAME = 'build.ninja' ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w')) n = ninja_writer if options.bootstrap: # Make the build directory. try: os.mkdir('build') except OSError: pass # Wrap ninja_writer with the Bootstrapper, which also executes the # commands. print('bootstrapping ninja...') n = Bootstrap(n, verbose=options.verbose) n.comment('This file is used to build ninja itself.') n.comment('It is generated by ' + os.path.basename(__file__) + '.') n.newline() n.variable('ninja_required_version', '1.3') n.newline() n.comment('The arguments passed to configure.py, for rerunning it.') configure_args = sys.argv[1:] if '--bootstrap' in configure_args: configure_args.remove('--bootstrap') n.variable('configure_args', ' '.join(configure_args)) env_keys = set(['CXX', 'AR', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS']) configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys) if configure_env: config_str = ' '.join([k + '=' + pipes.quote(configure_env[k]) for k in configure_env]) n.variable('configure_env', config_str + '$ ') n.newline() CXX = configure_env.get('CXX', 'g++') objext = '.o' if platform.is_msvc(): CXX = 'cl' objext = '.obj' def src(filename): return os.path.join('$root', 'src', filename) def built(filename): return os.path.join('$builddir', filename) def doc(filename): return os.path.join('$root', 'doc', filename) def cc(name, **kwargs): return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs) def cxx(name, **kwargs): return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs) def binary(name): if platform.is_windows(): exe = name + '.exe' n.build(name, 'phony', exe) return exe return name root = sourcedir if root == os.getcwd(): # In the common case where we're building directly in the source # tree, simplify all the paths to just be cwd-relative. root = '.' n.variable('root', root) n.variable('builddir', 'build') n.variable('cxx', CXX) if platform.is_msvc(): n.variable('ar', 'link') else: n.variable('ar', configure_env.get('AR', 'ar')) if platform.is_msvc(): cflags = ['/showIncludes', '/nologo', # Don't print startup banner. '/Zi', # Create pdb with debug info. '/W4', # Highest warning level. '/WX', # Warnings as errors. '/wd4530', '/wd4100', '/wd4706', '/wd4244', '/wd4512', '/wd4800', '/wd4702', '/wd4819', # Disable warnings about constant conditional expressions. '/wd4127', # Disable warnings about passing "this" during initialization. '/wd4355', # Disable warnings about ignored typedef in DbgHelp.h '/wd4091', '/GR-', # Disable RTTI. # Disable size_t -> int truncation warning. # We never have strings or arrays larger than 2**31. '/wd4267', '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS', '/D_HAS_EXCEPTIONS=0', '/DNINJA_PYTHON="%s"' % options.with_python] if platform.msvc_needs_fs(): cflags.append('/FS') ldflags = ['/DEBUG', '/libpath:$builddir'] if not options.debug: cflags += ['/Ox', '/DNDEBUG', '/GL'] ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF'] else: cflags = ['-g', '-Wall', '-Wextra', '-Wno-deprecated', '-Wno-missing-field-initializers', '-Wno-unused-parameter', '-fno-rtti', '-fno-exceptions', '-fvisibility=hidden', '-pipe', '-DNINJA_PYTHON="%s"' % options.with_python] if options.debug: cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC'] cflags.remove('-fno-rtti') # Needed for above pedanticness. else: cflags += ['-O2', '-DNDEBUG'] try: proc = subprocess.Popen( [CXX, '-fdiagnostics-color', '-c', '-x', 'c++', '/dev/null', '-o', '/dev/null'], stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT) if proc.wait() == 0: cflags += ['-fdiagnostics-color'] except: pass if platform.is_mingw(): cflags += ['-D_WIN32_WINNT=0x0501'] ldflags = ['-L$builddir'] if platform.uses_usr_local(): cflags.append('-I/usr/local/include') ldflags.append('-L/usr/local/lib') if platform.is_aix(): # printf formats for int64_t, uint64_t; large file support cflags.append('-D__STDC_FORMAT_MACROS') cflags.append('-D_LARGE_FILES') libs = [] if platform.is_mingw(): cflags.remove('-fvisibility=hidden'); ldflags.append('-static') elif platform.is_solaris(): cflags.remove('-fvisibility=hidden') elif platform.is_aix(): cflags.remove('-fvisibility=hidden') elif platform.is_msvc(): pass else: if options.profile == 'gmon': cflags.append('-pg') ldflags.append('-pg') elif options.profile == 'pprof': cflags.append('-fno-omit-frame-pointer') libs.extend(['-Wl,--no-as-needed', '-lprofiler']) if platform.supports_ppoll() and not options.force_pselect: cflags.append('-DUSE_PPOLL') if platform.supports_ninja_browse(): cflags.append('-DNINJA_HAVE_BROWSE') # Search for generated headers relative to build dir. cflags.append('-I.') def shell_escape(str): """Escape str such that it's interpreted as a single argument by the shell.""" # This isn't complete, but it's just enough to make NINJA_PYTHON work. if platform.is_windows(): return str if '"' in str: return "'%s'" % str.replace("'", "\\'") return str if 'CFLAGS' in configure_env: cflags.append(configure_env['CFLAGS']) ldflags.append(configure_env['CFLAGS']) if 'CXXFLAGS' in configure_env: cflags.append(configure_env['CXXFLAGS']) ldflags.append(configure_env['CXXFLAGS']) n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags)) if 'LDFLAGS' in configure_env: ldflags.append(configure_env['LDFLAGS']) n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags)) n.newline() if platform.is_msvc(): n.rule('cxx', command='$cxx $cflags -c $in /Fo$out', description='CXX $out', deps='msvc' # /showIncludes is included in $cflags. ) else: n.rule('cxx', command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out', depfile='$out.d', deps='gcc', description='CXX $out') n.newline() if host.is_msvc(): n.rule('ar', command='lib /nologo /ltcg /out:$out $in', description='LIB $out') elif host.is_mingw(): n.rule('ar', command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out', description='AR $out') else: n.rule('ar', command='rm -f $out && $ar crs $out $in', description='AR $out') n.newline() if platform.is_msvc(): n.rule('link', command='$cxx $in $libs /nologo /link $ldflags /out:$out', description='LINK $out') else: n.rule('link', command='$cxx $ldflags -o $out $in $libs', description='LINK $out') n.newline() objs = [] if platform.supports_ninja_browse(): n.comment('browse_py.h is used to inline browse.py.') n.rule('inline', command='"%s"' % src('inline.sh') + ' $varname < $in > $out', description='INLINE $out') n.build(built('browse_py.h'), 'inline', src('browse.py'), implicit=src('inline.sh'), variables=[('varname', 'kBrowsePy')]) n.newline() objs += cxx('browse', order_only=built('browse_py.h')) n.newline() n.comment('the depfile parser and ninja lexers are generated using re2c.') def has_re2c(): try: proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE) return int(proc.communicate()[0], 10) >= 1103 except OSError: return False if has_re2c(): n.rule('re2c', command='re2c -b -i --no-generation-date -o $out $in', description='RE2C $out') # Generate the .cc files in the source directory so we can check them in. n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc')) n.build(src('lexer.cc'), 're2c', src('lexer.in.cc')) else: print("warning: A compatible version of re2c (>= 0.11.3) was not found; " "changes to src/*.in.cc will not affect your build.") n.newline() n.comment('Core source files all build into ninja library.') for name in ['build', 'build_log', 'clean', 'clparser', 'debug_flags', 'depfile_parser', 'deps_log', 'disk_interface', 'edit_distance', 'eval_env', 'graph', 'graphviz', 'lexer', 'line_printer', 'manifest_parser', 'metrics', 'state', 'string_piece_util', 'util', 'version']: objs += cxx(name) if platform.is_windows(): for name in ['subprocess-win32', 'includes_normalize-win32', 'msvc_helper-win32', 'msvc_helper_main-win32']: objs += cxx(name) if platform.is_msvc(): objs += cxx('minidump-win32') objs += cc('getopt') else: objs += cxx('subprocess-posix') if platform.is_aix(): objs += cc('getopt') if platform.is_msvc(): ninja_lib = n.build(built('ninja.lib'), 'ar', objs) else: ninja_lib = n.build(built('libninja.a'), 'ar', objs) n.newline() if platform.is_msvc(): libs.append('ninja.lib') else: libs.append('-lninja') if platform.is_aix(): libs.append('-lperfstat') all_targets = [] n.comment('Main executable is library plus main() function.') objs = cxx('ninja') ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib, variables=[('libs', libs)]) n.newline() all_targets += ninja if options.bootstrap: # We've built the ninja binary. Don't run any more commands # through the bootstrap executor, but continue writing the # build.ninja file. n = ninja_writer n.comment('Tests all build into ninja_test executable.') objs = [] for name in ['build_log_test', 'build_test', 'clean_test', 'clparser_test', 'depfile_parser_test', 'deps_log_test', 'disk_interface_test', 'edit_distance_test', 'graph_test', 'lexer_test', 'manifest_parser_test', 'ninja_test', 'state_test', 'string_piece_util_test', 'subprocess_test', 'test', 'util_test']: objs += cxx(name) if platform.is_windows(): for name in ['includes_normalize_test', 'msvc_helper_test']: objs += cxx(name) ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib, variables=[('libs', libs)]) n.newline() all_targets += ninja_test n.comment('Ancillary executables.') for name in ['build_log_perftest', 'canon_perftest', 'depfile_parser_perftest', 'hash_collision_bench', 'manifest_parser_perftest', 'clparser_perftest']: objs = cxx(name) all_targets += n.build(binary(name), 'link', objs, implicit=ninja_lib, variables=[('libs', libs)]) n.newline() n.comment('Generate a graph using the "graph" tool.') n.rule('gendot', command='./ninja -t graph all > $out') n.rule('gengraph', command='dot -Tpng $in > $out') dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja']) n.build('graph.png', 'gengraph', dot) n.newline() n.comment('Generate the manual using asciidoc.') n.rule('asciidoc', command='asciidoc -b docbook -d book -o $out $in', description='ASCIIDOC $out') n.rule('xsltproc', command='xsltproc --nonet doc/docbook.xsl $in > $out', description='XSLTPROC $out') docbookxml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc')) manual = n.build(doc('manual.html'), 'xsltproc', docbookxml, implicit=[doc('style.css'), doc('docbook.xsl')]) n.build('manual', 'phony', order_only=manual) n.newline() n.rule('dblatex', command='dblatex -q -o $out -p doc/dblatex.xsl $in', description='DBLATEX $out') n.build(doc('manual.pdf'), 'dblatex', docbookxml, implicit=[doc('dblatex.xsl')]) n.comment('Generate Doxygen.') n.rule('doxygen', command='doxygen $in', description='DOXYGEN $in') n.variable('doxygen_mainpage_generator', src('gen_doxygen_mainpage.sh')) n.rule('doxygen_mainpage', command='$doxygen_mainpage_generator $in > $out', description='DOXYGEN_MAINPAGE $out') mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage', ['README', 'COPYING'], implicit=['$doxygen_mainpage_generator']) n.build('doxygen', 'doxygen', doc('doxygen.config'), implicit=mainpage) n.newline() if not host.is_mingw(): n.comment('Regenerate build files if build script changes.') n.rule('configure', command='${configure_env}%s $root/configure.py $configure_args' % options.with_python, generator=True) n.build('build.ninja', 'configure', implicit=['$root/configure.py', os.path.normpath('$root/misc/ninja_syntax.py')]) n.newline() n.default(ninja) n.newline() if host.is_linux(): n.comment('Packaging') n.rule('rpmbuild', command="misc/packaging/rpmbuild.sh", description='Building rpms..') n.build('rpm', 'rpmbuild') n.newline() n.build('all', 'phony', all_targets) n.close() print('wrote %s.' % BUILD_FILENAME) if options.bootstrap: print('bootstrap complete. rebuilding...') rebuild_args = [] if platform.can_rebuild_in_place(): rebuild_args.append('./ninja') else: if platform.is_windows(): bootstrap_exe = 'ninja.bootstrap.exe' final_exe = 'ninja.exe' else: bootstrap_exe = './ninja.bootstrap' final_exe = './ninja' if os.path.exists(bootstrap_exe): os.unlink(bootstrap_exe) os.rename(final_exe, bootstrap_exe) rebuild_args.append(bootstrap_exe) if options.verbose: rebuild_args.append('-v') subprocess.check_call(rebuild_args)
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request from ...operations._configuration_services_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request, build_validate_request_initial T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ConfigurationServicesOperations: """ConfigurationServicesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.appplatform.v2022_01_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config @distributed_trace_async async def get( self, resource_group_name: str, service_name: str, configuration_service_name: str, **kwargs: Any ) -> "_models.ConfigurationServiceResource": """Get the Application Configuration Service and its properties. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param service_name: The name of the Service resource. :type service_name: str :param configuration_service_name: The name of Application Configuration Service. :type configuration_service_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ConfigurationServiceResource, or the result of cls(response) :rtype: ~azure.mgmt.appplatform.v2022_01_01_preview.models.ConfigurationServiceResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationServiceResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_get_request( subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, template_url=self.get.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ConfigurationServiceResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, service_name: str, configuration_service_name: str, configuration_service_resource: "_models.ConfigurationServiceResource", **kwargs: Any ) -> "_models.ConfigurationServiceResource": cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationServiceResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(configuration_service_resource, 'ConfigurationServiceResource') request = build_create_or_update_request_initial( subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, content_type=content_type, json=_json, template_url=self._create_or_update_initial.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ConfigurationServiceResource', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ConfigurationServiceResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}'} # type: ignore @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, service_name: str, configuration_service_name: str, configuration_service_resource: "_models.ConfigurationServiceResource", **kwargs: Any ) -> AsyncLROPoller["_models.ConfigurationServiceResource"]: """Create the default Application Configuration Service or update the existing Application Configuration Service. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param service_name: The name of the Service resource. :type service_name: str :param configuration_service_name: The name of Application Configuration Service. :type configuration_service_name: str :param configuration_service_resource: Parameters for the update operation. :type configuration_service_resource: ~azure.mgmt.appplatform.v2022_01_01_preview.models.ConfigurationServiceResource :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ConfigurationServiceResource or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.appplatform.v2022_01_01_preview.models.ConfigurationServiceResource] :raises: ~azure.core.exceptions.HttpResponseError """ content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationServiceResource"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, configuration_service_resource=configuration_service_resource, content_type=content_type, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) def get_long_running_output(pipeline_response): response = pipeline_response.http_response deserialized = self._deserialize('ConfigurationServiceResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, service_name: str, configuration_service_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_delete_request_initial( subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, template_url=self._delete_initial.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}'} # type: ignore @distributed_trace_async async def begin_delete( self, resource_group_name: str, service_name: str, configuration_service_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Disable the default Application Configuration Service. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param service_name: The name of the Service resource. :type service_name: str :param configuration_service_name: The name of Application Configuration Service. :type configuration_service_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises: ~azure.core.exceptions.HttpResponseError """ polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}'} # type: ignore @distributed_trace def list( self, resource_group_name: str, service_name: str, **kwargs: Any ) -> AsyncIterable["_models.ConfigurationServiceResourceCollection"]: """Handles requests to list all resources in a Service. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param service_name: The name of the Service resource. :type service_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ConfigurationServiceResourceCollection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.appplatform.v2022_01_01_preview.models.ConfigurationServiceResourceCollection] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationServiceResourceCollection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, service_name=service_name, template_url=self.list.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_request( subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, service_name=service_name, template_url=next_link, ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ConfigurationServiceResourceCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices'} # type: ignore async def _validate_initial( self, resource_group_name: str, service_name: str, configuration_service_name: str, settings: "_models.ConfigurationServiceSettings", **kwargs: Any ) -> "_models.ConfigurationServiceSettingsValidateResult": cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationServiceSettingsValidateResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(settings, 'ConfigurationServiceSettings') request = build_validate_request_initial( subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, content_type=content_type, json=_json, template_url=self._validate_initial.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ConfigurationServiceSettingsValidateResult', pipeline_response) if response.status_code == 202: deserialized = self._deserialize('ConfigurationServiceSettingsValidateResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _validate_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}/validate'} # type: ignore @distributed_trace_async async def begin_validate( self, resource_group_name: str, service_name: str, configuration_service_name: str, settings: "_models.ConfigurationServiceSettings", **kwargs: Any ) -> AsyncLROPoller["_models.ConfigurationServiceSettingsValidateResult"]: """Check if the Application Configuration Service settings are valid. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param service_name: The name of the Service resource. :type service_name: str :param configuration_service_name: The name of Application Configuration Service. :type configuration_service_name: str :param settings: Application Configuration Service settings to be validated. :type settings: ~azure.mgmt.appplatform.v2022_01_01_preview.models.ConfigurationServiceSettings :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ConfigurationServiceSettingsValidateResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.appplatform.v2022_01_01_preview.models.ConfigurationServiceSettingsValidateResult] :raises: ~azure.core.exceptions.HttpResponseError """ content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationServiceSettingsValidateResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._validate_initial( resource_group_name=resource_group_name, service_name=service_name, configuration_service_name=configuration_service_name, settings=settings, content_type=content_type, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) def get_long_running_output(pipeline_response): response = pipeline_response.http_response deserialized = self._deserialize('ConfigurationServiceSettingsValidateResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_validate.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}/validate'} # type: ignore
from numpy.testing import assert_array_equal, assert_almost_equal, \ assert_array_almost_equal, assert_raises, assert_equal import numpy as np import math from skimage.measure._regionprops import regionprops, PROPS, perimeter SAMPLE = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], [0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]] ) INTENSITY_SAMPLE = SAMPLE.copy() INTENSITY_SAMPLE[1, 9:11] = 2 def test_all_props(): regions = regionprops(SAMPLE, 'all', INTENSITY_SAMPLE)[0] for prop in PROPS: regions[prop] def test_dtype(): regionprops(np.zeros((10, 10), dtype=np.int)) regionprops(np.zeros((10, 10), dtype=np.uint)) assert_raises((TypeError, RuntimeError), regionprops, np.zeros((10, 10), dtype=np.double)) def test_ndim(): regionprops(np.zeros((10, 10), dtype=np.int)) regionprops(np.zeros((10, 10, 1), dtype=np.int)) regionprops(np.zeros((10, 10, 1, 1), dtype=np.int)) assert_raises(TypeError, regionprops, np.zeros((10, 10, 2), dtype=np.int)) def test_area(): area = regionprops(SAMPLE)[0].area assert area == np.sum(SAMPLE) def test_bbox(): bbox = regionprops(SAMPLE)[0].bbox assert_array_almost_equal(bbox, (0, 0, SAMPLE.shape[0], SAMPLE.shape[1])) SAMPLE_mod = SAMPLE.copy() SAMPLE_mod[:, -1] = 0 bbox = regionprops(SAMPLE_mod)[0].bbox assert_array_almost_equal(bbox, (0, 0, SAMPLE.shape[0], SAMPLE.shape[1]-1)) def test_moments_central(): mu = regionprops(SAMPLE)[0].moments_central # determined with OpenCV assert_almost_equal(mu[0,2], 436.00000000000045) # different from OpenCV results, bug in OpenCV assert_almost_equal(mu[0,3], -737.333333333333) assert_almost_equal(mu[1,1], -87.33333333333303) assert_almost_equal(mu[1,2], -127.5555555555593) assert_almost_equal(mu[2,0], 1259.7777777777774) assert_almost_equal(mu[2,1], 2000.296296296291) assert_almost_equal(mu[3,0], -760.0246913580195) def test_centroid(): centroid = regionprops(SAMPLE)[0].centroid # determined with MATLAB assert_array_almost_equal(centroid, (5.66666666666666, 9.444444444444444)) def test_convex_area(): area = regionprops(SAMPLE)[0].convex_area # determined with MATLAB assert area == 124 def test_convex_image(): img = regionprops(SAMPLE)[0].convex_image # determined with MATLAB ref = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) assert_array_equal(img, ref) def test_coordinates(): sample = np.zeros((10, 10), dtype=np.int8) coords = np.array([[3, 2], [3, 3], [3, 4]]) sample[coords[:, 0], coords[:, 1]] = 1 prop_coords = regionprops(sample)[0].coords assert_array_equal(prop_coords, coords) def test_eccentricity(): eps = regionprops(SAMPLE)[0].eccentricity assert_almost_equal(eps, 0.814629313427) img = np.zeros((5, 5), dtype=np.int) img[2, 2] = 1 eps = regionprops(img)[0].eccentricity assert_almost_equal(eps, 0) def test_equiv_diameter(): diameter = regionprops(SAMPLE)[0].equivalent_diameter # determined with MATLAB assert_almost_equal(diameter, 9.57461472963) def test_euler_number(): en = regionprops(SAMPLE)[0].euler_number assert en == 0 SAMPLE_mod = SAMPLE.copy() SAMPLE_mod[7, -3] = 0 en = regionprops(SAMPLE_mod)[0].euler_number assert en == -1 def test_extent(): extent = regionprops(SAMPLE)[0].extent assert_almost_equal(extent, 0.4) def test_moments_hu(): hu = regionprops(SAMPLE)[0].moments_hu ref = np.array([ 3.27117627e-01, 2.63869194e-02, 2.35390060e-02, 1.23151193e-03, 1.38882330e-06, -2.72586158e-05, 6.48350653e-06 ]) # bug in OpenCV caused in Central Moments calculation? assert_array_almost_equal(hu, ref) def test_image(): img = regionprops(SAMPLE)[0].image assert_array_equal(img, SAMPLE) def test_label(): label = regionprops(SAMPLE)[0].label assert_array_equal(label, 1) def test_filled_area(): area = regionprops(SAMPLE)[0].filled_area assert area == np.sum(SAMPLE) SAMPLE_mod = SAMPLE.copy() SAMPLE_mod[7, -3] = 0 area = regionprops(SAMPLE_mod)[0].filled_area assert area == np.sum(SAMPLE) def test_filled_image(): img = regionprops(SAMPLE)[0].filled_image assert_array_equal(img, SAMPLE) def test_major_axis_length(): length = regionprops(SAMPLE)[0].major_axis_length # MATLAB has different interpretation of ellipse than found in literature, # here implemented as found in literature assert_almost_equal(length, 16.7924234999) def test_max_intensity(): intensity = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].max_intensity assert_almost_equal(intensity, 2) def test_mean_intensity(): intensity = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].mean_intensity assert_almost_equal(intensity, 1.02777777777777) def test_min_intensity(): intensity = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].min_intensity assert_almost_equal(intensity, 1) def test_minor_axis_length(): length = regionprops(SAMPLE)[0].minor_axis_length # MATLAB has different interpretation of ellipse than found in literature, # here implemented as found in literature assert_almost_equal(length, 9.739302807263) def test_moments(): m = regionprops(SAMPLE)[0].moments # determined with OpenCV assert_almost_equal(m[0,0], 72.0) assert_almost_equal(m[0,1], 408.0) assert_almost_equal(m[0,2], 2748.0) assert_almost_equal(m[0,3], 19776.0) assert_almost_equal(m[1,0], 680.0) assert_almost_equal(m[1,1], 3766.0) assert_almost_equal(m[1,2], 24836.0) assert_almost_equal(m[2,0], 7682.0) assert_almost_equal(m[2,1], 43882.0) assert_almost_equal(m[3,0], 95588.0) def test_moments_normalized(): nu = regionprops(SAMPLE)[0].moments_normalized # determined with OpenCV assert_almost_equal(nu[0,2], 0.08410493827160502) assert_almost_equal(nu[1,1], -0.016846707818929982) assert_almost_equal(nu[1,2], -0.002899800614433943) assert_almost_equal(nu[2,0], 0.24301268861454037) assert_almost_equal(nu[2,1], 0.045473992910668816) assert_almost_equal(nu[3,0], -0.017278118992041805) def test_orientation(): orientation = regionprops(SAMPLE)[0].orientation # determined with MATLAB assert_almost_equal(orientation, 0.10446844651921) # test correct quadrant determination orientation2 = regionprops(SAMPLE.T)[0].orientation assert_almost_equal(orientation2, math.pi / 2 - orientation) # test diagonal regions diag = np.eye(10, dtype=int) orientation_diag = regionprops(diag)[0].orientation assert_almost_equal(orientation_diag, -math.pi / 4) orientation_diag = regionprops(np.flipud(diag))[0].orientation assert_almost_equal(orientation_diag, math.pi / 4) orientation_diag = regionprops(np.fliplr(diag))[0].orientation assert_almost_equal(orientation_diag, math.pi / 4) orientation_diag = regionprops(np.fliplr(np.flipud(diag)))[0].orientation assert_almost_equal(orientation_diag, -math.pi / 4) def test_perimeter(): per = regionprops(SAMPLE)[0].perimeter assert_almost_equal(per, 55.2487373415) per = perimeter(SAMPLE.astype('double'), neighbourhood=8) assert_almost_equal(per, 46.8284271247) def test_solidity(): solidity = regionprops(SAMPLE)[0].solidity # determined with MATLAB assert_almost_equal(solidity, 0.580645161290323) def test_weighted_moments_central(): wmu = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].weighted_moments_central ref = np.array( [[ 7.4000000000e+01, -2.1316282073e-13, 4.7837837838e+02, -7.5943608473e+02], [ 3.7303493627e-14, -8.7837837838e+01, -1.4801314828e+02, -1.2714707125e+03], [ 1.2602837838e+03, 2.1571526662e+03, 6.6989799420e+03, 1.5304076361e+04], [ -7.6561796932e+02, -4.2385971907e+03, -9.9501164076e+03, -3.3156729271e+04]] ) np.set_printoptions(precision=10) assert_array_almost_equal(wmu, ref) def test_weighted_centroid(): centroid = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].weighted_centroid assert_array_almost_equal(centroid, (5.540540540540, 9.445945945945)) def test_weighted_moments_hu(): whu = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].weighted_moments_hu ref = np.array([ 3.1750587329e-01, 2.1417517159e-02, 2.3609322038e-02, 1.2565683360e-03, 8.3014209421e-07, -3.5073773473e-05, 6.7936409056e-06 ]) assert_array_almost_equal(whu, ref) def test_weighted_moments(): wm = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].weighted_moments ref = np.array( [[ 7.4000000000e+01, 4.1000000000e+02, 2.7500000000e+03, 1.9778000000e+04], [ 6.9900000000e+02, 3.7850000000e+03, 2.4855000000e+04, 1.7500100000e+05], [ 7.8630000000e+03, 4.4063000000e+04, 2.9347700000e+05, 2.0810510000e+06], [ 9.7317000000e+04, 5.7256700000e+05, 3.9007170000e+06, 2.8078871000e+07]] ) assert_array_almost_equal(wm, ref) def test_weighted_moments_normalized(): wnu = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE )[0].weighted_moments_normalized ref = np.array( [[ np.nan, np.nan, 0.0873590903, -0.0161217406], [ np.nan, -0.0160405109, -0.0031421072, -0.0031376984], [ 0.230146783, 0.0457932622, 0.0165315478, 0.0043903193], [-0.0162529732, -0.0104598869, -0.0028544152, -0.0011057191]] ) assert_array_almost_equal(wnu, ref) def test_old_dict_interface(): feats = regionprops(SAMPLE, ['Area', 'Eccentricity', 'EulerNumber', 'Extent', 'MinIntensity', 'MeanIntensity', 'MaxIntensity', 'Solidity'], intensity_image=INTENSITY_SAMPLE) np.array([list(props.values()) for props in feats], np.float) assert_equal(len(feats[0]), 8) def assign(): feats[0]['Area'] = 0 assert_raises(RuntimeError, assign) def test_label_sequence(): a = np.empty((2, 2), dtype=np.int) a[:, :] = 2 ps = regionprops(a) assert len(ps) == 1 assert ps[0].label == 2 def test_pure_background(): a = np.zeros((2, 2), dtype=np.int) ps = regionprops(a) assert len(ps) == 0 def test_invalid(): ps = regionprops(SAMPLE) def get_intensity_image(): ps[0].intensity_image assert_raises(AttributeError, get_intensity_image) if __name__ == "__main__": from numpy.testing import run_module_suite run_module_suite()
#!/usr/bin/env python # coding: UTF-8 """Higher order singular value decomposition routines as introduced in: Lieven de Lathauwer, Bart de Moor, Joos Vandewalle, 'A multilinear singular value decomposition', SIAM J. Matrix Anal. Appl. 21 (4), 2000, 1253-1278 implemented by Jiahao Chen <jiahao@mit.edu>, 2010-06-11 Disclaimer: this code may or may not work. """ __author__ = 'Jiahao Chen <jiahao@mit.edu>' __copyright__ = 'Copyright (c) 2010 Jiahao Chen' __license__ = 'Public domain' try: import numpy as np except ImportError: print "Error: HOSVD requires numpy" raise ImportError def unfold(A,n): """Computes the unfolded matrix representation of a tensor Parameters ---------- A : ndarray, shape (M_1, M_2, ..., M_N) n : (integer) axis along which to perform unfolding, starting from 1 for the first dimension Returns ------- Au : ndarray, shape (M_n, M_(n+1)*M_(n+2)*...*M_N*M_1*M_2*...*M_(n-1)) The unfolded tensor as a matrix Raises ------ ValueError if A is not an ndarray LinAlgError if axis n is not in the range 1:N Notes ----- As defined in Definition 1 of: Lieven de Lathauwer, Bart de Moor, Joos Vandewalle, "A multilinear singular value decomposition", SIAM J. Matrix Anal. Appl. 21 (4), 2000, 1253-1278 """ if type(A) != type(np.zeros((1))): print "Error: Function designed to work with numpy ndarrays" raise ValueError if not (1 <= n <= A.ndim): print "Error: axis %d not in range 1:%d" % (n, A.ndim) raise np.linalg.LinAlgError s = A.shape m = 1 for i in range(len(s)): m *= s[i] m /= s[n-1] #The unfolded matrix has shape (s[n-1],m) Au = np.zeros((s[n-1],m)) index = [0]*len(s) for i in range(s[n-1]): index[n-1] = i for j in range(m): Au[i,j] = A[tuple(index)] #increment (n-1)th index first index[n-2] += 1 #carry over: exploit python's automatic looparound of addressing! for k in range(n-2,n-1-len(s),-1): if index[k] == s[k]: index[k-1] += 1 index[k] = 0 return Au def fold(Au, n, s): """Reconstructs a tensor given its unfolded matrix representation Parameters ---------- Au : ndarray, shape (M_n, M_(n+1)*M_(n+2)*...*M_N*M_1*M_2*...*M_(n-1)) The unfolded matrix representation of a tensor n : (integer) axis along which to perform unfolding, starting from 1 for the first dimension s : (tuple of integers of length N) desired shape of resulting tensor Returns ------- A : ndarray, shape (M_1, M_2, ..., M_N) Raises ------ ValueError if A is not an ndarray LinAlgError if axis n is not in the range 1:N Notes ----- Defined as the natural inverse of the unfolding operation as defined in Definition 1 of: Lieven de Lathauwer, Bart de Moor, Joos Vandewalle, "A multilinear singular value decomposition", SIAM J. Matrix Anal. Appl. 21 (4), 2000, 1253-1278 """ m = 1 for i in range(len(s)): m *= s[i] m /= s[n-1] #check for shape compatibility if Au.shape != (s[n-1], m): print "Wrong shape: need", (s[n-1], m), "but have instead", Au.shape raise np.linalg.LinAlgError A = np.zeros(s) index = [0]*len(s) for i in range(s[n-1]): index[n-1] = i for j in range(m): A[tuple(index)] = Au[i,j] #increment (n-1)th index first index[n-2] += 1 #carry over: exploit python's automatic looparound of addressing! for k in range(n-2,n-1-len(s),-1): if index[k] == s[k]: index[k-1] += 1 index[k] = 0 return A def HOSVD(A): """Computes the higher order singular value decomposition of a tensor Parameters ---------- A : ndarray, shape (M_1, M_2, ..., M_N) Returns ------- U : list of N matrices, with the nth matrix having shape (M_n, M_n) The n-mode left singular matrices U^(n), n=1:N S : ndarray, shape (M_1, M_2, ..., M_N) The core tensor D : list of N lists, with the nth list having length M_n The n-mode singular values D^(n), n=1:N Raises ------ ValueError if A is not an ndarray LinAlgError if axis n is not in the range 1:N Notes ----- Returns the quantities in Equation 22 of: Lieven de Lathauwer, Bart de Moor, Joos Vandewalle, "A multilinear singular value decomposition", SIAM J. Matrix Anal. Appl. 21 (4), 2000, 1253-1278 """ Transforms = [] NModeSingularValues = [] #--- Compute the SVD of each possible unfolding for i in range(len(A.shape)): U,D,V = np.linalg.svd(unfold(A,i+1)) Transforms.append(np.asmatrix(U)) NModeSingularValues.append(D) #--- Compute the unfolded core tensor axis = 1 #An arbitrary choice, really Aun = unfold(A,axis) #--- Computes right hand side transformation matrix B = np.ones((1,)) for i in range(axis-A.ndim,axis-1): B = np.kron(B, Transforms[i]) #--- Compute the unfolded core tensor along the chosen axis Sun = Transforms[axis-1].transpose().conj() * Aun * B print "shapes",A.shape S = fold(Sun, axis, A.shape) return Transforms, S, NModeSingularValues if __name__ == '__main__': print print "Higher order singular value decomposition routines" print print "as introduced in:" print " Lieven de Lathauwer, Bart de Moor, Joos Vandewalle," print " 'A multilinear singular value decomposition'," print " SIAM J. Matrix Anal. Appl. 21 (4), 2000, 1253-1278" print print "Here are some worked examples from the paper." print print print "Example 1 from the paper (p. 1256)" A = np.zeros((3,2,3)) A[0,0,0]=A[0,0,1]=A[1,0,0]=1 A[1,0,1]=-1 A[1,0,2]=A[2,0,0]=A[2,0,2]=A[0,1,0]=A[0,1,1]=A[1,1,0]=2 A[1,1,1]=-2 A[1,1,2]=A[2,1,0]=A[2,1,2]=4 #other elements implied zero #test: compute unfold(A,1) print print "The input tensor is:" print A print print "Its unfolding along the first axis is:" print unfold(A,1) """ print print print "Example 2 from the paper (p. 1257)"" A = np.zeros((2,2,2)) A[0,0,0] = A[1,1,0] = A[0,0,1] = 1 #other elements implied zero """ """ print print print "Example 3 from the paper (p. 1257)"" A = np.zeros((2,2,2)) A[1,0,0] = A[0,1,0] = A[0,0,1] = 1 #other elements implied zero """ print print print "Example 4 from the paper (pp. 1264-5)" A = np.zeros((3,3,3)) A[:,0,:] = np.asmatrix([[0.9073, 0.8924, 2.1488], [0.7158, -0.4898, 0.3054], [-0.3698, 2.4288, 2.3753]]).transpose() A[:,1,:] = np.asmatrix([[1.7842, 1.7753, 4.2495], [1.6970, -1.5077, 0.3207], [0.0151, 4.0337, 4.7146]]).transpose() A[:,2,:] = np.asmatrix([[2.1236, -0.6631, 1.8260], [-0.0740, 1.9103, 2.1335], [1.4429, -1.7495,-0.2716]]).transpose() print "The input tensor has matrix unfolding along axis 1:" print unfold(A,1) print U, S, D = HOSVD(A) print "The left n-mode singular matrices are:" print U[0] print print U[1] print print U[2] print print "The core tensor has matrix unfolding along axis 1:" print unfold(S, 1) print print "The n-mode singular values are:" print D[0] print D[1] print D[2]
""" PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net) Copyright (C) 2004-2020 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved, Brett G. Olivier (bgoli@users.sourceforge.net) Triple-J Group for Molecular Cell Physiology Stellenbosch University, South Africa. Permission to use, modify, and distribute this software is given under the terms of the PySceS (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Brett G. Olivier """ from __future__ import division, print_function from __future__ import absolute_import from __future__ import unicode_literals from .version import __version__ __doc__ = '''PySCeS ModelMap module: useful for exploring model component relations''' class ModelMapBase(object): name = None def getName(self): return self.name def setName(self, name): self.name = name def get(self, attr): """Return an attribute whose name is str(attr)""" try: return getattr(self, attr) except: print("%s is not an attribute of this instance" % attr) return None class MapList(list): def __init__(self, *args): list.__init__(self, *args) def asSet(self): return set(self.__getslice__(0, self.__len__())) class ModelMap(ModelMapBase): __nDict__ = None reactions = None species = None species_fixed = None compartments = None __model__ = None __InitStrings__ = None __InitDict__ = None __not_inited__ = None global_parameters = None __parameter_store__ = None def __init__(self, model): self.setName(model.ModelFile[:-4]) self.__nDict__ = model.__nDict__ self.__model__ = model self.__InitDict__ = self.__model__.__InitDict__.copy() self.__compartments__ = self.__model__.__compartments__.copy() for k in list(self.__InitDict__.keys()): self.__InitDict__[k] = getattr(self.__model__, k) self.global_parameters = [] self.__parameter_store__ = [] self.__not_inited__ = [] # operational shortcuts self.addSpecies() self.addReactions() self.generateMappings() self.addCompartments() def __cleanString__(self, s): s = s.lstrip() s = s.rstrip() return s def addOneSpecies(self, species, fix=False): s = Species(species) s.setValue(self.__InitDict__[s.name]) if fix: s.fixed = True setattr(self, species, s) self.species.append(s) if fix: self.species_fixed.append(s) def addCompartments(self): self.compartments = [] for c in self.__model__.__compartments__: co = Compartment( self.__model__.__compartments__[c]['name'], self.__model__.__compartments__[c]['size'], ) self.compartments.append(co) setattr(self, c, co) cname = [c.name for c in self.compartments] for s in list(self.__model__.__sDict__.keys()): if self.__model__.__sDict__[s]['compartment'] in cname: getattr(self, self.__model__.__sDict__[s]['compartment']).setComponent( getattr(self, s) ) getattr(self, s).compartment = getattr( self, self.__model__.__sDict__[s]['compartment'] ) for r in list(self.__model__.__nDict__.keys()): if self.__model__.__nDict__[r]['compartment'] in cname: getattr(self, self.__model__.__nDict__[r]['compartment']).setComponent( getattr(self, r) ) getattr(self, r).compartment = getattr( self, self.__model__.__nDict__[r]['compartment'] ) def addOneReaction(self, reaction): r = Reaction(reaction) r.addFormula(self.__nDict__[r.name]['RateEq'].replace('self.', '')) if self.__nDict__[r.name]['Type'] == 'Irrev': r.reversible = False fxnames = self.hasFixedSpecies() for p in self.__nDict__[r.name]['Params']: p = p.replace('self.', '') if ( p not in self.hasGlobalParameters() and p not in fxnames and p not in self.__compartments__ ): if p in self.__InitDict__: par = Parameter(p, self.__InitDict__[p]) else: par = Parameter(p) if p not in self.__not_inited__: self.__not_inited__.append(p) par.setAssociation(r) self.global_parameters.append(par) setattr(self, p, par) r.addParameter(par) elif p not in fxnames and p not in self.__compartments__: pidx = self.hasGlobalParameters().index(p) self.global_parameters[pidx].setAssociation(r) r.addParameter(self.global_parameters[pidx]) setattr(self, reaction, r) self.reactions.append(r) def addSpecies(self): self.species = [] self.species_fixed = [] for s in self.__model__.species: self.addOneSpecies(s, fix=False) for s in self.__model__.fixed_species: self.addOneSpecies(s, fix=True) def addReactions(self): self.reactions = [] for r in self.__model__.reactions: self.addOneReaction(r) def generateMappings(self): for reac in self.reactions: for reag in self.__nDict__[reac.name]['Reagents']: if self.__nDict__[reac.name]['Reagents'][reag] < 0.0: reac.addSubstrate(getattr(self, reag.replace('self.', ''))) getattr(self, reag.replace('self.', '')).setSubstrate( getattr(self, reac.name) ) else: reac.addProduct(getattr(self, reag.replace('self.', ''))) getattr(self, reag.replace('self.', '')).setProduct( getattr(self, reac.name) ) reac.stoichiometry.setdefault( reag.replace('self.', ''), self.__nDict__[reac.name]['Reagents'][reag], ) for mod in self.__nDict__[reac.name]['Modifiers']: reac.addModifier(getattr(self, mod.replace('self.', ''))) getattr(self, mod.replace('self.', '')).setModifier( getattr(self, reac.name) ) def hasReactions(self): return MapList([r.name for r in self.reactions]) def hasSpecies(self): return MapList([s.name for s in self.species]) def hasFixedSpecies(self): return MapList([s.name for s in self.species_fixed]) def findReactionsThatIncludeAllSpecifiedReagents(self, *args): assert len(args) > 1, '\nNeed two or more species for this one!' setlist = [getattr(self, s).isReagentOf().asSet() for s in args] isect = setlist[0] for s in setlist: isect.intersection_update(s) return MapList(isect) def hasGlobalParameters(self): return MapList(p.name for p in self.global_parameters) class Reaction(ModelMapBase): modifiers = None substrates = None products = None stoichiometry = None parameters = None reversible = True formula = None compartment = None def __init__(self, name): self.setName(name) self.modifiers = [] self.substrates = [] self.products = [] self.stoichiometry = {} self.parameters = [] def addSubstrate(self, species): setattr(self, species.name, species) self.substrates.append(species) def addProduct(self, species): setattr(self, species.name, species) self.products.append(species) def addModifier(self, species): setattr(self, species.name, species) self.modifiers.append(species) def addFormula(self, formula): self.formula = formula def addParameter(self, par): setattr(self, par.name, par) self.parameters.append(par) def hasProducts(self, t=type): return MapList([p.name for p in self.products]) def hasSubstrates(self): return MapList([s.name for s in self.substrates]) def hasModifiers(self): return MapList([m.name for m in self.modifiers]) def hasParameters(self): return MapList([p.name for p in self.parameters]) def hasReagents(self): return MapList(self.hasSubstrates() + self.hasProducts()) class NumberBase(ModelMapBase): value = None def __call__(self): return self.value def getValue(self): return self.value def setValue(self, v): self.value = v class Species(NumberBase): subs = None prods = None mods = None fixed = False compartment = None def __init__(self, name): self.setName(name) self.subs = [] self.prods = [] self.mods = [] def setSubstrate(self, reaction): setattr(self, reaction.name, reaction) self.subs.append(reaction) def setProduct(self, reaction): setattr(self, reaction.name, reaction) self.prods.append(reaction) def setModifier(self, reaction): setattr(self, reaction.name, reaction) self.mods.append(reaction) def isSubstrateOf(self): return MapList([r.name for r in self.subs]) def isProductOf(self): return MapList([r.name for r in self.prods]) def isModifierOf(self): return MapList([r.name for r in self.mods]) def isReagentOf(self): return MapList(self.isSubstrateOf() + self.isProductOf()) class Parameter(NumberBase): association = None formula = None def __init__(self, name, value=None): self.name = name self.value = value self.association = [] def setAssociation(self, reac): self.association.append(reac) setattr(self, reac.name, reac) def isParameterOf(self): return MapList([a.name for a in self.association]) def setFormula(self, formula): self.formula = formula class Compartment(NumberBase): components = None def __init__(self, name, value=None): self.name = name self.value = value self.components = [] def setComponent(self, comp): self.components.append(comp) setattr(self, comp.name, comp) def hasComponents(self): return MapList([a.name for a in self.components]) if __name__ == '__main__': import pysces M = pysces.model('pysces_model_linear1') M.doLoad() print('\nModel', M.ModelFile) print('=============') modmap = ModelMap(M) print('Reactions\n', modmap.hasReactions()) print('Species\n', modmap.hasSpecies()) print('FixedSpecies\n', modmap.hasFixedSpecies()) print(' ') print('R1 has reagents\n', modmap.R1.hasReagents()) print('R1 has sub\n', modmap.R1.hasSubstrates()) print('R1 has prod\n', modmap.R1.hasProducts()) print('R1 has mod\n', modmap.R1.hasModifiers()) print(' ') print('s2 is reagent\n', modmap.s2.isReagentOf()) print('s2 is sub\n', modmap.s2.isSubstrateOf()) print('s2 is prod\n', modmap.s2.isProductOf()) print('s2 is mod\n', modmap.s2.isModifierOf()) print(' ') print('R2 stoich\n', modmap.R2.stoichiometry) print(' ') print( 'findReactionsThatIncludeAllSpecifiedReagents(A, B):', modmap.findReactionsThatIncludeAllSpecifiedReagents('s1', 's2'), ) print('\nmodmap.hasGlobalParameters\n', modmap.hasGlobalParameters()) print('\nParameter associations') for p in modmap.global_parameters: print('%s.isParameterOf() %s' % (p.name, p.isParameterOf()))
from typing import List from uchan.lib import action_authorizer, roles from uchan.lib.action_authorizer import ModeratorBoardAction, NoPermissionError from uchan.lib.exceptions import ArgumentError from uchan.lib.mod_log import mod_log from uchan.lib.model import ModeratorLogType, ModeratorModel, BoardModel, BoardModeratorModel, ModeratorLogModel from uchan.lib.repository import moderators, board_moderators, boards, moderator_logs from uchan.lib.service import board_service from uchan.lib.utils import now MESSAGE_PASSWORD_INCORRECT = 'Password does not match' # Moderators def find_moderator_id(moderator_id: int) -> ModeratorModel: return moderators.find_by_id(moderator_id) def find_moderator_username(username: str) -> ModeratorModel: return moderators.find_by_username_case_insensitive(username) def delete_moderator(moderator: ModeratorModel): moderators.delete(moderator) def get_all_moderators(include_boards=False) -> 'List[ModeratorModel]': return moderators.get_all(include_boards) def check_password(moderator: ModeratorModel, password: str): moderators.check_password_match(moderator, password) def set_password(moderator: ModeratorModel, password: str): moderators.update_password(moderator, password) def check_and_set_password(moderator: ModeratorModel, old_password: str, new_password: str): check_password(moderator, old_password) set_password(moderator, new_password) # Moderator roles def role_exists(role): return role is not None and role in roles.ALL_ROLES def has_role(moderator: ModeratorModel, role: str) -> bool: return moderators.has_role(moderator, role) def add_role(moderator: ModeratorModel, role: str): moderators.add_role(moderator, role) def remove_role(moderator: ModeratorModel, role: str): moderators.remove_role(moderator, role) # Board moderators def get_all_board_moderators_by_moderator(moderator: ModeratorModel) -> 'List[BoardModeratorModel]': return board_moderators.get_all_board_moderators_by_moderator(moderator) def get_all_board_moderators_by_board(board: BoardModel) -> 'List[BoardModeratorModel]': return board_moderators.get_all_board_moderators_by_board(board) def get_all_moderating_boards(moderator: ModeratorModel) -> 'List[BoardModel]': return board_moderators.get_all_moderating_boards(moderator) def moderates_board(moderator: ModeratorModel, board: BoardModel) -> bool: return board_moderators.moderator_has_board(moderator, board) def moderates_board_id(moderator: ModeratorModel, board_id: int) -> bool: if has_role(moderator, roles.ROLE_ADMIN): return True return board_moderators.moderator_has_board_id(moderator, board_id) # Board moderator roles def has_any_of_board_roles(moderator: ModeratorModel, board: BoardModel, role_list: 'List[str]'): return board_moderators.has_any_of_board_roles(moderator, board, role_list) def add_board_role(moderator: ModeratorModel, board: BoardModel, role: str): return board_moderators.add_board_role(moderator, board, role) def remove_board_role(moderator: ModeratorModel, board: BoardModel, role: str): return board_moderators.remove_board_role(moderator, board, role) # Board moderator user actions # Various actions checked with the authorizer def user_create_board(moderator: ModeratorModel, board_name: str): action_authorizer.authorize_action(moderator, action_authorizer.ModeratorAction.BOARD_CREATE) # TODO: make this atomic board = BoardModel.from_name(board_name) board = board_service.add_board(board) board_service.add_moderator(board, moderator) board_moderators.add_board_role(moderator, board, roles.BOARD_ROLE_CREATOR) board_moderators.add_board_role(moderator, board, roles.BOARD_ROLE_FULL_PERMISSION) mod_log('Board {} created'.format(board.name)) return board def user_delete_board(moderator, board): action_authorizer.authorize_action(moderator, action_authorizer.ModeratorAction.BOARD_DELETE) board_name = board.name board_service.delete_board(board) mod_log('Board {} deleted'.format(board_name)) def can_update_board_config(moderator: ModeratorModel, board: BoardModel) -> bool: try: action_authorizer.authorize_board_action(moderator, board, ModeratorBoardAction.CONFIG_UPDATE) return True except NoPermissionError: return False # TODO: merge with authorizer def can_update_advanced_board_configs(moderator: ModeratorModel) -> bool: return has_role(moderator, roles.ROLE_ADMIN) def can_create_board(moderator: ModeratorModel) -> bool: try: action_authorizer.authorize_action(moderator, action_authorizer.ModeratorAction.BOARD_CREATE) return True except (ArgumentError, NoPermissionError): return False def can_update_roles(moderator: ModeratorModel, board: BoardModel) -> bool: try: action_authorizer.authorize_board_action(moderator, board, ModeratorBoardAction.ROLES_UPDATE) return True except NoPermissionError: return False def can_invite_moderator(moderator: ModeratorModel, board: BoardModel): try: action_authorizer.authorize_board_action(moderator, board, ModeratorBoardAction.MODERATOR_ADD) return True except NoPermissionError: return False def can_remove_moderator(moderator: ModeratorModel, board: BoardModel): try: action_authorizer.authorize_board_action(moderator, board, ModeratorBoardAction.MODERATOR_REMOVE) return True except NoPermissionError: return False def can_delete_board(moderator: ModeratorModel): return has_role(moderator, roles.ROLE_ADMIN) def required_roles_for_viewing_reports(): return [roles.BOARD_ROLE_FULL_PERMISSION, roles.BOARD_ROLE_JANITOR] def user_update_board_config(moderator: ModeratorModel, board: BoardModel): action_authorizer.authorize_board_action(moderator, board, action_authorizer.ModeratorBoardAction.CONFIG_UPDATE) boards.update_config(board) log(ModeratorLogType.CONFIG_UPDATE, moderator, board, 'Config updated') def user_invite_moderator(moderator: ModeratorModel, board: BoardModel, username: str): action_authorizer.authorize_board_action(moderator, board, action_authorizer.ModeratorBoardAction.MODERATOR_ADD) invitee = find_moderator_username(username) if not invitee: raise ArgumentError('Moderator not found') board_service.add_moderator(board, invitee) log(ModeratorLogType.MODERATOR_INVITE, moderator, board, 'Invited {}'.format(invitee.username)) def user_remove_moderator(moderator: ModeratorModel, board: BoardModel, username: str): member = find_moderator_username(username) if not member: raise ArgumentError('Moderator not found') if has_any_of_board_roles(member, board, [roles.BOARD_ROLE_CREATOR]): raise ArgumentError('Cannot remove creator') if moderator.id == member.id: action_authorizer.authorize_board_action(moderator, board, action_authorizer.ModeratorBoardAction.MODERATOR_REMOVE_SELF) board_service.remove_moderator(board, member) log(ModeratorLogType.MODERATOR_REMOVE, moderator, board, 'Removed self') return True else: action_authorizer.authorize_board_action(moderator, board, action_authorizer.ModeratorBoardAction.MODERATOR_REMOVE) board_service.remove_moderator(board, member) log(ModeratorLogType.MODERATOR_REMOVE, moderator, board, 'Removed {}'.format(member.username)) return False def user_update_roles(moderator: ModeratorModel, board: BoardModel, username: str, new_roles: 'List[str]'): action_authorizer.authorize_board_action(moderator, board, action_authorizer.ModeratorBoardAction.ROLES_UPDATE) subject = find_moderator_username(username) if not subject: raise ArgumentError('Moderator not found') if moderator.id == subject.id: # and not has_role(moderator, roles.ROLE_ADMIN): raise ArgumentError('Cannot change self') board_moderator = board_moderators.get_board_moderator(board, subject) if not board_moderator: raise ArgumentError('Not a mod of that board') changed = set(new_roles) ^ set(board_moderator.roles) # creator is unchangeable if roles.BOARD_ROLE_CREATOR in changed: changed.remove(roles.BOARD_ROLE_CREATOR) if changed: added_roles = [] removed_roles = [] for i in changed: if i not in board_moderator.roles: added_roles.append(i) else: removed_roles.append(i) for add in added_roles: action_authorizer.authorize_board_action( moderator, board, action_authorizer.ModeratorBoardAction.ROLE_ADD, (subject, add)) add_board_role(subject, board, add) log(ModeratorLogType.MODERATOR_ROLE_ADD, moderator, board, 'Added role {} to {}'.format(add, subject.username)) for remove in removed_roles: action_authorizer.authorize_board_action( moderator, board, action_authorizer.ModeratorBoardAction.ROLE_REMOVE, (subject, remove)) remove_board_role(subject, board, remove) log(ModeratorLogType.MODERATOR_ROLE_REMOVE, moderator, board, 'Removed role {} from {}'.format(remove, subject.username)) def user_register(username: str, password: str, password_repeat: str): """ Register a moderator with the given passwords. The created moderator has no roles and no relationships to boards. If user registration was disabled in the site configuration, this methods throws an ArgumentError. :param username: username to register with :param password: password to register with :param password_repeat: repeated version of password, used for the error message. :raises ArgumentError if user registration is disabled. :raises ArgumentError if the two passwords don't match. :raises ArgumentError any error defined in :meth:`uchan.lib.repository.moderators.create_with_password` :return: the created moderator """ if password != password_repeat: raise ArgumentError(MESSAGE_PASSWORD_INCORRECT) action_authorizer.authorize_registration() moderator = ModeratorModel.from_username(username) moderator = moderators.create_with_password(moderator, password) mod_log('User {} registered'.format(username)) return moderator def user_get_logs(moderator: ModeratorModel, board: BoardModel, page: int, per_page: int) -> 'List[ModeratorLogModel]': action_authorizer.authorize_board_action(moderator, board, action_authorizer.ModeratorBoardAction.VIEW_LOG) return moderator_logs.get_all_logs_by_board(board, page * per_page, per_page) def log(log_type: ModeratorLogType, moderator: ModeratorModel, board: BoardModel, text: str): log_model = ModeratorLogModel.from_date_type_text_moderator_board( date=now(), type=log_type.value, text=text, moderator=moderator, board=board) moderator_logs.create(log_model)
class Node(object): def __init__(self, value): self.value = value self.edges = [] self.visited = False class Edge(object): def __init__(self, value, node_from, node_to): self.value = value self.node_from = node_from self.node_to = node_to # You only need to change code with docs strings that have TODO. # Specifically: Graph.dfs_helper and Graph.bfs # New methods have been added to associate node numbers with names # Specifically: Graph.set_node_names # and the methods ending in "_names" which will print names instead # of node numbers class Graph(object): def __init__(self, nodes=None, edges=None): self.nodes = nodes or [] self.edges = edges or [] self.node_names = [] self._node_map = {} def set_node_names(self, names): """The Nth name in names should correspond to node number N. Node numbers are 0 based (starting at 0). """ self.node_names = list(names) def insert_node(self, new_node_val): "Insert a new node with value new_node_val" new_node = Node(new_node_val) self.nodes.append(new_node) self._node_map[new_node_val] = new_node return new_node def insert_edge(self, new_edge_val, node_from_val, node_to_val): "Insert a new edge, creating new nodes if necessary" nodes = {node_from_val: None, node_to_val: None} for node in self.nodes: if node.value in nodes: nodes[node.value] = node if all(nodes.values()): break for node_val in nodes: nodes[node_val] = nodes[node_val] or self.insert_node(node_val) node_from = nodes[node_from_val] node_to = nodes[node_to_val] new_edge = Edge(new_edge_val, node_from, node_to) node_from.edges.append(new_edge) node_to.edges.append(new_edge) self.edges.append(new_edge) def get_edge_list(self): """Return a list of triples that looks like this: (Edge Value, From Node, To Node)""" return [(e.value, e.node_from.value, e.node_to.value) for e in self.edges] def get_edge_list_names(self): """Return a list of triples that looks like this: (Edge Value, From Node Name, To Node Name)""" return [(edge.value, self.node_names[edge.node_from.value], self.node_names[edge.node_to.value]) for edge in self.edges] def get_adjacency_list(self): """Return a list of lists. The indecies of the outer list represent "from" nodes. Each section in the list will store a list of tuples that looks like this: (To Node, Edge Value)""" max_index = self.find_max_index() adjacency_list = [[] for _ in range(max_index)] for edg in self.edges: from_value, to_value = edg.node_from.value, edg.node_to.value adjacency_list[from_value].append((to_value, edg.value)) return [a or None for a in adjacency_list] # replace []'s with None def get_adjacency_list_names(self): """Each section in the list will store a list of tuples that looks like this: (To Node Name, Edge Value). Node names should come from the names set with set_node_names.""" adjacency_list = self.get_adjacency_list() def convert_to_names(pair, graph=self): node_number, value = pair return (graph.node_names[node_number], value) def map_conversion(adjacency_list_for_node): if adjacency_list_for_node is None: return None return map(convert_to_names, adjacency_list_for_node) return [map_conversion(adjacency_list_for_node) for adjacency_list_for_node in adjacency_list] def get_adjacency_matrix(self): """Return a matrix, or 2D list. Row numbers represent from nodes, column numbers represent to nodes. Store the edge values in each spot, and a 0 if no edge exists.""" max_index = self.find_max_index() adjacency_matrix = [[0] * (max_index) for _ in range(max_index)] for edg in self.edges: from_index, to_index = edg.node_from.value, edg.node_to.value adjacency_matrix[from_index][to_index] = edg.value return adjacency_matrix def find_max_index(self): """Return the highest found node number Or the length of the node names if set with set_node_names().""" if len(self.node_names) > 0: return len(self.node_names) max_index = -1 if len(self.nodes): for node in self.nodes: if node.value > max_index: max_index = node.value return max_index def find_node(self, node_number): "Return the node with value node_number or None" return self._node_map.get(node_number) def _clear_visited(self): for node in self.nodes: node.visited = False def dfs_helper(self, start_node): """TODO: Write the helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node MODIFIES: the value of the visited property of nodes in self.nodes RETURN: a list of the traversed node values (integers). """ ret_list = [start_node.value] # Your code here start_node.visited = True for edge in start_node.edges: if (edge.node_to.visited is False): ret_list += self.dfs_helper(edge.node_to) return ret_list def dfs(self, start_node_num): """Outputs a list of numbers corresponding to the traversed nodes in a Depth First Search. ARGUMENTS: start_node_num is the starting node number (integer) MODIFIES: the value of the visited property of nodes in self.nodes RETURN: a list of the node values (integers).""" self._clear_visited() start_node = self.find_node(start_node_num) return self.dfs_helper(start_node) def dfs_names(self, start_node_num): """Return the results of dfs with numbers converted to names.""" return [self.node_names[num] for num in self.dfs(start_node_num)] def bfs(self, start_node_num): """TODO: Create an iterative implementation of Breadth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the traversed nodes. ARGUMENTS: start_node_num is the node number (integer) MODIFIES: the value of the visited property of nodes in self.nodes RETURN: a list of the node values (integers).""" node = self.find_node(start_node_num) self._clear_visited() ret_list = [] # Your code here queue = [node] node.visited = True while (len(queue) > 0): node = queue.pop(0) ret_list.append(node.value) for edge in node.edges: if (edge.node_from == node) and (edge.node_to.visited is False): queue.append(edge.node_to) edge.node_to.visited = True return ret_list def bfs_names(self, start_node_num): """Return the results of bfs with numbers converted to names.""" return [self.node_names[num] for num in self.bfs(start_node_num)] graph = Graph() # You do not need to change anything below this line. # You only need to implement Graph.dfs_helper and Graph.bfs graph.set_node_names(('Mountain View', # 0 'San Francisco', # 1 'London', # 2 'Shanghai', # 3 'Berlin', # 4 'Sao Paolo', # 5 'Bangalore')) # 6 graph.insert_edge(51, 0, 1) # MV <-> SF graph.insert_edge(51, 1, 0) # SF <-> MV graph.insert_edge(9950, 0, 3) # MV <-> Shanghai graph.insert_edge(9950, 3, 0) # Shanghai <-> MV graph.insert_edge(10375, 0, 5) # MV <-> Sao Paolo graph.insert_edge(10375, 5, 0) # Sao Paolo <-> MV graph.insert_edge(9900, 1, 3) # SF <-> Shanghai graph.insert_edge(9900, 3, 1) # Shanghai <-> SF graph.insert_edge(9130, 1, 4) # SF <-> Berlin graph.insert_edge(9130, 4, 1) # Berlin <-> SF graph.insert_edge(9217, 2, 3) # London <-> Shanghai graph.insert_edge(9217, 3, 2) # Shanghai <-> London graph.insert_edge(932, 2, 4) # London <-> Berlin graph.insert_edge(932, 4, 2) # Berlin <-> London graph.insert_edge(9471, 2, 5) # London <-> Sao Paolo graph.insert_edge(9471, 5, 2) # Sao Paolo <-> London # (6) 'Bangalore' is intentionally disconnected (no edges) # for this problem and should produce None in the # Adjacency List, etc. import pprint pp = pprint.PrettyPrinter(indent=2) print "Edge List" pp.pprint(graph.get_edge_list_names()) print "\nAdjacency List" pp.pprint(graph.get_adjacency_list_names()) print "\nAdjacency Matrix" pp.pprint(graph.get_adjacency_matrix()) print "\nDepth First Search" pp.pprint(graph.dfs_names(2)) # Should print: # Depth First Search # ['London', 'Shanghai', 'Mountain View', 'San Francisco', 'Berlin', 'Sao Paolo'] print "\nBreadth First Search" pp.pprint(graph.bfs_names(2)) # test error reporting # pp.pprint(['Sao Paolo', 'Mountain View', 'San Francisco', 'London', 'Shanghai', 'Berlin']) # Should print: # Breadth First Search # ['London', 'Shanghai', 'Berlin', 'Sao Paolo', 'Mountain View', 'San Francisco']
import logging from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.orm import joinedload from sqlalchemy.sql.expression import desc from sqlalchemy import Column, Boolean, func, or_ from sqlalchemy.exc import IntegrityError from flask import flash from flask.ext.admin._compat import string_types from flask.ext.admin.babel import gettext, ngettext, lazy_gettext from flask.ext.admin.model import BaseModelView from flask.ext.admin.model.form import wrap_fields_in_fieldlist from flask.ext.admin.model.fields import ListEditableFieldList from flask.ext.admin.actions import action from flask.ext.admin._backwards import ObsoleteAttr from flask.ext.admin.contrib.sqla import form, filters, tools from .typefmt import DEFAULT_FORMATTERS from .tools import get_query_for_ids from .ajax import create_ajax_loader # Set up logger log = logging.getLogger("flask-admin.sqla") class ModelView(BaseModelView): """ SQLAlchemy model view Usage sample:: admin = Admin() admin.add_view(ModelView(User, db.session)) """ column_auto_select_related = ObsoleteAttr('column_auto_select_related', 'auto_select_related', True) """ Enable automatic detection of displayed foreign keys in this view and perform automatic joined loading for related models to improve query performance. Please note that detection is not recursive: if `__unicode__` method of related model uses another model to generate string representation, it will still make separate database call. """ column_select_related_list = ObsoleteAttr('column_select_related', 'list_select_related', None) """ List of parameters for SQLAlchemy `subqueryload`. Overrides `column_auto_select_related` property. For example:: class PostAdmin(ModelView): column_select_related_list = ('user', 'city') You can also use properties:: class PostAdmin(ModelView): column_select_related_list = (Post.user, Post.city) Please refer to the `subqueryload` on list of possible values. """ column_display_all_relations = ObsoleteAttr('column_display_all_relations', 'list_display_all_relations', False) """ Controls if list view should display all relations, not only many-to-one. """ column_searchable_list = ObsoleteAttr('column_searchable_list', 'searchable_columns', None) """ Collection of the searchable columns. Example:: class MyModelView(ModelView): column_searchable_list = ('name', 'email') You can also pass columns:: class MyModelView(ModelView): column_searchable_list = (User.name, User.email) The following search rules apply: - If you enter *ZZZ* in the UI search field, it will generate *ILIKE '%ZZZ%'* statement against searchable columns. - If you enter multiple words, each word will be searched separately, but only rows that contain all words will be displayed. For example, searching for 'abc def' will find all rows that contain 'abc' and 'def' in one or more columns. - If you prefix your search term with ^, it will find all rows that start with ^. So, if you entered *^ZZZ*, *ILIKE 'ZZZ%'* will be used. - If you prefix your search term with =, it will perform an exact match. For example, if you entered *=ZZZ*, the statement *ILIKE 'ZZZ'* will be used. """ column_filters = None """ Collection of the column filters. Can contain either field names or instances of :class:`flask.ext.admin.contrib.sqla.filters.BaseFilter` classes. For example:: class MyModelView(BaseModelView): column_filters = ('user', 'email') or:: class MyModelView(BaseModelView): column_filters = (BooleanEqualFilter(User.name, 'Name')) """ model_form_converter = form.AdminModelConverter """ Model form conversion class. Use this to implement custom field conversion logic. For example:: class MyModelConverter(AdminModelConverter): pass class MyAdminView(ModelView): model_form_converter = MyModelConverter """ inline_model_form_converter = form.InlineModelConverter """ Inline model conversion class. If you need some kind of post-processing for inline forms, you can customize behavior by doing something like this:: class MyInlineModelConverter(AdminModelConverter): def post_process(self, form_class, info): form_class.value = wtf.StringField('value') return form_class class MyAdminView(ModelView): inline_model_form_converter = MyInlineModelConverter """ filter_converter = filters.FilterConverter() """ Field to filter converter. Override this attribute to use non-default converter. """ fast_mass_delete = False """ If set to `False` and user deletes more than one model using built in action, all models will be read from the database and then deleted one by one giving SQLAlchemy a chance to manually cleanup any dependencies (many-to-many relationships, etc). If set to `True`, will run a `DELETE` statement which is somewhat faster, but may leave corrupted data if you forget to configure `DELETE CASCADE` for your model. """ inline_models = None """ Inline related-model editing for models with parent-child relations. Accepts enumerable with one of the following possible values: 1. Child model class:: class MyModelView(ModelView): inline_models = (Post,) 2. Child model class and additional options:: class MyModelView(ModelView): inline_models = [(Post, dict(form_columns=['title']))] 3. Django-like ``InlineFormAdmin`` class instance:: class MyInlineModelForm(InlineFormAdmin): form_columns = ('title', 'date') class MyModelView(ModelView): inline_models = (MyInlineModelForm(MyInlineModel),) You can customize the generated field name by: 1. Using the `form_name` property as a key to the options dictionary: class MyModelView(ModelView): inline_models = ((Post, dict(form_label='Hello'))) 2. Using forward relation name and `column_labels` property: class Model1(Base): pass class Model2(Base): # ... model1 = relation(Model1, backref='models') class MyModel1View(Base): inline_models = (Model2,) column_labels = {'models': 'Hello'} """ column_type_formatters = DEFAULT_FORMATTERS form_choices = None """ Map choices to form fields Example:: class MyModelView(BaseModelView): form_choices = {'my_form_field': [ ('db_value', 'display_value'), ] """ form_optional_types = (Boolean,) """ List of field types that should be optional if column is not nullable. Example:: class MyModelView(BaseModelView): form_optional_types = (Boolean, Unicode) """ def __init__(self, model, session, name=None, category=None, endpoint=None, url=None, static_folder=None, menu_class_name=None, menu_icon_type=None, menu_icon_value=None): """ Constructor. :param model: Model class :param session: SQLAlchemy session :param name: View name. If not set, defaults to the model name :param category: Category name :param endpoint: Endpoint name. If not set, defaults to the model name :param url: Base URL. If not set, defaults to '/admin/' + endpoint :param menu_class_name: Optional class name for the menu item. :param menu_icon_type: Optional icon. Possible icon types: - `flask.ext.admin.consts.ICON_TYPE_GLYPH` - Bootstrap glyph icon - `flask.ext.admin.consts.ICON_TYPE_IMAGE` - Image relative to Flask static directory - `flask.ext.admin.consts.ICON_TYPE_IMAGE_URL` - Image with full URL :param menu_icon_value: Icon glyph name or URL, depending on `menu_icon_type` setting """ self.session = session self._search_fields = None self._search_joins = [] self._filter_joins = dict() self._sortable_joins = dict() if self.form_choices is None: self.form_choices = {} super(ModelView, self).__init__(model, name, category, endpoint, url, static_folder, menu_class_name=menu_class_name, menu_icon_type=menu_icon_type, menu_icon_value=menu_icon_value) # Primary key self._primary_key = self.scaffold_pk() if self._primary_key is None: raise Exception('Model %s does not have primary key.' % self.model.__name__) # Configuration if not self.column_select_related_list: self._auto_joins = self.scaffold_auto_joins() else: self._auto_joins = self.column_select_related_list # Internal API def _get_model_iterator(self, model=None): """ Return property iterator for the model """ if model is None: model = self.model return model._sa_class_manager.mapper.iterate_properties def _get_columns_for_field(self, field): if (not field or not hasattr(field, 'property') or not hasattr(field.property, 'columns') or not field.property.columns): raise Exception('Invalid field %s: does not contains any columns.' % field) return field.property.columns def _get_field_with_path(self, name): join_tables = [] if isinstance(name, string_types): model = self.model for attribute in name.split('.'): value = getattr(model, attribute) if (hasattr(value, 'property') and hasattr(value.property, 'direction')): model = value.property.mapper.class_ table = model.__table__ if self._need_join(table): join_tables.append(table) attr = value else: attr = name # determine joins if Table.column (relation object) is given if isinstance(name, InstrumentedAttribute): columns = self._get_columns_for_field(name) if len(columns) > 1: raise Exception('Can only handle one column for %s' % name) column = columns[0] if self._need_join(column.table): join_tables.append(column.table) return join_tables, attr def _need_join(self, table): return table not in self.model._sa_class_manager.mapper.tables # Scaffolding def scaffold_pk(self): """ Return the primary key name(s) from a model If model has single primary key, will return a string and tuple otherwise """ return tools.get_primary_key(self.model) def get_pk_value(self, model): """ Return the primary key value from a model object. If there are multiple primary keys, they're encoded into string representation. """ if isinstance(self._primary_key, tuple): return tools.iterencode(getattr(model, attr) for attr in self._primary_key) else: return tools.escape(getattr(model, self._primary_key)) def scaffold_list_columns(self): """ Return a list of columns from the model. """ columns = [] for p in self._get_model_iterator(): if hasattr(p, 'direction'): if self.column_display_all_relations or p.direction.name == 'MANYTOONE': columns.append(p.key) elif hasattr(p, 'columns'): if len(p.columns) > 1: filtered = tools.filter_foreign_columns(self.model.__table__, p.columns) if len(filtered) > 1: # TODO: Skip column and issue a warning raise TypeError('Can not convert multiple-column properties (%s.%s)' % (self.model, p.key)) column = filtered[0] else: column = p.columns[0] if column.foreign_keys: continue if not self.column_display_pk and column.primary_key: continue columns.append(p.key) return columns def scaffold_sortable_columns(self): """ Return a dictionary of sortable columns. Key is column name, value is sort column/field. """ columns = dict() for p in self._get_model_iterator(): if hasattr(p, 'columns'): # Sanity check if len(p.columns) > 1: # Multi-column properties are not supported continue column = p.columns[0] # Can't sort on primary or foreign keys by default if column.foreign_keys: continue if not self.column_display_pk and column.primary_key: continue columns[p.key] = column return columns def get_sortable_columns(self): """ Returns a dictionary of the sortable columns. Key is a model field name and value is sort column (for example - attribute). If `column_sortable_list` is set, will use it. Otherwise, will call `scaffold_sortable_columns` to get them from the model. """ self._sortable_joins = dict() if self.column_sortable_list is None: return self.scaffold_sortable_columns() else: result = dict() for c in self.column_sortable_list: if isinstance(c, tuple): join_tables, column = self._get_field_with_path(c[1]) column_name = c[0] elif isinstance(c, InstrumentedAttribute): join_tables, column = self._get_field_with_path(c) column_name = str(c) else: join_tables, column = self._get_field_with_path(c) column_name = c result[column_name] = column if join_tables: self._sortable_joins[column_name] = join_tables return result def init_search(self): """ Initialize search. Returns `True` if search is supported for this view. For SQLAlchemy, this will initialize internal fields: list of column objects used for filtering, etc. """ if self.column_searchable_list: self._search_fields = [] self._search_joins = [] joins = set() for p in self.column_searchable_list: join_tables, attr = self._get_field_with_path(p) if not attr: raise Exception('Failed to find field for search field: %s' % p) for column in self._get_columns_for_field(attr): column_type = type(column.type).__name__ self._search_fields.append(column) # Store joins, avoid duplicates for table in join_tables: if table.name not in joins: self._search_joins.append(table) joins.add(table.name) return bool(self.column_searchable_list) def is_text_column_type(self, name): """ Verify if the provided column type is text-based. :returns: ``True`` for ``String``, ``Unicode``, ``Text``, ``UnicodeText``, ``varchar`` """ if name: name = name.lower() return name in ('string', 'unicode', 'text', 'unicodetext', 'varchar') def scaffold_filters(self, name): """ Return list of enabled filters """ join_tables, attr = self._get_field_with_path(name) if attr is None: raise Exception('Failed to find field for filter: %s' % name) # Figure out filters for related column if hasattr(attr, 'property') and hasattr(attr.property, 'direction'): filters = [] for p in self._get_model_iterator(attr.property.mapper.class_): if hasattr(p, 'columns'): # TODO: Check for multiple columns column = p.columns[0] if column.foreign_keys or column.primary_key: continue visible_name = '%s / %s' % (self.get_column_name(attr.prop.table.name), self.get_column_name(p.key)) type_name = type(column.type).__name__ flt = self.filter_converter.convert(type_name, column, visible_name) if flt: table = column.table if join_tables: self._filter_joins[table.name] = join_tables elif self._need_join(table.name): self._filter_joins[table.name] = [table] filters.extend(flt) return filters else: columns = self._get_columns_for_field(attr) if len(columns) > 1: raise Exception('Can not filter more than on one column for %s' % name) column = columns[0] if self._need_join(column.table) and name not in self.column_labels: visible_name = '%s / %s' % ( self.get_column_name(column.table.name), self.get_column_name(column.name) ) else: if not isinstance(name, string_types): visible_name = self.get_column_name(name.property.key) else: visible_name = self.get_column_name(name) type_name = type(column.type).__name__ if join_tables: self._filter_joins[column.table.name] = join_tables flt = self.filter_converter.convert( type_name, column, visible_name, options=self.column_choices.get(name), ) if flt and not join_tables and self._need_join(column.table): self._filter_joins[column.table.name] = [column.table] return flt def is_valid_filter(self, filter): """ Verify that the provided filter object is derived from the SQLAlchemy-compatible filter class. :param filter: Filter object to verify. """ return isinstance(filter, filters.BaseSQLAFilter) def handle_filter(self, filter): column = filter.column if self._need_join(column.table): self._filter_joins[column.table.name] = [column.table] return filter def scaffold_form(self): """ Create form from the model. """ converter = self.model_form_converter(self.session, self) form_class = form.get_form(self.model, converter, base_class=self.form_base_class, only=self.form_columns, exclude=self.form_excluded_columns, field_args=self.form_args, extra_fields=self.form_extra_fields) if self.inline_models: form_class = self.scaffold_inline_form_models(form_class) return form_class def scaffold_list_form(self, custom_fieldlist=ListEditableFieldList, validators=None): """ Create form for the `index_view` using only the columns from `self.column_editable_list`. :param validators: `form_args` dict with only validators {'name': {'validators': [required()]}} :param custom_fieldlist: A WTForm FieldList class. By default, `ListEditableFieldList`. """ converter = self.model_form_converter(self.session, self) form_class = form.get_form(self.model, converter, base_class=self.form_base_class, only=self.column_editable_list, field_args=validators) return wrap_fields_in_fieldlist(self.form_base_class, form_class, custom_fieldlist) def scaffold_inline_form_models(self, form_class): """ Contribute inline models to the form :param form_class: Form class """ inline_converter = self.inline_model_form_converter(self.session, self, self.model_form_converter) for m in self.inline_models: form_class = inline_converter.contribute(self.model, form_class, m) return form_class def scaffold_auto_joins(self): """ Return a list of joined tables by going through the displayed columns. """ if not self.column_auto_select_related: return [] relations = set() for p in self._get_model_iterator(): if hasattr(p, 'direction'): # Check if it is pointing to same model if p.mapper.class_ == self.model: continue if p.direction.name in ['MANYTOONE', 'MANYTOMANY']: relations.add(p.key) joined = [] for prop, name in self._list_columns: if prop in relations: joined.append(getattr(self.model, prop)) return joined # AJAX foreignkey support def _create_ajax_loader(self, name, options): return create_ajax_loader(self.model, self.session, name, name, options) # Database-related API def get_query(self): """ Return a query for the model type. If you override this method, don't forget to override `get_count_query` as well. This method can be used to set a "persistent filter" on an index_view. Example:: class MyView(ModelView): def get_query(self): return super(MyView, self).get_query().filter(User.username == current_user.username) """ return self.session.query(self.model) def get_count_query(self): """ Return a the count query for the model type A query(self.model).count() approach produces an excessive subquery, so query(func.count('*')) should be used instead. See #45a2723 commit message for details. """ return self.session.query(func.count('*')).select_from(self.model) def _order_by(self, query, joins, sort_joins, sort_field, sort_desc): """ Apply order_by to the query :param query: Query :param joins: Joins set :param sort_field: Sort field :param sort_desc: Ascending or descending """ # TODO: Preprocessing for joins # Handle joins if sort_joins: for table in sort_joins: if table.name not in joins: query = query.outerjoin(table) joins.add(table.name) if sort_field is not None: if sort_desc: query = query.order_by(desc(sort_field)) else: query = query.order_by(sort_field) return query, joins def _get_default_order(self): order = super(ModelView, self)._get_default_order() if order is not None: field, direction = order join_tables, attr = self._get_field_with_path(field) return join_tables, attr, direction return None def get_list(self, page, sort_column, sort_desc, search, filters, execute=True): """ Return models from the database. :param page: Page number :param sort_column: Sort column name :param sort_desc: Descending or ascending sort :param search: Search query :param execute: Execute query immediately? Default is `True` :param filters: List of filter tuples """ # Will contain names of joined tables to avoid duplicate joins joins = set() query = self.get_query() count_query = self.get_count_query() # Ignore eager-loaded relations (prevent unnecessary joins) # TODO: Separate join detection for query and count query? if hasattr(query, '_join_entities'): for entity in query._join_entities: for table in entity.tables: joins.add(table.name) # Apply search criteria if self._search_supported and search: # Apply search-related joins if self._search_joins: for table in self._search_joins: if table.name not in joins: query = query.outerjoin(table) count_query = count_query.outerjoin(table) joins.add(table.name) # Apply terms terms = search.split(' ') for term in terms: if not term: continue stmt = tools.parse_like_term(term) filter_stmt = [c.ilike(stmt) for c in self._search_fields] query = query.filter(or_(*filter_stmt)) count_query = count_query.filter(or_(*filter_stmt)) # Apply filters if filters and self._filters: for idx, flt_name, value in filters: flt = self._filters[idx] # Figure out joins tbl = flt.column.table.name join_tables = self._filter_joins.get(tbl, []) for table in join_tables: if table.name not in joins: query = query.join(table) count_query = count_query.join(table) joins.add(table.name) # turn into python format with .clean() and apply filter query = flt.apply(query, flt.clean(value)) count_query = flt.apply(count_query, flt.clean(value)) # Calculate number of rows count = count_query.scalar() # Auto join for j in self._auto_joins: query = query.options(joinedload(j)) # Sorting if sort_column is not None: if sort_column in self._sortable_columns: sort_field = self._sortable_columns[sort_column] sort_joins = self._sortable_joins.get(sort_column) query, joins = self._order_by(query, joins, sort_joins, sort_field, sort_desc) else: order = self._get_default_order() if order: sort_joins, sort_field, sort_desc = order query, joins = self._order_by(query, joins, sort_joins, sort_field, sort_desc) # Pagination if page is not None: query = query.offset(page * self.page_size) query = query.limit(self.page_size) # Execute if needed if execute: query = query.all() return count, query def get_one(self, id): """ Return a single model by its id. :param id: Model id """ return self.session.query(self.model).get(tools.iterdecode(id)) # Error handler def handle_view_exception(self, exc): if isinstance(exc, IntegrityError): flash(gettext('Integrity error. %(message)s', message=exc.message), 'error') return True return super(ModelView, self).handle_view_exception(exc) # Model handlers def create_model(self, form): """ Create model from form. :param form: Form instance """ try: model = self.model() form.populate_obj(model) self.session.add(model) self._on_model_change(form, model, True) self.session.commit() except Exception as ex: if not self.handle_view_exception(ex): flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error') log.exception('Failed to create record.') self.session.rollback() return False else: self.after_model_change(form, model, True) return True def update_model(self, form, model): """ Update model from form. :param form: Form instance :param model: Model instance """ try: form.populate_obj(model) self._on_model_change(form, model, False) self.session.commit() except Exception as ex: if not self.handle_view_exception(ex): flash(gettext('Failed to update record. %(error)s', error=str(ex)), 'error') log.exception('Failed to update record.') self.session.rollback() return False else: self.after_model_change(form, model, False) return True def delete_model(self, model): """ Delete model. :param model: Model to delete """ try: self.on_model_delete(model) self.session.flush() self.session.delete(model) self.session.commit() return True except Exception as ex: if not self.handle_view_exception(ex): flash(gettext('Failed to delete record. %(error)s', error=str(ex)), 'error') log.exception('Failed to delete record.') self.session.rollback() return False # Default model actions def is_action_allowed(self, name): # Check delete action permission if name == 'delete' and not self.can_delete: return False return super(ModelView, self).is_action_allowed(name) @action('delete', lazy_gettext('Delete'), lazy_gettext('Are you sure you want to delete selected records?')) def action_delete(self, ids): try: query = get_query_for_ids(self.get_query(), self.model, ids) if self.fast_mass_delete: count = query.delete(synchronize_session=False) else: count = 0 for m in query.all(): if self.delete_model(m): count += 1 self.session.commit() flash(ngettext('Record was successfully deleted.', '%(count)s records were successfully deleted.', count, count=count)) except Exception as ex: if not self.handle_view_exception(ex): raise flash(gettext('Failed to delete records. %(error)s', error=str(ex)), 'error')
# Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime import time from glanceclient import client as glance_client from glanceclient import exc as glance_exc import mock from oslo_config import cfg from oslo_serialization import jsonutils from oslo_utils import uuidutils from six.moves.urllib import parse as urlparse import testtools from ironic.common import context from ironic.common import exception from ironic.common.glance_service import base_image_service from ironic.common.glance_service import service_utils from ironic.common.glance_service.v2 import image_service as glance_v2 from ironic.common import image_service as service from ironic.tests import base from ironic.tests.unit import stubs CONF = cfg.CONF class NullWriter(object): """Used to test ImageService.get which takes a writer object.""" def write(self, *arg, **kwargs): pass class TestGlanceSerializer(testtools.TestCase): def test_serialize(self): metadata = {'name': 'image1', 'is_public': True, 'foo': 'bar', 'properties': { 'prop1': 'propvalue1', 'mappings': [ {'virtual': 'aaa', 'device': 'bbb'}, {'virtual': 'xxx', 'device': 'yyy'}], 'block_device_mapping': [ {'virtual_device': 'fake', 'device_name': '/dev/fake'}, {'virtual_device': 'ephemeral0', 'device_name': '/dev/fake0'}]}} converted_expected = { 'name': 'image1', 'is_public': True, 'foo': 'bar', 'properties': {'prop1': 'propvalue1'} } converted = service_utils._convert(metadata, 'to') self.assertEqual(metadata, service_utils._convert(converted, 'from')) # Fields that rely on dict ordering can't be compared as text mappings = jsonutils.loads(converted['properties'] .pop('mappings')) self.assertEqual([{"device": "bbb", "virtual": "aaa"}, {"device": "yyy", "virtual": "xxx"}], mappings) bd_mapping = jsonutils.loads(converted['properties'] .pop('block_device_mapping')) self.assertEqual([{"virtual_device": "fake", "device_name": "/dev/fake"}, {"virtual_device": "ephemeral0", "device_name": "/dev/fake0"}], bd_mapping) # Compare the remaining self.assertEqual(converted_expected, converted) class TestGlanceImageService(base.TestCase): NOW_GLANCE_OLD_FORMAT = "2010-10-11T10:30:22" NOW_GLANCE_FORMAT = "2010-10-11T10:30:22.000000" NOW_DATETIME = datetime.datetime(2010, 10, 11, 10, 30, 22) def setUp(self): super(TestGlanceImageService, self).setUp() client = stubs.StubGlanceClient() self.context = context.RequestContext(auth_token=True) self.context.user_id = 'fake' self.context.project_id = 'fake' self.service = service.GlanceImageService(client, 1, self.context) self.config(glance_host='localhost', group='glance') try: self.config(auth_strategy='keystone', group='glance') except Exception: opts = [ cfg.StrOpt('auth_strategy', default='keystone'), ] CONF.register_opts(opts) return @staticmethod def _make_fixture(**kwargs): fixture = {'name': None, 'properties': {}, 'status': None, 'is_public': None} fixture.update(kwargs) return fixture @property def endpoint(self): # For glanceclient versions >= 0.13, the endpoint is located # under http_client (blueprint common-client-library-2) # I5addc38eb2e2dd0be91b566fda7c0d81787ffa75 # Test both options to keep backward compatibility if getattr(self.service.client, 'endpoint', None): endpoint = self.service.client.endpoint else: endpoint = self.service.client.http_client.endpoint return endpoint def _make_datetime_fixture(self): return self._make_fixture(created_at=self.NOW_GLANCE_FORMAT, updated_at=self.NOW_GLANCE_FORMAT, deleted_at=self.NOW_GLANCE_FORMAT) def test_create_with_instance_id(self): # Ensure instance_id is persisted as an image-property. fixture = {'name': 'test image', 'is_public': False, 'properties': {'instance_id': '42', 'user_id': 'fake'}} image_id = self.service.create(fixture)['id'] image_meta = self.service.show(image_id) expected = { 'id': image_id, 'name': 'test image', 'is_public': False, 'size': None, 'min_disk': None, 'min_ram': None, 'disk_format': None, 'container_format': None, 'checksum': None, 'created_at': self.NOW_DATETIME, 'updated_at': self.NOW_DATETIME, 'deleted_at': None, 'deleted': None, 'status': None, 'properties': {'instance_id': '42', 'user_id': 'fake'}, 'owner': None, } self.assertDictEqual(expected, image_meta) image_metas = self.service.detail() self.assertDictEqual(expected, image_metas[0]) def test_create_without_instance_id(self): """Test creating an image without an instance ID. Ensure we can create an image without having to specify an instance_id. Public images are an example of an image not tied to an instance. """ fixture = {'name': 'test image', 'is_public': False} image_id = self.service.create(fixture)['id'] expected = { 'id': image_id, 'name': 'test image', 'is_public': False, 'size': None, 'min_disk': None, 'min_ram': None, 'disk_format': None, 'container_format': None, 'checksum': None, 'created_at': self.NOW_DATETIME, 'updated_at': self.NOW_DATETIME, 'deleted_at': None, 'deleted': None, 'status': None, 'properties': {}, 'owner': None, } actual = self.service.show(image_id) self.assertDictEqual(expected, actual) def test_create(self): fixture = self._make_fixture(name='test image') num_images = len(self.service.detail()) image_id = self.service.create(fixture)['id'] self.assertIsNotNone(image_id) self.assertEqual( num_images + 1, len(self.service.detail())) def test_create_and_show_non_existing_image(self): fixture = self._make_fixture(name='test image') image_id = self.service.create(fixture)['id'] self.assertIsNotNone(image_id) self.assertRaises(exception.ImageNotFound, self.service.show, 'bad image id') def test_detail_private_image(self): fixture = self._make_fixture(name='test image') fixture['is_public'] = False properties = {'owner_id': 'proj1'} fixture['properties'] = properties self.service.create(fixture)['id'] proj = self.context.project_id self.context.project_id = 'proj1' image_metas = self.service.detail() self.context.project_id = proj self.assertEqual(1, len(image_metas)) self.assertEqual('test image', image_metas[0]['name']) self.assertFalse(image_metas[0]['is_public']) def test_detail_marker(self): fixtures = [] ids = [] for i in range(10): fixture = self._make_fixture(name='TestImage %d' % (i)) fixtures.append(fixture) ids.append(self.service.create(fixture)['id']) image_metas = self.service.detail(marker=ids[1]) self.assertEqual(8, len(image_metas)) i = 2 for meta in image_metas: expected = { 'id': ids[i], 'status': None, 'is_public': None, 'name': 'TestImage %d' % (i), 'properties': {}, 'size': None, 'min_disk': None, 'min_ram': None, 'disk_format': None, 'container_format': None, 'checksum': None, 'created_at': self.NOW_DATETIME, 'updated_at': self.NOW_DATETIME, 'deleted_at': None, 'deleted': None, 'owner': None, } self.assertDictEqual(expected, meta) i = i + 1 def test_detail_limit(self): fixtures = [] ids = [] for i in range(10): fixture = self._make_fixture(name='TestImage %d' % (i)) fixtures.append(fixture) ids.append(self.service.create(fixture)['id']) image_metas = self.service.detail(limit=5) self.assertEqual(5, len(image_metas)) def test_detail_default_limit(self): fixtures = [] ids = [] for i in range(10): fixture = self._make_fixture(name='TestImage %d' % (i)) fixtures.append(fixture) ids.append(self.service.create(fixture)['id']) image_metas = self.service.detail() for i, meta in enumerate(image_metas): self.assertEqual(meta['name'], 'TestImage %d' % (i)) def test_detail_marker_and_limit(self): fixtures = [] ids = [] for i in range(10): fixture = self._make_fixture(name='TestImage %d' % (i)) fixtures.append(fixture) ids.append(self.service.create(fixture)['id']) image_metas = self.service.detail(marker=ids[3], limit=5) self.assertEqual(5, len(image_metas)) i = 4 for meta in image_metas: expected = { 'id': ids[i], 'status': None, 'is_public': None, 'name': 'TestImage %d' % (i), 'properties': {}, 'size': None, 'min_disk': None, 'min_ram': None, 'disk_format': None, 'container_format': None, 'checksum': None, 'created_at': self.NOW_DATETIME, 'updated_at': self.NOW_DATETIME, 'deleted_at': None, 'deleted': None, 'owner': None, } self.assertDictEqual(expected, meta) i = i + 1 def test_detail_invalid_marker(self): fixtures = [] ids = [] for i in range(10): fixture = self._make_fixture(name='TestImage %d' % (i)) fixtures.append(fixture) ids.append(self.service.create(fixture)['id']) self.assertRaises(exception.Invalid, self.service.detail, marker='invalidmarker') def test_update(self): fixture = self._make_fixture(name='test image') image = self.service.create(fixture) image_id = image['id'] fixture['name'] = 'new image name' self.service.update(image_id, fixture) new_image_data = self.service.show(image_id) self.assertEqual('new image name', new_image_data['name']) def test_delete(self): fixture1 = self._make_fixture(name='test image 1') fixture2 = self._make_fixture(name='test image 2') fixtures = [fixture1, fixture2] num_images = len(self.service.detail()) self.assertEqual(0, num_images) ids = [] for fixture in fixtures: new_id = self.service.create(fixture)['id'] ids.append(new_id) num_images = len(self.service.detail()) self.assertEqual(2, num_images) self.service.delete(ids[0]) # When you delete an image from glance, it sets the status to DELETED # and doesn't actually remove the image. # Check the image is still there. num_images = len(self.service.detail()) self.assertEqual(2, num_images) # Check the image is marked as deleted. num_images = len([x for x in self.service.detail() if not x['deleted']]) self.assertEqual(1, num_images) def test_show_passes_through_to_client(self): fixture = self._make_fixture(name='image1', is_public=True) image_id = self.service.create(fixture)['id'] image_meta = self.service.show(image_id) expected = { 'id': image_id, 'name': 'image1', 'is_public': True, 'size': None, 'min_disk': None, 'min_ram': None, 'disk_format': None, 'container_format': None, 'checksum': None, 'created_at': self.NOW_DATETIME, 'updated_at': self.NOW_DATETIME, 'deleted_at': None, 'deleted': None, 'status': None, 'properties': {}, 'owner': None, } self.assertEqual(expected, image_meta) def test_show_raises_when_no_authtoken_in_the_context(self): fixture = self._make_fixture(name='image1', is_public=False, properties={'one': 'two'}) image_id = self.service.create(fixture)['id'] self.context.auth_token = False self.assertRaises(exception.ImageNotFound, self.service.show, image_id) def test_detail_passes_through_to_client(self): fixture = self._make_fixture(name='image10', is_public=True) image_id = self.service.create(fixture)['id'] image_metas = self.service.detail() expected = [ { 'id': image_id, 'name': 'image10', 'is_public': True, 'size': None, 'min_disk': None, 'min_ram': None, 'disk_format': None, 'container_format': None, 'checksum': None, 'created_at': self.NOW_DATETIME, 'updated_at': self.NOW_DATETIME, 'deleted_at': None, 'deleted': None, 'status': None, 'properties': {}, 'owner': None, }, ] self.assertEqual(expected, image_metas) def test_show_makes_datetimes(self): fixture = self._make_datetime_fixture() image_id = self.service.create(fixture)['id'] image_meta = self.service.show(image_id) self.assertEqual(self.NOW_DATETIME, image_meta['created_at']) self.assertEqual(self.NOW_DATETIME, image_meta['updated_at']) def test_detail_makes_datetimes(self): fixture = self._make_datetime_fixture() self.service.create(fixture) image_meta = self.service.detail()[0] self.assertEqual(self.NOW_DATETIME, image_meta['created_at']) self.assertEqual(self.NOW_DATETIME, image_meta['updated_at']) @mock.patch.object(time, 'sleep', autospec=True) def test_download_with_retries(self, mock_sleep): tries = [0] class MyGlanceStubClient(stubs.StubGlanceClient): """A client that fails the first time, then succeeds.""" def get(self, image_id): if tries[0] == 0: tries[0] = 1 raise glance_exc.ServiceUnavailable('') else: return {} stub_client = MyGlanceStubClient() stub_context = context.RequestContext(auth_token=True) stub_context.user_id = 'fake' stub_context.project_id = 'fake' stub_service = service.GlanceImageService(stub_client, 1, stub_context) image_id = 1 # doesn't matter writer = NullWriter() # When retries are disabled, we should get an exception self.config(glance_num_retries=0, group='glance') self.assertRaises(exception.GlanceConnectionFailed, stub_service.download, image_id, writer) # Now lets enable retries. No exception should happen now. tries = [0] self.config(glance_num_retries=1, group='glance') stub_service.download(image_id, writer) self.assertTrue(mock_sleep.called) @mock.patch('sendfile.sendfile', autospec=True) @mock.patch('os.path.getsize', autospec=True) @mock.patch('%s.open' % __name__, new=mock.mock_open(), create=True) def test_download_file_url(self, mock_getsize, mock_sendfile): # NOTE: only in v2 API class MyGlanceStubClient(stubs.StubGlanceClient): """A client that returns a file url.""" s_tmpfname = '/whatever/source' def get(self, image_id): return type('GlanceTestDirectUrlMeta', (object,), {'direct_url': 'file://%s' + self.s_tmpfname}) stub_context = context.RequestContext(auth_token=True) stub_context.user_id = 'fake' stub_context.project_id = 'fake' stub_client = MyGlanceStubClient() stub_service = service.GlanceImageService(stub_client, context=stub_context, version=2) image_id = 1 # doesn't matter self.config(allowed_direct_url_schemes=['file'], group='glance') # patching open in base_image_service module namespace # to make call-spec assertions with mock.patch('ironic.common.glance_service.base_image_service.open', new=mock.mock_open(), create=True) as mock_ironic_open: with open('/whatever/target', 'w') as mock_target_fd: stub_service.download(image_id, mock_target_fd) # assert the image data was neither read nor written # but rather sendfiled mock_ironic_open.assert_called_once_with(MyGlanceStubClient.s_tmpfname, 'r') mock_source_fd = mock_ironic_open() self.assertFalse(mock_source_fd.read.called) self.assertFalse(mock_target_fd.write.called) mock_sendfile.assert_called_once_with( mock_target_fd.fileno(), mock_source_fd.fileno(), 0, mock_getsize(MyGlanceStubClient.s_tmpfname)) def test_client_forbidden_converts_to_imagenotauthed(self): class MyGlanceStubClient(stubs.StubGlanceClient): """A client that raises a Forbidden exception.""" def get(self, image_id): raise glance_exc.Forbidden(image_id) stub_client = MyGlanceStubClient() stub_context = context.RequestContext(auth_token=True) stub_context.user_id = 'fake' stub_context.project_id = 'fake' stub_service = service.GlanceImageService(stub_client, 1, stub_context) image_id = 1 # doesn't matter writer = NullWriter() self.assertRaises(exception.ImageNotAuthorized, stub_service.download, image_id, writer) def test_client_httpforbidden_converts_to_imagenotauthed(self): class MyGlanceStubClient(stubs.StubGlanceClient): """A client that raises a HTTPForbidden exception.""" def get(self, image_id): raise glance_exc.HTTPForbidden(image_id) stub_client = MyGlanceStubClient() stub_context = context.RequestContext(auth_token=True) stub_context.user_id = 'fake' stub_context.project_id = 'fake' stub_service = service.GlanceImageService(stub_client, 1, stub_context) image_id = 1 # doesn't matter writer = NullWriter() self.assertRaises(exception.ImageNotAuthorized, stub_service.download, image_id, writer) def test_client_notfound_converts_to_imagenotfound(self): class MyGlanceStubClient(stubs.StubGlanceClient): """A client that raises a NotFound exception.""" def get(self, image_id): raise glance_exc.NotFound(image_id) stub_client = MyGlanceStubClient() stub_context = context.RequestContext(auth_token=True) stub_context.user_id = 'fake' stub_context.project_id = 'fake' stub_service = service.GlanceImageService(stub_client, 1, stub_context) image_id = 1 # doesn't matter writer = NullWriter() self.assertRaises(exception.ImageNotFound, stub_service.download, image_id, writer) def test_client_httpnotfound_converts_to_imagenotfound(self): class MyGlanceStubClient(stubs.StubGlanceClient): """A client that raises a HTTPNotFound exception.""" def get(self, image_id): raise glance_exc.HTTPNotFound(image_id) stub_client = MyGlanceStubClient() stub_context = context.RequestContext(auth_token=True) stub_context.user_id = 'fake' stub_context.project_id = 'fake' stub_service = service.GlanceImageService(stub_client, 1, stub_context) image_id = 1 # doesn't matter writer = NullWriter() self.assertRaises(exception.ImageNotFound, stub_service.download, image_id, writer) def test_check_image_service_client_set(self): def func(self): return True self.service.client = True wrapped_func = base_image_service.check_image_service(func) self.assertTrue(wrapped_func(self.service)) @mock.patch.object(glance_client, 'Client', autospec=True) def test_check_image_service__no_client_set_http(self, mock_gclient): def func(service, *args, **kwargs): return (self.endpoint, args, kwargs) endpoint = 'http://123.123.123.123:9292' mock_gclient.return_value.endpoint = endpoint self.service.client = None params = {'image_href': '%s/image_uuid' % endpoint} self.config(auth_strategy='keystone', group='glance') wrapped_func = base_image_service.check_image_service(func) self.assertEqual((endpoint, (), params), wrapped_func(self.service, **params)) mock_gclient.assert_called_once_with( 1, endpoint, **{'insecure': CONF.glance.glance_api_insecure, 'token': self.context.auth_token}) @mock.patch.object(glance_client, 'Client', autospec=True) def test_get_image_service__no_client_set_https_insecure(self, mock_gclient): def func(service, *args, **kwargs): return (self.endpoint, args, kwargs) endpoint = 'https://123.123.123.123:9292' mock_gclient.return_value.endpoint = endpoint self.service.client = None params = {'image_href': '%s/image_uuid' % endpoint} self.config(auth_strategy='keystone', group='glance') self.config(glance_api_insecure=True, group='glance') wrapped_func = base_image_service.check_image_service(func) self.assertEqual((endpoint, (), params), wrapped_func(self.service, **params)) mock_gclient.assert_called_once_with( 1, endpoint, **{'insecure': CONF.glance.glance_api_insecure, 'token': self.context.auth_token}) @mock.patch.object(glance_client, 'Client', autospec=True) def test_get_image_service__no_client_set_https_secure(self, mock_gclient): def func(service, *args, **kwargs): return (self.endpoint, args, kwargs) endpoint = 'https://123.123.123.123:9292' mock_gclient.return_value.endpoint = endpoint self.service.client = None params = {'image_href': '%s/image_uuid' % endpoint} self.config(auth_strategy='keystone', group='glance') self.config(glance_api_insecure=False, group='glance') self.config(glance_cafile='/path/to/certfile', group='glance') wrapped_func = base_image_service.check_image_service(func) self.assertEqual((endpoint, (), params), wrapped_func(self.service, **params)) mock_gclient.assert_called_once_with( 1, endpoint, **{'cacert': CONF.glance.glance_cafile, 'insecure': CONF.glance.glance_api_insecure, 'token': self.context.auth_token}) def _create_failing_glance_client(info): class MyGlanceStubClient(stubs.StubGlanceClient): """A client that fails the first time, then succeeds.""" def get(self, image_id): info['num_calls'] += 1 if info['num_calls'] == 1: raise glance_exc.ServiceUnavailable('') return {} return MyGlanceStubClient() class TestGlanceSwiftTempURL(base.TestCase): def setUp(self): super(TestGlanceSwiftTempURL, self).setUp() client = stubs.StubGlanceClient() self.context = context.RequestContext() self.context.auth_token = 'fake' self.service = service.GlanceImageService(client, 2, self.context) self.config(swift_temp_url_key='correcthorsebatterystaple', group='glance') self.config(swift_endpoint_url='https://swift.example.com', group='glance') self.config(swift_account='AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30', group='glance') self.config(swift_api_version='v1', group='glance') self.config(swift_container='glance', group='glance') self.config(swift_temp_url_duration=1200, group='glance') self.config(swift_store_multiple_containers_seed=0, group='glance') self.config() self.fake_image = { 'id': '757274c4-2856-4bd2-bb20-9a4a231e187b' } @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_swift_temp_url(self, tempurl_mock): path = ('/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30' '/glance' '/757274c4-2856-4bd2-bb20-9a4a231e187b') tempurl_mock.return_value = ( path + '?temp_url_sig=hmacsig&temp_url_expires=1400001200') self.service._validate_temp_url_config = mock.Mock() temp_url = self.service.swift_temp_url(image_info=self.fake_image) self.assertEqual(CONF.glance.swift_endpoint_url + tempurl_mock.return_value, temp_url) tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_swift_temp_url_invalid_image_info(self, tempurl_mock): self.service._validate_temp_url_config = mock.Mock() image_info = {} self.assertRaises(exception.ImageUnacceptable, self.service.swift_temp_url, image_info) image_info = {'id': 'not an id'} self.assertRaises(exception.ImageUnacceptable, self.service.swift_temp_url, image_info) self.assertFalse(tempurl_mock.called) @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_swift_temp_url_radosgw(self, tempurl_mock): self.config(temp_url_endpoint_type='radosgw', group='glance') path = ('/v1' '/glance' '/757274c4-2856-4bd2-bb20-9a4a231e187b') tempurl_mock.return_value = ( path + '?temp_url_sig=hmacsig&temp_url_expires=1400001200') self.service._validate_temp_url_config = mock.Mock() temp_url = self.service.swift_temp_url(image_info=self.fake_image) self.assertEqual( (urlparse.urljoin(CONF.glance.swift_endpoint_url, 'swift') + tempurl_mock.return_value), temp_url) tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_swift_temp_url_radosgw_endpoint_with_swift(self, tempurl_mock): self.config(swift_endpoint_url='https://swift.radosgw.com/swift', group='glance') self.config(temp_url_endpoint_type='radosgw', group='glance') path = ('/v1' '/glance' '/757274c4-2856-4bd2-bb20-9a4a231e187b') tempurl_mock.return_value = ( path + '?temp_url_sig=hmacsig&temp_url_expires=1400001200') self.service._validate_temp_url_config = mock.Mock() temp_url = self.service.swift_temp_url(image_info=self.fake_image) self.assertEqual( CONF.glance.swift_endpoint_url + tempurl_mock.return_value, temp_url) tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_swift_temp_url_radosgw_endpoint_invalid(self, tempurl_mock): self.config(swift_endpoint_url='https://swift.radosgw.com/eggs/', group='glance') self.config(temp_url_endpoint_type='radosgw', group='glance') self.service._validate_temp_url_config = mock.Mock() self.assertRaises(exception.InvalidParameterValue, self.service.swift_temp_url, self.fake_image) self.assertFalse(tempurl_mock.called) @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_swift_temp_url_multiple_containers(self, tempurl_mock): self.config(swift_store_multiple_containers_seed=8, group='glance') path = ('/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30' '/glance_757274c4' '/757274c4-2856-4bd2-bb20-9a4a231e187b') tempurl_mock.return_value = ( path + '?temp_url_sig=hmacsig&temp_url_expires=1400001200') self.service._validate_temp_url_config = mock.Mock() temp_url = self.service.swift_temp_url(image_info=self.fake_image) self.assertEqual(CONF.glance.swift_endpoint_url + tempurl_mock.return_value, temp_url) tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') def test_swift_temp_url_url_bad_no_info(self): self.assertRaises(exception.ImageUnacceptable, self.service.swift_temp_url, image_info={}) def test__validate_temp_url_config(self): self.service._validate_temp_url_config() def test__validate_temp_url_key_exception(self): self.config(swift_temp_url_key=None, group='glance') self.assertRaises(exception.MissingParameterValue, self.service._validate_temp_url_config) def test__validate_temp_url_endpoint_config_exception(self): self.config(swift_endpoint_url=None, group='glance') self.assertRaises(exception.MissingParameterValue, self.service._validate_temp_url_config) def test__validate_temp_url_account_exception(self): self.config(swift_account=None, group='glance') self.assertRaises(exception.MissingParameterValue, self.service._validate_temp_url_config) def test__validate_temp_url_no_account_exception_radosgw(self): self.config(swift_account=None, group='glance') self.config(temp_url_endpoint_type='radosgw', group='glance') self.service._validate_temp_url_config() def test__validate_temp_url_endpoint_less_than_download_delay(self): self.config(swift_temp_url_expected_download_start_delay=1000, group='glance') self.config(swift_temp_url_duration=15, group='glance') self.assertRaises(exception.InvalidParameterValue, self.service._validate_temp_url_config) def test__validate_temp_url_multiple_containers(self): self.config(swift_store_multiple_containers_seed=-1, group='glance') self.assertRaises(exception.InvalidParameterValue, self.service._validate_temp_url_config) self.config(swift_store_multiple_containers_seed=None, group='glance') self.assertRaises(exception.InvalidParameterValue, self.service._validate_temp_url_config) self.config(swift_store_multiple_containers_seed=33, group='glance') self.assertRaises(exception.InvalidParameterValue, self.service._validate_temp_url_config) class TestSwiftTempUrlCache(base.TestCase): def setUp(self): super(TestSwiftTempUrlCache, self).setUp() client = stubs.StubGlanceClient() self.context = context.RequestContext() self.context.auth_token = 'fake' self.config(swift_temp_url_expected_download_start_delay=100, group='glance') self.config(swift_temp_url_key='correcthorsebatterystaple', group='glance') self.config(swift_endpoint_url='https://swift.example.com', group='glance') self.config(swift_account='AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30', group='glance') self.config(swift_api_version='v1', group='glance') self.config(swift_container='glance', group='glance') self.config(swift_temp_url_duration=1200, group='glance') self.config(swift_temp_url_cache_enabled=True, group='glance') self.config(swift_store_multiple_containers_seed=0, group='glance') self.glance_service = service.GlanceImageService(client, version=2, context=self.context) @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_add_items_to_cache(self, tempurl_mock): fake_image = { 'id': uuidutils.generate_uuid() } path = ('/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30' '/glance' '/%s' % fake_image['id']) exp_time = int(time.time()) + 1200 tempurl_mock.return_value = ( path + '?temp_url_sig=hmacsig&temp_url_expires=%s' % exp_time) cleanup_mock = mock.Mock() self.glance_service._remove_expired_items_from_cache = cleanup_mock self.glance_service._validate_temp_url_config = mock.Mock() temp_url = self.glance_service.swift_temp_url( image_info=fake_image) self.assertEqual(CONF.glance.swift_endpoint_url + tempurl_mock.return_value, temp_url) cleanup_mock.assert_called_once_with() tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') self.assertEqual((temp_url, exp_time), self.glance_service._cache[fake_image['id']]) @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_return_cached_tempurl(self, tempurl_mock): fake_image = { 'id': uuidutils.generate_uuid() } exp_time = int(time.time()) + 1200 temp_url = CONF.glance.swift_endpoint_url + ( '/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30' '/glance' '/%(uuid)s' '?temp_url_sig=hmacsig&temp_url_expires=%(exp_time)s' % {'uuid': fake_image['id'], 'exp_time': exp_time} ) self.glance_service._cache[fake_image['id']] = ( glance_v2.TempUrlCacheElement(url=temp_url, url_expires_at=exp_time) ) cleanup_mock = mock.Mock() self.glance_service._remove_expired_items_from_cache = cleanup_mock self.glance_service._validate_temp_url_config = mock.Mock() self.assertEqual( temp_url, self.glance_service.swift_temp_url(image_info=fake_image) ) cleanup_mock.assert_called_once_with() self.assertFalse(tempurl_mock.called) @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def test_do_not_return_expired_tempurls(self, tempurl_mock): fake_image = { 'id': uuidutils.generate_uuid() } old_exp_time = int(time.time()) + 99 path = ( '/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30' '/glance' '/%s' % fake_image['id'] ) query = '?temp_url_sig=hmacsig&temp_url_expires=%s' self.glance_service._cache[fake_image['id']] = ( glance_v2.TempUrlCacheElement( url=(CONF.glance.swift_endpoint_url + path + query % old_exp_time), url_expires_at=old_exp_time) ) new_exp_time = int(time.time()) + 1200 tempurl_mock.return_value = ( path + query % new_exp_time) self.glance_service._validate_temp_url_config = mock.Mock() fresh_temp_url = self.glance_service.swift_temp_url( image_info=fake_image) self.assertEqual(CONF.glance.swift_endpoint_url + tempurl_mock.return_value, fresh_temp_url) tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') self.assertEqual( (fresh_temp_url, new_exp_time), self.glance_service._cache[fake_image['id']]) def test_remove_expired_items_from_cache(self): expired_items = { uuidutils.generate_uuid(): glance_v2.TempUrlCacheElement( 'fake-url-1', int(time.time()) - 10 ), uuidutils.generate_uuid(): glance_v2.TempUrlCacheElement( 'fake-url-2', int(time.time()) + 90 # Agent won't be able to start in time ) } valid_items = { uuidutils.generate_uuid(): glance_v2.TempUrlCacheElement( 'fake-url-3', int(time.time()) + 1000 ), uuidutils.generate_uuid(): glance_v2.TempUrlCacheElement( 'fake-url-4', int(time.time()) + 2000 ) } self.glance_service._cache.update(expired_items) self.glance_service._cache.update(valid_items) self.glance_service._remove_expired_items_from_cache() for uuid in valid_items: self.assertEqual(valid_items[uuid], self.glance_service._cache[uuid]) for uuid in expired_items: self.assertNotIn(uuid, self.glance_service._cache) @mock.patch('swiftclient.utils.generate_temp_url', autospec=True) def _test__generate_temp_url(self, fake_image, tempurl_mock): path = ('/v1/AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30' '/glance' '/%s' % fake_image['id']) tempurl_mock.return_value = ( path + '?temp_url_sig=hmacsig&temp_url_expires=1400001200') self.glance_service._validate_temp_url_config = mock.Mock() temp_url = self.glance_service._generate_temp_url( path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET', endpoint=CONF.glance.swift_endpoint_url, image_id=fake_image['id'] ) self.assertEqual(CONF.glance.swift_endpoint_url + tempurl_mock.return_value, temp_url) tempurl_mock.assert_called_with( path=path, seconds=CONF.glance.swift_temp_url_duration, key=CONF.glance.swift_temp_url_key, method='GET') def test_swift_temp_url_cache_enabled(self): fake_image = { 'id': uuidutils.generate_uuid() } rm_expired = mock.Mock() self.glance_service._remove_expired_items_from_cache = rm_expired self._test__generate_temp_url(fake_image) rm_expired.assert_called_once_with() self.assertIn(fake_image['id'], self.glance_service._cache) def test_swift_temp_url_cache_disabled(self): self.config(swift_temp_url_cache_enabled=False, group='glance') fake_image = { 'id': uuidutils.generate_uuid() } rm_expired = mock.Mock() self.glance_service._remove_expired_items_from_cache = rm_expired self._test__generate_temp_url(fake_image) self.assertFalse(rm_expired.called) self.assertNotIn(fake_image['id'], self.glance_service._cache) class TestGlanceUrl(base.TestCase): def test_generate_glance_http_url(self): self.config(glance_host="127.0.0.1", group='glance') generated_url = service_utils.generate_glance_url() http_url = "http://%s:%d" % (CONF.glance.glance_host, CONF.glance.glance_port) self.assertEqual(http_url, generated_url) def test_generate_glance_https_url(self): self.config(glance_protocol="https", group='glance') self.config(glance_host="127.0.0.1", group='glance') generated_url = service_utils.generate_glance_url() https_url = "https://%s:%d" % (CONF.glance.glance_host, CONF.glance.glance_port) self.assertEqual(https_url, generated_url) class TestServiceUtils(base.TestCase): def test_parse_image_ref_no_ssl(self): image_href = u'http://127.0.0.1:9292/image_path/'\ u'image_\u00F9\u00FA\u00EE\u0111' parsed_href = service_utils.parse_image_ref(image_href) self.assertEqual((u'image_\u00F9\u00FA\u00EE\u0111', '127.0.0.1', 9292, False), parsed_href) def test_parse_image_ref_ssl(self): image_href = 'https://127.0.0.1:9292/image_path/'\ u'image_\u00F9\u00FA\u00EE\u0111' parsed_href = service_utils.parse_image_ref(image_href) self.assertEqual((u'image_\u00F9\u00FA\u00EE\u0111', '127.0.0.1', 9292, True), parsed_href) def test_generate_image_url(self): image_href = u'image_\u00F9\u00FA\u00EE\u0111' self.config(glance_host='123.123.123.123', group='glance') self.config(glance_port=1234, group='glance') self.config(glance_protocol='https', group='glance') generated_url = service_utils.generate_image_url(image_href) self.assertEqual('https://123.123.123.123:1234/images/' u'image_\u00F9\u00FA\u00EE\u0111', generated_url) def test_is_glance_image(self): image_href = u'uui\u0111' self.assertFalse(service_utils.is_glance_image(image_href)) image_href = u'733d1c44-a2ea-414b-aca7-69decf20d810' self.assertTrue(service_utils.is_glance_image(image_href)) image_href = u'glance://uui\u0111' self.assertTrue(service_utils.is_glance_image(image_href)) image_href = 'http://aaa/bbb' self.assertFalse(service_utils.is_glance_image(image_href)) image_href = None self.assertFalse(service_utils.is_glance_image(image_href)) def test_is_image_href_ordinary_file_name_true(self): image = u"\u0111eploy.iso" result = service_utils.is_image_href_ordinary_file_name(image) self.assertTrue(result) def test_is_image_href_ordinary_file_name_false(self): for image in ('733d1c44-a2ea-414b-aca7-69decf20d810', u'glance://\u0111eploy_iso', u'http://\u0111eploy_iso', u'https://\u0111eploy_iso', u'file://\u0111eploy_iso',): result = service_utils.is_image_href_ordinary_file_name(image) self.assertFalse(result) class TestGlanceAPIServers(base.TestCase): def setUp(self): super(TestGlanceAPIServers, self).setUp() service_utils._GLANCE_API_SERVER = None def test__get_api_servers_default(self): host, port, use_ssl = service_utils._get_api_server() self.assertEqual(CONF.glance.glance_host, host) self.assertEqual(CONF.glance.glance_port, port) self.assertEqual(CONF.glance.glance_protocol == 'https', use_ssl) def test__get_api_servers_one(self): CONF.set_override('glance_api_servers', ['https://10.0.0.1:9293'], 'glance') s1 = service_utils._get_api_server() s2 = service_utils._get_api_server() self.assertEqual(('10.0.0.1', 9293, True), s1) # Only one server, should always get the same one self.assertEqual(s1, s2) def test__get_api_servers_two(self): CONF.set_override('glance_api_servers', ['http://10.0.0.1:9293', 'http://10.0.0.2:9294'], 'glance') s1 = service_utils._get_api_server() s2 = service_utils._get_api_server() s3 = service_utils._get_api_server() self.assertNotEqual(s1, s2) # 2 servers, so cycles to the first again self.assertEqual(s1, s3)
#! /usr/bin/env python #coding=utf-8 # This module is used to parse and create new style ini file. This # new style ini file format should like a very simple python program # but you can define section like normal ini file, for example: # # [default] # key = value # # Then the result should be ini.default.key1 = value1 # Whole ini file will be parsed into a dict-like object, but you can access # each section and key with '.', just like ini.section.key # For value can be simple python data type, such as: tuple, list, dict, int # float, string, etc. So it's very like a normal python file, but it's has # some sections definition. import sys, os import re import codecs import StringIO import locale import copy import tokenize import token from sorteddict import SortedDict from traceback import print_exc __all__ = ['SortedDict', 'Section', 'Ini', 'uni_prt'] try: set except: from sets import Set as set try: defaultencoding = locale.getdefaultlocale()[1] except: defaultencoding = None if not defaultencoding: defaultencoding = 'UTF-8' try: codecs.lookup(defaultencoding) except: defaultencoding = 'UTF-8' r_encoding = re.compile(r'\s*coding\s*[=:]\s*([-\w.]+)') r_var = re.compile(ur'(?<!\{)\{\{([^\{].*?)(?<!\})\}\}(?!\})', re.U) r_var_env = re.compile(ur'(?<!\{)\{\{([^\{].*?)(?<!\})\}\}(?!\})|(?:\$(\w[\d\w_]*)|\$\{(\w[\d\w_]*)\})', re.U) r_pre_var = re.compile(ur'#\{\w+\}', re.U) __default_env__ = {} def set_env(env=None): global __default_env__ __default_env__.update(env or {}) def merge_data(values, prev=None): if prev: _type = type(prev) for value in values: if not isinstance(value, (list, dict, set)): return values[-1] if prev and _type != type(value): raise ValueError("Value %r should be the same type as previous type %r" % (value, _type)) if not prev: prev = value _type = type(prev) continue if isinstance(value, list): for x in value: if x not in prev: prev.append(x) elif isinstance(value, dict): for k, v in value.items(): if k not in prev: prev[k] = v else: prev[k] = merge_data([v], prev[k]) else: prev.update(value) return prev def uni_prt(a, encoding='utf-8', beautiful=False, indent=0, convertors=None): convertors = convertors or {} escapechars = [("\\", "\\\\"), ("'", r"\'"), ('\"', r'\"'), ('\b', r'\b'), ('\t', r"\t"), ('\r', r"\r"), ('\n', r"\n")] s = [] indent_char = ' '*4 if isinstance(a, (list, tuple)): if isinstance(a, list): s.append(indent_char*indent + '[') else: s.append(indent_char*indent + '(') if beautiful: s.append('\n') for i, k in enumerate(a): if beautiful: ind = indent + 1 else: ind = indent s.append(indent_char*ind + uni_prt(k, encoding, beautiful, indent+1, convertors=convertors)) if i<len(a)-1: if beautiful: s.append(',\n') else: s.append(', ') if beautiful: s.append('\n') if isinstance(a, list): s.append(indent_char*indent + ']') else: if len(a) == 1: s.append(',') s.append(indent_char*indent + ')') elif isinstance(a, dict): s.append(indent_char*indent + '{') if beautiful: s.append('\n') for i, k in enumerate(a.items()): key, value = k if beautiful: ind = indent + 1 else: ind = indent s.append('%s: %s' % (indent_char*ind + uni_prt(key, encoding, beautiful, indent+1, convertors=convertors), uni_prt(value, encoding, beautiful, indent+1, convertors=convertors))) if i<len(a.items())-1: if beautiful: s.append(',\n') else: s.append(', ') if beautiful: s.append('\n') s.append(indent_char*indent + '}') elif isinstance(a, str): t = a for i in escapechars: t = t.replace(i[0], i[1]) s.append("'%s'" % t) elif isinstance(a, unicode): t = a for i in escapechars: t = t.replace(i[0], i[1]) try: s.append("u'%s'" % t.encode(encoding)) except: print_exc() else: _type = type(a) c_func = convertors.get(_type) if c_func: s.append(c_func(a)) else: s.append(str(a)) return ''.join(s) def eval_value(value, globals, locals, encoding, include_env): #process {{format}} def sub_(m): txt = filter(None, m.groups())[0].strip() try: v = eval_value(str(txt), globals, locals, encoding, include_env) _type = type(txt) if not isinstance(v, (str, unicode)): v = _type(v) elif not isinstance(v, _type): if _type is unicode: v = unicode(v, encoding) else: v = v.encode(encoding) except: print_exc() v = m.group() return v if isinstance(value, (str, unicode)): if include_env: v = r_var_env.sub(sub_, value) else: v = r_var.sub(sub_, value) else: v = value txt = '#coding=%s\n%s' % (encoding, v) result = eval(txt, dict(globals), dict(locals)) # if isinstance(result, (str, unicode)): # result = r_var.sub(sub_, result) return result class Empty(object): pass class EvalValue(object): def __init__(self, value, filename, lineno, line): self.value = value self.filename = filename self.lineno = lineno self.line = line def __str__(self): return self.value def __repr__(self): return self.__str__() class Lazy(object): """ Lazy class can be used to save multiple EvalValue or normal data type You can use add() funciton to add new value, it'll be sotred as a list, just like: [EvalValue, int, str] """ def __init__(self, key, globals, sec_name, encoding, include_env): self.key = key self.values = [] self.globals = globals self.sec_name = sec_name self.encoding = encoding self.cached_value = Empty self.include_env = include_env def eval(self, value): try: _locals = self.globals[self.sec_name] if not isinstance(_locals, SortedDict): _locals = {} v = eval_value(value, self.globals, _locals, self.encoding, self.include_env) return v except Exception as e: print_exc() raise Exception("Converting value (%s) error" % value) def add(self, value, replace=False): if not replace: self.values.append(value) else: self.values = [value] def get(self): if self.cached_value is Empty: result = [] for v in self.values: value = self.eval(v) if not isinstance(value, (list, dict, set)) and len(self.values)>1: self.cached_value = self.eval(self.values[-1]) break else: result.append(value) if result: self.cached_value = merge_data(result) #sync self.globals[self.sec_name][self.key] = self.cached_value return self.cached_value class RawValue(object): def __init__(self, filename, lineno, text, replace_flag=''): self.filename = filename self.lineno = lineno self.text = text self.replace_flag = replace_flag def __str__(self): _length = 26 if len(self.filename) > _length: s = self.filename.replace('\\', '/').split('/') t = -1 for i in range(len(s)-1, -1, -1): t = len(s[i]) + t + 1 if t > _length: break filename = '.../' + '/'.join(s[i+1:]) else: filename = self.filename.replace('\\', '/') return '%-30s:%04d' % (filename, self.lineno) def value(self): if self.replace_flag: op = ' <= ' else: op = ' = ' return "%s%s" % (op, self.text) class Section(SortedDict): def __init__(self, name, comments=None, encoding=None, root=None, info=None): super(Section, self).__init__() self._root = root self._name = name self.add_comment(comments=comments) self._field_comments = {} self._field_flag = {} self._encoding = encoding self._info = info #sync if self._root and self._lazy: # self._root._globals.setdefault(name, SortedDict()) self._root._globals[name] = SortedDict() @property def _lazy(self): if self._root: return self._root._lazy else: return False def add(self, key, value, comments=None, replace=False): self.__setitem__(key, value, replace) self._field_flag[key] = replace self.add_comment(key, comments) def __setitem__(self, key, value, replace=False): if self._lazy: if not key in self or replace: v = Lazy(key, self._root._globals, self._name, self._encoding, self._root._import_env) else: v = self[key] v.add(value) else: v = value if not replace: v = merge_data([value], self.get(key)) super(Section, self).__setitem__(key, v, append=replace) def add_comment(self, key=None, comments=None): comments = comments or [] if not isinstance(comments, (tuple, list)): comments = [comments] if not key: self._comments = comments else: self._field_comments[key] = copy.copy(comments) def comment(self, key=None): if not key: return self._comments else: return self._field_comments.get(key, []) def del_comment(self, key=None): self.add_comment(key, None) def dumps(self, out, convertors=None): if self._comments: print >> out, '\n'.join(self._comments) if self._root and self._root._raw: print >> out, '%s [%s]' % (self._info, self._name) else: print >> out, '[%s]' % self._name for f in self.keys(): comments = self.comment(f) if comments: print >> out, '\n'.join(comments) if self._root and self._root._raw: print >> out, "%s %s%s" % (str(self[f]), f, self[f].value()) else: if self._field_flag.get(f, False): op = ' <= ' else: op = ' = ' buf = f + op + uni_prt(self[f], self._encoding, convertors=convertors) if len(buf) > 79: buf = f + op + uni_prt(self[f], self._encoding, True, convertors=convertors) print >> out, buf def __delitem__(self, key): super(Section, self).__delitem__(key) self.del_comment(key) def __delattr__(self, key): try: del self[key] except KeyError as k: raise AttributeError(k) def __str__(self): buf = StringIO.StringIO() self.dumps(buf) return buf.getvalue() class Ini(SortedDict): def __init__(self, inifile='', commentchar=None, encoding=None, env=None, convertors=None, lazy=False, writable=False, raw=False, import_env=True, basepath='.', pre_variables=None): """ lazy is used to parse first but not deal at time, and only when the user invoke finish() function, it'll parse the data. import_env will import all environment variables if inifile is dict, then automatically add to ini object """ super(Ini, self).__init__() if isinstance(inifile, dict): self._inifile = '' data = inifile else: self._inifile = inifile data = None self._basepath = basepath self._commentchar = commentchar or __default_env__.get('commentchar', '#') self._encoding = encoding or __default_env__.get('encoding', 'utf-8') self._env = __default_env__.get('env', {}).copy() self._env.update(env or {}) self._env['set'] = set self.update(self._env) self._globals = SortedDict() self._pre_variables = pre_variables or {} self._import_env = import_env if self._import_env: self._globals.update(os.environ) self._convertors = __default_env__.get('convertors', {}).copy() self._convertors.update(convertors or {}) self._lazy = lazy self._writable = writable self._raw = raw if lazy: self._globals.update(self._env.copy()) if self._inifile: self.read(self._inifile) if data: for k, v in data.items(): s = self.add(k) for _k, _v in v.items(): s[_k] = _v def set_filename(self, filename): self._inifile = filename def get_filename(self): return self._inifile def set_basepath(self, basepath): self._basepath = basepath def set_pre_variables(self, v): self._pre_variables = v or {} filename = property(get_filename, set_filename) def _pre_var(self, value): """ replace predefined variables, the format is #{name} """ def sub_(m): return self._pre_variables.get(m.group()[2:-1].strip(), '') return r_pre_var.sub(sub_, value) def read(self, fobj, filename=''): encoding = None if isinstance(fobj, (str, unicode)): f = open(fobj, 'rb') text = f.read() f.close() else: text = fobj.read() text = text + '\n' begin = 0 if text.startswith(codecs.BOM_UTF8): begin = 3 encoding = 'UTF-8' elif text.startswith(codecs.BOM_UTF16): begin = 2 encoding = 'UTF-16' if not encoding: try: unicode(text, 'UTF-8') encoding = 'UTF-8' except: encoding = defaultencoding self._encoding = encoding f = StringIO.StringIO(text) f.seek(begin) lineno = 0 comments = [] status = 'c' section = None while 1: lastpos = f.tell() line = f.readline() lineno += 1 if not line: break line = line.strip() if line: if line.startswith(self._commentchar): if lineno == 1: #first comment line b = r_encoding.search(line[1:]) if b: self._encoding = b.groups()[0] continue comments.append(line) elif line.startswith('[') and line.endswith(']'): sec_name = line[1:-1].strip() #process include notation if sec_name.startswith('include:'): _filename = sec_name[8:].strip() _file = os.path.join(self._basepath, _filename) if os.path.exists(_file): old_encoding = self._encoding old_filename = self.filename self.set_filename(_file) self.read(_file, filename=_file) self.set_filename(old_filename) self._encoding = old_encoding else: import warnings warnings.warn(Warning("Can't find the file [%s], so just skip it" % _filename), stacklevel=2) continue info = RawValue(self._inifile, lineno, sec_name) section = self.add(sec_name, comments, info=info) comments = [] elif '=' in line: if section is None: raise Exception("No section found, please define it first in %s file" % self.filename) #if find <=, then it'll replace the old value for mutable variables #because the default behavior will merge list and dict pos = line.find('<=') if pos != -1: begin, end = pos, pos+2 replace_flag = True else: pos = line.find('=') begin, end = pos, pos+1 replace_flag = False keyname = line[:begin].strip() #check keyname if keyname in self._env: raise KeyError("Settings key %s is alread defined in env, please change it's name" % keyname) rest = line[end:].strip() #if key= then value will be set '' if rest == '': value = 'None' else: f.seek(lastpos+end) try: value, iden_existed = self.__read_line(f) #add pre variables process value = self._pre_var(value) except Exception as e: print_exc() raise Exception("Parsing ini file error in %s:%d:%s" % (filename or self._inifile, lineno, line)) if self._lazy: if iden_existed: v = EvalValue(value, filename or self._inifile, lineno, line) else: v = value else: if self._raw: v = RawValue(self._inifile, lineno, value, replace_flag) else: try: v = eval_value(value, self.env(), self[sec_name], self._encoding, self._import_env) except Exception as e: print_exc() raise Exception("Converting value (%s) error in %s:%d:%s" % (value, filename or self._inifile, lineno, line)) section.add(keyname, v, comments, replace=replace_flag) comments = [] else: comments.append(line) def save(self, filename=None): if not filename: filename = self.filename if not filename: filename = sys.stdout if isinstance(filename, (str, unicode)): f = open(filename, 'wb') need_close = True else: f = filename need_close = False print >> f, '#coding=%s' % self._encoding for s in self.keys(): if s in self._env: continue section = self[s] section.dumps(f, convertors=self._convertors) if need_close: f.close() def __read_line(self, f): """ Get logic line according the syntax not the physical line It'll return the line text and if there is identifier existed return line, bool """ g = tokenize.generate_tokens(f.readline) buf = [] time = 0 iden_existed = False while 1: v = g.next() tokentype, t, start, end, line = v if tokentype == 54: continue if tokentype in (token.INDENT, token.DEDENT, tokenize.COMMENT): continue if tokentype == token.NAME: iden_existed = True if tokentype == token.NEWLINE: return ''.join(buf), iden_existed else: if t == '=' and time == 0: time += 1 continue buf.append(t) def __setitem__(self, key, value): if key not in self: super(Ini, self).__setitem__(key, value) def update(self, value): for k, v in value.items(): self.set_var(k, v) def add(self, sec_name, comments=None, info=None): if sec_name in self: section = self[sec_name] else: section = Section(sec_name, comments, self._encoding, root=self, info=info) self[sec_name] = section return section def __str__(self): buf = StringIO.StringIO() self.save(buf) return buf.getvalue() def get_var(self, key, default=None): obj = self for i in key.split('/', 1): obj = obj.get(i) if obj is None: break if obj is None: return default return obj def set_var(self, key, value): s = key.split('/', 1) obj = self for i in s[:-1]: obj = obj.add(i) obj[s[-1]] = value return True def del_var(self, key): s = key.split('/', 1) obj = self for i in s[:-1]: obj = obj.get(i) if obj is None: return False if s[-1] in obj: del obj[s[-1]] flag = True else: flag = False return flag def items(self): return ((k, self[k]) for k in self.keys() if not k in self._env) def env(self): if self._import_env: d = {} d.update(os.environ.copy()) d.update(dict(self)) return d return self def freeze(self): """ Process all EvalValue to real value """ self._lazy = False for k, v in self.items(): if k in self._env: continue for _k, _v in v.items(): if isinstance(_v, Lazy): if self.writable: _v.get() else: try: v.__setitem__(_k, _v.get(), replace=True) except: print "Error ini key:", _k raise del _v self._globals = SortedDict()
#!/usr/bin/python # ======================================================================== # Copyright (c) 2007, Metaweb Technologies, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB TECHNOLOGIES BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ======================================================================== import unittest import sys, logging import freebase import random import getlogindetails from freebase.api import HTTPMetawebSession, MetawebError USERNAME = 'username' PASSWORD = 'password' API_HOST = 'http://sandbox-freebase.com' TEST_QUERY = {'id': 'null', 'name': 'Sting'} s = HTTPMetawebSession(API_HOST) if USERNAME == "username" and PASSWORD == "password": USERNAME, PASSWORD = getlogindetails.main() s.login(USERNAME, PASSWORD) class TestFreebase(unittest.TestCase): def test_freebase_dot_login_logout(self): freebase.login(username=USERNAME, password=PASSWORD) self.assertNotEqual(freebase.user_info(), None) self.assertEqual(freebase.loggedin(), True) freebase.logout() self.assertRaises(MetawebError, freebase.user_info) self.assertEqual(freebase.loggedin(), False) def test_login_logout(self): mss = HTTPMetawebSession(API_HOST, username=USERNAME, password=PASSWORD) mss.login() user_info = mss.user_info() self.assertNotEqual(None, user_info) self.assertEqual(user_info.code, "/api/status/ok") self.assertEqual(mss.loggedin(), True) mss.logout() self.assertRaises(MetawebError, mss.user_info) self.assertEqual(mss.loggedin(), False) def test_freebase_dot_read(self): query = {'type':'/music/artist','guid':[{}],'name':'Sting', 'album':[{}]} result = freebase.mqlread(query) self.assertNotEqual(None, result) self.assert_(result.has_key('guid')) self.assert_(result.has_key('type')) self.assert_(result.has_key('name')) self.assert_(result.has_key('album')) self.assertEqual(type([]), type(result['album'])) self.assert_(len(result['album']) > 0) self.assertEqual( 'Sting', result['name']) self.assertEqual('#9202a8c04000641f8000000000092a01', result['guid'][0]['value']) def test_freebase_dot_write(self): read_query = {'type':'/music/artist','name':'Yanni\'s Cousin Tom', 'id':{}} freebase.sandbox.login(username=USERNAME, password=PASSWORD) result = freebase.sandbox.mqlread(read_query) self.assertEqual(None, result) write_query = {'create':'unless_exists', 'type':'/music/artist','name':'Yanni'} write_result = freebase.sandbox.mqlwrite(write_query) self.assertNotEqual(None, write_result) self.assert_(write_result.has_key('create')) self.assert_(write_result.has_key('type')) self.assert_(write_result.has_key('name')) self.assertEqual('existed', write_result['create']) self.assertEqual('Yanni', write_result['name']) self.assertEqual('/music/artist', write_result['type']) def test_read(self): query = {'type':'/music/artist','guid':[{}],'name':'Sting', 'album':[{}]} mss = HTTPMetawebSession(API_HOST) result = mss.mqlread(query) self.assertNotEqual(None, result) self.assert_(result.has_key('guid')) self.assert_(result.has_key('type')) self.assert_(result.has_key('name')) self.assert_(result.has_key('album')) self.assertEqual(type([]), type(result['album'])) self.assert_(len(result['album']) > 0) self.assertEqual( 'Sting', result['name']) self.assertEqual('#9202a8c04000641f8000000000092a01', result['guid'][0]['value']) def test_mqlreaditer(self): filmq = [{'id': None, 'initial_release_date>=': '2009', 'name': None, 'type': '/film/film' }] r0 = freebase.mqlreaditer(filmq) r1 = freebase.mqlreaditer(filmq[0]) # The difference between [{}] and []. mqlreaditer should be able to handle both self.assertNotEqual(r0, None) self.assertEqual([a for a in r0], [b for b in r1]) # and let's test it for mqlread, just in case # actually, for mqlread, it must be [{}], because there are lots of elements m0 = freebase.mqlread(filmq) m1 = lambda : freebase.mqlread(filmq[0]) self.assertRaises(MetawebError, m1) self.assertNotEqual(m0, None) def test_ridiculously_long_write(self): q = [{ "id":None, "id|=":["/guid/9202a8c04000641f80000000000" + str(a) for a in range(10000,10320)] }] self.assert_(len(str(q)), 1024) self.assertNotEqual(len(freebase.mqlread(q)), 0) def test_write(self): read_query = {'type':'/music/artist','name':'Yanni\'s Cousin Tom', 'id':{}} mss = HTTPMetawebSession(API_HOST, username=USERNAME, password=PASSWORD) result = mss.mqlread(read_query) self.assertEqual(None, result) write_query = {'create':'unless_exists', 'type':'/music/artist','name':'Yanni'} mss.login() write_result = mss.mqlwrite(write_query) self.assertNotEqual(None, write_result) self.assert_(write_result.has_key('create')) self.assert_(write_result.has_key('type')) self.assert_(write_result.has_key('name')) self.assertEqual('existed', write_result['create']) self.assertEqual('Yanni', write_result['name']) self.assertEqual('/music/artist', write_result['type']) def test_trans_blurb(self): kurt = "/en/kurt_vonnegut" blurb = freebase.blurb(kurt) self.assert_(blurb.startswith("Kurt Vonnegut")) self.assertNotEqual(len(blurb), 0) blurb14 = freebase.blurb(kurt, maxlength=14) blurb57 = freebase.blurb(kurt, maxlength=57) self.assertNotEqual(len(blurb14), len(blurb57)) blurbpar = freebase.blurb(kurt, break_paragraphs=True, maxlength=20000) blurbnopar = freebase.blurb(kurt, break_paragraphs=False, maxlength=20000) # self.assertNotEqual(blurbpar, blurbnopar) this doesn't work unless I get a good example # of an article with paragraphs. def test_trans_raw(self): kurt = "/en/kurt_vonnegut" self.assertRaises(MetawebError, lambda: freebase.raw(kurt)) r = freebase.mqlread({"id":kurt, "/common/topic/article":[{"id":None, "optional":True, "limit":1}]}) raw = freebase.raw(r["/common/topic/article"][0].id) self.assertNotEqual(len(raw), 0) # trans should also work trans = freebase.trans(r["/common/topic/article"][0].id) self.assertEqual(trans, raw) def test_unsafe(self): kurt = "/en/kurt_vonnegut" self.assertRaises(MetawebError, lambda: freebase.unsafe(kurt)) r = freebase.mqlread({"id":kurt, "/common/topic/article":[{"id":None, "optional":True, "limit":1}]}) unsafe = freebase.unsafe(r["/common/topic/article"][0].id) self.assertNotEqual(len(unsafe), 0) # we need an example of getting unsafe data # ... def test_trans_image_thumb(self): kurt = "/en/kurt_vonnegut" r = freebase.mqlread({"id":kurt, "/common/topic/image":[{"id":None, "optional":True, "limit":1}]}) imageid = r["/common/topic/image"][0].id rawimage = freebase.raw(imageid) thumbedimage = freebase.image_thumb(imageid, maxheight=99) self.assertNotEqual(rawimage, thumbedimage) def test_upload(self): my_text = "Kurt Vonnegut was an author! " + str(random.random()) freebase.sandbox.login(USERNAME, PASSWORD) response = freebase.sandbox.upload(my_text, "text/plain") self.assertEqual(freebase.sandbox.raw(response.id), my_text) # since it's text/plain, blurb should also be equal self.assertEqual(freebase.sandbox.blurb(response.id), my_text) def is_kurt_there(self, results): for result in results: if result.name == "Kurt Vonnegut": return True return False def test_search(self): r0 = freebase.search("Kurt V") self.assertEqual(self.is_kurt_there(r0), True) r1 = freebase.search("Kurt V", type=["/location/citytown"]) self.assertEqual(self.is_kurt_there(r1), False) r2 = freebase.search("Kurt V", type=["/location/citytown", "/music/artist"]) self.assertEqual(self.is_kurt_there(r2), False) self.assertNotEqual(len(r0), len(r1)) self.assertNotEqual(len(r0), len(r2)) self.assertNotEqual(len(r1), len(r2)) def test_touch(self): # this one's hard to test... let's just make sure it works. freebase.touch() def test_geosearch(self): self.assertRaises(Exception, freebase.geosearch) r0 = freebase.geosearch(location="/en/california") self.assertNotEqual(len(r0), 0) json = freebase.geosearch(location="/en/san_francisco", format="json") kml = freebase.geosearch(location="/en/san_francisco", format="kml") self.assertNotEqual(json, kml) def test_uri_submit(self): # test a pdf r = freebase.sandbox.uri_submit("http://www.jcbl.or.jp/game/nec/necfest07/nec2007_data/HayashiMiyake.pdf", content_type="application/pdf") self.assertEqual(r['/type/content/media_type'], 'application/pdf') # test an image r = freebase.sandbox.uri_submit("http://datamob.org/media/detail_freebase.png") self.assertEqual(r['/type/content/media_type'], 'image/png') def test_version(self): r = freebase.version() self.assertNotEqual(len(r), 0) def test_status(self): r = freebase.status() self.assertNotEqual(len(r), 0) self.assertEqual(r["status"], u"200 OK") def test_private_domains(self): freebase.sandbox.login(username=USERNAME, password=PASSWORD) r = freebase.sandbox.create_private_domain("superfly" + str(int(random.random() * 1e10)), "Superfly!") q = {"id" : r["domain_id"], "*" : None} info = freebase.sandbox.mqlread(q) self.assertEqual(info["type"], ["/type/domain"]) self.assertNotEqual(len(info["key"]), 0) self.assertEqual(info["attribution"], info["creator"]) freebase.sandbox.delete_private_domain(info["key"][0]) deleted = freebase.sandbox.mqlread(q) self.assertEqual(len(deleted["key"]), 0) self.assertEqual(len(deleted["type"]), 0) self.assertEqual(deleted["name"], None) self.assertEqual(deleted["creator"], info["attribution"]) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 # binary2DICOM converter # Author: Rafal Maselek # Email: rafal.maselek@ncbj.gov.pl # # This script enables converting raw 3D binary images to DICOM file format and importing meta-data from external file. import sys try: from pydicom.dataset import Dataset, FileDataset except ImportError: from dicom.dataset import Dataset, FileDataset import datetime import time import argparse import numpy as np binary2DICOM_version = "version 1.3 features included:\n\t1)Reading raw binary file with image\n\t2)Reading file with meta-data\n\t3)Creating\ a new DICOM file\n\t4)Reading image parameters from meta-data\n\t5)Smart argument parser\n\t6)Using converter as a module" def recognize_type(bytes_per_pix, is_signed, is_float=False): """ A function to recognize type of the data. :param bytes_per_pix: How many bytes are used to encode one pixel. :param is_signed: Are signed other unsigned integers used. :param is_float: currently not used :return: Numpy type """ if is_signed: if bytes_per_pix == 1: return np.int8 elif bytes_per_pix == 2: return np.int16 elif bytes_per_pix== 4: return np.int32 elif bytes_per_pix == 8: return np.int64 else: raise ValueError('[ERROR] Invalid type declared!') else: if bytes_per_pix == 1: return np.uint8 elif bytes_per_pix == 2: return np.uint16 elif bytes_per_pix== 4: return np.uint32 elif bytes_per_pix == 8: return np.uint64 else: raise ValueError('[ERROR] Invalid type declared!') def read_meta(filename): """ A naive parser for DICOM meta-data. :param filename: Contains meta-data in a format: <group tag> , <element tag> , <VR>, <value> Commas are delimiters. :return: An array N x 3, where N is the number of correctly parsed lines. """ meta_arr = [] lines_with_data = 0 with open(filename) as f: for line_no, line in enumerate(f): line = line.partition('#')[0] line = line.strip() line = line.split(',') err_str = ' could not be parsed correctly!' if len(line[0]) > 0: lines_with_data +=1 if len(line) > 4: print("[WARNING] Line "+str(line_no+1)+" contains more values than required. Please, check it.") try: if len(str(line[2]).strip()) != 2: raise ValueError('VR should consist of exactly 2 characters! VR parsed:'+str(line[2]).strip()) line_data = [int(line[0], 16), int(line[1], 16), str(line[2]).strip()] # parsing the value val = line[3].strip() if val[0] == '\'' or val[-1] == '\'': # parse as string line_data.append(val.replace('\'', '').strip()) elif val.find('.') != -1: # parse as float line_data.append(float(val)) else: # parse as int line_data.append(int(val)) meta_arr.append(line_data) except ValueError as e: print('[WARNING] Line '+str(line_no+1)+err_str + " Wrong value!" + "ERR MSG: "+str(e)) except IndexError as e: print('[WARNING] Line '+str(line_no+1)+err_str + " Tags or/and value are missing!" + "ERR MSG: "+str(e)) print("[INFO] Reading meta-data is complete! " + str(len(meta_arr))+'/'+str(lines_with_data)+' lines were parsed correctly.') return meta_arr def write_meta(meta_data, data_set): """ Writes meta data into the data set. :param meta_data: Array N x 4, where N is the number of data elements. :param data_set: Dicom Data Set :return: Modified Data Set """ for elem in meta_data: data_set.add_new((hex(elem[0]), hex(elem[1])), elem[2], elem[3]) return data_set def read_binary(arguments): """ Reads image data from a binary file. :param arguments: Dictionary containing input parameters. :return: Numpy array containing pixel values. """ if arguments['byte_order'] == 'system': byte_order_local = sys.byteorder print('[WARNING] Byte order was not specified. I will use system\'s default: '+sys.byteorder) else: byte_order_local = arguments['byte_order'] values = [] total_pix = arguments['width']*arguments['height']*arguments['frames'] # Opening the file with open(arguments['in_file'], "rb") as f: byte_list = f.read() if total_pix != len(byte_list) // arguments['bytes_per_pix']: raise IOError('[ERROR] The given image dimensions and encoding does not match given data!'\ + '\n\t>\tTotal number of pixels declared: '+str(total_pix)\ + '\n\t>\tEstimation from file: '+str(len(byte_list) // arguments['bytes_per_pix'])) # decoding depends on whether data is float or not if arguments['is_float']: raise ValueError('[ERROR] Floats are currently unavailable!') # TODO: enable reading floats # for pix_no in range(0, total_pix): # values.append(float.from_bytes(byte_list[bytes_per_pix * pix_no: (bytes_per_pix * (pix_no + 1))], \ # byteorder=byte_order_local, signed=is_signed)) else: for pix_no in range(0, total_pix): values.append(int.from_bytes(byte_list[arguments['bytes_per_pix'] * pix_no: (arguments['bytes_per_pix'] * (pix_no + 1))], \ byteorder=byte_order_local, signed=arguments['is_signed'])) resh_arr = np.asarray(values).reshape((arguments['frames'], arguments['width'], arguments['height'])) print('[INFO] Reading image data is complete!') return resh_arr def write_dicom(arguments, pixel_array, meta_arr = []): """ Function to create completely new DICOM file. :param arguments: Dictionary containing input parameters. :param pixel_array: 2D or 3D numpy array containing pixel values. :param meta_arr: An array contaning parsed meta data. :return: """ #TODO:Check the possibility to use UID generator instead hardcoded ones. file_meta = Dataset() # The Secondary Capture (SC) Image Information Object Definition (IOD) specifies images that are converted from # a non-DICOM format to a modality independent DICOM format. file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage' file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780' file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0' # Since we don't want to store any additional info in the header, we set it to x00 ds = FileDataset(arguments['out_file'], {}, file_meta=file_meta, preamble=b'0' * 128) # Type of equipment that originally acquired the data. ds.Modality = 'WSD' # Setting the date and time ds.ContentDate = str(datetime.date.today()).replace('-', '') ds.ContentTime = str(time.time()) # milliseconds since the epoch # Keep scrolling :) ds.SOPClassUID = 'Secondary Capture Image Storage' ds.SOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780' ds.StudyInstanceUID = '1.3.6.1.4.1.9590.100.1.1.124313977412360175234271287472804872093' ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421859172643143649' # Manufacturer ds.SecondaryCaptureDeviceManufctur = 'NCBJ' # These are the necessary imaging components of the FileDataset object. # Number of color channels. ds.SamplesPerPixel = 1 # It defines what does every color channel hold ds.PhotometricInterpretation = "MONOCHROME2" # ds.PixelRepresentation = 0 ds.HighBit = 15 # Here meta-data is put into the Data Set. It can override hardcoded values, but parameters providided as program # arguments will be inserted no matter what is in the meta-data file. ds = write_meta(meta_arr, ds) # How many bits are allocated to store pixel info ds.BitsAllocated = arguments['bytes_per_pix'] * 8 # How many bits are used to store pixel info ds.BitsStored = arguments['bytes_per_pix']*8 # Whether signed or unsigned numbers are used if arguments['is_signed']: ds.PixelRepresentation = 1 else: ds.PixelRepresentation = 0 # Read from data the dimensions. if len(pixel_array.shape) == 3: ds.NumberOfFrames = pixel_array.shape[0] ds.Columns = pixel_array.shape[1] ds.Rows = pixel_array.shape[2] else: ds.Columns = pixel_array.shape[0] ds.Rows = pixel_array.shape[1] try: err_str = '[ERROR] The file could not be created because of: ' data_type = recognize_type(arguments['bytes_per_pix'], arguments['is_signed'], arguments['is_float']) if pixel_array.dtype != data_type: pixel_array = pixel_array.astype(data_type) ds.PixelData = pixel_array.tostring() ds.save_as(arguments['out_file'].replace('.dcm', '') + '.dcm') print('[INFO] Writing to DICOM file is complete!') except ValueError as ve: print(err_str+'ValueError '+str(ve)) sys.exit(1) except FileExistsError as fe: print(err_str+'FileExistsError '+str(fe)) sys.exit(1) except Exception as e: print(err_str+str(e)) sys.exit(1) def convert(arguments): """ Calls functions to read binary image and write it (with meta data) to a new DICOM file. :param arguments: Dictionary containing input parameters. {'meta': <META DATA FILE, STRING>, 'in_file': <INPUT FILE, STRING>, 'out_file': <OUTPUT FILE, STRING>, 'width': <INT>, 'height': <INT>, 'frames': <INT>, 'is_signed': <BOOL>, 'byte_order': <'little' OR 'big'>, 'bytes_per_pix': <INT>, 'is_float': <BOOL>} :return: """ meta_arr = [] try: if arguments['meta'] != '': meta_arr = read_meta(arguments['meta']) except FileNotFoundError as fnfe: print("[ERROR] Meta-data was not loaded, because the file was not found: "+str(fnfe)) sys.exit(1) image_arr = read_binary(arguments) write_dicom(arguments, image_arr, meta_arr) def main(): """ Main function of the program, parses the input parameters and calls necessary functions. :return: """ parser = argparse.ArgumentParser( description='This is a binary -> DICOM converter created by Rafal Maselek.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('in_file', metavar='input_file_name', type=str) parser.add_argument('out_file', metavar='output_file_name', type=str) parser.add_argument('width', metavar='image_width', type=int) parser.add_argument('height', metavar='image_height', type=int) parser.add_argument('frames', metavar='no._of_frames', type=int) parser.add_argument('-bpp', '--bytes_per_pix', metavar='bytes_per_pixel', type=int, nargs='?', default=2, help='Pixel encoding') parser.add_argument('-uint', '--unsigned', dest='is_signed', action='store_false', help='Use unsigned ints', default=False) parser.add_argument('-int', '--signed', dest='is_signed', action='store_true', help='Use signed ints', default=True) parser.add_argument('-f', '--float', dest='is_float', action='store_true', help='Not supported now', default=False) parser.add_argument('-nf', '--non_float', dest='is_float', action='store_false', help='Not supported now') parser.add_argument('-bo', '--byte_order', metavar='byte_order', type=str, nargs='?', default='system', choices=['little', 'big'],\ help='ENDIAN type (little/big)') parser.add_argument('-m', '--meta', help='use external meta data', type=str, nargs='?', default='') parser.add_argument('-v', '--version', action='version', version=binary2DICOM_version) try: args = parser.parse_args() args_dict = vars(args) if args_dict['width'] < 1: raise ValueError('Invalid value of image width! It has to be >0') if args_dict['height'] < 1: raise ValueError('Invalid value of image height! It has to be >0') if args_dict['bytes_per_pix'] < 1: raise ValueError('Invalid number of bytes_per_pixel! It has to be >0') except ValueError as ve: print('[ERROR] Could not parse input parameters correctly! ' +str(ve)) exit(1) except Exception as e: print('[ERROR] Unknown error! Could not parse input parameters correctly! ' + str(e)) exit(1) print('[INFO] Parsed arguments:') print(args_dict) convert(args_dict) if __name__ == "__main__": main()
import time import synapse.cortex as s_cortex import synapse.daemon as s_daemon import synapse.telepath as s_telepath import synapse.lib.service as s_service import synapse.lib.userauth as s_userauth import synapse.swarm.runtime as s_runtime from synapse.tests.common import * class SwarmRunBase(SynTest): def getSwarmEnv(self): tenv = TestEnv() core0 = s_cortex.openurl('ram://') core1 = s_cortex.openurl('ram://') tenv.add('core0',core0,fini=True) tenv.add('core1',core1,fini=True) tufo0 = core0.formTufoByProp('foo:bar','baz',vvv='visi') tufo1 = core0.formTufoByProp('foo:bar','faz',vvv='visi') tufo2 = core1.formTufoByProp('foo:bar','lol',vvv='visi') tufo3 = core1.formTufoByProp('foo:bar','hai',vvv='visi') tufo4 = core0.formTufoByProp('zzz:woot',10,vvv='visi') tufo5 = core1.formTufoByProp('zzz:woot',12,vvv='romp') tenv.add('tufo0',tufo0) tenv.add('tufo1',tufo1) tenv.add('tufo2',tufo2) tenv.add('tufo3',tufo3) dmon = s_daemon.Daemon() link = dmon.listen('tcp://127.0.0.1:0') tenv.add('link',link) tenv.add('dmon',dmon,fini=True) port = link[1].get('port') svcbus = s_service.SvcBus() tenv.add('svcbus',svcbus,fini=True) dmon.share('syn.svcbus',svcbus) svcrmi = s_telepath.openurl('tcp://127.0.0.1/syn.svcbus', port=port) tenv.add('svcrmi',svcrmi,fini=True) s_service.runSynSvc('cortex',core0,svcrmi,tags=('hehe.haha',)) s_service.runSynSvc('cortex',core1,svcrmi,tags=('hehe.hoho',)) runt = s_runtime.Runtime(svcrmi) tenv.add('runt',runt,fini=True) return tenv class SwarmRunTest(SwarmRunBase): def test_swarm_runtime_eq(self): tenv = self.getSwarmEnv() answ = tenv.runt.ask('foo:bar="baz"') data = answ.get('data') self.assertEqual( data[0][0], tenv.tufo0[0] ) # FIXME check for other expected results info! answ = tenv.runt.ask('foo:bar:vvv') data = answ.get('data') self.assertEqual( len(data), 4 ) answ = tenv.runt.ask('hehe.haha/foo:bar:vvv') data = answ.get('data') self.assertEqual( len(data), 2 ) answ = tenv.runt.ask('hehe.haha/foo:bar:vvv="visi"') data = answ.get('data') self.assertEqual( len(data), 2 ) tenv.fini() def test_swarm_runtime_pivot(self): tenv = self.getSwarmEnv() data = tenv.runt.eval('foo:bar="baz" foo:bar:vvv->foo:bar:vvv') self.assertEqual( len(data), 4 ) tenv.fini() def test_swarm_runtime_opts(self): tenv = self.getSwarmEnv() answ = tenv.runt.ask('%foo') self.assertEqual( answ['options'].get('foo'), 1 ) answ = tenv.runt.ask('opts(foo=10)') self.assertEqual( answ['options'].get('foo'), 10 ) answ = tenv.runt.ask('%foo=10') self.assertEqual( answ['options'].get('foo'), 10 ) answ = tenv.runt.ask('opts(foo="bar")') self.assertEqual( answ['options'].get('foo'), 'bar' ) answ = tenv.runt.ask('%foo="bar"') self.assertEqual( answ['options'].get('foo'), 'bar' ) tenv.fini() def test_swarm_runtime_opts_uniq(self): tenv = self.getSwarmEnv() answ = tenv.runt.ask('%uniq foo:bar="baz" foo:bar="baz"') self.assertEqual( len(answ['data']), 1 ) answ = tenv.runt.ask('%uniq=0 foo:bar="baz" foo:bar="baz"') self.assertEqual( len(answ['data']), 2 ) tenv.fini() def test_swarm_runtime_join(self): tenv = self.getSwarmEnv() answ = tenv.runt.ask('foo:bar="baz" join("foo:bar:vvv")') data = answ.get('data') self.assertEqual( len(data), 4 ) answ = tenv.runt.ask('foo:bar="baz" join("zzz:woot:vvv","foo:bar:vvv")') data = answ.get('data') self.assertEqual( len(data), 2 ) tenv.fini() def test_swarm_runtime_gele(self): env = self.getSwarmEnv() answ = env.runt.ask('zzz:woot>=11') data = answ.get('data') self.assertEqual( len(data), 1 ) self.assertEqual( data[0][1].get('zzz:woot'), 12 ) answ = env.runt.ask('zzz:woot>10') data = answ.get('data') self.assertEqual( len(data), 1 ) self.assertEqual( data[0][1].get('zzz:woot'), 12 ) answ = env.runt.ask('zzz:woot>=10') data = answ.get('data') self.assertEqual( len(data), 2 ) answ = env.runt.ask('zzz:woot<=11') data = answ.get('data') self.assertEqual( len(data), 1 ) self.assertEqual( data[0][1].get('zzz:woot'), 10 ) answ = env.runt.ask('zzz:woot<12') data = answ.get('data') self.assertEqual( len(data), 1 ) self.assertEqual( data[0][1].get('zzz:woot'), 10 ) answ = env.runt.ask('zzz:woot<=13') data = answ.get('data') self.assertEqual( len(data), 2 ) answ = env.runt.ask('zzz:woot -zzz:woot<=11') data = answ.get('data') self.assertEqual( len(data), 1 ) env.fini() def test_swarm_runtime_regex(self): env = self.getSwarmEnv() answ = env.runt.ask('foo:bar +foo:bar~="^l"') data = answ.get('data') self.assertEqual( data[0][1].get('foo:bar'), 'lol') answ = env.runt.ask('foo:bar +foo:bar~="^Q"') self.assertEqual( len(answ.get('data')), 0) answ = env.runt.ask('foo:bar +foo:bar~="^Q"') self.assertEqual( len(answ.get('data')), 0) answ = env.runt.ask('foo:bar -foo:bar~="^[a-z]{3}$"') self.assertEqual( len(answ.get('data')), 0) env.fini() def test_swarm_runtime_or(self): env = self.getSwarmEnv() answ = env.runt.ask('foo:bar +foo:bar="baz"|foo:bar="faz"') tufos = answ.get('data') foobars = [ t[1].get('foo:bar') for t in tufos ] foobars.sort() self.assertEqual( foobars, ['baz','faz'] ) env.fini() def test_swarm_runtime_and(self): with self.getSwarmEnv() as env: answ = env.runt.ask('foo:bar -foo:bar="baz" & foo:bar:vvv="newp" ') tufos = answ.get('data') foobars = [ t[1].get('foo:bar') for t in tufos ] foobars.sort() self.assertEqual( foobars, ['baz','faz','hai','lol'] ) def test_swarm_runtime_clear(self): env = self.getSwarmEnv() answ = env.runt.ask('foo:bar clear()') tufos = answ.get('data') self.assertEqual( len(tufos), 0 ) env.fini() def test_swarm_runtime_saveload(self): env = self.getSwarmEnv() answ = env.runt.ask('foo:bar="baz" save("woot") clear() load("woot")') tufos = answ.get('data') self.assertEqual( len(tufos), 1 ) self.assertEqual( tufos[0][1].get('foo:bar'), 'baz' ) env.fini() def test_swarm_runtime_has(self): env = self.getSwarmEnv() # use the lift code for has() answ = env.runt.ask('foo:bar') tufos = answ.get('data') self.assertEqual( len(tufos), 4 ) self.assertEqual( tufos[0][1].get('tufo:form'), 'foo:bar' ) # use the filter code for has() answ = env.runt.ask('tufo:form +foo:bar') tufos = answ.get('data') self.assertEqual( len(tufos), 4 ) self.assertEqual( tufos[0][1].get('tufo:form'), 'foo:bar' ) env.fini() def test_swarm_runtime_maxtime(self): env = self.getSwarmEnv() self.assertRaises(HitStormLimit, env.runt.eval, 'foo:bar', timeout=0) env.fini() def test_swarm_runtime_by(self): env = self.getSwarmEnv() # test out long form using range #answ = env.runt.ask('by("range","zzz:woot",(10,13))') #print('answ: %r' % (answ,)) #tufos = answ.get('data') #self.eq( len(tufos), 2 ) answ = env.runt.ask('zzz:woot*range=(10,13)') tufos = answ.get('data') self.eq( len(tufos), 2 ) answ = env.runt.ask('zzz:woot*range=(10,12)') tufos = answ.get('data') self.eq( len(tufos), 1 ) answ = env.runt.ask('zzz:woot#1*range=(10,13)') tufos = answ.get('data') self.eq( len(tufos), 2 ) env.fini() def test_swarm_runtime_frob(self): env = self.getSwarmEnv() env.core0.formTufoByProp('inet:ipv4', 0x01020304) answ = env.runt.ask('inet:ipv4="1.2.3.4"') #foo:bar="baz" save("woot") clear() load("woot")') tufos = answ.get('data') self.assertEqual( len(tufos), 1 ) self.assertEqual( tufos[0][1].get('inet:ipv4'), 0x01020304 ) answ = env.runt.ask('inet:ipv4=0x01020304') tufos = answ.get('data') self.assertEqual( len(tufos), 1 ) self.assertEqual( tufos[0][1].get('inet:ipv4'), 0x01020304 ) env.fini()
"""The tests for the device tracker component.""" # pylint: disable=protected-access import asyncio import json import logging import unittest from unittest.mock import call, patch from datetime import datetime, timedelta import os from homeassistant.components import zone from homeassistant.core import callback from homeassistant.bootstrap import setup_component from homeassistant.loader import get_component from homeassistant.util.async import run_coroutine_threadsafe import homeassistant.util.dt as dt_util from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM) import homeassistant.components.device_tracker as device_tracker from homeassistant.exceptions import HomeAssistantError from homeassistant.remote import JSONEncoder from tests.common import ( get_test_home_assistant, fire_time_changed, fire_service_discovered, patch_yaml_files, assert_setup_component) from ...test_util.aiohttp import mock_aiohttp_client TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}} _LOGGER = logging.getLogger(__name__) class TestComponentsDeviceTracker(unittest.TestCase): """Test the Device tracker.""" hass = None # HomeAssistant yaml_devices = None # type: str # pylint: disable=invalid-name def setUp(self): """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.yaml_devices = self.hass.config.path(device_tracker.YAML_DEVICES) # pylint: disable=invalid-name def tearDown(self): """Stop everything that was started.""" try: os.remove(self.yaml_devices) except FileNotFoundError: pass self.hass.stop() def test_is_on(self): """Test is_on method.""" entity_id = device_tracker.ENTITY_ID_FORMAT.format('test') self.hass.states.set(entity_id, STATE_HOME) self.assertTrue(device_tracker.is_on(self.hass, entity_id)) self.hass.states.set(entity_id, STATE_NOT_HOME) self.assertFalse(device_tracker.is_on(self.hass, entity_id)) # pylint: disable=no-self-use def test_reading_broken_yaml_config(self): """Test when known devices contains invalid data.""" files = {'empty.yaml': '', 'nodict.yaml': '100', 'badkey.yaml': '@:\n name: Device', 'noname.yaml': 'my_device:\n', 'allok.yaml': 'My Device:\n name: Device', 'oneok.yaml': ('My Device!:\n name: Device\n' 'bad_device:\n nme: Device')} args = {'hass': self.hass, 'consider_home': timedelta(seconds=60)} with patch_yaml_files(files): assert device_tracker.load_config('empty.yaml', **args) == [] assert device_tracker.load_config('nodict.yaml', **args) == [] assert device_tracker.load_config('noname.yaml', **args) == [] assert device_tracker.load_config('badkey.yaml', **args) == [] res = device_tracker.load_config('allok.yaml', **args) assert len(res) == 1 assert res[0].name == 'Device' assert res[0].dev_id == 'my_device' res = device_tracker.load_config('oneok.yaml', **args) assert len(res) == 1 assert res[0].name == 'Device' assert res[0].dev_id == 'my_device' def test_reading_yaml_config(self): """Test the rendering of the YAML configuration.""" dev_id = 'test' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, dev_id, 'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture', hide_if_away=True) device_tracker.update_config(self.yaml_devices, dev_id, device) with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) config = device_tracker.load_config(self.yaml_devices, self.hass, device.consider_home)[0] self.assertEqual(device.dev_id, config.dev_id) self.assertEqual(device.track, config.track) self.assertEqual(device.mac, config.mac) self.assertEqual(device.config_picture, config.config_picture) self.assertEqual(device.away_hide, config.away_hide) self.assertEqual(device.consider_home, config.consider_home) self.assertEqual(device.vendor, config.vendor) # pylint: disable=invalid-name @patch('homeassistant.components.device_tracker._LOGGER.warning') def test_track_with_duplicate_mac_dev_id(self, mock_warning): """Test adding duplicate MACs or device IDs to DeviceTracker.""" devices = [ device_tracker.Device(self.hass, True, True, 'my_device', 'AB:01', 'My device', None, None, False), device_tracker.Device(self.hass, True, True, 'your_device', 'AB:01', 'Your device', None, None, False)] device_tracker.DeviceTracker(self.hass, False, True, devices) _LOGGER.debug(mock_warning.call_args_list) assert mock_warning.call_count == 1, \ "The only warning call should be duplicates (check DEBUG)" args, _ = mock_warning.call_args assert 'Duplicate device MAC' in args[0], \ 'Duplicate MAC warning expected' mock_warning.reset_mock() devices = [ device_tracker.Device(self.hass, True, True, 'my_device', 'AB:01', 'My device', None, None, False), device_tracker.Device(self.hass, True, True, 'my_device', None, 'Your device', None, None, False)] device_tracker.DeviceTracker(self.hass, False, True, devices) _LOGGER.debug(mock_warning.call_args_list) assert mock_warning.call_count == 1, \ "The only warning call should be duplicates (check DEBUG)" args, _ = mock_warning.call_args assert 'Duplicate device IDs' in args[0], \ 'Duplicate device IDs warning expected' def test_setup_without_yaml_file(self): """Test with no YAML file.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) # pylint: disable=invalid-name def test_adding_unknown_device_to_config(self): """Test the adding of unknown devices to configuration file.""" scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('DEV1') with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}}) # wait for async calls (macvendor) to finish self.hass.block_till_done() config = device_tracker.load_config(self.yaml_devices, self.hass, timedelta(seconds=0)) assert len(config) == 1 assert config[0].dev_id == 'dev1' assert config[0].track def test_gravatar(self): """Test the Gravatar generation.""" dev_id = 'test' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, dev_id, 'AB:CD:EF:GH:IJ', 'Test name', gravatar='test@example.com') gravatar_url = ("https://www.gravatar.com/avatar/" "55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar") self.assertEqual(device.config_picture, gravatar_url) def test_gravatar_and_picture(self): """Test that Gravatar overrides picture.""" dev_id = 'test' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, dev_id, 'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture', gravatar='test@example.com') gravatar_url = ("https://www.gravatar.com/avatar/" "55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar") self.assertEqual(device.config_picture, gravatar_url) def test_mac_vendor_lookup(self): """Test if vendor string is lookup on macvendors API.""" mac = 'B8:27:EB:00:00:00' vendor_string = 'Raspberry Pi Foundation' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') with mock_aiohttp_client() as aioclient_mock: aioclient_mock.get('http://api.macvendors.com/b8:27:eb', text=vendor_string) run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() assert aioclient_mock.call_count == 1 self.assertEqual(device.vendor, vendor_string) def test_mac_vendor_mac_formats(self): """Verify all variations of MAC addresses are handled correctly.""" vendor_string = 'Raspberry Pi Foundation' with mock_aiohttp_client() as aioclient_mock: aioclient_mock.get('http://api.macvendors.com/b8:27:eb', text=vendor_string) aioclient_mock.get('http://api.macvendors.com/00:27:eb', text=vendor_string) mac = 'B8:27:EB:00:00:00' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() self.assertEqual(device.vendor, vendor_string) mac = '0:27:EB:00:00:00' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() self.assertEqual(device.vendor, vendor_string) mac = 'PREFIXED_B8:27:EB:00:00:00' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() self.assertEqual(device.vendor, vendor_string) def test_mac_vendor_lookup_unknown(self): """Prevent another mac vendor lookup if was not found first time.""" mac = 'B8:27:EB:00:00:00' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') with mock_aiohttp_client() as aioclient_mock: aioclient_mock.get('http://api.macvendors.com/b8:27:eb', status=404) run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() self.assertEqual(device.vendor, 'unknown') def test_mac_vendor_lookup_error(self): """Prevent another lookup if failure during API call.""" mac = 'B8:27:EB:00:00:00' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') with mock_aiohttp_client() as aioclient_mock: aioclient_mock.get('http://api.macvendors.com/b8:27:eb', status=500) run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() self.assertEqual(device.vendor, 'unknown') def test_mac_vendor_lookup_exception(self): """Prevent another lookup if exception during API call.""" mac = 'B8:27:EB:00:00:00' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name') with mock_aiohttp_client() as aioclient_mock: aioclient_mock.get('http://api.macvendors.com/b8:27:eb', exc=asyncio.TimeoutError()) run_coroutine_threadsafe(device.set_vendor_for_mac(), self.hass.loop).result() self.assertEqual(device.vendor, 'unknown') def test_mac_vendor_lookup_on_see(self): """Test if macvendor is looked up when device is seen.""" mac = 'B8:27:EB:00:00:00' vendor_string = 'Raspberry Pi Foundation' tracker = device_tracker.DeviceTracker( self.hass, timedelta(seconds=60), 0, []) with mock_aiohttp_client() as aioclient_mock: aioclient_mock.get('http://api.macvendors.com/b8:27:eb', text=vendor_string) run_coroutine_threadsafe( tracker.async_see(mac=mac), self.hass.loop).result() assert aioclient_mock.call_count == 1, \ 'No http request for macvendor made!' self.assertEqual(tracker.devices['b827eb000000'].vendor, vendor_string) def test_discovery(self): """Test discovery.""" scanner = get_component('device_tracker.test').SCANNER with patch.dict(device_tracker.DISCOVERY_PLATFORMS, {'test': 'test'}): with patch.object(scanner, 'scan_devices', autospec=True) as mock_scan: with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component( self.hass, device_tracker.DOMAIN, TEST_PLATFORM) fire_service_discovered(self.hass, 'test', {}) self.assertTrue(mock_scan.called) def test_update_stale(self): """Test stalled update.""" scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('DEV1') register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC) scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC) with patch('homeassistant.components.device_tracker.dt_util.utcnow', return_value=register_time): with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'test', device_tracker.CONF_CONSIDER_HOME: 59, }}) self.assertEqual(STATE_HOME, self.hass.states.get('device_tracker.dev1').state) scanner.leave_home('DEV1') with patch('homeassistant.components.device_tracker.dt_util.utcnow', return_value=scan_time): fire_time_changed(self.hass, scan_time) self.hass.block_till_done() self.assertEqual(STATE_NOT_HOME, self.hass.states.get('device_tracker.dev1').state) def test_entity_attributes(self): """Test the entity attributes.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) friendly_name = 'Paulus' picture = 'http://placehold.it/200x200' device = device_tracker.Device( self.hass, timedelta(seconds=180), True, dev_id, None, friendly_name, picture, hide_if_away=True) device_tracker.update_config(self.yaml_devices, dev_id, device) with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) attrs = self.hass.states.get(entity_id).attributes self.assertEqual(friendly_name, attrs.get(ATTR_FRIENDLY_NAME)) self.assertEqual(picture, attrs.get(ATTR_ENTITY_PICTURE)) def test_device_hidden(self): """Test hidden devices.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) device = device_tracker.Device( self.hass, timedelta(seconds=180), True, dev_id, None, hide_if_away=True) device_tracker.update_config(self.yaml_devices, dev_id, device) scanner = get_component('device_tracker.test').SCANNER scanner.reset() with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) self.assertTrue(self.hass.states.get(entity_id) .attributes.get(ATTR_HIDDEN)) def test_group_all_devices(self): """Test grouping of devices.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) device = device_tracker.Device( self.hass, timedelta(seconds=180), True, dev_id, None, hide_if_away=True) device_tracker.update_config(self.yaml_devices, dev_id, device) scanner = get_component('device_tracker.test').SCANNER scanner.reset() with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) state = self.hass.states.get(device_tracker.ENTITY_ID_ALL_DEVICES) self.assertIsNotNone(state) self.assertEqual(STATE_NOT_HOME, state.state) self.assertSequenceEqual((entity_id,), state.attributes.get(ATTR_ENTITY_ID)) @patch('homeassistant.components.device_tracker.DeviceTracker.async_see') def test_see_service(self, mock_see): """Test the see service with a unicode dev_id and NO MAC.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) params = { 'dev_id': 'some_device', 'host_name': 'example.com', 'location_name': 'Work', 'gps': [.3, .8], 'attributes': { 'test': 'test' } } device_tracker.see(self.hass, **params) self.hass.block_till_done() assert mock_see.call_count == 1 self.assertEqual(mock_see.call_count, 1) self.assertEqual(mock_see.call_args, call(**params)) mock_see.reset_mock() params['dev_id'] += chr(233) # e' acute accent from icloud device_tracker.see(self.hass, **params) self.hass.block_till_done() assert mock_see.call_count == 1 self.assertEqual(mock_see.call_count, 1) self.assertEqual(mock_see.call_args, call(**params)) def test_new_device_event_fired(self): """Test that the device tracker will fire an event.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) test_events = [] @callback def listener(event): """Helper method that will verify our event got called.""" test_events.append(event) self.hass.bus.listen("device_tracker_new_device", listener) device_tracker.see(self.hass, 'mac_1', host_name='hello') device_tracker.see(self.hass, 'mac_1', host_name='hello') self.hass.block_till_done() assert len(test_events) == 1 # Assert we can serialize the event json.dumps(test_events[0].as_dict(), cls=JSONEncoder) assert test_events[0].data == { 'entity_id': 'device_tracker.hello', 'host_name': 'hello', } # pylint: disable=invalid-name def test_not_write_duplicate_yaml_keys(self): """Test that the device tracker will not generate invalid YAML.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) device_tracker.see(self.hass, 'mac_1', host_name='hello') device_tracker.see(self.hass, 'mac_2', host_name='hello') self.hass.block_till_done() config = device_tracker.load_config(self.yaml_devices, self.hass, timedelta(seconds=0)) assert len(config) == 2 # pylint: disable=invalid-name def test_not_allow_invalid_dev_id(self): """Test that the device tracker will not allow invalid dev ids.""" with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) device_tracker.see(self.hass, dev_id='hello-world') config = device_tracker.load_config(self.yaml_devices, self.hass, timedelta(seconds=0)) assert len(config) == 0 def test_see_state(self): """Test device tracker see records state correctly.""" self.assertTrue(setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM)) params = { 'mac': 'AA:BB:CC:DD:EE:FF', 'dev_id': 'some_device', 'host_name': 'example.com', 'location_name': 'Work', 'gps': [.3, .8], 'gps_accuracy': 1, 'battery': 100, 'attributes': { 'test': 'test', 'number': 1, }, } device_tracker.see(self.hass, **params) self.hass.block_till_done() config = device_tracker.load_config(self.yaml_devices, self.hass, timedelta(seconds=0)) assert len(config) == 1 state = self.hass.states.get('device_tracker.examplecom') attrs = state.attributes self.assertEqual(state.state, 'Work') self.assertEqual(state.object_id, 'examplecom') self.assertEqual(state.name, 'example.com') self.assertEqual(attrs['friendly_name'], 'example.com') self.assertEqual(attrs['battery'], 100) self.assertEqual(attrs['latitude'], 0.3) self.assertEqual(attrs['longitude'], 0.8) self.assertEqual(attrs['test'], 'test') self.assertEqual(attrs['gps_accuracy'], 1) self.assertEqual(attrs['source_type'], 'gps') self.assertEqual(attrs['number'], 1) def test_see_passive_zone_state(self): """Test that the device tracker sets gps for passive trackers.""" register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC) scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC) with assert_setup_component(1, zone.DOMAIN): zone_info = { 'name': 'Home', 'latitude': 1, 'longitude': 2, 'radius': 250, 'passive': False } setup_component(self.hass, zone.DOMAIN, { 'zone': zone_info }) scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('dev1') with patch('homeassistant.components.device_tracker.dt_util.utcnow', return_value=register_time): with assert_setup_component(1, device_tracker.DOMAIN): assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: { CONF_PLATFORM: 'test', device_tracker.CONF_CONSIDER_HOME: 59, }}) state = self.hass.states.get('device_tracker.dev1') attrs = state.attributes self.assertEqual(STATE_HOME, state.state) self.assertEqual(state.object_id, 'dev1') self.assertEqual(state.name, 'dev1') self.assertEqual(attrs.get('friendly_name'), 'dev1') self.assertEqual(attrs.get('latitude'), 1) self.assertEqual(attrs.get('longitude'), 2) self.assertEqual(attrs.get('gps_accuracy'), 0) self.assertEqual(attrs.get('source_type'), device_tracker.SOURCE_TYPE_ROUTER) scanner.leave_home('dev1') with patch('homeassistant.components.device_tracker.dt_util.utcnow', return_value=scan_time): fire_time_changed(self.hass, scan_time) self.hass.block_till_done() state = self.hass.states.get('device_tracker.dev1') attrs = state.attributes self.assertEqual(STATE_NOT_HOME, state.state) self.assertEqual(state.object_id, 'dev1') self.assertEqual(state.name, 'dev1') self.assertEqual(attrs.get('friendly_name'), 'dev1') self.assertEqual(attrs.get('latitude'), None) self.assertEqual(attrs.get('longitude'), None) self.assertEqual(attrs.get('gps_accuracy'), None) self.assertEqual(attrs.get('source_type'), device_tracker.SOURCE_TYPE_ROUTER) @patch('homeassistant.components.device_tracker._LOGGER.warning') def test_see_failures(self, mock_warning): """Test that the device tracker see failures.""" tracker = device_tracker.DeviceTracker( self.hass, timedelta(seconds=60), 0, []) # MAC is not a string (but added) tracker.see(mac=567, host_name="Number MAC") # No device id or MAC(not added) with self.assertRaises(HomeAssistantError): run_coroutine_threadsafe( tracker.async_see(), self.hass.loop).result() assert mock_warning.call_count == 0 # Ignore gps on invalid GPS (both added & warnings) tracker.see(mac='mac_1_bad_gps', gps=1) tracker.see(mac='mac_2_bad_gps', gps=[1]) tracker.see(mac='mac_3_bad_gps', gps='gps') self.hass.block_till_done() config = device_tracker.load_config(self.yaml_devices, self.hass, timedelta(seconds=0)) assert mock_warning.call_count == 3 assert len(config) == 4 @patch('homeassistant.components.device_tracker.async_log_exception') def test_config_failure(self, mock_ex): """Test that the device tracker see failures.""" with assert_setup_component(0, device_tracker.DOMAIN): setup_component(self.hass, device_tracker.DOMAIN, {device_tracker.DOMAIN: { device_tracker.CONF_CONSIDER_HOME: -1}})
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities of SNLI data and GloVe word vectors for SPINN model. See more details about the SNLI data set at: https://nlp.stanford.edu/projects/snli/ See more details about the GloVe pretrained word embeddings at: https://nlp.stanford.edu/projects/glove/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import math import os import random import numpy as np POSSIBLE_LABELS = ("entailment", "contradiction", "neutral") UNK_CODE = 0 # Code for unknown word tokens. PAD_CODE = 1 # Code for padding tokens. SHIFT_CODE = 3 REDUCE_CODE = 2 WORD_VECTOR_LEN = 300 # Embedding dimensions. LEFT_PAREN = "(" RIGHT_PAREN = ")" PARENTHESES = (LEFT_PAREN, RIGHT_PAREN) def get_non_parenthesis_words(items): """Get the non-parenthesis items from a SNLI parsed sentence. Args: items: Data items from a parsed SNLI sentence, with parentheses. E.g., ["(", "Man", "(", "(", "(", "(", "(", "wearing", "pass", ")", ... Returns: A list of non-parentheses word items, all converted to lower case. E.g., ["man", "wearing", "pass", ... """ return [x.lower() for x in items if x not in PARENTHESES and x] def get_shift_reduce(items): """Obtain shift-reduce vector from a list of items from the SNLI data. Args: items: Data items as a list of str, e.g., ["(", "Man", "(", "(", "(", "(", "(", "wearing", "pass", ")", ... Returns: A list of shift-reduce transitions, encoded as `SHIFT_CODE` for shift and `REDUCE_CODE` for reduce. See code above for the values of `SHIFT_CODE` and `REDUCE_CODE`. """ trans = [] for item in items: if item == LEFT_PAREN: continue elif item == RIGHT_PAREN: trans.append(REDUCE_CODE) else: trans.append(SHIFT_CODE) return trans def pad_and_reverse_word_ids(sentences): """Pad a list of sentences to the common maximum length + 1. Args: sentences: A list of sentences as a list of list of integers. Each integer is a word ID. Each list of integer corresponds to one sentence. Returns: A numpy.ndarray of shape (num_sentences, max_length + 1), wherein max_length is the maximum sentence length (in # of words). Each sentence is reversed and then padded with an extra one at head, as required by the model. """ max_len = max(len(sent) for sent in sentences) for sent in sentences: if len(sent) < max_len: sent.extend([PAD_CODE] * (max_len - len(sent))) # Reverse in time order and pad an extra one. sentences = np.fliplr(np.array(sentences, dtype=np.int64)) sentences = np.concatenate( [np.ones([sentences.shape[0], 1], dtype=np.int64), sentences], axis=1) return sentences def pad_transitions(sentences_transitions): """Pad a list of shift-reduce transitions to the maximum length.""" max_len = max(len(transitions) for transitions in sentences_transitions) for transitions in sentences_transitions: if len(transitions) < max_len: transitions.extend([PAD_CODE] * (max_len - len(transitions))) return np.array(sentences_transitions, dtype=np.int64) def load_vocabulary(data_root): """Load vocabulary from SNLI data files. Args: data_root: Root directory of the data. It is assumed that the SNLI data files have been downloaded and extracted to the "snli/snli_1.0" subdirectory of it. Returns: Vocabulary as a set of strings. Raises: ValueError: If SNLI data files cannot be found. """ snli_path = os.path.join(data_root, "snli") snli_glob_pattern = os.path.join(snli_path, "snli_1.0/snli_1.0_*.txt") file_names = glob.glob(snli_glob_pattern) if not file_names: raise ValueError( "Cannot find SNLI data files at %s. " "Please download and extract SNLI data first." % snli_glob_pattern) print("Loading vocabulary...") vocab = set() for file_name in file_names: with open(os.path.join(snli_path, file_name), "rt") as f: for i, line in enumerate(f): if i == 0: continue items = line.split("\t") premise_words = get_non_parenthesis_words(items[1].split(" ")) hypothesis_words = get_non_parenthesis_words(items[2].split(" ")) vocab.update(premise_words) vocab.update(hypothesis_words) return vocab def load_word_vectors(data_root, vocab): """Load GloVe word vectors for words present in the vocabulary. Args: data_root: Data root directory. It is assumed that the GloVe file has been downloaded and extracted at the "glove/" subdirectory of it. vocab: A `set` of words, representing the vocabulary. Returns: 1. word2index: A dict from lower-case word to row index in the embedding matrix, i.e, `embed` below. 2. embed: The embedding matrix as a float32 numpy array. Its shape is [vocabulary_size, WORD_VECTOR_LEN]. vocabulary_size is len(vocab). WORD_VECTOR_LEN is the embedding dimension (300). Raises: ValueError: If GloVe embedding file cannot be found. """ glove_path = os.path.join(data_root, "glove/glove.42B.300d.txt") if not os.path.isfile(glove_path): raise ValueError( "Cannot find GloVe embedding file at %s. " "Please download and extract GloVe embeddings first." % glove_path) print("Loading word vectors...") word2index = dict() embed = [] embed.append([0] * WORD_VECTOR_LEN) # <unk> embed.append([0] * WORD_VECTOR_LEN) # <pad> word2index["<unk>"] = UNK_CODE word2index["<pad>"] = PAD_CODE with open(glove_path, "rt") as f: for line in f: items = line.split(" ") word = items[0] if word in vocab and word not in word2index: word2index[word] = len(embed) vector = np.array([float(item) for item in items[1:]]) assert (WORD_VECTOR_LEN,) == vector.shape embed.append(vector) embed = np.array(embed, dtype=np.float32) return word2index, embed def calculate_bins(length2count, min_bin_size): """Calculate bin boundaries given a histogram of lengths and minimum bin size. Args: length2count: A `dict` mapping length to sentence count. min_bin_size: Minimum bin size in terms of total number of sentence pairs in the bin. Returns: A `list` representing the right bin boundaries, starting from the inclusive right boundary of the first bin. For example, if the output is [10, 20, 35], it means there are three bins: [1, 10], [11, 20] and [21, 35]. """ bounds = [] lengths = sorted(length2count.keys()) cum_count = 0 for length in lengths: cum_count += length2count[length] if cum_count >= min_bin_size: bounds.append(length) cum_count = 0 if bounds[-1] != lengths[-1]: bounds.append(lengths[-1]) return bounds def encode_sentence(sentence, word2index): """Encode a single sentence as word indices and shift-reduce code. Args: sentence: The sentence with added binary parse information, represented as a string, with all the word items and parentheses separated by spaces. E.g., '( ( The dog ) ( ( is ( playing toys ) ) . ) )'. word2index: A `dict` mapping words to their word indices. Returns: 1. Word indices as a numpy array, with shape `(sequence_len, 1)`. 2. Shift-reduce sequence as a numpy array, with shape `(sequence_len * 2 - 3, 1)`. """ items = [w for w in sentence.split(" ") if w] words = get_non_parenthesis_words(items) shift_reduce = get_shift_reduce(items) word_indices = pad_and_reverse_word_ids( [[word2index.get(word, UNK_CODE) for word in words]]).T return (word_indices, np.expand_dims(np.array(shift_reduce, dtype=np.int64), -1)) class SnliData(object): """A split of SNLI data.""" def __init__(self, data_file, word2index, sentence_len_limit=-1): """SnliData constructor. Args: data_file: Full path to the data file, e.g., "/tmp/spinn-data/snli/snli_1.0/snli_1.0.train.txt" word2index: A dict from lower-case word to row index in the embedding matrix (see `load_word_vectors()` for details). sentence_len_limit: Maximum allowed sentence length (# of words). A value of <= 0 means unlimited. Sentences longer than this limit are currently discarded, not truncated. """ self._labels = [] self._premises = [] self._premise_transitions = [] self._hypotheses = [] self._hypothesis_transitions = [] with open(data_file, "rt") as f: for i, line in enumerate(f): if i == 0: # Skip header line. continue items = line.split("\t") if items[0] not in POSSIBLE_LABELS: continue premise_items = items[1].split(" ") hypothesis_items = items[2].split(" ") premise_words = get_non_parenthesis_words(premise_items) hypothesis_words = get_non_parenthesis_words(hypothesis_items) if (sentence_len_limit > 0 and (len(premise_words) > sentence_len_limit or len(hypothesis_words) > sentence_len_limit)): # TODO(cais): Maybe truncate; do not discard. continue premise_ids = [ word2index.get(word, UNK_CODE) for word in premise_words] hypothesis_ids = [ word2index.get(word, UNK_CODE) for word in hypothesis_words] self._premises.append(premise_ids) self._hypotheses.append(hypothesis_ids) self._premise_transitions.append(get_shift_reduce(premise_items)) self._hypothesis_transitions.append(get_shift_reduce(hypothesis_items)) assert (len(self._premise_transitions[-1]) == 2 * len(premise_words) - 1) assert (len(self._hypothesis_transitions[-1]) == 2 * len(hypothesis_words) - 1) self._labels.append(POSSIBLE_LABELS.index(items[0]) + 1) assert len(self._labels) == len(self._premises) assert len(self._labels) == len(self._hypotheses) assert len(self._labels) == len(self._premise_transitions) assert len(self._labels) == len(self._hypothesis_transitions) def num_batches(self, batch_size): """Calculate number of batches given batch size.""" return int(math.ceil(len(self._labels) / batch_size)) def get_generator(self, batch_size): """Obtain a generator for batched data. All examples of this SnliData object are randomly shuffled, sorted according to the maximum sentence length of the premise and hypothesis sentences in the pair, and batched. Args: batch_size: Desired batch size. Returns: A generator for data batches. The generator yields a 5-tuple: label: An array of the shape (batch_size,). premise: An array of the shape (max_premise_len, batch_size), wherein max_premise_len is the maximum length of the (padded) premise sentence in the batch. premise_transitions: An array of the shape (2 * max_premise_len -3, batch_size). hypothesis: Same as `premise`, but for hypothesis sentences. hypothesis_transitions: Same as `premise_transitions`, but for hypothesis sentences. All the elements of the 5-tuple have dtype `int64`. """ # Randomly shuffle examples. zipped = list(zip( self._labels, self._premises, self._premise_transitions, self._hypotheses, self._hypothesis_transitions)) random.shuffle(zipped) # Then sort the examples by maximum of the premise and hypothesis sentence # lengths in the pair. During training, the batches are expected to be # shuffled. So it is okay to leave them sorted by max length here. (labels, premises, premise_transitions, hypotheses, hypothesis_transitions) = zip( *sorted(zipped, key=lambda x: max(len(x[1]), len(x[3])))) def _generator(): begin = 0 while begin < len(labels): # The sorting above and the batching here makes sure that sentences of # similar max lengths are batched together, minimizing the inefficiency # due to uneven max lengths. The sentences are batched differently in # each call to get_generator() due to the shuffling before sorting # above. The pad_and_reverse_word_ids() and pad_transitions() functions # take care of any remaining unevenness of the max sentence lengths. end = min(begin + batch_size, len(labels)) # Transpose, because the SPINN model requires time-major, instead of # batch-major. yield (labels[begin:end], pad_and_reverse_word_ids(premises[begin:end]).T, pad_transitions(premise_transitions[begin:end]).T, pad_and_reverse_word_ids(hypotheses[begin:end]).T, pad_transitions(hypothesis_transitions[begin:end]).T) begin = end return _generator
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.ops.tensor_array_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session as session_lib from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import gen_data_flow_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import tensor_array_grad from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables import tensorflow.python.ops.nn_grad # pylint: disable=unused-import from tensorflow.python.platform import test def _make_converter(tf_dtype): def _converter(x): if tf_dtype == dtypes.string: # In Python3, np.str is unicode, while we always want bytes return np.asarray(x).astype("|S") x = np.asarray(x).astype(tf_dtype.as_numpy_dtype) if tf_dtype.is_complex: # Add a non-zero imaginary component to x. x -= 1j * x return x return _converter def _make_ta(size, name, dtype=dtypes.float32, infer_shape=False): return tensor_array_ops.TensorArray( dtype=dtype, tensor_array_name=name, size=size, infer_shape=infer_shape) @test_util.run_all_in_graph_and_eager_modes @test_util.with_control_flow_v2 class TensorArrayTest(test.TestCase): @classmethod def setUpClass(cls): super(TensorArrayTest, cls).setUpClass() cls._workers, _ = test.create_local_cluster(num_workers=3, num_ps=0) @classmethod def tearDownClass(cls): super(TensorArrayTest, cls).tearDownClass() session_lib.Session.reset(cls._workers[0].target) @test_util.run_in_graph_and_eager_modes def testTensorArrayWriteRead(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, infer_shape=False) w0 = ta.write(0, [[4.0, 5.0]]) w1 = w0.write(1, [[1.0]]) w2 = w1.write(2, -3.0) r0 = w2.read(0) r1 = w2.read(1) r2 = w2.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual([[4.0, 5.0]], d0) self.assertAllEqual([[1.0]], d1) self.assertAllEqual(-3.0, d2) def _testTensorArrayWritePack(self, tf_dtype): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=tf_dtype, tensor_array_name="foo", size=3) convert = _make_converter(tf_dtype) w0 = ta.write(0, convert([[4.0, 5.0]])) w1 = w0.write(1, convert([[6.0, 7.0]])) w2 = w1.write(2, convert([[8.0, 9.0]])) c0 = w2.stack() c0 = self.evaluate(c0) self.assertAllEqual( convert([[[4.0, 5.0]], [[6.0, 7.0]], [[8.0, 9.0]]]), c0) def _testTensorArrayWritePackMaybeLegacy(self): self._testTensorArrayWritePack(dtypes.float32) self._testTensorArrayWritePack(dtypes.float64) self._testTensorArrayWritePack(dtypes.int32) self._testTensorArrayWritePack(dtypes.int64) self._testTensorArrayWritePack(dtypes.complex64) self._testTensorArrayWritePack(dtypes.complex128) self._testTensorArrayWritePack(dtypes.string) def testTensorArrayWritePack(self): self._testTensorArrayWritePackMaybeLegacy() def testEmptyTensorArrayPack(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) empty_element = np.zeros((0, 1), dtype=np.float32) w0 = ta.write(0, empty_element) w1 = w0.write(1, empty_element) w2 = w1.write(2, empty_element) c0 = w2.stack() c0 = self.evaluate(c0) self.assertAllEqual([3, 0, 1], c0.shape) def _testTensorArrayWriteConcat(self, tf_dtype): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=tf_dtype, tensor_array_name="foo", size=3, infer_shape=False) convert = _make_converter(tf_dtype) w0 = ta.write(0, convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0]])) w1 = w0.write(1, convert([[6.0, 7.0], [106.0, 107.0]])) w2 = w1.write(2, convert([[8.0, 9.0]])) c0 = w2.concat() c0 = self.evaluate(c0) self.assertAllEqual( convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0], [6.0, 7.0], [106.0, 107.0], [8.0, 9.0]]), c0) @test_util.deprecated_graph_mode_only def testTensorArrayWriteConcat(self): self._testTensorArrayWriteConcat(dtypes.float32) self._testTensorArrayWriteConcat(dtypes.float64) self._testTensorArrayWriteConcat(dtypes.int32) self._testTensorArrayWriteConcat(dtypes.int64) self._testTensorArrayWriteConcat(dtypes.complex64) self._testTensorArrayWriteConcat(dtypes.complex128) self._testTensorArrayWriteConcat(dtypes.string) def _testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros(self): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, element_shape=tensor_shape.TensorShape([1, 2])) self.assertAllEqual([[0.0, 0.0]], self.evaluate(ta.read(0))) self.assertAllEqual([[[0.0, 0.0]], [[4.0, 5.0]], [[0.0, 0.0]]], self.evaluate(ta.write(1, [[4.0, 5.0]]).stack())) self.assertAllEqual([[0.0, 0.0], [4.0, 5.0], [0.0, 0.0]], self.evaluate(ta.write(1, [[4.0, 5.0]]).concat())) @test_util.run_v1_only("b/122324791") def testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros(self): self._testTensorArrayReadOrPackNotAllValuesAvailableFillsZeros() def _testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros(self): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) self.assertAllEqual( [[0.0, 0.0]], self.evaluate(ta.write(1, [[4.0, 5.0]]).read(0))) self.assertAllEqual([[[0.0, 0.0]], [[4.0, 5.0]], [[0.0, 0.0]]], self.evaluate(ta.write(1, [[4.0, 5.0]]).stack())) self.assertAllEqual([[0.0, 0.0], [4.0, 5.0], [0.0, 0.0]], self.evaluate(ta.write(1, [[4.0, 5.0]]).concat())) @test_util.run_v1_only("b/122324791") def testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros(self): self._testTensorArrayReadOrPackNotAllValuesAvailableInferShapeFillsZeros() @test_util.run_v1_only("Uses placeholders") def testSkipEagerTensorArrayReadUninitializedInferShapeFillsZeros(self): with self.cached_session(use_gpu=True) as sess: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) val = array_ops.placeholder(dtypes.float32) self.assertAllEqual( [[0.0, 0.0]], sess.run(ta.write(1, val).read(0), {val: [[4.0, 5.0]]})) def _testTensorArrayUnpackRead(self, tf_dtype): with self.cached_session(use_gpu=True): convert = _make_converter(tf_dtype) ta = _make_ta(3, "foo", dtype=tf_dtype) # Unpack a vector into scalars w0 = ta.unstack(convert([1.0, 2.0, 3.0])) r0 = w0.read(0) r1 = w0.read(1) r2 = w0.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual(convert(1.0), d0) self.assertAllEqual(convert(2.0), d1) self.assertAllEqual(convert(3.0), d2) # Unpack a matrix into vectors w1 = ta.unstack(convert([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])) r0 = w1.read(0) r1 = w1.read(1) r2 = w1.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual(convert([1.0, 1.1]), d0) self.assertAllEqual(convert([2.0, 2.1]), d1) self.assertAllEqual(convert([3.0, 3.1]), d2) # Try unpacking an empty matrix, which should not cause an error. w2 = ta.unstack(convert([[], [], []])) r0 = w2.read(0) r1 = w2.read(1) r2 = w2.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual(convert([]), d0) self.assertAllEqual(convert([]), d1) self.assertAllEqual(convert([]), d2) def _testTensorArrayUnpackReadMaybeLegacy(self): self._testTensorArrayUnpackRead(dtypes.float32) self._testTensorArrayUnpackRead(dtypes.float64) self._testTensorArrayUnpackRead(dtypes.int32) self._testTensorArrayUnpackRead(dtypes.int64) self._testTensorArrayUnpackRead(dtypes.complex64) self._testTensorArrayUnpackRead(dtypes.complex128) self._testTensorArrayUnpackRead(dtypes.string) def testTensorArrayUnpackRead(self): self._testTensorArrayUnpackReadMaybeLegacy() def _testTensorArraySplitRead(self, tf_dtype): with self.cached_session(use_gpu=True): convert = _make_converter(tf_dtype) # Split an empty vector ta = _make_ta(3, "foo", dtype=tf_dtype) lengths = constant_op.constant([0, 0, 0]) w0 = ta.split(convert([]), lengths=lengths) r0 = w0.read(0) r1 = w0.read(1) r2 = w0.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual(convert([]), d0) self.assertAllEqual(convert([]), d1) self.assertAllEqual(convert([]), d2) # Split a vector lengths = constant_op.constant([2, 0, 1]) w0 = ta.split(convert([1.0, 2.0, 3.0]), lengths=lengths) r0 = w0.read(0) r1 = w0.read(1) r2 = w0.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual(convert([1.0, 2.0]), d0) self.assertAllEqual(convert([]), d1) self.assertAllEqual(convert([3.0]), d2) # Split a matrix lengths = constant_op.constant([2, 0, 1]) w0 = ta.split( convert([[1.0, 101.0], [2.0, 201.0], [3.0, 301.0]]), lengths=lengths) r0 = w0.read(0) r1 = w0.read(1) r2 = w0.read(2) d0, d1, d2 = self.evaluate([r0, r1, r2]) self.assertAllEqual(convert([[1.0, 101.0], [2.0, 201.0]]), d0) self.assertAllEqual(convert([]).reshape(0, 2), d1) self.assertAllEqual(convert([[3.0, 301.0]]), d2) @test_util.deprecated_graph_mode_only def testTensorArraySplitRead(self): self._testTensorArraySplitRead(dtypes.float32) self._testTensorArraySplitRead(dtypes.float64) self._testTensorArraySplitRead(dtypes.int32) self._testTensorArraySplitRead(dtypes.int64) self._testTensorArraySplitRead(dtypes.complex64) self._testTensorArraySplitRead(dtypes.complex128) self._testTensorArraySplitRead(dtypes.string) @test_util.disable_control_flow_v2("v2 does not support TensorArray.grad.") @test_util.run_v1_only("v2 does not support TensorArray.grad.") def testSkipEagerTensorGradArrayWriteRead(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, infer_shape=False) g_ta = ta.grad("grad") w0 = ta.write(0, [[4.0, 5.0]]) w1 = w0.write(1, [[1.0]]) w2 = w1.write(2, -3.0) g_w0 = g_ta.write(0, [[5.0, 6.0]]) g_w1 = g_w0.write(1, [[2.0]]) g_w2 = g_w1.write(2, -2.0) r0 = w2.read(0) r1 = w2.read(1) r2 = w2.read(2) g_r0 = g_w2.read(0) g_r1 = g_w2.read(1) g_r2 = g_w2.read(2) d0, d1, d2, g_d0, g_d1, g_d2 = session.run([r0, r1, r2, g_r0, g_r1, g_r2]) self.assertAllEqual([[4.0, 5.0]], d0) self.assertAllEqual([[1.0]], d1) self.assertAllEqual(-3.0, d2) self.assertAllEqual([[5.0, 6.0]], g_d0) self.assertAllEqual([[2.0]], g_d1) self.assertAllEqual(-2.0, g_d2) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradGrad(self): if not control_flow_util.ENABLE_CONTROL_FLOW_V2: self.skipTest("Legacy TensorArray does not support double derivatives.") with self.test_session(use_gpu=True) as session: x = constant_op.constant(4.0) ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=1, infer_shape=False) w0 = ta.write(0, x) r0 = w0.read(0) y = r0 * r0 g1 = gradients_impl.gradients(ys=[y], xs=[x]) g2 = gradients_impl.gradients(ys=[g1], xs=[x]) self.assertAllEqual([2.0], session.run(g2)) @test_util.disable_control_flow_v2("v2 does not support TensorArray.grad.") @test_util.run_v1_only("v2 does not support TensorArray.grad.") def testSkipEagerTensorGradArrayDynamicWriteRead(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True, infer_shape=False) w0 = ta.write(0, [[4.0, 5.0]]) w1 = w0.write(1, [[1.0]]) w2 = w1.write(2, -3.0) g_ta = w2.grad("grad") # Get gradient array here so we know the shape s = w2.size() g_s = g_ta.size() g_w0 = g_ta.write(0, [[5.0, 6.0]]) g_w1 = g_w0.write(1, [[2.0]]) g_w2 = g_w1.write(2, -2.0) r0 = w2.read(0) r1 = w2.read(1) r2 = w2.read(2) g_r0 = g_w2.read(0) g_r1 = g_w2.read(1) g_r2 = g_w2.read(2) d0, d1, d2, g_d0, g_d1, g_d2, vs, g_vs = session.run( [r0, r1, r2, g_r0, g_r1, g_r2, s, g_s]) self.assertAllEqual([[4.0, 5.0]], d0) self.assertAllEqual([[1.0]], d1) self.assertAllEqual(-3.0, d2) self.assertAllEqual([[5.0, 6.0]], g_d0) self.assertAllEqual([[2.0]], g_d1) self.assertAllEqual(-2.0, g_d2) self.assertAllEqual(3, vs) self.assertAllEqual(3, g_vs) @test_util.disable_control_flow_v2("v2 does not support TensorArray.grad.") @test_util.run_v1_only("v2 does not support TensorArray.grad.") def testSkipEagerTensorGradAccessTwiceReceiveSameObject(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) g_ta_0 = ta.grad("grad") g_ta_1 = ta.grad("grad") with ops.control_dependencies([g_ta_0.write(0, [[4.0, 5.0]]).flow]): # Write with one gradient handle, read with another copy of it r1_0 = g_ta_1.read(0) t_g_ta_0, t_g_ta_1, d_r1_0 = session.run( [g_ta_0.handle.op, g_ta_1.handle.op, r1_0]) self.assertAllEqual(t_g_ta_0, t_g_ta_1) self.assertAllEqual([[4.0, 5.0]], d_r1_0) def testTensorArrayWriteWrongIndexOrDataTypeFails(self): with self.session(use_gpu=True): ta = _make_ta(3, "foo", dtype=dtypes.float32) # Test writing the wrong datatype if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and not context.executing_eagerly()): error_msg = ("Invalid data types; op elements string but list elements " "float") else: error_msg = ( "TensorArray dtype is (float|float32) but Op is trying to write " "dtype string") with self.assertRaisesOpError(error_msg): self.evaluate(ta.write(0, "wrong_type_scalar").flow) if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and not context.executing_eagerly()): error_msg = "Trying to modify element -1 in a list with 3 elements." else: error_msg = "index -1" with self.assertRaisesOpError(error_msg): self.evaluate(ta.write(-1, 3.0).flow) if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and not context.executing_eagerly()): error_msg = "Trying to modify element 3 in a list with 3 elements" else: error_msg = ("Tried to write to index 3 but array is not " "resizeable and size is: 3") # Test reading from too large an index with self.assertRaisesOpError(error_msg): self.evaluate(ta.write(3, 3.0).flow) def testTensorArrayReadWrongIndexOrDataTypeFails(self): with self.session(use_gpu=True): ta = _make_ta(3, "foo", dtype=dtypes.float32) w0 = ta.write(0, [[4.0, 5.0]]) # Test reading wrong datatype (only possible when constructing graphs). if (not context.executing_eagerly() and not control_flow_util.ENABLE_CONTROL_FLOW_V2): r0_bad = gen_data_flow_ops.tensor_array_read_v3( handle=w0.handle, index=0, dtype=dtypes.float64, flow_in=w0.flow) with self.assertRaisesOpError( "TensorArray dtype is float but Op requested dtype double."): self.evaluate(r0_bad) if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and not context.executing_eagerly()): error_msg = "Trying to access element -1 in a list with 3 elements." else: error_msg = "index -1" # Test reading from a negative index, which is not allowed with self.assertRaisesOpError(error_msg): self.evaluate(ta.read(-1)) if (control_flow_util.ENABLE_CONTROL_FLOW_V2 and not context.executing_eagerly()): error_msg = "Trying to access element 3 in a list with 3 elements." else: error_msg = "Tried to read from index 3 but array size is: 3" # Test reading from too large an index with self.assertRaisesOpError(error_msg): self.evaluate(ta.read(3)) @test_util.disable_control_flow_v2("v2 allows multiple writes.") @test_util.run_v1_only("v2 allows multiple writes.") def testSkipEagerTensorArrayWriteMultipleFails(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) with self.assertRaisesOpError( "Could not write to TensorArray index 2 because " "it has already been written to."): self.evaluate(ta.write(2, 3.0).write(2, 3.0).flow) def testTensorArrayConcatIncompatibleShapesFails(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, infer_shape=False) w1 = ta.write(0, 3.0) w2 = w1.write(1, 4.0) w3 = w2.write(2, [3.0]) with self.assertRaisesOpError( "Concat saw a scalar shape at index 0 but requires at least vectors"): self.evaluate(w3.concat()) ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, infer_shape=False) w1 = ta.write(0, [3.0]) w2 = w1.write(1, [4.0]) w3 = w2.write(2, [[3.0]]) # The exact error messages differ between eager execution and graph # construction as the former bubbles up the error from array_op.concat. error_msg = ("Incompatible ranks" if control_flow_util.ENABLE_CONTROL_FLOW_V2 and not context.executing_eagerly() else "shape") with self.assertRaisesRegexp(errors.InvalidArgumentError, error_msg): self.evaluate(w3.concat()) def testTensorArraySplitIncompatibleShapesFails(self): with self.session(use_gpu=True): in_eager_mode = context.executing_eagerly() ta = _make_ta(3, "foo") with self.assertRaisesOpError( r"Expected lengths to be a vector, received shape: \[\]"): if in_eager_mode: self.evaluate(ta.split([1.0, 2.0, 3.0], 1)) else: lengths = array_ops.placeholder(dtypes.int64) ta.split([1.0, 2.0, 3.0], lengths).flow.eval(feed_dict={lengths: 1}) error_msg = ("Unused values in tensor. Length of tensor: 3 Values used: 1" if control_flow_util.ENABLE_CONTROL_FLOW_V2 and not in_eager_mode else r"Expected sum of lengths to be equal to values.shape\[0\], " r"but sum of lengths is 1 and value's shape is: \[3\]") with self.assertRaisesOpError(error_msg): self.evaluate(ta.split([1.0, 2.0, 3.0], [1]).flow) ta = _make_ta(1, "baz") if control_flow_util.ENABLE_CONTROL_FLOW_V2 and not in_eager_mode: with self.assertRaisesRegexp( ValueError, "Shape must be at least rank 1 but is rank 0"): self.evaluate(ta.split(1.0, [1]).flow) else: with self.assertRaisesOpError( r"Expected value to be at least a vector, but received shape: \[\]" ): self.evaluate(ta.split(1.0, [1]).flow) if not control_flow_util.ENABLE_CONTROL_FLOW_V2 or in_eager_mode: ta = _make_ta(2, "buz") with self.assertRaisesOpError( r"TensorArray's size is not equal to the size of lengths " r"\(2 vs. 1\), and the TensorArray is not marked as " r"dynamically resizeable"): self.evaluate(ta.split([1.0], [1]).flow) def _testTensorArrayWriteGradientAddMultipleAdds(self, dtype): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtype, tensor_array_name="foo", size=3, infer_shape=False) ta_grad = ta.grad("grad") c = lambda x: np.asarray(x, dtype=dtype.as_numpy_dtype) w0 = ta.write(2, c(3.0)) w1 = w0.write(2, c(4.0)) w0_grad = ta_grad.write(2, c(3.0)) w1_grad = w0_grad.write(2, c(4.0)) w2_grad = w1_grad.write(2, c(5.0)) # Assert that aggregation works correctly self.assertAllEqual(c(12.00), w2_grad.read(2).eval()) # Assert that if multiple_writes_aggregate is not enabled, # multiple writes raise an exception. with self.assertRaisesOpError( r"TensorArray foo_.*: Could not write to TensorArray index 2 because " r"it has already been written to."): w1.flow.eval() # Using differing shapes causes an exception wb0_grad = ta_grad.write(1, c(1.0)) wb1_grad = wb0_grad.write(1, c([1.0])) with self.assertRaisesOpError( r"Could not aggregate to TensorArray index 1 because the " r"existing shape is \[\] but the new input shape is \[1\]"): wb1_grad.flow.eval() @test_util.disable_control_flow_v2("v2 does not support TensorArray.grad.") @test_util.run_v1_only("v2 does not support TensorArray.grad.") def testSkipEagerTensorArrayWriteGradientAddMultipleAdds(self): for dtype in (dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128): self._testTensorArrayWriteGradientAddMultipleAdds(dtype) @test_util.disable_control_flow_v2("Low level legacy TA op test.") @test_util.run_v1_only("Low level legacy TA op test.") def testSkipEagerTensorArrayGradWithShapeKnownElementShape(self): with self.session(use_gpu=True) as sess: ta = tensor_array_ops.TensorArray( size=3, dtype=dtypes.float32, element_shape=tensor_shape.TensorShape([2, 3])) handle, flow = data_flow_ops.tensor_array_grad_with_shape( handle=ta.handle, flow_in=ta.flow, shape_to_prepend=tensor_shape.TensorShape([4, 5]), source="source") ta_grad = tensor_array_ops.TensorArray( dtypes.float32, handle=handle, flow=flow) value = array_ops.placeholder(dtypes.float32) ta_grad = ta_grad.write(0, value) read_value = ta_grad.read(0) # Make sure shape inference worked. self.assertAllEqual([None, None, 2, 3], read_value.shape.as_list()) # Writing with wrong shape should not work. with self.assertRaisesRegexp(errors.InvalidArgumentError, "Could not write to TensorArray"): fed_value = np.random.random([2, 3]) sess.run(read_value, feed_dict={value: fed_value}) # Writing with correct shape should work. fed_value = np.random.random([4, 5, 2, 3]) self.assertAllClose(fed_value, sess.run(read_value, feed_dict={value: fed_value})) @test_util.disable_control_flow_v2("Low level legacy TA op test.") @test_util.run_v1_only("Low level legacy TA op test.") def testSkipEagerTensorArrayGradWithShapeUnknownElementShape(self): with self.session(use_gpu=True) as sess: ta = tensor_array_ops.TensorArray( size=3, dtype=dtypes.float32, element_shape=None) # Note that element_shape is unknown handle, flow = data_flow_ops.tensor_array_grad_with_shape( handle=ta.handle, flow_in=ta.flow, shape_to_prepend=tensor_shape.TensorShape([4, 5]), source="source") ta_grad = tensor_array_ops.TensorArray( dtypes.float32, handle=handle, flow=flow) value = array_ops.placeholder(dtypes.float32) ta_grad = ta_grad.write(0, value) read_value = ta_grad.read(0) # Make sure shape inference worked. self.assertIsNone(read_value.shape.ndims) # Write with some shape and check read value. fed_value = np.random.random([4, 5, 7]) self.assertAllClose(fed_value, sess.run(read_value, feed_dict={value: fed_value})) def testMultiTensorArray(self): with self.session(use_gpu=True): h1 = tensor_array_ops.TensorArray( size=1, dtype=dtypes.float32, tensor_array_name="foo") w1 = h1.write(0, 4.0) r1 = w1.read(0) h2 = tensor_array_ops.TensorArray( size=1, dtype=dtypes.float32, tensor_array_name="bar") w2 = h2.write(0, 5.0) r2 = w2.read(0) r = r1 + r2 val = self.evaluate(r) self.assertAllClose(9.0, val) def _testTensorArrayGradientWriteReadType(self, dtype): with self.cached_session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.as_dtype(dtype), tensor_array_name="foo", size=3, infer_shape=False) c = lambda x: np.array(x, dtype=dtype) value_0 = constant_op.constant(c([[4.0, 5.0]])) value_1 = constant_op.constant(c(3.0)) w0 = ta.write(0, value_0) w1 = w0.write(1, value_1) r0 = w1.read(0) r1 = w1.read(1) r0_2 = w1.read(0) # Test individual components' gradients grad_just_r0 = gradients_impl.gradients( ys=[r0], xs=[value_0], grad_ys=[c([[2.0, 3.0]])]) grad_just_r0_vals = session.run(grad_just_r0) self.assertAllEqual(c([[2.0, 3.0]]), grad_just_r0_vals[0]) grad_r0_r0_2 = gradients_impl.gradients( ys=[r0, r0_2], xs=[value_0], grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]])]) grad_r0_r0_2_vals = session.run(grad_r0_r0_2) self.assertAllEqual(c([[3.0, 2.0]]), grad_r0_r0_2_vals[0]) grad_just_r1 = gradients_impl.gradients( ys=[r1], xs=[value_1], grad_ys=[c(-2.0)]) grad_just_r1_vals = session.run(grad_just_r1) self.assertAllEqual(c(-2.0), grad_just_r1_vals[0]) # Test combined gradients grad = gradients_impl.gradients( ys=[r0, r0_2, r1], xs=[value_0, value_1], grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]]), c(-2.0)]) grad_vals = session.run(grad) self.assertEqual(len(grad_vals), 2) self.assertAllEqual(c([[3.0, 2.0]]), grad_vals[0]) self.assertAllEqual(c(-2.0), grad_vals[1]) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradientWriteRead(self): for dtype in (np.float32, np.float64, np.complex64, np.complex128): self._testTensorArrayGradientWriteReadType(dtype) def _testTensorArrayGradientWritePackConcatAndRead(self): with self.cached_session(use_gpu=True) as sess: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=2, clear_after_read=False) value_0 = constant_op.constant([-1.0, 1.0]) value_1 = constant_op.constant([-10.0, 10.0]) w0 = ta.write(0, value_0) w1 = w0.write(1, value_1) p0 = w1.stack() r0 = w1.read(0) s0 = w1.concat() # Test gradient accumulation between read(0), pack(), and concat() with ops.control_dependencies([p0, r0, s0]): grad_r = gradients_impl.gradients( ys=[p0, r0, s0], xs=[value_0, value_1], grad_ys=[ [[2.0, 3.0], [4.0, 5.0]], # pack gradient [-0.5, 1.5], # read(0) gradient [20.0, 30.0, 40.0, 50.0] ]) # concat gradient grad_vals = self.evaluate(grad_r) # 2 + 2 entries self.assertAllClose([2.0 - 0.5 + 20.0, 3.0 + 1.5 + 30.0], grad_vals[0]) self.assertAllEqual([4.0 + 40.0, 5.0 + 50.0], grad_vals[1]) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradientWritePackConcatAndRead(self): self._testTensorArrayGradientWritePackConcatAndRead() @test_util.disable_control_flow_v2("v2 does not support clear_after_read.") @test_util.run_v1_only("v2 does not support clear_after_read.") def testTensorArrayReadTwice(self): with self.session(use_gpu=True): value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) ta_readonce = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=2) w_readonce = ta_readonce.unstack(value) r0_readonce = w_readonce.read(0) with self.assertRaisesOpError( r"Could not read index 0 twice because it was cleared after a " r"previous read \(perhaps try setting clear_after_read = false\?\)"): with ops.control_dependencies([r0_readonce]): self.evaluate(w_readonce.read(0)) ta_readtwice = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=2, clear_after_read=False) w_readtwice = ta_readtwice.unstack(value) r0_readtwice = w_readtwice.read(0) with ops.control_dependencies([r0_readtwice]): r1_readtwice = w_readtwice.read(0) self.assertAllEqual([1.0, -1.0], self.evaluate(r1_readtwice)) def _testTensorArrayGradientUnpackRead(self): with self.cached_session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=2, clear_after_read=False) value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) w = ta.unstack(value) r0 = w.read(0) r0_1 = w.read(0) r1 = w.read(1) # Test combined gradients + aggregation of read(0) grad = gradients_impl.gradients( ys=[r0, r0_1, r1], xs=[value], grad_ys=[[2.0, 3.0], [-1.5, 1.5], [4.0, 5.0]]) grad_vals = session.run(grad) self.assertEqual(len(grad_vals), 1) self.assertAllEqual([[2.0 - 1.5, 3.0 + 1.5], [4.0, 5.0]], grad_vals[0]) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradientUnpackRead(self): self._testTensorArrayGradientUnpackRead() @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradientSplitConcat(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=2, infer_shape=False) value = constant_op.constant( [[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]]) w = ta.split(value, [2, 1]) r = w.concat() # Test combined gradients grad = gradients_impl.gradients( ys=[r], xs=[value], grad_ys=[[[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]]]) grad_vals = session.run(grad) self.assertEqual(len(grad_vals), 1) self.assertAllEqual([[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]], grad_vals[0]) def _testTensorArrayGradientDynamicUnpackRead(self): with self.cached_session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True) value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) w = ta.unstack(value) r0 = w.read(0) r1 = w.read(1) # Test combined gradients + aggregation of read(0) grad = gradients_impl.gradients( ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]]) grad_vals = session.run(grad) self.assertEqual(len(grad_vals), 1) self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0]) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradientDynamicUnpackRead(self): self._testTensorArrayGradientDynamicUnpackRead() def testCloseTensorArray(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) self.evaluate(ta.close()) def testSizeTensorArray(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) s = ta.size() self.assertAllEqual(3, self.evaluate(s)) def testWriteCloseTensorArray(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, infer_shape=False) w0 = ta.write(0, [[4.0, 5.0]]) w1 = w0.write(1, [3.0]) self.evaluate(w1.close()) # Expected to run without problems def _testWhileLoopWritePackGradients(self, dynamic_size, dtype): np_dtype = dtype.as_numpy_dtype with self.cached_session(use_gpu=True): def func(v0, state0, var): ta = tensor_array_ops.TensorArray( dtype=dtype, tensor_array_name="foo", size=0 if dynamic_size else 3, dynamic_size=dynamic_size) time_0 = array_ops.identity(0) def body(time, ta_t, state): sliced = array_ops.slice( v0, begin=array_ops.stack([time, 0]), size=[1, -1]) sliced = array_ops.squeeze(sliced) out = sliced + var + state state += sliced ta_t = ta_t.write(time, out) return (time + 1, ta_t, state) (unused_0, h_final, unused_2) = control_flow_ops.while_loop( cond=lambda time, unused_1, unused_2: time < 3, body=body, loop_vars=(time_0, ta, state0), shape_invariants=(time_0.get_shape(), tensor_shape.unknown_shape(), tensor_shape.unknown_shape()), parallel_iterations=3) vout = h_final.stack() return vout v0 = array_ops.identity(np.arange(3 * 5, dtype=np_dtype).reshape(3, 5)) state0 = array_ops.identity(np.array([1] * 5, dtype=np_dtype)) init_val = np.arange(100, 105, dtype=np_dtype) var = variable_scope.get_variable( "var", shape=init_val.shape, dtype=np_dtype, initializer=init_ops.constant_initializer(init_val)) vout = func(v0, state0, var) grad_val = -np.arange(3 * 5, dtype=np_dtype).reshape(3, 5) if context.executing_eagerly(): grad_fn = backprop.gradients_function(func) v0_grad, state0_grad, var_grad = grad_fn(v0, state0, var, dy=grad_val) else: v0_grad = gradients_impl.gradients([vout], [v0], [grad_val])[0] state0_grad = gradients_impl.gradients([vout], [state0], [grad_val])[0] var_grad = gradients_impl.gradients([vout], [var], [grad_val])[0] self.evaluate(variables.global_variables_initializer()) state0_t, var_t, v0_t, vout_t, v0_grad_t, var_grad_t, state0_grad_t = ( self.evaluate( ([state0, var, v0, vout, v0_grad, var_grad, state0_grad]))) just_v0_grad_t = self.evaluate(v0_grad) # state = [ state0 | state0 + v0[0] | state0 + v0[0] + v0[1] ] # vout = [ v0[0] + var + state[0] | # v0[1] + var + state[1] | # v0[2] + var + state[2] ] # = [ v0[0] + var + state0 | # v0[1] + var + state0 + v0[0] | # v0[2] + var + state0 + v0[0] + v0[1] ] # # d(vout[0])/d(v0) = [1 | 0 | 0 ] # d(vout[1])/d(v0) = [1 | 1 | 0 ] # d(vout[2])/d(v0) = [1 | 1 | 1 ] # d(vout)/d(var) = [1 | 1 | 1] # d(vout)/d(state0) = [ 1 | 1 | 1 ] state_per_time = np.array( [state0_t, state0_t + v0_t[0, :], state0_t + v0_t[0, :] + v0_t[1, :]]) # Compare forward prop self.assertAllClose(v0_t + var_t + state_per_time, vout_t) # Compare backward prop expected_v0_grad_t = np.array([ grad_val[0, :] + grad_val[1, :] + grad_val[2, :], grad_val[1, :] + grad_val[2, :], grad_val[2, :] ]) self.assertAllEqual(expected_v0_grad_t, v0_grad_t) self.assertAllEqual(expected_v0_grad_t, just_v0_grad_t) self.assertAllClose(grad_val.sum(axis=0), var_grad_t) self.assertAllClose(grad_val.sum(axis=0), state0_grad_t) def testWhileLoopWritePackGradients(self): self._testWhileLoopWritePackGradients( dynamic_size=False, dtype=dtypes.float32) # TODO(ebrevdo): re-enable when While supports non-float32 gradients. # self._testWhileLoopWritePackGradients( # dynamic_size=False, dtype=tf.int64) @test_util.run_v1_only("b/117943489") def testSkipEagerWhileLoopDynamicWritePackGradients(self): self._testWhileLoopWritePackGradients( dynamic_size=True, dtype=dtypes.float32) def testGradSerialTwoLoops(self): with self.session(use_gpu=True): def loop(x): num_steps = 100 acc = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=num_steps, clear_after_read=False, element_shape=tensor_shape.scalar()) i = constant_op.constant(0, name="i") c = lambda i, acc: i < 5 def b(i, acc): x1 = control_flow_ops.cond( math_ops.equal(i, 0), lambda: x, lambda: math_ops.multiply(acc.read(i - 1), 2.0)) return i + 1, acc.write(i, x1) i1, acc1 = control_flow_ops.while_loop(c, b, [i, acc]) z = constant_op.constant(0.0) def fn(i, acc): return i + 1, acc.write(i, z) _, acc2 = control_flow_ops.while_loop(lambda i, acc: i < num_steps, fn, [i1, acc1]) r = acc2.stack() return r x = constant_op.constant(2.0, name="x") if context.executing_eagerly(): grad = backprop.gradients_function(loop)(x)[0] else: grad = gradients_impl.gradients(loop(x), [x])[0] self.assertAllClose(31.0, self.evaluate(grad)) @test_util.deprecated_graph_mode_only def testSkipEagerSumOfTwoReadVariablesWithoutRepeatGrad(self): with self.session(use_gpu=True) as session: a = array_ops.identity( np.arange( 3 * 5, dtype=np.float32).reshape(3, 5) + 1) b = array_ops.identity( np.arange( 3 * 5, dtype=np.float32).reshape(3, 5) + 1 + 3 * 5) ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) ta = ta.write(0, a, name="write_a") ta = ta.write(1, b, name="write_b") c = ( ta.read( 0, name="read_a_0") + # a + b ta.read( 1, name="read_b_0")) g0 = -(np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1) grad_a = gradients_impl.gradients([c], [a], [g0])[0] # d(a+b)/da = 1 grad_b = gradients_impl.gradients([c], [b], [g0])[0] # d(a+b)/db = 1 # Test gradients calculated individually grad_a_t, = session.run([grad_a]) self.assertAllEqual(grad_a_t, g0) grad_b_t, = session.run([grad_b]) self.assertAllEqual(grad_b_t, g0) # Test gradients calculated jointly joint_grad_a_t, joint_grad_b_t = session.run([grad_a, grad_b]) self.assertAllEqual(joint_grad_a_t, g0) self.assertAllEqual(joint_grad_b_t, g0) def _grad_source_for_name(self, name): return tensor_array_grad._GetGradSource(constant_op.constant(0, name=name)) @test_util.deprecated_graph_mode_only def testSkipEagerGetGradSource_Invalid(self): with self.assertRaises(ValueError): self._grad_source_for_name("") with self.assertRaises(ValueError): self._grad_source_for_name("foo") with self.assertRaises(ValueError): self._grad_source_for_name("foo/bar") @test_util.deprecated_graph_mode_only def testSkipEagerGetGradSource_NoEnclosingScope(self): self.assertEqual("gradients:0", self._grad_source_for_name("gradients")) self.assertEqual("gradients_0:0", self._grad_source_for_name("gradients_0")) self.assertEqual("gradients", self._grad_source_for_name("gradients/foo")) self.assertEqual("gradients_0", self._grad_source_for_name("gradients_0/foo")) self.assertEqual("gradients", self._grad_source_for_name("gradients/foo/bar")) self.assertEqual("gradients_0", self._grad_source_for_name("gradients_0/foo/bar")) @test_util.deprecated_graph_mode_only def testSkipEagerGetGradSource_EnclosingScope(self): self.assertEqual("foo/gradients:0", self._grad_source_for_name("foo/gradients")) self.assertEqual("foo/gradients_0:0", self._grad_source_for_name("foo/gradients_0")) self.assertEqual("foo/gradients", self._grad_source_for_name("foo/gradients/bar")) self.assertEqual("foo/gradients_0", self._grad_source_for_name("foo/gradients_0/bar")) self.assertEqual("foo/bar/gradients", self._grad_source_for_name("foo/bar/gradients/baz")) self.assertEqual("foo/bar/gradients_0", self._grad_source_for_name("foo/bar/gradients_0/baz")) @test_util.deprecated_graph_mode_only def testSkipEagerGetGradSource_NestedUsesInnermost(self): self.assertEqual( "foo/gradients/bar/gradients_0", self._grad_source_for_name("foo/gradients/bar/gradients_0/baz")) @test_util.deprecated_graph_mode_only def testSkipEagerWriteShape(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) c0 = constant_op.constant([4.0, 5.0]) w0 = ta.write(0, c0) r0 = w0.read(0) self.assertAllEqual(c0.get_shape(), r0.get_shape()) ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) c1 = constant_op.constant([6.0, 7.0]) w1 = w0.write(1, c1) r0 = w1.read(0) r1 = w1.read(1) self.assertAllEqual(c0.get_shape(), r0.get_shape()) self.assertAllEqual(c1.get_shape(), r1.get_shape()) ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3) c2 = constant_op.constant([4.0, 5.0, 6.0]) with self.assertRaises(ValueError): w0.write(0, c2) @test_util.deprecated_graph_mode_only def testSkipEagerPartlyUnknownShape(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=6) c0 = array_ops.placeholder(dtypes.float32, [None, None, None, 3]) w0 = ta.write(0, c0) r0 = w0.read(0) self.assertAllEqual([None, None, None, 3], r0.get_shape().as_list()) c1 = array_ops.placeholder(dtypes.float32, [None, None, None, 3]) w1 = w0.write(1, c1) r1 = w1.read(0) self.assertAllEqual([None, None, None, 3], r1.get_shape().as_list()) # Writing less specific shape (doesn't change type.) c2 = array_ops.placeholder(dtypes.float32, [None, None, None, None]) w2 = w1.write(2, c2) r2 = w2.read(0) self.assertAllEqual([None, None, None, 3], r2.get_shape().as_list()) # Writing more specific shape in one dimension and less specific in # another. c3 = array_ops.placeholder(dtypes.float32, [None, None, 2, None]) w3 = w2.write(3, c3) r3 = w3.read(0) self.assertAllEqual([None, None, 2, 3], r3.get_shape().as_list()) # Writing partly defined shape using TensorArray.scatter. c4 = array_ops.placeholder(dtypes.float32, [2, None, 4, 2, 3]) w4 = w3.scatter([4, 5], c4) r4 = w4.read(0) self.assertAllEqual([None, 4, 2, 3], r4.get_shape().as_list()) # Writing fully defined shape using TensorArray.split. c5 = array_ops.placeholder(dtypes.float32, [10, 4, 2, 3]) w5 = w4.split(c5, constant_op.constant([5, 5])) r5 = w5.read(0) self.assertAllEqual([5, 4, 2, 3], r5.get_shape().as_list()) def _testUnpackShape(self): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True, infer_shape=True) value = constant_op.constant( [[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]]) w0 = ta.unstack(value) r0 = w0.read(0) self.assertAllEqual((2,), r0.get_shape()) c1 = constant_op.constant([4.0, 5.0]) w1 = w0.write(3, c1) if not control_flow_util.ENABLE_CONTROL_FLOW_V2: # TensorArray v2 does not support clear_after_read. with self.assertRaisesOpError( r"Could not read index 0 twice because it was cleared after a " r"previous read \(perhaps try setting clear_after_read = false\?\)" ): with ops.control_dependencies([r0]): self.evaluate(w1.read(0)) r1 = w1.read(1) self.assertAllEqual(c1.get_shape(), r1.shape) c2 = constant_op.constant([4.0, 5.0, 6.0]) with self.assertRaises(ValueError): w1.write(4, c2) @test_util.run_v1_only("b/117943489") def testUnpackShape(self): self._testUnpackShape() @test_util.deprecated_graph_mode_only def testSplitShape(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True, infer_shape=True) value = constant_op.constant([[1.0, -1.0], [2.0, -2.0], [3.0, -3.0]]) w0 = ta.split(value, [1, 1, 1]) r0 = w0.read(0) self.assertAllEqual((1, 2), r0.get_shape()) ta1 = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo1", size=0, dynamic_size=True, infer_shape=True) w0 = ta1.split(value, [1, 2]) r0 = w0.read(0) if context.executing_eagerly(): self.assertEqual((1, 2), r0.get_shape()) self.assertEqual((2, 2), w0.read(1).get_shape()) else: self.assertEqual(r0.get_shape().ndims, None) if not control_flow_util.ENABLE_CONTROL_FLOW_V2: self.assertEqual( tensor_shape.TensorShape( ta1.handle.op.get_attr("element_shape")).ndims, None) @test_util.deprecated_graph_mode_only def testSkipEagerWriteUnknownShape(self): with self.session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=3, infer_shape=True) c0 = array_ops.placeholder(dtypes.float32) w0 = ta.write(0, c0) r0 = w0.read(0) self.assertAllEqual(r0.get_shape(), tensor_shape.unknown_shape()) def _testGradientWhenNotAllComponentsRead(self): with self.cached_session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) x = constant_op.constant([2.0, 3.0]) w = ta.unstack(x) r0 = w.read(0) # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0). grad_r0 = gradients_impl.gradients(ys=[r0], xs=[x], grad_ys=[1.0]) grad_r0_vals = session.run(grad_r0)[0] self.assertAllEqual(grad_r0_vals, [1.0, 0.0]) @test_util.deprecated_graph_mode_only def testSkipEagerGradientWhenNotAllComponentsRead(self): self._testGradientWhenNotAllComponentsRead() @test_util.deprecated_graph_mode_only def testSkipEagerWriteButNotAllComponentsReadGrad(self): with self.cached_session(use_gpu=True) as session: x0 = constant_op.constant(5.0) x1 = constant_op.constant(10.0) ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=2).write(0, x0).write(1, x1) r0 = ta.read(0) # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0). grad_r0_x1 = gradients_impl.gradients(ys=[r0], xs=[x0, x1], grad_ys=[1.0]) grad_r0_x1_vals = session.run(grad_r0_x1) self.assertAllEqual(grad_r0_x1_vals, [1.0, 0.0]) def _testTensorArrayUnpackDynamic(self): with self.cached_session(use_gpu=True) as sess: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=3, dynamic_size=True) x = constant_op.constant([1.0, 2.0, 3.0]) w0 = ta.unstack(x) w1 = w0.write(3, 4.0) r = w1.stack() self.assertAllEqual(np.array([1.0, 2.0, 3.0, 4.0]), self.evaluate(r)) grad = gradients_impl.gradients(ys=[r], xs=[x]) self.assertAllEqual(np.array([1.0, 1.0, 1.0]), self.evaluate(grad)[0]) @test_util.run_v1_only("b/117943489") def testSkipEagerTensorArrayUnpackDynamic(self): self._testTensorArrayUnpackDynamic() @test_util.run_v1_only("b/117943489") def testSkipEagerTensorArraySplitDynamic(self): with self.session(use_gpu=True) as sess: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=3, dynamic_size=True) x = constant_op.constant([1.0, 2.0, 3.0]) w0 = ta.split(x, [1, 1, 1]) w1 = w0.write(3, [4.0]) r = w1.concat() self.assertAllEqual(np.array([1.0, 2.0, 3.0, 4.0]), self.evaluate(r)) grad = gradients_impl.gradients(ys=[r], xs=[x]) self.assertAllEqual(np.array([1.0, 1.0, 1.0]), self.evaluate(grad)[0]) def _testTensorArrayEvalEmpty(self): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=0, dynamic_size=False, infer_shape=False) v2_msg = ("Tried to stack elements of an empty list with " "non-fully-defined element_shape") v1_msg = ( "TensorArray has size zero, but element shape <unknown> is not " "fully defined. Currently only static shapes are supported when " "packing zero-size TensorArrays.") with self.assertRaisesOpError( v2_msg if control_flow_util.ENABLE_CONTROL_FLOW_V2 else v1_msg): ta.stack().eval() @test_util.run_v1_only("b/120545219") def testSkipEagerTensorArrayEvalEmpty(self): self._testTensorArrayEvalEmpty() # this test is ill-defined for Eager mode --- unpacking an empty tensor # gives an empty list / there is not equivalent of "mark_used" in Eager def _testTensorArrayEvalEmptyWithDefault(self): with self.cached_session(use_gpu=True): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=0, dynamic_size=False, infer_shape=True) self.assertEqual(0, ta.size().eval()) # Don't actually perform the pack. This stores the static shape. if control_flow_util.ENABLE_CONTROL_FLOW_V2: ta = ta.unstack(array_ops.zeros([0, 3, 5])) else: ta.unstack(array_ops.zeros([0, 3, 5])).mark_used() packed = ta.stack() concatenated = ta.concat() self.assertAllEqual([0, 3, 5], self.evaluate(packed).shape) # Concatenating zero tensors along their first dimension gives a # first dimension of zero self.assertAllEqual([0, 5], self.evaluate(concatenated).shape) @test_util.run_v1_only("b/117943489") def testSkipEagerTensorArrayEvalEmptyWithDefault(self): self._testTensorArrayEvalEmptyWithDefault() @test_util.run_v1_only("b/117943489") def testSkipEagerTensorArrayScatterReadAndGradients(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True) indices = constant_op.constant([1, 8]) value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) w = ta.scatter(indices, value) r0 = w.read(1) r1 = w.read(8) # Test combined gradients + aggregation of read(0) grad = gradients_impl.gradients( ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]]) read_vals, grad_vals = session.run([[r0, r1], grad]) self.assertEqual(len(read_vals), 2) self.assertEqual(len(grad_vals), 1) self.assertAllEqual([1.0, -1.0], read_vals[0]) self.assertAllEqual([10.0, -10.0], read_vals[1]) self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0]) @test_util.run_v1_only("b/117943489") def testSkipEagerTensorArrayScatterPartialReadAndGradients(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True) indices = constant_op.constant([1, 8]) value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) w = ta.scatter(indices, value) r0 = w.read(1) # Test combined gradients + aggregation of read(0) grad = gradients_impl.gradients( ys=[r0], xs=[value], grad_ys=[[2.0, 3.0]])[0] read_val, grad_val = session.run([r0, grad]) self.assertAllEqual([1.0, -1.0], read_val) self.assertAllEqual([[2.0, 3.0], [0.0, 0.0]], grad_val) def testScatterIntoExistingList(self): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=5) ta = ta.scatter(indices=[3, 4], value=array_ops.ones([2])) self.assertAllEqual(ta.stack(), [0., 0., 0., 1., 1.]) ta = ta.scatter(indices=[1], value=array_ops.ones([1])) self.assertAllEqual(ta.stack(), [0., 1., 0., 1., 1.]) ta = ta.scatter(indices=[0, 2], value=[5., 6.]) self.assertAllEqual(ta.stack(), [5., 1., 6., 1., 1.]) @test_util.run_v1_only("b/118890905") def testTensorArrayWriteGatherAndGradients(self): with self.session(use_gpu=True) as session: ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, tensor_array_name="foo", size=0, dynamic_size=True) def func(values): indices = constant_op.constant([1, 8]) w = ta.unstack(values) g = w.gather(indices) return g values = constant_op.constant([[1.0 * x, -1.0 * x] for x in range(10)]) g = func(values) grad_ys = [[[2.0, 3.0], [4.0, 5.0]]] # Test combined gradients + aggregation of read(0) if context.executing_eagerly(): g_vals = [g] grad_vals = backprop.gradients_function(func)( values, dy=constant_op.constant(grad_ys[0], dtype=dtypes.float32)) else: grad = gradients_impl.gradients(ys=[g], xs=[values], grad_ys=grad_ys) g_vals, grad_vals = session.run([[g], grad]) # Gradients for 8 of the 10 unread components are zero. expected_grad = np.zeros((10, 2)) expected_grad[1] = [2.0, 3.0] expected_grad[8] = [4.0, 5.0] self.assertEqual(len(g_vals), 1) self.assertEqual(len(grad_vals), 1) self.assertAllEqual([[1.0, -1.0], [8.0, -8.0]], g_vals[0]) self.assertAllEqual(expected_grad, grad_vals[0]) @test_util.disable_control_flow_v2("colocate_with not supported in v2.") @test_util.run_v1_only("b/120545219") def testSkipEagerTensorArrayGetsDeviceFromFirstWrite(self): with ops.device("/job:worker/task:0/cpu:0"): # this initial device will be ignored. ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) with ops.device("/job:worker/task:1/cpu:0"): # the first write sets the op's device. ta = ta.write(0, 1.0) with ops.device("/job:worker/task:2/cpu:0"): # subsequent writes do not modify the op's device. ta = ta.write(1, 1.0) # The gradient TA will sit on the same device as the forward TA. ta_grad = ta.grad("grad") flows = [ta.flow, ta_grad.flow] # Similar tests for unpack and split with ops.device("/job:worker/task:0/cpu:0"): ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3) with ops.device("/job:worker/task:1/cpu:0"): ta = ta.unstack([1.0, 2.0]) with ops.device("/job:worker/task:2/cpu:0"): ta = ta.write(2, 3.0) flows.append(ta.flow) with ops.device("/job:worker/task:0/cpu:0"): ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) with ops.device("/job:worker/task:1/cpu:0"): ta = ta.split([1.0, 2.0], [1, 1]) flows.append(ta.flow) session = session_lib.Session(self._workers[0].target) run_options = config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE) run_metadata = config_pb2.RunMetadata() session.run(flows, options=run_options, run_metadata=run_metadata) self.assertTrue(run_metadata.HasField("step_stats")) dev_stats = {d.device: d.node_stats for d in run_metadata.step_stats.dev_stats} for d in dev_stats: if "/task:1/" in d: self.assertTrue( [s for s in dev_stats[d] if "/TensorArray" in s.node_name]) elif "/host:CPU" not in d: self.assertFalse( [s for s in dev_stats[d] if "/TensorArray" in s.node_name]) @test_util.disable_control_flow_v2("colocate_with not supported in v2.") @test_util.run_v1_only("b/120545219") def testSkipEagerTensorArrayGetsDeviceFromFirstWriteInWhileLoop(self): with ops.device("/job:worker/task:0/cpu:0"): ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) def _body(i, ta_i): with ops.device("/job:worker/task:1/cpu:0"): return i + 1, ta_i.write(i, constant_op.constant(0.0)) _, ta_out = control_flow_ops.while_loop( lambda i, ta: i < 2, _body, loop_vars=[0, ta]) session = session_lib.Session(self._workers[0].target) run_options = config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE) run_metadata = config_pb2.RunMetadata() session.run(ta_out.flow, options=run_options, run_metadata=run_metadata) self.assertTrue(run_metadata.HasField("step_stats")) dev_stats = {d.device: d.node_stats for d in run_metadata.step_stats.dev_stats} for d in dev_stats: if "/task:1/" in d: self.assertTrue( [s for s in dev_stats[d] if "TensorArray" == s.node_name]) else: self.assertFalse( [s for s in dev_stats[d] if "TensorArray" == s.node_name]) @test_util.disable_control_flow_v2("colocate_with not supported in v2.") @test_util.run_v1_only("b/120545219") def testSkipEagerTensorArrayDisabledColocateWithFirstWriteCall(self): with ops.device("/job:worker/task:0/cpu:0"): ta = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=2, colocate_with_first_write_call=False) def _body(i, ta_i): with ops.device("/job:worker/task:1/cpu:0"): return i + 1, ta_i.write(i, constant_op.constant(0.0)) _, ta_out = control_flow_ops.while_loop( lambda i, ta: i < 2, _body, loop_vars=[0, ta]) session = session_lib.Session(self._workers[0].target) run_options = config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE) run_metadata = config_pb2.RunMetadata() session.run(ta_out.flow, options=run_options, run_metadata=run_metadata) self.assertTrue(run_metadata.HasField("step_stats")) dev_stats = {d.device: list(d.node_stats) for d in run_metadata.step_stats.dev_stats} for d in dev_stats: if "/task:0/" in d and "CPU" in d: # Skip any GPU node stats self.assertTrue( [s for s in dev_stats[d] if "TensorArray" == s.node_name]) else: self.assertFalse( [s for s in dev_stats[d] if "TensorArray" == s.node_name]) def testTensorArrayIdentity(self): with self.session(use_gpu=True): ta0 = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2, infer_shape=False) ta1 = tensor_array_ops.TensorArray(dtype=dtypes.int32, size=4, infer_shape=True) ta0 = ta0.write(0, 0.) ta1 = ta1.write(0, 1) v0 = variable_scope.get_variable( "v0", shape=(), initializer=init_ops.zeros_initializer()) v1 = variable_scope.get_variable( "v1", shape=(), initializer=init_ops.zeros_initializer()) with ops.control_dependencies([v0.assign_add(1)]): ta0 = ta0.identity() with ops.control_dependencies([v1.assign_add(1)]): ta1 = ta1.identity() read0 = ta0.read(0) read1 = ta1.read(0) size0 = ta0.size() size1 = ta1.size() # Tests correct properties on new TensorArrays. self.assertEqual(dtypes.float32, ta0.dtype) self.assertEqual(dtypes.int32, ta1.dtype) if context.executing_eagerly(): self.assertEqual(tensor_shape.scalar(), read0.get_shape()) else: self.assertEqual(tensor_shape.unknown_shape(), read0.get_shape()) self.assertEqual(tensor_shape.scalar(), read1.get_shape()) if not context.executing_eagerly(): self.evaluate(variables.global_variables_initializer()) read0_v, read1_v, size0_v, size1_v = self.evaluate((read0, read1, size0, size1)) # Tests that the control dependencies was added and executed. self.assertEqual(1, self.evaluate(v0)) self.assertEqual(1, self.evaluate(v1)) # Tests correct TensorArray. self.assertEqual(read0_v, 0) self.assertEqual(read1_v, 1) self.assertEqual(size0_v, 2) self.assertEqual(size1_v, 4) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayGradYsInCorrectScope(self): n_time = 1 n_dim = 1 x = constant_op.constant([[1.42]]) dy = constant_op.constant([[2.42]]) ta = tensor_array_ops.TensorArray( dtypes.float32, size=n_time, element_shape=[n_dim]) for t in range(n_time): ta = ta.write(index=t, value=x[t]) y = ta.stack() # dy is outside of the gradients name scope; tf.gradients must # wrap it in the correct name scope. dx, = gradients_impl.gradients(ys=[y], xs=[x], grad_ys=[dy]) with self.cached_session(use_gpu=True) as sess: vdx, vdy = self.evaluate([dx, dy]) self.assertAllClose(vdx, vdy) @test_util.deprecated_graph_mode_only def testSkipEagerTensorArrayInt64GPU(self): if not test.is_gpu_available(): return with self.session(use_gpu=True, force_gpu=True) as sess: value = array_ops.placeholder(dtypes.int64) ta = tensor_array_ops.TensorArray(dtype=dtypes.int64, size=2) ta = ta.scatter([0, 1], value) r0 = ta.read(0) r1 = ta.read(1) v0, v1 = sess.run([r0, r1], feed_dict={value: [-3, 100]}) self.assertAllEqual(v0, -3) self.assertAllEqual(v1, 100) class TensorArrayBenchmark(test.Benchmark): def _benchmarkWriteInWhile(self): ops.reset_default_graph() def write(): size = 10000 ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=size) ta = control_flow_ops.while_loop( lambda i, _: i < size, lambda i, ta: (i + 1, ta.write(i, 0.)), [0, ta], parallel_iterations=1)[1] return ta.stack() op = write() self.run_op_benchmark(session_lib.Session(), op) def benchmarkWriteInWhile(self): self._benchmarkWriteInWhile() @test_util.enable_control_flow_v2 def benchmarkWriteInWhileWithControlFlowV2(self): self._benchmarkWriteInWhile() if __name__ == "__main__": test.main()
#!/usr/bin/python # -*- coding: utf-8 -*- # # FILE: twitterDB.py # # An object for managing a twitter DB # # Copyright by Author. All rights reserved. Not for reuse without # express permissions. # # from sochi.data.db.base.baseDB import BaseDB from sochi.data.db.base.dbManager import DBManager from sochi.data.db.base.tweetObj import tweetObj as TweetObj from sochi.data.db.base.userObj import userObj from sochi.data.db.base.userMetaObj import userMetaObj from sochi.data.db.base.friendObj import friendObj from sochi.data.db.base.followerObj import followerObj from sqlalchemy.orm import mapper, class_mapper from sqlalchemy.orm.exc import UnmappedClassError import sys TWEETS_TABLE_NAME = "twitter_tweets" USER_TABLE_NAME = "twitter_users" USER_META_TABLE_NAME = "twitter_user_meta" FRIENDS_TABLE_NAME = "twitter_friends" FOLLOWERS_TABLE_NAME = "twitter_followers" class TweetsDB(BaseDB): def __init__(self, config = None): BaseDB.__init__(self, config=config) self.db = DBManager(config=config) self.session = self.db.session self.tweet_table = self.db.get_table(TWEETS_TABLE_NAME) self.user_table = self.db.get_table(USER_TABLE_NAME) self.user_meta_table = self.db.get_table(USER_META_TABLE_NAME) self.friends_table = self.db.get_table(FRIENDS_TABLE_NAME) self.followers_table = self.db.get_table(FOLLOWERS_TABLE_NAME) try: self.tweet_mapper = class_mapper(TweetObj) except UnmappedClassError: self.tweet_mapper = mapper(TweetObj,self.tweet_table) try: self.user_mapper = class_mapper(userObj) except UnmappedClassError: self.user_mapper = mapper(userObj,self.user_table) try: self.user_meta_mapper = class_mapper(userMetaObj) except UnmappedClassError: self.user_meta_mapper = mapper(userMetaObj,self.user_meta_table) try: self.friend_mapper = class_mapper(friendObj) except UnmappedClassError: self.friend_mapper = mapper(friendObj,self.friends_table) try: self.follower_mapper = class_mapper(followerObj) except UnmappedClassError: self.follower_mapper = mapper(followerObj,self.followers_table) ## # New object creation routines ## ## Create "tweet" objects and records def new_tweet_table_item(self, rec=None): nto = TweetObj() if( rec ): return nto.from_dict(rec) return nto def tweet_table_item_to_dict(self, tto=None): rec = {} if( tto ): rec = tto.to_dict() return rec ## Create "user" objects and records def new_user_table_item(self, rec=None): uto = userObj() if( rec ): return uto.from_dict(rec) return uto def user_table_item_to_dict(self, uto=None): rec = {} if( uto ): rec = uto.to_dict() return rec ## Create "user_meta" objects and records def new_user_meta_table_item(self, rec=None): umto = userMetaObj() if( rec ): return umto.from_dict(rec) return umto def user_meta_table_item_to_dict(self, umto=None): rec = {} if( umto ): rec = umto.to_dict() return rec ## Create "friend" objects and records def new_friend_table_item(self, rec=None): nf = friendObj() if( rec ): return nf.from_dict(rec) return nf def friend_table_item_to_dict(self, nf=None): rec = {} if( nf ): rec = nf.to_dict() return rec ## Create "follower" objects and records def new_follower_table_item(self, rec=None): nf = followerObj() if( rec ): return nf.from_dict(rec) return nf def follower_table_item_to_dict(self, nf=None): rec = {} if( nf ): rec = nf.to_dict() return rec ## # straight forward query types ## ## ## Query the tweet table ## def query_tweet_table_by_tweet_id(self, tid): t = self.session.query(TweetObj).filter(TweetObj.tweet_id==tid).all() return t def query_tweet_table_by_username(self, uname=None, start_date=None, end_date=None): q = self._tweet_table_date_range(start_date=start_date, end_date=end_date) q = q.filter(TweetObj.from_user==uname) tlist = q.all() return tlist def query_tweet_table_by_user_id(self, uid=None, start_date=None, end_date=None): q = self._tweet_table_date_range(start_date=start_date, end_date=end_date) q = q.filter(TweetObj.from_user_id==uid) tlist = q.all() return tlist def query_tweet_table_by_tweet_substr(self, substr=None, start_date=None, end_date=None): qtext = "%"+substr+"%" q = self._tweet_table_date_range(start_date=start_date, end_date=end_date) q = q.filter(TweetObj.tweet_text.like(qtext)) tlist = q.all() return tlist def query_tweet_table_by_date_range(self, start_date=None, end_date=None, in_order=True): q = self._tweet_table_date_range(start_date=start_date, end_date=end_date) if( in_order ): q = q.order_by(TweetObj.created_at) tlist = q.all() return tlist def _tweet_table_date_range(self, start_date=None, end_date=None): query = self.session.query(TweetObj) if( start_date and end_date ): query = query.filter(TweetObj.created_at>=start_date, TweetObj.created_at<end_date) elif( start_date ): query = query.filter(TweetObj.created_at>=start_date) elif( end_date ): query = query.filter(TweetObj.created_at<end_date) else: pass return query ## ## Query the user table ## def query_user_table_by_fullname(self, sname): tlist = self.session.query(userObj).filter(userObj.screen_name==sname).all() return tlist def query_user_table_by_screenname(self, sname): tlist = self.session.query(userObj).filter(userObj.screen_name==sname).all() return tlist def query_user_table_by_username(self, uname): tlist = self.session.query(userObj).filter(userObj.user_name==uname).all() return tlist def query_user_table_by_user_id(self, uid): tlist = self.session.query(userObj).filter(userObj.user_id==uid).all() return tlist ## ## Query the user_meta table ## def query_user_meta_table_by_fullname(self, sname): tlist = self.session.query(userMetaObj).filter(userMetaObj.screen_name==sname).all() return tlist def query_user_meta_table_by_screenname(self, sname): tlist = self.session.query(userMetaObj).filter(userMetaObj.screen_name==sname).all() return tlist def query_user_meta_table_by_username(self, uname): tlist = self.session.query(userMetaObj).filter(userMetaObj.user_name==uname).all() return tlist def query_user_meta_table_by_user_id(self, uid): tlist = self.session.query(userMetaObj).filter(userMetaObj.user_id==uid).all() return tlist ## ## Query the friends table ## def query_friends_by_username(self, uname, fname=None): q = self.session.query(friendObj).filter(friendObj.user==uname) if( fname ): q = q.filter(friendObj.friend==fname) flist = q.all() return flist def query_friends_by_user_id(self, uid, fid=None): q = self.session.query(friendObj).filter(friendObj.user_id==uid) if( fid ): q = q.filter(friendObj.friend_id==fid) flist = q.all() return flist ## ## Query the followers table ## def query_followers_by_username(self, uname, fname=None): q = self.session.query(followerObj).filter(followerObj.user==uname) if( fname ): q = q.filter(followerObj.follower==fname) flist = q.all() return flist def query_followers_by_user_id(self, uid, fid=None): q = self.session.query(followerObj).filter(followerObj.user_id==uid) if( fid ): q = q.filter(followerObj.follower_id==fid) flist = q.all() return flist
import xml.etree.ElementTree as et import pytest from django.urls import reverse from ..models import Question users = ( ('editor', 'editor'), ('reviewer', 'reviewer'), ('user', 'user'), ('api', 'api'), ('anonymous', None), ) status_map = { 'list': { 'editor': 200, 'reviewer': 200, 'api': 200, 'user': 403, 'anonymous': 401 }, 'detail': { 'editor': 200, 'reviewer': 200, 'api': 200, 'user': 403, 'anonymous': 401 }, 'create': { 'editor': 201, 'reviewer': 403, 'api': 201, 'user': 403, 'anonymous': 401 }, 'update': { 'editor': 200, 'reviewer': 403, 'api': 200, 'user': 403, 'anonymous': 401 }, 'delete': { 'editor': 204, 'reviewer': 403, 'api': 204, 'user': 403, 'anonymous': 401 } } urlnames = { 'list': 'v1-questions:question-list', 'nested': 'v1-questions:question-nested', 'index': 'v1-questions:question-index', 'export': 'v1-questions:question-export', 'detail': 'v1-questions:question-detail', 'detail_export': 'v1-questions:question-detail-export', 'copy': 'v1-questions:question-copy' } @pytest.mark.parametrize('username,password', users) def test_list(db, client, username, password): client.login(username=username, password=password) url = reverse(urlnames['list']) response = client.get(url) assert response.status_code == status_map['list'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_index(db, client, username, password): client.login(username=username, password=password) url = reverse(urlnames['index']) response = client.get(url) assert response.status_code == status_map['list'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_export(db, client, username, password): client.login(username=username, password=password) url = reverse(urlnames['export']) response = client.get(url) assert response.status_code == status_map['list'][username], response.content if response.status_code == 200: root = et.fromstring(response.content) assert root.tag == 'rdmo' for child in root: assert child.tag in ['question'] @pytest.mark.parametrize('username,password', users) def test_detail(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['detail'], args=[instance.pk]) response = client.get(url) assert response.status_code == status_map['detail'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_nested(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['nested'], args=[instance.pk]) response = client.get(url) assert response.status_code == status_map['detail'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_create(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['list']) data = { 'uri_prefix': instance.uri_prefix, 'key': '%s_new_%s' % (instance.key, username), 'comment': instance.comment or '', 'attribute': instance.attribute.pk if instance.attribute else '', 'questionset': instance.questionset.pk, 'is_collection': instance.is_collection, 'order': instance.order, 'help_en': instance.help_lang1 or '', 'help_de': instance.help_lang2 or '', 'text_en': instance.text_lang1 or '', 'text_de': instance.text_lang2 or '', 'verbose_name_en': instance.verbose_name_lang1 or '', 'verbose_name_de': instance.verbose_name_lang2 or '', 'verbose_name_plural_en': instance.verbose_name_plural_lang1 or '', 'verbose_name_plural_de': instance.verbose_name_plural_lang2 or '', 'widget_type': instance.widget_type, 'value_type': instance.value_type, 'minimum': instance.minimum or '', 'maximum': instance.maximum or '', 'step': instance.step or '', 'unit': instance.unit or '', 'optionsets': [optionset.pk for optionset in instance.optionsets.all()], 'conditions': [condition.pk for condition in instance.conditions.all()] } response = client.post(url, data, content_type='application/json') assert response.status_code == status_map['create'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_update(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['detail'], args=[instance.pk]) data = { 'uri_prefix': instance.uri_prefix, 'key': instance.key, 'comment': instance.comment, 'attribute': instance.attribute.pk if instance.attribute else None, 'questionset': instance.questionset.pk, 'is_collection': instance.is_collection, 'order': instance.order, 'help_en': instance.help_lang1, 'help_de': instance.help_lang2, 'text_en': instance.text_lang1, 'text_de': instance.text_lang2, 'verbose_name_en': instance.verbose_name_lang1, 'verbose_name_de': instance.verbose_name_lang2, 'verbose_name_plural_en': instance.verbose_name_plural_lang1, 'verbose_name_plural_de': instance.verbose_name_plural_lang2, 'widget_type': instance.widget_type, 'value_type': instance.value_type, 'minimum': instance.minimum, 'maximum': instance.maximum, 'step': instance.step, 'unit': instance.unit, 'optionsets': [optionset.pk for optionset in instance.optionsets.all()], 'conditions': [condition.pk for condition in instance.conditions.all()], } response = client.put(url, data, content_type='application/json') assert response.status_code == status_map['update'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_delete(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['detail'], args=[instance.pk]) response = client.delete(url) assert response.status_code == status_map['delete'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_detail_export(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['detail_export'], args=[instance.pk]) response = client.get(url) assert response.status_code == status_map['list'][username], response.content if response.status_code == 200: root = et.fromstring(response.content) assert root.tag == 'rdmo' for child in root: assert child.tag in ['question'] @pytest.mark.parametrize('username,password', users) def test_copy(db, client, username, password): client.login(username=username, password=password) instances = Question.objects.all() for instance in instances: url = reverse(urlnames['copy'], args=[instance.pk]) data = { 'uri_prefix': instance.uri_prefix + '-', 'key': instance.key + '-', 'questionset': instance.questionset.id } response = client.put(url, data, content_type='application/json') assert response.status_code == status_map['create'][username], response.json() @pytest.mark.parametrize('username,password', users) def test_copy_wrong(db, client, username, password): client.login(username=username, password=password) instance = Question.objects.first() url = reverse(urlnames['copy'], args=[instance.pk]) data = { 'uri_prefix': instance.uri_prefix, 'key': instance.key, 'questionset': instance.questionset.id } response = client.put(url, data, content_type='application/json') if status_map['create'][username] == 201: assert response.status_code == 400, response.json() else: assert response.status_code == status_map['create'][username], response.json()
from sqlalchemy import * from sqlalchemy.sql import table, column, ClauseElement from sqlalchemy.sql.expression import _clone, _from_objects from test.lib import * from sqlalchemy.sql.visitors import * from sqlalchemy import util, exc from sqlalchemy.sql import util as sql_util from test.lib.testing import eq_, ne_, assert_raises class TraversalTest(fixtures.TestBase, AssertsExecutionResults): """test ClauseVisitor's traversal, particularly its ability to copy and modify a ClauseElement in place.""" @classmethod def setup_class(cls): global A, B # establish two ficticious ClauseElements. # define deep equality semantics as well as deep # identity semantics. class A(ClauseElement): __visit_name__ = 'a' def __init__(self, expr): self.expr = expr def is_other(self, other): return other is self __hash__ = ClauseElement.__hash__ def __eq__(self, other): return other.expr == self.expr def __ne__(self, other): return other.expr != self.expr def __str__(self): return "A(%s)" % repr(self.expr) class B(ClauseElement): __visit_name__ = 'b' def __init__(self, *items): self.items = items def is_other(self, other): if other is not self: return False for i1, i2 in zip(self.items, other.items): if i1 is not i2: return False return True __hash__ = ClauseElement.__hash__ def __eq__(self, other): for i1, i2 in zip(self.items, other.items): if i1 != i2: return False return True def __ne__(self, other): for i1, i2 in zip(self.items, other.items): if i1 != i2: return True return False def _copy_internals(self, clone=_clone): self.items = [clone(i) for i in self.items] def get_children(self, **kwargs): return self.items def __str__(self): return "B(%s)" % repr([str(i) for i in self.items]) def test_test_classes(self): a1 = A("expr1") struct = B(a1, A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3")) struct2 = B(a1, A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3")) struct3 = B(a1, A("expr2"), B(A("expr1b"), A("expr2bmodified")), A("expr3")) assert a1.is_other(a1) assert struct.is_other(struct) assert struct == struct2 assert struct != struct3 assert not struct.is_other(struct2) assert not struct.is_other(struct3) def test_clone(self): struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3")) class Vis(CloningVisitor): def visit_a(self, a): pass def visit_b(self, b): pass vis = Vis() s2 = vis.traverse(struct) assert struct == s2 assert not struct.is_other(s2) def test_no_clone(self): struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3")) class Vis(ClauseVisitor): def visit_a(self, a): pass def visit_b(self, b): pass vis = Vis() s2 = vis.traverse(struct) assert struct == s2 assert struct.is_other(s2) def test_change_in_place(self): struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3")) struct2 = B(A("expr1"), A("expr2modified"), B(A("expr1b"), A("expr2b")), A("expr3")) struct3 = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2bmodified")), A("expr3")) class Vis(CloningVisitor): def visit_a(self, a): if a.expr == "expr2": a.expr = "expr2modified" def visit_b(self, b): pass vis = Vis() s2 = vis.traverse(struct) assert struct != s2 assert not struct.is_other(s2) assert struct2 == s2 class Vis2(CloningVisitor): def visit_a(self, a): if a.expr == "expr2b": a.expr = "expr2bmodified" def visit_b(self, b): pass vis2 = Vis2() s3 = vis2.traverse(struct) assert struct != s3 assert struct3 == s3 def test_visit_name(self): # override fns in testlib/schema.py from sqlalchemy import Column class CustomObj(Column): pass assert CustomObj.__visit_name__ == Column.__visit_name__ == 'column' foo, bar = CustomObj('foo', String), CustomObj('bar', String) bin = foo == bar s = set(ClauseVisitor().iterate(bin)) assert set(ClauseVisitor().iterate(bin)) == set([foo, bar, bin]) class ClauseTest(fixtures.TestBase, AssertsCompiledSQL): """test copy-in-place behavior of various ClauseElements.""" __dialect__ = 'default' @classmethod def setup_class(cls): global t1, t2, t3 t1 = table("table1", column("col1"), column("col2"), column("col3"), ) t2 = table("table2", column("col1"), column("col2"), column("col3"), ) t3 = Table('table3', MetaData(), Column('col1', Integer), Column('col2', Integer) ) def test_binary(self): clause = t1.c.col2 == t2.c.col2 eq_(str(clause), str(CloningVisitor().traverse(clause))) def test_binary_anon_label_quirk(self): t = table('t1', column('col1')) f = t.c.col1 * 5 self.assert_compile(select([f]), "SELECT t1.col1 * :col1_1 AS anon_1 FROM t1") f.anon_label a = t.alias() f = sql_util.ClauseAdapter(a).traverse(f) self.assert_compile(select([f]), "SELECT t1_1.col1 * :col1_1 AS anon_1 FROM t1 AS t1_1") def test_join(self): clause = t1.join(t2, t1.c.col2==t2.c.col2) c1 = str(clause) assert str(clause) == str(CloningVisitor().traverse(clause)) class Vis(CloningVisitor): def visit_binary(self, binary): binary.right = t2.c.col3 clause2 = Vis().traverse(clause) assert c1 == str(clause) assert str(clause2) == str(t1.join(t2, t1.c.col2==t2.c.col3)) def test_aliased_column_adapt(self): clause = t1.select() aliased = t1.select().alias() aliased2 = t1.alias() adapter = sql_util.ColumnAdapter(aliased) f = select([ adapter.columns[c] for c in aliased2.c ]).select_from(aliased) s = select([aliased2]).select_from(aliased) eq_(str(s), str(f)) f = select([ adapter.columns[func.count(aliased2.c.col1)] ]).select_from(aliased) eq_( str(select([func.count(aliased2.c.col1)]).select_from(aliased)), str(f) ) def test_aliased_cloned_column_adapt_inner(self): clause = select([t1.c.col1, func.foo(t1.c.col2).label('foo')]) aliased1 = select([clause.c.col1, clause.c.foo]) aliased2 = clause aliased2.c.col1, aliased2.c.foo aliased3 = cloned_traverse(aliased2, {}, {}) # fixed by [ticket:2419]. the inside columns # on aliased3 have _is_clone_of pointers to those of # aliased2. corresponding_column checks these # now. adapter = sql_util.ColumnAdapter(aliased1) f1 = select([ adapter.columns[c] for c in aliased2._raw_columns ]) f2 = select([ adapter.columns[c] for c in aliased3._raw_columns ]) eq_( str(f1), str(f2) ) def test_aliased_cloned_column_adapt_exported(self): clause = select([t1.c.col1, func.foo(t1.c.col2).label('foo')]) aliased1 = select([clause.c.col1, clause.c.foo]) aliased2 = clause aliased2.c.col1, aliased2.c.foo aliased3 = cloned_traverse(aliased2, {}, {}) # also fixed by [ticket:2419]. When we look at the # *outside* columns of aliased3, they previously did not # have an _is_clone_of pointer. But we now modified _make_proxy # to assign this. adapter = sql_util.ColumnAdapter(aliased1) f1 = select([ adapter.columns[c] for c in aliased2.c ]) f2 = select([ adapter.columns[c] for c in aliased3.c ]) eq_( str(f1), str(f2) ) def test_aliased_cloned_schema_column_adapt_exported(self): clause = select([t3.c.col1, func.foo(t3.c.col2).label('foo')]) aliased1 = select([clause.c.col1, clause.c.foo]) aliased2 = clause aliased2.c.col1, aliased2.c.foo aliased3 = cloned_traverse(aliased2, {}, {}) # also fixed by [ticket:2419]. When we look at the # *outside* columns of aliased3, they previously did not # have an _is_clone_of pointer. But we now modified _make_proxy # to assign this. adapter = sql_util.ColumnAdapter(aliased1) f1 = select([ adapter.columns[c] for c in aliased2.c ]) f2 = select([ adapter.columns[c] for c in aliased3.c ]) eq_( str(f1), str(f2) ) def test_text(self): clause = text( "select * from table where foo=:bar", bindparams=[bindparam('bar')]) c1 = str(clause) class Vis(CloningVisitor): def visit_textclause(self, text): text.text = text.text + " SOME MODIFIER=:lala" text.bindparams['lala'] = bindparam('lala') clause2 = Vis().traverse(clause) assert c1 == str(clause) assert str(clause2) == c1 + " SOME MODIFIER=:lala" assert clause.bindparams.keys() == ['bar'] assert set(clause2.bindparams.keys()) == set(['bar', 'lala']) def test_select(self): s2 = select([t1]) s2_assert = str(s2) s3_assert = str(select([t1], t1.c.col2==7)) class Vis(CloningVisitor): def visit_select(self, select): select.append_whereclause(t1.c.col2==7) s3 = Vis().traverse(s2) assert str(s3) == s3_assert assert str(s2) == s2_assert print str(s2) print str(s3) class Vis(ClauseVisitor): def visit_select(self, select): select.append_whereclause(t1.c.col2==7) Vis().traverse(s2) assert str(s2) == s3_assert print "------------------" s4_assert = str(select([t1], and_(t1.c.col2==7, t1.c.col3==9))) class Vis(CloningVisitor): def visit_select(self, select): select.append_whereclause(t1.c.col3==9) s4 = Vis().traverse(s3) print str(s3) print str(s4) assert str(s4) == s4_assert assert str(s3) == s3_assert print "------------------" s5_assert = str(select([t1], and_(t1.c.col2==7, t1.c.col1==9))) class Vis(CloningVisitor): def visit_binary(self, binary): if binary.left is t1.c.col3: binary.left = t1.c.col1 binary.right = bindparam("col1", unique=True) s5 = Vis().traverse(s4) print str(s4) print str(s5) assert str(s5) == s5_assert assert str(s4) == s4_assert def test_union(self): u = union(t1.select(), t2.select()) u2 = CloningVisitor().traverse(u) assert str(u) == str(u2) assert [str(c) for c in u2.c] == [str(c) for c in u.c] u = union(t1.select(), t2.select()) cols = [str(c) for c in u.c] u2 = CloningVisitor().traverse(u) assert str(u) == str(u2) assert [str(c) for c in u2.c] == cols s1 = select([t1], t1.c.col1 == bindparam('id_param')) s2 = select([t2]) u = union(s1, s2) u2 = u.params(id_param=7) u3 = u.params(id_param=10) assert str(u) == str(u2) == str(u3) assert u2.compile().params == {'id_param':7} assert u3.compile().params == {'id_param':10} def test_in(self): expr = t1.c.col1.in_(['foo', 'bar']) expr2 = CloningVisitor().traverse(expr) assert str(expr) == str(expr2) def test_over(self): expr = func.row_number().over(order_by=t1.c.col1) expr2 = CloningVisitor().traverse(expr) assert str(expr) == str(expr2) def test_adapt_union(self): u = union( t1.select().where(t1.c.col1==4), t1.select().where(t1.c.col1==5) ).alias() assert sql_util.ClauseAdapter(u).traverse(t1) is u def test_binds(self): """test that unique bindparams change their name upon clone() to prevent conflicts""" s = select([t1], t1.c.col1==bindparam(None, unique=True)).alias() s2 = CloningVisitor().traverse(s).alias() s3 = select([s], s.c.col2==s2.c.col2) self.assert_compile(s3, "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM " "(SELECT table1.col1 AS col1, table1.col2 AS col2, " "table1.col3 AS col3 FROM table1 WHERE table1.col1 = :param_1) " "AS anon_1, " "(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 " "AS col3 FROM table1 WHERE table1.col1 = :param_2) AS anon_2 " "WHERE anon_1.col2 = anon_2.col2") s = select([t1], t1.c.col1==4).alias() s2 = CloningVisitor().traverse(s).alias() s3 = select([s], s.c.col2==s2.c.col2) self.assert_compile(s3, "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM " "(SELECT table1.col1 AS col1, table1.col2 AS col2, " "table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) " "AS anon_1, " "(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 " "AS col3 FROM table1 WHERE table1.col1 = :col1_2) AS anon_2 " "WHERE anon_1.col2 = anon_2.col2") def test_extract(self): s = select([extract('foo', t1.c.col1).label('col1')]) self.assert_compile(s, "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1") s2 = CloningVisitor().traverse(s).alias() s3 = select([s2.c.col1]) self.assert_compile(s, "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1") self.assert_compile(s3, "SELECT anon_1.col1 FROM (SELECT EXTRACT(foo FROM " "table1.col1) AS col1 FROM table1) AS anon_1") @testing.emits_warning('.*replaced by another column with the same key') def test_alias(self): subq = t2.select().alias('subq') s = select([t1.c.col1, subq.c.col1], from_obj=[t1, subq, t1.join(subq, t1.c.col1==subq.c.col2)] ) orig = str(s) s2 = CloningVisitor().traverse(s) assert orig == str(s) == str(s2) s4 = CloningVisitor().traverse(s2) assert orig == str(s) == str(s2) == str(s4) s3 = sql_util.ClauseAdapter(table('foo')).traverse(s) assert orig == str(s) == str(s3) s4 = sql_util.ClauseAdapter(table('foo')).traverse(s3) assert orig == str(s) == str(s3) == str(s4) subq = subq.alias('subq') s = select([t1.c.col1, subq.c.col1], from_obj=[t1, subq, t1.join(subq, t1.c.col1==subq.c.col2)] ) s5 = CloningVisitor().traverse(s) assert orig == str(s) == str(s5) def test_correlated_select(self): s = select(['*'], t1.c.col1==t2.c.col1, from_obj=[t1, t2]).correlate(t2) class Vis(CloningVisitor): def visit_select(self, select): select.append_whereclause(t1.c.col2==7) self.assert_compile(Vis().traverse(s), "SELECT * FROM table1 WHERE table1.col1 = table2.col1 " "AND table1.col2 = :col2_1") def test_this_thing(self): s = select([t1]).where(t1.c.col1=='foo').alias() s2 = select([s.c.col1]) self.assert_compile(s2, 'SELECT anon_1.col1 FROM (SELECT ' 'table1.col1 AS col1, table1.col2 AS col2, ' 'table1.col3 AS col3 FROM table1 WHERE ' 'table1.col1 = :col1_1) AS anon_1') t1a = t1.alias() s2 = sql_util.ClauseAdapter(t1a).traverse(s2) self.assert_compile(s2, 'SELECT anon_1.col1 FROM (SELECT ' 'table1_1.col1 AS col1, table1_1.col2 AS ' 'col2, table1_1.col3 AS col3 FROM table1 ' 'AS table1_1 WHERE table1_1.col1 = ' ':col1_1) AS anon_1') def test_select_fromtwice(self): t1a = t1.alias() s = select([1], t1.c.col1==t1a.c.col1, from_obj=t1a).correlate(t1) self.assert_compile(s, 'SELECT 1 FROM table1 AS table1_1 WHERE ' 'table1.col1 = table1_1.col1') s = CloningVisitor().traverse(s) self.assert_compile(s, 'SELECT 1 FROM table1 AS table1_1 WHERE ' 'table1.col1 = table1_1.col1') s = select([t1]).where(t1.c.col1=='foo').alias() s2 = select([1], t1.c.col1==s.c.col1, from_obj=s).correlate(t1) self.assert_compile(s2, 'SELECT 1 FROM (SELECT table1.col1 AS ' 'col1, table1.col2 AS col2, table1.col3 AS ' 'col3 FROM table1 WHERE table1.col1 = ' ':col1_1) AS anon_1 WHERE table1.col1 = ' 'anon_1.col1') s2 = ReplacingCloningVisitor().traverse(s2) self.assert_compile(s2, 'SELECT 1 FROM (SELECT table1.col1 AS ' 'col1, table1.col2 AS col2, table1.col3 AS ' 'col3 FROM table1 WHERE table1.col1 = ' ':col1_1) AS anon_1 WHERE table1.col1 = ' 'anon_1.col1') class ClauseAdapterTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = 'default' @classmethod def setup_class(cls): global t1, t2 t1 = table("table1", column("col1"), column("col2"), column("col3"), ) t2 = table("table2", column("col1"), column("col2"), column("col3"), ) def test_correlation_on_clone(self): t1alias = t1.alias('t1alias') t2alias = t2.alias('t2alias') vis = sql_util.ClauseAdapter(t1alias) s = select(['*'], from_obj=[t1alias, t2alias]).as_scalar() assert t2alias in s._froms assert t1alias in s._froms self.assert_compile(select(['*'], t2alias.c.col1 == s), 'SELECT * FROM table2 AS t2alias WHERE ' 't2alias.col1 = (SELECT * FROM table1 AS ' 't1alias)') s = vis.traverse(s) assert t2alias not in s._froms # not present because it's been # cloned assert t1alias in s._froms # present because the adapter placed # it there # correlate list on "s" needs to take into account the full # _cloned_set for each element in _froms when correlating self.assert_compile(select(['*'], t2alias.c.col1 == s), 'SELECT * FROM table2 AS t2alias WHERE ' 't2alias.col1 = (SELECT * FROM table1 AS ' 't1alias)') s = select(['*'], from_obj=[t1alias, t2alias]).correlate(t2alias).as_scalar() self.assert_compile(select(['*'], t2alias.c.col1 == s), 'SELECT * FROM table2 AS t2alias WHERE ' 't2alias.col1 = (SELECT * FROM table1 AS ' 't1alias)') s = vis.traverse(s) self.assert_compile(select(['*'], t2alias.c.col1 == s), 'SELECT * FROM table2 AS t2alias WHERE ' 't2alias.col1 = (SELECT * FROM table1 AS ' 't1alias)') s = CloningVisitor().traverse(s) self.assert_compile(select(['*'], t2alias.c.col1 == s), 'SELECT * FROM table2 AS t2alias WHERE ' 't2alias.col1 = (SELECT * FROM table1 AS ' 't1alias)') s = select(['*']).where(t1.c.col1 == t2.c.col1).as_scalar() self.assert_compile(select([t1.c.col1, s]), 'SELECT table1.col1, (SELECT * FROM table2 ' 'WHERE table1.col1 = table2.col1) AS ' 'anon_1 FROM table1') vis = sql_util.ClauseAdapter(t1alias) s = vis.traverse(s) self.assert_compile(select([t1alias.c.col1, s]), 'SELECT t1alias.col1, (SELECT * FROM ' 'table2 WHERE t1alias.col1 = table2.col1) ' 'AS anon_1 FROM table1 AS t1alias') s = CloningVisitor().traverse(s) self.assert_compile(select([t1alias.c.col1, s]), 'SELECT t1alias.col1, (SELECT * FROM ' 'table2 WHERE t1alias.col1 = table2.col1) ' 'AS anon_1 FROM table1 AS t1alias') s = select(['*']).where(t1.c.col1 == t2.c.col1).correlate(t1).as_scalar() self.assert_compile(select([t1.c.col1, s]), 'SELECT table1.col1, (SELECT * FROM table2 ' 'WHERE table1.col1 = table2.col1) AS ' 'anon_1 FROM table1') vis = sql_util.ClauseAdapter(t1alias) s = vis.traverse(s) self.assert_compile(select([t1alias.c.col1, s]), 'SELECT t1alias.col1, (SELECT * FROM ' 'table2 WHERE t1alias.col1 = table2.col1) ' 'AS anon_1 FROM table1 AS t1alias') s = CloningVisitor().traverse(s) self.assert_compile(select([t1alias.c.col1, s]), 'SELECT t1alias.col1, (SELECT * FROM ' 'table2 WHERE t1alias.col1 = table2.col1) ' 'AS anon_1 FROM table1 AS t1alias') @testing.fails_on_everything_except() def test_joins_dont_adapt(self): # adapting to a join, i.e. ClauseAdapter(t1.join(t2)), doesn't # make much sense. ClauseAdapter doesn't make any changes if # it's against a straight join. users = table('users', column('id')) addresses = table('addresses', column('id'), column('user_id')) ualias = users.alias() s = select([func.count(addresses.c.id)], users.c.id == addresses.c.user_id).correlate(users) s = sql_util.ClauseAdapter(ualias).traverse(s) j1 = addresses.join(ualias, addresses.c.user_id==ualias.c.id) self.assert_compile(sql_util.ClauseAdapter(j1).traverse(s), 'SELECT count(addresses.id) AS count_1 ' 'FROM addresses WHERE users_1.id = ' 'addresses.user_id') def test_table_to_alias(self): t1alias = t1.alias('t1alias') vis = sql_util.ClauseAdapter(t1alias) ff = vis.traverse(func.count(t1.c.col1).label('foo')) assert list(_from_objects(ff)) == [t1alias] self.assert_compile(vis.traverse(select(['*'], from_obj=[t1])), 'SELECT * FROM table1 AS t1alias') self.assert_compile(select(['*'], t1.c.col1 == t2.c.col2), 'SELECT * FROM table1, table2 WHERE ' 'table1.col1 = table2.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2)), 'SELECT * FROM table1 AS t1alias, table2 ' 'WHERE t1alias.col1 = table2.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2])), 'SELECT * FROM table1 AS t1alias, table2 ' 'WHERE t1alias.col1 = table2.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2]).correlate(t1)), 'SELECT * FROM table2 WHERE t1alias.col1 = ' 'table2.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2]).correlate(t2)), 'SELECT * FROM table1 AS t1alias WHERE ' 't1alias.col1 = table2.col2') self.assert_compile(vis.traverse(case([(t1.c.col1 == 5, t1.c.col2)], else_=t1.c.col1)), 'CASE WHEN (t1alias.col1 = :col1_1) THEN ' 't1alias.col2 ELSE t1alias.col1 END') self.assert_compile(vis.traverse(case([(5, t1.c.col2)], value=t1.c.col1, else_=t1.c.col1)), 'CASE t1alias.col1 WHEN :param_1 THEN ' 't1alias.col2 ELSE t1alias.col1 END') s = select(['*'], from_obj=[t1]).alias('foo') self.assert_compile(s.select(), 'SELECT foo.* FROM (SELECT * FROM table1) ' 'AS foo') self.assert_compile(vis.traverse(s.select()), 'SELECT foo.* FROM (SELECT * FROM table1 ' 'AS t1alias) AS foo') self.assert_compile(s.select(), 'SELECT foo.* FROM (SELECT * FROM table1) ' 'AS foo') ff = vis.traverse(func.count(t1.c.col1).label('foo')) self.assert_compile(select([ff]), 'SELECT count(t1alias.col1) AS foo FROM ' 'table1 AS t1alias') assert list(_from_objects(ff)) == [t1alias] # TODO: self.assert_compile(vis.traverse(select([func.count(t1.c # .col1).l abel('foo')]), clone=True), "SELECT # count(t1alias.col1) AS foo FROM table1 AS t1alias") t2alias = t2.alias('t2alias') vis.chain(sql_util.ClauseAdapter(t2alias)) self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2)), 'SELECT * FROM table1 AS t1alias, table2 ' 'AS t2alias WHERE t1alias.col1 = ' 't2alias.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2])), 'SELECT * FROM table1 AS t1alias, table2 ' 'AS t2alias WHERE t1alias.col1 = ' 't2alias.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2]).correlate(t1)), 'SELECT * FROM table2 AS t2alias WHERE ' 't1alias.col1 = t2alias.col2') self.assert_compile(vis.traverse(select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2]).correlate(t2)), 'SELECT * FROM table1 AS t1alias WHERE ' 't1alias.col1 = t2alias.col2') def test_include_exclude(self): m = MetaData() a=Table( 'a',m, Column( 'id', Integer, primary_key=True), Column( 'xxx_id', Integer, ForeignKey( 'a.id', name='adf',use_alter=True ) ) ) e = (a.c.id == a.c.xxx_id) assert str(e) == "a.id = a.xxx_id" b = a.alias() e = sql_util.ClauseAdapter( b, include= set([ a.c.id ]), equivalents= { a.c.id: set([ a.c.id]) } ).traverse( e) assert str(e) == "a_1.id = a.xxx_id" def test_recursive_equivalents(self): m = MetaData() a = Table('a', m, Column('x', Integer), Column('y', Integer)) b = Table('b', m, Column('x', Integer), Column('y', Integer)) c = Table('c', m, Column('x', Integer), Column('y', Integer)) # force a recursion overflow, by linking a.c.x<->c.c.x, and # asking for a nonexistent col. corresponding_column should prevent # endless depth. adapt = sql_util.ClauseAdapter(b, equivalents={a.c.x: set([c.c.x]), c.c.x: set([a.c.x])}) assert adapt._corresponding_column(a.c.x, False) is None def test_multilevel_equivalents(self): m = MetaData() a = Table('a', m, Column('x', Integer), Column('y', Integer)) b = Table('b', m, Column('x', Integer), Column('y', Integer)) c = Table('c', m, Column('x', Integer), Column('y', Integer)) alias = select([a]).select_from(a.join(b, a.c.x==b.c.x)).alias() # two levels of indirection from c.x->b.x->a.x, requires recursive # corresponding_column call adapt = sql_util.ClauseAdapter(alias, equivalents={b.c.x: set([a.c.x]), c.c.x: set([b.c.x])}) assert adapt._corresponding_column(a.c.x, False) is alias.c.x assert adapt._corresponding_column(c.c.x, False) is alias.c.x def test_join_to_alias(self): metadata = MetaData() a = Table('a', metadata, Column('id', Integer, primary_key=True)) b = Table('b', metadata, Column('id', Integer, primary_key=True), Column('aid', Integer, ForeignKey('a.id')), ) c = Table('c', metadata, Column('id', Integer, primary_key=True), Column('bid', Integer, ForeignKey('b.id')), ) d = Table('d', metadata, Column('id', Integer, primary_key=True), Column('aid', Integer, ForeignKey('a.id')), ) j1 = a.outerjoin(b) j2 = select([j1], use_labels=True) j3 = c.join(j2, j2.c.b_id==c.c.bid) j4 = j3.outerjoin(d) self.assert_compile(j4, 'c JOIN (SELECT a.id AS a_id, b.id AS ' 'b_id, b.aid AS b_aid FROM a LEFT OUTER ' 'JOIN b ON a.id = b.aid) ON b_id = c.bid ' 'LEFT OUTER JOIN d ON a_id = d.aid') j5 = j3.alias('foo') j6 = sql_util.ClauseAdapter(j5).copy_and_process([j4])[0] # this statement takes c join(a join b), wraps it inside an # aliased "select * from c join(a join b) AS foo". the outermost # right side "left outer join d" stays the same, except "d" # joins against foo.a_id instead of plain "a_id" self.assert_compile(j6, '(SELECT c.id AS c_id, c.bid AS c_bid, ' 'a_id AS a_id, b_id AS b_id, b_aid AS ' 'b_aid FROM c JOIN (SELECT a.id AS a_id, ' 'b.id AS b_id, b.aid AS b_aid FROM a LEFT ' 'OUTER JOIN b ON a.id = b.aid) ON b_id = ' 'c.bid) AS foo LEFT OUTER JOIN d ON ' 'foo.a_id = d.aid') def test_derived_from(self): assert select([t1]).is_derived_from(t1) assert not select([t2]).is_derived_from(t1) assert not t1.is_derived_from(select([t1])) assert t1.alias().is_derived_from(t1) s1 = select([t1, t2]).alias('foo') s2 = select([s1]).limit(5).offset(10).alias() assert s2.is_derived_from(s1) s2 = s2._clone() assert s2.is_derived_from(s1) def test_aliasedselect_to_aliasedselect_straight(self): # original issue from ticket #904 s1 = select([t1]).alias('foo') s2 = select([s1]).limit(5).offset(10).alias() self.assert_compile(sql_util.ClauseAdapter(s2).traverse(s1), 'SELECT foo.col1, foo.col2, foo.col3 FROM ' '(SELECT table1.col1 AS col1, table1.col2 ' 'AS col2, table1.col3 AS col3 FROM table1) ' 'AS foo LIMIT :param_1 OFFSET :param_2', {'param_1': 5, 'param_2': 10}) def test_aliasedselect_to_aliasedselect_join(self): s1 = select([t1]).alias('foo') s2 = select([s1]).limit(5).offset(10).alias() j = s1.outerjoin(t2, s1.c.col1 == t2.c.col1) self.assert_compile(sql_util.ClauseAdapter(s2).traverse(j).select(), 'SELECT anon_1.col1, anon_1.col2, ' 'anon_1.col3, table2.col1, table2.col2, ' 'table2.col3 FROM (SELECT foo.col1 AS ' 'col1, foo.col2 AS col2, foo.col3 AS col3 ' 'FROM (SELECT table1.col1 AS col1, ' 'table1.col2 AS col2, table1.col3 AS col3 ' 'FROM table1) AS foo LIMIT :param_1 OFFSET ' ':param_2) AS anon_1 LEFT OUTER JOIN ' 'table2 ON anon_1.col1 = table2.col1', {'param_1': 5, 'param_2': 10}) def test_aliasedselect_to_aliasedselect_join_nested_table(self): s1 = select([t1]).alias('foo') s2 = select([s1]).limit(5).offset(10).alias() talias = t1.alias('bar') assert not s2.is_derived_from(talias) j = s1.outerjoin(talias, s1.c.col1 == talias.c.col1) self.assert_compile(sql_util.ClauseAdapter(s2).traverse(j).select(), 'SELECT anon_1.col1, anon_1.col2, ' 'anon_1.col3, bar.col1, bar.col2, bar.col3 ' 'FROM (SELECT foo.col1 AS col1, foo.col2 ' 'AS col2, foo.col3 AS col3 FROM (SELECT ' 'table1.col1 AS col1, table1.col2 AS col2, ' 'table1.col3 AS col3 FROM table1) AS foo ' 'LIMIT :param_1 OFFSET :param_2) AS anon_1 ' 'LEFT OUTER JOIN table1 AS bar ON ' 'anon_1.col1 = bar.col1', {'param_1': 5, 'param_2': 10}) def test_functions(self): self.assert_compile( sql_util.ClauseAdapter(t1.alias()).\ traverse(func.count(t1.c.col1)), 'count(table1_1.col1)') s = select([func.count(t1.c.col1)]) self.assert_compile(sql_util.ClauseAdapter(t1.alias()).traverse(s), 'SELECT count(table1_1.col1) AS count_1 ' 'FROM table1 AS table1_1') def test_recursive(self): metadata = MetaData() a = Table('a', metadata, Column('id', Integer, primary_key=True)) b = Table('b', metadata, Column('id', Integer, primary_key=True), Column('aid', Integer, ForeignKey('a.id')), ) c = Table('c', metadata, Column('id', Integer, primary_key=True), Column('bid', Integer, ForeignKey('b.id')), ) d = Table('d', metadata, Column('id', Integer, primary_key=True), Column('aid', Integer, ForeignKey('a.id')), ) u = union( a.join(b).select().apply_labels(), a.join(d).select().apply_labels() ).alias() self.assert_compile( sql_util.ClauseAdapter(u).\ traverse(select([c.c.bid]).where(c.c.bid==u.c.b_aid)), "SELECT c.bid "\ "FROM c, (SELECT a.id AS a_id, b.id AS b_id, b.aid AS b_aid " "FROM a JOIN b ON a.id = b.aid UNION SELECT a.id AS a_id, d.id " "AS d_id, d.aid AS d_aid " "FROM a JOIN d ON a.id = d.aid) AS anon_1 " "WHERE c.bid = anon_1.b_aid" ) class SpliceJoinsTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = 'default' @classmethod def setup_class(cls): global table1, table2, table3, table4 def _table(name): return table(name, column('col1'), column('col2'), column('col3')) table1, table2, table3, table4 = [_table(name) for name in ('table1', 'table2', 'table3', 'table4')] def test_splice(self): t1, t2, t3, t4 = table1, table2, table1.alias(), table2.alias() j = t1.join(t2, t1.c.col1 == t2.c.col1).join(t3, t2.c.col1 == t3.c.col1).join(t4, t4.c.col1 == t1.c.col1) s = select([t1]).where(t1.c.col2 < 5).alias() self.assert_compile(sql_util.splice_joins(s, j), '(SELECT table1.col1 AS col1, table1.col2 ' 'AS col2, table1.col3 AS col3 FROM table1 ' 'WHERE table1.col2 < :col2_1) AS anon_1 ' 'JOIN table2 ON anon_1.col1 = table2.col1 ' 'JOIN table1 AS table1_1 ON table2.col1 = ' 'table1_1.col1 JOIN table2 AS table2_1 ON ' 'table2_1.col1 = anon_1.col1') def test_stop_on(self): t1, t2, t3 = table1, table2, table3 j1 = t1.join(t2, t1.c.col1 == t2.c.col1) j2 = j1.join(t3, t2.c.col1 == t3.c.col1) s = select([t1]).select_from(j1).alias() self.assert_compile(sql_util.splice_joins(s, j2), '(SELECT table1.col1 AS col1, table1.col2 ' 'AS col2, table1.col3 AS col3 FROM table1 ' 'JOIN table2 ON table1.col1 = table2.col1) ' 'AS anon_1 JOIN table2 ON anon_1.col1 = ' 'table2.col1 JOIN table3 ON table2.col1 = ' 'table3.col1') self.assert_compile(sql_util.splice_joins(s, j2, j1), '(SELECT table1.col1 AS col1, table1.col2 ' 'AS col2, table1.col3 AS col3 FROM table1 ' 'JOIN table2 ON table1.col1 = table2.col1) ' 'AS anon_1 JOIN table3 ON table2.col1 = ' 'table3.col1') def test_splice_2(self): t2a = table2.alias() t3a = table3.alias() j1 = table1.join(t2a, table1.c.col1 == t2a.c.col1).join(t3a, t2a.c.col2 == t3a.c.col2) t2b = table4.alias() j2 = table1.join(t2b, table1.c.col3 == t2b.c.col3) self.assert_compile(sql_util.splice_joins(table1, j1), 'table1 JOIN table2 AS table2_1 ON ' 'table1.col1 = table2_1.col1 JOIN table3 ' 'AS table3_1 ON table2_1.col2 = ' 'table3_1.col2') self.assert_compile(sql_util.splice_joins(table1, j2), 'table1 JOIN table4 AS table4_1 ON ' 'table1.col3 = table4_1.col3') self.assert_compile(sql_util.splice_joins(sql_util.splice_joins(table1, j1), j2), 'table1 JOIN table2 AS table2_1 ON ' 'table1.col1 = table2_1.col1 JOIN table3 ' 'AS table3_1 ON table2_1.col2 = ' 'table3_1.col2 JOIN table4 AS table4_1 ON ' 'table1.col3 = table4_1.col3') class SelectTest(fixtures.TestBase, AssertsCompiledSQL): """tests the generative capability of Select""" __dialect__ = 'default' @classmethod def setup_class(cls): global t1, t2 t1 = table("table1", column("col1"), column("col2"), column("col3"), ) t2 = table("table2", column("col1"), column("col2"), column("col3"), ) def test_select(self): self.assert_compile(t1.select().where(t1.c.col1 == 5).order_by(t1.c.col3), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1 WHERE table1.col1 ' '= :col1_1 ORDER BY table1.col3') self.assert_compile(t1.select().select_from(select([t2], t2.c.col1 == t1.c.col1)).order_by(t1.c.col3), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2 WHERE ' 'table2.col1 = table1.col1) ORDER BY ' 'table1.col3') s = select([t2], t2.c.col1 == t1.c.col1, correlate=False) s = s.correlate(t1).order_by(t2.c.col3) self.assert_compile(t1.select().select_from(s).order_by(t1.c.col3), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2 WHERE ' 'table2.col1 = table1.col1 ORDER BY ' 'table2.col3) ORDER BY table1.col3') def test_columns(self): s = t1.select() self.assert_compile(s, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1') select_copy = s.column('yyy') self.assert_compile(select_copy, 'SELECT table1.col1, table1.col2, ' 'table1.col3, yyy FROM table1') assert s.columns is not select_copy.columns assert s._columns is not select_copy._columns assert s._raw_columns is not select_copy._raw_columns self.assert_compile(s, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1') def test_froms(self): s = t1.select() self.assert_compile(s, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1') select_copy = s.select_from(t2) self.assert_compile(select_copy, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, table2') assert s._froms is not select_copy._froms self.assert_compile(s, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1') def test_correlation(self): s = select([t2], t1.c.col1 == t2.c.col1) self.assert_compile(s, 'SELECT table2.col1, table2.col2, ' 'table2.col3 FROM table2, table1 WHERE ' 'table1.col1 = table2.col1') s2 = select([t1], t1.c.col2 == s.c.col2) self.assert_compile(s2, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2 WHERE ' 'table1.col1 = table2.col1) WHERE ' 'table1.col2 = col2') s3 = s.correlate(None) self.assert_compile(select([t1], t1.c.col2 == s3.c.col2), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2, table1 ' 'WHERE table1.col1 = table2.col1) WHERE ' 'table1.col2 = col2') self.assert_compile(select([t1], t1.c.col2 == s.c.col2), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2 WHERE ' 'table1.col1 = table2.col1) WHERE ' 'table1.col2 = col2') s4 = s3.correlate(t1) self.assert_compile(select([t1], t1.c.col2 == s4.c.col2), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2 WHERE ' 'table1.col1 = table2.col1) WHERE ' 'table1.col2 = col2') self.assert_compile(select([t1], t1.c.col2 == s3.c.col2), 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1, (SELECT ' 'table2.col1 AS col1, table2.col2 AS col2, ' 'table2.col3 AS col3 FROM table2, table1 ' 'WHERE table1.col1 = table2.col1) WHERE ' 'table1.col2 = col2') def test_prefixes(self): s = t1.select() self.assert_compile(s, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1') select_copy = s.prefix_with('FOOBER') self.assert_compile(select_copy, 'SELECT FOOBER table1.col1, table1.col2, ' 'table1.col3 FROM table1') self.assert_compile(s, 'SELECT table1.col1, table1.col2, ' 'table1.col3 FROM table1') def test_execution_options(self): s = select().execution_options(foo='bar') s2 = s.execution_options(bar='baz') s3 = s.execution_options(foo='not bar') # The original select should not be modified. assert s._execution_options == dict(foo='bar') # s2 should have its execution_options based on s, though. assert s2._execution_options == dict(foo='bar', bar='baz') assert s3._execution_options == dict(foo='not bar') def test_invalid_options(self): assert_raises( exc.ArgumentError, select().execution_options, compiled_cache={} ) assert_raises( exc.ArgumentError, select().execution_options, isolation_level='READ_COMMITTED' ) # this feature not available yet def _NOTYET_test_execution_options_in_kwargs(self): s = select(execution_options=dict(foo='bar')) s2 = s.execution_options(bar='baz') # The original select should not be modified. assert s._execution_options == dict(foo='bar') # s2 should have its execution_options based on s, though. assert s2._execution_options == dict(foo='bar', bar='baz') # this feature not available yet def _NOTYET_test_execution_options_in_text(self): s = text('select 42', execution_options=dict(foo='bar')) assert s._execution_options == dict(foo='bar') class InsertTest(fixtures.TestBase, AssertsCompiledSQL): """Tests the generative capability of Insert""" __dialect__ = 'default' # fixme: consolidate converage from elsewhere here and expand @classmethod def setup_class(cls): global t1, t2 t1 = table("table1", column("col1"), column("col2"), column("col3"), ) t2 = table("table2", column("col1"), column("col2"), column("col3"), ) def test_prefixes(self): i = t1.insert() self.assert_compile(i, "INSERT INTO table1 (col1, col2, col3) " "VALUES (:col1, :col2, :col3)") gen = i.prefix_with("foober") self.assert_compile(gen, "INSERT foober INTO table1 (col1, col2, col3) " "VALUES (:col1, :col2, :col3)") self.assert_compile(i, "INSERT INTO table1 (col1, col2, col3) " "VALUES (:col1, :col2, :col3)") i2 = t1.insert(prefixes=['squiznart']) self.assert_compile(i2, "INSERT squiznart INTO table1 (col1, col2, col3) " "VALUES (:col1, :col2, :col3)") gen2 = i2.prefix_with("quux") self.assert_compile(gen2, "INSERT squiznart quux INTO " "table1 (col1, col2, col3) " "VALUES (:col1, :col2, :col3)")
# -*- coding: utf-8 -*- import json import operator from django.db import models from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError from django.core.cache import cache from django.utils import timezone from django.conf import settings from django.template.defaultfilters import slugify from django.contrib.sites.models import Site from polymorphic import PolymorphicModel from polymorphic.showfields import ShowFieldContent from opps.core.cache import _cache_key from opps.core.models import Publishable, Slugged, Channeling, Imaged from opps.core.tags.models import Tagged from opps.db.models.fields import JSONField from opps.boxes.models import BaseBox from .managers import ContainerManager from .signals import shorturl_generate, delete_container from .tasks import check_mirror_channel, check_mirror_site class Container(PolymorphicModel, ShowFieldContent, Publishable, Slugged, Channeling, Imaged, Tagged): title = models.CharField(_(u"Title"), max_length=140, db_index=True) hat = models.CharField( _(u"Hat"), max_length=140, null=True, blank=True, ) short_url = models.URLField( _(u"Short URL"), null=True, blank=True, ) child_class = models.CharField( _(u'Child class'), max_length=30, null=True, blank=True, db_index=True ) child_module = models.CharField( _(u'Child module'), max_length=120, null=True, blank=True, db_index=True ) child_app_label = models.CharField( _(u'Child app label'), max_length=30, null=True, blank=True, db_index=True ) show_on_root_channel = models.BooleanField( _(u"Show on root channel?"), default=True ) source = models.CharField( _('Source'), null=True, blank=True, max_length=255) json = JSONField(_(u"Customized"), null=True, blank=True) related_containers = models.ManyToManyField( 'containers.Container', null=True, blank=True, related_name='container_relatedcontainers', through='containers.ContainerRelated', ) objects = ContainerManager() def __unicode__(self): return u"{0}".format(self.get_absolute_url()) def __repr__(self): val = self.__unicode__() if isinstance(val, str): return val elif not isinstance(val, unicode): val = unicode(val) return val.encode('utf8') class Meta: ordering = ['-date_available'] verbose_name = _(u'Container') verbose_name_plural = _(u'Containers') unique_together = ("site", "channel", "slug") def save(self, *args, **kwargs): if not self.channel_name: self.channel_name = self.channel.name if not self.channel_long_slug: self.channel_long_slug = self.channel.long_slug self.child_class = self.__class__.__name__ self.child_module = self.__class__.__module__ self.child_app_label = self._meta.app_label if self.slug == u"": self.slug = slugify(self.title) models.signals.post_save.connect(shorturl_generate, sender=self.__class__) super(Container, self).save(*args, **kwargs) if settings.OPPS_MIRROR_CHANNEL and ( self.mirror_channel or self.mirror_site)\ and self.child_class != u"Mirror": check_mirror_channel.delay( container=self, Mirror=Mirror) check_mirror_site.delay( container=self, Mirror=Mirror) def get_absolute_url(self): if self.channel.homepage: return u"/{0}.html".format(self.slug) return u"/{0}/{1}.html".format(self.channel_long_slug, self.slug) @classmethod def get_children_models(cls): children = models.get_models() return [model for model in children if (model is not None and issubclass(model, cls) and model is not cls)] def get_thumb(self): return self.main_image @property def search_category(self): """for use in search result""" return _(self.child_class) def get_http_absolute_url(self): return u"http://{0}{1}".format(self.site_domain, self.get_absolute_url()) get_http_absolute_url.short_description = _(u'Get HTTP Absolute URL') def recommendation(self, child_class=False, query_slice=[None, 10]): if not child_class: child_class = self.child_class now = timezone.now() start = now - timezone.timedelta( days=settings.OPPS_RECOMMENDATION_RANGE_DAYS ) cachekey = _cache_key( u'{0}-recommendation'.format(self.__class__.__name__), self.__class__, self.site_domain, u"{0}-{1}-{2}".format(child_class, self.channel_long_slug, self.slug)) getcache = cache.get(cachekey) if getcache: return getcache containers = Container.objects.filter( site_domain=self.site_domain, child_class=child_class, channel_long_slug=self.channel_long_slug, date_available__range=(start, now), published=True ).exclude(pk=self.pk) tag_list = [] if self.tags: tag_list = [t for t in self.tags.split(',')[:3]] containers = containers.filter( reduce(operator.or_, (Q(tags__contains=tag) for tag in tag_list)), ) containers = containers.distinct().order_by( '-date_available')[slice(*query_slice)] _list = [a for a in containers] cache.set(cachekey, _list, 3600) return _list def inbox(self, containerbox=None): obj = ContainerBoxContainers.objects if containerbox: return obj.get(container=self.id, containerbox__slug=containerbox) return obj.filter(container=self.id) def custom_fields(self): if not self.json: return {} return json.loads(self.json) class ContainerImage(models.Model): container = models.ForeignKey( 'containers.Container', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_(u'Container'), ) order = models.PositiveIntegerField(_(u'Order'), default=0) image = models.ForeignKey( 'images.Image', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_(u'Image'), ) caption = models.CharField( _(u"Caption"), max_length=255, blank=True, null=True ) class Meta: verbose_name = _(u'Container image') verbose_name_plural = _(u'Container images') ordering = ('order',) def __unicode__(self): if self.image: return u"{0}".format(self.image.title) return u'Id:{0} - Order:{1}'.format(self.id, self.order) class ContainerBox(BaseBox): title = models.CharField( _(u"Title"), null=True, blank=True, max_length=140, ) title_url = models.CharField( _(u"Title Link"), null=True, blank=True, max_length=250, ) main_image = models.ForeignKey( 'images.Image', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_(u'Main Image'), ) main_image_caption = models.CharField( _(u"Main Image Caption"), max_length=4000, blank=True, null=True, help_text=_(u'Maximum characters 4000'), ) containers = models.ManyToManyField( 'containers.Container', null=True, blank=True, verbose_name=_(u'Container'), related_name='containerbox_containers', through='containers.ContainerBoxContainers' ) queryset = models.ForeignKey( 'boxes.QuerySet', null=True, blank=True, related_name='containerbox_querysets', verbose_name=_(u'Query Set') ) content_group = models.CharField( _(u"Content Group"), max_length=255, default='default', help_text=_(u"Boxes in the same group do not allow repetitions") ) class Meta: verbose_name = _(u'Container box') verbose_name_plural = _(u'Containers boxes') def __init__(self, *args, **kwargs): """ to avoid re-execution of methods its results are cached in a local storage per instance cache """ super(ContainerBox, self).__init__(*args, **kwargs) if not hasattr(self, 'local_cache'): self.local_cache = {} @property def has_content(self): # TODO: should check start/end available_dates if self.containerboxcontainers_set.exists(): return True qs = self.get_queryset(use_local_cache=False) if qs and qs.exists(): return True def ordered_containers(self, field='order', exclude_ids=None): cached = self.local_cache.get('ordered_containers', None) if cached: return cached exclude_ids = exclude_ids or [] now = timezone.now() fallback = getattr(settings, 'OPPS_MULTISITE_FALLBACK', False) if not fallback: qs = self.containers.filter( models.Q(containerboxcontainers__date_end__gte=now) | models.Q(containerboxcontainers__date_end__isnull=True), published=True, date_available__lte=now, containerboxcontainers__date_available__lte=now ).exclude( id__in=exclude_ids ).order_by('containerboxcontainers__order').distinct() else: site_master = cache.get("site_master") if not site_master: site_master = Site.objects.order_by('id')[0] cache.set('site_master', site_master, 3600) boxes = [self] if fallback and site_master.pk != self.site_id: try: master_box = self.__class__.objects.get( site=site_master, slug=self.slug ) boxes.insert(0, master_box) except self.__class__.DoesNotExist: pass qs = ContainerBoxContainers.objects.filter( models.Q(date_end__gte=now) | models.Q(date_end__isnull=True), models.Q(container__published=True, container__date_available__lte=now) | models.Q(container__isnull=True), containerbox__in=boxes, date_available__lte=now, ).exclude( container__id__in=exclude_ids ).order_by('-containerbox__site__id', 'order').distinct() self.local_cache['ordered_containers'] = qs return qs def ordered_box_containers(self, exclude_ids=None): fallback = getattr(settings, 'OPPS_MULTISITE_FALLBACK', False) if fallback: return self.ordered_containers(exclude_ids=exclude_ids) cached = self.local_cache.get('ordered_box_containers') if cached: return cached exclude_ids = exclude_ids or [] now = timezone.now() qs = self.containerboxcontainers_set.prefetch_related( 'main_image', 'container', 'container__main_image', 'container__channel') qs = qs.filter( models.Q(date_end__gte=now) | models.Q(date_end__isnull=True), date_available__lte=now ).exclude( container_id__in=exclude_ids ).order_by('order').distinct() self.local_cache['ordered_box_containers'] = qs return qs def get_containers_queryset(self): if self.queryset: return self.queryset.get_queryset() else: return self.ordered_containers() def get_queryset(self, exclude_ids=None, use_local_cache=True): cached = self.local_cache.get('get_queryset') if use_local_cache and cached: return cached queryset = self.queryset and self.queryset.get_queryset( content_group=self.content_group, exclude_ids=exclude_ids, use_local_cache=use_local_cache ) if use_local_cache: self.local_cache['get_queryset'] = queryset return queryset class ContainerBoxContainers(models.Model): URL_TARGET_CHOICES = ( ('_blank', _(u'Load in a new window')), ('_self', _(u'Load in the same frame as it was clicked')), ('_parent', _(u'Load in the parent frameset')), ('_top', _(u'Load in the full body of the window')) ) containerbox = models.ForeignKey( 'containers.ContainerBox', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_(u'Container Box'), ) container = models.ForeignKey( 'containers.Container', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_(u'Container'), ) order = models.PositiveIntegerField(_(u'Order'), default=0) aggregate = models.BooleanField(_(u'Aggregate container'), default=False) highlight = models.BooleanField(_(u'Highlight container'), default=False) date_available = models.DateTimeField(_(u"Date available"), default=timezone.now, null=True) date_end = models.DateTimeField(_(u"End date"), null=True, blank=True) title = models.CharField(_(u"Title"), max_length=140, null=True, blank=True) hat = models.CharField( _(u"Hat"), max_length=140, null=True, blank=True, ) main_image = models.ForeignKey( 'images.Image', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_(u'Main Image'), ) main_image_caption = models.CharField( _(u"Main Image Caption"), max_length=4000, blank=True, null=True, help_text=_(u'Maximum characters 4000'), ) url = models.CharField(_(u"URL"), max_length=255, null=True, blank=True) url_target = models.CharField(_(u"URL Target"), max_length=255, choices=URL_TARGET_CHOICES, default="_self", null=True, blank=True) class Meta: ordering = ('order',) verbose_name = _(u'Article box articles') verbose_name_plural = _(u'Article boxes articles') ordering = ('order', 'aggregate',) def __unicode__(self): if self.container: return u"{0}-{1}".format(self.containerbox.slug, self.container.slug) else: return u"{0}".format(self.containerbox.slug) def clean(self): if not self.container and not self.url: raise ValidationError(_(u'Please select a Container or insert a ' u'URL!')) if self.container and not self.container.published: raise ValidationError(_(u'Article not published!')) class ContainerRelated(models.Model): container = models.ForeignKey( 'containers.Container', verbose_name=_(u'Container'), related_name='containerrelated_container' ) related = models.ForeignKey( 'containers.Container', verbose_name=_(u'Related Container'), related_name="%(app_label)s_%(class)s_container" ) order = models.PositiveIntegerField(_(u'Order'), default=0) class Meta: verbose_name = _('Related content') verbose_name_plural = _('Related contents') ordering = ('order',) def __unicode__(self): return u"{0}->{1}".format(self.related.slug, self.container.slug) class Mirror(Container): container = models.ForeignKey('containers.Container', related_name='containers_mirror', verbose_name=_(u'Container')) class Meta: verbose_name = _(u'Mirror') verbose_name_plural = _(u'Mirrors') models.signals.post_delete.connect(delete_container, sender=Container)
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=invalid-name """Built-in optimizer classes. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import six from six.moves import zip # pylint: disable=redefined-builtin from tensorflow.python.eager import context from tensorflow.python.framework import dtypes as dtypes_module from tensorflow.python.framework import ops from tensorflow.python.keras._impl.keras import backend as K from tensorflow.python.keras._impl.keras.utils.generic_utils import deserialize_keras_object from tensorflow.python.keras._impl.keras.utils.generic_utils import serialize_keras_object from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.training import optimizer as tf_optimizer_module def clip_norm(g, c, n): """Clip a tensor by norm. Arguments: g: gradient tensor to clip. c: clipping threshold. n: norm of gradient tensor. Returns: Clipped gradient tensor. """ if c > 0: condition = n >= c then_expression = lambda: math_ops.scalar_mul(c / n, g) else_expression = lambda: g # saving the shape to avoid converting sparse tensor to dense if isinstance(g, ops.Tensor): g_shape = copy.copy(g.get_shape()) elif isinstance(g, ops.IndexedSlices): g_shape = copy.copy(g.dense_shape) if condition.dtype != dtypes_module.bool: condition = math_ops.cast(condition, 'bool') g = control_flow_ops.cond(condition, then_expression, else_expression) if isinstance(g, ops.Tensor): g.set_shape(g_shape) elif isinstance(g, ops.IndexedSlices): g._dense_shape = g_shape # pylint: disable=protected-access return g class Optimizer(object): """Abstract optimizer base class. Note: this is the parent class of all optimizers, not an actual optimizer that can be used for training models. All Keras optimizers support the following keyword arguments: clipnorm: float >= 0. Gradients will be clipped when their L2 norm exceeds this value. clipvalue: float >= 0. Gradients will be clipped when their absolute value exceeds this value. """ def __init__(self, **kwargs): allowed_kwargs = {'clipnorm', 'clipvalue'} for k in kwargs: if k not in allowed_kwargs: raise TypeError('Unexpected keyword argument ' 'passed to optimizer: ' + str(k)) self.__dict__.update(kwargs) self.updates = [] self.weights = [] def get_updates(self, loss, params): raise NotImplementedError def get_gradients(self, loss, params): grads = K.gradients(loss, params) if hasattr(self, 'clipnorm') and self.clipnorm > 0: norm = K.sqrt(sum([K.sum(K.square(g)) for g in grads])) grads = [clip_norm(g, self.clipnorm, norm) for g in grads] if hasattr(self, 'clipvalue') and self.clipvalue > 0: grads = [K.clip(g, -self.clipvalue, self.clipvalue) for g in grads] return grads def set_weights(self, weights): """Sets the weights of the optimizer, from Numpy arrays. Should only be called after computing the gradients (otherwise the optimizer has no weights). Arguments: weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the optimizer (i.e. it should match the output of `get_weights`). Raises: ValueError: in case of incompatible weight shapes. """ params = self.weights weight_value_tuples = [] param_values = K.batch_get_value(params) for pv, p, w in zip(param_values, params, weights): if pv.shape != w.shape: raise ValueError( 'Optimizer weight shape ' + str(pv.shape) + ' not compatible with ' 'provided weight shape ' + str(w.shape)) weight_value_tuples.append((p, w)) K.batch_set_value(weight_value_tuples) def get_weights(self): """Returns the current value of the weights of the optimizer. Returns: A list of numpy arrays. """ return K.batch_get_value(self.weights) def get_config(self): config = {} if hasattr(self, 'clipnorm'): config['clipnorm'] = self.clipnorm if hasattr(self, 'clipvalue'): config['clipvalue'] = self.clipvalue return config @classmethod def from_config(cls, config): return cls(**config) class SGD(Optimizer): """Stochastic gradient descent optimizer. Includes support for momentum, learning rate decay, and Nesterov momentum. Arguments: lr: float >= 0. Learning rate. momentum: float >= 0. Parameter that accelerates SGD in the relevant direction and dampens oscillations. decay: float >= 0. Learning rate decay over each update. nesterov: boolean. Whether to apply Nesterov momentum. """ def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False, **kwargs): super(SGD, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.iterations = K.variable(0, dtype='int64', name='iterations') self.lr = K.variable(lr, name='lr') self.momentum = K.variable(momentum, name='momentum') self.decay = K.variable(decay, name='decay') self.initial_decay = decay self.nesterov = nesterov def get_updates(self, loss, params): grads = self.get_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr *= (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) # momentum shapes = [K.int_shape(p) for p in params] moments = [K.zeros(shape) for shape in shapes] self.weights = [self.iterations] + moments for p, g, m in zip(params, grads, moments): v = self.momentum * m - lr * g # velocity self.updates.append(K.update(m, v)) if self.nesterov: new_p = p + self.momentum * v - lr * g else: new_p = p + v # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'momentum': float(K.get_value(self.momentum)), 'decay': float(K.get_value(self.decay)), 'nesterov': self.nesterov } base_config = super(SGD, self).get_config() return dict(list(base_config.items()) + list(config.items())) class RMSprop(Optimizer): """RMSProp optimizer. It is recommended to leave the parameters of this optimizer at their default values (except the learning rate, which can be freely tuned). This optimizer is usually a good choice for recurrent neural networks. Arguments: lr: float >= 0. Learning rate. rho: float >= 0. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. decay: float >= 0. Learning rate decay over each update. """ def __init__(self, lr=0.001, rho=0.9, epsilon=None, decay=0., **kwargs): super(RMSprop, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.lr = K.variable(lr, name='lr') self.rho = K.variable(rho, name='rho') self.decay = K.variable(decay, name='decay') self.iterations = K.variable(0, dtype='int64', name='iterations') if epsilon is None: epsilon = K.epsilon() self.epsilon = epsilon self.initial_decay = decay def get_updates(self, loss, params): grads = self.get_gradients(loss, params) accumulators = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] self.weights = accumulators self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr *= (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) for p, g, a in zip(params, grads, accumulators): # update accumulator new_a = self.rho * a + (1. - self.rho) * K.square(g) self.updates.append(K.update(a, new_a)) new_p = p - lr * g / (K.sqrt(new_a) + self.epsilon) # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'rho': float(K.get_value(self.rho)), 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon } base_config = super(RMSprop, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Adagrad(Optimizer): """Adagrad optimizer. It is recommended to leave the parameters of this optimizer at their default values. Arguments: lr: float >= 0. Learning rate. epsilon: float >= 0. If `None`, defaults to `K.epsilon()`. decay: float >= 0. Learning rate decay over each update. """ def __init__(self, lr=0.01, epsilon=None, decay=0., **kwargs): super(Adagrad, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.lr = K.variable(lr, name='lr') self.decay = K.variable(decay, name='decay') self.iterations = K.variable(0, dtype='int64', name='iterations') if epsilon is None: epsilon = K.epsilon() self.epsilon = epsilon self.initial_decay = decay def get_updates(self, loss, params): grads = self.get_gradients(loss, params) shapes = [K.int_shape(p) for p in params] accumulators = [K.zeros(shape) for shape in shapes] self.weights = accumulators self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr *= (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) for p, g, a in zip(params, grads, accumulators): new_a = a + K.square(g) # update accumulator self.updates.append(K.update(a, new_a)) new_p = p - lr * g / (K.sqrt(new_a) + self.epsilon) # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon } base_config = super(Adagrad, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Adadelta(Optimizer): """Adadelta optimizer. It is recommended to leave the parameters of this optimizer at their default values. Arguments: lr: float >= 0. Learning rate. It is recommended to leave it at the default value. rho: float >= 0. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. decay: float >= 0. Learning rate decay over each update. """ def __init__(self, lr=1.0, rho=0.95, epsilon=None, decay=0., **kwargs): super(Adadelta, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.lr = K.variable(lr, name='lr') self.decay = K.variable(decay, name='decay') self.iterations = K.variable(0, dtype='int64', name='iterations') if epsilon is None: epsilon = K.epsilon() self.rho = rho self.epsilon = epsilon self.initial_decay = decay def get_updates(self, loss, params): grads = self.get_gradients(loss, params) shapes = [K.int_shape(p) for p in params] accumulators = [K.zeros(shape) for shape in shapes] delta_accumulators = [K.zeros(shape) for shape in shapes] self.weights = accumulators + delta_accumulators self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr *= (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) for p, g, a, d_a in zip(params, grads, accumulators, delta_accumulators): # update accumulator new_a = self.rho * a + (1. - self.rho) * K.square(g) self.updates.append(K.update(a, new_a)) # use the new accumulator and the *old* delta_accumulator update = g * K.sqrt(d_a + self.epsilon) / K.sqrt(new_a + self.epsilon) new_p = p - lr * update # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) # update delta_accumulator new_d_a = self.rho * d_a + (1 - self.rho) * K.square(update) self.updates.append(K.update(d_a, new_d_a)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'rho': self.rho, 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon } base_config = super(Adadelta, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Adam(Optimizer): """Adam optimizer. Default parameters follow those provided in the original paper. Arguments: lr: float >= 0. Learning rate. beta_1: float, 0 < beta < 1. Generally close to 1. beta_2: float, 0 < beta < 1. Generally close to 1. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. decay: float >= 0. Learning rate decay over each update. amsgrad: boolean. Whether to apply the AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and Beyond". """ def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0., amsgrad=False, **kwargs): super(Adam, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.iterations = K.variable(0, dtype='int64', name='iterations') self.lr = K.variable(lr, name='lr') self.beta_1 = K.variable(beta_1, name='beta_1') self.beta_2 = K.variable(beta_2, name='beta_2') self.decay = K.variable(decay, name='decay') if epsilon is None: epsilon = K.epsilon() self.epsilon = epsilon self.initial_decay = decay self.amsgrad = amsgrad def get_updates(self, loss, params): grads = self.get_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr *= (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) t = K.cast(self.iterations, K.floatx()) + 1 lr_t = lr * ( K.sqrt(1. - K.pow(self.beta_2, t)) / (1. - K.pow(self.beta_1, t))) ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] if self.amsgrad: vhats = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] else: vhats = [K.zeros(1) for _ in params] self.weights = [self.iterations] + ms + vs + vhats for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats): m_t = (self.beta_1 * m) + (1. - self.beta_1) * g v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g) if self.amsgrad: vhat_t = K.maximum(vhat, v_t) p_t = p - lr_t * m_t / (K.sqrt(vhat_t) + self.epsilon) self.updates.append(K.update(vhat, vhat_t)) else: p_t = p - lr_t * m_t / (K.sqrt(v_t) + self.epsilon) self.updates.append(K.update(m, m_t)) self.updates.append(K.update(v, v_t)) new_p = p_t # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'beta_1': float(K.get_value(self.beta_1)), 'beta_2': float(K.get_value(self.beta_2)), 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon, 'amsgrad': self.amsgrad } base_config = super(Adam, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Adamax(Optimizer): """Adamax optimizer from Adam paper's Section 7. It is a variant of Adam based on the infinity norm. Default parameters follow those provided in the paper. Arguments: lr: float >= 0. Learning rate. beta_1/beta_2: floats, 0 < beta < 1. Generally close to 1. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. decay: float >= 0. Learning rate decay over each update. """ def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0., **kwargs): super(Adamax, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.iterations = K.variable(0, dtype='int64', name='iterations') self.lr = K.variable(lr, name='lr') self.beta_1 = K.variable(beta_1, name='beta_1') self.beta_2 = K.variable(beta_2, name='beta_2') self.decay = K.variable(decay, name='decay') if epsilon is None: epsilon = K.epsilon() self.epsilon = epsilon self.initial_decay = decay def get_updates(self, loss, params): grads = self.get_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr *= (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) t = K.cast(self.iterations, K.floatx()) + 1 lr_t = lr / (1. - K.pow(self.beta_1, t)) shapes = [K.int_shape(p) for p in params] # zero init of 1st moment ms = [K.zeros(shape) for shape in shapes] # zero init of exponentially weighted infinity norm us = [K.zeros(shape) for shape in shapes] self.weights = [self.iterations] + ms + us for p, g, m, u in zip(params, grads, ms, us): m_t = (self.beta_1 * m) + (1. - self.beta_1) * g u_t = K.maximum(self.beta_2 * u, K.abs(g)) p_t = p - lr_t * m_t / (u_t + self.epsilon) self.updates.append(K.update(m, m_t)) self.updates.append(K.update(u, u_t)) new_p = p_t # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'beta_1': float(K.get_value(self.beta_1)), 'beta_2': float(K.get_value(self.beta_2)), 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon } base_config = super(Adamax, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Nadam(Optimizer): """Nesterov Adam optimizer. Much like Adam is essentially RMSprop with momentum, Nadam is Adam RMSprop with Nesterov momentum. Default parameters follow those provided in the paper. It is recommended to leave the parameters of this optimizer at their default values. Arguments: lr: float >= 0. Learning rate. beta_1/beta_2: floats, 0 < beta < 1. Generally close to 1. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. """ def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004, **kwargs): super(Nadam, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.iterations = K.variable(0, dtype='int64', name='iterations') self.m_schedule = K.variable(1., name='m_schedule') self.lr = K.variable(lr, name='lr') self.beta_1 = K.variable(beta_1, name='beta_1') self.beta_2 = K.variable(beta_2, name='beta_2') if epsilon is None: epsilon = K.epsilon() self.epsilon = epsilon self.schedule_decay = schedule_decay def get_updates(self, loss, params): grads = self.get_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] t = K.cast(self.iterations, K.floatx()) + 1 # Due to the recommendations in [2], i.e. warming momentum schedule momentum_cache_t = self.beta_1 * ( 1. - 0.5 * (K.pow(K.cast_to_floatx(0.96), t * self.schedule_decay))) momentum_cache_t_1 = self.beta_1 * ( 1. - 0.5 * (K.pow(K.cast_to_floatx(0.96), (t + 1) * self.schedule_decay))) m_schedule_new = self.m_schedule * momentum_cache_t m_schedule_next = self.m_schedule * momentum_cache_t * momentum_cache_t_1 self.updates.append((self.m_schedule, m_schedule_new)) shapes = [K.int_shape(p) for p in params] ms = [K.zeros(shape) for shape in shapes] vs = [K.zeros(shape) for shape in shapes] self.weights = [self.iterations] + ms + vs for p, g, m, v in zip(params, grads, ms, vs): # the following equations given in [1] g_prime = g / (1. - m_schedule_new) m_t = self.beta_1 * m + (1. - self.beta_1) * g m_t_prime = m_t / (1. - m_schedule_next) v_t = self.beta_2 * v + (1. - self.beta_2) * K.square(g) v_t_prime = v_t / (1. - K.pow(self.beta_2, t)) m_t_bar = ( 1. - momentum_cache_t) * g_prime + momentum_cache_t_1 * m_t_prime self.updates.append(K.update(m, m_t)) self.updates.append(K.update(v, v_t)) p_t = p - self.lr * m_t_bar / (K.sqrt(v_t_prime) + self.epsilon) new_p = p_t # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'beta_1': float(K.get_value(self.beta_1)), 'beta_2': float(K.get_value(self.beta_2)), 'epsilon': self.epsilon, 'schedule_decay': self.schedule_decay } base_config = super(Nadam, self).get_config() return dict(list(base_config.items()) + list(config.items())) class TFOptimizer(Optimizer): """Wrapper class for native TensorFlow optimizers. """ def __init__(self, optimizer): # pylint: disable=super-init-not-called self.optimizer = optimizer with K.name_scope(self.__class__.__name__): if context.in_graph_mode(): self.iterations = K.variable(0, dtype='int64', name='iterations') def apply_gradients(self, grads): self.optimizer.apply_gradients(grads) def get_grads(self, loss, params): return self.optimizer.compute_gradients(loss, params) def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, global_step=self.iterations) self.updates.append(opt_update) return self.updates @property def weights(self): raise NotImplementedError def get_config(self): raise NotImplementedError def from_config(self, config): raise NotImplementedError # Aliases. sgd = SGD rmsprop = RMSprop adagrad = Adagrad adadelta = Adadelta adam = Adam adamax = Adamax nadam = Nadam def serialize(optimizer): return serialize_keras_object(optimizer) def deserialize(config, custom_objects=None): """Inverse of the `serialize` function. Arguments: config: Optimizer configuration dictionary. custom_objects: Optional dictionary mapping names (strings) to custom objects (classes and functions) to be considered during deserialization. Returns: A Keras Optimizer instance. """ all_classes = { 'sgd': SGD, 'rmsprop': RMSprop, 'adagrad': Adagrad, 'adadelta': Adadelta, 'adam': Adam, 'adamax': Adamax, 'nadam': Nadam, 'tfoptimizer': TFOptimizer, } # Make deserialization case-insensitive for built-in optimizers. if config['class_name'].lower() in all_classes: config['class_name'] = config['class_name'].lower() return deserialize_keras_object( config, module_objects=all_classes, custom_objects=custom_objects, printable_module_name='optimizer') def get(identifier): """Retrieves a Keras Optimizer instance. Arguments: identifier: Optimizer identifier, one of - String: name of an optimizer - Dictionary: configuration dictionary. - Keras Optimizer instance (it will be returned unchanged). - TensorFlow Optimizer instance (it will be wrapped as a Keras Optimizer). Returns: A Keras Optimizer instance. Raises: ValueError: If `identifier` cannot be interpreted. """ # Wrap TF optimizer instances if isinstance(identifier, tf_optimizer_module.Optimizer): return TFOptimizer(identifier) if isinstance(identifier, dict): return deserialize(identifier) elif isinstance(identifier, six.string_types): config = {'class_name': str(identifier), 'config': {}} return deserialize(config) if isinstance(identifier, Optimizer): return identifier else: raise ValueError('Could not interpret optimizer identifier:', identifier)
#!/usr/bin/env python # # VM Backup extension # # Copyright 2014 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os try: import urlparse as urlparser except ImportError: import urllib.parse as urlparser import traceback import datetime try: import ConfigParser as ConfigParsers except ImportError: import configparser as ConfigParsers import multiprocessing as mp import datetime from common import CommonVariables from HttpUtil import HttpUtil from Utils import Status from Utils import HandlerUtil from fsfreezer import FsFreezer from Utils import HostSnapshotObjects class SnapshotInfoIndexerObj(): def __init__(self, index, isSuccessful, snapshotTs, errorMessage): self.index = index self.isSuccessful = isSuccessful self.snapshotTs = snapshotTs self.errorMessage = errorMessage self.statusCode = 500 def __str__(self): return 'index: ' + str(self.index) + ' isSuccessful: ' + str(self.isSuccessful) + ' snapshotTs: ' + str(self.snapshotTs) + ' errorMessage: ' + str(self.errorMessage) + ' statusCode: ' + str(self.statusCode) class SnapshotError(object): def __init__(self): self.errorcode = CommonVariables.success self.sasuri = None def __str__(self): return 'errorcode: ' + str(self.errorcode) class SnapshotResult(object): def __init__(self): self.errors = [] def __str__(self): error_str = "" for error in self.errors: error_str+=(str(error)) + "\n" return error_str class GuestSnapshotter(object): """description of class""" def __init__(self, logger, hutil): self.logger = logger self.configfile='/etc/azure/vmbackup.conf' self.hutil = hutil def snapshot(self, sasuri, sasuri_index, meta_data, snapshot_result_error, snapshot_info_indexer_queue, global_logger, global_error_logger): temp_logger='' error_logger='' snapshot_error = SnapshotError() snapshot_info_indexer = SnapshotInfoIndexerObj(sasuri_index, False, None, None) if(sasuri is None): error_logger = error_logger + str(datetime.datetime.utcnow()) + " Failed to do the snapshot because sasuri is none " snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri try: sasuri_obj = urlparser.urlparse(sasuri) if(sasuri_obj is None or sasuri_obj.hostname is None): error_logger = error_logger + str(datetime.datetime.utcnow()) + " Failed to parse the sasuri " snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri else: start_time = datetime.datetime.utcnow() body_content = '' headers = {} headers["Content-Length"] = '0' if(meta_data is not None): for meta in meta_data: key = meta['Key'] value = meta['Value'] headers["x-ms-meta-" + key] = value temp_logger = temp_logger + str(headers) http_util = HttpUtil(self.logger) sasuri_obj = urlparser.urlparse(sasuri + '&comp=snapshot') temp_logger = temp_logger + str(datetime.datetime.utcnow()) + ' start calling the snapshot rest api. ' # initiate http call for blob-snapshot and get http response result, httpResp, errMsg, responseBody = http_util.HttpCallGetResponse('PUT', sasuri_obj, body_content, headers = headers, responseBodyRequired = True) temp_logger = temp_logger + str("responseBody: " + responseBody) if(result == CommonVariables.success and httpResp != None): # retrieve snapshot information from http response snapshot_info_indexer, snapshot_error, message = self.httpresponse_get_snapshot_info(httpResp, sasuri_index, sasuri, responseBody) temp_logger = temp_logger + str(datetime.datetime.utcnow()) + ' httpresponse_get_snapshot_info message: ' + str(message) else: # HttpCall failed error_logger = error_logger + str(datetime.datetime.utcnow()) + " snapshot HttpCallGetResponse failed " error_logger = error_logger + str(datetime.datetime.utcnow()) + str(errMsg) snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri end_time = datetime.datetime.utcnow() time_taken=end_time-start_time temp_logger = temp_logger + str(datetime.datetime.utcnow()) + ' time taken for snapshot ' + str(time_taken) except Exception as e: errorMsg = " Failed to do the snapshot with error: %s, stack trace: %s" % (str(e), traceback.format_exc()) error_logger = error_logger + str(datetime.datetime.utcnow()) + errorMsg snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri temp_logger=temp_logger + str(datetime.datetime.utcnow()) + ' snapshot ends..' global_logger.put(temp_logger) global_error_logger.put(error_logger) snapshot_result_error.put(snapshot_error) snapshot_info_indexer_queue.put(snapshot_info_indexer) def snapshot_seq(self, sasuri, sasuri_index, meta_data): result = None snapshot_error = SnapshotError() snapshot_info_indexer = SnapshotInfoIndexerObj(sasuri_index, False, None, None) if(sasuri is None): self.logger.log("Failed to do the snapshot because sasuri is none",False,'Error') snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri try: sasuri_obj = urlparser.urlparse(sasuri) if(sasuri_obj is None or sasuri_obj.hostname is None): self.logger.log("Failed to parse the sasuri",False,'Error') snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri else: body_content = '' headers = {} headers["Content-Length"] = '0' if(meta_data is not None): for meta in meta_data: key = meta['Key'] value = meta['Value'] headers["x-ms-meta-" + key] = value self.logger.log(str(headers)) http_util = HttpUtil(self.logger) sasuri_obj = urlparser.urlparse(sasuri + '&comp=snapshot') self.logger.log("start calling the snapshot rest api") # initiate http call for blob-snapshot and get http response result, httpResp, errMsg, responseBody = http_util.HttpCallGetResponse('PUT', sasuri_obj, body_content, headers = headers, responseBodyRequired = True) self.logger.log("responseBody: " + responseBody) if(result == CommonVariables.success and httpResp != None): # retrieve snapshot information from http response snapshot_info_indexer, snapshot_error, message = self.httpresponse_get_snapshot_info(httpResp, sasuri_index, sasuri, responseBody) self.logger.log(' httpresponse_get_snapshot_info message: ' + str(message)) else: # HttpCall failed self.logger.log(" snapshot HttpCallGetResponse failed ") self.logger.log(str(errMsg)) snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri except Exception as e: errorMsg = "Failed to do the snapshot with error: %s, stack trace: %s" % (str(e), traceback.format_exc()) self.logger.log(errorMsg, False, 'Error') snapshot_error.errorcode = CommonVariables.error snapshot_error.sasuri = sasuri return snapshot_error, snapshot_info_indexer def snapshotall_parallel(self, paras, freezer, thaw_done, g_fsfreeze_on): self.logger.log("doing snapshotall now in parallel...") snapshot_result = SnapshotResult() blob_snapshot_info_array = [] all_failed = True exceptOccurred = False is_inconsistent = False thaw_done_local = thaw_done unable_to_sleep = False all_snapshots_failed = False set_next_backup_to_seq = False try: self.logger.log("before start of multiprocessing queues..") mp_jobs = [] queue_creation_starttime = datetime.datetime.now() global_logger = mp.Queue() global_error_logger = mp.Queue() snapshot_result_error = mp.Queue() snapshot_info_indexer_queue = mp.Queue() time_before_snapshot_start = datetime.datetime.utcnow() blobs = paras.blobs if blobs is not None: # initialize blob_snapshot_info_array mp_jobs = [] blob_index = 0 self.logger.log('****** 5. Snaphotting (Guest-parallel) Started') for blob in blobs: blobUri = blob.split("?")[0] self.logger.log("index: " + str(blob_index) + " blobUri: " + str(blobUri)) blob_snapshot_info_array.append(HostSnapshotObjects.BlobSnapshotInfo(False, blobUri, None, 500)) try: mp_jobs.append(mp.Process(target=self.snapshot,args=(blob, blob_index, paras.backup_metadata, snapshot_result_error, snapshot_info_indexer_queue, global_logger, global_error_logger))) except Exception as e: self.logger.log("multiprocess queue creation failed") all_snapshots_failed = True raise Exception("Exception while creating multiprocess queue") blob_index = blob_index + 1 counter = 0 for job in mp_jobs: job.start() if(counter == 0): queue_creation_endtime = datetime.datetime.now() timediff = queue_creation_endtime - queue_creation_starttime if(timediff.seconds >= 10): self.logger.log("mp queue creation took more than 10 secs. Setting next backup to sequential") set_next_backup_to_seq = True counter = counter + 1 for job in mp_jobs: job.join() self.logger.log('****** 6. Snaphotting (Guest-parallel) Completed') thaw_result = None if g_fsfreeze_on and thaw_done_local == False: time_before_thaw = datetime.datetime.now() thaw_result, unable_to_sleep = freezer.thaw_safe() time_after_thaw = datetime.datetime.now() HandlerUtil.HandlerUtility.add_to_telemetery_data("ThawTime", str(time_after_thaw-time_before_thaw)) thaw_done_local = True if(set_next_backup_to_seq == True): self.logger.log("Setting to sequential snapshot") self.hutil.set_value_to_configfile('seqsnapshot', '1') self.logger.log('T:S thaw result ' + str(thaw_result)) if(thaw_result is not None and len(thaw_result.errors) > 0 and (snapshot_result is None or len(snapshot_result.errors) == 0)): is_inconsistent = True snapshot_result.errors.append(thaw_result.errors) return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep, all_snapshots_failed self.logger.log('end of snapshot process') logging = [global_logger.get() for job in mp_jobs] self.logger.log(str(logging)) error_logging = [global_error_logger.get() for job in mp_jobs] self.logger.log(str(error_logging),False,'Error') if not snapshot_result_error.empty(): results = [snapshot_result_error.get() for job in mp_jobs] for result in results: if(result.errorcode != CommonVariables.success): snapshot_result.errors.append(result) if not snapshot_info_indexer_queue.empty(): snapshot_info_indexers = [snapshot_info_indexer_queue.get() for job in mp_jobs] for snapshot_info_indexer in snapshot_info_indexers: # update blob_snapshot_info_array element properties from snapshot_info_indexer object self.get_snapshot_info(snapshot_info_indexer, blob_snapshot_info_array[snapshot_info_indexer.index]) if (blob_snapshot_info_array[snapshot_info_indexer.index].isSuccessful == True): all_failed = False self.logger.log("index: " + str(snapshot_info_indexer.index) + " blobSnapshotUri: " + str(blob_snapshot_info_array[snapshot_info_indexer.index].snapshotUri)) all_snapshots_failed = all_failed self.logger.log("Setting all_snapshots_failed to " + str(all_snapshots_failed)) return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep, all_snapshots_failed else: self.logger.log("the blobs are None") return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep except Exception as e: errorMsg = " Unable to perform parallel snapshot with error: %s, stack trace: %s" % (str(e), traceback.format_exc()) self.logger.log(errorMsg) exceptOccurred = True return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep, all_snapshots_failed def snapshotall_seq(self, paras, freezer, thaw_done, g_fsfreeze_on): exceptOccurred = False self.logger.log("doing snapshotall now in sequence...") snapshot_result = SnapshotResult() blob_snapshot_info_array = [] all_failed = True is_inconsistent = False thaw_done_local = thaw_done unable_to_sleep = False all_snapshots_failed = False try: blobs = paras.blobs if blobs is not None: blob_index = 0 self.logger.log('****** 5. Snaphotting (Guest-seq) Started') for blob in blobs: blobUri = blob.split("?")[0] self.logger.log("index: " + str(blob_index) + " blobUri: " + str(blobUri)) blob_snapshot_info_array.append(HostSnapshotObjects.BlobSnapshotInfo(False, blobUri, None, 500)) snapshotError, snapshot_info_indexer = self.snapshot_seq(blob, blob_index, paras.backup_metadata) if(snapshotError.errorcode != CommonVariables.success): snapshot_result.errors.append(snapshotError) # update blob_snapshot_info_array element properties from snapshot_info_indexer object self.get_snapshot_info(snapshot_info_indexer, blob_snapshot_info_array[blob_index]) if (blob_snapshot_info_array[blob_index].isSuccessful == True): all_failed = False blob_index = blob_index + 1 self.logger.log('****** 6. Snaphotting (Guest-seq) Completed') all_snapshots_failed = all_failed self.logger.log("Setting all_snapshots_failed to " + str(all_snapshots_failed)) thaw_result= None if g_fsfreeze_on and thaw_done_local== False: time_before_thaw = datetime.datetime.now() thaw_result, unable_to_sleep = freezer.thaw_safe() time_after_thaw = datetime.datetime.now() HandlerUtil.HandlerUtility.add_to_telemetery_data("ThawTime", str(time_after_thaw-time_before_thaw)) thaw_done_local = True self.logger.log('T:S thaw result ' + str(thaw_result)) if(thaw_result is not None and len(thaw_result.errors) > 0 and (snapshot_result is None or len(snapshot_result.errors) == 0)): snapshot_result.errors.append(thaw_result.errors) is_inconsistent= True return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep, all_snapshots_failed else: self.logger.log("the blobs are None") return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep except Exception as e: errorMsg = " Unable to perform sequential snapshot with error: %s, stack trace: %s" % (str(e), traceback.format_exc()) self.logger.log(errorMsg) exceptOccurred = True return snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done_local, unable_to_sleep, all_snapshots_failed def snapshotall(self, paras, freezer, g_fsfreeze_on): thaw_done = False if (self.hutil.get_intvalue_from_configfile('seqsnapshot',0) == 1 or self.hutil.get_intvalue_from_configfile('seqsnapshot',0) == 2 or (len(paras.blobs) <= 4)): snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done, unable_to_sleep, all_snapshots_failed = self.snapshotall_seq(paras, freezer, thaw_done, g_fsfreeze_on) else: snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent, thaw_done, unable_to_sleep, all_snapshots_failed = self.snapshotall_parallel(paras, freezer, thaw_done, g_fsfreeze_on) self.logger.log("exceptOccurred : " + str(exceptOccurred) + " thaw_done : " + str(thaw_done) + " all_snapshots_failed : " + str(all_snapshots_failed)) if exceptOccurred and thaw_done == False and all_snapshots_failed: self.logger.log("Trying sequential snapshotting as parallel snapshotting failed") snapshot_result, blob_snapshot_info_array, all_failed, exceptOccurred, is_inconsistent,thaw_done, unable_to_sleep, all_snapshots_failed = self.snapshotall_seq(paras, freezer, thaw_done, g_fsfreeze_on) return snapshot_result, blob_snapshot_info_array, all_failed, is_inconsistent, unable_to_sleep, all_snapshots_failed def httpresponse_get_snapshot_info(self, resp, sasuri_index, sasuri, responseBody): snapshot_error = SnapshotError() snapshot_info_indexer = SnapshotInfoIndexerObj(sasuri_index, False, None, None) result = CommonVariables.error_http_failure message = "" if(resp != None): message = message + str(datetime.datetime.utcnow()) + " snapshot resp status: " + str(resp.status) + " " resp_headers = resp.getheaders() message = message + str(datetime.datetime.utcnow()) + " snapshot resp-header: " + str(resp_headers) + " " if(resp.status == 200 or resp.status == 201): result = CommonVariables.success snapshot_info_indexer.isSuccessful = True snapshot_info_indexer.snapshotTs = resp.getheader('x-ms-snapshot') else: result = resp.status snapshot_info_indexer.errorMessage = responseBody snapshot_info_indexer.statusCode = resp.status else: message = message + str(datetime.datetime.utcnow()) + " snapshot Http connection response is None" + " " message = message + str(datetime.datetime.utcnow()) + ' snapshot api returned: {0} '.format(result) + " " if(result != CommonVariables.success): snapshot_error.errorcode = result snapshot_error.sasuri = sasuri return snapshot_info_indexer, snapshot_error, message def get_snapshot_info(self, snapshot_info_indexer, snapshot_info): if (snapshot_info_indexer != None): self.logger.log("snapshot_info_indexer: " + str(snapshot_info_indexer)) snapshot_info.isSuccessful = snapshot_info_indexer.isSuccessful if (snapshot_info.isSuccessful == True): snapshot_info.snapshotUri = snapshot_info.snapshotUri + "?snapshot=" + str(snapshot_info_indexer.snapshotTs) else: snapshot_info.snapshotUri = None snapshot_info.errorMessage = snapshot_info_indexer.errorMessage snapshot_info.statusCode = snapshot_info_indexer.statusCode else: snapshot_info.isSuccessful = False snapshot_info.snapshotUri = None
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=g-short-docstring-punctuation """## Higher level ops related to regularization and building layers. This package provides several ops that take care of creating variables that are used internally in a consistent way and provide the building blocks for many common machine learning algorithms. @@convolution2d @@fully_connected ## Regularizers Regularization can help prevent overfitting. These have the signature `fn(weights)`. The loss is typically added to `tf.GraphKeys.REGULARIZATION_LOSS` @@l1_regularizer @@l2_regularizer ## Initializations This also includes a common initialization for connecting multiple layers. @@xavier_initializer """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numbers from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import nn from tensorflow.python.ops import standard_ops from tensorflow.python.ops import variable_scope from tensorflow.python.platform import logging __all__ = ['xavier_initializer', 'fully_connected', 'l1_regularizer', 'l2_regularizer'] def xavier_initializer(n_inputs, n_outputs, uniform=True): """Set the parameter initialization using the method described in paper. Xavier Glorot and Yoshua Bengio (2010): Understanding the difficulty of training deep feedforward neural networks. International conference on artificial intelligence and statistics. This method is designed to keep the scale of the gradients roughly the same in all layers. In uniform distribution this ends up being the range: `x = sqrt(6. / (in + out)); [-x, x]` and for normal distribution a standard deviation of `sqrt(3. / (in + out))` is used. Args: n_inputs: The number of input nodes into each output. n_outputs: The number of output nodes for each input. uniform: If true use a uniform distribution, otherwise use a truncated normal. Returns: An initializer. """ if uniform: # 6 was used in the paper. init_range = math.sqrt(6.0 / (n_inputs + n_outputs)) return standard_ops.random_uniform_initializer(-init_range, init_range) else: # 3 gives us approximately the same limits as above since this repicks # values greater than 2 standard deviations from the mean. stddev = math.sqrt(3.0 / (n_inputs + n_outputs)) return standard_ops.truncated_normal_initializer(stddev=stddev) def _assert_summary_tag_unique(tag): for summary in ops.get_collection(ops.GraphKeys.SUMMARIES): old_tag = tensor_util.constant_value(summary.op.inputs[0]) if tag == str(old_tag): raise ValueError('Conflict with summary tag: %s exists on summary %s %s' % (tag, summary, old_tag)) def _add_scalar_summary(tensor, tag=None): """Add a summary operation for the tensor. Args: tensor: The tensor to summarize. tag: The tag to use, if None then use tensor's op's name. Returns: The created histogram summary. Raises: ValueError: If the tag is already in use or the rank is not 0. """ tensor.get_shape().assert_has_rank(0) tag = tag or tensor.op.name _assert_summary_tag_unique(tag) return standard_ops.scalar_summary(tag, tensor, name='%s_summary' % tag) def _add_histogram_summary(tensor, tag=None): """Add a summary operation for the histogram of a tensor. Args: tensor: The tensor to summarize. tag: The tag to use, if None then use tensor's op's name. Returns: The created histogram summary. Raises: ValueError: If the tag is already in use. """ tag = tag or tensor.op.name _assert_summary_tag_unique(tag) return standard_ops.histogram_summary(tag, tensor, name='%s_summary' % tag) def _apply_activation_with_summaries(x, activation_fn): """Returns activation_fn(x). This applies the given activation and adds useful summaries specific to the activation. Args: x: The tensor to apply activation to. activation_fn: An activation function. Returns: A tensor with activation applied to x. """ if activation_fn is None: return x y = activation_fn(x) if activation_fn in (nn.relu, nn.softplus, nn.relu6): # Using x for comparison to avoid floating point equality and/or epsilons. _add_scalar_summary( standard_ops.reduce_mean(standard_ops.to_float(standard_ops.less( x, 0.0))), '%s/zeros' % y.op.name) if activation_fn is nn.relu6: _add_scalar_summary( standard_ops.reduce_mean(standard_ops.to_float(standard_ops.greater( x, 6.0))), '%s/sixes' % y.op.name) if activation_fn is nn.l2_normalize: _add_scalar_summary( standard_ops.reduce_mean(standard_ops.sqrt(standard_ops.sum( standard_ops.square(x), 1))), '%s/length' % y.op.name) _add_histogram_summary(y, '%s/activations' % y.op.name) return y def _apply_regularization(w, regularizer): loss = regularizer(w) if loss: ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES, loss) def l1_regularizer(scale): """Returns a function that can be used to apply L1 regularization to weights. L1 regularization encourages sparsity. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. Returns: A function with signature `l1(weights, name=None)` that apply L1 regularization. Raises: ValueError: If scale is outside of the range [0.0, 1.0] or if scale is not a float. """ if isinstance(scale, numbers.Integral): raise ValueError('scale cannot be an integer: %s' % scale) if isinstance(scale, numbers.Real): if scale < 0.: raise ValueError('Setting a scale less than 0 on a regularizer: %g' % scale) if scale >= 1.: raise ValueError('Setting a scale greater than 1 on a regularizer: %g' % scale) if scale == 0.: logging.info('Scale of 0 disables regularizer.') return lambda _, name=None: None def l1(weights, name=None): """Applies L1 regularization to weights.""" with ops.op_scope([weights], name, 'l1_regularizer') as scope: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') return standard_ops.mul( my_scale, standard_ops.reduce_sum(standard_ops.abs(weights)), name=scope) return l1 def l2_regularizer(scale): """Returns a function that can be used to apply L2 regularization to weights. Small values of L2 can help prevent overfitting the training data. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. Returns: A function with signature `l2(weights, name=None)` that applies L2 regularization. Raises: ValueError: If scale is outside of the range [0.0, 1.0] or if scale is not a float. """ if isinstance(scale, numbers.Integral): raise ValueError('scale cannot be an integer: %s' % (scale,)) if isinstance(scale, numbers.Real): if scale < 0.: raise ValueError('Setting a scale less than 0 on a regularizer: %g.' % scale) if scale >= 1.: raise ValueError('Setting a scale greater than 1 on a regularizer: %g.' % scale) if scale == 0.: logging.info('Scale of 0 disables regularizer.') return lambda _, name=None: None def l2(weights, name=None): """Applies l2 regularization to weights.""" with ops.op_scope([weights], name, 'l2_regularizer') as scope: my_scale = ops.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') return standard_ops.mul(my_scale, nn.l2_loss(weights), name=scope) return l2 def fully_connected(x, num_output_nodes, activation_fn=None, weight_init=None, bias_init=standard_ops.constant_initializer(0.), num_input_nodes=None, name=None, weight_collections=None, bias_collections=None, weight_regularizer=None, create_summaries=True): """Adds the parameters for a fully connected layer and returns the output. A fully connected layer is generally defined as a matrix multiply: \\\\(y = f(w * x + b)\\\\) where **f** is given by `activation_fn` This op creates `w` and optionally `b` and adds various summaries that can be useful for visualizing learning or diagnosing training problems. Bias can be disabled by setting `bias_init` to `None`. The variable creation is compatible with `tf.variable_scope` and so can be reused with `tf.variable_scope` or `tf.make_template`. In almost all cases, the number of input nodes can be inferred from the shape of `x`, but if it is unspecified or additional size checks are desired, then `num_input_nodes` can be specified. Most of the details of variable creation can be controlled by specifying the initializers (`weight_init` and `bias_init`) and which collections to place the created variables in (`weight_collections` and `bias_collections`). A per layer regularization can be specified by setting `weight_regularizer`. This is only applied to weights and not the bias. Args: x: The input `Tensor`. num_output_nodes: The size of the output. activation_fn: A function that requires a single Tensor that is applied as a non-linearity. If None is used, do not apply any activation. weight_init: An optional initialization. If not specified, uses Xavier initialization (see `tf.learn.xavier_initializer`). bias_init: An initializer for the bias, defaults to 0. Set to`None` in order to disable bias. num_input_nodes: The number of input nodes. name: The name for this operation is used to name operations and to find variables. If specified it must be unique for this scope, otherwise a unique name starting with "fully_connected" will be created. See `tf.variable_op_scope` for details. weight_collections: List of graph collections for just weights. bias_collections: List of graph collections for just bias. weight_regularizer: A regularizer like the result of `tf.learn.l1_regularizer` or `tf.learn.l2_regularizer`. create_summaries: Set to false to disable summaries. Returns: The result of applying a fully connected layer. Raises: ValueError: if `x` is not rank 2; or `x`'s second dimension is not known and `num_input_nodes` is not specified. """ with variable_scope.variable_op_scope([x], name, 'fully_connected') as vs: # Check rank and if num_input_nodes is specified, make sure it matches. x.get_shape().assert_is_compatible_with([None, num_input_nodes]) if not num_input_nodes: if x.get_shape().dims is None or x.get_shape().dims[1].value is None: raise ValueError( 'If x has an unknown second dimension then num_input_nodes ' 'must be specified; shape: %s num_input_nodes: %s' % (x.get_shape(), num_input_nodes)) else: num_input_nodes = x.get_shape().dims[1].value weight_init = weight_init or xavier_initializer( num_input_nodes, num_output_nodes) dtype = x.dtype.base_dtype w = variable_scope.get_variable('weights', shape=[num_input_nodes, num_output_nodes], dtype=dtype, initializer=weight_init, collections=weight_collections) if not vs.reuse and create_summaries: _add_histogram_summary(w) y = standard_ops.matmul(x, w) # Regularization is only applied to the weights and not bias. if weight_regularizer: _apply_regularization(w, weight_regularizer) if bias_init is not None: b = variable_scope.get_variable('bias', shape=[num_output_nodes], dtype=dtype, initializer=bias_init, collections=bias_collections) if not vs.reuse and create_summaries: _add_histogram_summary(b) y = nn.bias_add(y, b) if create_summaries: return _apply_activation_with_summaries(y, activation_fn) else: return y if activation_fn is None else activation_fn(y) def convolution2d(x, num_output_channels, kernel_size, activation_fn=None, stride=(1, 1), padding='SAME', weight_init=None, bias_init=standard_ops.constant_initializer(0.), num_input_channels=None, name=None, weight_collections=None, bias_collections=None, weight_regularizer=None, create_summaries=True): """Adds the parameters for a conv2d layer and returns the output. A neural network convolution layer is generally defined as: \\\\(y = f(conv2d(w, x) + b)\\\\) where **f** is given by `activation_fn`, **conv2d** is `tf.nn.conv2d` and `x` has shape `[batch, height, width, channels]` This op creates `w` and optionally `b` and adds various summaries that can be useful for visualizing learning or diagnosing training problems. Bias can be disabled by setting `bias_init` to `None`. The variable creation is compatible with `tf.variable_scope` and so can be reused with `tf.variable_scope` or `tf.make_template`. In almost all cases, the input channels can be inferred from the shape of `x`, but if it is unspecified or additional size checks are desired, then `num_input_channels` can be specified. Most of the details of variable creation can be controlled by specifying the initializers (`weight_init` and `bias_init`) and which collections to place the created variables in (`weight_collections` and `bias_collections`). A per layer regularization can be specified by setting `weight_regularizer`. This is only applied to weights and not the bias. Args: x: The input `Tensor`. num_output_channels: The number of output channels (i.e. the size of dim[3]). kernel_size: A length 2 `list` or `tuple` containing the kernel size. activation_fn: A function that requires a single Tensor that is applied as a non-linearity. stride: A length 2 `list` or `tuple` specifying the stride of the sliding window across the image. padding: A `string` from: "SAME", "VALID". The type of padding algorithm to use. weight_init: An optional initialization. If not specified, uses Xavier initialization (see `tf.learn.xavier_initializer`). bias_init: An initializer for the bias, defaults to 0. Set to`None` in order to disable bias. num_input_channels: The length of the channel dimension in the input. name: The name for this operation is used to name operations and to find variables. If specified it must be unique for this scope, otherwise a unique name starting with "convolution2d" will be created. See `tf.variable_op_scope` for details. weight_collections: List of graph collections for just weights. bias_collections: List of graph collections for just bias. weight_regularizer: A regularizer like the result of `tf.learn.l1_regularizer` or `tf.learn.l2_regularizer`. create_summaries: Set to false to disable summaries. Returns: The result of applying a fully connected layer. Raises: ValueError: if `x` is not rank 4; or `x`'s channel dimension is not known and `num_input_channels` is not specified. """ with variable_scope.variable_op_scope([x], name, 'convolution2d') as vs: # Check rank and if num_input_channels is specified, make sure it matches. x.get_shape().assert_is_compatible_with([None, None, None, num_input_channels]) if not num_input_channels: if x.get_shape().dims is None or x.get_shape().dims[3].value is None: raise ValueError( 'If x has an unknown channels dimension then num_input_channels ' 'must be specified; shape: %s num_input_channels: %s' % (x.get_shape(), num_input_channels)) else: num_input_channels = x.get_shape().dims[3].value # QQQ: Should we accept a scalar for a square convolution? if len(kernel_size) != 2: raise ValueError('kernel_size must be length 2: ' % kernel_size) if len(stride) != 2: raise ValueError('stride must be length 2: ' % kernel_size) stride = [1, stride[0], stride[1], 1] shape = [kernel_size[0], kernel_size[1], num_input_channels, num_output_channels] patch_size = kernel_size[0] * kernel_size[1] weight_init = weight_init or xavier_initializer( num_input_channels * patch_size, num_output_channels * patch_size) dtype = x.dtype.base_dtype w = variable_scope.get_variable('weights', shape=shape, dtype=dtype, initializer=weight_init, collections=weight_collections) if not vs.reuse and create_summaries: _add_histogram_summary(w) y = nn.conv2d(x, w, stride, padding) # Regularization is only applied to the weights and not bias. if weight_regularizer: _apply_regularization(w, weight_regularizer) if bias_init is not None: b = variable_scope.get_variable('bias', shape=[num_output_channels], dtype=dtype, initializer=bias_init, collections=bias_collections) if not vs.reuse and create_summaries: _add_histogram_summary(b) y = nn.bias_add(y, b) if create_summaries: return _apply_activation_with_summaries(y, activation_fn) else: return y if activation_fn is None else activation_fn(y)
#!/usr/bin/env python # -*- encoding: utf-8 """Print log event messages from a CloudWatch log group. Usage: aws_get_log_events.py <LOG_GROUP_NAME> [--log-stream=<LOG_STREAM_NAME>] [--start=<START>] [--end=<END>] [--day=<DAY>] [--limit=<LIMIT>] [--filter=<FILTER_PATTERN>] [--regex=<REGEX_PATTERN>] [--log-streams-number=<LOG_STREAMS_NUMBER>] [--is_print=IS_PRINT] aws_get_log_events.py -h --help Options: <LOG_GROUP_NAME> Name of the CloudWatch log group. --log-stream=<LOG_GROUP_NAME> Name of the CloudWatch log stream. --start=<START> Only print events with a timestamp after this time. --end=<END> Only print events with a timestamp before this time. --day=<DAY> Only print events with a timestamp after this time. --limit=<LIMIT> Maximum number of messages to get --regex=<FILTER_PATTERN> Patter to regex messages --filter=<FILTER_PATTERN> Patter to filter messages --log-streams-number=<LOG_STREAMS_NUMBER> Number of recent logs streams to process --is_print=<IS_PRINT> Should logs be printed to the console -h --help Show this screen. """ import boto3 import docopt import maya import re import sys import datetime import concurrent.futures import logging import os client = boto3.client('logs') logging.basicConfig(level=logging.INFO) def ensure_dir(directory): if not os.path.exists(directory): os.makedirs(directory) def get_logs(log_group, stream, start_time=None, end_time=None, limit=10000, filter="", regex="", is_print="no", filename_prefix=""): LOG_DIR="/tmp/awslogs" log_stream_name = "" if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) if isinstance(stream, str): log_stream_name = stream filename = f"{LOG_DIR}/{filename_prefix}" + log_stream_name.split("/")[-1] logging.debug(f"GETTING log stream name: {log_stream_name}; filename: {filename}") elif stream is None: filename = f"{LOG_DIR}/time-based-logs" logging.debug(f"GETTING time-based logs start: {start_time} end: {end_time}; filename: {filename}") else: log_stream_name = stream.get("logStreamName") creation_time = stream.get("creationTime") creation_time = datetime.datetime.fromtimestamp(int(creation_time)/1000) last_event_time = stream.get("lastEventTimestamp") last_event_time = datetime.datetime.fromtimestamp(int(last_event_time)/1000) filename = f"{LOG_DIR}/{filename_prefix}" + log_stream_name.split("/")[-1] logging.debug(f"GETTING log stream name: {log_stream_name}; filename: {filename}; creation_time: {creation_time}; last_event_time: {last_event_time}") kwargs = { 'logGroupName': log_group, 'limit': limit, } if stream: kwargs['logStreamNames'] = [log_stream_name] if start_time: kwargs['startTime'] = milliseconds_since_epoch(start_time) if end_time: kwargs['endTime'] = milliseconds_since_epoch(end_time) if filter != "": kwargs['filterPattern'] = filter #if os.path.exists(filename) and os.path.getsize(filename) > 0: #logging.debug(f"{filename} already exists and is not empty - skipping getting these logs...") #if(is_print.startswith("y")): #return log_stream_name file = open(filename, "w") while True: resp = client.filter_log_events(**kwargs) #yield from resp['events'] for event in resp['events']: log_message = event['message'].rstrip() if re.search(regex, log_message): if(is_print.startswith("y")): print(f"{log_stream_name} => {log_message}") file.write(log_message + "\n") try: kwargs['nextToken'] = resp['nextToken'] except KeyError: file.close() break return filename def get_log_events(log_group, log_stream=None, start_time=None, end_time=None, limit=10000, filter="", start_log_streams_number=1, end_log_streams_number=2, regex="", is_print="no", filename_prefix=""): log_streams = [log_stream] if start_time is None and end_time is None and log_stream is None: response = client.describe_log_streams( logGroupName=log_group, orderBy="LastEventTime", descending=True, limit=end_log_streams_number ) log_streams = response.get("logStreams")[start_log_streams_number-1:] output_files = [] with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: try: stream_futures = {executor.submit(get_logs, log_group, stream, start_time, end_time, limit, filter, regex, is_print, filename_prefix): stream for stream in log_streams} except Exception as ex: logging.error(f"exception: {ex}") for future in concurrent.futures.as_completed(stream_futures): stream = stream_futures[future] output_file = future.result() logging.debug(f"finished getting logs into file: {output_file}") output_files.append(output_file) return output_files def milliseconds_since_epoch(time_string): dt = maya.when(time_string) seconds = dt.epoch return seconds * 1000 if __name__ == '__main__': args = docopt.docopt(__doc__) log_group = args['<LOG_GROUP_NAME>'] log_stream = None start_time = None end_time = None limit = 10000 filter="" regex="" start_log_streams_number = 1 end_log_streams_number = 2 is_print="no" if args['--log-stream']: log_stream = args['--log-stream'] if args['--log-streams-number']: log_streams_number = args['--log-streams-number'] if len(log_streams_number.split("-")) == 2: start_log_streams_number = int(log_streams_number.split("-")[0]) end_log_streams_number = int(log_streams_number.split("-")[1]) else: end_log_streams_number = int(log_streams_number) if args['--limit']: limit = int(args['--limit']) if args['--filter']: filter = args['--filter'] if args['--regex']: regex = args['--regex'] if args['--is_print']: is_print = args['--is_print'] if is_print.startswith("y"): logging.getLogger().setLevel(logging.WARN) if args['--day']: start_time = args['--day'] + " 00:00:00" end_time = args['--day'] + " 23:59:59" if args['--start']: start_time = args['--start'] if args['--end']: end_time = args['--end'] logs = get_log_events( log_group=log_group, log_stream=log_stream, start_time=start_time, end_time=end_time, limit=limit, filter=filter, start_log_streams_number=start_log_streams_number, end_log_streams_number=end_log_streams_number, regex=regex, is_print=is_print, )
""" An implementation of the scheme of Shen and Yang, SIAM J. Numer. Anal., 2015. Binary electrohydrodynamics solved using a partial splitting approach and linearisation. The problem is split between the following subproblems. * PF: Solved with stabilization and a modified phase field potential. * EC: Improvised. (This is not covered by Shen and Yang) * NSu: Velocity. * NSp: Pressure. GL, 2017-05-29 """ import dolfin as df import math from common.functions import ramp, dramp, diff_pf_potential, \ diff_pf_potential_c, diff_pf_potential_e, diff_pf_potential_linearised, \ ramp_harmonic, ramp_geometric from common.cmd import info_red from common.io import mpi_barrier from .basic import unit_interval_filter # GL: Move this to common.functions? from . import * from . import __all__ import numpy as np def get_subproblems(base_elements, solutes, enable_NS, enable_PF, enable_EC, **namespace): """ Returns dict of subproblems the solver splits the problem into. """ subproblems = dict() if enable_NS: subproblems["NSu"] = [dict(name="u", element="u")] subproblems["NSp"] = [dict(name="p", element="p")] if enable_PF: subproblems["PF"] = [dict(name="phi", element="phi"), dict(name="g", element="g")] if enable_EC: subproblems["EC"] = ([dict(name=solute[0], element="c") for solute in solutes] + [dict(name="V", element="V")]) return subproblems def unpack_quantities(surface_tension, grav_const, grav_dir, pf_mobility_coeff, pf_mobility, interface_thickness, density, viscosity, permittivity, trial_functions, test_functions, w_, w_1, solutes, dt, enable_EC, enable_PF, enable_NS): """ """ # Constant sigma_bar = surface_tension*3./(2*math.sqrt(2)) per_tau = df.Constant(1./dt) grav = df.Constant(tuple(grav_const*np.array(grav_dir))) gamma = pf_mobility_coeff eps = interface_thickness rho_min = min(density) if enable_PF else density[0] # Navier-Stokes if enable_NS: u = trial_functions["NSu"] p = trial_functions["NSp"] v = test_functions["NSu"] q = test_functions["NSp"] u_ = w_["NSu"] p_ = w_["NSp"] u_1 = w_1["NSu"] p_1 = w_1["NSp"] else: u = p = v = q = None u_ = p_ = None u_1 = p_1 = None # Phase field if enable_PF: phi, g = trial_functions["PF"] psi, h = test_functions["PF"] phi_, g_ = df.split(w_["PF"]) phi_1, g_1 = df.split(w_1["PF"]) else: # Defaults to phase 1 if phase field is disabled phi = 1. g = psi = h = None phi_ = phi_1 = 1. g_ = g_1 = None # Electrochemistry if enable_EC: num_solutes = len(trial_functions["EC"])-1 assert(num_solutes == len(solutes)) c = trial_functions["EC"][:num_solutes] V = trial_functions["EC"][num_solutes] b = test_functions["EC"][:num_solutes] U = test_functions["EC"][num_solutes] cV_ = df.split(w_["EC"]) cV_1 = df.split(w_1["EC"]) c_, V_ = cV_[:num_solutes], cV_[num_solutes] c_1, V_1 = cV_1[:num_solutes], cV_1[num_solutes] else: c = V = b = U = c_ = V_ = c_1 = V_1 = None phi_flt_ = unit_interval_filter(phi_) phi_flt_1 = unit_interval_filter(phi_1) # phi_flt_ = phi_ # phi_flt_1 = phi_1 #phi_ = phi_flt_ phi_1 = phi_flt_1 M_ = pf_mobility(phi_flt_, gamma) M_1 = pf_mobility(phi_flt_1, gamma) nu_ = ramp(phi_flt_, viscosity) rho_ = ramp(phi_flt_, density) veps_ = ramp(phi_flt_, permittivity) rho_1 = ramp(phi_flt_1, density) nu_1 = ramp(phi_flt_1, viscosity) dveps = dramp(permittivity) drho = dramp(density) dbeta = [] # Diff. in beta z = [] # Charge z[species] K_ = [] # Diffusivity K[species] beta_ = [] # Conc. jump func. beta[species] for solute in solutes: z.append(solute[1]) K_.append(ramp_geometric(phi_flt_, [solute[2], solute[3]])) beta_.append(ramp(phi_flt_, [solute[4], solute[5]])) dbeta.append(dramp([solute[4], solute[5]])) if enable_EC: rho_e = sum([c_e*z_e for c_e, z_e in zip(c, z)]) rho_e_ = sum([c_e_*z_e for c_e_, z_e in zip(c_, z)]) rho_e_1 = sum([c_e_1*z_e for c_e_1, z_e in zip(c_1, z)]) else: rho_e = rho_e_ = rho_e_1 = None return (sigma_bar, per_tau, grav, gamma, eps, rho_min, u, p, v, q, u_, p_, u_1, p_1, phi, g, psi, h, phi_, g_, phi_1, g_1, c, V, b, U, c_, V_, c_1, V_1, phi_flt_, phi_flt_1, M_, M_1, nu_, rho_, veps_, rho_1, nu_1, dveps, drho, dbeta, z, K_, beta_, rho_e, rho_e_, rho_e_1) def setup(tstep, test_functions, trial_functions, w_, w_1, ds, dx, normal, dirichlet_bcs, neumann_bcs, boundary_to_mark, permittivity, density, viscosity, solutes, enable_PF, enable_EC, enable_NS, surface_tension, dt, interface_thickness, grav_const, grav_dir, pf_mobility, pf_mobility_coeff, use_iterative_solvers, solve_initial, **namespace): """ Set up problem. """ (sigma_bar, per_tau, grav, gamma, eps, rho_min, u, p, v, q, u_, p_, u_1, p_1, phi, g, psi, h, phi_, g_, phi_1, g_1, c, V, b, U, c_, V_, c_1, V_1, phi_flt_, phi_flt_1, M_, M_1, mu_, rho_, veps_, rho_1, mu_1, dveps, drho, dbeta, z, K_, beta_, rho_e, rho_e_, rho_e_1) = unpack_quantities( surface_tension, grav_const, grav_dir, pf_mobility_coeff, pf_mobility, interface_thickness, density, viscosity, permittivity, trial_functions, test_functions, w_, w_1, solutes, dt, enable_EC, enable_PF, enable_NS) if tstep == 0 and enable_NS: solve_initial_pressure(w_["NSp"], p, q, u, v, dx, ds, dirichlet_bcs["NSp"], neumann_bcs, boundary_to_mark, M_, g_, phi_, rho_, rho_e_, V_, drho, sigma_bar, eps, grav, dveps, enable_PF, enable_EC, use_iterative_solvers, solve_initial) #x = df.Expression(tuple(["x[0]", "x[1]", "x[2]"][:len(grav_dir)]), # degree=1) solvers = dict() if enable_PF: w_PF = w_["PF"] dirichlet_bcs_PF = dirichlet_bcs["PF"] #phi = phi_ #g = g_ solvers["PF"] = setup_PF(**vars()) if enable_EC: solvers["EC"] = setup_EC(w_["EC"], c, V, b, U, rho_e, dx, ds, dirichlet_bcs["EC"], neumann_bcs, boundary_to_mark, c_1, u_1, K_, veps_, phi_flt_, rho_1, dt, z, dbeta, enable_NS, enable_PF, use_iterative_solvers) if enable_NS: w_NSu = w_["NSu"] w_NSp = w_["NSp"] dirichlet_bcs_NSu = dirichlet_bcs["NSu"] dirichlet_bcs_NSp = dirichlet_bcs["NSp"] solvers["NSu"] = setup_NSu(**vars()) solvers["NSp"] = setup_NSp(**vars()) return dict(solvers=solvers) def setup_PF(w_PF, phi, g, psi, h, dx, ds, dirichlet_bcs_PF, neumann_bcs, boundary_to_mark, phi_1, u_1, M_, M_1, c_1, V_1, rho_1, dt, sigma_bar, eps, drho, dbeta, dveps, grav, enable_NS, enable_EC, use_iterative_solvers, **namespace): """ Set up phase field subproblem. """ # Projected velocity (for energy stability) if enable_NS: u_proj = u_1 # - dt*phi_1*df.grad(g)/rho_1 phi_adv = phi # phi_1 F_phi = (1./dt*(phi - phi_1)*psi*dx + M_1*df.dot(df.grad(g), df.grad(psi))*dx) if enable_NS: F_phi += - phi_adv * df.dot(u_proj, df.grad(psi))*dx F_g = (g*h*dx # - sigma_bar/eps * (phi - phi_1) * h * dx # Damping term (makes the system elliptic) - sigma_bar*eps * df.dot(df.grad(phi), df.grad(h))*dx # - sigma_bar/eps * diff_pf_potential(phi_1)*h*dx - sigma_bar/eps * diff_pf_potential_linearised(phi, phi_1)*h*dx) # Add gravity # F_g += drho * df.dot(grav, x) * h * dx if enable_EC: F_g += (-sum([dbeta_i*ci_1*h*dx for dbeta_i, ci_1 in zip(dbeta, c_1)]) + 0.5*dveps*df.dot(df.grad(V_1), df.grad(V_1))*h*dx) F = F_phi + F_g a, L = df.lhs(F), df.rhs(F) problem = df.LinearVariationalProblem(a, L, w_PF, dirichlet_bcs_PF) solver = df.LinearVariationalSolver(problem) if use_iterative_solvers: solver.parameters["linear_solver"] = "gmres" # "bicgstab" # "gmres" solver.parameters["preconditioner"] = "jacobi" #"amg" # solver.parameters["preconditioner"] = "hypre_euclid" return solver def setup_PFEC(w_PF, phi, g, psi, h, dx, ds, dirichlet_bcs_PF, neumann_bcs, boundary_to_mark, phi_1, u_1, M_, M_1, c_1, V_1, rho_1, dt, sigma_bar, eps, drho, dbeta, dveps, grav, enable_NS, enable_EC, use_iterative_solvers, **namespace): """ Set up phase field subproblem. """ # Projected velocity (for energy stability) if enable_NS: u_proj = u_1 #- dt*phi_1*df.grad(g)/rho_1 F_phi = (1./dt*(phi - phi_1)*psi*dx + M_1*df.dot(df.grad(g), df.grad(psi))*dx) if enable_NS: F_phi += - phi_1 * df.dot(u_proj, df.grad(psi))*dx F_g = (g*h*dx - sigma_bar*eps * df.dot(df.grad(phi), df.grad(h))*dx - sigma_bar/eps * (diff_pf_potential_c(phi) - diff_pf_potential_e(phi_1))*h*dx) # Add gravity # F_g += drho * df.dot(grav, x) * h * dx if enable_EC: F_g += (-sum([dbeta_i*ci_1*h*dx for dbeta_i, ci_1 in zip(dbeta, c_1)]) + 0.5*dveps*df.dot(df.grad(V_1), df.grad(V_1))*h*dx) F = F_phi + F_g # a, L = df.lhs(F), df.rhs(F) J = df.derivative(F, w_PF) problem = df.NonlinearVariationalProblem(F, w_PF, dirichlet_bcs_PF, J) solver = df.NonlinearVariationalSolver(problem) solver.parameters["newton_solver"]["relative_tolerance"] = 1e-5 if use_iterative_solvers: solver.parameters["newton_solver"]["linear_solver"] = "bicgstab" # "gmres" solver.parameters["newton_solver"]["preconditioner"] = "jacobi" #"amg" # solver.parameters["preconditioner"] = "hypre_euclid" return solver def setup_EC(w_EC, c, V, b, U, rho_e, dx, ds, dirichlet_bcs_EC, neumann_bcs, boundary_to_mark, c_1, u_1, K_, veps_, phi_, rho_1, dt, z, dbeta, enable_NS, enable_PF, use_iterative_solvers, **namespace): """ Set up electrochemistry subproblem. """ F_c = [] for ci, ci_1, bi, Ki_, zi, dbetai in zip(c, c_1, b, K_, z, dbeta): u_proj_i = u_1 # - dt/rho_1*df.grad(ci) ci_adv = ci # ci_1 F_ci = (1./dt*(ci-ci_1)*bi*dx + Ki_*df.dot(df.nabla_grad(ci), df.nabla_grad(bi))*dx) if zi != 0: F_ci += Ki_*zi*ci_1*df.dot(df.nabla_grad(V), df.nabla_grad(bi))*dx # u_proj_i += -dt/rho_1 * zi * ci_1 * df.grad(V) if enable_PF: F_ci += Ki_*ci*dbetai*df.dot(df.nabla_grad(phi_), df.nabla_grad(bi))*dx # u_proj_i += -dt/rho_1 * ci_1 * dbetai*df.grad(phi_) if enable_NS: F_ci += - ci_adv * df.dot(u_proj_i, df.nabla_grad(bi))*dx F_c.append(F_ci) F_V = veps_*df.dot(df.nabla_grad(V), df.nabla_grad(U))*dx for boundary_name, sigma_e in neumann_bcs["V"].items(): F_V += -sigma_e*U*ds(boundary_to_mark[boundary_name]) if rho_e != 0: F_V += -rho_e*U*dx F = sum(F_c) + F_V a, L = df.lhs(F), df.rhs(F) problem = df.LinearVariationalProblem(a, L, w_EC, dirichlet_bcs_EC) solver = df.LinearVariationalSolver(problem) if use_iterative_solvers: solver.parameters["linear_solver"] = "gmres" solver.parameters["preconditioner"] = "amg" return solver def setup_NSu(w_NSu, u, v, dx, ds, normal, dirichlet_bcs_NSu, neumann_bcs, boundary_to_mark, u_, u_1, p_, p_1, phi_, phi_1, rho_, rho_1, g_, g_1, c_, c_1, M_, M_1, mu_, mu_1, rho_e_, rho_e_1, V_, dt, drho, sigma_bar, eps, dveps, grav, dbeta, z, enable_PF, enable_EC, use_iterative_solvers, **namespace): """ Set up the Navier-Stokes velocity subproblem. """ mom_1 = rho_1*u_1 if enable_PF: mom_1 += -drho * M_1 * df.grad(g_1) F_predict = (1./dt * rho_1 * df.dot(u - u_1, v) * dx + df.inner(df.nabla_grad(u), df.outer(mom_1, v)) * dx + 2*mu_*df.inner(df.sym(df.nabla_grad(u)), df.sym(df.nabla_grad(v))) * dx - p_1 * df.div(v) * dx - rho_*df.dot(grav, v) * dx + 0.5 * ( 1./dt * (rho_ - rho_1) - df.inner(mom_1, df.grad(df.dot(u, v)))) * dx) if enable_PF: F_predict += phi_1 * df.dot(df.grad(g_), v) * dx for boundary_name, pressure in neumann_bcs["p"].items(): F_predict += pressure * df.inner( normal, v) * ds(boundary_to_mark[boundary_name]) if enable_EC: for ci_, ci_1_ in zip(c_, c_1): # F_predict += df.dot(df.nabla_grad(ci_), v) * dx pass #if enable_EC and rho_e_ != 0: # F += rho_e_1 * df.dot(df.nabla_grad(V_), v) * dx #if enable_PF and enable_EC: # # Not clear how to discretize this term! # # F += dveps * df.dot(df.grad(phi_), v)*df.dot(df.grad(V_), # # df.grad(V_))*dx # F_c = [] # for ci_, ci_1, zi, dbetai in zip(c_, c_1, z, dbeta): # F_ci = ci_1*dbetai*df.dot(df.grad(phi_), v)*dx # F_c.append(F_ci) # F += sum(F_c) solvers = dict() a_predict, L_predict = df.lhs(F_predict), df.rhs(F_predict) problem_predict = df.LinearVariationalProblem( a_predict, L_predict, w_NSu, dirichlet_bcs_NSu) solvers["predict"] = df.LinearVariationalSolver(problem_predict) if use_iterative_solvers: solvers["predict"].parameters["linear_solver"] = "bicgstab" solvers["predict"].parameters["preconditioner"] = "jacobi" # "amg" F_correct = ( rho_ * df.inner(u - u_, v) * dx - dt * (p_ - p_1) * df.div(v) * dx ) a_correct, L_correct = df.lhs(F_correct), df.rhs(F_correct) problem_correct = df.LinearVariationalProblem( a_correct, L_correct, w_NSu, dirichlet_bcs_NSu) solvers["correct"] = df.LinearVariationalSolver(problem_correct) if use_iterative_solvers: solvers["correct"].parameters["linear_solver"] = "cg" # "bicgstab" solvers["correct"].parameters["preconditioner"] = "jacobi" # "amg" return solvers def setup_NSp(w_NSp, p, q, dx, ds, dirichlet_bcs_NSp, neumann_bcs, boundary_to_mark, u_, u_1, p_, p_1, rho_, dt, rho_min, use_iterative_solvers, **namespace): F = ( df.dot(df.nabla_grad(p - p_1), df.nabla_grad(q)) * df.dx + 1./dt * rho_min * df.div(u_) * q * df.dx ) a, L = df.lhs(F), df.rhs(F) problem = df.LinearVariationalProblem(a, L, w_NSp, dirichlet_bcs_NSp) solver = df.LinearVariationalSolver(problem) if use_iterative_solvers: solver.parameters["linear_solver"] = "gmres" solver.parameters["preconditioner"] = "hypre_amg" # "amg" # solver.parameters["preconditioner"] = "hypre_euclid" return solver def solve(tstep, w_, w_1, w_tmp, solvers, enable_PF, enable_EC, enable_NS, **namespace): """ Solve equations. """ timer_outer = df.Timer("Solve system") if enable_PF: timer_inner = df.Timer("Solve supproblem PF") mpi_barrier() solvers["PF"].solve() timer_inner.stop() if enable_EC: timer_inner = df.Timer("Solve subproblem EC") mpi_barrier() solvers["EC"].solve() timer_inner.stop() if enable_NS: # Step 1: Predict u timer = df.Timer("NS: Predict velocity.") solvers["NSu"]["predict"].solve() timer.stop() # Step 2: Pressure correction timer = df.Timer("NS: Pressure correction") solvers["NSp"].solve() timer.stop() # Step 3: Velocity correction timer = df.Timer("NS: Velocity correction") solvers["NSu"]["correct"].solve() timer.stop() timer_outer.stop() def update(t, dt, w_, w_1, enable_PF, enable_EC, enable_NS, q_rhs, bcs, **namespace): """ Update work variables at end of timestep. """ # Update the time-dependent source terms for qi in q_rhs.values(): qi.t = t+dt # Update the time-dependent boundary conditions for boundary_name, bcs_fields in bcs.items(): for field, bc in bcs_fields.items(): if isinstance(bc.value, df.Expression): bc.value.t = t+dt for subproblem, enable in zip( ["PF", "EC", "NSu", "NSp"], [enable_PF, enable_EC, enable_NS, enable_NS]): if enable: w_1[subproblem].assign(w_[subproblem]) def epsilon(u): return df.sym(df.nabla_grad(u)) def stress(u, p, mu): return 2*mu*epsilon(u) - p*df.Identity(len(u)) def solve_initial_pressure(w_NSp, p, q, u, v, dx, ds, dirichlet_bcs_NSp, neumann_bcs, boundary_to_mark, M_, g_, phi_, rho_, rho_e_, V_, drho, sigma_bar, eps, grav, dveps, enable_PF, enable_EC, use_iterative_solvers, solve_initial=True): if solve_initial: V = u.function_space() grad_p = df.TrialFunction(V) grad_p_out = df.Function(V) F_grad_p = ( df.dot(grad_p, v) * dx - rho_*df.dot(grav, v) * dx ) if enable_PF: F_grad_p += - drho*M_*df.inner(df.grad(u), df.outer(df.grad(g_), v))*dx F_grad_p += - sigma_bar*eps*df.inner(df.outer(df.grad(phi_), df.grad(phi_)), df.grad(v))*dx if enable_EC and rho_e_ != 0: F_grad_p += rho_e_ * df.dot(df.grad(V_), v)*dx if enable_PF and enable_EC: F_grad_p += 0.5 * dveps * df.dot(df.grad( phi_), v)*df.dot(df.grad(V_), df.grad(V_))*dx info_red("Solving initial grad_p...") problem_grad_p = df.LinearVariationalProblem( df.lhs(F_grad_p), df.rhs(F_grad_p), grad_p_out) # df.solve(df.lhs(F_grad_p) == df.rhs(F_grad_p), grad_p_out) solver_grad_p = df.LinearVariationalSolver(problem_grad_p) if use_iterative_solvers: solver_grad_p.parameters["linear_solver"] = "gmres" solver_grad_p.parameters["preconditioner"] = "amg" solver_grad_p.solve() F_p = ( df.dot(df.grad(q), df.grad(p))*dx - df.dot(df.grad(q), grad_p_out)*dx ) info_red("Solving initial p...") problem_p = df.LinearVariationalProblem( df.lhs(F_p), df.rhs(F_p), w_NSp, dirichlet_bcs_NSp) # df.solve(df.lhs(F_p) == df.rhs(F_p), w_NSp, dirichlet_bcs_NSp) solver_p = df.LinearVariationalSolver(problem_p) if use_iterative_solvers: solver_p.parameters["linear_solver"] = "gmres" solver_p.parameters["preconditioner"] = "amg" solver_p.solve() info_red("Done with the initials.")
""" Floodfill operation implementation """ import math, functools import numpy from .base import Operation from ..image import Image from ..analyze import detect_bg class TargetNotFoundError(Exception): """ An internal use exception that indicates the lack of a valid pixel from a selection operation e.g. see `FloofillOperation._spiral()` """ pass class FloodfillOperation(Operation): """ A floodfill operation implementing a more or less generic floodfill operation """ def __init__(self, image, keycolor=None, channel='a', replacevalue=0.0, tol=.04, seedpixel=None): """ Initializes a floodfill operation with all the needed parameters :Parameters: image : `Image` The image object we would like to operate on keycolor : `tuple` The color to key out in the floodfill. If `None` specified, this is detected automatically. Default=None [TODO: should also support lists and `numpy.ndarray` but currently untested] channel : `basestring` The channel we wish to be replaced with `replacevalue` for all pixels contiguous with the seeded pixel. Valid values are 'r','g','b', and 'a'. Default='a' replacevalue : `float` The value to replace the given channel with for the pixels that match the keycolor and are contiguous with the seeded pixel. Default=0.0 tol : `float` The threshold tolerance to allow in the difference of squares between pixels contiguous with the seed pixel and the key color. The the difference of squared norms exceeds tol, the pixel is not treated as equal for the purpose of floodfilling. Default=.04 seedpixel : `tuple` Any iterable of (row, col) indices for where to begin the floodfill. Note that this is assumed to be the same as keycolor. If not, the floodfill may end up being a no-op. If seedpixel is None, the seed is determined procedurally by spiraling inward clockwise from the upper righthand pixel of the image. Default=None """ self.image = image self.channel = 'rgba'.index(channel.lower()) self.keycolor = keycolor self.replacevalue = replacevalue self.tol = tol self.seedpixel = None self.opimage = None def run(self): """ Runs the floodfill on this operation's image :Returns: A copy of the input image after floodfill has been applied :Rtype: `Image` """ image = self.image.clone() # get dims rows, cols = image.shape[:2] if len(image.shape) > 2: chans = image.shape[2] else: image = image.reshape(rows,cols,1) chans = 1 if 0 < self.channel < 3 and chans < 3: # need to convert to RGB image.to_rgb() elif self.channel == 3 and chans < 4: # need to convert to RGBA image.to_rgba() # convenient to put here though because this happens # after we've reshaped the image as necessary # so the keycolor num channels should match if self.keycolor is None: self.keycolor = detect_bg(image) # find a pixel with the keycolor on the edge to start if self.seedpixel is None: try: first_index = self._spiral(image, functools.partial(self._floatIterEquals, self.keycolor)) except TargetNotFoundError: # there are no pixels of the given color in the whole image, so we're done return else: first_index = self.seedpixel # so we don't run up against python's recursion limits, lets do the floodfill with a set (order doesn't matter anyways) pixels = set([first_index]) # TODO: inline floodfill as the all python implementation is rather slow # e.g. # see http://docs.scipy.org/doc/scipy/reference/tutorial/weave.html#catalog-search-paths-and-the-pythoncompiled-variable while pixels: row, col = pixels.pop() if not self._floatIterEquals(image[row, col, ...], self.keycolor) or \ self._floatEquals(image[row, col, self.channel], self.replacevalue, tol=1e-9): # base case: on an already changed pixel or a border pixel continue # if we get here, this pixel needs to be changed (it is the keycolor) and hasn't been # changed already image.data[row, col, self.channel] = self.replacevalue # "recurse" to all surrounding pixels if row < rows - 1: pixels.add((row+1, col)) if row > 0: pixels.add((row-1, col)) if col < cols - 1: pixels.add((row, col+1)) if col > 0: pixels.add((row, col-1)) self.opimage = image return image def _floatIterEquals(self, first, second, tol=None): """ Private method to determine whether two iterables of floats are equal within some tolerance. :Parameters: first : `numpy.ndarray` Any iterable to compare against second second : `numpy.ndarray` Any iterable to compare against first tol : `float` The threshold at which each float is considered equal Defaults to the tolerance passed into the operation. :Returns: True if the two iterables are considered equal with the given tolerance, False otherwise. :Rtype: `bool` """ if tol is None: tol = self.tol return all([self._floatEquals(first[i], second[i], tol=tol) for i in range(len(first))]) def _floatEquals(self, first, second, tol=None): """ Private method to determine whether 2 floats are equal within some tolerance :Parameters: first : `float` The first float to compare second : `float` The second float ot compare tol : `float` The threshold at which first and second are considered equal. Defaults to the tolerance passed into the operation :Returns: True if the floats are considered equal within the given tolerance, False otherwise :Rtype: `bool` """ if tol is None: tol = self.tol return abs(first - second) <= tol def _spiral(self, matrix, func): """ Private helper method to iterate through all cells of an image starting at the upper-left pixel and apply the given function to each cell, passing in the value at that cell. Returns the first index of the matrix whose value evaluates to True :Parameters: matrix : `numpy.ndarray` A matrix of at least 2 dimensions function : `function` or `instancemethod` A function to run on each cell. It should take one parameter, the value at the cell. Should return True for a pixel whose indices we wish to capture :Returns: The indices of the first cell in the matrix for which the function evaluated to True. The indices are returned as a tuple of (row, col) :Rtype: `tuple` """ rows, cols = matrix.shape[:2] row_jumps, col_jumps = rows-1, cols row = 0 col = -1 row_diff = 0 col_diff = 1 row_counter = 0 col_counter = 0 for _ in range(rows * cols): # update row, col row += row_diff col += col_diff # test if func(matrix[row, col, ...]): # short-circuit return (row, col) # update counters and traversal direction row_counter += abs(row_diff) col_counter += abs(col_diff) if row_diff and row_counter >= row_jumps: row_jumps -= 1 row_counter = 0 col_diff = -1 if row_diff > 0 else 1 row_diff = 0 elif col_diff and col_counter >= col_jumps: col_jumps -= 1 col_counter = 0 row_diff = 1 if col_diff > 0 else -1 col_diff = 0 raise TargetNotFoundError("No pixels match target function")
#!/usr/bin/env python """oc_csr_approve module""" # Copyright 2020 Red Hat, Inc. and/or its affiliates # and other contributors as indicated by the @author tags. # # 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 base64 import json import time from ansible.module_utils.basic import AnsibleModule try: # Python >= 3.5 from json.decoder import JSONDecodeError except ImportError: # Python < 3.5 JSONDecodeError = ValueError DOCUMENTATION = ''' --- module: oc_csr_approve short_description: Retrieve and approve node client and server CSRs version_added: "2.9" description: - Retrieve and approve node client and server CSRs author: - "Michael Gugino <mgugino@redhat.com>" - "Russell Teague <rteague@redhat.com>" ''' EXAMPLES = ''' - name: Approve node CSRs oc_csr_approve: kubeconfig: "{{ openshift_node_kubeconfig_path }}" nodename: "{{ ansible_nodename | lower }}" delegate_to: localhost ''' CERT_MODE = {'client': 'client auth', 'server': 'server auth'} def parse_subject_cn(subject_str): """parse output of openssl req -noout -subject to retrieve CN. example input: 'subject=/C=US/CN=test.io/L=Raleigh/O=Red Hat/ST=North Carolina/OU=OpenShift\n' or 'subject=C = US, CN = test.io, L = City, O = Company, ST = State, OU = Dept\n' example output: 'test.io' """ stripped_string = subject_str[len('subject='):].strip() kv_strings = [x.strip() for x in stripped_string.split(',')] if len(kv_strings) == 1: kv_strings = [x.strip() for x in stripped_string.split('/')][1:] for item in kv_strings: item_parts = [x.strip() for x in item.split('=')] if item_parts[0] == 'CN': return item_parts[1] return None def csr_present_check(nodename, csr_dict): """Ensure node has a CSR Returns True if CSR for node is present""" for _, val in csr_dict.items(): if val == nodename: # CSR for node is present return True # Didn't find a CSR for node return False class CSRapprove(object): # pylint: disable=useless-object-inheritance """Approves node CSRs""" def __init__(self, module, oc_bin, kubeconfig, nodename): """init method""" self.module = module self.oc_bin = oc_bin self.kubeconfig = kubeconfig self.nodename = nodename # Build a dictionary to hold all of our output information so nothing # is lost when we fail. self.result = {'changed': False, 'rc': 0, 'client_approve_results': [], 'server_approve_results': [], } def run_command(self, command, rc_opts=None): """Run a command using AnsibleModule.run_command, or fail""" if rc_opts is None: rc_opts = {} rtnc, stdout, err = self.module.run_command(command, **rc_opts) if rtnc: self.result['failed'] = True self.result['rc'] = rtnc self.result['msg'] = str(err) self.result['state'] = 'unknown' self.module.fail_json(**self.result) return stdout def get_nodes(self): """Get all nodes via oc get nodes -ojson""" # json output is necessary for consistency here. command = "{} {} get nodes -ojson".format(self.oc_bin, self.kubeconfig) stdout = self.run_command(command) try: data = json.loads(stdout) except JSONDecodeError as err: self.result['failed'] = True self.result['rc'] = 1 self.result['msg'] = str(err) self.result['state'] = 'unknown' self.module.fail_json(**self.result) return [node['metadata']['name'] for node in data['items']] def get_csrs(self): """Retrieve CSRs from cluster using oc get csr -ojson""" command = "{} {} get csr -ojson".format(self.oc_bin, self.kubeconfig) stdout = self.run_command(command) try: data = json.loads(stdout) except JSONDecodeError as err: self.result['failed'] = True self.result['rc'] = 1 self.result['msg'] = str(err) self.result['state'] = 'unknown' self.module.fail_json(**self.result) return data['items'] def process_csrs(self, csrs, mode): """Return a dictionary of pending CSRs where the format of the dict is k=csr name, v=Subject Common Name""" csr_dict = {} for item in csrs: status = item['status'].get('conditions') if status: # If status is not an empty dictionary, cert is not pending. continue if CERT_MODE[mode] not in item['spec']['usages']: continue name = item['metadata']['name'] request_data = base64.b64decode(item['spec']['request']) command = "openssl req -noout -subject" # ansible's module.run_command accepts data to pipe via stdin as # as 'data' kwarg. rc_opts = {'data': request_data, 'binary_data': True} stdout = self.run_command(command, rc_opts=rc_opts) # parse common_name from subject string. common_name = parse_subject_cn(stdout) if common_name and common_name.startswith('system:node:'): # common name is typically prepended with system:node:. common_name = common_name.split('system:node:')[1] # we only want to approve CSRs from nodes we know about. if common_name == self.nodename: csr_dict[name] = common_name return csr_dict def approve_csrs(self, csr_pending_list, mode): """Loop through csr_pending_list and call: oc adm certificate approve <item>""" results_mode = "{}_approve_results".format(mode) base_command = "{} {} adm certificate approve {}" approve_results = [] for csr in csr_pending_list: command = base_command.format(self.oc_bin, self.kubeconfig, csr) rtnc, stdout, err = self.module.run_command(command) if rtnc: self.result['failed'] = True self.result['rc'] = rtnc self.result['msg'] = str(err) self.result[results_mode].extend(approve_results) self.result['state'] = 'unknown' self.module.fail_json(**self.result) approve_results.append("{}: {}".format(csr_pending_list[csr], stdout)) self.result[results_mode].extend(approve_results) # We set changed for approved client or server CSRs. self.result['changed'] = bool(approve_results) or bool(self.result['changed']) def node_is_ready(self, nodename): """Determine if node has working server certificate Returns True if the node is ready""" base_command = "{} {} get --raw /api/v1/nodes/{}/proxy/healthz" # need this to look like /api/v1/nodes/<node>/proxy/healthz # if we can hit that api endpoint (rtnc=0), the node has a valid server cert. command = base_command.format(self.oc_bin, self.kubeconfig, nodename) rtnc, _, _ = self.module.run_command(command) return not bool(rtnc) def runner(self, attempts, mode): """Approve CSRs if they are present for node""" results_mode = "{}_approve_results".format(mode) # Get all CSRs, no good way to filter on pending. csrs = self.get_csrs() # process data in CSRs and build a dictionary of requests csr_dict = self.process_csrs(csrs, mode) if csr_present_check(self.nodename, csr_dict): # Approve outstanding CSRs for node self.approve_csrs(csr_dict, mode) else: # CSR is not present, increment attempts and retry if attempts < 36: # 36 * 5 = 3 minutes waiting for CSRs self.result[results_mode].append( "Attempt: {}, Node {} not present or CSR not yet available".format(attempts, self.nodename)) attempts += 1 time.sleep(5) else: # If attempts < 36, fail waiting for CSRs to appear # Using 'describe' to have the API provide the decoded results for all CSRs command = "{} {} describe csr".format(self.oc_bin, self.kubeconfig) stdout = self.run_command(command) self.result['failed'] = True self.result['rc'] = 1 self.result['msg'] = "Node {} not present or could not find {} CSR".format(self.nodename, mode) self.result['oc_describe_csr'] = stdout self.module.fail_json(**self.result) return attempts def run(self): """execute the CSR approval process""" # # Client Cert Section # # mode = "client" attempts = 1 while True: # If the node is in the list of all nodes, we do not need to approve client CSRs if self.nodename not in self.get_nodes(): attempts = self.runner(attempts, mode) else: self.result["{}_approve_results".format(mode)].append( "Node {} is present in node list".format(self.nodename)) break # # Server Cert Section # # mode = "server" attempts = 1 while True: # If the node API is healthy, we do not need to approve server CSRs if not self.node_is_ready(self.nodename): attempts = self.runner(attempts, mode) else: self.result["{}_approve_results".format(mode)].append( "Node {} API is ready".format(self.nodename)) break self.module.exit_json(**self.result) def run_module(): """Run this module""" module_args = dict( oc_bin=dict(type='path', required=False, default='oc'), kubeconfig=dict(type='path', required=True), nodename=dict(type='str', required=True), ) module = AnsibleModule( supports_check_mode=False, argument_spec=module_args ) oc_bin = module.params['oc_bin'] kubeconfig = '--kubeconfig={}'.format(module.params['kubeconfig']) nodename = module.params['nodename'] approver = CSRapprove(module, oc_bin, kubeconfig, nodename) approver.run() def main(): """main""" run_module() if __name__ == '__main__': main()
""" Randomized Lasso/Logistic: feature selection based on Lasso and sparse Logistic Regression """ # Author: Gael Varoquaux, Alexandre Gramfort # # License: BSD 3 clause import itertools from abc import ABCMeta, abstractmethod import warnings import numpy as np from scipy.sparse import issparse from scipy import sparse from scipy.interpolate import interp1d from .base import _preprocess_data from ..base import BaseEstimator from ..externals import six from ..externals.joblib import Memory, Parallel, delayed from ..feature_selection.base import SelectorMixin from ..utils import (as_float_array, check_random_state, check_X_y, safe_mask) from ..utils.validation import check_is_fitted from .least_angle import lars_path, LassoLarsIC from .logistic import LogisticRegression from ..exceptions import ConvergenceWarning ############################################################################### # Randomized linear model: feature selection def _resample_model(estimator_func, X, y, scaling=.5, n_resampling=200, n_jobs=1, verbose=False, pre_dispatch='3*n_jobs', random_state=None, sample_fraction=.75, **params): random_state = check_random_state(random_state) # We are generating 1 - weights, and not weights n_samples, n_features = X.shape if not (0 < scaling < 1): raise ValueError( "'scaling' should be between 0 and 1. Got %r instead." % scaling) scaling = 1. - scaling scores_ = 0.0 for active_set in Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)( delayed(estimator_func)( X, y, weights=scaling * random_state.randint( 0, 2, size=(n_features,)), mask=(random_state.rand(n_samples) < sample_fraction), verbose=max(0, verbose - 1), **params) for _ in range(n_resampling)): scores_ += active_set scores_ /= n_resampling return scores_ class BaseRandomizedLinearModel(six.with_metaclass(ABCMeta, BaseEstimator, SelectorMixin)): """Base class to implement randomized linear models for feature selection This implements the strategy by Meinshausen and Buhlman: stability selection with randomized sampling, and random re-weighting of the penalty. """ @abstractmethod def __init__(self): pass _preprocess_data = staticmethod(_preprocess_data) def fit(self, X, y): """Fit the model using X, y as training data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training data. y : array-like, shape = [n_samples] Target values. Returns ------- self : object Returns an instance of self. """ X, y = check_X_y(X, y, ['csr', 'csc'], y_numeric=True, ensure_min_samples=2, estimator=self) X = as_float_array(X, copy=False) n_samples, n_features = X.shape X, y, X_offset, y_offset, X_scale = \ self._preprocess_data(X, y, self.fit_intercept, self.normalize) estimator_func, params = self._make_estimator_and_params(X, y) memory = self.memory if isinstance(memory, six.string_types): memory = Memory(cachedir=memory) scores_ = memory.cache( _resample_model, ignore=['verbose', 'n_jobs', 'pre_dispatch'] )( estimator_func, X, y, scaling=self.scaling, n_resampling=self.n_resampling, n_jobs=self.n_jobs, verbose=self.verbose, pre_dispatch=self.pre_dispatch, random_state=self.random_state, sample_fraction=self.sample_fraction, **params) if scores_.ndim == 1: scores_ = scores_[:, np.newaxis] self.all_scores_ = scores_ self.scores_ = np.max(self.all_scores_, axis=1) return self def _make_estimator_and_params(self, X, y): """Return the parameters passed to the estimator""" raise NotImplementedError def _get_support_mask(self): """Get the boolean mask indicating which features are selected. Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention. """ check_is_fitted(self, 'scores_') return self.scores_ > self.selection_threshold ############################################################################### # Randomized lasso: regression settings def _randomized_lasso(X, y, weights, mask, alpha=1., verbose=False, precompute=False, eps=np.finfo(np.float).eps, max_iter=500): X = X[safe_mask(X, mask)] y = y[mask] # Center X and y to avoid fit the intercept X -= X.mean(axis=0) y -= y.mean() alpha = np.atleast_1d(np.asarray(alpha, dtype=np.float64)) X = (1 - weights) * X with warnings.catch_warnings(): warnings.simplefilter('ignore', ConvergenceWarning) alphas_, _, coef_ = lars_path(X, y, Gram=precompute, copy_X=False, copy_Gram=False, alpha_min=np.min(alpha), method='lasso', verbose=verbose, max_iter=max_iter, eps=eps) if len(alpha) > 1: if len(alphas_) > 1: # np.min(alpha) < alpha_min interpolator = interp1d(alphas_[::-1], coef_[:, ::-1], bounds_error=False, fill_value=0.) scores = (interpolator(alpha) != 0.0) else: scores = np.zeros((X.shape[1], len(alpha)), dtype=np.bool) else: scores = coef_[:, -1] != 0.0 return scores class RandomizedLasso(BaseRandomizedLinearModel): """Randomized Lasso. Randomized Lasso works by subsampling the training data and computing a Lasso estimate where the penalty of a random subset of coefficients has been scaled. By performing this double randomization several times, the method assigns high scores to features that are repeatedly selected across randomizations. This is known as stability selection. In short, features selected more often are considered good features. Read more in the :ref:`User Guide <randomized_l1>`. Parameters ---------- alpha : float, 'aic', or 'bic', optional The regularization parameter alpha parameter in the Lasso. Warning: this is not the alpha parameter in the stability selection article which is scaling. scaling : float, optional The s parameter used to randomly scale the penalty of different features (See :ref:`User Guide <randomized_l1>` for details ). Should be between 0 and 1. sample_fraction : float, optional The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. n_resampling : int, optional Number of randomized models. selection_threshold : float, optional The score above which features should be selected. fit_intercept : boolean, optional whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). verbose : boolean or integer, optional Sets the verbosity amount normalize : boolean, optional, default False If True, the regressors X will be normalized before regression. This parameter is ignored when `fit_intercept` is set to False. When the regressors are normalized, note that this makes the hyperparameters learned more robust and almost independent of the number of samples. The same property is not valid for standardized data. However, if you wish to standardize, please use `preprocessing.StandardScaler` before calling `fit` on an estimator with `normalize=False`. precompute : True | False | 'auto' Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument. max_iter : integer, optional Maximum number of iterations to perform in the Lars algorithm. eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the 'tol' parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. n_jobs : integer, optional Number of CPUs to use during the resampling. If '-1', use all the CPUs random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' memory : Instance of joblib.Memory or string Used for internal caching. By default, no caching is done. If a string is given, it is the path to the caching directory. Attributes ---------- scores_ : array, shape = [n_features] Feature scores between 0 and 1. all_scores_ : array, shape = [n_features, n_reg_parameter] Feature scores between 0 and 1 for all values of the regularization \ parameter. The reference article suggests ``scores_`` is the max of \ ``all_scores_``. Examples -------- >>> from sklearn.linear_model import RandomizedLasso >>> randomized_lasso = RandomizedLasso() Notes ----- See examples/linear_model/plot_sparse_recovery.py for an example. References ---------- Stability selection Nicolai Meinshausen, Peter Buhlmann Journal of the Royal Statistical Society: Series B Volume 72, Issue 4, pages 417-473, September 2010 DOI: 10.1111/j.1467-9868.2010.00740.x See also -------- RandomizedLogisticRegression, Lasso, ElasticNet """ def __init__(self, alpha='aic', scaling=.5, sample_fraction=.75, n_resampling=200, selection_threshold=.25, fit_intercept=True, verbose=False, normalize=True, precompute='auto', max_iter=500, eps=np.finfo(np.float).eps, random_state=None, n_jobs=1, pre_dispatch='3*n_jobs', memory=Memory(cachedir=None, verbose=0)): self.alpha = alpha self.scaling = scaling self.sample_fraction = sample_fraction self.n_resampling = n_resampling self.fit_intercept = fit_intercept self.max_iter = max_iter self.verbose = verbose self.normalize = normalize self.precompute = precompute self.eps = eps self.random_state = random_state self.n_jobs = n_jobs self.selection_threshold = selection_threshold self.pre_dispatch = pre_dispatch self.memory = memory def _make_estimator_and_params(self, X, y): assert self.precompute in (True, False, None, 'auto') alpha = self.alpha if isinstance(alpha, six.string_types) and alpha in ('aic', 'bic'): model = LassoLarsIC(precompute=self.precompute, criterion=self.alpha, max_iter=self.max_iter, eps=self.eps) model.fit(X, y) self.alpha_ = alpha = model.alpha_ return _randomized_lasso, dict(alpha=alpha, max_iter=self.max_iter, eps=self.eps, precompute=self.precompute) ############################################################################### # Randomized logistic: classification settings def _randomized_logistic(X, y, weights, mask, C=1., verbose=False, fit_intercept=True, tol=1e-3): X = X[safe_mask(X, mask)] y = y[mask] if issparse(X): size = len(weights) weight_dia = sparse.dia_matrix((1 - weights, 0), (size, size)) X = X * weight_dia else: X *= (1 - weights) C = np.atleast_1d(np.asarray(C, dtype=np.float64)) scores = np.zeros((X.shape[1], len(C)), dtype=np.bool) for this_C, this_scores in zip(C, scores.T): # XXX : would be great to do it with a warm_start ... clf = LogisticRegression(C=this_C, tol=tol, penalty='l1', dual=False, fit_intercept=fit_intercept) clf.fit(X, y) this_scores[:] = np.any( np.abs(clf.coef_) > 10 * np.finfo(np.float).eps, axis=0) return scores class RandomizedLogisticRegression(BaseRandomizedLinearModel): """Randomized Logistic Regression Randomized Logistic Regression works by subsampling the training data and fitting a L1-penalized LogisticRegression model where the penalty of a random subset of coefficients has been scaled. By performing this double randomization several times, the method assigns high scores to features that are repeatedly selected across randomizations. This is known as stability selection. In short, features selected more often are considered good features. Read more in the :ref:`User Guide <randomized_l1>`. Parameters ---------- C : float, optional, default=1 The regularization parameter C in the LogisticRegression. scaling : float, optional, default=0.5 The s parameter used to randomly scale the penalty of different features (See :ref:`User Guide <randomized_l1>` for details ). Should be between 0 and 1. sample_fraction : float, optional, default=0.75 The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. n_resampling : int, optional, default=200 Number of randomized models. selection_threshold : float, optional, default=0.25 The score above which features should be selected. fit_intercept : boolean, optional, default=True whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). verbose : boolean or integer, optional Sets the verbosity amount normalize : boolean, optional, default False If True, the regressors X will be normalized before regression. This parameter is ignored when `fit_intercept` is set to False. When the regressors are normalized, note that this makes the hyperparameters learnt more robust and almost independent of the number of samples. The same property is not valid for standardized data. However, if you wish to standardize, please use `preprocessing.StandardScaler` before calling `fit` on an estimator with `normalize=False`. tol : float, optional, default=1e-3 tolerance for stopping criteria of LogisticRegression n_jobs : integer, optional Number of CPUs to use during the resampling. If '-1', use all the CPUs random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' memory : Instance of joblib.Memory or string Used for internal caching. By default, no caching is done. If a string is given, it is the path to the caching directory. Attributes ---------- scores_ : array, shape = [n_features] Feature scores between 0 and 1. all_scores_ : array, shape = [n_features, n_reg_parameter] Feature scores between 0 and 1 for all values of the regularization \ parameter. The reference article suggests ``scores_`` is the max \ of ``all_scores_``. Examples -------- >>> from sklearn.linear_model import RandomizedLogisticRegression >>> randomized_logistic = RandomizedLogisticRegression() Notes ----- See examples/linear_model/plot_sparse_recovery.py for an example. References ---------- Stability selection Nicolai Meinshausen, Peter Buhlmann Journal of the Royal Statistical Society: Series B Volume 72, Issue 4, pages 417-473, September 2010 DOI: 10.1111/j.1467-9868.2010.00740.x See also -------- RandomizedLasso, LogisticRegression """ def __init__(self, C=1, scaling=.5, sample_fraction=.75, n_resampling=200, selection_threshold=.25, tol=1e-3, fit_intercept=True, verbose=False, normalize=True, random_state=None, n_jobs=1, pre_dispatch='3*n_jobs', memory=Memory(cachedir=None, verbose=0)): self.C = C self.scaling = scaling self.sample_fraction = sample_fraction self.n_resampling = n_resampling self.fit_intercept = fit_intercept self.verbose = verbose self.normalize = normalize self.tol = tol self.random_state = random_state self.n_jobs = n_jobs self.selection_threshold = selection_threshold self.pre_dispatch = pre_dispatch self.memory = memory def _make_estimator_and_params(self, X, y): params = dict(C=self.C, tol=self.tol, fit_intercept=self.fit_intercept) return _randomized_logistic, params def _preprocess_data(self, X, y, fit_intercept, normalize=False): """Center the data in X but not in y""" X, _, X_offset, _, X_scale = _preprocess_data(X, y, fit_intercept, normalize=normalize) return X, y, X_offset, y, X_scale ############################################################################### # Stability paths def _lasso_stability_path(X, y, mask, weights, eps): "Inner loop of lasso_stability_path" X = X * weights[np.newaxis, :] X = X[safe_mask(X, mask), :] y = y[mask] alpha_max = np.max(np.abs(np.dot(X.T, y))) / X.shape[0] alpha_min = eps * alpha_max # set for early stopping in path with warnings.catch_warnings(): warnings.simplefilter('ignore', ConvergenceWarning) alphas, _, coefs = lars_path(X, y, method='lasso', verbose=False, alpha_min=alpha_min) # Scale alpha by alpha_max alphas /= alphas[0] # Sort alphas in ascending order alphas = alphas[::-1] coefs = coefs[:, ::-1] # Get rid of the alphas that are too small mask = alphas >= eps # We also want to keep the first one: it should be close to the OLS # solution mask[0] = True alphas = alphas[mask] coefs = coefs[:, mask] return alphas, coefs def lasso_stability_path(X, y, scaling=0.5, random_state=None, n_resampling=200, n_grid=100, sample_fraction=0.75, eps=4 * np.finfo(np.float).eps, n_jobs=1, verbose=False): """Stability path based on randomized Lasso estimates Read more in the :ref:`User Guide <randomized_l1>`. Parameters ---------- X : array-like, shape = [n_samples, n_features] training data. y : array-like, shape = [n_samples] target values. scaling : float, optional, default=0.5 The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. random_state : integer or numpy.random.RandomState, optional The generator used to randomize the design. n_resampling : int, optional, default=200 Number of randomized models. n_grid : int, optional, default=100 Number of grid points. The path is linearly reinterpolated on a grid between 0 and 1 before computing the scores. sample_fraction : float, optional, default=0.75 The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. eps : float, optional Smallest value of alpha / alpha_max considered n_jobs : integer, optional Number of CPUs to use during the resampling. If '-1', use all the CPUs verbose : boolean or integer, optional Sets the verbosity amount Returns ------- alphas_grid : array, shape ~ [n_grid] The grid points between 0 and 1: alpha/alpha_max scores_path : array, shape = [n_features, n_grid] The scores for each feature along the path. Notes ----- See examples/linear_model/plot_sparse_recovery.py for an example. """ rng = check_random_state(random_state) if not (0 < scaling < 1): raise ValueError("Parameter 'scaling' should be between 0 and 1." " Got %r instead." % scaling) n_samples, n_features = X.shape paths = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(_lasso_stability_path)( X, y, mask=rng.rand(n_samples) < sample_fraction, weights=1. - scaling * rng.randint(0, 2, size=(n_features,)), eps=eps) for k in range(n_resampling)) all_alphas = sorted(list(set(itertools.chain(*[p[0] for p in paths])))) # Take approximately n_grid values stride = int(max(1, int(len(all_alphas) / float(n_grid)))) all_alphas = all_alphas[::stride] if not all_alphas[-1] == 1: all_alphas.append(1.) all_alphas = np.array(all_alphas) scores_path = np.zeros((n_features, len(all_alphas))) for alphas, coefs in paths: if alphas[0] != 0: alphas = np.r_[0, alphas] coefs = np.c_[np.ones((n_features, 1)), coefs] if alphas[-1] != all_alphas[-1]: alphas = np.r_[alphas, all_alphas[-1]] coefs = np.c_[coefs, np.zeros((n_features, 1))] scores_path += (interp1d(alphas, coefs, kind='nearest', bounds_error=False, fill_value=0, axis=-1)(all_alphas) != 0) scores_path /= n_resampling return all_alphas, scores_path
from __future__ import division import itertools from enum import Enum import numpy as np import amnet from amnet.util import Relation import z3 ################################################################################ # Classes and routines related to Multiplexing Programming with AMNs ################################################################################ ############ # Objective ############ class Objective(object): """ Class that keeps track of: flag to minimize or maximize real-valued Amn instance (ensures 1-dimensional output) unique variable input """ def __init__(self, phi, minimize=True): assert phi.outdim == 1 self.minimize = minimize self.phi = phi self.variable = amnet.tree.unique_leaf_of(phi) self.is_negated = False def negate(self): assert self.phi.outdim == 1 self.phi = amnet.atoms.negate(self.phi) self.is_negated = (not self.is_negated) self.minimize = (not self.minimize) def __repr__(self): return "Objective(phi=%s, minimize=%s)" % (repr(self.phi), repr(self.minimize)) class Minimize(Objective): def __init__(self, phi): super(Minimize, self).__init__(phi, minimize=True) class Maximize(Objective): def __init__(self, phi): super(Maximize, self).__init__(phi, minimize=False) ############## # Constraints ############## class Constraint(object): """ Class that keeps track of the lhs, rhs, the type of relation, and ensures dimensionality coherence between the lhs and rhs """ def __init__(self, lhs, rhs, rel): # supported relations assert rel in [Relation.LT, Relation.LE, Relation.GT, Relation.GE, Relation.EQ, Relation.NE] self.rel = rel # lhs and rhs must be an Amn assert isinstance(lhs, amnet.Amn) self.lhs = lhs assert isinstance(rhs, amnet.Amn) self.rhs = rhs # at this point both self.lhs and self.rhs are valid Amn's assert self.lhs.outdim == self.rhs.outdim assert self.lhs.outdim >= 1 # cache input variable reference # XXX: possibly move this check into the problem creation routines lhs_variable = amnet.tree.unique_leaf_of(self.lhs) rhs_variable = amnet.tree.unique_leaf_of(self.rhs) assert lhs_variable is rhs_variable, 'LHS and RHS must depend on the same Variable' self.variable = lhs_variable def __repr__(self): return "Constraint(lhs=%s, rhs=%s, rel=%s)" % (repr(self.lhs), repr(self.rhs), repr(self.rel)) ########## # Problem ########## class OptResultCode(Enum): SUCCESS = 1 FAILURE = 2 INFEASIBLE = 3 UNBOUNDED_BELOW = 4 # not yet implemented UNBOUNDED_ABOVE = 5 # not yet implemented MAX_ITER = 6 class OptResult(object): def __init__(self, objval, value, code=OptResultCode.SUCCESS, model=None): self.objval = objval self.value = value self.status = code self.model = model def __repr__(self): return "OptResult(objval=%s, value=%s, status=%s, model=%s)" % \ (repr(self.objval), repr(self.value), repr(self.status), repr(self.model)) class OptOptions(object): def __init__(self): # default options self.obj_lo = -float(2**20) self.obj_hi = float(2**20) self.fptol = float(2**-1) self.verbosity = 2 self.max_iter = 100 class Problem(object): # Objective (or constant) # list of Constraints # solve() # single variable def __init__(self, objective, constraints=None, options=None, solver=None): assert objective is not None self.objective = objective self.constraints = [] if constraints is None else constraints self.options = OptOptions() if options is None else options # default options # default objective is zero for a feasibility problem if objective is None: assert len(constraints) >= 1 self.variable = constraints[0].variable self.objective = amnet.atoms.zero_from(self.variable, dim=1) else: self.variable = self.objective.variable # ensure the leaf variable is the same across constraints assert all([constraint.variable is self.variable for constraint in self.constraints]) # initialize default solver if necessary if solver is None: self.solver = z3.Solver() else: self.solver = solver self.enc_list = [] # initialize objective and constraint relations into the solver self._init_objective_constraints() self._encode_constraint_relations() def eval_feasible(self, xinp): """ returns whether or not xinp satisfies the constraints """ assert len(xinp) == self.objective.phi.indim feas = True for constraint in self.constraints: lhsval = constraint.lhs.eval(xinp) rhsval = constraint.rhs.eval(xinp) rel = constraint.rel # TODO: implement fptol here if rel == Relation.LT: feases = [l < r for (l, r) in itertools.izip(lhsval, rhsval)] elif rel == Relation.LE: feases = [l <= r for (l, r) in itertools.izip(lhsval, rhsval)] elif rel == Relation.GT: feases = [l > r for (l, r) in itertools.izip(lhsval, rhsval)] elif rel == Relation.GE: feases = [l >= r for (l, r) in itertools.izip(lhsval, rhsval)] elif rel == Relation.EQ: feases = [l == r for (l, r) in itertools.izip(lhsval, rhsval)] elif rel == Relation.NE: feases = [l != r for (l, r) in itertools.izip(lhsval, rhsval)] else: assert False, 'Impossible relation' assert len(lhsval) == len(feases) feas = feas and all(feases) # short-circuit if not feas: return feas return feas def _init_objective_constraints(self): assert self.solver is not None assert self.objective.phi.outdim == 1 # Amn instances for this problem are encoded in a particular order amn_list = list(itertools.chain( [self.objective.phi], [constraint.lhs for constraint in self.constraints], [constraint.rhs for constraint in self.constraints] )) assert len(amn_list) >= 1 assert (not (len(self.constraints) == 0)) or (len(amn_list) == 1) assert (not (len(self.constraints) > 0)) or (len(amn_list) > 1) # encode them into a single Smt encoder enc_list = amnet.smt.SmtEncoder.multiple_encoders_for( phi_list=amn_list, solver=self.solver, push_between=False ) assert len(enc_list) == len(amn_list) assert len(enc_list) >= 1 assert all([enc.solver is self.solver for enc in enc_list]) # set the encoder lists after encoding from Smt encoder self.enc_list = enc_list self.enc_objective = enc_list[0] assert (len(enc_list) - 1) % 2 == 0 ncons = (len(enc_list) - 1) // 2 self.enc_lhs_list = enc_list[1:1+ncons] self.enc_rhs_list = enc_list[1+ncons:1+2*ncons] assert len(self.enc_lhs_list) == len(self.constraints) assert len(self.enc_rhs_list) == len(self.constraints) assert 1 + len(self.enc_lhs_list) + len(self.enc_rhs_list) == len(self.enc_list) def _encode_constraint_relations(self): assert self.solver is not None assert len(self.enc_list) >= 1 # input variable amn reference x = self.enc_objective.var_of_input() # Amn instances for this problem are encoded in a particular order for i in xrange(len(self.constraints)): phi_lhs = self.constraints[i].lhs phi_rhs = self.constraints[i].rhs enc_lhs = self.enc_lhs_list[i] enc_rhs = self.enc_rhs_list[i] rel = self.constraints[i].rel # determine z3 variables v_lhs = enc_lhs.var_of(phi_lhs) v_rhs = enc_rhs.var_of(phi_rhs) inp_lhs = enc_lhs.var_of_input() inp_rhs = enc_rhs.var_of_input() assert len(v_lhs) == len(v_rhs) assert len(v_lhs) == phi_lhs.outdim assert len(v_lhs) == phi_rhs.outdim assert len(x) == len(inp_lhs) == len(inp_rhs) # encode the relation amnet.util.relv_z3(self.solver, v_lhs, v_rhs, rel) # equate all the inputs of all the constraints to the input of the objective amnet.util.eqv_z3(self.solver, x, inp_lhs) amnet.util.eqv_z3(self.solver, x, inp_rhs) def _encode_objective_relation(self, gamma, rel=Relation.LE): assert self.solver is not None assert len(self.enc_list) >= 1 # determine z3 variables to compare v_obj = self.enc_objective.var_of(self.objective.phi) v_obj_rhs = np.array([gamma]) assert len(v_obj) == 1 # encode the relation amnet.util.relv_z3(self.solver, v_obj, v_obj_rhs, rel) def _bisection_minimize(self, check_constraints=True): assert self.objective.minimize # initialize lo and hi lo = self.options.obj_lo hi = self.options.obj_hi assert lo <= hi # initialize z3 encoding of objective and constraints # self._init_objective_constraints() # self._encode_constraint_relations() result = OptResult( value=None, objval=None, code=OptResultCode.FAILURE, model=None ) if check_constraints: result_z3 = self.solver.check() if result_z3 == z3.unsat: result.status = OptResultCode.INFEASIBLE if self.options.verbosity >= 2: print "Problem Infeasible" return result iter_ctr = 0 if self.options.verbosity >= 1: print print '{:3s} | {:11} | {:11} | {:11} | {:5} | {:11} | {:11} '.format( 'itr', 'lo', 'hi', 'gam', 'res', 'obj', 'feas' ) print '='*79 while True: assert lo <= hi iter_ctr += 1 # give up if the number of iterations exceeded maximum if iter_ctr > self.options.max_iter: result.status = OptResultCode.MAX_ITER if self.options.verbosity >= 1: print "Max iterations reached." return result # done with bisection, exit with last valid model # TODO: implement unboundedness check if (hi - lo) <= self.options.fptol: if self.options.verbosity >= 1: print "Solution found." print " objval: {:f}".format(result.objval) if self.options.verbosity >= 2: print ' point:', result.value return result # reset solver state to remove last obj <= gamma constraint if iter_ctr > 1: self.solver.pop() # try an objective value assert hi - lo > self.options.fptol self.solver.push() gamma = (lo + hi) / 2 self._encode_objective_relation(gamma, rel=Relation.LE) # bisect #print 'OPT: trying gamma=%d' % (gamma) print '{:>3d} | {:11.5g} | {:11.5g} | {:11.5g} |'.format(iter_ctr, lo, hi, gamma), #print 'SOLVER: %s' % self.solver result_z3 = self.solver.check() if result_z3 == z3.sat: print '{:5} |'.format('sat'), model = self.solver.model() #print 'MODEL: %s' % model xv = self.enc_objective.var_of_input() f = self.enc_objective.var_of(self.objective.phi) assert len(xv) == self.variable.outdim assert len(f) == 1 result.value = amnet.util.mfpv(model, xv) result.objval = amnet.util.mfp(model, f[0]) result.status = OptResultCode.SUCCESS result.model = model # numerical feasibility check is_feas = self.eval_feasible(result.value) #assert is_feas print '{:11.5g} | {} '.format(result.objval, is_feas) # update bound hi = gamma elif result_z3 == z3.unsat: print '{:5} |'.format('unsat'), print '{:11} | {} '.format(result.objval, False) # update bound lo = gamma else: assert False, 'Invalid result from z3' def _bisection_maximize(self): # XXX: default implementation: negate the objective and minimize instead assert (not self.objective.minimize) self.objective.negate() assert self.objective.minimize return self._bisection_minimize() def solve(self): if self.objective.minimize: return self._bisection_minimize() else: return self._bisection_maximize()
# Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Main entry point into the EC2 Credentials service. This service allows the creation of access/secret credentials used for the ec2 interop layer of OpenStack. A user can create as many access/secret pairs, each of which map to a specific project. This is required because OpenStack supports a user belonging to multiple projects, whereas the signatures created on ec2-style requests don't allow specification of which project the user wishes to act upon. To complete the cycle, we provide a method that OpenStack services can use to validate a signature and get a corresponding OpenStack token. This token allows method calls to other services within the context the access/secret was created. As an example, Nova requests Keystone to validate the signature of a request, receives a token, and then makes a request to Glance to list images needed to perform the requested task. """ import abc import sys import uuid import six from keystoneclient.contrib.ec2 import utils as ec2_utils from keystone.common import controller from keystone.common import dependency from keystone.common import utils from keystone.common import wsgi from keystone import exception from keystone.i18n import _ from keystone.openstack.common import jsonutils @dependency.requires('assignment_api', 'catalog_api', 'credential_api', 'identity_api', 'token_api') @six.add_metaclass(abc.ABCMeta) class Ec2ControllerCommon(object): def check_signature(self, creds_ref, credentials): signer = ec2_utils.Ec2Signer(creds_ref['secret']) signature = signer.generate(credentials) if utils.auth_str_equal(credentials['signature'], signature): return # NOTE(vish): Some libraries don't use the port when signing # requests, so try again without port. elif ':' in credentials['signature']: hostname, _port = credentials['host'].split(':') credentials['host'] = hostname signature = signer.generate(credentials) if not utils.auth_str_equal(credentials.signature, signature): raise exception.Unauthorized(message='Invalid EC2 signature.') else: raise exception.Unauthorized(message='EC2 signature not supplied.') @abc.abstractmethod def authenticate(self, context, credentials=None, ec2Credentials=None): """Validate a signed EC2 request and provide a token. Other services (such as Nova) use this **admin** call to determine if a request they signed received is from a valid user. If it is a valid signature, an OpenStack token that maps to the user/tenant is returned to the caller, along with all the other details returned from a normal token validation call. The returned token is useful for making calls to other OpenStack services within the context of the request. :param context: standard context :param credentials: dict of ec2 signature :param ec2Credentials: DEPRECATED dict of ec2 signature :returns: token: OpenStack token equivalent to access key along with the corresponding service catalog and roles """ raise exception.NotImplemented() def _authenticate(self, credentials=None, ec2credentials=None): """Common code shared between the V2 and V3 authenticate methods. :returns: user_ref, tenant_ref, metadata_ref, roles_ref, catalog_ref """ # FIXME(ja): validate that a service token was used! # NOTE(termie): backwards compat hack if not credentials and ec2credentials: credentials = ec2credentials if 'access' not in credentials: raise exception.Unauthorized(message='EC2 signature not supplied.') creds_ref = self._get_credentials(credentials['access']) self.check_signature(creds_ref, credentials) # TODO(termie): don't create new tokens every time # TODO(termie): this is copied from TokenController.authenticate tenant_ref = self.assignment_api.get_project(creds_ref['tenant_id']) user_ref = self.identity_api.get_user(creds_ref['user_id']) metadata_ref = {} metadata_ref['roles'] = ( self.assignment_api.get_roles_for_user_and_project( user_ref['id'], tenant_ref['id'])) trust_id = creds_ref.get('trust_id') if trust_id: metadata_ref['trust_id'] = trust_id metadata_ref['trustee_user_id'] = user_ref['id'] # Validate that the auth info is valid and nothing is disabled try: self.identity_api.assert_user_enabled( user_id=user_ref['id'], user=user_ref) self.assignment_api.assert_domain_enabled( domain_id=user_ref['domain_id']) self.assignment_api.assert_project_enabled( project_id=tenant_ref['id'], project=tenant_ref) except AssertionError as e: six.reraise(exception.Unauthorized, exception.Unauthorized(e), sys.exc_info()[2]) roles = metadata_ref.get('roles', []) if not roles: raise exception.Unauthorized(message='User not valid for tenant.') roles_ref = [self.assignment_api.get_role(role_id) for role_id in roles] catalog_ref = self.catalog_api.get_catalog( user_ref['id'], tenant_ref['id'], metadata_ref) return user_ref, tenant_ref, metadata_ref, roles_ref, catalog_ref def create_credential(self, context, user_id, tenant_id): """Create a secret/access pair for use with ec2 style auth. Generates a new set of credentials that map the user/tenant pair. :param context: standard context :param user_id: id of user :param tenant_id: id of tenant :returns: credential: dict of ec2 credential """ self.identity_api.get_user(user_id) self.assignment_api.get_project(tenant_id) trust_id = self._get_trust_id_for_request(context) blob = {'access': uuid.uuid4().hex, 'secret': uuid.uuid4().hex, 'trust_id': trust_id} credential_id = utils.hash_access_key(blob['access']) cred_ref = {'user_id': user_id, 'project_id': tenant_id, 'blob': jsonutils.dumps(blob), 'id': credential_id, 'type': 'ec2'} self.credential_api.create_credential(credential_id, cred_ref) return {'credential': self._convert_v3_to_ec2_credential(cred_ref)} def get_credentials(self, user_id): """List all credentials for a user. :param user_id: id of user :returns: credentials: list of ec2 credential dicts """ self.identity_api.get_user(user_id) credential_refs = self.credential_api.list_credentials( user_id=user_id) return {'credentials': [self._convert_v3_to_ec2_credential(credential) for credential in credential_refs]} def get_credential(self, user_id, credential_id): """Retrieve a user's access/secret pair by the access key. Grab the full access/secret pair for a given access key. :param user_id: id of user :param credential_id: access key for credentials :returns: credential: dict of ec2 credential """ self.identity_api.get_user(user_id) return {'credential': self._get_credentials(credential_id)} def delete_credential(self, user_id, credential_id): """Delete a user's access/secret pair. Used to revoke a user's access/secret pair :param user_id: id of user :param credential_id: access key for credentials :returns: bool: success """ self.identity_api.get_user(user_id) self._get_credentials(credential_id) ec2_credential_id = utils.hash_access_key(credential_id) return self.credential_api.delete_credential(ec2_credential_id) @staticmethod def _convert_v3_to_ec2_credential(credential): # Prior to bug #1259584 fix, blob was stored unserialized # but it should be stored as a json string for compatibility # with the v3 credentials API. Fall back to the old behavior # for backwards compatibility with existing DB contents try: blob = jsonutils.loads(credential['blob']) except TypeError: blob = credential['blob'] return {'user_id': credential.get('user_id'), 'tenant_id': credential.get('project_id'), 'access': blob.get('access'), 'secret': blob.get('secret'), 'trust_id': blob.get('trust_id')} def _get_credentials(self, credential_id): """Return credentials from an ID. :param credential_id: id of credential :raises exception.Unauthorized: when credential id is invalid :returns: credential: dict of ec2 credential. """ ec2_credential_id = utils.hash_access_key(credential_id) creds = self.credential_api.get_credential(ec2_credential_id) if not creds: raise exception.Unauthorized(message='EC2 access key not found.') return self._convert_v3_to_ec2_credential(creds) @dependency.requires('policy_api', 'token_provider_api') class Ec2Controller(Ec2ControllerCommon, controller.V2Controller): @controller.v2_deprecated def authenticate(self, context, credentials=None, ec2Credentials=None): (user_ref, tenant_ref, metadata_ref, roles_ref, catalog_ref) = self._authenticate(credentials=credentials, ec2credentials=ec2Credentials) # NOTE(morganfainberg): Make sure the data is in correct form since it # might be consumed external to Keystone and this is a v2.0 controller. # The token provider does not explicitly care about user_ref version # in this case, but the data is stored in the token itself and should # match the version user_ref = self.v3_to_v2_user(user_ref) auth_token_data = dict(user=user_ref, tenant=tenant_ref, metadata=metadata_ref, id='placeholder') (token_id, token_data) = self.token_provider_api.issue_v2_token( auth_token_data, roles_ref, catalog_ref) return token_data @controller.v2_deprecated def get_credential(self, context, user_id, credential_id): if not self._is_admin(context): self._assert_identity(context, user_id) return super(Ec2Controller, self).get_credential(user_id, credential_id) @controller.v2_deprecated def get_credentials(self, context, user_id): if not self._is_admin(context): self._assert_identity(context, user_id) return super(Ec2Controller, self).get_credentials(user_id) @controller.v2_deprecated def create_credential(self, context, user_id, tenant_id): if not self._is_admin(context): self._assert_identity(context, user_id) return super(Ec2Controller, self).create_credential(context, user_id, tenant_id) @controller.v2_deprecated def delete_credential(self, context, user_id, credential_id): if not self._is_admin(context): self._assert_identity(context, user_id) self._assert_owner(user_id, credential_id) return super(Ec2Controller, self).delete_credential(user_id, credential_id) def _assert_identity(self, context, user_id): """Check that the provided token belongs to the user. :param context: standard context :param user_id: id of user :raises exception.Forbidden: when token is invalid """ try: token_ref = self.token_api.get_token(context['token_id']) except exception.TokenNotFound as e: raise exception.Unauthorized(e) if token_ref['user'].get('id') != user_id: raise exception.Forbidden(_('Token belongs to another user')) def _is_admin(self, context): """Wrap admin assertion error return statement. :param context: standard context :returns: bool: success """ try: # NOTE(morganfainberg): policy_api is required for assert_admin # to properly perform policy enforcement. self.assert_admin(context) return True except exception.Forbidden: return False def _assert_owner(self, user_id, credential_id): """Ensure the provided user owns the credential. :param user_id: expected credential owner :param credential_id: id of credential object :raises exception.Forbidden: on failure """ ec2_credential_id = utils.hash_access_key(credential_id) cred_ref = self.credential_api.get_credential(ec2_credential_id) if user_id != cred_ref['user_id']: raise exception.Forbidden(_('Credential belongs to another user')) @dependency.requires('policy_api', 'token_provider_api') class Ec2ControllerV3(Ec2ControllerCommon, controller.V3Controller): member_name = 'project' def __init__(self): super(Ec2ControllerV3, self).__init__() self.get_member_from_driver = self.credential_api.get_credential def _check_credential_owner_and_user_id_match(self, context, prep_info, user_id, credential_id): # NOTE(morganfainberg): this method needs to capture the arguments of # the method that is decorated with @controller.protected() (with # exception of the first argument ('context') since the protected # method passes in *args, **kwargs. In this case, it is easier to see # the expected input if the argspec is `user_id` and `credential_id` # explicitly (matching the :class:`.ec2_delete_credential()` method # below). ref = {} credential_id = utils.hash_access_key(credential_id) ref['credential'] = self.credential_api.get_credential(credential_id) # NOTE(morganfainberg): policy_api is required for this # check_protection to properly be able to perform policy enforcement. self.check_protection(context, prep_info, ref) def authenticate(self, context, credentials=None, ec2Credentials=None): (user_ref, project_ref, metadata_ref, roles_ref, catalog_ref) = self._authenticate(credentials=credentials, ec2credentials=ec2Credentials) method_names = ['ec2credential'] token_id, token_data = self.token_provider_api.issue_v3_token( user_ref['id'], method_names, project_id=project_ref['id'], metadata_ref=metadata_ref) return render_token_data_response(token_id, token_data) @controller.protected() def ec2_get_credential(self, context, user_id, credential_id): return super(Ec2ControllerV3, self).get_credential(user_id, credential_id) @controller.protected() def ec2_list_credentials(self, context, user_id): return super(Ec2ControllerV3, self).get_credentials(user_id) @controller.protected() def ec2_create_credential(self, context, user_id, tenant_id): return super(Ec2ControllerV3, self).create_credential(context, user_id, tenant_id) @controller.protected(callback=_check_credential_owner_and_user_id_match) def ec2_delete_credential(self, context, user_id, credential_id): return super(Ec2ControllerV3, self).delete_credential(user_id, credential_id) def render_token_data_response(token_id, token_data): """Render token data HTTP response. Stash token ID into the X-Subject-Token header. """ headers = [('X-Subject-Token', token_id)] return wsgi.render_response(body=token_data, status=(200, 'OK'), headers=headers)
"""File like interface for reading pdb coordinates.""" import os import numpy as np import topology as t STDOPEN=open def read_topology_parts(pdb_file_name): with STDOPEN(pdb_file_name) as pdb_file: for line in pdb_file: line_type = line[:6].strip() if line_type == 'ATOM' or line_type == 'HETATM': if line[12].isdigit(): atom_name = (line[13:16].strip() + line[12]).strip() else: atom_name = line[12:16].strip() resname = line[17:20].strip() res_idx = int(line[23:26]) # print ' yielding ', atom_name, resname, res_idx yield atom_name, resname, res_idx elif line_type == 'TER': yield None elif line_type == 'ENDMDL': return def read_residues(pdb_file_name): """Return a sequence of resname, atom_names for each molecule in the geometry or None. Chain separations are denoted by Nones. """ atom_names = [] last_resname = None last_res_idx = -1e100 for part in read_topology_parts(pdb_file_name): # print 'part = ', part if not part: last_resname += str(last_res_idx) yield last_resname, atom_names yield None atom_names = [] continue atom_name, resname, res_idx = part if last_res_idx != res_idx and atom_names != []: assert last_resname is not None last_resname += str(last_res_idx) yield last_resname, atom_names atom_names = [] atom_names.append(atom_name) last_res_idx = res_idx last_resname = resname if atom_names != []: last_resname += str(last_res_idx) yield last_resname, atom_names def read_topology(pdb_file_name, name=None): if name is None: name = os.path.splitext(pdb_file_name)[0] chain_idx = 0 chain_monomers = [] monomers = [] for residue in read_residues(pdb_file_name): if residue is None: chain_monomers.append(t.Polymer('%s_CHAIN%d' % (name, chain_idx), monomers)) chain_idx += 1 monomers = [] else: resname, atoms = residue monomers.append(t.Molecule(resname, atoms)) if chain_monomers != []: if monomers != []: chain_monomers.append(t.Polymer('%s_CHAIN%d' % (name, chain_idx), monomers)) return t.Polymer(name, chain_monomers) else: return t.Polymer(name, monomers) def read_coords(pdb_file_name): with PDBFile(pdb_file_name) as f: for coord in f: yield coord class PDBError(Exception): pass def molecule_coords_to_pdb(monomer, coords, adx=1, mdx=1): resname = monomer.name[:3] pdb_lines = [] for atom in monomer.atoms: if len(atom) < 4: atom_name = ' %-3s' % atom elif len(atom) == 4: atom_name = atom else: raise PDBError("Atom name too long: '%s'" % atom) x, y, z = coords[3 * (adx - 1):3 * adx] pdb_lines.append('ATOM %(adx)5d %(atom_name)s %(resname)3s %(mdx)3d %(x)8.3f%(y)8.3f%(z)8.3f' % locals()) adx += 1 return '\n'.join(pdb_lines) def single_chain_coords_to_pdb(top, coords): if len(coords) != 3 * top.num_atoms: raise PDBError("Wrong number of atoms in coords to match topology: %s != %s" % (len(coords), 3 * top.num_atoms)) adx = 1 monomer_parts = [] for mdx, monomer in enumerate(top.monomers, 1): monomer_parts.append(molecule_coords_to_pdb(monomer, coords, adx=adx, mdx=mdx)) adx += monomer.num_atoms return '\n'.join(monomer_parts) def multi_chain_coords_to_pdb(top, coords): if len(coords) != 3 * top.num_atoms: raise PDBError("Wrong number of atoms in coords to match topology: %s != %s" % (len(coords), 3 * top.num_atoms)) single_chain_parts = [] for polymer in top.monomers: chain_coords = polymer.get_coords(coords) single_chain_parts.append(single_chain_coords_to_pdb(polymer, chain_coords)) return '\nTER\n'.join(single_chain_parts) def coords_to_pdb(top, coords): if isinstance(top, t.Molecule): return molecule_coords_to_pdb(top, coords) elif isinstance(top, t.Polymer): if isinstance(top.monomers[0], t.Polymer): return multi_chain_coords_to_pdb(top, coords) else: return single_chain_coords_to_pdb(top, coords) else: raise Exception("Unrecognized Topology type.") def write_coords(pdb_file_name, topology, coords_iter): with PDBFile(pdb_file_name, 'w', topology=topology) as f: for coord in coords_iter: f.write(coord) class PDBFile(object): def __init__(self, name, mode='r', topology=None): available_modes = ['r', 'w', 'a'] if mode not in available_modes: raise PDBError("Mode string must be one of %s" % (', '.join("'%s'" % mode for mode in available_modes))) if mode=='w': if topology is None: raise PDBError("A topology is required to create a new PDB file.") self.file = STDOPEN(name, mode) self.topology = topology else: if topology is None: topology = read_topology(name) self.topology = topology self.file = STDOPEN(name, mode) self.name = name def __enter__(self): return self def __exit__(self, *args): self.close() return all(arg is None for arg in args) def close(self): self.file.close() def __iter__(self): return self def next(self): crds = [] f = self.file while True: line = f.next() line_type = line[:6].strip() if line_type == 'ATOM' or line_type == 'HETATM': x = float(line[30:38]) y = float(line[38:46]) z = float(line[46:54]) crds.extend([x, y, z]) elif line_type == 'ENDMDL': break return crds def read(self): return list(self) def write(self, x): self.file.write(coords_to_pdb(self.topology, x) + '\nENDMDL\n') open=PDBFile
from datetime import datetime from collections import namedtuple class Field(namedtuple("Field", ["field", "default", "formatter", "model"])): """Model Field Model fields represent JSON key/value pairs. When added to a PandoraModel the describe the unpacking logic for the API JSON and will be replaced at runtime with the values from the parsed JSON or their defaults. field name of the field from the incoming JSON default default value if key does not exist in the incoming JSON, None if not provided formatter formatter function accepting an API client and the value of the field as arguments, will be called on the value of the data for the field key in the incoming JSON. The return value of this function is used as the value of the field on the model object. model the model class that the value of this field should be constructed into the model construction logic will handle building a list or single model based on the type of data in the JSON """ def __new__(cls, field, default=None, formatter=None, model=None): return super().__new__(cls, field, default, formatter, model) class SyntheticField(namedtuple("SyntheticField", ["field"])): """Field Requiring Synthesis Synthetic fields may exist in the data but generally do not and require additional synthesis to arrive ate a sane value. Subclasses must define a formatter method that receives an API client, field name, and full data payload. """ def formatter(self, api_client, data, newval): """Format Value for Model The return value of this method is used as a value for the field in the model of which this field is a member api_client instance of a Pandora API client data complete JSON data blob for the parent model of which this field is a member newval the value of this field as retrieved from the JSON data after having resolved default value logic """ raise NotImplementedError class DateField(SyntheticField): """Date Field Handles a JSON map that contains a time field which is the timestamp with nanosecond precision. """ def formatter(self, api_client, data, newval): if not newval: return None return datetime.utcfromtimestamp(newval["time"] / 1000) class ModelMetaClass(type): def __new__(cls, name, parents, dct): dct["_fields"] = fields = {} new_dct = dct.copy() for key, val in dct.items(): if key.startswith("__"): continue if isinstance(val, Field) or isinstance(val, SyntheticField): fields[key] = val del new_dct[key] return super().__new__(cls, name, parents, new_dct) class PandoraModel(metaclass=ModelMetaClass): """Pandora API Model A single object representing a Pandora data object. Subclasses are specified declaratively and contain Field objects as well as optionally other methods. The end result object after loading from JSON will be a normal python object with all fields declared in the schema populated and consumers of these instances can ignore all of the details of this class. """ @classmethod def from_json_list(cls, api_client, data): """Convert a list of JSON values to a list of models""" return [cls.from_json(api_client, item) for item in data] def __init__(self, api_client): self._api_client = api_client safe_types = (type(None), str, bytes, int, bool) for key, value in self._fields.items(): default = getattr(value, "default", None) if not isinstance(default, safe_types): default = type(default)() setattr(self, key, default) @staticmethod def populate_fields(api_client, instance, data): """Populate all fields of a model with data Given a model with a PandoraModel superclass will enumerate all declared fields on that model and populate the values of their Field and SyntheticField classes. All declared fields will have a value after this function runs even if they are missing from the incoming JSON. """ for key, value in instance.__class__._fields.items(): default = getattr(value, "default", None) newval = data.get(value.field, default) if isinstance(value, SyntheticField): newval = value.formatter(api_client, data, newval) setattr(instance, key, newval) continue model_class = getattr(value, "model", None) if newval and model_class: if isinstance(newval, list): newval = model_class.from_json_list(api_client, newval) else: newval = model_class.from_json(api_client, newval) if newval and value.formatter: newval = value.formatter(api_client, newval) setattr(instance, key, newval) @classmethod def from_json(cls, api_client, data): """Convert one JSON value to a model object""" self = cls(api_client) PandoraModel.populate_fields(api_client, self, data) return self def _base_repr(self, and_also=None): """Common repr logic for subclasses to hook""" items = [ "=".join((key, repr(getattr(self, key)))) for key in sorted(self._fields.keys()) ] if items: output = ", ".join(items) else: output = None if and_also: return "{}({}, {})".format( self.__class__.__name__, output, and_also ) else: return "{}({})".format(self.__class__.__name__, output) def __repr__(self): return self._base_repr() class PandoraListModel(PandoraModel, list): """Dict-like List of Pandora Models Processes a JSON map, expecting a key that contains a list of maps. Will process each item in the list, creating models for each one and a secondary index based on the value in each item. This object behaves like a list and like a dict. Example JSON: { "__list_key__": [ { "__index_key__": "key", "other": "fields" }, { "__index_key__": "key", "other": "fields" } ], "other": "fields" } __list_key__ they key within the parent map containing a list __list_model__ model class to use when constructing models for list contents __index_key__ key from each object in the model list that will be used as an index within this object """ __list_key__ = None __list_model__ = None __index_key__ = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._index = {} @classmethod def from_json(cls, api_client, data): self = cls(api_client) PandoraModel.populate_fields(api_client, self, data) for item in data[cls.__list_key__]: model = cls.__list_model__.from_json(api_client, item) if self.__index_key__: value = getattr(model, self.__index_key__) self._index[value] = model self.append(model) return self def __getitem__(self, key): item = self._index.get(key, None) if item: return item else: return list.__getitem__(self, key) def __contains__(self, key): if key in self._index: return True else: return list.__contains__(self, key) def keys(self): return self._index.keys() def items(self): return self._index.items() def __repr__(self): return self._base_repr(and_also=list.__repr__(self)) class PandoraDictListModel(PandoraModel, dict): """Dict of Models Processes a JSON map, expecting a key that contains a list of maps, each of which contain a key and a list of values which are the final models. Will process each item in the list, creating models for each one and storing the constructed models in a map indexed by the dict key. Duplicated sub-maps will be merged into one key for this model. Example JSON: { "__dict_list_key__": [ { "__dict_key__": "key for this model", "__list_key__": [ { "model": "fields" }, { "model": "fields" } ] } ], "other": "fields" } __dict_list_key__ the key within the parent map that contains the maps that contain lists of models __dict_key__ the key within the nested map that contains the key for this object __list_key__ they key within the nested map that contains the list of models __list_model__ model class to use when constructing models for list contents """ __dict_list_key__ = None __dict_key__ = None __list_key__ = None __list_model__ = None @classmethod def from_json(cls, api_client, data): self = cls(api_client) PandoraModel.populate_fields(api_client, self, data) for item in data[self.__dict_list_key__]: key = item[self.__dict_key__] self[key] = [] for part in item[self.__list_key__]: self[key].append( cls.__list_model__.from_json(api_client, part) ) return self def __repr__(self): return self._base_repr(and_also=dict.__repr__(self))
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Rupesh Tare <rupesht@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON ) # Import Salt Libs from salt.modules import influx DB_LIST = ['A', 'B', 'C'] USER_LIST = [{'name': 'A'}, {'name': 'B'}] class MockInfluxDBClient(object): def get_list_database(self): return DB_LIST def create_database(self, name): return name def delete_database(self, name): return name def switch_database(self, name): return name def get_list_users(self): return USER_LIST def get_list_cluster_admins(self): return USER_LIST def update_cluster_admin_password(self, name, passwd): return name, passwd def update_database_user_password(self, name, passwd): return name, passwd def delete_cluster_admin(self, name): return name def delete_database_user(self, name): return name def query(self, query, time_precision, chunked): return query, time_precision, chunked @skipIf(NO_MOCK, NO_MOCK_REASON) class InfluxTestCase(TestCase): ''' TestCase for the salt.modules.at module ''' def test_db_list(self): """ Test to list all InfluxDB databases """ mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): self.assertEqual(influx.db_list(user='root', password='root', host='localhost', port=8086), DB_LIST) def test_db_exists(self): ''' Tests for checks if a database exists in InfluxDB ''' with patch.object(influx, 'db_list', side_effect=[[{'name': 'A'}], None]): self.assertTrue(influx.db_exists(name='A', user='root', password='root', host='localhost', port=8000)) self.assertFalse(influx.db_exists(name='A', user='root', password='root', host='localhost', port=8000)) def test_db_create(self): ''' Test to create a database ''' with patch.object(influx, 'db_exists', side_effect=[True, False]): self.assertFalse(influx.db_create(name='A', user='root', password='root', host='localhost', port=8000)) mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): self.assertTrue(influx.db_create(name='A', user='root', password='root', host='localhost', port=8000)) def test_db_remove(self): ''' Test to remove a database ''' with patch.object(influx, 'db_exists', side_effect=[False, True]): self.assertFalse(influx.db_remove(name='A', user='root', password='root', host='localhost', port=8000)) mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): self.assertTrue(influx.db_remove(name='A', user='root', password='root', host='localhost', port=8000)) def test_user_list(self): ''' Tests for list cluster admins or database users. ''' mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): self.assertListEqual(influx.user_list(database='A', user='root', password='root', host='localhost', port=8086), USER_LIST) self.assertListEqual(influx.user_list(user='root', password='root', host='localhost', port=8086), USER_LIST) def test_user_exists(self): ''' Test to checks if a cluster admin or database user exists. ''' with patch.object(influx, 'user_list', side_effect=[[{'name': 'A'}], None]): self.assertTrue(influx.user_exists(name='A', user='root', password='root', host='localhost', port=8000)) self.assertFalse(influx.user_exists(name='A', user='root', password='root', host='localhost', port=8000)) def test_user_chpass(self): ''' Tests to change password for a cluster admin or a database user. ''' with patch.object(influx, 'user_exists', return_value=False): self.assertFalse(influx.user_chpass(name='A', passwd='*', user='root', password='root', host='localhost', port=8000)) self.assertFalse(influx.user_chpass(name='A', passwd='*', database='test', user='root', password='root', host='localhost', port=8000)) mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): with patch.object(influx, 'user_exists', return_value=True): self.assertTrue(influx.user_chpass(name='A', passwd='*', user='root', password='root', host='localhost', port=8000)) self.assertTrue(influx.user_chpass(name='A', passwd='*', database='test', user='root', password='root', host='localhost', port=8000)) def test_user_remove(self): ''' Tests to remove a cluster admin or a database user. ''' with patch.object(influx, 'user_exists', return_value=False): self.assertFalse(influx.user_remove(name='A', user='root', password='root', host='localhost', port=8000)) self.assertFalse(influx.user_remove(name='A', database='test', user='root', password='root', host='localhost', port=8000)) mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): with patch.object(influx, 'user_exists', return_value=True): self.assertTrue(influx.user_remove(name='A', user='root', password='root', host='localhost', port=8000)) self.assertTrue(influx.user_remove(name='A', database='test', user='root', password='root', host='localhost', port=8000)) def test_query(self): ''' Test for querying data ''' mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): self.assertTrue(influx.query(database='db', query='q', user='root', password='root', host='localhost', port=8000)) def test_retention_policy_get(self): client = MockInfluxDBClient() policy = {'name': 'foo'} with patch.object(influx, '_client', MagicMock(return_value=client)): client.get_list_retention_policies = MagicMock(return_value=[policy]) self.assertEqual( policy, influx.retention_policy_get(database='db', name='foo') ) def test_retention_policy_add(self): client = MockInfluxDBClient() with patch.object(influx, '_client', MagicMock(return_value=client)): client.create_retention_policy = MagicMock() self.assertTrue(influx.retention_policy_add( database='db', name='name', duration='30d', replication=1, )) client.create_retention_policy.assert_called_once_with( 'name', '30d', 1, 'db', False) def test_retention_policy_modify(self): client = MockInfluxDBClient() with patch.object(influx, '_client', MagicMock(return_value=client)): client.alter_retention_policy = MagicMock() self.assertTrue(influx.retention_policy_alter( database='db', name='name', duration='30d', replication=1, )) client.alter_retention_policy.assert_called_once_with( 'name', 'db', '30d', 1, False) if __name__ == '__main__': from integration import run_tests run_tests(InfluxTestCase, needs_daemon=False)
"""Support for Huawei LTE routers.""" from collections import defaultdict from datetime import timedelta from functools import partial import ipaddress import logging from typing import Any, Callable, Dict, List, Set, Tuple from urllib.parse import urlparse import attr from getmac import get_mac_address from huawei_lte_api.AuthorizedConnection import AuthorizedConnection from huawei_lte_api.Client import Client from huawei_lte_api.Connection import Connection from huawei_lte_api.exceptions import ( ResponseErrorLoginRequiredException, ResponseErrorNotSupportedException, ) from requests.exceptions import Timeout from url_normalize import url_normalize import voluptuous as vol from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_PASSWORD, CONF_RECIPIENT, CONF_URL, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import CALLBACK_TYPE from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import ( config_validation as cv, device_registry as dr, discovery, ) from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, dispatcher_send, ) from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.typing import HomeAssistantType from .const import ( ALL_KEYS, CONNECTION_TIMEOUT, DEFAULT_DEVICE_NAME, DOMAIN, KEY_DEVICE_BASIC_INFORMATION, KEY_DEVICE_INFORMATION, KEY_DEVICE_SIGNAL, KEY_DIALUP_MOBILE_DATASWITCH, KEY_MONITORING_STATUS, KEY_MONITORING_TRAFFIC_STATISTICS, KEY_WLAN_HOST_LIST, SERVICE_CLEAR_TRAFFIC_STATISTICS, SERVICE_REBOOT, UPDATE_OPTIONS_SIGNAL, UPDATE_SIGNAL, ) _LOGGER = logging.getLogger(__name__) # dicttoxml (used by huawei-lte-api) has uselessly verbose INFO level. # https://github.com/quandyfactory/dicttoxml/issues/60 logging.getLogger("dicttoxml").setLevel(logging.WARNING) DEFAULT_NAME_TEMPLATE = "Huawei {} {}" SCAN_INTERVAL = timedelta(seconds=10) NOTIFY_SCHEMA = vol.Any( None, vol.Schema( { vol.Optional(CONF_RECIPIENT): vol.Any( None, vol.All(cv.ensure_list, [cv.string]) ) } ), ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( cv.ensure_list, [ vol.Schema( { vol.Required(CONF_URL): cv.url, vol.Optional(CONF_USERNAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(NOTIFY_DOMAIN): NOTIFY_SCHEMA, } ) ], ) }, extra=vol.ALLOW_EXTRA, ) SERVICE_SCHEMA = vol.Schema({vol.Optional(CONF_URL): cv.url}) CONFIG_ENTRY_PLATFORMS = ( BINARY_SENSOR_DOMAIN, DEVICE_TRACKER_DOMAIN, SENSOR_DOMAIN, SWITCH_DOMAIN, ) @attr.s class Router: """Class for router state.""" connection: Connection = attr.ib() url: str = attr.ib() mac: str = attr.ib() signal_update: CALLBACK_TYPE = attr.ib() data: Dict[str, Any] = attr.ib(init=False, factory=dict) subscriptions: Dict[str, Set[str]] = attr.ib( init=False, factory=lambda: defaultdict(set, ((x, {"initial_scan"}) for x in ALL_KEYS)), ) unload_handlers: List[CALLBACK_TYPE] = attr.ib(init=False, factory=list) client: Client def __attrs_post_init__(self): """Set up internal state on init.""" self.client = Client(self.connection) @property def device_name(self) -> str: """Get router device name.""" for key, item in ( (KEY_DEVICE_BASIC_INFORMATION, "devicename"), (KEY_DEVICE_INFORMATION, "DeviceName"), ): try: return self.data[key][item] except (KeyError, TypeError): pass return DEFAULT_DEVICE_NAME @property def device_connections(self) -> Set[Tuple[str, str]]: """Get router connections for device registry.""" return {(dr.CONNECTION_NETWORK_MAC, self.mac)} if self.mac else set() def _get_data(self, key: str, func: Callable[[None], Any]) -> None: if not self.subscriptions.get(key): return _LOGGER.debug("Getting %s for subscribers %s", key, self.subscriptions[key]) try: self.data[key] = func() except ResponseErrorNotSupportedException: _LOGGER.info( "%s not supported by device, excluding from future updates", key ) self.subscriptions.pop(key) except ResponseErrorLoginRequiredException: if isinstance(self.connection, AuthorizedConnection): _LOGGER.debug("Trying to authorize again...") if self.connection.enforce_authorized_connection(): _LOGGER.debug( "...success, %s will be updated by a future periodic run", key, ) else: _LOGGER.debug("...failed") return _LOGGER.info( "%s requires authorization, excluding from future updates", key ) self.subscriptions.pop(key) finally: _LOGGER.debug("%s=%s", key, self.data.get(key)) def update(self) -> None: """Update router data.""" self._get_data(KEY_DEVICE_INFORMATION, self.client.device.information) if self.data.get(KEY_DEVICE_INFORMATION): # Full information includes everything in basic self.subscriptions.pop(KEY_DEVICE_BASIC_INFORMATION, None) self._get_data( KEY_DEVICE_BASIC_INFORMATION, self.client.device.basic_information ) self._get_data(KEY_DEVICE_SIGNAL, self.client.device.signal) self._get_data( KEY_DIALUP_MOBILE_DATASWITCH, self.client.dial_up.mobile_dataswitch ) self._get_data(KEY_MONITORING_STATUS, self.client.monitoring.status) self._get_data( KEY_MONITORING_TRAFFIC_STATISTICS, self.client.monitoring.traffic_statistics ) self._get_data(KEY_WLAN_HOST_LIST, self.client.wlan.host_list) self.signal_update() def cleanup(self, *_) -> None: """Clean up resources.""" self.subscriptions.clear() for handler in self.unload_handlers: handler() self.unload_handlers.clear() if not isinstance(self.connection, AuthorizedConnection): return try: self.client.user.logout() except ResponseErrorNotSupportedException: _LOGGER.debug("Logout not supported by device", exc_info=True) except ResponseErrorLoginRequiredException: _LOGGER.debug("Logout not supported when not logged in", exc_info=True) except Exception: # pylint: disable=broad-except _LOGGER.warning("Logout error", exc_info=True) @attr.s class HuaweiLteData: """Shared state.""" hass_config: dict = attr.ib() # Our YAML config, keyed by router URL config: Dict[str, Dict[str, Any]] = attr.ib() routers: Dict[str, Router] = attr.ib(init=False, factory=dict) async def async_setup_entry(hass: HomeAssistantType, config_entry: ConfigEntry) -> bool: """Set up Huawei LTE component from config entry.""" url = config_entry.data[CONF_URL] # Override settings from YAML config, but only if they're changed in it # Old values are stored as *_from_yaml in the config entry yaml_config = hass.data[DOMAIN].config.get(url) if yaml_config: # Config values new_data = {} for key in CONF_USERNAME, CONF_PASSWORD: if key in yaml_config: value = yaml_config[key] if value != config_entry.data.get(f"{key}_from_yaml"): new_data[f"{key}_from_yaml"] = value new_data[key] = value # Options new_options = {} yaml_recipient = yaml_config.get(NOTIFY_DOMAIN, {}).get(CONF_RECIPIENT) if yaml_recipient is not None and yaml_recipient != config_entry.options.get( f"{CONF_RECIPIENT}_from_yaml" ): new_options[f"{CONF_RECIPIENT}_from_yaml"] = yaml_recipient new_options[CONF_RECIPIENT] = yaml_recipient # Update entry if overrides were found if new_data or new_options: hass.config_entries.async_update_entry( config_entry, data={**config_entry.data, **new_data}, options={**config_entry.options, **new_options}, ) # Get MAC address for use in unique ids. Being able to use something # from the API would be nice, but all of that seems to be available only # through authenticated calls (e.g. device_information.SerialNumber), and # we want this available and the same when unauthenticated too. host = urlparse(url).hostname try: if ipaddress.ip_address(host).version == 6: mode = "ip6" else: mode = "ip" except ValueError: mode = "hostname" mac = await hass.async_add_executor_job(partial(get_mac_address, **{mode: host})) def get_connection() -> Connection: """ Set up a connection. Authorized one if username/pass specified (even if empty), unauthorized one otherwise. """ username = config_entry.data.get(CONF_USERNAME) password = config_entry.data.get(CONF_PASSWORD) if username or password: connection = AuthorizedConnection( url, username=username, password=password, timeout=CONNECTION_TIMEOUT ) else: connection = Connection(url, timeout=CONNECTION_TIMEOUT) return connection def signal_update() -> None: """Signal updates to data.""" dispatcher_send(hass, UPDATE_SIGNAL, url) try: connection = await hass.async_add_executor_job(get_connection) except Timeout as ex: raise ConfigEntryNotReady from ex # Set up router and store reference to it router = Router(connection, url, mac, signal_update) hass.data[DOMAIN].routers[url] = router # Do initial data update await hass.async_add_executor_job(router.update) # Clear all subscriptions, enabled entities will push back theirs router.subscriptions.clear() # Set up device registry device_data = {} sw_version = None if router.data.get(KEY_DEVICE_INFORMATION): device_info = router.data[KEY_DEVICE_INFORMATION] serial_number = device_info.get("SerialNumber") if serial_number: device_data["identifiers"] = {(DOMAIN, serial_number)} sw_version = device_info.get("SoftwareVersion") if device_info.get("DeviceName"): device_data["model"] = device_info["DeviceName"] if not sw_version and router.data.get(KEY_DEVICE_BASIC_INFORMATION): sw_version = router.data[KEY_DEVICE_BASIC_INFORMATION].get("SoftwareVersion") if sw_version: device_data["sw_version"] = sw_version device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections=router.device_connections, name=router.device_name, manufacturer="Huawei", **device_data, ) # Forward config entry setup to platforms for domain in CONFIG_ENTRY_PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) ) # Notify doesn't support config entry setup yet, load with discovery for now await discovery.async_load_platform( hass, NOTIFY_DOMAIN, DOMAIN, {CONF_URL: url, CONF_RECIPIENT: config_entry.options.get(CONF_RECIPIENT)}, hass.data[DOMAIN].hass_config, ) # Add config entry options update listener router.unload_handlers.append( config_entry.add_update_listener(async_signal_options_update) ) def _update_router(*_: Any) -> None: """ Update router data. Separate passthrough function because lambdas don't work with track_time_interval. """ router.update() # Set up periodic update router.unload_handlers.append( async_track_time_interval(hass, _update_router, SCAN_INTERVAL) ) # Clean up at end hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, router.cleanup) return True async def async_unload_entry( hass: HomeAssistantType, config_entry: ConfigEntry ) -> bool: """Unload config entry.""" # Forward config entry unload to platforms for domain in CONFIG_ENTRY_PLATFORMS: await hass.config_entries.async_forward_entry_unload(config_entry, domain) # Forget about the router and invoke its cleanup router = hass.data[DOMAIN].routers.pop(config_entry.data[CONF_URL]) await hass.async_add_executor_job(router.cleanup) return True async def async_setup(hass: HomeAssistantType, config) -> bool: """Set up Huawei LTE component.""" # Arrange our YAML config to dict with normalized URLs as keys domain_config = {} if DOMAIN not in hass.data: hass.data[DOMAIN] = HuaweiLteData(hass_config=config, config=domain_config) for router_config in config.get(DOMAIN, []): domain_config[url_normalize(router_config.pop(CONF_URL))] = router_config def service_handler(service) -> None: """Apply a service.""" url = service.data.get(CONF_URL) routers = hass.data[DOMAIN].routers if url: router = routers.get(url) elif len(routers) == 1: router = next(iter(routers.values())) else: _LOGGER.error( "%s: more than one router configured, must specify one of URLs %s", service.service, sorted(routers), ) return if not router: _LOGGER.error("%s: router %s unavailable", service.service, url) return if service.service == SERVICE_CLEAR_TRAFFIC_STATISTICS: result = router.client.monitoring.set_clear_traffic() _LOGGER.debug("%s: %s", service.service, result) elif service.service == SERVICE_REBOOT: result = router.client.device.reboot() _LOGGER.debug("%s: %s", service.service, result) else: _LOGGER.error("%s: unsupported service", service.service) for service in (SERVICE_CLEAR_TRAFFIC_STATISTICS, SERVICE_REBOOT): hass.helpers.service.async_register_admin_service( DOMAIN, service, service_handler, schema=SERVICE_SCHEMA, ) for url, router_config in domain_config.items(): hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_URL: url, CONF_USERNAME: router_config.get(CONF_USERNAME), CONF_PASSWORD: router_config.get(CONF_PASSWORD), }, ) ) return True async def async_signal_options_update( hass: HomeAssistantType, config_entry: ConfigEntry ) -> None: """Handle config entry options update.""" async_dispatcher_send(hass, UPDATE_OPTIONS_SIGNAL, config_entry) @attr.s class HuaweiLteBaseEntity(Entity): """Huawei LTE entity base class.""" router: Router = attr.ib() _available: bool = attr.ib(init=False, default=True) _unsub_handlers: List[Callable] = attr.ib(init=False, factory=list) @property def _entity_name(self) -> str: raise NotImplementedError @property def _device_unique_id(self) -> str: """Return unique ID for entity within a router.""" raise NotImplementedError @property def unique_id(self) -> str: """Return unique ID for entity.""" return f"{self.router.mac}-{self._device_unique_id}" @property def name(self) -> str: """Return entity name.""" return DEFAULT_NAME_TEMPLATE.format(self.router.device_name, self._entity_name) @property def available(self) -> bool: """Return whether the entity is available.""" return self._available @property def should_poll(self) -> bool: """Huawei LTE entities report their state without polling.""" return False @property def device_info(self) -> Dict[str, Any]: """Get info for matching with parent router.""" return {"connections": self.router.device_connections} async def async_update(self) -> None: """Update state.""" raise NotImplementedError async def async_update_options(self, config_entry: ConfigEntry) -> None: """Update config entry options.""" pass async def async_added_to_hass(self) -> None: """Connect to update signals.""" self._unsub_handlers.append( async_dispatcher_connect(self.hass, UPDATE_SIGNAL, self._async_maybe_update) ) self._unsub_handlers.append( async_dispatcher_connect( self.hass, UPDATE_OPTIONS_SIGNAL, self._async_maybe_update_options ) ) async def _async_maybe_update(self, url: str) -> None: """Update state if the update signal comes from our router.""" if url == self.router.url: self.async_schedule_update_ha_state(True) async def _async_maybe_update_options(self, config_entry: ConfigEntry) -> None: """Update options if the update signal comes from our router.""" if config_entry.data[CONF_URL] == self.router.url: await self.async_update_options(config_entry) async def async_will_remove_from_hass(self) -> None: """Invoke unsubscription handlers.""" for unsub in self._unsub_handlers: unsub() self._unsub_handlers.clear()
""" OpenDaylight REST API Copyright 2013 The University of Wisconsin Board of Regents 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. Written by: Dale W. Carder, dwcarder@wisc.edu Network Services Group Division of Information Technology University of Wisconsin at Madison This material is based upon work supported by the National Science Foundation under Grant No. 1247322. """ from __future__ import print_function import json import requests from requests.auth import HTTPBasicAuth class OpenDaylight(object): """An object holding details to talk to the OpenDaylight REST API OpenDaylight.setup is a dictionary loaded with the following default values: {'hostname':'localhost', 'port':'8080', 'username':'admin', 'password':'admin', 'path':'/controller/nb/v2/', 'container':'default', 'http':'http://' } Your code should change these as required for your installation. OpenDaylight.url holds the url for each REST query. Typically you would let OpenDaylight.prepare() build this for you. OpenDaylight.auth holds an auth object for Requests to use for each REST query. Typically you would also let OpenDaylight.prepare() build this for you. """ def __init__(self): """Set some mostly reasonable defaults. """ self.setup = {'hostname':'192.168.231.246', 'port':'8080', 'username':'admin', 'password':'admin', 'path':'/controller/nb/v2/', 'container':'default', 'http':'http://'} self._base_url = None self.url = None self.auth = None def prepare(self, app, path): """Sets up the necessary details for the REST connection by calling prepare_url and prepare_auth. Arguments: 'app' - which OpenDaylight northbound api component (application) we want to talk to. 'path' - the specific rest query for the application. """ self.prepare_url(app, path) self.prepare_auth() def prepare_url(self, app, path): """Build the URL for this REST connection which is then stored as OpenDaylight.url If you use prepare(), you shouldn't need to call prepare_url() yourself. However, if there were a URL you wanted to construct that was so whacked out custom, then by all means build it yourself and don't bother to call this function. Arguments: 'app' - which OpenDaylight northbound api component (application) we want to talk to. 'path' - the specific rest query for the application. Note that other attributes, including 'container' are specified in the OpenDaylight.setup dictionary. """ # the base url we will use for the connection self._base_url = self.setup['http'] + self.setup['hostname'] + ':' + \ self.setup['port'] + self.setup['path'] # the specific path we are building self.url = self._base_url + app + '/' + self.setup['container'] + path def prepare_auth(self): """Set up the credentials for the REST connection by creating an auth object for Requests and shoving it into OpenDaylight.auth Currently, as far as I know, the OpenDaylight controller uses http basic auth. If/when that changes this function should be updated. If you use prepare(), you shouldn't need to call prepare_auth() yourself. However, if there were something you wanted to do that was so whacked out custom, then by all means build it yourself and don't bother to call this function. """ # stuff an HTTPBasicAuth object in here ready for use self.auth = HTTPBasicAuth(self.setup['username'], self.setup['password']) #print("Prepare set up auth: " + self.setup['username'] + ', ' + \ # self.setup['password']) class OpenDaylightFlow(object): """OpenDaylightFlow is an object that talks to the OpenDaylight Flow Programmer application REST API OpenDaylight.odl holds an OpenDaylight object containing details on how to communicate with the controller. OpenDaylightFlow.request holds a Requests object for the REST session. Take a look at the Requests documentation for all of the methods available, but here are a few handy examples: OpenDaylightFlow.request.status_code - returns the http code OpenDaylightFlow.request.text - returns the response as text OpenDaylightFlow.flows holds a dictionary that corresponds to the flowConfig element in the OpenDaylight REST API. Note that we don't statically define what those fields are here in this object. This makes this library code more flexible as flowConfig changes over time. After all, this is REST, not RPC. """ def __init__(self, odl): """Mandatory argument: odl - an OpenDaylight object """ self.odl = odl self.__app = 'flow' self.request = None self.flows = None def get(self, node_id=None, flow_name=None): """Get Flows specified on the Controller and stuffs the results into the OpenDaylightFlow.flows dictionary. Optional Arguments: node_id - returns flows just for that switch dpid flow_name - returns the specifically named flow on that switch """ # clear out any remaining crud from previous calls if hasattr(self, 'request'): del self.request if hasattr(self, 'flows'): del self.flows if node_id is None: self.odl.prepare(self.__app, '/') elif flow_name is None: self.odl.prepare(self.__app, '/' + 'OF/' + node_id + '/') else: self.odl.prepare(self.__app, '/' + 'OF/' + node_id + '/' + flow_name + '/') self.request = requests.get(url=self.odl.url, auth=self.odl.auth) if self.request.status_code == 200: self.flows = self.request.json() if 'flowConfig' in self.flows: self.flows = self.flows.get('flowConfig') else: raise OpenDaylightError({'url':self.odl.url, 'http_code':self.request.status_code, 'msg':self.request.text}) def add(self, flow): """Given a dictionary corresponding to a flowConfig, add this flow to the Controller. Note that the switch dpid and the flow's name is specified in the flowConfig passed in. """ if hasattr(self, 'request'): del self.request #print(flow) self.odl.prepare(self.__app, '/' + flow['node']['@type'] + '/' + flow['node']['@id'] + '/' + flow['name'] + '/') headers = {'Content-type': 'application/json'} body = json.dumps(flow) self.request = requests.post(url=self.odl.url, auth=self.odl.auth, data=body, headers=headers) if self.request.status_code != 201: raise OpenDaylightError({'url':self.odl.url, 'http_code':self.request.status_code, 'msg':self.request.text}) #def update(self): # """Update a flow to a Node on the Controller # """ # raise NotImplementedError("update()") def delete(self, node_id, flow_name): """Delete a flow to a Node on the Controller Mandatory Arguments: node_id - the switch dpid flow_name - the specifically named flow on that switch """ if hasattr(self, 'request'): del self.request self.odl.prepare(self.__app, '/' + 'OF/' + node_id + '/' + flow_name + '/') self.request = requests.delete(url=self.odl.url, auth=self.odl.auth) # note, if you wanted to pass in a flowConfig style dictionary, # this is how you would do it. This is what I did initially, but # it seemed clunky to pass in an entire flow. #self.prepare(self.__app, '/' + flow['node']['@type'] + '/' + # flow['node']['@id'] + '/' + flow['name'] + '/') if self.request.status_code != 200: raise OpenDaylightError({'url':self.odl.url, 'http_code':self.request.status_code, 'msg':self.request.text}) #pylint: disable=R0921 class OpenDaylightNode(object): """A way to talk to the OpenDaylight Switch Manager REST API OpenDaylight.odl holds an OpenDaylight object containing details on how to communicate with the controller. OpenDaylightNode.request holds a Requests object for the REST session. Take a look at the Requests documentation for all of the methods available, but here are a few handy examples: OpenDaylightNode.request.status_code - returns the http code OpenDaylightNode.request.text - returns the response as text OpenDaylightNode.nodes holds a dictionary that corresponds to the 'nodes' element in the OpenDaylight REST API. OpenDaylightNode.node_connectors holds a dictionary that corresponds to the 'nodeConnectors' element in the OpenDaylight REST API. Note that we don't statically define what those fields are contained in the 'nodes' or 'nodeConnectors' elements here in this object. """ # Just a note that there are more functions available on # the controller that could be implemented, but it is not # clear at this time if that is useful def __init__(self, odl): """Mandatory argument: odl - an OpenDaylight object """ self.odl = odl self.__app = 'switch' self.nodes = None self.node_connectors = None self.request = None def get_nodes(self): """Get information about Nodes on the Controller and stuffs the result into the OpenDaylightNode.notes dictionary. """ if hasattr(self, 'request'): del self.request if hasattr(self, 'nodes'): del self.nodes self.odl.prepare(self.__app, '/nodes/') self.request = requests.get(url=self.odl.url, auth=self.odl.auth) if self.request.status_code == 200: self.nodes = self.request.json() if 'nodeProperties' in self.nodes: self.nodes = self.nodes.get('nodeProperties') else: raise OpenDaylightError({'url':self.odl.url, 'http_code':self.request.status_code, 'msg':self.request.text}) def get_node_connectors(self, node_id): """Get information about NodeConnectors on the Controller and stuffs the result into the OpenDaylightNode.node_connectors dictionary. Mandatory Arguments: node_id - returns flows just for that switch dpid """ if hasattr(self, 'request'): del self.request if hasattr(self, 'node_connectors'): del self.node_connectors self.odl.prepare(self.__app, '/node/' + 'OF/' + node_id + '/') self.request = requests.get(url=self.odl.url, auth=self.odl.auth) if self.request.status_code == 200: self.node_connectors = self.request.json() if 'nodeConnectorProperties' in self.node_connectors: self.node_connectors = self.node_connectors.get( 'nodeConnectorProperties') else: raise OpenDaylightError({'url':self.odl.url, 'http_code':self.request.status_code, 'msg':self.request.text}) def save(self): """Save current switch configurations The REST API documentation says: "Save the current switch configurations", but I am not sure what that actually means. If you think you do, then here you go. """ if hasattr(self, 'request'): del self.request self.odl.prepare(self.__app, '/switch-config/') self.request = requests.post(url=self.odl.url, auth=self.odl.auth) if self.request.status_code != 200: raise OpenDaylightError({'url':self.odl.url, 'http_code':self.request.status_code, 'msg':self.request.text}) def delete_node_property(self): """Delete a property of a Node on the Controller """ raise NotImplementedError("delete_node_property()") def add_node_property(self): """Add a property of a Node on the Controller """ raise NotImplementedError("add_node_property()") def delete_node_connector_property(self): """Delete a property of a Node on the Controller """ raise NotImplementedError("delete_node_connector_property()") def add_node_connector_property(self): """Add a property of a Node on the Controller """ raise NotImplementedError("add_node_connector_property()") class OpenDaylightError(Exception): """OpenDaylight Exception Class """ pass
try: import StringIO except: import io as StringIO import traceback from os.path import basename try: __setFalse = False except: import __builtin__ setattr(__builtin__, 'True', 1) setattr(__builtin__, 'False', 0) from _pydevd_bundle import pydevd_constants from _pydevd_bundle.pydevd_constants import dict_iter_items, dict_keys, xrange # Note: 300 is already a lot to see in the outline (after that the user should really use the shell to get things) # and this also means we'll pass less information to the client side (which makes debugging faster). MAX_ITEMS_TO_HANDLE = 300 TOO_LARGE_MSG = 'Too large to show contents. Max items to show: ' + str(MAX_ITEMS_TO_HANDLE) TOO_LARGE_ATTR = 'Unable to handle:' #======================================================================================================================= # UnableToResolveVariableException #======================================================================================================================= class UnableToResolveVariableException(Exception): pass #======================================================================================================================= # InspectStub #======================================================================================================================= class InspectStub: def isbuiltin(self, _args): return False def isroutine(self, object): return False try: import inspect except: inspect = InspectStub() try: import java.lang #@UnresolvedImport except: pass #types does not include a MethodWrapperType try: MethodWrapperType = type([].__str__) except: MethodWrapperType = None #======================================================================================================================= # AbstractResolver #======================================================================================================================= class AbstractResolver: ''' This class exists only for documentation purposes to explain how to create a resolver. Some examples on how to resolve things: - list: get_dictionary could return a dict with index->item and use the index to resolve it later - set: get_dictionary could return a dict with id(object)->object and reiterate in that array to resolve it later - arbitrary instance: get_dictionary could return dict with attr_name->attr and use getattr to resolve it later ''' def resolve(self, var, attribute): ''' In this method, we'll resolve some child item given the string representation of the item in the key representing the previously asked dictionary. @param var: this is the actual variable to be resolved. @param attribute: this is the string representation of a key previously returned in get_dictionary. ''' raise NotImplementedError def get_dictionary(self, var): ''' @param var: this is the variable that should have its children gotten. @return: a dictionary where each pair key, value should be shown to the user as children items in the variables view for the given var. ''' raise NotImplementedError #======================================================================================================================= # DefaultResolver #======================================================================================================================= class DefaultResolver: ''' DefaultResolver is the class that'll actually resolve how to show some variable. ''' use_value_repr_instead_of_str = False def resolve(self, var, attribute): return getattr(var, attribute) def get_dictionary(self, var, names=None): if MethodWrapperType: return self._getPyDictionary(var, names) else: return self._getJyDictionary(var) def _getJyDictionary(self, obj): ret = {} found = java.util.HashMap() original = obj if hasattr(obj, '__class__') and obj.__class__ == java.lang.Class: #get info about superclasses classes = [] classes.append(obj) c = obj.getSuperclass() while c != None: classes.append(c) c = c.getSuperclass() #get info about interfaces interfs = [] for obj in classes: interfs.extend(obj.getInterfaces()) classes.extend(interfs) #now is the time when we actually get info on the declared methods and fields for obj in classes: declaredMethods = obj.getDeclaredMethods() declaredFields = obj.getDeclaredFields() for i in xrange(len(declaredMethods)): name = declaredMethods[i].getName() ret[name] = declaredMethods[i].toString() found.put(name, 1) for i in xrange(len(declaredFields)): name = declaredFields[i].getName() found.put(name, 1) #if declaredFields[i].isAccessible(): declaredFields[i].setAccessible(True) #ret[name] = declaredFields[i].get( declaredFields[i] ) try: ret[name] = declaredFields[i].get(original) except: ret[name] = declaredFields[i].toString() #this simple dir does not always get all the info, that's why we have the part before #(e.g.: if we do a dir on String, some methods that are from other interfaces such as #charAt don't appear) try: d = dir(original) for name in d: if found.get(name) is not 1: ret[name] = getattr(original, name) except: #sometimes we're unable to do a dir pass return ret def get_names(self, var): names = dir(var) if not names and hasattr(var, '__members__'): names = var.__members__ return names def _getPyDictionary(self, var, names=None): filterPrivate = False filterSpecial = True filterFunction = True filterBuiltIn = True if not names: names = self.get_names(var) d = {} #Be aware that the order in which the filters are applied attempts to #optimize the operation by removing as many items as possible in the #first filters, leaving fewer items for later filters if filterBuiltIn or filterFunction: for n in names: if filterSpecial: if n.startswith('__') and n.endswith('__'): continue if filterPrivate: if n.startswith('_') or n.endswith('__'): continue try: attr = getattr(var, n) #filter builtins? if filterBuiltIn: if inspect.isbuiltin(attr): continue #filter functions? if filterFunction: if inspect.isroutine(attr) or isinstance(attr, MethodWrapperType): continue except: #if some error occurs getting it, let's put it to the user. strIO = StringIO.StringIO() traceback.print_exc(file=strIO) attr = strIO.getvalue() d[ n ] = attr return d #======================================================================================================================= # DictResolver #======================================================================================================================= class DictResolver: use_value_repr_instead_of_str = False def resolve(self, dict, key): if key in ('__len__', TOO_LARGE_ATTR): return None if '(' not in key: #we have to treat that because the dict resolver is also used to directly resolve the global and local #scopes (which already have the items directly) try: return dict[key] except: return getattr(dict, key) #ok, we have to iterate over the items to find the one that matches the id, because that's the only way #to actually find the reference from the string we have before. expected_id = int(key.split('(')[-1][:-1]) for key, val in dict_iter_items(dict): if id(key) == expected_id: return val raise UnableToResolveVariableException() def key_to_str(self, key): if isinstance(key, str): return '%r' % key else: if not pydevd_constants.IS_PY3K: if isinstance(key, unicode): return "u'%s'" % key return key def get_dictionary(self, dict): ret = {} i = 0 for key, val in dict_iter_items(dict): i += 1 #we need to add the id because otherwise we cannot find the real object to get its contents later on. key = '%s (%s)' % (self.key_to_str(key), id(key)) ret[key] = val if i > MAX_ITEMS_TO_HANDLE: ret[TOO_LARGE_ATTR] = TOO_LARGE_MSG break ret['__len__'] = len(dict) # in case if the class extends built-in type and has some additional fields additional_fields = defaultResolver.get_dictionary(dict) ret.update(additional_fields) return ret #======================================================================================================================= # TupleResolver #======================================================================================================================= class TupleResolver: #to enumerate tuples and lists use_value_repr_instead_of_str = False def resolve(self, var, attribute): ''' @param var: that's the original attribute @param attribute: that's the key passed in the dict (as a string) ''' if attribute in ('__len__', TOO_LARGE_ATTR): return None try: return var[int(attribute)] except: return getattr(var, attribute) def get_dictionary(self, var): l = len(var) d = {} format_str = '%0' + str(int(len(str(l)))) + 'd' i = 0 for item in var: d[format_str % i] = item i += 1 if i > MAX_ITEMS_TO_HANDLE: d[TOO_LARGE_ATTR] = TOO_LARGE_MSG break d['__len__'] = len(var) # in case if the class extends built-in type and has some additional fields additional_fields = defaultResolver.get_dictionary(var) d.update(additional_fields) return d #======================================================================================================================= # SetResolver #======================================================================================================================= class SetResolver: ''' Resolves a set as dict id(object)->object ''' use_value_repr_instead_of_str = False def resolve(self, var, attribute): if attribute in ('__len__', TOO_LARGE_ATTR): return None try: attribute = int(attribute) except: return getattr(var, attribute) for v in var: if id(v) == attribute: return v raise UnableToResolveVariableException('Unable to resolve %s in %s' % (attribute, var)) def get_dictionary(self, var): d = {} i = 0 for item in var: i+= 1 d[id(item)] = item if i > MAX_ITEMS_TO_HANDLE: d[TOO_LARGE_ATTR] = TOO_LARGE_MSG break d['__len__'] = len(var) # in case if the class extends built-in type and has some additional fields additional_fields = defaultResolver.get_dictionary(var) d.update(additional_fields) return d #======================================================================================================================= # InstanceResolver #======================================================================================================================= class InstanceResolver: use_value_repr_instead_of_str = False def resolve(self, var, attribute): field = var.__class__.getDeclaredField(attribute) field.setAccessible(True) return field.get(var) def get_dictionary(self, obj): ret = {} declaredFields = obj.__class__.getDeclaredFields() for i in xrange(len(declaredFields)): name = declaredFields[i].getName() try: declaredFields[i].setAccessible(True) ret[name] = declaredFields[i].get(obj) except: traceback.print_exc() return ret #======================================================================================================================= # JyArrayResolver #======================================================================================================================= class JyArrayResolver: ''' This resolves a regular Object[] array from java ''' use_value_repr_instead_of_str = False def resolve(self, var, attribute): if attribute == '__len__': return None return var[int(attribute)] def get_dictionary(self, obj): ret = {} for i in xrange(len(obj)): ret[ i ] = obj[i] ret['__len__'] = len(obj) return ret #======================================================================================================================= # NdArrayResolver #======================================================================================================================= class NdArrayResolver: ''' This resolves a numpy ndarray returning some metadata about the NDArray ''' use_value_repr_instead_of_str = False def is_numeric(self, obj): if not hasattr(obj, 'dtype'): return False return obj.dtype.kind in 'biufc' def resolve(self, obj, attribute): if attribute == '__internals__': return defaultResolver.get_dictionary(obj) if attribute == 'min': if self.is_numeric(obj): return obj.min() else: return None if attribute == 'max': if self.is_numeric(obj): return obj.max() else: return None if attribute == 'shape': return obj.shape if attribute == 'dtype': return obj.dtype if attribute == 'size': return obj.size if attribute.startswith('['): container = NdArrayItemsContainer() i = 0 format_str = '%0' + str(int(len(str(len(obj))))) + 'd' for item in obj: setattr(container, format_str % i, item) i += 1 if i > MAX_ITEMS_TO_HANDLE: setattr(container, TOO_LARGE_ATTR, TOO_LARGE_MSG) break return container return None def get_dictionary(self, obj): ret = dict() ret['__internals__'] = defaultResolver.get_dictionary(obj) if obj.size > 1024 * 1024: ret['min'] = 'ndarray too big, calculating min would slow down debugging' ret['max'] = 'ndarray too big, calculating max would slow down debugging' else: if self.is_numeric(obj): ret['min'] = obj.min() ret['max'] = obj.max() else: ret['min'] = 'not a numeric object' ret['max'] = 'not a numeric object' ret['shape'] = obj.shape ret['dtype'] = obj.dtype ret['size'] = obj.size ret['[0:%s] ' % (len(obj))] = list(obj[0:MAX_ITEMS_TO_HANDLE]) return ret class NdArrayItemsContainer: pass #======================================================================================================================= # MultiValueDictResolver #======================================================================================================================= class MultiValueDictResolver(DictResolver): use_value_repr_instead_of_str = False def resolve(self, dict, key): if key in ('__len__', TOO_LARGE_ATTR): return None #ok, we have to iterate over the items to find the one that matches the id, because that's the only way #to actually find the reference from the string we have before. expected_id = int(key.split('(')[-1][:-1]) for key in dict_keys(dict): val = dict.getlist(key) if id(key) == expected_id: return val raise UnableToResolveVariableException() #======================================================================================================================= # DjangoFormResolver #======================================================================================================================= class DjangoFormResolver(DefaultResolver): has_errors_attr = False use_value_repr_instead_of_str = True def get_names(self, var): names = dir(var) if not names and hasattr(var, '__members__'): names = var.__members__ if "errors" in names: self.has_errors_attr = True names.remove("errors") return names def get_dictionary(self, var, names=None): # Do not call self.errors because it is property and has side effects d = defaultResolver.get_dictionary(var, self.get_names(var)) if self.has_errors_attr: try: errors_attr = getattr(var, "_errors") except: errors_attr = None d["errors"] = errors_attr return d #======================================================================================================================= # DequeResolver #======================================================================================================================= class DequeResolver(TupleResolver): use_value_repr_instead_of_str = False def get_dictionary(self, var): d = TupleResolver.get_dictionary(self, var) d['maxlen'] = getattr(var, 'maxlen', None) return d #======================================================================================================================= # FrameResolver #======================================================================================================================= class FrameResolver: ''' This resolves a frame. ''' use_value_repr_instead_of_str = False def resolve(self, obj, attribute): if attribute == '__internals__': return defaultResolver.get_dictionary(obj) if attribute == 'stack': return self.get_frame_stack(obj) if attribute == 'f_locals': return obj.f_locals return None def get_dictionary(self, obj): ret = dict() ret['__internals__'] = defaultResolver.get_dictionary(obj) ret['stack'] = self.get_frame_stack(obj) ret['f_locals'] = obj.f_locals return ret def get_frame_stack(self, frame): ret = [] if frame is not None: ret.append(self.get_frame_name(frame)) while frame.f_back: frame = frame.f_back ret.append(self.get_frame_name(frame)) return ret def get_frame_name(self, frame): if frame is None: return 'None' try: name = basename(frame.f_code.co_filename) return 'frame: %s [%s:%s] id:%s' % (frame.f_code.co_name, name, frame.f_lineno, id(frame)) except: return 'frame object' defaultResolver = DefaultResolver() dictResolver = DictResolver() tupleResolver = TupleResolver() instanceResolver = InstanceResolver() jyArrayResolver = JyArrayResolver() setResolver = SetResolver() ndarrayResolver = NdArrayResolver() multiValueDictResolver = MultiValueDictResolver() djangoFormResolver = DjangoFormResolver() dequeResolver = DequeResolver() frameResolver = FrameResolver()
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * class TabStopSimpleReplace_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${0:End} ${1:Beginning}") keys = "hallo" + EX + "na" + JF + "Du Nase" wanted = "hallo Du Nase na" class TabStopSimpleReplaceZeroLengthTabstops_ExpectCorrectResult(_VimTest): snippets = ("test", r":latex:\`$1\`$0") keys = "test" + EX + "Hello" + JF + "World" wanted = ":latex:`Hello`World" class TabStopSimpleReplaceReversed_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${1:End} ${0:Beginning}") keys = "hallo" + EX + "na" + JF + "Du Nase" wanted = "hallo na Du Nase" class TabStopSimpleReplaceSurrounded_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${0:End} a small feed") keys = "hallo" + EX + "Nase" wanted = "hallo Nase a small feed" class TabStopSimpleReplaceSurrounded1_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $0 a small feed") keys = "hallo" + EX + "Nase" wanted = "hallo Nase a small feed" class TabStop_Exit_ExpectCorrectResult(_VimTest): snippets = ("echo", "$0 run") keys = "echo" + EX + "test" wanted = "test run" class TabStopNoReplace_ExpectCorrectResult(_VimTest): snippets = ("echo", "echo ${1:Hallo}") keys = "echo" + EX wanted = "echo Hallo" class TabStop_EscapingCharsBackticks(_VimTest): snippets = ("test", r"snip \` literal") keys = "test" + EX wanted = "snip ` literal" class TabStop_EscapingCharsDollars(_VimTest): snippets = ("test", r"snip \$0 $$0 end") keys = "test" + EX + "hi" wanted = "snip $0 $hi end" class TabStop_EscapingCharsDollars1(_VimTest): snippets = ("test", r"a\${1:literal}") keys = "test" + EX wanted = "a${1:literal}" class TabStop_EscapingCharsDollars_BeginningOfLine(_VimTest): snippets = ("test", "\n\\${1:literal}") keys = "test" + EX wanted = "\n${1:literal}" class TabStop_EscapingCharsDollars_BeginningOfDefinitionText(_VimTest): snippets = ("test", "\\${1:literal}") keys = "test" + EX wanted = "${1:literal}" class TabStop_EscapingChars_Backslash(_VimTest): snippets = ("test", r"This \ is a backslash!") keys = "test" + EX wanted = "This \\ is a backslash!" class TabStop_EscapingChars_Backslash2(_VimTest): snippets = ("test", r"This is a backslash \\ done") keys = "test" + EX wanted = r"This is a backslash \ done" class TabStop_EscapingChars_Backslash3(_VimTest): snippets = ("test", r"These are two backslashes \\\\ done") keys = "test" + EX wanted = r"These are two backslashes \\ done" class TabStop_EscapingChars_Backslash4(_VimTest): # Test for bug 746446 snippets = ("test", r"\\$1{$2}") keys = "test" + EX + "hello" + JF + "world" wanted = r"\hello{world}" class TabStop_EscapingChars_RealLife(_VimTest): snippets = ("test", r"usage: \`basename \$0\` ${1:args}") keys = "test" + EX + "[ -u -v -d ]" wanted = "usage: `basename $0` [ -u -v -d ]" class TabStopEscapingWhenSelected_ECR(_VimTest): snippets = ("test", "snip ${1:default}") keys = "test" + EX + ESC + "0ihi" wanted = "hisnip default" class TabStopEscapingWhenSelectedSingleCharTS_ECR(_VimTest): snippets = ("test", "snip ${1:i}") keys = "test" + EX + ESC + "0ihi" wanted = "hisnip i" class TabStopEscapingWhenSelectedNoCharTS_ECR(_VimTest): snippets = ("test", "snip $1") keys = "test" + EX + ESC + "0ihi" wanted = "hisnip " class TabStopWithOneChar_ExpectCorrectResult(_VimTest): snippets = ("hallo", "nothing ${1:i} hups") keys = "hallo" + EX + "ship" wanted = "nothing ship hups" class TabStopTestJumping_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${2:End} mitte ${1:Beginning}") keys = "hallo" + EX + JF + "Test" + JF + "Hi" wanted = "hallo Test mitte BeginningHi" class TabStopTestJumping2_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $2 $1") keys = "hallo" + EX + JF + "Test" + JF + "Hi" wanted = "hallo Test Hi" class TabStopTestJumpingRLExampleWithZeroTab_ExpectCorrectResult(_VimTest): snippets = ("test", "each_byte { |${1:byte}| $0 }") keys = "test" + EX + JF + "Blah" wanted = "each_byte { |byte| Blah }" class TabStopTestJumpingDontJumpToEndIfThereIsTabZero_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $0 $1") keys = "hallo" + EX + "Test" + JF + "Hi" + JF + JF + "du" wanted = "hallo Hi" + 2*JF + "du Test" class TabStopTestBackwardJumping_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo ${2:End} mitte${1:Beginning}") keys = "hallo" + EX + "Somelengthy Text" + JF + "Hi" + JB + \ "Lets replace it again" + JF + "Blah" + JF + JB*2 + JF wanted = "hallo Blah mitteLets replace it again" + JB*2 + JF class TabStopTestBackwardJumping2_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $2 $1") keys = "hallo" + EX + "Somelengthy Text" + JF + "Hi" + JB + \ "Lets replace it again" + JF + "Blah" + JF + JB*2 + JF wanted = "hallo Blah Lets replace it again" + JB*2 + JF class TabStopTestMultilineExpand_ExpectCorrectResult(_VimTest): snippets = ("hallo", "hallo $0\nnice $1 work\n$3 $2\nSeem to work") keys ="test hallo World" + ESC + "02f i" + EX + "world" + JF + "try" + \ JF + "test" + JF + "one more" + JF wanted = "test hallo one more" + JF + "\nnice world work\n" \ "test try\nSeem to work World" class TabStop_TSInDefaultTextRLExample_OverwriteNone_ECR(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX wanted = """<div id="some_id">\n \n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteFirst_NoJumpBack(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX + " blah" + JF + "Hallo" wanted = """<div blah>\n Hallo\n</div>""" class TabStop_TSInDefaultTextRLExample_DeleteFirst(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX + BS + JF + "Hallo" wanted = """<div>\n Hallo\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteFirstJumpBack(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $3 $0\n</div>""") keys = "test" + EX + "Hi" + JF + "Hallo" + JB + "SomethingElse" + JF + \ "Nupl" + JF + "Nox" wanted = """<divSomethingElse>\n Nupl Nox\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteSecond(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $0\n</div>""") keys = "test" + EX + JF + "no" + JF + "End" wanted = """<div id="no">\n End\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteSecondTabBack(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $3 $0\n</div>""") keys = "test" + EX + JF + "no" + JF + "End" + JB + "yes" + JF + "Begin" \ + JF + "Hi" wanted = """<div id="yes">\n Begin Hi\n</div>""" class TabStop_TSInDefaultTextRLExample_OverwriteSecondTabBackTwice(_VimTest): snippets = ("test", """<div${1: id="${2:some_id}"}>\n $3 $0\n</div>""") keys = "test" + EX + JF + "no" + JF + "End" + JB + "yes" + JB + \ " allaway" + JF + "Third" + JF + "Last" wanted = """<div allaway>\n Third Last\n</div>""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecond(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "ups" + JF + "End" wanted = """haupsblEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteFirst(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + "ups" + JF + "End" wanted = """hupslEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecondJumpBackOverwrite(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "longertext" + JB + "overwrite" + JF + "End" wanted = """hoverwritelEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecondJumpBackAndForward0(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "longertext" + JB + JF + "overwrite" + JF + "End" wanted = """haoverwriteblEnd""" class TabStop_TSInDefaultText_ZeroLengthNested_OverwriteSecondJumpBackAndForward1(_VimTest): snippets = ("test", """h${1:a$2b}l""") keys = "test" + EX + JF + "longertext" + JB + JF + JF + "End" wanted = """halongertextblEnd""" class TabStop_TSInDefaultNested_OverwriteOneJumpBackToOther(_VimTest): snippets = ("test", "hi ${1:this ${2:second ${3:third}}} $4") keys = "test" + EX + JF + "Hallo" + JF + "Ende" wanted = "hi this Hallo Ende" class TabStop_TSInDefaultNested_OverwriteOneJumpToThird(_VimTest): snippets = ("test", "hi ${1:this ${2:second ${3:third}}} $4") keys = "test" + EX + JF + JF + "Hallo" + JF + "Ende" wanted = "hi this second Hallo Ende" class TabStop_TSInDefaultNested_OverwriteOneJumpAround(_VimTest): snippets = ("test", "hi ${1:this ${2:second ${3:third}}} $4") keys = "test" + EX + JF + JF + "Hallo" + JB+JB + "Blah" + JF + "Ende" wanted = "hi Blah Ende" class TabStop_TSInDefault_MirrorsOutside_DoNothing(_VimTest): snippets = ("test", "hi ${1:this ${2:second}} $2") keys = "test" + EX wanted = "hi this second second" class TabStop_TSInDefault_MirrorsOutside_OverwriteSecond(_VimTest): snippets = ("test", "hi ${1:this ${2:second}} $2") keys = "test" + EX + JF + "Hallo" wanted = "hi this Hallo Hallo" class TabStop_TSInDefault_MirrorsOutside_Overwrite0(_VimTest): snippets = ("test", "hi ${1:this ${2:second}} $2") keys = "test" + EX + "Hallo" wanted = "hi Hallo " class TabStop_TSInDefault_MirrorsOutside_Overwrite1(_VimTest): snippets = ("test", "$1: ${1:'${2:second}'} $2") keys = "test" + EX + "Hallo" wanted = "Hallo: Hallo " class TabStop_TSInDefault_MirrorsOutside_OverwriteSecond1(_VimTest): snippets = ("test", "$1: ${1:'${2:second}'} $2") keys = "test" + EX + JF + "Hallo" wanted = "'Hallo': 'Hallo' Hallo" class TabStop_TSInDefault_MirrorsOutside_OverwriteFirstSwitchNumbers(_VimTest): snippets = ("test", "$2: ${2:'${1:second}'} $1") keys = "test" + EX + "Hallo" wanted = "'Hallo': 'Hallo' Hallo" class TabStop_TSInDefault_MirrorsOutside_OverwriteFirst_RLExample(_VimTest): snippets = ("test", """`!p snip.rv = t[1].split('/')[-1].lower().strip("'")` = require(${1:'${2:sys}'})""") keys = "test" + EX + "WORLD" + JF + "End" wanted = "world = require(WORLD)End" class TabStop_TSInDefault_MirrorsOutside_OverwriteSecond_RLExample(_VimTest): snippets = ("test", """`!p snip.rv = t[1].split('/')[-1].lower().strip("'")` = require(${1:'${2:sys}'})""") keys = "test" + EX + JF + "WORLD" + JF + "End" wanted = "world = require('WORLD')End" class TabStop_Multiline_Leave(_VimTest): snippets = ("test", "hi ${1:first line\nsecond line} world" ) keys = "test" + EX wanted = "hi first line\nsecond line world" class TabStop_Multiline_Overwrite(_VimTest): snippets = ("test", "hi ${1:first line\nsecond line} world" ) keys = "test" + EX + "Nothing" wanted = "hi Nothing world" class TabStop_Multiline_MirrorInFront_Leave(_VimTest): snippets = ("test", "hi $1 ${1:first line\nsecond line} world" ) keys = "test" + EX wanted = "hi first line\nsecond line first line\nsecond line world" class TabStop_Multiline_MirrorInFront_Overwrite(_VimTest): snippets = ("test", "hi $1 ${1:first line\nsecond line} world" ) keys = "test" + EX + "Nothing" wanted = "hi Nothing Nothing world" class TabStop_Multiline_DelFirstOverwriteSecond_Overwrite(_VimTest): snippets = ("test", "hi $1 $2 ${1:first line\nsecond line} ${2:Hi} world" ) keys = "test" + EX + BS + JF + "Nothing" wanted = "hi Nothing Nothing world" class TabStopNavigatingInInsertModeSimple_ExpectCorrectResult(_VimTest): snippets = ("hallo", "Hallo ${1:WELT} ups") keys = "hallo" + EX + "haselnut" + 2*ARR_L + "hips" + JF + "end" wanted = "Hallo haselnhipsut upsend" class TabStop_CROnlyOnSelectedNear(_VimTest): snippets = ("test", "t$1t${2: }t{\n\t$0\n}") keys = "test" + EX + JF + "\n" + JF + "t" wanted = "tt\nt{\n\tt\n}"
from __future__ import print_function from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # Standard imports from future import standard_library standard_library.install_aliases() from builtins import str from builtins import * from past.utils import old_div import json from random import randrange from emission.net.api.bottle import route, post, get, run, template, static_file, request, app, HTTPError, abort, BaseRequest, JSONPlugin, response import emission.net.api.bottle as bt # To support dynamic loading of client-specific libraries import sys import os import logging import logging.config from datetime import datetime import time import arrow from uuid import UUID # So that we can set the socket timeout import socket # For decoding JWTs using the google decode URL import urllib.request, urllib.parse, urllib.error import requests import traceback import xmltodict import urllib.request, urllib.error, urllib.parse import bson.json_util # Our imports import emission.net.api.visualize as visualize import emission.net.api.stats as stats import emission.net.api.usercache as usercache import emission.net.api.timeline as timeline import emission.net.api.metrics as metrics import emission.net.api.pipeline as pipeline import emission.net.auth.auth as enaa # import emission.net.ext_service.moves.register as auth import emission.net.ext_service.habitica.proxy as habitproxy from emission.core.wrapper.client import Client from emission.core.wrapper.user import User from emission.core.get_database import get_uuid_db, get_mode_db import emission.core.wrapper.motionactivity as ecwm import emission.storage.timeseries.timequery as estt import emission.storage.timeseries.tcquery as esttc import emission.storage.timeseries.aggregate_timeseries as estag import emission.storage.timeseries.cache_series as esdc import emission.core.timer as ect import emission.core.get_database as edb try: config_file = open('conf/net/api/webserver.conf') except: logging.debug("webserver not configured, falling back to sample, default configuration") config_file = open('conf/net/api/webserver.conf.sample') config_data = json.load(config_file) static_path = config_data["paths"]["static_path"] python_path = config_data["paths"]["python_path"] server_host = config_data["server"]["host"] server_port = config_data["server"]["port"] socket_timeout = config_data["server"]["timeout"] log_base_dir = config_data["paths"]["log_base_dir"] auth_method = config_data["server"]["auth"] BaseRequest.MEMFILE_MAX = 1024 * 1024 * 1024 # Allow the request size to be 1G # to accomodate large section sizes print("Finished configuring logging for %s" % logging.getLogger()) app = app() # On MacOS, the current working directory is always in the python path However, # on ubuntu, it looks like the script directory (api in our case) is in the # python path, but the pwd is not. This means that "main" is not seen even if # we run from the CFC_WebApp directory. Let's make sure to manually add it to # the python path so that we can keep our separation between the main code and # the webapp layer #Simple path that serves up a static landing page with javascript in it @route('/') def index(): return static_file("index.html", static_path) # Bunch of static pages that constitute our website # Should we have gone for something like django instead after all? # If this gets to be too much, we should definitely consider that @route("/docs/<filename>") def docs(filename): if filename != "privacy.html" and filename != "support.html" and filename != "about.html" and filename != "consent.html" and filename != "approval_letter.pdf": logging.error("Request for unknown filename "% filename) logging.error("Request for unknown filename "% filename) return HTTPError(404, "Don't try to hack me, you evil spammer") else: return static_file(filename, "%s/%s" % (static_path, "docs")) @route("/<filename>") def docs(filename): if filename != "privacy" and filename != "support" and filename != "about" and filename != "consent": return HTTPError(404, "Don't try to hack me, you evil spammer") else: return static_file("%s.html" % filename, "%s/%s" % (static_path, "docs")) # Serve up the components of the webapp - library files, our javascript and css # files, and HTML templates, properly @route('/css/<filepath:path>') def server_css(filepath): logging.debug("static filepath = %s" % filepath) return static_file(filepath, "%s/%s" % (static_path, "css")) @route('/img/<filepath:path>') def server_img(filepath): logging.debug("static filepath = %s" % filepath) return static_file(filepath, "%s/%s" % (static_path, "img")) @route('/js/<filepath:path>') def server_js(filepath): logging.debug("static filepath = %s" % filepath) return static_file(filepath, "%s/%s" % (static_path, "js")) @route('/lib/<filepath:path>') def server_lib(filepath): logging.debug("static filepath = %s" % filepath) return static_file(filepath, "%s/%s" % (static_path, "lib")) @route('/templates/<filepath:path>') def server_templates(filepath): logging.debug("static filepath = %s" % filepath) return static_file(filepath, "%s/%s" % (static_path, "templates")) @post("/result/heatmap/pop.route/<time_type>") def getPopRoute(time_type): if 'user' in request.json: user_uuid = getUUID(request) else: user_uuid = None if 'from_local_date' in request.json and 'to_local_date' in request.json: start_time = request.json['from_local_date'] end_time = request.json['to_local_date'] else: start_time = request.json['start_time'] end_time = request.json['end_time'] modes = request.json['modes'] region = request.json['sel_region'] logging.debug("Filtering values for user %s, range %s -> %s, region %s" % (user_uuid, start_time, end_time, region)) time_type_map = { 'timestamp': visualize.range_mode_heatmap_timestamp, 'local_date': visualize.range_mode_heatmap_local_date } viz_fn = time_type_map[time_type] retVal = viz_fn(user_uuid, modes, start_time, end_time, region) return retVal @post("/result/heatmap/incidents/<time_type>") def getStressMap(time_type): if 'user' in request.json: user_uuid = getUUID(request) else: user_uuid = None # modes = request.json['modes'] # hardcode modes to None because we currently don't store # mode information along with the incidents # we need to have some kind of cleaned incident that: # has a mode # maybe has a count generated from clustering.... # but then what about times? modes = None if 'from_local_date' in request.json and 'to_local_date' in request.json: start_time = request.json['from_local_date'] end_time = request.json['to_local_date'] else: start_time = request.json['start_time'] end_time = request.json['end_time'] region = request.json['sel_region'] logging.debug("Filtering values for %s, range %s -> %s, region %s" % (user_uuid, start_time, end_time, region)) time_type_map = { 'timestamp': visualize.incident_heatmap_timestamp, 'local_date': visualize.incident_heatmap_local_date } viz_fn = time_type_map[time_type] retVal = viz_fn(user_uuid, modes, start_time, end_time, region) return retVal @post("/pipeline/get_complete_ts") def getPipelineState(): user_uuid = getUUID(request) return {"complete_ts": pipeline.get_complete_ts(user_uuid)} @post("/datastreams/find_entries/<time_type>") def getTimeseriesEntries(time_type): if 'user' not in request.json: abort(401, "only a user can read his/her data") user_uuid = getUUID(request) key_list = request.json['key_list'] if 'from_local_date' in request.json and 'to_local_date' in request.json: start_time = request.json['from_local_date'] end_time = request.json['to_local_date'] time_query = esttc.TimeComponentQuery("metadata.write_ts", start_time, end_time) else: start_time = request.json['start_time'] end_time = request.json['end_time'] time_query = estt.TimeQuery("metadata.write_ts", start_time, end_time) # Note that queries from usercache are limited to 100,000 entries # and entries from timeseries are limited to 250,000, so we will # return at most 350,000 entries. So this means that we don't need # additional filtering, but this should be documented in # the API data_list = esdc.find_entries(user_uuid, key_list, time_query) return {'phone_data': data_list} @post('/usercache/get') def getFromCache(): logging.debug("Called userCache.get") user_uuid=getUUID(request) logging.debug("user_uuid %s" % user_uuid) to_phone = usercache.sync_server_to_phone(user_uuid) return {'server_to_phone': to_phone} @post('/usercache/put') def putIntoCache(): logging.debug("Called userCache.put") user_uuid=getUUID(request) logging.debug("user_uuid %s" % user_uuid) from_phone = request.json['phone_to_server'] return usercache.sync_phone_to_server(user_uuid, from_phone) @post('/timeline/getTrips/<day>') def getTrips(day): logging.debug("Called timeline.getTrips/%s" % day) user_uuid=getUUID(request) force_refresh = request.query.get('refresh', False) logging.debug("user_uuid %s" % user_uuid) ret_geojson = timeline.get_trips_for_day(user_uuid, day, force_refresh) logging.debug("type(ret_geojson) = %s" % type(ret_geojson)) ret_dict = {"timeline": ret_geojson} logging.debug("type(ret_dict) = %s" % type(ret_dict)) return ret_dict @post('/profile/create') def createUserProfile(): try: logging.debug("Called createUserProfile") userEmail = enaa._getEmail(request, auth_method) logging.debug("userEmail = %s" % userEmail) user = User.register(userEmail) logging.debug("Looked up user = %s" % user) logging.debug("Returning result %s" % {'uuid': str(user.uuid)}) return {'uuid': str(user.uuid)} except ValueError as e: traceback.print_exc() abort(403, e.message) @post('/profile/update') def updateUserProfile(): logging.debug("Called updateUserProfile") user_uuid = getUUID(request) user = User.fromUUID(user_uuid) new_fields = request.json['update_doc'] return user.update(new_fields) @post('/profile/get') def getUserProfile(): logging.debug("Called getUserProfile") user_uuid = getUUID(request) user = User.fromUUID(user_uuid) return user.getProfile() @post('/result/metrics/<time_type>') def summarize_metrics(time_type): if 'user' in request.json: user_uuid = getUUID(request) else: user_uuid = None start_time = request.json['start_time'] end_time = request.json['end_time'] freq_name = request.json['freq'] old_style = False if 'metric' in request.json: old_style = True metric_list = [request.json['metric']] else: metric_list = request.json['metric_list'] logging.debug("metric_list = %s" % metric_list) if 'is_return_aggregate' in request.json: is_return_aggregate = request.json['is_return_aggregate'] else: old_style = True is_return_aggregate = True time_type_map = { 'timestamp': metrics.summarize_by_timestamp, 'local_date': metrics.summarize_by_local_date } metric_fn = time_type_map[time_type] ret_val = metric_fn(user_uuid, start_time, end_time, freq_name, metric_list, is_return_aggregate) # logging.debug("ret_val = %s" % bson.json_util.dumps(ret_val)) if old_style: logging.debug("old_style metrics found, returning array of entries instead of array of arrays") assert(len(metric_list) == 1) if 'user_metrics' in ret_val: ret_val['user_metrics'] = ret_val['user_metrics'][0] ret_val['aggregate_metrics'] = ret_val['aggregate_metrics'][0] return ret_val @post('/join.group/<group_id>') def habiticaJoinGroup(group_id): if 'user' in request.json: user_uuid = getUUID(request) else: user_uuid = None inviter_id = request.json['inviter'] logging.debug("%s about to join party %s after invite from %s" % (user_uuid, group_id, inviter_id)) try: ret_val = habitproxy.setup_party(user_uuid, group_id, inviter_id) logging.debug("ret_val = %s after joining group" % bson.json_util.dumps(ret_val)) return {'result': ret_val} except RuntimeError as e: logging.info("Aborting call with message %s" % e.message) abort(400, e.message) # Small utilities to make client software easier START # Redirect to custom URL. $%$%$$ gmail @get('/redirect/<route>') def getCustomURL(route): print(route) print(urllib.parse.urlencode(request.query)) logging.debug("route = %s, query params = %s" % (route, request.query)) if route == "join": redirected_url = "/#/setup?%s" % (urllib.parse.urlencode(request.query)) else: redirected_url = 'emission://%s?%s' % (route, urllib.parse.urlencode(request.query)) response.status = 303 response.set_header('Location', redirected_url) # response.set_header('Location', 'mailto://%s@%s' % (route, urllib.urlencode(request.query))) logging.debug("Redirecting to URL %s" % redirected_url) print("Redirecting to URL %s" % redirected_url) return {'redirect': 'success'} # proxy used to request and process XML from an external API, then convert it to JSON # original URL should be encoded in UTF-8 @get("/asJSON/<originalXMLWebserviceURL>") def xmlProxy(originalXMLWebserviceURL): decodedURL = urllib.parse.unquote(originalXMLWebserviceURL) f = urllib.request.urlopen(decodedURL) xml = f.read() parsedXML = xmltodict.parse(xml) return json.dumps(parsedXML) # Small utilities to make client software easier END @post('/habiticaRegister') def habiticaRegister(): logging.debug("habitica registration request %s from user = %s" % (request.json, request)) user_uuid = getUUID(request) assert(user_uuid is not None) username = request.json['regConfig']['username'] # TODO: Move this logic into register since there is no point in # regenerating the password if we already have the user autogen_id = requests.get("http://www.dinopass.com/password/simple").text logging.debug("generated id %s through dinopass" % autogen_id) autogen_email = "%s@save.world" % autogen_id autogen_password = autogen_id return habitproxy.habiticaRegister(username, autogen_email, autogen_password, user_uuid) @post('/habiticaProxy') def habiticaProxy(): logging.debug("habitica registration request %s" % (request)) user_uuid = getUUID(request) assert(user_uuid is not None) method = request.json['callOpts']['method'] method_url = request.json['callOpts']['method_url'] method_args = request.json['callOpts']['method_args'] return habitproxy.habiticaProxy(user_uuid, method, method_url, method_args) # Data source integration END @app.hook('before_request') def before_request(): print("START %s %s %s" % (datetime.now(), request.method, request.path)) request.params.start_ts = time.time() request.params.timer = ect.Timer() request.params.timer.__enter__() logging.debug("START %s %s" % (request.method, request.path)) @app.hook('after_request') def after_request(): msTimeNow = time.time() request.params.timer.__exit__() duration = msTimeNow - request.params.start_ts new_duration = request.params.timer.elapsed if round(old_div((duration - new_duration), new_duration) > 100) > 0: logging.error("old style duration %s != timer based duration %s" % (duration, new_duration)) stats.store_server_api_error(request.params.user_uuid, "MISMATCH_%s_%s" % (request.method, request.path), msTimeNow, duration - new_duration) print("END %s %s %s %s %s " % (datetime.now(), request.method, request.path, request.params.user_uuid, duration)) logging.debug("END %s %s %s %s " % (request.method, request.path, request.params.user_uuid, duration)) # Keep track of the time and duration for each call stats.store_server_api_time(request.params.user_uuid, "%s_%s" % (request.method, request.path), msTimeNow, duration) stats.store_server_api_time(request.params.user_uuid, "%s_%s_cputime" % (request.method, request.path), msTimeNow, new_duration) # Auth helpers BEGIN # This should only be used by createUserProfile since we may not have a UUID # yet. All others should use the UUID. def getUUID(request, inHeader=False): try: retUUID = enaa.getUUID(request, auth_method, inHeader) logging.debug("retUUID = %s" % retUUID) if retUUID is None: raise HTTPError(403, "token is valid, but no account found for user") return retUUID except ValueError as e: traceback.print_exc() abort(401, e.message) # Auth helpers END if __name__ == '__main__': try: webserver_log_config = json.load(open("conf/log/webserver.conf", "r")) except: webserver_log_config = json.load(open("conf/log/webserver.conf.sample", "r")) logging.config.dictConfig(webserver_log_config) logging.debug("This should go to the log file") # We have see the sockets hang in practice. Let's set the socket timeout = 1 # hour to be on the safe side, and see if it is hit. socket.setdefaulttimeout(float(socket_timeout)) for plugin in app.plugins: if isinstance(plugin, JSONPlugin): print("Replaced json_dumps in plugin with the one from bson") plugin.json_dumps = bson.json_util.dumps print("Changing bt.json_loads from %s to %s" % (bt.json_loads, bson.json_util.loads)) bt.json_loads = bson.json_util.loads # The selection of SSL versus non-SSL should really be done through a config # option and not through editing source code, so let's make this keyed off the # port number if server_port == "443": # We support SSL and want to use it key_file = open('conf/net/keys.json') key_data = json.load(key_file) ssl_cert = key_data["ssl_certificate"] private_key = key_data["private_key"] run(host=server_host, port=server_port, server='cheroot', debug=True, certfile=ssl_cert, keyfile=private_key, ssl_module='builtin') else: # Non SSL option for testing on localhost print("Running with HTTPS turned OFF - use a reverse proxy on production") run(host=server_host, port=server_port, server='cheroot', debug=True) # run(host="0.0.0.0", port=server_port, server='cherrypy', debug=True)
# sqlalchemy/pool.py # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Connection pooling for DB-API connections. Provides a number of connection pool implementations for a variety of usage scenarios and thread behavior requirements imposed by the application, DB-API or database itself. Also provides a DB-API 2.0 connection proxying mechanism allowing regular DB-API connect() methods to be transparently managed by a SQLAlchemy connection pool. """ import weakref import time import traceback from sqlalchemy import exc, log, event, events, interfaces, util from sqlalchemy.util import queue as sqla_queue from sqlalchemy.util import threading, memoized_property, \ chop_traceback proxies = {} def manage(module, **params): """Return a proxy for a DB-API module that automatically pools connections. Given a DB-API 2.0 module and pool management parameters, returns a proxy for the module that will automatically pool connections, creating new connection pools for each distinct set of connection arguments sent to the decorated module's connect() function. :param module: a DB-API 2.0 database module :param poolclass: the class used by the pool module to provide pooling. Defaults to :class:`.QueuePool`. :param \*\*params: will be passed through to *poolclass* """ try: return proxies[module] except KeyError: return proxies.setdefault(module, _DBProxy(module, **params)) def clear_managers(): """Remove all current DB-API 2.0 managers. All pools and connections are disposed. """ for manager in proxies.itervalues(): manager.close() proxies.clear() reset_rollback = util.symbol('reset_rollback') reset_commit = util.symbol('reset_commit') reset_none = util.symbol('reset_none') class Pool(log.Identified): """Abstract base class for connection pools.""" def __init__(self, creator, recycle=-1, echo=None, use_threadlocal=False, logging_name=None, reset_on_return=True, listeners=None, events=None, _dispatch=None): """ Construct a Pool. :param creator: a callable function that returns a DB-API connection object. The function will be called with parameters. :param recycle: If set to non -1, number of seconds between connection recycling, which means upon checkout, if this timeout is surpassed the connection will be closed and replaced with a newly opened connection. Defaults to -1. :param logging_name: String identifier which will be used within the "name" field of logging records generated within the "sqlalchemy.pool" logger. Defaults to a hexstring of the object's id. :param echo: If True, connections being pulled and retrieved from the pool will be logged to the standard output, as well as pool sizing information. Echoing can also be achieved by enabling logging for the "sqlalchemy.pool" namespace. Defaults to False. :param use_threadlocal: If set to True, repeated calls to :meth:`connect` within the same application thread will be guaranteed to return the same connection object, if one has already been retrieved from the pool and has not been returned yet. Offers a slight performance advantage at the cost of individual transactions by default. The :meth:`unique_connection` method is provided to bypass the threadlocal behavior installed into :meth:`connect`. :param reset_on_return: If true, reset the database state of connections returned to the pool. This is typically a ROLLBACK to release locks and transaction resources. Disable at your own peril. Defaults to True. :param events: a list of 2-tuples, each of the form ``(callable, target)`` which will be passed to event.listen() upon construction. Provided here so that event listeners can be assigned via ``create_engine`` before dialect-level listeners are applied. :param listeners: Deprecated. A list of :class:`~sqlalchemy.interfaces.PoolListener`-like objects or dictionaries of callables that receive events when DB-API connections are created, checked out and checked in to the pool. This has been superseded by :func:`~sqlalchemy.event.listen`. """ if logging_name: self.logging_name = self._orig_logging_name = logging_name else: self._orig_logging_name = None log.instance_logger(self, echoflag=echo) self._threadconns = threading.local() self._creator = creator self._recycle = recycle self._use_threadlocal = use_threadlocal if reset_on_return in ('rollback', True, reset_rollback): self._reset_on_return = reset_rollback elif reset_on_return in (None, False, reset_none): self._reset_on_return = reset_none elif reset_on_return in ('commit', reset_commit): self._reset_on_return = reset_commit else: raise exc.ArgumentError( "Invalid value for 'reset_on_return': %r" % reset_on_return) self.echo = echo if _dispatch: self.dispatch._update(_dispatch, only_propagate=False) if events: for fn, target in events: event.listen(self, target, fn) if listeners: util.warn_deprecated( "The 'listeners' argument to Pool (and " "create_engine()) is deprecated. Use event.listen().") for l in listeners: self.add_listener(l) dispatch = event.dispatcher(events.PoolEvents) @util.deprecated(2.7, "Pool.add_listener is deprecated. Use event.listen()") def add_listener(self, listener): """Add a :class:`.PoolListener`-like object to this pool. ``listener`` may be an object that implements some or all of PoolListener, or a dictionary of callables containing implementations of some or all of the named methods in PoolListener. """ interfaces.PoolListener._adapt_listener(self, listener) def unique_connection(self): """Produce a DBAPI connection that is not referenced by any thread-local context. This method is different from :meth:`.Pool.connect` only if the ``use_threadlocal`` flag has been set to ``True``. """ return _ConnectionFairy(self).checkout() def _create_connection(self): """Called by subclasses to create a new ConnectionRecord.""" return _ConnectionRecord(self) def recreate(self): """Return a new :class:`.Pool`, of the same class as this one and configured with identical creation arguments. This method is used in conjunection with :meth:`dispose` to close out an entire :class:`.Pool` and create a new one in its place. """ raise NotImplementedError() def dispose(self): """Dispose of this pool. This method leaves the possibility of checked-out connections remaining open, as it only affects connections that are idle in the pool. See also the :meth:`Pool.recreate` method. """ raise NotImplementedError() def _replace(self): """Dispose + recreate this pool. Subclasses may employ special logic to move threads waiting on this pool to the new one. """ self.dispose() return self.recreate() def connect(self): """Return a DBAPI connection from the pool. The connection is instrumented such that when its ``close()`` method is called, the connection will be returned to the pool. """ if not self._use_threadlocal: return _ConnectionFairy(self).checkout() try: rec = self._threadconns.current() if rec: return rec.checkout() except AttributeError: pass agent = _ConnectionFairy(self) self._threadconns.current = weakref.ref(agent) return agent.checkout() def _return_conn(self, record): """Given a _ConnectionRecord, return it to the :class:`.Pool`. This method is called when an instrumented DBAPI connection has its ``close()`` method called. """ if self._use_threadlocal: try: del self._threadconns.current except AttributeError: pass self._do_return_conn(record) def _do_get(self): """Implementation for :meth:`get`, supplied by subclasses.""" raise NotImplementedError() def _do_return_conn(self, conn): """Implementation for :meth:`return_conn`, supplied by subclasses.""" raise NotImplementedError() def status(self): raise NotImplementedError() class _ConnectionRecord(object): finalize_callback = None def __init__(self, pool): self.__pool = pool self.connection = self.__connect() self.info = {} pool.dispatch.first_connect.\ for_modify(pool.dispatch).\ exec_once(self.connection, self) pool.dispatch.connect(self.connection, self) def close(self): if self.connection is not None: self.__pool.logger.debug("Closing connection %r", self.connection) try: self.connection.close() except (SystemExit, KeyboardInterrupt): raise except: self.__pool.logger.debug("Exception closing connection %r", self.connection) def invalidate(self, e=None): if e is not None: self.__pool.logger.info( "Invalidate connection %r (reason: %s:%s)", self.connection, e.__class__.__name__, e) else: self.__pool.logger.info( "Invalidate connection %r", self.connection) self.__close() self.connection = None def get_connection(self): if self.connection is None: self.connection = self.__connect() self.info.clear() if self.__pool.dispatch.connect: self.__pool.dispatch.connect(self.connection, self) elif self.__pool._recycle > -1 and \ time.time() - self.starttime > self.__pool._recycle: self.__pool.logger.info( "Connection %r exceeded timeout; recycling", self.connection) self.__close() self.connection = self.__connect() self.info.clear() if self.__pool.dispatch.connect: self.__pool.dispatch.connect(self.connection, self) return self.connection def __close(self): try: self.__pool.logger.debug("Closing connection %r", self.connection) self.connection.close() except (SystemExit, KeyboardInterrupt): raise except Exception, e: self.__pool.logger.debug( "Connection %r threw an error on close: %s", self.connection, e) def __connect(self): try: self.starttime = time.time() connection = self.__pool._creator() self.__pool.logger.debug("Created new connection %r", connection) return connection except Exception, e: self.__pool.logger.debug("Error on connect(): %s", e) raise def _finalize_fairy(connection, connection_record, pool, ref, echo): _refs.discard(connection_record) if ref is not None and \ connection_record.fairy is not ref: return if connection is not None: try: if pool._reset_on_return is reset_rollback: connection.rollback() elif pool._reset_on_return is reset_commit: connection.commit() # Immediately close detached instances if connection_record is None: connection.close() except Exception, e: if connection_record is not None: connection_record.invalidate(e=e) if isinstance(e, (SystemExit, KeyboardInterrupt)): raise if connection_record is not None: connection_record.fairy = None if echo: pool.logger.debug("Connection %r being returned to pool", connection) if connection_record.finalize_callback: connection_record.finalize_callback(connection) del connection_record.finalize_callback if pool.dispatch.checkin: pool.dispatch.checkin(connection, connection_record) pool._return_conn(connection_record) _refs = set() class _ConnectionFairy(object): """Proxies a DB-API connection and provides return-on-dereference support.""" __slots__ = '_pool', '__counter', 'connection', \ '_connection_record', '__weakref__', \ '_detached_info', '_echo' def __init__(self, pool): self._pool = pool self.__counter = 0 self._echo = _echo = pool._should_log_debug() try: rec = self._connection_record = pool._do_get() conn = self.connection = self._connection_record.get_connection() rec.fairy = weakref.ref( self, lambda ref:_finalize_fairy and _finalize_fairy(conn, rec, pool, ref, _echo) ) _refs.add(rec) except: # helps with endless __getattr__ loops later on self.connection = None self._connection_record = None raise if self._echo: self._pool.logger.debug("Connection %r checked out from pool" % self.connection) @property def _logger(self): return self._pool.logger @property def is_valid(self): return self.connection is not None @property def info(self): """An info collection unique to this DB-API connection.""" try: return self._connection_record.info except AttributeError: if self.connection is None: raise exc.InvalidRequestError("This connection is closed") try: return self._detached_info except AttributeError: self._detached_info = value = {} return value def invalidate(self, e=None): """Mark this connection as invalidated. The connection will be immediately closed. The containing ConnectionRecord will create a new connection when next used. """ if self.connection is None: raise exc.InvalidRequestError("This connection is closed") if self._connection_record is not None: self._connection_record.invalidate(e=e) self.connection = None self._close() def cursor(self, *args, **kwargs): return self.connection.cursor(*args, **kwargs) def __getattr__(self, key): return getattr(self.connection, key) def checkout(self): if self.connection is None: raise exc.InvalidRequestError("This connection is closed") self.__counter += 1 if not self._pool.dispatch.checkout or self.__counter != 1: return self # Pool listeners can trigger a reconnection on checkout attempts = 2 while attempts > 0: try: self._pool.dispatch.checkout(self.connection, self._connection_record, self) return self except exc.DisconnectionError, e: self._pool.logger.info( "Disconnection detected on checkout: %s", e) self._connection_record.invalidate(e) self.connection = self._connection_record.get_connection() attempts -= 1 self._pool.logger.info("Reconnection attempts exhausted on checkout") self.invalidate() raise exc.InvalidRequestError("This connection is closed") def detach(self): """Separate this connection from its Pool. This means that the connection will no longer be returned to the pool when closed, and will instead be literally closed. The containing ConnectionRecord is separated from the DB-API connection, and will create a new connection when next used. Note that any overall connection limiting constraints imposed by a Pool implementation may be violated after a detach, as the detached connection is removed from the pool's knowledge and control. """ if self._connection_record is not None: _refs.remove(self._connection_record) self._connection_record.fairy = None self._connection_record.connection = None self._pool._do_return_conn(self._connection_record) self._detached_info = \ self._connection_record.info.copy() self._connection_record = None def close(self): self.__counter -= 1 if self.__counter == 0: self._close() def _close(self): _finalize_fairy(self.connection, self._connection_record, self._pool, None, self._echo) self.connection = None self._connection_record = None class SingletonThreadPool(Pool): """A Pool that maintains one connection per thread. Maintains one connection per each thread, never moving a connection to a thread other than the one which it was created in. Options are the same as those of :class:`.Pool`, as well as: :param pool_size: The number of threads in which to maintain connections at once. Defaults to five. :class:`.SingletonThreadPool` is used by the SQLite dialect automatically when a memory-based database is used. See :ref:`sqlite_toplevel`. """ def __init__(self, creator, pool_size=5, **kw): kw['use_threadlocal'] = True Pool.__init__(self, creator, **kw) self._conn = threading.local() self._all_conns = set() self.size = pool_size def recreate(self): self.logger.info("Pool recreating") return self.__class__(self._creator, pool_size=self.size, recycle=self._recycle, echo=self.echo, logging_name=self._orig_logging_name, use_threadlocal=self._use_threadlocal, _dispatch=self.dispatch) def dispose(self): """Dispose of this pool.""" for conn in self._all_conns: try: conn.close() except (SystemExit, KeyboardInterrupt): raise except: # pysqlite won't even let you close a conn from a thread # that didn't create it pass self._all_conns.clear() def _cleanup(self): while len(self._all_conns) > self.size: c = self._all_conns.pop() c.close() def status(self): return "SingletonThreadPool id:%d size: %d" % \ (id(self), len(self._all_conns)) def _do_return_conn(self, conn): pass def _do_get(self): try: c = self._conn.current() if c: return c except AttributeError: pass c = self._create_connection() self._conn.current = weakref.ref(c) self._all_conns.add(c) if len(self._all_conns) > self.size: self._cleanup() return c class DummyLock(object): def acquire(self, wait=True): return True def release(self): pass class QueuePool(Pool): """A :class:`.Pool` that imposes a limit on the number of open connections. :class:`.QueuePool` is the default pooling implementation used for all :class:`.Engine` objects, unless the SQLite dialect is in use. """ def __init__(self, creator, pool_size=5, max_overflow=10, timeout=30, **kw): """ Construct a QueuePool. :param creator: a callable function that returns a DB-API connection object. The function will be called with parameters. :param pool_size: The size of the pool to be maintained, defaults to 5. This is the largest number of connections that will be kept persistently in the pool. Note that the pool begins with no connections; once this number of connections is requested, that number of connections will remain. ``pool_size`` can be set to 0 to indicate no size limit; to disable pooling, use a :class:`~sqlalchemy.pool.NullPool` instead. :param max_overflow: The maximum overflow size of the pool. When the number of checked-out connections reaches the size set in pool_size, additional connections will be returned up to this limit. When those additional connections are returned to the pool, they are disconnected and discarded. It follows then that the total number of simultaneous connections the pool will allow is pool_size + `max_overflow`, and the total number of "sleeping" connections the pool will allow is pool_size. `max_overflow` can be set to -1 to indicate no overflow limit; no limit will be placed on the total number of concurrent connections. Defaults to 10. :param timeout: The number of seconds to wait before giving up on returning a connection. Defaults to 30. :param recycle: If set to non -1, number of seconds between connection recycling, which means upon checkout, if this timeout is surpassed the connection will be closed and replaced with a newly opened connection. Defaults to -1. :param echo: If True, connections being pulled and retrieved from the pool will be logged to the standard output, as well as pool sizing information. Echoing can also be achieved by enabling logging for the "sqlalchemy.pool" namespace. Defaults to False. :param use_threadlocal: If set to True, repeated calls to :meth:`connect` within the same application thread will be guaranteed to return the same connection object, if one has already been retrieved from the pool and has not been returned yet. Offers a slight performance advantage at the cost of individual transactions by default. The :meth:`unique_connection` method is provided to bypass the threadlocal behavior installed into :meth:`connect`. :param reset_on_return: Determine steps to take on connections as they are returned to the pool. reset_on_return can have any of these values: * 'rollback' - call rollback() on the connection, to release locks and transaction resources. This is the default value. The vast majority of use cases should leave this value set. * True - same as 'rollback', this is here for backwards compatibility. * 'commit' - call commit() on the connection, to release locks and transaction resources. A commit here may be desirable for databases that cache query plans if a commit is emitted, such as Microsoft SQL Server. However, this value is more dangerous than 'rollback' because any data changes present on the transaction are committed unconditionally. * None - don't do anything on the connection. This setting should only be made on a database that has no transaction support at all, namely MySQL MyISAM. By not doing anything, performance can be improved. This setting should **never be selected** for a database that supports transactions, as it will lead to deadlocks and stale state. * False - same as None, this is here for backwards compatibility. .. versionchanged:: 0.7.6 ``reset_on_return`` accepts values. :param listeners: A list of :class:`~sqlalchemy.interfaces.PoolListener`-like objects or dictionaries of callables that receive events when DB-API connections are created, checked out and checked in to the pool. """ Pool.__init__(self, creator, **kw) self._pool = sqla_queue.Queue(pool_size) self._overflow = 0 - pool_size self._max_overflow = max_overflow self._timeout = timeout self._overflow_lock = self._max_overflow > -1 and \ threading.Lock() or DummyLock() def _do_return_conn(self, conn): try: self._pool.put(conn, False) except sqla_queue.Full: conn.close() self._overflow_lock.acquire() try: self._overflow -= 1 finally: self._overflow_lock.release() def _do_get(self): try: wait = self._max_overflow > -1 and \ self._overflow >= self._max_overflow return self._pool.get(wait, self._timeout) except sqla_queue.SAAbort, aborted: return aborted.context._do_get() except sqla_queue.Empty: if self._max_overflow > -1 and \ self._overflow >= self._max_overflow: if not wait: return self._do_get() else: raise exc.TimeoutError( "QueuePool limit of size %d overflow %d reached, " "connection timed out, timeout %d" % (self.size(), self.overflow(), self._timeout)) self._overflow_lock.acquire() try: if self._max_overflow > -1 and \ self._overflow >= self._max_overflow: return self._do_get() else: con = self._create_connection() self._overflow += 1 return con finally: self._overflow_lock.release() def recreate(self): self.logger.info("Pool recreating") return self.__class__(self._creator, pool_size=self._pool.maxsize, max_overflow=self._max_overflow, timeout=self._timeout, recycle=self._recycle, echo=self.echo, logging_name=self._orig_logging_name, use_threadlocal=self._use_threadlocal, _dispatch=self.dispatch) def dispose(self): while True: try: conn = self._pool.get(False) conn.close() except sqla_queue.Empty: break self._overflow = 0 - self.size() self.logger.info("Pool disposed. %s", self.status()) def _replace(self): self.dispose() np = self.recreate() self._pool.abort(np) return np def status(self): return "Pool size: %d Connections in pool: %d "\ "Current Overflow: %d Current Checked out "\ "connections: %d" % (self.size(), self.checkedin(), self.overflow(), self.checkedout()) def size(self): return self._pool.maxsize def checkedin(self): return self._pool.qsize() def overflow(self): return self._overflow def checkedout(self): return self._pool.maxsize - self._pool.qsize() + self._overflow class NullPool(Pool): """A Pool which does not pool connections. Instead it literally opens and closes the underlying DB-API connection per each connection open/close. Reconnect-related functions such as ``recycle`` and connection invalidation are not supported by this Pool implementation, since no connections are held persistently. .. versionchanged:: 0.7 :class:`.NullPool` is used by the SQlite dialect automatically when a file-based database is used. See :ref:`sqlite_toplevel`. """ def status(self): return "NullPool" def _do_return_conn(self, conn): conn.close() def _do_get(self): return self._create_connection() def recreate(self): self.logger.info("Pool recreating") return self.__class__(self._creator, recycle=self._recycle, echo=self.echo, logging_name=self._orig_logging_name, use_threadlocal=self._use_threadlocal, _dispatch=self.dispatch) def dispose(self): pass class StaticPool(Pool): """A Pool of exactly one connection, used for all requests. Reconnect-related functions such as ``recycle`` and connection invalidation (which is also used to support auto-reconnect) are not currently supported by this Pool implementation but may be implemented in a future release. """ @memoized_property def _conn(self): return self._creator() @memoized_property def connection(self): return _ConnectionRecord(self) def status(self): return "StaticPool" def dispose(self): if '_conn' in self.__dict__: self._conn.close() self._conn = None def recreate(self): self.logger.info("Pool recreating") return self.__class__(creator=self._creator, recycle=self._recycle, use_threadlocal=self._use_threadlocal, reset_on_return=self._reset_on_return, echo=self.echo, logging_name=self._orig_logging_name, _dispatch=self.dispatch) def _create_connection(self): return self._conn def _do_return_conn(self, conn): pass def _do_get(self): return self.connection class AssertionPool(Pool): """A :class:`.Pool` that allows at most one checked out connection at any given time. This will raise an exception if more than one connection is checked out at a time. Useful for debugging code that is using more connections than desired. .. versionchanged:: 0.7 :class:`.AssertionPool` also logs a traceback of where the original connection was checked out, and reports this in the assertion error raised. """ def __init__(self, *args, **kw): self._conn = None self._checked_out = False self._store_traceback = kw.pop('store_traceback', True) self._checkout_traceback = None Pool.__init__(self, *args, **kw) def status(self): return "AssertionPool" def _do_return_conn(self, conn): if not self._checked_out: raise AssertionError("connection is not checked out") self._checked_out = False assert conn is self._conn def dispose(self): self._checked_out = False if self._conn: self._conn.close() def recreate(self): self.logger.info("Pool recreating") return self.__class__(self._creator, echo=self.echo, logging_name=self._orig_logging_name, _dispatch=self.dispatch) def _do_get(self): if self._checked_out: if self._checkout_traceback: suffix = ' at:\n%s' % ''.join( chop_traceback(self._checkout_traceback)) else: suffix = '' raise AssertionError("connection is already checked out" + suffix) if not self._conn: self._conn = self._create_connection() self._checked_out = True if self._store_traceback: self._checkout_traceback = traceback.format_stack() return self._conn class _DBProxy(object): """Layers connection pooling behavior on top of a standard DB-API module. Proxies a DB-API 2.0 connect() call to a connection pool keyed to the specific connect parameters. Other functions and attributes are delegated to the underlying DB-API module. """ def __init__(self, module, poolclass=QueuePool, **kw): """Initializes a new proxy. module a DB-API 2.0 module poolclass a Pool class, defaulting to QueuePool Other parameters are sent to the Pool object's constructor. """ self.module = module self.kw = kw self.poolclass = poolclass self.pools = {} self._create_pool_mutex = threading.Lock() def close(self): for key in self.pools.keys(): del self.pools[key] def __del__(self): self.close() def __getattr__(self, key): return getattr(self.module, key) def get_pool(self, *args, **kw): key = self._serialize(*args, **kw) try: return self.pools[key] except KeyError: self._create_pool_mutex.acquire() try: if key not in self.pools: kw.pop('sa_pool_key', None) pool = self.poolclass(lambda: self.module.connect(*args, **kw), **self.kw) self.pools[key] = pool return pool else: return self.pools[key] finally: self._create_pool_mutex.release() def connect(self, *args, **kw): """Activate a connection to the database. Connect to the database using this DBProxy's module and the given connect arguments. If the arguments match an existing pool, the connection will be returned from the pool's current thread-local connection instance, or if there is no thread-local connection instance it will be checked out from the set of pooled connections. If the pool has no available connections and allows new connections to be created, a new database connection will be made. """ return self.get_pool(*args, **kw).connect() def dispose(self, *args, **kw): """Dispose the pool referenced by the given connect arguments.""" key = self._serialize(*args, **kw) try: del self.pools[key] except KeyError: pass def _serialize(self, *args, **kw): if "sa_pool_key" in kw: return kw['sa_pool_key'] return tuple( list(args) + [(k, kw[k]) for k in sorted(kw)] )
from django.db.models.aggregates import Count from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from dateutil.rrule import DAILY, FR, MO, SA, TH, TU, WE, rrule from sqlagg.columns import SimpleColumn from sqlagg.filters import EQ from sqlagg.sorting import OrderBy from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader from corehq.apps.reports.filters.dates import DatespanFilter from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.reports.sqlreport import DatabaseColumn, SqlData from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin from corehq.apps.sms.models import ( INCOMING, SMS, MessagingEvent, MessagingSubEvent, ) from corehq.apps.userreports.util import get_table_name from corehq.sql_db.connections import DEFAULT_ENGINE_ID from custom.abt.reports.filters import ( CountryFilter, LevelFourFilter, LevelOneFilter, LevelThreeFilter, LevelTwoFilter, SubmissionStatusFilter, UsernameFilter, ) class LatePMTUsers(SqlData): engine_id = DEFAULT_ENGINE_ID @property def table_name(self): return get_table_name(self.domain, "static-late-pmt") @property def domain(self): return self.config['domain'] @property def filters(self): filters = [] filter_fields = [ 'country', 'level_1', 'level_2', 'level_3', 'level_4', ] for filter_field in filter_fields: if filter_field in self.config and self.config[filter_field]: filters.append(EQ(filter_field, filter_field)) if 'user_id' in self.config and self.config['user_id']: filters.append(EQ('doc_id', 'user_id')) return filters @property def group_by(self): return [ 'user_id', 'username', 'phone_number', 'country', 'level_1', 'level_2', 'level_3', 'level_4', ] @property def order_by(self): return [OrderBy('username')] @property def columns(self): return [ DatabaseColumn('user_id', SimpleColumn('doc_id', alias='user_id')), DatabaseColumn('username', SimpleColumn('username')), DatabaseColumn('phone_number', SimpleColumn('phone_number')), DatabaseColumn('country', SimpleColumn('country')), DatabaseColumn('level_1', SimpleColumn('level_1')), DatabaseColumn('level_2', SimpleColumn('level_2')), DatabaseColumn('level_3', SimpleColumn('level_3')), DatabaseColumn('level_4', SimpleColumn('level_4')) ] class LatePmtReport(GenericTabularReport, CustomProjectReport, DatespanMixin): report_title = "Late PMT" slug = 'late_pmt' name = "Late PMT 2019" languages = ( 'en', 'fra', 'por' ) fields = [ DatespanFilter, UsernameFilter, CountryFilter, LevelOneFilter, LevelTwoFilter, LevelThreeFilter, LevelFourFilter, SubmissionStatusFilter, ] @property def report_config(self): return { 'domain': self.domain, 'startdate': self.startdate, 'enddate': self.enddate, 'user_id': self.request.GET.get('user_id', ''), 'country': self.request.GET.get('country', ''), 'level_1': self.request.GET.get('level_1', ''), 'level_2': self.request.GET.get('level_2', ''), 'level_3': self.request.GET.get('level_3', ''), 'level_4': self.request.GET.get('level_4', ''), 'submission_status': self.request.GET.get('submission_status', '') } @property def startdate(self): return self.request.datespan.startdate @property def enddate(self): return self.request.datespan.end_of_end_day @property def headers(self): return DataTablesHeader( DataTablesColumn(_("Missing Report Date")), DataTablesColumn(_("Username")), DataTablesColumn(_("Phone Number")), DataTablesColumn(_("Country")), DataTablesColumn(_("Level 1")), DataTablesColumn(_("Level 2")), DataTablesColumn(_("Level 3")), DataTablesColumn(_("Level 4")), DataTablesColumn(_("Submission Status")), ) @cached_property def smss_received(self): data = SMS.objects.filter( domain=self.domain, couch_recipient_doc_type='CommCareUser', direction=INCOMING, couch_recipient__in=self.get_user_ids, date__range=( self.startdate, self.enddate ) ).exclude( text="123" ).values('date', 'couch_recipient').annotate( number_of_sms=Count('couch_recipient') ) return {(sms['date'].date(), sms['couch_recipient']) for sms in data} @cached_property def valid_smss_received(self): data = MessagingSubEvent.objects.filter( parent__domain=self.domain, parent__recipient_type=MessagingEvent.RECIPIENT_MOBILE_WORKER, parent__source=MessagingEvent.SOURCE_KEYWORD, xforms_session__isnull=False, xforms_session__submission_id__isnull=False, recipient_id__in=self.get_user_ids, date__range=( self.startdate, self.enddate ) ).values('date', 'recipient_id') return {(subevent['date'].date(), subevent['recipient_id']) for subevent in data} @cached_property def get_user_ids(self): return [user['user_id'] for user in self.get_users] @cached_property def get_users(self): return LatePMTUsers(config=self.report_config).get_data() @property def rows(self): def _to_report_format(date, user, error_msg): return [ date.strftime("%Y-%m-%d"), user['username'].split('@')[0], user['phone_number'], user['country'], user['level_1'], user['level_2'], user['level_3'], user['level_4'], error_msg ] users = self.get_users dates = rrule( DAILY, dtstart=self.startdate, until=self.enddate, byweekday=(MO, TU, WE, TH, FR, SA) ) include_missing_pmt_data = self.report_config['submission_status'] != 'group_b' include_incorrect_pmt_data = self.report_config['submission_status'] != 'group_a' rows = [] if users: for date in dates: for user in users: sms_received = (date.date(), user['user_id']) in self.smss_received valid_sms = (date.date(), user['user_id']) in self.valid_smss_received if not sms_received and include_missing_pmt_data: error_msg = _('No PMT data Submitted') elif sms_received and not valid_sms and include_incorrect_pmt_data: error_msg = _('Incorrect PMT data Submitted') else: continue rows.append(_to_report_format(date, user, error_msg)) return rows
from Data import Parameters from Data.Events import ChangeEvent from Data.Vertex import Vertex from Data.Objects import IdObject, ObservableObject, NamedObservableObject __author__ = 'mamj' components = "xyz" class Point3d(Vertex, IdObject): def __init__(self, x=0.0, y=0.0, z=0.0): Vertex.__init__(self, x, y, z) IdObject.__init__(self) def serialize_json(self): return \ { 'v': Vertex.serialize_json(self), 'uid': IdObject.serialize_json(self) } @staticmethod def deserialize(data): point = Point3d() point.deserialize_data(data) return point def deserialize_data(self, data): try: IdObject.deserialize_data(self, data['uid']) except TypeError as e: print("error: " + str(e)) Vertex.deserialize_data(self, data['v']) class KeyPoint(Point3d, NamedObservableObject): def __init__(self, parameters: Parameters, x=0.0, y=0.0, z=0.0, name="Keypoint"): Point3d.__init__(self, x, y, z) NamedObservableObject.__init__(self, name) self._component_parameters = [None, None, None] self._instances = {} self._parameters = parameters self._edges = [] self.editable = True self._component_change_handlers = [] self._component_change_handlers.append(self.on_x_param_changed) self._component_change_handlers.append(self.on_y_param_changed) self._component_change_handlers.append(self.on_z_param_changed) @property def instances(self): return self._instances.items() @property def parameters(self): return self._parameters def delete(self): self.changed(ChangeEvent(self, ChangeEvent.Deleted, self)) def get_edges(self): return list(self._edges) def add_edge(self, edge): if edge not in self._edges: self._edges.append(edge) edge.add_change_handler(self.edge_changed_handler) def edge_changed_handler(self, event): if event.type == ChangeEvent.Deleted: self.remove_edge(event.object) def remove_edge(self, edge): if edge in self._edges: edge.remove_change_handler(self.edge_changed_handler) self._edges.remove(edge) def get_x_parameter(self): return self._component_parameters[0] def get_y_parameter(self): return self._component_parameters[1] def get_z_parameter(self): return self._component_parameters[2] def create_value_change_object(self, new_value, old_value, component, instance_uid): change_object = { 'new value': new_value, 'old value': old_value, 'name': components[component], 'component': component, 'instance': instance_uid } return change_object def set_instance_generic(self, instance_uid, value, component): changed = False old_value = self.get_instance_generic(instance_uid, component) if instance_uid is None: self.xyz[component] = value changed = True else: if instance_uid in self._instances: instance_vertice = self._instances[instance_uid] instance_vertice.xyz[component] = value if self.equals(instance_vertice): self._instances.pop(instance_uid) changed = True else: if value != self.xyz[component]: instance_vertice = Vertex(self.x, self.y, self.z) instance_vertice.xyz[component] = value self._instances[instance_uid] = instance_vertice changed = True if changed: name = components[component] change_object = self.create_value_change_object(value, old_value, component, instance_uid) self.changed(ChangeEvent(self, ChangeEvent.ValueChanged, change_object)) def set_instance_x(self, instance_uid, value): self.set_instance_generic(instance_uid, value, 0) def set_instance_y(self, instance_uid, value): self.set_instance_generic(instance_uid, value, 1) def set_instance_z(self, instance_uid, value): self.set_instance_generic(instance_uid, value, 2) def get_instance_generic(self, instance_uid, component): if self._component_parameters[component] is None: if instance_uid in self._instances: return self._instances[instance_uid].xyz[component] return self.xyz[component] else: return self._component_parameters[component].get_instance_value(instance_uid) def get_instance_x(self, instance_uid): return self.get_instance_generic(instance_uid, 0) def get_instance_y(self, instance_uid): return self.get_instance_generic(instance_uid, 1) def get_instance_z(self, instance_uid): return self.get_instance_generic(instance_uid, 2) def get_instance_xyz(self, instance_uid): if instance_uid in self._instances: return self._instances[instance_uid].xyz return self.xyz def get_instance(self, instance_uid): if instance_uid in self._instances: return self._instances[instance_uid] return self @property def x(self): return self.xyz[0] @property def y(self): return self.xyz[1] @property def z(self): return self.xyz[2] @x.setter def x(self, value): self.set_instance_generic(None, value, 0) @y.setter def y(self, value): self.set_instance_generic(None, value, 1) @z.setter def z(self, value): self.set_instance_generic(None, value, 2) def set_parameter_generic(self, param_uid, component): old_value = self.get_instance_generic(None, component) if self._component_parameters[component] is not None: self._component_parameters[component].remove_change_handler(self._component_change_handlers[component]) self._component_parameters[component] = None if param_uid is not None: param = self._parameters.get_parameter_by_uid(param_uid) self._component_parameters[component] = param if param is not None: new_value = self.get_instance_generic(None, component) param.add_change_handler(self._component_change_handlers[component]) change_object = self.create_value_change_object(new_value, old_value, component, None) self._component_change_handlers[component](ChangeEvent(self, ChangeEvent.ValueChanged, change_object)) def set_x_parameter(self, param_uid): self.set_parameter_generic(param_uid, 0) def set_y_parameter(self, param_uid): self.set_parameter_generic(param_uid, 1) def set_z_parameter(self, param_uid): self.set_parameter_generic(param_uid, 2) def on_param_changed_generic(self, event, component): instance = None if 'instance' in event.object: instance = event.object['instance'] old_value = self.get_instance_generic(instance, component) new_value = float(self._component_parameters[component].evaluate(instance)) self.set_instance_generic(instance, new_value, component) if event.type == ChangeEvent.Deleted: event.object.remove_change_handler(self._component_change_handlers[component]) self._component_parameters[component] = None change_object = self.create_value_change_object(new_value, old_value, component, instance) self.changed(ChangeEvent(self, ChangeEvent.ValueChanged, change_object)) def on_x_param_changed(self, event): self.on_param_changed_generic(event, 0) def on_y_param_changed(self, event): self.on_param_changed_generic(event, 1) def on_z_param_changed(self, event): self.on_param_changed_generic(event, 2) def get_param_uid(self, param): if param is None: return None else: return param.uid def serialize_json(self): return \ { 'p3d': Point3d.serialize_json(self), 'no': NamedObservableObject.serialize_json(self), 'instances': self._instances, 'x_param_uid': self.get_param_uid(self._component_parameters[0]), 'y_param_uid': self.get_param_uid(self._component_parameters[1]), 'z_param_uid': self.get_param_uid(self._component_parameters[2]) } @staticmethod def deserialize(data, parameters): key_point = KeyPoint(parameters) key_point.deserialize_data(data) return key_point def deserialize_data(self, data): Point3d.deserialize_data(self, data.get('p3d')) if 'no' in data: NamedObservableObject.deserialize_data(self, data['no']) else: self.name = "Keypoint" for instance_tuple in data.get('instances', {}).items(): instance_uid = instance_tuple[0] vertex = Vertex.deserialize(instance_tuple[1]) self._instances[instance_uid] = vertex self.set_parameter_generic(data['x_param_uid'], 0) self.set_parameter_generic(data['y_param_uid'], 1) self.set_parameter_generic(data['z_param_uid'], 2)
""" Copyright (c) 2014-2015 F-Secure See LICENSE for details """ import json import logging import traceback from functools import partial from werkzeug.wrappers import Request, Response from werkzeug.routing import Map, Rule from werkzeug import exceptions as http_exceptions from resource_api.schema import ListField, ObjectField from resource_api import errors def _preprocess_query(schema, args): rval = {} for key in args.keys(): field = getattr(schema, key, None) if field is None: continue elif isinstance(field, ListField): rval[key] = args.getlist(key) elif isinstance(field, ObjectField): try: rval[key] = json.loads(args.get(key)) except ValueError, e: errors.ValidationError({key: e}) else: rval[key] = args.get(key) return rval def get_schema(request, service): return service.get_schema(), 200 def _get_col(request, service, resource_name): res = service.get_entry_point(request.headers).get_resource_by_name(resource_name) args = _preprocess_query(res._res.query_schema, request.args) if args: return res.filter(params=args) else: return res def get_resource_collection(request, service, resource_name): return _get_col(request, service, resource_name).serialize(), 200 def get_resource_collection_count(request, service, resource_name): return _get_col(request, service, resource_name).count(), 200 def get_resource_item(request, service, resource_name, resource_pk): res = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk) if request.method == "HEAD": return None, 200 else: return res.serialize(), 200 def delete_resource_item(request, service, resource_name, resource_pk): return service.get_entry_point(request.headers).get_resource_by_name(resource_name)\ .get(resource_pk).delete(), 204 def update_resource_item(request, service, resource_name, resource_pk): return service.get_entry_point(request.headers).get_resource_by_name(resource_name)\ .get(resource_pk).update(json.loads(request.data)), 204 def create_resource_item(request, service, resource_name): resource_data = json.loads(request.data) links = resource_data.pop("@links", {}) return service.get_entry_point(request.headers).get_resource_by_name(resource_name)\ .create(resource_data, links).serialize_pk(), 201 def _get_link_col(request, service, resource_name, resource_pk, link_name): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links lnk = getattr(links, link_name) args = _preprocess_query(lnk._forward_link_instance.query_schema, request.args) if args: return lnk.filter(params=args) else: return lnk def get_link_to_many_collection(request, service, resource_name, resource_pk, link_name): return _get_link_col(request, service, resource_name, resource_pk, link_name).serialize(), 200 def get_link_to_many_collection_count(request, service, resource_name, resource_pk, link_name): return _get_link_col(request, service, resource_name, resource_pk, link_name).count(), 200 def update_link_to_many_item(request, service, resource_name, resource_pk, link_name, target_pk): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links return getattr(links, link_name).get(target_pk).update(json.loads(request.data)), 204 def delete_link_to_many_item(request, service, resource_name, resource_pk, link_name, target_pk): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links return getattr(links, link_name).get(target_pk).delete(), 204 def get_link_to_many_item_data(request, service, resource_name, resource_pk, link_name, target_pk): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links link = getattr(links, link_name).get(target_pk) if request.method == "HEAD": return None, 200 else: return link.serialize(), 200 def create_link_to_many_item(request, service, resource_name, resource_pk, link_name): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links link_item = getattr(links, link_name).create(json.loads(request.data)) return link_item.target.serialize_pk(), 201 def set_link_to_one(request, service, resource_name, resource_pk, link_name): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links link = getattr(links, link_name) link.set(json.loads(request.data)) return link.item.target.serialize_pk(), 201 def delete_link_to_one(request, service, resource_name, resource_pk, link_name): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links getattr(links, link_name).item.delete() return None, 204 def update_link_to_one(request, service, resource_name, resource_pk, link_name): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links getattr(links, link_name).item.update(json.loads(request.data)) return None, 204 def get_link_to_one_data(request, service, resource_name, resource_pk, link_name): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links link = getattr(links, link_name).item if request.method == "HEAD": return None, 200 else: return link.serialize(), 200 def get_link_to_one_target(request, service, resource_name, resource_pk, link_name, redirect=False): links = service.get_entry_point(request.headers).get_resource_by_name(resource_name).get(resource_pk).links link = getattr(links, link_name) return link.item.target.serialize_pk(), 200 class Application(object): """ Plain WSGI application for Resource API service service (:class:`Service's <resource_api.service.Service>` subclass instance) Service to generate HTTP interface for debug (bool) If True 500 responses will include detailed traceback describing the error """ def __init__(self, service, debug=False): service.setup() url_map = [] def rule(url, endpoint, method="GET", **kwargs): url_map.append(Rule(url, methods=[method], endpoint=partial(endpoint, **kwargs))) rule("/", get_schema, service=service, method="OPTIONS") schema = service.get_schema() for resource_name, resource_meta in schema.iteritems(): kwargs = dict(resource_name=resource_name, service=service) rule("/%s" % resource_name, get_resource_collection, **kwargs) rule("/%s:count" % resource_name, get_resource_collection_count, **kwargs) rule("/%s" % resource_name, create_resource_item, "POST", **kwargs) rule("/%s/<resource_pk>" % resource_name, get_resource_item, "GET", **kwargs) rule("/%s/<resource_pk>" % resource_name, delete_resource_item, "DELETE", **kwargs) rule("/%s/<resource_pk>" % resource_name, update_resource_item, "PATCH", **kwargs) for link_name, link_meta in resource_meta.get("links", {}).iteritems(): kwargs = dict(kwargs) kwargs["link_name"] = link_name base_url = "/%s/<resource_pk>/%s" % (resource_name, link_name) def link_rule(endpoint, suffix="", method="GET"): rule(base_url + suffix, endpoint, method, **kwargs) if link_meta.get("cardinality", "MANY") == "ONE": link_rule(get_link_to_one_target, suffix="/item") link_rule(set_link_to_one, method="PUT") link_rule(get_link_to_one_data, suffix="/item:data") link_rule(update_link_to_one, method="PATCH", suffix="/item") link_rule(delete_link_to_one, method="DELETE", suffix="/item") else: link_rule(get_link_to_many_collection) link_rule(get_link_to_many_collection_count, suffix=":count") link_rule(create_link_to_many_item, method="POST") link_rule(update_link_to_many_item, method="PATCH", suffix="/<target_pk>") link_rule(delete_link_to_many_item, method="DELETE", suffix="/<target_pk>") link_rule(get_link_to_many_item_data, suffix="/<target_pk>:data") self._url_map = Map(url_map) self._debug = debug def __call__(self, environ, start_response): def _resp(data, status): resp = Response(json.dumps(data, indent=2 if self._debug else None), mimetype="application/json") if data is None: status = 204 resp.status_code = status return resp(environ, start_response) try: urls = self._url_map.bind_to_environ(environ) endpoint, params = urls.match() rval = endpoint(Request(environ), **params) if isinstance(rval, Response): return rval(environ, start_response) else: rval, status = rval return _resp(rval, status) except errors.MultipleFound, e: return _resp(e.message, 500) # this is actually a server problem except errors.ValidationError, e: return _resp(e.message, 400) except errors.DoesNotExist, e: return _resp(e.message, 404) except errors.DataConflictError, e: return _resp(e.message, 409) except errors.Forbidden, e: return _resp(e.message, 405) except errors.AuthorizationError, e: return _resp(e.message, 403) except NotImplementedError, e: return _resp(e.message, 501) except http_exceptions.HTTPException, e: return _resp(e.description, e.code) except Exception, e: logging.exception("Internal server error") if self._debug: msg = traceback.format_exc() else: msg = "Server error" return _resp(msg, 500)
import urlparse import sys import util import json import cgi import multiprocessing from multiprocessing import Queue from multiprocessing import Manager sys.path.append('../') from util import BackgroundWorker from urlparse import urlparse, parse_qs import config as gc # async_request_queue holds list of active async requests async_request_queue = {} #active_threads = [] #################### ## ASYNC REQUESTS ## #################### def project_request(request_handler): ''' POST /project { "project_name" : "my project name" "username" : "mm@force.com", "password" : "force", "org_type" : "developer", "package" : { "ApexClass" : "*", "ApexTrigger" : ["Trigger1", "Trigger2"] } } ''' run_async_operation(request_handler, 'new_project') def project_edit_request(request_handler): ''' POST /project/edit (body same as project_request) ''' run_async_operation(request_handler, 'edit_project') def project_upgrade_request(request_handler): ''' POST /project/upgrade { "project_name" : "my project name" "username" : "mm@force.com", "password" : "force", "org_type" : "developer" } ''' run_async_operation(request_handler, 'upgrade_project') def execute_apex_request(request_handler): ''' POST /apex/execute { "project_name" : "my project name" "log_level" : "DEBUG", "log_category" : "APEX_CODE", "body" : "String foo = 'bar';", } ''' run_async_operation(request_handler, 'execute_apex') def deploy_request(request_handler): ''' POST /project/deploy call to deploy metadata to a server { "check_only" : true, "rollback_on_error" : true, "destinations" : [ { "username" : "username1@force.com", "org_type" : "developer" } ], "package" : { "ApexClass" : "*" } } ''' run_async_operation(request_handler, 'deploy') def unit_test_request(request_handler): ''' POST /project/unit_test { "classes" : [ "UnitTestClass1", "UnitTestClass2" ], "run_all_tests" : false } ''' gc.logger.debug('in unit test method!') run_async_operation(request_handler, 'unit_test') def metadata_index_request(request_handler): ''' call to update the project .metadata index ''' run_async_operation(request_handler, 'index_metadata') ########################## ## SYNCHRONOUS REQUESTS ## ########################## def get_active_session_request(request_handler): ''' GET /session?username=mm@force.com&password=force&org_type=developer ''' request_id = util.generate_request_id() params, json_body = get_request_params(request_handler) worker = BackgroundWorker('get_active_session', params, False, request_id, json_body) response = worker.run() respond(request_handler, response) def update_credentials_request(request_handler): ''' POST /project/creds { "project_name" : "my project name" "username" : "mm@force.com", "password" : "force", "org_type" : "developer", } NOTE: project name should not be updated, as it is used to find the project in question TODO: maybe we assign a unique ID to each project which will give users the flexibility to change the project name?? TODO: we may need to implement a "clean" flag which will clean the project after creds have been updated ''' request_id = util.generate_request_id() params, raw_post_body = get_request_params(request_handler) worker = BackgroundWorker('update_credentials', params, False, request_id, raw_post_body) response = worker.run() respond(request_handler, response) def connections_list_request(request_handler): request_id = util.generate_request_id() params, raw_post_body = get_request_params(request_handler) worker = BackgroundWorker('list_connections', params, False, request_id, raw_post_body) response = worker.run() respond(request_handler, response) def connections_new_request(request_handler): request_id = util.generate_request_id() params, raw_post_body = get_request_params(request_handler) worker = BackgroundWorker('new_connection', params, False, request_id, raw_post_body) response = worker.run() respond(request_handler, response) def connections_delete_request(request_handler): request_id = util.generate_request_id() params, raw_post_body = get_request_params(request_handler) worker = BackgroundWorker('delete_connection', params, False, request_id, raw_post_body) response = worker.run() respond(request_handler, response) def metadata_list_request(request_handler): ''' GET /metadata/list { "sid" : "", "metadata_type" : "", "murl" : "" } call to get a list of metadata of a certain type ''' request_id = util.generate_request_id() params, json_body = get_request_params(request_handler) worker = BackgroundWorker('list_metadata', params, False, request_id, json_body) response = worker.run() respond(request_handler, response) ########################## ## END REQUEST HANDLERS ## ########################## def run_async_operation(request_handler, operation_name): gc.logger.debug('>>> running an async operation') request_id = util.generate_request_id() params, raw_post_body = get_request_params(request_handler) gc.logger.debug(request_id) gc.logger.debug(params) gc.logger.debug(raw_post_body) worker_thread = BackgroundWorker(operation_name, params, True, request_id, raw_post_body) gc.logger.debug('worker created') worker_thread.start() gc.logger.debug('worker thread started') async_request_queue[request_id] = worker_thread gc.logger.debug('placed into queue') #q = Queue() #on larger object puts, process would hang #using manager based on this recommendation: #http://stackoverflow.com/questions/11442892/python-multiprocessing-queue-failure # manager = Manager() # q = manager.Queue() #TODO: request is failing here many times # gc.logger.debug('finished with queue') #worker = BackgroundWorker(operation_name, params, True, request_id, raw_post_body, q) #gc.logger.debug('worker created') #p = multiprocessing.Process(target=process_request_in_background,args=(worker,)) #p.start() #gc.logger.debug('started process!') #add_to_request_queue(request_id, p, q) #gc.logger.debug('preparing to response with the async id!') return respond_with_async_request_id(request_handler, request_id) #client polls this servlet to determine whether the request is done #if the request IS done, it will respond with the body of the request def status_request(request_handler): gc.logger.debug('>>> status request') params, json_string = get_request_params(request_handler) gc.logger.debug('>>> params: ') gc.logger.debug(params) try: request_id = params['id'] except: request_id = params['id'][0] gc.logger.debug('>>> request id: ' + request_id) gc.logger.debug('>>> async queue: ') gc.logger.debug(async_request_queue) if request_id not in async_request_queue: response = { 'status' : 'error', 'id' : request_id, 'body' : 'Request ID was not found' } response_body = json.dumps(response) respond(request_handler, response_body, 'text/json') else: async_thread = async_request_queue[request_id] gc.logger.debug('found async thread') gc.logger.debug(async_thread) if async_thread.is_alive(): gc.logger.debug('>>> request is not ready') print '>>>> NOT READY....' respond_with_async_request_id(request_handler, request_id) elif async_thread.is_alive() == False: gc.logger.debug('>>> request is probably ready, returning response!!') print '>>>> DONE!!!' async_request_queue.pop(request_id, None) # result = [] # for i in iter(queue.get, 'STOP'): # result.append(i) # time.sleep(.1) respond(request_handler, async_thread.response, 'text/json') def add_to_request_queue(request_id, p, q): async_request_queue[request_id] = { 'process' : p, 'queue' : q } def get_request_params(request_handler): print '>>>>>> ', request_handler.path print '>>>>>> ', request_handler.command #print '>>>>>> ', request_handler.headers if request_handler.command == 'POST': data_string = request_handler.rfile.read(int(request_handler.headers['Content-Length'])) #print '>>>>>>> ', data_string postvars = json.loads(data_string) if 'package' in postvars: postvars['package'] = json.dumps(postvars['package']) return postvars, data_string elif request_handler.command == 'GET': params = parse_qs(urlparse(request_handler.path).query) for key in params: params[key] = params[key][0] json_string = json.dumps(params) return params, json_string def process_request_in_background(worker): worker.run() ###################### ## RESPONSE METHODS ## ###################### #this returns the request id after an initial async request def respond_with_async_request_id(request_handler, request_id): gc.logger.debug('responding with async request id!') response = { 'status' : 'pending', 'id' : request_id } json_response_body = json.dumps(response) gc.logger.debug(json_response_body) respond(request_handler, json_response_body, 'text/json') def respond(request_handler, body, type='text/json'): gc.logger.debug('responding!') gc.logger.debug(body) #print '>>>>>>>> responding with, ' body request_handler.send_response(200) request_handler.send_header('Content-type', type) request_handler.send_header('Access-Control-Allow-Origin', '*') request_handler.end_headers() request_handler.wfile.write(body) return ################## ## PATH MAPPING ## ################## mappings = { '/status' : { 'GET' : status_request }, '/project' : { 'POST' : project_request }, '/project/edit' : { 'POST' : project_edit_request }, '/project/creds' : { 'POST' : update_credentials_request }, '/project/deploy' : { 'POST' : deploy_request }, '/project/unit_test' : { 'POST' : unit_test_request }, '/project/index' : { 'POST' : metadata_index_request }, '/project/conns/list' : { 'GET' : connections_list_request }, '/project/conns/new' : { 'POST' : connections_new_request }, '/project/conns/delete' : { 'POST' : connections_delete_request }, '/project/upgrade' : { 'POST' : project_upgrade_request }, '/session' : { 'GET' : get_active_session_request }, '/apex/execute' : { 'POST' : execute_apex_request }, '/metadata/list' : { 'GET' : metadata_list_request } } if __name__ == "__main__": # add freeze support multiprocessing.freeze_support()
from __future__ import unicode_literals import click from pyinfra import logger from .connectors import EXECUTION_CONNECTORS from .connectors.util import remove_any_sudo_askpass_file from .exceptions import ConnectError, PyinfraError from .facts import ( create_host_fact, delete_host_fact, get_fact_class, get_fact_names, get_host_fact, is_fact, ) # TODO: remove this! COMPAT w/<2 # This is the old-style `host.fact.<snake_case_name>` "magic" fact attributes # which have been replaced by the much cleaner `host.get_fact(fact_cls, *args, **kwargs)`. class HostFacts(object): def __init__(self, host=None): self.host = host def __dir__(self): return get_fact_names() def _check_host(self): if not self.host: raise TypeError('Cannot call this function with no host!') def __getattr__(self, key): self._check_host() if not is_fact(key): raise AttributeError('No such fact: {0}'.format(key)) # Ensure this host is connected connection = self.host.connect(reason='for {0} fact'.format(key)) # If we can't connect - fail immediately as we specifically need this # fact for this host and without it we cannot satisfy the deploy. if not connection: raise PyinfraError('Could not connect to {0} for fact {1}!'.format( self.host, key, )) # Expecting a function to return if callable(getattr(get_fact_class(key), 'command', None)): def wrapper(*args, **kwargs): return get_host_fact(self.host.state, self.host, key, args=args, kwargs=kwargs) return wrapper # Expecting the fact as a return value else: return get_host_fact(self.host.state, self.host, key) def _create(self, key, data=None, args=None): self._check_host() return create_host_fact(self.host.state, self.host, key, data, args) def _delete(self, key, args=None): self._check_host() return delete_host_fact(self.host.state, self.host, key, args) class Host(object): ''' Represents a target host. Thin class that links up to facts and host/group data. ''' connection = None state = None fact = HostFacts() # this isn't usable, but provides support for dir() def __init__( self, name, inventory, groups, data, executor=EXECUTION_CONNECTORS['ssh'], ): self.inventory = inventory self.groups = groups self.data = data self.executor = executor self.name = name # Attach the fact proxy self.fact = HostFacts(self) # Arbitrary dict for connector use self.connector_data = {} def __str__(self): return '{0}'.format(self.name) def __repr__(self): return 'Host({0})'.format(self.name) @property def connected(self): return self.connection is not None @property def host_data(self): return self.inventory.get_host_data(self.name) @property def group_data(self): return self.inventory.get_groups_data(self.groups) @property def print_prefix(self): return '{0}[{1}] '.format( click.style(''), # reset click.style(self.name, bold=True), ) def style_print_prefix(self, *args, **kwargs): return '{0}[{1}] '.format( click.style(''), # reset click.style(self.name, *args, **kwargs), ) def noop(self, description): ''' Log a description for a noop operation. ''' handler = logger.info if self.state.print_noop_info else logger.debug handler('{0}noop: {1}'.format(self.print_prefix, description)) # Host facts # def get_fact(self, name_or_cls, *args, **kwargs): return get_host_fact(self.state, self, name_or_cls, args=args, kwargs=kwargs) def create_fact(self, name_or_cls, data=None, kwargs=None): return create_host_fact(self.state, self, name_or_cls, data, kwargs=kwargs) def delete_fact(self, name_or_cls, kwargs=None): return delete_host_fact(self.state, self, name_or_cls, kwargs=kwargs) # Connector proxy # def _check_state(self): if not self.state: raise TypeError('Cannot call this function with no state!') def connect(self, reason=None, show_errors=True): self._check_state() if not self.connection: self.state.trigger_callbacks('host_before_connect', self) try: self.connection = self.executor.connect(self.state, self) except ConnectError as e: if show_errors: log_message = '{0}{1}'.format( self.print_prefix, click.style(e.args[0], 'red'), ) logger.error(log_message) self.state.trigger_callbacks('host_connect_error', self, e) else: log_message = '{0}{1}'.format( self.print_prefix, click.style('Connected', 'green'), ) if reason: log_message = '{0}{1}'.format( log_message, ' ({0})'.format(reason), ) logger.info(log_message) self.state.trigger_callbacks('host_connect', self) return self.connection def disconnect(self): self._check_state() # Disconnect is an optional function for executors if needed disconnect_func = getattr(self.executor, 'disconnect', None) if disconnect_func: return disconnect_func(self.state, self) # TODO: consider whether this should be here! remove_any_sudo_askpass_file(self) self.state.trigger_callbacks('host_disconnect', self) def run_shell_command(self, *args, **kwargs): self._check_state() return self.executor.run_shell_command(self.state, self, *args, **kwargs) def put_file(self, *args, **kwargs): self._check_state() return self.executor.put_file(self.state, self, *args, **kwargs) def get_file(self, *args, **kwargs): self._check_state() return self.executor.get_file(self.state, self, *args, **kwargs) # Rsync - optional executor specific ability def check_can_rsync(self): check_can_rsync_func = getattr(self.executor, 'check_can_rsync', None) if check_can_rsync_func: return check_can_rsync_func(self) raise NotImplementedError('The {0} connector does not support rsync!'.format( self.executor.__name__, )) def rsync(self, *args, **kwargs): self._check_state() return self.executor.rsync(self.state, self, *args, **kwargs)