gt
stringclasses
1 value
context
stringlengths
2.49k
119k
import socket import yaml import os from teuthology.util.compat import parse_qs from copy import deepcopy from libcloud.compute.providers import get_driver from mock import patch, Mock, DEFAULT from pytest import raises, mark from teuthology.config import config from teuthology.exceptions import MaxWhileTries from teuthology.provision import cloud test_config = dict( providers=dict( my_provider=dict( driver='openstack', driver_args=dict( username='user', password='password', ex_force_auth_url='http://127.0.0.1:9999/v2.0/tokens', ), ), image_exclude_provider=dict( driver='openstack', exclude_image=['.*-exclude1', '.*-exclude2'], driver_args=dict( username='user', password='password', ex_force_auth_url='http://127.0.0.1:9999/v2.0/tokens', ), ) ) ) @patch('time.sleep') def test_retry(m_sleep): orig_exceptions = cloud.openstack.RETRY_EXCEPTIONS new_exceptions = orig_exceptions + (RuntimeError, ) class test_cls(object): def __init__(self, min_val): self.min_val = min_val self.cur_val = 0 def func(self): self.cur_val += 1 if self.cur_val < self.min_val: raise RuntimeError return self.cur_val with patch.object( cloud.openstack, 'RETRY_EXCEPTIONS', new=new_exceptions, ): test_obj = test_cls(min_val=5) assert cloud.openstack.retry(test_obj.func) == 5 test_obj = test_cls(min_val=1000) with raises(MaxWhileTries): cloud.openstack.retry(test_obj.func) def get_fake_obj(mock_args=None, attributes=None): if mock_args is None: mock_args = dict() if attributes is None: attributes = dict() obj = Mock(**mock_args) for name, value in attributes.items(): setattr(obj, name, value) return obj class TestOpenStackBase(object): def setup(self, conf=dict(), test_config=test_config): config.load(conf or dict(libcloud=deepcopy(test_config))) self.start_patchers() def start_patchers(self): self.patchers = dict() self.patchers['m_list_images'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.list_images' ) self.patchers['m_list_sizes'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.list_sizes' ) self.patchers['m_ex_list_networks'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStack_1_1_NodeDriver.ex_list_networks' ) self.patchers['m_ex_list_security_groups'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStack_1_1_NodeDriver.ex_list_security_groups' ) self.patchers['m_get_user_ssh_pubkey'] = patch( 'teuthology.provision.cloud.util.get_user_ssh_pubkey' ) self.patchers['m_list_nodes'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.list_nodes' ) self.patchers['m_create_node'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStack_1_1_NodeDriver.create_node' ) self.patchers['m_wait_until_running'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.wait_until_running' ) self.patchers['m_create_volume'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.create_volume' ) self.patchers['m_attach_volume'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.attach_volume' ) self.patchers['m_detach_volume'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.detach_volume' ) self.patchers['m_list_volumes'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.list_volumes' ) self.patchers['m_destroy_volume'] = patch( 'libcloud.compute.drivers.openstack' '.OpenStackNodeDriver.destroy_volume' ) self.patchers['m_get_service_catalog'] = patch( 'libcloud.common.openstack' '.OpenStackBaseConnection.get_service_catalog' ) self.patchers['m_auth_token'] = patch( 'teuthology.provision.cloud.util.AuthToken' ) self.patchers['m_get_endpoint'] = patch( 'libcloud.common.openstack' '.OpenStackBaseConnection.get_endpoint', ) self.patchers['m_connect'] = patch( 'libcloud.common.base' '.Connection.connect', ) self.patchers['m_sleep'] = patch( 'time.sleep' ) self.patchers['m_get'] = patch( 'requests.get' ) self.mocks = dict() for name, patcher in self.patchers.items(): self.mocks[name] = patcher.start() self.mocks['m_get_endpoint'].return_value = 'endpoint' def teardown(self): for patcher in self.patchers.values(): patcher.stop() class TestOpenStackProvider(TestOpenStackBase): klass = cloud.openstack.OpenStackProvider def test_init(self): obj = cloud.get_provider('my_provider') assert obj.name == 'my_provider' assert obj.driver_name == 'openstack' assert obj.conf == test_config['providers']['my_provider'] def test_driver(self): token = self.mocks['m_auth_token'].return_value self.mocks['m_auth_token'].return_value.__enter__.return_value = token token.value = None obj = cloud.get_provider('my_provider') assert isinstance(obj.driver, get_driver('openstack')) assert obj._auth_token.value is None def test_images(self): obj = cloud.get_provider('my_provider') self.mocks['m_list_images'].return_value = [ get_fake_obj(attributes=dict(name=_)) for _ in ['image0', 'image1']] assert not hasattr(obj, '_images') assert [_.name for _ in obj.images] == ['image0', 'image1'] assert hasattr(obj, '_images') def test_exclude_image(self): obj = cloud.get_provider('image_exclude_provider') self.mocks['m_list_images'].return_value = [ get_fake_obj(attributes=dict(name=_)) for _ in ['image0', 'image1', 'image2-exclude1', 'image3-exclude2']] assert not hasattr(obj, '_images') assert [_.name for _ in obj.images] == ['image0', 'image1'] assert hasattr(obj, '_images') def test_sizes(self): obj = cloud.get_provider('my_provider') fake_sizes = [get_fake_obj(attributes=dict(name='size%s' % i)) for i in range(2)] self.mocks['m_list_sizes'].return_value = fake_sizes assert not hasattr(obj, '_sizes') assert [s.name for s in obj.sizes] == ['size0', 'size1'] assert hasattr(obj, '_sizes') def test_networks(self): obj = cloud.get_provider('my_provider') nets = [get_fake_obj(attributes=dict(name=i)) for i in ['net0', 'net1']] self.mocks['m_ex_list_networks'].return_value = nets assert not hasattr(obj, '_networks') assert [i.name for i in obj.networks] == [i.name for i in nets] assert hasattr(obj, '_networks') self.mocks['m_ex_list_networks'].side_effect = AttributeError obj = cloud.get_provider('my_provider') assert not hasattr(obj, '_networks') assert obj.networks == list() assert hasattr(obj, '_networks') def test_security_groups(self): obj = cloud.get_provider('my_provider') self.mocks['m_ex_list_security_groups'].return_value = ['sg0', 'sg1'] assert not hasattr(obj, '_security_groups') assert obj.security_groups == ['sg0', 'sg1'] assert hasattr(obj, '_security_groups') self.mocks['m_ex_list_security_groups'].side_effect = AttributeError obj = cloud.get_provider('my_provider') assert not hasattr(obj, '_security_groups') assert obj.security_groups == list() assert hasattr(obj, '_security_groups') class TestOpenStackCustomProvisioner(TestOpenStackBase): klass = cloud.openstack.OpenStackProvisioner def get_obj( self, name='node_name', os_type='ubuntu', os_version='16.04', conf=None, test_conf=None): if test_conf: yaml_file = os.path.dirname(__file__) + '/' + test_conf print("Reading conf: %s" % yaml_file) with open(yaml_file) as f: teuth_conf=yaml.safe_load(f) print(teuth_conf) config.libcloud = deepcopy(teuth_conf['libcloud'] or test_config) else: config.libcloud = deepcopy(test_config) return cloud.get_provisioner( node_type='my_provider', name=name, os_type=os_type, os_version=os_version, conf=conf, ) @mark.parametrize( "conf", [ dict( path='test_openstack_userdata_conf.yaml', runcmd_head=['uptime', 'date'], ssh_authorized_keys=['user_public_key1', 'user_public_key2'], user_ssh_pubkey='my_ssh_key', os_version='16.04', os_type='ubuntu', ), dict( path='test_openstack_userdata_conf.yaml', runcmd_head=['uptime', 'date'], ssh_authorized_keys=['user_public_key1', 'user_public_key2'], user_ssh_pubkey=None, os_version='16.04', os_type='ubuntu', ), dict( os_version='16.04', os_type='ubuntu', path=None, user_ssh_pubkey=None, ), ] ) def test_userdata_conf(self, conf): self.mocks['m_get_user_ssh_pubkey'].return_value = conf['user_ssh_pubkey'] obj = self.get_obj(os_version=conf['os_version'], os_type=conf['os_type'], test_conf=conf['path']) userdata = yaml.safe_load(obj.userdata) print(">>>> ", obj.conf) print(">>>> ", obj.provider.conf) print(">>>> ", obj.provider) print(obj.userdata) if conf and 'path' in conf and conf['path']: assert userdata['runcmd'][0:len(conf['runcmd_head'])] == conf['runcmd_head'] assert userdata['bootcmd'] == [ 'SuSEfirewall2 stop || true', 'service firewalld stop || true', ] assert 'packages' not in userdata else: assert 'bootcmd' not in userdata assert userdata['packages'] == ['git', 'wget', 'python', 'ntp'] assert userdata['user'] == obj.user assert userdata['hostname'] == obj.hostname if 'user_ssh_pubkey' in conf and conf['user_ssh_pubkey']: assert userdata['ssh_authorized_keys'][-1] == conf['user_ssh_pubkey'] if 'ssh_authorized_keys' in conf: keys = conf['ssh_authorized_keys'] assert userdata['ssh_authorized_keys'][0:len(keys)] == keys else: if 'ssh_authorized_keys' in conf: keys = conf['ssh_authorized_keys'] assert userdata['ssh_authorized_keys'][0:len(keys)] == keys else: assert 'ssh_authorized_keys' not in userdata @mark.parametrize( "conf", [ dict( path='test_openstack_userdata_conf.yaml', runcmd_head=['uptime', 'date'], ), dict( path=None, ), ] ) def test_userdata_conf_runcmd(self, conf): self.mocks['m_get_user_ssh_pubkey'].return_value = None obj = self.get_obj(test_conf=conf['path']) userdata = yaml.safe_load(obj.userdata) assert userdata['runcmd'][-2:] == [['passwd', '-d', 'ubuntu'], ['touch', '/.teuth_provisioned']] @mark.parametrize( "conf", [ dict( path='test_openstack_userdata_conf.yaml', packages=None, ), dict( path=None, packages=['git', 'wget', 'python', 'ntp'] ), ] ) def test_userdata_conf_packages(self, conf): self.mocks['m_get_user_ssh_pubkey'].return_value = None obj = self.get_obj(test_conf=conf['path']) userdata = yaml.safe_load(obj.userdata) assert userdata.get('packages', None) == conf['packages'] class TestOpenStackProvisioner(TestOpenStackBase): klass = cloud.openstack.OpenStackProvisioner def get_obj( self, name='node_name', os_type='ubuntu', os_version='16.04', conf=None): return cloud.get_provisioner( node_type='my_provider', name=name, os_type=os_type, os_version=os_version, conf=conf, ) def test_init(self): with patch.object( self.klass, '_read_conf', ) as m_read_conf: self.get_obj() assert len(m_read_conf.call_args_list) == 1 @mark.parametrize( 'input_conf', [ dict(machine=dict( disk=42, ram=9001, cpus=3, )), dict(volumes=dict( count=3, size=100, )), dict(), dict( machine=dict( disk=1, ram=2, cpus=3, ), volumes=dict( count=4, size=5, ) ), dict( machine=dict( disk=100, ), ), ] ) def test_read_conf(self, input_conf): obj = self.get_obj(conf=input_conf) for topic in ['machine', 'volumes']: combined = cloud.util.combine_dicts( [input_conf, config.openstack], lambda x, y: x > y, ) assert obj.conf[topic] == combined[topic] @mark.parametrize( 'input_conf, expected_machine, expected_vols', [ [ dict(openstack=[ dict(machine=dict(disk=64, ram=10000, cpus=3)), dict(volumes=dict(count=1, size=1)), ]), dict(disk=64, ram=10000, cpus=3), dict(count=1, size=1), ], [ dict(openstack=[ dict(machine=dict(cpus=3)), dict(machine=dict(disk=1, ram=9000)), dict(machine=dict(disk=50, ram=2, cpus=1)), dict(machine=dict()), dict(volumes=dict()), dict(volumes=dict(count=0, size=0)), dict(volumes=dict(count=1, size=0)), dict(volumes=dict(size=1)), ]), dict(disk=50, ram=9000, cpus=3), dict(count=1, size=1), ], [ dict(openstack=[ dict(volumes=dict(count=3, size=30)), dict(volumes=dict(size=50)), ]), None, dict(count=3, size=50), ], [ dict(openstack=[ dict(machine=dict(disk=100)), dict(volumes=dict(count=3, size=30)), ]), dict(disk=100, ram=8000, cpus=1), dict(count=3, size=30), ], ] ) def test_read_conf_legacy( self, input_conf, expected_machine, expected_vols): obj = self.get_obj(conf=input_conf) if expected_machine is not None: assert obj.conf['machine'] == expected_machine else: assert obj.conf['machine'] == config.openstack['machine'] if expected_vols is not None: assert obj.conf['volumes'] == expected_vols @mark.parametrize( "os_type, os_version, should_find", [ ('centos', '7', True), ('BeOS', '42', False), ] ) def test_image(self, os_type, os_version, should_find): image_attrs = [ dict(name='ubuntu-14.04'), dict(name='ubuntu-16.04'), dict(name='centos-7.0'), ] fake_images = list() for item in image_attrs: fake_images.append( get_fake_obj(attributes=item) ) obj = self.get_obj(os_type=os_type, os_version=os_version) self.mocks['m_list_images'].return_value = fake_images if should_find: assert obj.os_version in obj.image.name assert obj.image in fake_images else: with raises(RuntimeError): obj.image @mark.parametrize( "input_attrs, func_or_exc", [ (dict(ram=2**16), lambda s: s.ram == 2**16), (dict(disk=9999), lambda s: s.disk == 9999), (dict(cpus=99), lambda s: s.vcpus == 99), (dict(ram=2**16, disk=9999, cpus=99), IndexError), ] ) def test_size(self, input_attrs, func_or_exc): size_attrs = [ dict(ram=8000, disk=9999, vcpus=99, name='s0'), dict(ram=2**16, disk=20, vcpus=99, name='s1'), dict(ram=2**16, disk=9999, vcpus=1, name='s2'), ] fake_sizes = list() for item in size_attrs: fake_sizes.append( get_fake_obj(attributes=item) ) base_spec = dict(machine=dict( ram=1, disk=1, cpus=1, )) spec = deepcopy(base_spec) spec['machine'].update(input_attrs) obj = self.get_obj(conf=spec) self.mocks['m_list_sizes'].return_value = fake_sizes if isinstance(func_or_exc, type): with raises(func_or_exc): obj.size else: assert obj.size in fake_sizes assert func_or_exc(obj.size) is True @mark.parametrize( "wanted_groups", [ ['group1'], ['group0', 'group2'], [], ] ) def test_security_groups(self, wanted_groups): group_names = ['group0', 'group1', 'group2'] fake_groups = list() for name in group_names: fake_groups.append( get_fake_obj(attributes=dict(name=name)) ) self.mocks['m_ex_list_security_groups'].return_value = fake_groups obj = self.get_obj() assert obj.security_groups is None obj = self.get_obj() obj.provider.conf['security_groups'] = wanted_groups assert [g.name for g in obj.security_groups] == wanted_groups def test_security_groups_exc(self): fake_groups = [ get_fake_obj(attributes=dict(name='sg')) for i in range(2) ] obj = self.get_obj() obj.provider.conf['security_groups'] = ['sg'] with raises(RuntimeError): obj.security_groups self.mocks['m_ex_list_security_groups'].return_value = fake_groups obj = self.get_obj() obj.provider.conf['security_groups'] = ['sg'] with raises(RuntimeError): obj.security_groups @mark.parametrize( "ssh_key", [ 'my_ssh_key', None, ] ) def test_userdata(self, ssh_key): self.mocks['m_get_user_ssh_pubkey'].return_value = ssh_key obj = self.get_obj() userdata = yaml.safe_load(obj.userdata) assert userdata['user'] == obj.user assert userdata['hostname'] == obj.hostname if ssh_key: assert userdata['ssh_authorized_keys'] == [ssh_key] else: assert 'ssh_authorized_keys' not in userdata @mark.parametrize( 'wanted_name, should_find, exception', [ ('node0', True, None), ('node1', True, None), ('node2', False, RuntimeError), ('node3', False, None), ] ) def test_node(self, wanted_name, should_find, exception): node_names = ['node0', 'node1', 'node2', 'node2'] fake_nodes = list() for name in node_names: fake_nodes.append( get_fake_obj(attributes=dict(name=name)) ) self.mocks['m_list_nodes'].return_value = fake_nodes obj = self.get_obj(name=wanted_name) if should_find: assert obj.node.name == wanted_name elif exception: with raises(exception) as excinfo: obj.node assert excinfo.value.message else: assert obj.node is None @mark.parametrize( 'networks, security_groups', [ ([], []), (['net0'], []), ([], ['sg0']), (['net0'], ['sg0']), ] ) def test_create(self, networks, security_groups): node_name = 'node0' fake_sizes = [ get_fake_obj( attributes=dict(ram=2**16, disk=9999, vcpus=99, name='s0')), ] fake_security_groups = [ get_fake_obj(attributes=dict(name=name)) for name in security_groups ] self.mocks['m_ex_list_networks'].return_value = networks self.mocks['m_ex_list_security_groups'].return_value = \ fake_security_groups self.mocks['m_list_sizes'].return_value = fake_sizes fake_images = [ get_fake_obj(attributes=dict(name='ubuntu-16.04')), ] self.mocks['m_list_images'].return_value = fake_images self.mocks['m_get_user_ssh_pubkey'].return_value = 'ssh_key' fake_node = get_fake_obj(attributes=dict(name=node_name)) fake_ips = ['555.123.4.0'] self.mocks['m_create_node'].return_value = fake_node self.mocks['m_wait_until_running'].return_value = \ [(fake_node, fake_ips)] obj = self.get_obj(name=node_name) obj._networks = networks obj.provider.conf['security_groups'] = security_groups p_wait_for_ready = patch( 'teuthology.provision.cloud.openstack.OpenStackProvisioner' '._wait_for_ready' ) with p_wait_for_ready: res = obj.create() assert res is obj.node # Test once again to ensure that if volume creation/attachment fails, # we destroy any remaining volumes and consider the node creation to # have failed as well. del obj._node with p_wait_for_ready: obj.conf['volumes']['count'] = 1 obj.provider.driver.create_volume.side_effect = Exception with patch.object(obj, '_destroy_volumes'): assert obj.create() is False assert obj._destroy_volumes.called_once_with() def test_update_dns(self): config.nsupdate_url = 'nsupdate_url' obj = self.get_obj() obj.name = 'x' obj.ips = ['y'] obj._update_dns() call_args = self.mocks['m_get'].call_args_list assert len(call_args) == 1 url_base, query_string = call_args[0][0][0].split('?') assert url_base == 'nsupdate_url' parsed_query = parse_qs(query_string) assert parsed_query == dict(name=['x'], ip=['y']) @mark.parametrize( 'nodes', [[], [Mock()], [Mock(), Mock()]] ) def test_destroy(self, nodes): with patch( 'teuthology.provision.cloud.openstack.' 'OpenStackProvisioner._find_nodes' ) as m_find_nodes: m_find_nodes.return_value = nodes obj = self.get_obj() result = obj.destroy() if not all(nodes): assert result is True else: for node in nodes: assert node.destroy.called_once_with() _volume_matrix = ( 'count, size, should_succeed', [ (1, 10, True), (0, 10, True), (10, 1, True), (1, 10, False), (10, 1, False), ] ) @mark.parametrize(*_volume_matrix) def test_create_volumes(self, count, size, should_succeed): obj_conf = dict(volumes=dict(count=count, size=size)) obj = self.get_obj(conf=obj_conf) node = get_fake_obj() if not should_succeed: obj.provider.driver.create_volume.side_effect = Exception obj._node = node result = obj._create_volumes() assert result is should_succeed if should_succeed: create_calls = obj.provider.driver.create_volume.call_args_list attach_calls = obj.provider.driver.attach_volume.call_args_list assert len(create_calls) == count assert len(attach_calls) == count for i in range(count): vol_size, vol_name = create_calls[i][0] assert vol_size == size assert vol_name == '%s_%s' % (obj.name, i) assert attach_calls[i][0][0] is obj._node assert attach_calls[i][1]['device'] is None @mark.parametrize(*_volume_matrix) def test_destroy_volumes(self, count, size, should_succeed): obj_conf = dict(volumes=dict(count=count, size=size)) obj = self.get_obj(conf=obj_conf) fake_volumes = list() for i in range(count): vol_name = '%s_%s' % (obj.name, i) fake_volumes.append( get_fake_obj(attributes=dict(name=vol_name)) ) obj.provider.driver.list_volumes.return_value = fake_volumes obj._destroy_volumes() detach_calls = obj.provider.driver.detach_volume.call_args_list destroy_calls = obj.provider.driver.destroy_volume.call_args_list assert len(detach_calls) == count assert len(destroy_calls) == count assert len(obj.provider.driver.detach_volume.call_args_list) == count assert len(obj.provider.driver.destroy_volume.call_args_list) == count obj.provider.driver.detach_volume.reset_mock() obj.provider.driver.destroy_volume.reset_mock() obj.provider.driver.detach_volume.side_effect = Exception obj.provider.driver.destroy_volume.side_effect = Exception obj._destroy_volumes() assert len(obj.provider.driver.detach_volume.call_args_list) == count assert len(obj.provider.driver.destroy_volume.call_args_list) == count def test_destroy_volumes_exc(self): obj = self.get_obj() obj.provider.driver.detach_volume.side_effect = Exception def test_wait_for_ready(self): obj = self.get_obj() obj._node = get_fake_obj(attributes=dict(name='node_name')) with patch.multiple( 'teuthology.orchestra.remote.Remote', connect=DEFAULT, run=DEFAULT, ) as mocks: obj._wait_for_ready() mocks['connect'].side_effect = socket.error with raises(MaxWhileTries): obj._wait_for_ready()
# 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. """ .. _tutorial-deploy-model-on-android: Deploy the Pretrained Model on Android ======================================= **Author**: `Tomohiro Kato <https://tkat0.github.io/>`_ This is an example of using Relay to compile a keras model and deploy it on Android device. """ import os import numpy as np from PIL import Image import keras from keras.applications.mobilenet_v2 import MobileNetV2 import tvm import tvm.relay as relay from tvm import rpc from tvm.contrib import util, ndk, graph_runtime as runtime from tvm.contrib.download import download_testdata ###################################################################### # Setup Environment # -------------------- # Since there are many required packages for Android, it is recommended to use the official Docker Image. # # First, to build and run Docker Image, we can run the following command. # # .. code-block:: bash # # git clone --recursive https://github.com/dmlc/tvm # cd tvm # docker build -t tvm.demo_android -f docker/Dockerfile.demo_android ./docker # docker run --pid=host -h tvm -v $PWD:/workspace \ # -w /workspace -p 9190:9190 --name tvm -it tvm.demo_android bash # # You are now inside the container. The cloned TVM directory is mounted on /workspace. # At this time, mount the 9190 port used by RPC described later. # # .. note:: # # Please execute the following steps in the container. # We can execute :code:`docker exec -it tvm bash` to open a new terminal in the container. # # Next we build the TVM. # # .. code-block:: bash # # mkdir build # cd build # cmake -DUSE_LLVM=llvm-config-8 \ # -DUSE_RPC=ON \ # -DUSE_SORT=ON \ # -DUSE_VULKAN=ON \ # -DUSE_GRAPH_RUNTIME=ON \ # .. # make -j10 # # After building TVM successfully, Please set PYTHONPATH. # # .. code-block:: bash # # echo 'export PYTHONPATH=/workspace/python:/workspacem/topi/python:/workspace/nnvm/python/:/workspace/vta/python:${PYTHONPATH}' >> ~/.bashrc # source ~/.bashrc ################################################################# # Start RPC Tracker # ----------------- # TVM uses RPC session to communicate with Android device. # # To start an RPC tracker, run this command in the container. The tracker is # required during the whole tuning process, so we need to open a new terminal for # this command: # # .. code-block:: bash # # python3 -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190 # # The expected output is # # .. code-block:: bash # # INFO:RPCTracker:bind to 0.0.0.0:9190 ################################################################# # Register Android device to RPC Tracker # --------------------------------------- # Now we can register our Android device to the tracker. # # Follow this `readme page <https://github.com/dmlc/tvm/tree/master/apps/android_rpc>`_ to # install TVM RPC APK on the android device. # # Here is an example of config.mk. I enabled OpenCL and Vulkan. # # # .. code-block:: bash # # APP_ABI = arm64-v8a # # APP_PLATFORM = android-24 # # # whether enable OpenCL during compile # USE_OPENCL = 1 # # # whether to enable Vulkan during compile # USE_VULKAN = 1 # # ifeq ($(USE_VULKAN), 1) # # Statically linking vulkan requires API Level 24 or higher # APP_PLATFORM = android-24 # endif # # # the additional include headers you want to add, e.g., SDK_PATH/adrenosdk/Development/Inc # ADD_C_INCLUDES += /work/adrenosdk-linux-5_0/Development/Inc # # downloaded from https://github.com/KhronosGroup/OpenCL-Headers # ADD_C_INCLUDES += /usr/local/OpenCL-Headers/ # # # the additional link libs you want to add, e.g., ANDROID_LIB_PATH/libOpenCL.so # ADD_LDLIBS = /workspace/pull-from-android-device/libOpenCL.so # # .. note:: # # At this time, don't forget to `create a standalone toolchain <https://github.com/dmlc/tvm/tree/master/apps/android_rpc#architecture-and-android-standalone-toolchain>`_ . # # for example # # .. code-block:: bash # # /opt/android-sdk-linux/ndk-bundle/build/tools/make-standalone-toolchain.sh \ # --platform=android-24 --use-llvm --arch=arm64 --install-dir=/opt/android-toolchain-arm64 # export TVM_NDK_CC=/opt/android-toolchain-arm64/bin/aarch64-linux-android-g++ # # Next, start the Android application and enter the IP address and port of RPC Tracker. # Then you have already registered your device. # # After registering devices, we can confirm it by querying rpc_tracker # # .. code-block:: bash # # python3 -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190 # # For example, if we have 1 Android device. # the output can be # # .. code-block:: bash # # Queue Status # ---------------------------------- # key total free pending # ---------------------------------- # android 1 1 0 # ---------------------------------- # # To confirm that you can communicate with Android, we can run following test script. # If you use OpenCL and Vulkan, please set :code:`test_opencl` and :code:`test_vulkan` in the script. # # .. code-block:: bash # # export TVM_TRACKER_HOST=0.0.0.0 # export TVM_TRACKER_PORT=9190 # # .. code-block:: bash # # cd /workspace/apps/android_rpc # python3 tests/android_rpc_test.py # ###################################################################### # Load pretrained keras model # ---------------------------- # We load a pretrained MobileNetV2(alpha=0.5) classification model provided by keras. keras.backend.clear_session() # Destroys the current TF graph and creates a new one. weights_url = ''.join(['https://github.com/JonathanCMitchell/', 'mobilenet_v2_keras/releases/download/v1.1/', 'mobilenet_v2_weights_tf_dim_ordering_tf_kernels_0.5_224.h5']) weights_file = 'mobilenet_v2_weights.h5' weights_path = download_testdata(weights_url, weights_file, module='keras') keras_mobilenet_v2 = MobileNetV2(alpha=0.5, include_top=True, weights=None, input_shape=(224, 224, 3), classes=1000) keras_mobilenet_v2.load_weights(weights_path) ###################################################################### # In order to test our model, here we download an image of cat and # transform its format. img_url = 'https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true' img_name = 'cat.png' img_path = download_testdata(img_url, img_name, module='data') image = Image.open(img_path).resize((224, 224)) dtype = 'float32' def transform_image(image): image = np.array(image) - np.array([123., 117., 104.]) image /= np.array([58.395, 57.12, 57.375]) image = image.transpose((2, 0, 1)) image = image[np.newaxis, :] return image x = transform_image(image) ###################################################################### # synset is used to transform the label from number of ImageNet class to # the word human can understand. synset_url = ''.join(['https://gist.githubusercontent.com/zhreshold/', '4d0b62f3d01426887599d4f7ede23ee5/raw/', '596b27d23537e5a1b5751d2b0481ef172f58b539/', 'imagenet1000_clsid_to_human.txt']) synset_name = 'imagenet1000_clsid_to_human.txt' synset_path = download_testdata(synset_url, synset_name, module='data') with open(synset_path) as f: synset = eval(f.read()) ###################################################################### # Compile the model with relay # --------------------------------------------- # If we run the example on our x86 server for demonstration, we can simply # set it as :code:`llvm`. If running it on the Android device, we need to # specify its instruction set. Set :code:`local_demo` to False if you want # to run this tutorial with a real device. local_demo = True # by default on CPU target will execute. # select 'cpu', 'opencl' and 'vulkan' test_target = 'cpu' # Change target configuration. # Run `adb shell cat /proc/cpuinfo` to find the arch. arch = 'arm64' target = 'llvm -target=%s-linux-android' % arch target_host = None if local_demo: target_host = None target = 'llvm' elif test_target == 'opencl': target_host = target target = 'opencl' elif test_target == 'vulkan': target_host = target target = 'vulkan' input_name = 'input_1' shape_dict = {input_name: x.shape} mod, params = relay.frontend.from_keras(keras_mobilenet_v2, shape_dict) with relay.build_config(opt_level=3): graph, lib, params = relay.build(mod, target=target, target_host=target_host, params=params) # After `relay.build`, you will get three return values: graph, # library and the new parameter, since we do some optimization that will # change the parameters but keep the result of model as the same. # Save the library at local temporary directory. tmp = util.tempdir() lib_fname = tmp.relpath('net.so') fcompile = ndk.create_shared if not local_demo else None lib.export_library(lib_fname, fcompile) ###################################################################### # Deploy the Model Remotely by RPC # --------------------------------------------- # With RPC, you can deploy the model remotely from your host machine # to the remote android device. tracker_host = os.environ.get('TVM_TRACKER_HOST', '0.0.0.0') tracker_port = int(os.environ.get('TVM_TRACKER_PORT', 9190)) key = 'android' if local_demo: remote = rpc.LocalSession() else: tracker = rpc.connect_tracker(tracker_host, tracker_port) # When running a heavy model, we should increase the `session_timeout` remote = tracker.request(key, priority=0, session_timeout=60) if local_demo: ctx = remote.cpu(0) elif test_target == 'opencl': ctx = remote.cl(0) elif test_target == 'vulkan': ctx = remote.vulkan(0) else: ctx = remote.cpu(0) # upload the library to remote device and load it remote.upload(lib_fname) rlib = remote.load_module('net.so') # create the remote runtime module module = runtime.create(graph, rlib, ctx) ###################################################################### # Execute on TVM # --------------------------------------------- # set parameter (upload params to the remote device. This may take a while) module.set_input(**params) # set input data module.set_input(input_name, tvm.nd.array(x.astype(dtype))) # run module.run() # get output out = module.get_output(0) # get top1 result top1 = np.argmax(out.asnumpy()) print('TVM prediction top-1: {}'.format(synset[top1])) print('Evaluate inference time cost...') ftimer = module.module.time_evaluator('run', ctx, number=1, repeat=10) prof_res = np.array(ftimer().results) * 1000 # convert to millisecond print('Mean inference time (std dev): %.2f ms (%.2f ms)' % (np.mean(prof_res), np.std(prof_res))) ###################################################################### # Sample Output # --------------------------------------------- # The following is the result of 'cpu', 'opencl' and 'vulkan' using Adreno 530 on Snapdragon 820 # # Although we can run on a GPU, it is slower than CPU. # To speed up, we need to write and optimize the schedule according to the GPU architecture. # # .. code-block:: bash # # # cpu # TVM prediction top-1: tiger cat # Evaluate inference time cost... # Mean inference time (std dev): 37.92 ms (19.67 ms) # # # opencl # TVM prediction top-1: tiger cat # Evaluate inference time cost... # Mean inference time (std dev): 419.83 ms (7.49 ms) # # # vulkan # TVM prediction top-1: tiger cat # Evaluate inference time cost... # Mean inference time (std dev): 465.80 ms (4.52 ms)
"""python 2.7 plugin for substance painter 2.3+ Export substance painter maps to a RenderMan Asset package. """ # ----------------------------------------------------------------------------- # MIT License # # Copyright (c) 2016 Philippe Leprince # # 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. # ----------------------------------------------------------------------------- # standard imports first import os import os.path import sys import re import json import shutil import logging import getpass import subprocess THIS_DIR = os.path.dirname(os.path.realpath(__file__)) LOGFILE = os.path.join(THIS_DIR, 'rfsp_log.txt') logging.basicConfig(filename=LOGFILE, filemode='w', level=logging.DEBUG, format='%(levelname)-10s %(message)s') DBUG = logging.debug INFO = logging.info WARN = logging.warning ERR = logging.error XCPT = logging.exception IMG_EXTS = ['.png', '.jpg', '.exr'] TEX_EXTS = ['.tex', '.tx', '.txr'] class FilePath(unicode): """A class based on unicode to handle filepaths on various OS platforms. Extends: unicode """ def __new__(cls, path): """Create new unicode file path in POSIX format. Windows paths will be converted. Arguments: path {str} -- a file path, in any format. """ fpath = path if os.sep is not '/': fpath = fpath.replace(os.sep, '/') return unicode.__new__(cls, fpath) def osPath(self): """return the platform-specif path, i.e. convert to windows format if need be. Returns: str -- a path formatted for the current OS. """ return r'%s' % os.path.normpath(self) def exists(self): """Check is the path actually exists, using os.path. Returns: bool -- True if the path exists. """ return os.path.exists(self) def join(self, *args): """Combine the arguments with the current path and return a new FilePath object. Arguments: *args {list} -- a list of path segments. Returns: FilePath -- A new object containing the joined path. """ return FilePath(os.path.join(self, *args)) def dirname(self): """Returns the dirname of the current path (using os.path.dirname) as a FilePath object. Returns: FilePath -- the path's directory name. """ return FilePath(os.path.dirname(self)) def basename(self): """Return the basename, i.e. '/path/to/file.ext' -> 'file.ext' Returns: str -- The final segment of the path. """ return os.path.basename(self) def isWritable(self): """Checks if the path is writable. The Write and Execute bits must be enabled. Returns: bool -- True is writable """ return os.access(self, os.W_OK | os.X_OK) # functions ------------------------------------------------------------------- def readJson(fpath): """Read a json file without exception handling. Arguments: fpath {str} -- full path to json file Returns: dict -- json data """ with open(fpath, 'r') as fhdl: data = json.load(fhdl) return data def setup_environment(jsonDict): """make sure that RMANTREE and RMSTREE are defined in our environment and we can import our python module. Arguments: jsonDict {dict} -- json data Returns: tuple -- (rmanAssets, rman_version) """ rmantree = FilePath(jsonDict['RMANTREE']) rmstree = FilePath(jsonDict['RMSTREE']) if not rmantree in os.environ: os.environ['RMANTREE'] = rmantree.osPath() if not rmstree in os.environ: os.environ['RMSTREE'] = rmstree.osPath() rman_version = float(re.search(r'RenderManProServer-(\d+\.\d+)', rmantree).group(1)) rmstree_py = rmstree.join(rmstree, "scripts") if int(rman_version) == 21: if rmstree_py not in sys.path: sys.path.append(rmstree_py) else: rmantree_py = rmantree.join(rmantree, "bin") if rmstree_py not in sys.path: sys.path.insert(0, rmstree_py) if rmantree_py not in sys.path: sys.path.insert(0, rmantree_py) return rman_version def set_params(settings_dict, chan, node_name, asset): # The bxdf may need specific settings to match Substance Painter try: params = settings_dict[chan] except (KeyError, TypeError): pass else: for pname, pdict in params.iteritems(): asset.addParam(node_name, pname, pdict) DBUG(' |_ param: %s %s = %s', pdict['type'], pname, pdict['value']) def add_texture_node(asset, node_name, ntype, filepath): asset.addNode(node_name, ntype, 'pattern', ntype) pdict = {'type': 'string', 'value': filepath} asset.addParam(node_name, 'filename', pdict) if '_MAPID_' in filepath: asset.addParam(node_name, 'atlasStyle', {'type': 'int', 'value': 1}) def set_metadata(asset, mat_dict): meta = asset.stdMetadata() meta['author'] = getpass.getuser() meta['description'] = 'Created by RenderMan for Substance Painter 0.3.0' meta['resolution'] = '%d x %d' % (mat_dict['resolution'][0], mat_dict['resolution'][1]) for k, v in meta.iteritems(): asset.addMetadata(k, v) def startupInfo(): """Returns a Windows-only object to make sure tasks launched through subprocess don't open a cmd window. Returns: subprocess.STARTUPINFO -- the properly configured object if we are on Windows, otherwise None """ startupinfo = None if os.name is 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return startupinfo def app(name): if os.name is 'nt': return (name + '.exe') return name def txmake(is_udim, asset_path, fpath_list): rmantree = FilePath(os.environ['RMANTREE']) binary = rmantree.join('bin', app('txmake')).osPath() cmd = [binary] if is_udim: cmd += ['-resize', 'round-', '-mode', 'clamp', '-format', 'pixar', '-compression', 'lossless', '-newer', 'src', 'dst'] else: cmd += ['-resize', 'round-', '-mode', 'periodic', '-format', 'pixar', '-compression', 'lossless', '-newer', 'src', 'dst'] for img in fpath_list: cmd[-2] = FilePath(img).osPath() dirname, filename = os.path.split(img) texfile = os.path.splitext(filename)[0] + '.tex' cmd[-1] = asset_path.join(texfile).osPath() DBUG(' |_ txmake : %s -> %s', cmd[-2], cmd[-1]) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupInfo()) p.wait() # return a local path to the tex file. dirname, filename = os.path.split(fpath_list[0]) fname, fext = os.path.splitext(filename) asset_file_ref = FilePath(dirname).join(fname + '.tex') if is_udim: asset_file_ref = re.sub(r'1\d{3}', '_MAPID_', asset_file_ref) return asset_file_ref def export(): """Export a RenderManAsset package based on a json file. """ INFO('Start !') if len(sys.argv) < 2: ERR('expecting 2 arguments !') raise Exception # get the input json file jsonFile = FilePath(sys.argv[1].replace('"', '')) # import json file jsonDict = readJson(jsonFile) DBUG('OK: json read') rman_version = setup_environment(jsonDict) if int(rman_version) >= 22: import rmanAssets.core as ra # pylint: disable=import-error else: import rfm.rmanAssets as ra # pylint: disable=import-error DBUG('OK: imported rmanAssets') # constants _bump = ('height', 'normal') slotsFile = FilePath(os.path.dirname(os.path.realpath(__file__))).join('rules.json') rules = readJson(slotsFile) DBUG('OK: rules read') _bxdf = jsonDict['bxdf'] bxdf_rules = rules[_bxdf] mappings = bxdf_rules['mapping'] graph = bxdf_rules.get('graph', None) settings = bxdf_rules.get('settings', None) is_udim = jsonDict['udim'] # we save the assets to SP's export directory, because we know it is writable. # We will move them to the requested location later. exportPath = jsonFile.dirname() # build assets assetList = [] scene = jsonDict['scene'] matArray = jsonDict['document'] for mat in matArray: label = scene if not is_udim: label = '%s_%s' % (scene, mat['textureSet']) chans = mat['channels'] DBUG('+ Exporting %s', label) assetPath = exportPath.join(label + '.rma') DBUG(' + assetPath %s', assetPath) assetJsonPath = assetPath.join('asset.json') DBUG(' + assetJsonPath %s', assetJsonPath) # create asset directory if not assetPath.exists(): try: os.mkdir(assetPath.osPath()) except (OSError, IOError): XCPT('Asset directory could not be created !') sys.exit(0) DBUG(' + Created dir: %s', assetPath) else: DBUG(' + dir exists: %s', assetPath) # create asset try: asset = ra.RmanAsset(assetType='nodeGraph', label=label) except Exception: XCPT('Asset creation failed') sys.exit(0) # create standard metadata # set_metadata(asset, mat) # Compatibility data # This will help other application decide if they can use this asset. # prmanVersion = str(rman_version) asset.setCompatibility(hostName='Substance Painter', hostVersion=jsonDict['sp_version'], rendererVersion=prmanVersion) DBUG(' + compatibility set') # create nodes # start by adding a root node # rootNode = label + '_Material' asset.addNode(rootNode, 'shadingEngine', 'root', 'shadingEngine') pdict = {'type': 'reference float[]', 'value': None} asset.addParam(rootNode, 'surfaceShader', pdict) DBUG(' + Root node: %s', rootNode) # add a disney or pixar bxdf # bxdfNode = label + "_Srf" asset.addNode(bxdfNode, _bxdf, 'bxdf', _bxdf) DBUG(' + BxDF node: %s (%s)', (rootNode, _bxdf)) # The bxdf may need specific settings to match Substance Painter set_params(settings, 'bxdf', bxdfNode, asset) # connect surf to root node # asset.addConnection('%s.outColor' % bxdfNode, '%s.surfaceShader' % rootNode) # build additional nodes if need be. # if graph: DBUG(' + Create graph nodes...') for nname, ndict in graph['nodes'].iteritems(): lname = label + nname asset.addNode(lname, ndict['nodetype'], 'pattern', ndict['nodetype']) DBUG(' |_ %s (%s)' % (lname, ndict['nodetype'])) if 'params' in ndict: for pname, pdict in ndict['params'].iteritems(): asset.addParam(lname, pname, pdict) DBUG(' |_ param: %s %s = %s' % (pdict['type'], pname, pdict['value'])) # create texture nodes DBUG(' + Create texture nodes...') chanNodes = {} for chan, fpath_list in chans.iteritems(): nodeName = "%s_%s_tex" % (label, chan) DBUG(' |_ %s' % nodeName) chanNodes[chan] = nodeName fpath = txmake(is_udim, assetPath, fpath_list) if chan == 'normal': add_texture_node(asset, nodeName, 'PxrNormalMap', fpath) elif chan == 'height': add_texture_node(asset, nodeName, 'PxrBump', fpath) else: add_texture_node(asset, nodeName, 'PxrTexture', fpath) set_params(settings, chan, nodeName, asset) # make direct connections # DBUG(' + Direct connections...') for chan in chans: src = None dstType = mappings[chan]['type'] dstParam = mappings[chan]['param'] if dstType == 'normal': src = '%s.resultN' % (chanNodes[chan]) elif dstType == 'color': src = '%s.resultRGB' % (chanNodes[chan]) elif dstType == 'float': src = '%s.resultR' % (chanNodes[chan]) else: # don't create a connection if dstParam != 'graph': # connections with a graph type will be handled later, so # we don't warn in that case. print 'WARNING: Not connecting: %s' % chan continue if dstParam == 'graph': continue dst = '%s.%s' % (bxdfNode, dstParam) asset.addConnection(src, dst) DBUG(' |_ connect: %s -> %s' % (src, dst)) # also tag the bxdf param as connected pdict = {'type': 'reference ' + dstType, 'value': None} asset.addParam(bxdfNode, dstParam, pdict) DBUG(' |_ param: %s %s -> %s' % (pdict['type'], dstParam, pdict['value'])) # make graph connections # if graph: if 'connections' in graph: DBUG(' + Connect graph nodes...') for con in graph['connections']: src_node = con['src']['node'] src_ch = None if src_node == _bxdf: src_node = bxdfNode elif src_node.startswith('ch:'): src_ch = src_node[3:] if src_ch in chanNodes: src_node = chanNodes[src_ch] else: continue if not src_node.startswith(label): src_node = label + src_node src = '%s.%s' % (src_node, con['src']['param']) dst_node = con['dst']['node'] dst_ch = None if dst_node == _bxdf: dst_node = bxdfNode elif dst_node.startswith('ch:'): dst_ch = dst_node[3:] if dst_ch in chanNodes: dst_node = chanNodes[dst_ch] else: continue if not dst_node.startswith(label): dst_node = label + dst_node dst = '%s.%s' % (dst_node, con['dst']['param']) asset.addConnection(src, dst) DBUG(' |_ connect: %s -> %s' % (src, dst)) # mark param as a connected dstType = con['dst']['type'] pdict = {'type': 'reference %s' % dstType, 'value': None} asset.addParam(dst_node, con['dst']['param'], pdict) DBUG(' |_ param: %s %s = %s' % (pdict['type'], con['dst']['param'], pdict['value'])) # save asset # DBUG(' + ready to save: %s' % assetJsonPath) try: asset.save(assetJsonPath, False) except: XCPT('Saving the asset failed !') raise # mark this asset as ready to be moved # assetList.append(assetPath) # move assets to the requested location # dst = jsonDict['saveTo'] for item in assetList: # if the asset already exists in the destination # location, we need to move it first. dstAsset = os.path.join(dst, os.path.basename(item)) if os.path.exists(dstAsset): try: os.rename(dstAsset, dstAsset + '_old') except (OSError, IOError): XCPT('Could not rename asset to %s_old' % dstAsset) continue else: shutil.rmtree(dstAsset + '_old', ignore_errors=False) try: shutil.move(item, dst) except (OSError, IOError): XCPT('WARNING: Could not copy asset to %s' % dst) # clean-up intermediate files for mat in matArray: for chan, fpath_list in chans.iteritems(): for fpath in fpath_list: if not os.path.exists(fpath): print 'cleanup: file not found: %s' % fpath continue try: os.remove(fpath) except (OSError, IOError): XCPT('Cleanup failed: %s' % fpath) else: DBUG('Cleanup: %s' % fpath) if os.path.exists(jsonFile): try: os.remove(jsonFile) except (OSError, IOError): XCPT('Cleanup failed: %s' % jsonFile) else: DBUG('Cleanup: %s' % jsonFile) INFO('RenderMan : Done !') # main try: export() except Exception: XCPT('Export failed') sys.exit(0)
import numpy as np import pytest from pandas import Categorical, DataFrame, Series import pandas._testing as tm class TestSeriesSortValues: def test_sort_values(self, datetime_series): # check indexes are reordered corresponding with the values ser = Series([3, 2, 4, 1], ["A", "B", "C", "D"]) expected = Series([1, 2, 3, 4], ["D", "B", "A", "C"]) result = ser.sort_values() tm.assert_series_equal(expected, result) ts = datetime_series.copy() ts[:5] = np.NaN vals = ts.values result = ts.sort_values() assert np.isnan(result[-5:]).all() tm.assert_numpy_array_equal(result[:-5].values, np.sort(vals[5:])) # na_position result = ts.sort_values(na_position="first") assert np.isnan(result[:5]).all() tm.assert_numpy_array_equal(result[5:].values, np.sort(vals[5:])) # something object-type ser = Series(["A", "B"], [1, 2]) # no failure ser.sort_values() # ascending=False ordered = ts.sort_values(ascending=False) expected = np.sort(ts.dropna().values)[::-1] tm.assert_almost_equal(expected, ordered.dropna().values) ordered = ts.sort_values(ascending=False, na_position="first") tm.assert_almost_equal(expected, ordered.dropna().values) # ascending=[False] should behave the same as ascending=False ordered = ts.sort_values(ascending=[False]) expected = ts.sort_values(ascending=False) tm.assert_series_equal(expected, ordered) ordered = ts.sort_values(ascending=[False], na_position="first") expected = ts.sort_values(ascending=False, na_position="first") tm.assert_series_equal(expected, ordered) msg = "ascending must be boolean" with pytest.raises(ValueError, match=msg): ts.sort_values(ascending=None) msg = r"Length of ascending \(0\) must be 1 for Series" with pytest.raises(ValueError, match=msg): ts.sort_values(ascending=[]) msg = r"Length of ascending \(3\) must be 1 for Series" with pytest.raises(ValueError, match=msg): ts.sort_values(ascending=[1, 2, 3]) msg = r"Length of ascending \(2\) must be 1 for Series" with pytest.raises(ValueError, match=msg): ts.sort_values(ascending=[False, False]) msg = "ascending must be boolean" with pytest.raises(ValueError, match=msg): ts.sort_values(ascending="foobar") # inplace=True ts = datetime_series.copy() return_value = ts.sort_values(ascending=False, inplace=True) assert return_value is None tm.assert_series_equal(ts, datetime_series.sort_values(ascending=False)) tm.assert_index_equal( ts.index, datetime_series.sort_values(ascending=False).index ) # GH#5856/5853 # Series.sort_values operating on a view df = DataFrame(np.random.randn(10, 4)) s = df.iloc[:, 0] msg = ( "This Series is a view of some other array, to sort in-place " "you must create a copy" ) with pytest.raises(ValueError, match=msg): s.sort_values(inplace=True) def test_sort_values_categorical(self): c = Categorical(["a", "b", "b", "a"], ordered=False) cat = Series(c.copy()) # sort in the categories order expected = Series( Categorical(["a", "a", "b", "b"], ordered=False), index=[0, 3, 1, 2] ) result = cat.sort_values() tm.assert_series_equal(result, expected) cat = Series(Categorical(["a", "c", "b", "d"], ordered=True)) res = cat.sort_values() exp = np.array(["a", "b", "c", "d"], dtype=np.object_) tm.assert_numpy_array_equal(res.__array__(), exp) cat = Series( Categorical( ["a", "c", "b", "d"], categories=["a", "b", "c", "d"], ordered=True ) ) res = cat.sort_values() exp = np.array(["a", "b", "c", "d"], dtype=np.object_) tm.assert_numpy_array_equal(res.__array__(), exp) res = cat.sort_values(ascending=False) exp = np.array(["d", "c", "b", "a"], dtype=np.object_) tm.assert_numpy_array_equal(res.__array__(), exp) raw_cat1 = Categorical( ["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False ) raw_cat2 = Categorical( ["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True ) s = ["a", "b", "c", "d"] df = DataFrame( {"unsort": raw_cat1, "sort": raw_cat2, "string": s, "values": [1, 2, 3, 4]} ) # Cats must be sorted in a dataframe res = df.sort_values(by=["string"], ascending=False) exp = np.array(["d", "c", "b", "a"], dtype=np.object_) tm.assert_numpy_array_equal(res["sort"].values.__array__(), exp) assert res["sort"].dtype == "category" res = df.sort_values(by=["sort"], ascending=False) exp = df.sort_values(by=["string"], ascending=True) tm.assert_series_equal(res["values"], exp["values"]) assert res["sort"].dtype == "category" assert res["unsort"].dtype == "category" # unordered cat, but we allow this df.sort_values(by=["unsort"], ascending=False) # multi-columns sort # GH#7848 df = DataFrame( {"id": [6, 5, 4, 3, 2, 1], "raw_grade": ["a", "b", "b", "a", "a", "e"]} ) df["grade"] = Categorical(df["raw_grade"], ordered=True) df["grade"] = df["grade"].cat.set_categories(["b", "e", "a"]) # sorts 'grade' according to the order of the categories result = df.sort_values(by=["grade"]) expected = df.iloc[[1, 2, 5, 0, 3, 4]] tm.assert_frame_equal(result, expected) # multi result = df.sort_values(by=["grade", "id"]) expected = df.iloc[[2, 1, 5, 4, 3, 0]] tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_list, sorted_list, ignore_index, output_index", [ ([2, 3, 6, 1], [6, 3, 2, 1], True, [0, 1, 2, 3]), ([2, 3, 6, 1], [6, 3, 2, 1], False, [2, 1, 0, 3]), ], ) def test_sort_values_ignore_index( self, inplace, original_list, sorted_list, ignore_index, output_index ): # GH 30114 ser = Series(original_list) expected = Series(sorted_list, index=output_index) kwargs = {"ignore_index": ignore_index, "inplace": inplace} if inplace: result_ser = ser.copy() result_ser.sort_values(ascending=False, **kwargs) else: result_ser = ser.sort_values(ascending=False, **kwargs) tm.assert_series_equal(result_ser, expected) tm.assert_series_equal(ser, Series(original_list)) class TestSeriesSortingKey: def test_sort_values_key(self): series = Series(np.array(["Hello", "goodbye"])) result = series.sort_values(0) expected = series tm.assert_series_equal(result, expected) result = series.sort_values(0, key=lambda x: x.str.lower()) expected = series[::-1] tm.assert_series_equal(result, expected) def test_sort_values_key_nan(self): series = Series(np.array([0, 5, np.nan, 3, 2, np.nan])) result = series.sort_values(0) expected = series.iloc[[0, 4, 3, 1, 2, 5]] tm.assert_series_equal(result, expected) result = series.sort_values(0, key=lambda x: x + 5) expected = series.iloc[[0, 4, 3, 1, 2, 5]] tm.assert_series_equal(result, expected) result = series.sort_values(0, key=lambda x: -x, ascending=False) expected = series.iloc[[0, 4, 3, 1, 2, 5]] tm.assert_series_equal(result, expected)
""" Communication classes and functions. This module contains the classes and functions for the communication between the vehicles, or between the vehicles and the GCS. Generally, XBee modules are used for the vehicles to talk to each other. For software-in-the-loop simulation, `pyzmq` is used to establish a publish-subscrib model. Reference: DIJI Xbee: https://docs.digi.com/display/XBeeZigBeeMeshKit/Frame+structure python-xbee: https://github.com/nioinnovation/python-xbee Classes: Broadcast(threading.Thread): broadcast datapacks across the PAN. Purge(threading.Thread): clean the neighborhood periodically. Subscriber(threading.Thread): subscriber thread by `pyzmq` for SITL. WrappedData(object): a data structure that packs the information into binary. Functions: zmq_init(pub_port, sub_port_list): initialize ZeroMQ pub-sub. dispatch_init(ser): initialize a dispatcher. xbee_init(ser): initialize an XBee interface. xbee_broadcast(xbee, data): broadcast some data via the XBee interface. Copyright: Copyright 2017 Quan Yuan, Adaptive Networks and Control Lab, Research Center of Smart Networks and Systems, School of Information Science and Engineering, Fudan University. 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 sys import time import math import serial import threading import zmq from struct import pack from struct import unpack from xbee import XBee from xbee import ZigBee from xbee.helpers.dispatch import Dispatch from dronekit import LocationGlobal from dronekit import LocationGlobalRelative from zmq.error import Again import mas import nav import util import shared class Broadcast(threading.Thread): """ Broadcast `my` data to `my neighbors` periodically via the XBee interface. Because it requires a high-level command link with the GCS (`gcs.py`), an `xbee.XBee` or `xbee.Zigbee` object (either a real one or simulated) is need. The copter is a `dronekit.Vehicle` object. The status of the copter is needed. Args: agent_id(str): `my` agent id vehicle(dronekit.Vehicle): the copter to be controlled. xbee(xbee.Zigbee): the XBee communication interface. """ def __init__(self, agent_id, vehicle, xbee): threading.Thread.__init__(self) self._vehicle = vehicle self._xbee = xbee self._agent_id = agent_id self._stopflag = False def run(self): """ Broadcast the data at 16Hz. Pack all the data into a binary pack using `struct.pack`. The payload will have a constant 39 byte length. Coordinates should be Ctype-double to guarantee precision. Altitude and velocity should work okay with float. The data list: (ID is also the Key in <neighbors>) ---------------------------------- item: Python-type: C-type length(B) offset: agent_id string char[] 3 0 lat float double 8 1 lon float double 8 2 msl_alt float float 4 3 rel_alt float float 4 4 vx float float 4 5 vy float float 4 6 vz float float 4 7 ----------------------------------- """ util.log_info("Broadcast Started.") while not self._stopflag: time.sleep(.0625) # 16Hz if self._vehicle.armed: # Only broadcast while vehicle is armed package = pack( '=3s2d5f', self._agent_id, self._vehicle.location.global_frame.lat, self._vehicle.location.global_frame.lon, self._vehicle.location.global_frame.alt, self._vehicle.location.global_relative_frame.alt, self._vehicle.velocity[0], self._vehicle.velocity[1], self._vehicle.velocity[2] ) xbee_broadcast(self._xbee, package) if shared.status['thread_flag'] & shared.BROADCAST_FLAG: self._stopflag = True util.log_info("Broadcast killed by flag.") def stop(self): """ Set a flag to exit the thread. """ self._stopflag = True class Purge(threading.Thread): """ Clear a dictionary periodically. Args: table(dict): the dictionary to be purged. """ def __init__(self, table): threading.Thread.__init__(self) self.table = table self._stopflag = False def run(self): """ Run the thread and purge periodically. """ util.log_info("Purge Started.") count = 0 while not self._stopflag: time.sleep(.2) count = count + 1 count = count % 15 # Clear neighbors table each 3s if count == 0: self.table.clear() if shared.status['thread_flag'] & shared.PURGE_FLAG: util.log_info("Purge killed by flag.") self._stopflag = True def stop(self): """ Set a flag to exit the thread. """ self._stopflag = True class WrappedData(object): """ Wrap a list of data components into an data pack object. """ def __init__(self, info_list): """ Input a list of data components. The info_list components: (ID is also the Key in <neighbors>) ---------------------------------- item: Python-type: C-type length(B) offset: ID string char[] 3 0 lat float double 8 1 lon float double 8 2 msl_alt float float 4 3 rel_alt float float 4 4 vx float float 4 5 vy float float 4 6 vz float float 4 7 ----------------------------------- Example: Key : ID latitude longitude msl_alt rel_alt vx vy vz 'A12': ['A12', '31.3011976','121.4981926','21.6','12.59','-0.57','-0.04','0.17'] """ self.__ID = info_list[0] self.__lat = float(info_list[1]) # These two are double self.__lon = float(info_list[2]) self.__msl_alt = round(float(info_list[3]),8) # round-up floats self.__rel_alt = round(float(info_list[4]),8) self.__vx = round(float(info_list[5]),8) self.__vy = round(float(info_list[6]),8) self.__vz = round(float(info_list[7]),8) @property def ID(self): """ str: Pack ID. """ return self.__ID @property def velocity(self): """ list: Velocity vector in NED. """ return [self.__vx, self.__vy, self.__vz] @property def location_global(self): """ dronekit.LocationGlobal: Global NED coordinate. Altitude is MSL altitude. """ return LocationGlobal(self.__lat, self.__lon, self.__msl_alt) @property def location_global_relative(self): """ dronekit.LocationGlobalRelative: Global NED coordinate. Altitude is home-relative. """ return LocationGlobalRelative(self.__lat, self.__lon, self.__rel_alt) def __str__(self): return "WrappedData: %s,%f,%f,%.2f,%.2f,%.2f,%.2f,%.2f" % ( self.__ID, self.__lat, self.__lon, self.__msl_alt, self.__rel_alt, self.__vx, self.__vy, self.__vz ) class Subscriber(threading.Thread): """ A ZeroMQ subscriber thread that monitors the publisher periodically. The parameters are for the Decentralized Model Predictive Control algorithm only. Args: agent_id(str): `my` agent id sub(zmq.Context.socket): a subscriber listening the publisher. """ def __init__(self, agent_id, sub): threading.Thread.__init__(self) self.sub = sub self.agent_id = agent_id self._stopflag = False def run(self): """ Run the subscriber and listen to the publisher every 5ms. """ util.log_info("Subscriber started for %s." % self.agent_id) while not self._stopflag: time.sleep(.005) try: [tag, payload] = self.sub.recv_multipart(flags=1) if tag == 'XBEE': # package to be consistent with <rx_data_handler> packet = {'rf_data': payload} rx_data_handler('sub_rx', packet) except Again: # zmq.error Exception pass if shared.status['thread_flag'] & shared.SUBSCRIBER_FLAG: self._stopflag = True util.log_info("Subscriber killed by flag.") def stop(self): """ Set a flag to exit the thread. """ self._stopflag = True def zmq_init(pub_port, sub_port_list): """ Initialize the ZeroMQ publisher and subscriber. `My` publisher publishes `my` data to the neighbors. `My` subscriber listen to the ports of other neighbors. `sub_port_list` stores all the possible neighbors' TCP ports. The data packs are wrapped as an XBee interface, compatable with the XBee transmission and reception functions in this module. Args: pub_port(str/int): TCP port for the publisher. sub_port_list(list): TCP port list for the subscriber to listen to. Returns: list: `my` publisher and `my` subscriber (i.e. listener). """ pub = zmq.Context().socket(zmq.PUB) pub.bind('tcp://*:%s' % pub_port) sub = zmq.Context().socket(zmq.SUB) for port in sub_port_list: if sub_port_list[port] != pub_port: sub.connect('tcp://127.0.0.1:%s' % sub_port_list[port]) time.sleep(0.05) sub.setsockopt(zmq.SUBSCRIBE, 'XBEE') return [pub, sub] def rx_data_handler(name, packet): """ Callback function for incoming XBee transmission. Args: name(str): name to identify the callback function in a dispatcher. packet(dict): package received from the XBee API. """ # Split datapack header and payload -- Small misc packs. if packet['rf_data'][0:3] == 'CTR': # control command pack recv_pack = packet['rf_data'].split(',') shared.status['command'] = recv_pack[1] util.log_info("CMD: %s" % recv_pack[1]) elif packet['rf_data'][0:3] == 'IFO': # information string pack recv_pack = packet['rf_data'].split(',') util.log_info("IFO: %s" % recv_pack[1]) elif packet['rf_data'][0:3] == 'PRM': # parameter pack recv_pack = packet['rf_data'].split(',') if recv_pack[1][0:3] == 'MPC': # currently only DMPC is available shared.param_mpc = mas.ParamMPC(unpack('=3s3f2i', recv_pack[1])) util.log_info("New MPC param received: %s" % shared.param_mpc) shared.status['new_param'] = True elif packet['rf_data'] == 'CLR_RDV': # clear rendezvous command, no comma split. shared.rendezvous = None util.log_info("'CLR_RDV' received, clear rendezvous") # guarantee packet integrity (payload length) -- Actual agent data pack elif len(packet['rf_data']) == shared.PAYLOAD_LENGTH: #from binascii import hexlify # logging binary bytes #util.log_debug("DATAPACK: %s" % hexlify(packet['rf_data'])) # unpack data into lists and wrap into local datapacks recv_pack = WrappedData(unpack('=3s2d5f', packet['rf_data'])) util.log_debug("%s" % recv_pack) if recv_pack.ID == 'TAR': # target point pack shared.rendezvous = recv_pack util.log_debug("Rendezvous coordinate received.") elif recv_pack.ID == 'ORG': # HOME_ORIGIN pack shared.home_origin = recv_pack.location_global_relative util.log_info("HOME_ORIGIN set: %s." % shared.home_origin) elif recv_pack.ID[0] == 'A': # normal neighbor begins with 'Axx' shared.neighbors[recv_pack.ID] = recv_pack def dispatch_init(ser): """ Initialize a dispatcher and register rx_data_handler. Args: ser(serial.Serial): a serial interface object. Returns: xbee.helpers.dispatch.Dispatch: an XBee dispatcher object. """ # -------------------------------------------------------------------- # When a Dispatch is created with a serial port, it will automatically # create an XBee object on your behalf for accessing the device. # If you wish, you may explicitly provide your own XBee: # # xbee = XBee(ser) # dispatch = Dispatch(xbee=xbee) # # Functionally, these are the same. --Paul Malmsten # -------------------------------------------------------------------- # Register the packet handlers with the dispatch: # The string name allows one to distinguish between mutiple registrations # for a single callback function. # The second argument is the callback function name. # The third argument is a function which determines whether to call its # associated callback when a packet arrives. It should return a boolean. # -------------------------------------------------------------------- # Spawn a dispatch instance and associate it with packet id 'rx' dispatcher = Dispatch(ser) dispatcher.register( "rx_data", rx_data_handler, lambda packet: packet['id']=='rx' ) return dispatcher def xbee_init(ser): """ Initialize an XBee communication interface running in API mode. Args: ser(serial.Serial): a serial interface object. Returns: xbee.ZigBee: an XBee interface running in Zigbee compatable API. """ dispatcher = dispatch_init(ser) return ZigBee(ser, callback=dispatcher.dispatch, escaped=True) def xbee_broadcast(xbee, data): """ Broadcast a payload through the XBee interface. Args: xbee(xbee.Zigbee): the XBee communication interface. data(str): data string or raw binary. """ # if xbee is ZeroMQ socket type, initialize the publisher. SITL only. if isinstance(xbee, zmq.sugar.socket.Socket): xbee.send_multipart(['XBEE',data]) return # else this is a real xbee xbee.send( 'tx', frame_id = '\x00', # frameID dest_addr_long = '\x00\x00\x00\x00\x00\x00\xFF\xFF', # 64-bit address - broadcast dest_addr = '\xFF\xFE', # 16-bit address - non-identified options = b'\x01', # disable ACK data = data )
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def get_unspent(listunspent, amount): for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount)) class RawTransactionsTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() def run_test(self): print("Mining blocks...") min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee'] # This test is not meant to test fee estimation and we'd like # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) # if the fee's positive delta is higher than this value tests will fail, # neg. delta always fail the tests. # The size of the signature of every input may be at most 2 bytes larger # than a minimum sized signature. # = 2 bytes * minRelayTxFeePerByte feeTolerance = 2 * min_relay_tx_fee/1000 self.nodes[2].generate(1) self.sync_all() self.nodes[0].generate(121) self.sync_all() watchonly_address = self.nodes[0].getnewaddress() watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"] watchonly_amount = Decimal(200) self.nodes[3].importpubkey(watchonly_pubkey, "", True) watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount) self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.5) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 5.0) self.nodes[0].generate(1) self.sync_all() ############### # simple test # ############### inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) #test that we have enough inputs ############################## # simple test with two coins # ############################## inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.2 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) #test if we have enough inputs ############################## # simple test with two coins # ############################## inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.6 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ################################ # simple test with two outputs # ################################ inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.6, self.nodes[1].getnewaddress() : 2.5 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ######################################################################### # test a fundrawtransaction with a VIN greater than the required amount # ######################################################################### utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee ##################################################################### # test a fundrawtransaction with which will not get a change output # ##################################################################### utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : Decimal(5.0) - fee - feeTolerance } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert_equal(rawtxfund['changepos'], -1) assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee #################################################### # test a fundrawtransaction with an invalid option # #################################################### utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(4.0) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) try: self.nodes[2].fundrawtransaction(rawtx, {'foo': 'bar'}) raise AssertionError("Accepted invalid option foo") except JSONRPCException as e: assert("Unexpected key foo" in e.error['message']) ############################################################ # test a fundrawtransaction with an invalid change address # ############################################################ utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(4.0) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) try: self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': 'foobar'}) raise AssertionError("Accepted invalid mitocoin address") except JSONRPCException as e: assert("changeAddress must be a valid mitocoin address" in e.error['message']) ############################################################ # test a fundrawtransaction with a provided change address # ############################################################ utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(4.0) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) change = self.nodes[2].getnewaddress() try: rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 2}) except JSONRPCException as e: assert('changePosition out of bounds' == e.error['message']) else: assert(False) rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 0}) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) out = dec_tx['vout'][0]; assert_equal(change, out['scriptPubKey']['addresses'][0]) ######################################################################### # test a fundrawtransaction with a VIN smaller than the required amount # ######################################################################### utx = get_unspent(self.nodes[2].listunspent(), 1) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) # 4-byte version + 1-byte vin count + 36-byte prevout then script_len rawtx = rawtx[:82] + "0100" + rawtx[84:] dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for i, out in enumerate(dec_tx['vout']): totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 else: assert_equal(i, rawtxfund['changepos']) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex']) assert_equal(matchingOuts, 1) assert_equal(len(dec_tx['vout']), 2) ########################################### # test a fundrawtransaction with two VINs # ########################################### utx = get_unspent(self.nodes[2].listunspent(), 1) utx2 = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 6.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for out in dec_tx['vout']: totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 assert_equal(matchingOuts, 1) assert_equal(len(dec_tx['vout']), 2) matchingIns = 0 for vinOut in dec_tx['vin']: for vinIn in inputs: if vinIn['txid'] == vinOut['txid']: matchingIns+=1 assert_equal(matchingIns, 2) #we now must see two vins identical to vins given as params ######################################################### # test a fundrawtransaction with two VINs and two vOUTs # ######################################################### utx = get_unspent(self.nodes[2].listunspent(), 1) utx2 = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 6.0, self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for out in dec_tx['vout']: totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 assert_equal(matchingOuts, 2) assert_equal(len(dec_tx['vout']), 3) ############################################## # test a fundrawtransaction with invalid vin # ############################################## listunspent = self.nodes[2].listunspent() inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin! outputs = { self.nodes[0].getnewaddress() : 1.0} rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) try: rawtxfund = self.nodes[2].fundrawtransaction(rawtx) raise AssertionError("Spent more than available") except JSONRPCException as e: assert("Insufficient" in e.error['message']) ############################################################ #compare fee of a standard pubkeyhash transaction inputs = [] outputs = {self.nodes[1].getnewaddress():1.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1.1) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a standard pubkeyhash transaction with multiple outputs inputs = [] outputs = {self.nodes[1].getnewaddress():1.1,self.nodes[1].getnewaddress():1.2,self.nodes[1].getnewaddress():0.1,self.nodes[1].getnewaddress():1.3,self.nodes[1].getnewaddress():0.2,self.nodes[1].getnewaddress():0.3} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendmany("", outputs) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a 2of2 multisig p2sh transaction # create 2of2 addr addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[1].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[1].validateaddress(addr2) mSigObj = self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) inputs = [] outputs = {mSigObj:1.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(mSigObj, 1.1) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a standard pubkeyhash transaction # create 4of5 addr addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[1].getnewaddress() addr3 = self.nodes[1].getnewaddress() addr4 = self.nodes[1].getnewaddress() addr5 = self.nodes[1].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[1].validateaddress(addr2) addr3Obj = self.nodes[1].validateaddress(addr3) addr4Obj = self.nodes[1].validateaddress(addr4) addr5Obj = self.nodes[1].validateaddress(addr5) mSigObj = self.nodes[1].addmultisigaddress(4, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey'], addr4Obj['pubkey'], addr5Obj['pubkey']]) inputs = [] outputs = {mSigObj:1.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(mSigObj, 1.1) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ # spend a 2of2 multisig transaction over fundraw # create 2of2 addr addr1 = self.nodes[2].getnewaddress() addr2 = self.nodes[2].getnewaddress() addr1Obj = self.nodes[2].validateaddress(addr1) addr2Obj = self.nodes[2].validateaddress(addr2) mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) # send 1.2 BTC to msig addr txId = self.nodes[0].sendtoaddress(mSigObj, 1.2) self.sync_all() self.nodes[1].generate(1) self.sync_all() oldBalance = self.nodes[1].getbalance() inputs = [] outputs = {self.nodes[1].getnewaddress():1.1} rawTx = self.nodes[2].createrawtransaction(inputs, outputs) fundedTx = self.nodes[2].fundrawtransaction(rawTx) signedTx = self.nodes[2].signrawtransaction(fundedTx['hex']) txId = self.nodes[2].sendrawtransaction(signedTx['hex']) self.sync_all() self.nodes[1].generate(1) self.sync_all() # make sure funds are received at node1 assert_equal(oldBalance+Decimal('1.10000000'), self.nodes[1].getbalance()) ############################################################ # locked wallet test self.nodes[1].encryptwallet("test") self.nodes.pop(1) stop_nodes(self.nodes) self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) # This test is not meant to test fee estimation and we'd like # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() # drain the keypool self.nodes[1].getnewaddress() inputs = [] outputs = {self.nodes[0].getnewaddress():1.1} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) # fund a transaction that requires a new key for the change output # creating the key must be impossible because the wallet is locked try: fundedTx = self.nodes[1].fundrawtransaction(rawTx) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: assert('Keypool ran out' in e.error['message']) #refill the keypool self.nodes[1].walletpassphrase("test", 100) self.nodes[1].walletlock() try: self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1.2) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: assert('walletpassphrase' in e.error['message']) oldBalance = self.nodes[0].getbalance() inputs = [] outputs = {self.nodes[0].getnewaddress():1.1} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) #now we need to unlock self.nodes[1].walletpassphrase("test", 100) signedTx = self.nodes[1].signrawtransaction(fundedTx['hex']) txId = self.nodes[1].sendrawtransaction(signedTx['hex']) self.nodes[1].generate(1) self.sync_all() # make sure funds are received at node1 assert_equal(oldBalance+Decimal('51.10000000'), self.nodes[0].getbalance()) ############################################### # multiple (~19) inputs tx test | Compare fee # ############################################### #empty node1, send some small coins from node0 to node1 self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True) self.sync_all() self.nodes[0].generate(1) self.sync_all() for i in range(0,20): self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01) self.nodes[0].generate(1) self.sync_all() #fund a tx with ~20 small inputs inputs = [] outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[1].sendmany("", outputs) signedFee = self.nodes[1].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs ############################################# # multiple (~19) inputs tx test | sign/send # ############################################# #again, empty node1, send some small coins from node0 to node1 self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True) self.sync_all() self.nodes[0].generate(1) self.sync_all() for i in range(0,20): self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01) self.nodes[0].generate(1) self.sync_all() #fund a tx with ~20 small inputs oldBalance = self.nodes[0].getbalance() inputs = [] outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) fundedAndSignedTx = self.nodes[1].signrawtransaction(fundedTx['hex']) txId = self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex']) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(oldBalance+Decimal('50.19000000'), self.nodes[0].getbalance()) #0.19+block reward ##################################################### # test fundrawtransaction with OP_RETURN and no vin # ##################################################### rawtx = "0100000000010000000000000000066a047465737400000000" dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(len(dec_tx['vin']), 0) assert_equal(len(dec_tx['vout']), 1) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert_greater_than(len(dec_tx['vin']), 0) # at least one vin assert_equal(len(dec_tx['vout']), 2) # one change output added ################################################## # test a fundrawtransaction using only watchonly # ################################################## inputs = [] outputs = {self.nodes[2].getnewaddress() : watchonly_amount / 2} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = self.nodes[3].fundrawtransaction(rawtx, {'includeWatching': True }) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 1) assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) assert("fee" in result.keys()) assert_greater_than(result["changepos"], -1) ############################################################### # test fundrawtransaction using the entirety of watched funds # ############################################################### inputs = [] outputs = {self.nodes[2].getnewaddress() : watchonly_amount} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) # Backward compatibility test (2nd param is includeWatching) result = self.nodes[3].fundrawtransaction(rawtx, True) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 2) assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid) assert_greater_than(result["fee"], 0) assert_greater_than(result["changepos"], -1) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) signedtx = self.nodes[3].signrawtransaction(result["hex"]) assert(not signedtx["complete"]) signedtx = self.nodes[0].signrawtransaction(signedtx["hex"]) assert(signedtx["complete"]) self.nodes[0].sendrawtransaction(signedtx["hex"]) self.nodes[0].generate(1) self.sync_all() ####################### # Test feeRate option # ####################### # Make sure there is exactly one input so coin selection can't skew the result assert_equal(len(self.nodes[3].listunspent(1)), 1) inputs = [] outputs = {self.nodes[2].getnewaddress() : 1} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = self.nodes[3].fundrawtransaction(rawtx) # uses min_relay_tx_fee (set by settxfee) result2 = self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 2*min_relay_tx_fee}) result3 = self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 10*min_relay_tx_fee}) result_fee_rate = result['fee'] * 1000 / count_bytes(result['hex']) assert_fee_amount(result2['fee'], count_bytes(result2['hex']), 2 * result_fee_rate) assert_fee_amount(result3['fee'], count_bytes(result3['hex']), 10 * result_fee_rate) if __name__ == '__main__': RawTransactionsTest().main()
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # 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 netforce.model import Model, fields, get_model from netforce.utils import get_data_path, roundup import time from netforce.access import get_active_user, set_active_user from netforce.access import get_active_company, check_permission_other, set_active_company from . import utils from datetime import datetime, timedelta from decimal import Decimal class SaleOrder(Model): _name = "sale.order" _string = "Sales Order" _audit_log = True _name_field = "number" _multi_company = True _key = ["company_id", "number"] # need migration first otherwise can't add constraint... _fields = { "number": fields.Char("Number", required=True, search=True), "ref": fields.Char("Ref", search=True), "contact_id": fields.Many2One("contact", "Customer", required=True, search=True), "date": fields.Date("Date", required=True, search=True), "state": fields.Selection([("draft", "Draft"), ("confirmed", "Confirmed"), ("done", "Completed"), ("voided", "Voided")], "Status", required=True), "lines": fields.One2Many("sale.order.line", "order_id", "Lines"), "amount_subtotal": fields.Decimal("Subtotal", function="get_amount", function_multi=True, store=True), "amount_tax": fields.Decimal("Tax Amount", function="get_amount", function_multi=True, store=True), "amount_total": fields.Decimal("Total", function="get_amount", function_multi=True, store=True), "amount_total_discount": fields.Decimal("Total Discount", function="get_amount", function_multi=True, store=True), "amount_total_words": fields.Char("Total Words", function="get_amount_total_words"), "amount_total_cur": fields.Decimal("Total", function="get_amount", function_multi=True, store=True), "qty_total": fields.Decimal("Total", function="get_qty_total"), "currency_id": fields.Many2One("currency", "Currency", required=True, search=True), "quot_id": fields.Many2One("sale.quot", "Quotation", search=True), # XXX: deprecated "user_id": fields.Many2One("base.user", "Owner", search=True), "tax_type": fields.Selection([["tax_ex", "Tax Exclusive"], ["tax_in", "Tax Inclusive"], ["no_tax", "No Tax"]], "Tax Type", required=True), "invoice_lines": fields.One2Many("account.invoice.line", "sale_id", "Invoice Lines"), "invoices": fields.One2Many("account.invoice", "related_id", "Invoices"), "pickings": fields.Many2Many("stock.picking", "Stock Pickings", function="get_pickings"), "is_delivered": fields.Boolean("Delivered", function="get_delivered"), "is_paid": fields.Boolean("Paid", function="get_paid"), "comments": fields.One2Many("message", "related_id", "Comments"), "activities": fields.One2Many("activity", "related_id", "Activities"), "location_id": fields.Many2One("stock.location", "Warehouse", search=True), # XXX: deprecated "price_list_id": fields.Many2One("price.list", "Price List", condition=[["type", "=", "sale"]]), "payment_terms": fields.Text("Payment Terms"), "delivery_date": fields.Date("Due Date"), # XXX; deprecated "due_date": fields.Date("Due Date"), "team_id": fields.Many2One("mfg.team", "Production Team"), "ship_method_id": fields.Many2One("ship.method", "Shipping Method"), # XXX: deprecated "emails": fields.One2Many("email.message", "related_id", "Emails"), "documents": fields.One2Many("document", "related_id", "Documents"), "addresses": fields.One2Many("address", "related_id", "Addresses"), "bill_address_id": fields.Many2One("address", "Billing Address"), "ship_address_id": fields.Many2One("address", "Shipping Address"), "coupon_id": fields.Many2One("sale.coupon", "Coupon"), "purchase_lines": fields.One2Many("purchase.order.line", "sale_id", "Purchase Orders"), "production_orders": fields.One2Many("production.order", "sale_id", "Production Orders"), "other_info": fields.Text("Other Information"), "costs": fields.One2Many("sale.cost", "sale_id", "Costs"), "est_cost_total": fields.Decimal("Estimated Cost Total", function="get_profit", function_multi=True, store=True), # XXX: deprecated "est_profit": fields.Decimal("Estimated Profit", function="get_profit", function_multi=True, store=True), # XXX: deprecated "est_profit_percent": fields.Decimal("Estimated Profit Percent", function="get_profit", function_multi=True, store=True), # XXX: deprecated "act_cost_total": fields.Decimal("Actual Cost Total", function="get_profit", function_multi=True, store=True), # XXX: deprecated "act_profit": fields.Decimal("Actual Profit", function="get_profit", function_multi=True, store=True), # XXX: deprecated "act_profit_percent": fields.Decimal("Actual Profit Percent", function="get_profit", function_multi=True, store=True), # XXX: deprecated "company_id": fields.Many2One("company", "Company"), "production_status": fields.Json("Production", function="get_production_status"), "overdue": fields.Boolean("Overdue", function="get_overdue", function_search="search_overdue"), "ship_term_id": fields.Many2One("ship.term", "Shipping Terms"), "approved_by_id": fields.Many2One("base.user", "Approved By", readonly=True), "sequence_id": fields.Many2One("sequence", "Number Sequence"), "stock_moves": fields.One2Many("stock.move", "related_id", "Stock Movements"), "state_label": fields.Char("Status Label", function="get_state_label"), # XXX: not needed "ship_tracking": fields.Char("Tracking Numbers", function="get_ship_tracking"), "job_template_id": fields.Many2One("job.template", "Service Order Template"), "jobs": fields.One2Many("job", "related_id", "Service Orders"), "agg_amount_total": fields.Decimal("Total Amount", agg_function=["sum", "amount_total"]), "agg_amount_total_cur": fields.Decimal("Total Amount (Converted)", agg_function=["sum", "amount_total_cur"]), "agg_amount_subtotal": fields.Decimal("Total Amount w/o Tax", agg_function=["sum", "amount_subtotal"]), "agg_est_profit": fields.Decimal("Total Estimated Profit", agg_function=["sum", "est_profit_amount"]), "agg_act_profit": fields.Decimal("Total Actual Profit", agg_function=["sum", "act_profit_amount"]), "year": fields.Char("Year", sql_function=["year", "date"]), "quarter": fields.Char("Quarter", sql_function=["quarter", "date"]), "month": fields.Char("Month", sql_function=["month", "date"]), "week": fields.Char("Week", sql_function=["week", "date"]), "pay_method_id": fields.Many2One("payment.method", "Payment Method",search=True), "sale_channel_id": fields.Many2One("sale.channel", "Sales Channel",search=True), "related_id": fields.Reference([["sale.quot", "Quotation"], ["ecom.cart", "Ecommerce Cart"], ["purchase.order", "Purchase Order"]], "Related To"), "est_costs": fields.One2Many("sale.cost","sale_id","Costs"), "est_cost_amount": fields.Float("Est. Cost Amount", function="get_est_profit", function_multi=True, store=True), "est_profit_amount": fields.Float("Est. Profit Amount", function="get_est_profit", function_multi=True, store=True), "est_margin_percent": fields.Float("Est. Margin %", function="get_est_profit", function_multi=True, store=True), "act_cost_amount": fields.Float("Act. Cost Amount", function="get_act_profit", function_multi=True, store=True), "act_profit_amount": fields.Float("Act. Profit Amount", function="get_act_profit", function_multi=True, store=True), "act_margin_percent": fields.Float("Act. Margin %", function="get_act_profit", function_multi=True, store=True), "track_id": fields.Many2One("account.track.categ","Tracking Code"), "track_entries": fields.One2Many("account.track.entry",None,"Tracking Entries",function="get_track_entries",function_write="write_track_entries"), "track_balance": fields.Decimal("Tracking Balance",function="_get_related",function_context={"path":"track_id.balance"}), "used_promotions": fields.One2Many("sale.order.promotion", "sale_id", "Used Promotions"), "seller_id": fields.Many2One("seller","Seller"), "product_id": fields.Many2One("product","Product",store=False,function_search="search_product",search=True), "currency_rates": fields.One2Many("custom.currency.rate","related_id","Currency Rates"), "delivery_slot_id": fields.Many2One("delivery.slot","Delivery Slot"), } def _get_number(self, context={}): seq_id = get_model("sequence").find_sequence(type="sale_order",context=context) if not seq_id: return None while 1: num = get_model("sequence").get_next_number(seq_id, context=context) if not num: return None user_id = get_active_user() set_active_user(1) res = self.search([["number", "=", num]]) set_active_user(user_id) if not res: return num get_model("sequence").increment_number(seq_id, context=context) def _get_currency(self, context={}): settings = get_model("settings").browse(1) return settings.currency_id.id def _get_currency_rates(self,context={}): settings = get_model("settings").browse(1) lines=[] date = time.strftime("%Y-%m-%d") line_vals={ "currency_id": settings.currency_id.id, "rate": settings.currency_id and settings.currency_id.get_rate(date,"sell") or 1 } if context.get("is_create"): lines.append(('create',line_vals)) else: lines.append(line_vals) return lines _defaults = { "state": "draft", "date": lambda *a: time.strftime("%Y-%m-%d"), "number": _get_number, "currency_id": _get_currency, "tax_type": "tax_ex", "user_id": lambda *a: get_active_user(), "company_id": lambda *a: get_active_company(), "currency_rates": _get_currency_rates, } _order = "date desc,number desc" def search_product(self, clause, context={}): product_id = clause[2] product = get_model("product").browse(product_id) product_ids = [product_id] for var in product.variants: product_ids.append(var.id) for comp in product.components: product_ids.append(comp.component_id.id) order_ids = [] for line in get_model("sale.order.line").search_browse([["product_id","in",product_ids]]): order_ids.append(line.order_id.id) cond = [["id","in",order_ids]] return cond def create(self, vals, context={}): context['is_create']=True #send to function _get_currency_rates id = super(SaleOrder, self).create(vals, context) self.function_store([id]) quot_id = vals.get("quot_id") if quot_id: get_model("sale.quot").function_store([quot_id]) if 'lines' in vals.keys(): self.create_est_costs([id]) return id def write(self, ids, vals, **kw): quot_ids = [] for obj in self.browse(ids): if obj.quot_id: quot_ids.append(obj.quot_id.id) super(SaleOrder, self).write(ids, vals, **kw) self.function_store(ids) if 'lines' in vals.keys(): self.create_est_costs(ids) quot_id = vals.get("quot_id") if quot_id: quot_ids.append(quot_id) if quot_ids: get_model("sale.quot").function_store(quot_ids) def delete(self, ids, **kw): quot_ids = [] for obj in self.browse(ids): if obj.state in ("confirmed", "done"): raise Exception("Can not delete sales order in this status") if obj.quot_id: quot_ids.append(obj.quot_id.id) super(SaleOrder, self).delete(ids, **kw) if quot_ids: get_model("sale.quot").function_store(quot_ids) def get_amount(self, ids, context={}): res = {} settings = get_model("settings").browse(1) for obj in self.browse(ids): vals = {} subtotal = 0 tax = 0 discount = 0 for line in obj.lines: discount += line.amount_discount if line.tax_id: line_tax = get_model("account.tax.rate").compute_tax( line.tax_id.id, line.amount, tax_type=obj.tax_type) else: line_tax = 0 tax += line_tax if obj.tax_type == "tax_in": subtotal += line.amount - line_tax else: subtotal += line.amount for line in obj.used_promotions: if line.product_id or line.percent: continue prom=line.promotion_id prod=prom.product_id prom_tax=prod.sale_tax_id if prod else None if prom_tax: line_tax = get_model("account.tax.rate").compute_tax( prom_tax.id, line.amount, tax_type=obj.tax_type) else: line_tax = 0 tax -= line_tax if obj.tax_type == "tax_in": subtotal -= line.amount - line_tax else: subtotal -= line.amount vals["amount_subtotal"] = subtotal vals["amount_tax"] = tax vals["amount_total"] = (subtotal + tax) vals["amount_total_cur"] = get_model("currency").convert( vals["amount_total"], obj.currency_id.id, settings.currency_id.id, rate_type="sell", date=obj.date) vals["amount_total_discount"] = discount res[obj.id] = vals return res def get_qty_total(self, ids, context={}): res = {} for obj in self.browse(ids): qty = sum([line.qty for line in obj.lines]) res[obj.id] = qty or 0 return res def confirm(self, ids, context={}): obj = self.browse(ids)[0] if obj.state != "draft": raise Exception("Invalid state") for line in obj.lines: prod = line.product_id if prod and prod.type in ("stock", "consumable", "bundle") and not line.location_id: raise Exception("Missing location for product %s" % prod.code) obj.write({"state": "confirmed"}) settings = get_model("settings").browse(1) if settings.sale_copy_picking: res=obj.copy_to_picking() picking_id=res["picking_id"] get_model("stock.picking").pending([picking_id]) if settings.sale_copy_invoice: obj.copy_to_invoice() if settings.sale_copy_production: obj.copy_to_production() obj.trigger("confirm") return { "next": { "name": "sale", "mode": "form", "active_id": obj.id, }, "flash": "Sales order %s confirmed" % obj.number, } def done(self, ids, context={}): for obj in self.browse(ids): if obj.state != "confirmed": raise Exception("Invalid state") obj.write({"state": "done"}) def reopen(self, ids, context={}): for obj in self.browse(ids): if obj.state != "done": raise Exception("Invalid state") obj.write({"state": "confirmed"}) def to_draft(self, ids, context={}): for obj in self.browse(ids): obj.write({"state": "draft"}) def onchange_currency(self,context={}): settings=get_model("settings").browse(1) data = context["data"] for line in data["lines"]: if not line: continue amt = (line.get("qty") or 0) * (line.get("unit_price") or 0) new_cur=get_model("currency").convert(amt, int(data.get("currency_id")), settings.currency_id.id) line['amount_cur']=new_cur and new_cur or None return data def update_amounts(self, context): settings=get_model("settings").browse(1) data = context["data"] data["amount_subtotal"] = 0 data["amount_tax"] = 0 tax_type = data["tax_type"] for line in data["lines"]: if not line: continue amt = (line.get("qty") or 0) * (line.get("unit_price") or 0) amt = roundup(amt) if line.get("discount"): disc = amt * line["discount"] / Decimal(100) amt -= disc if line.get("discount_amount"): amt -= line["discount_amount"] line["amount"] = amt new_cur=get_model("currency").convert(amt, int(data.get("currency_id")), settings.currency_id.id) line['amount_cur']=new_cur and new_cur or None tax_id = line.get("tax_id") if tax_id: tax = get_model("account.tax.rate").compute_tax(tax_id, amt, tax_type=tax_type) data["amount_tax"] += tax else: tax = 0 amt=Decimal(round(float(amt),2)) # # convert to float because Decimal gives wrong rounding if tax_type == "tax_in": data["amount_subtotal"] += amt - tax else: data["amount_subtotal"] += amt data["amount_total"] = data["amount_subtotal"] + data["amount_tax"] return data def onchange_product(self, context): data = context["data"] path = context["path"] line = get_data_path(data, path, parent=True) prod_id = line.get("product_id") if not prod_id: return {} prod = get_model("product").browse(prod_id) line["description"] = prod.description or "/" line["qty"] = 1 line["uom_id"] = prod.sale_uom_id.id or prod.uom_id.id line["qty_stock"] = 0 pricelist_id = data["price_list_id"] price = None if pricelist_id: price = get_model("price.list").get_price(pricelist_id, prod.id, 1) line['discount'] = get_model("price.list").get_discount(pricelist_id, prod.id, 1) price_list = get_model("price.list").browse(pricelist_id) price_currency_id = price_list.currency_id.id if price is None: price = prod.sale_price settings = get_model("settings").browse(1) price_currency_id = settings.currency_id.id if price is not None: currency_id = data["currency_id"] price_cur = get_model("currency").convert(price, price_currency_id, currency_id) line["unit_price"] = price_cur if prod.sale_tax_id is not None: line["tax_id"] = prod.sale_tax_id.id if prod.location_id: line["location_id"] = prod.location_id.id elif prod.locations: line["location_id"] = prod.locations[0].location_id.id for loc in prod.locations: if loc.stock_qty: line['location_id']=loc.location_id.id break if "location_id" in line and line["location_id"]: qty_stock = get_model("stock.balance").search_browse([["product_id","=",prod_id],["location_id","=",line["location_id"]]]) if len(qty_stock) > 0: line["qty_stock"] = qty_stock[0].qty_phys data = self.update_amounts(context) return data def onchange_qty(self, context): data = context["data"] path = context["path"] line = get_data_path(data, path, parent=True) prod_id = line.get("product_id") if not prod_id: return {} prod = get_model("product").browse(prod_id) pricelist_id = data["price_list_id"] qty = line["qty"] price = None if pricelist_id: price = get_model("price.list").get_price(pricelist_id, prod.id, qty) price_list = get_model("price.list").browse(pricelist_id) price_currency_id = price_list.currency_id.id if price is None: price = prod.sale_price settings = get_model("settings").browse(1) price_currency_id = settings.currency_id.id if price is not None: currency_id = data["currency_id"] price_cur = get_model("currency").convert(price, price_currency_id, currency_id) line["unit_price"] = price_cur data = self.update_amounts(context) return data def onchange_location(self, context): data = context["data"] path = context["path"] line = get_data_path(data, path, parent=True) line["qty_stock"] = 0 if "product_id" in line and line["product_id"]: qty_stock = get_model("stock.balance").search_browse([["product_id","=",line["product_id"]],["location_id","=",line["location_id"]]]) if len(qty_stock) > 0: line["qty_stock"] = qty_stock[0].qty_phys return data def onchange_uom(self, context): data = context["data"] path = context["path"] line = get_data_path(data, path, parent=True) prod_id = line.get("product_id") if not prod_id: return {} prod = get_model("product").browse(prod_id) uom_id = line.get("uom_id") if not uom_id: return {} uom = get_model("uom").browse(uom_id) if prod.sale_price is not None: line["unit_price"] = prod.sale_price * uom.ratio / prod.uom_id.ratio data = self.update_amounts(context) #update est ..... sale = self.browse(int(data['id'])) item_costs=Decimal(0) for cost in sale.est_costs: k=(sale.id,cost.sequence) amt=cost.amount or 0 if cost.currency_id: rate=sale.get_relative_currency_rate(cost.currency_id.id) amt=amt*rate item_costs+=amt cost=item_costs profit=line['amount']-Decimal(cost) margin=Decimal(profit)*100/Decimal(line['amount']) if line['amount'] else None amount={ "est_cost_amount": cost, "est_profit_amount": profit, "est_margin_percent": margin, } line['est_cost_amount'] = amount['est_cost_amount'] line['est_profit_amount'] = amount['est_profit_amount'] line['est_margin_percent'] = amount['est_margin_percent'] return data def get_qty_to_deliver(self, ids): obj = self.browse(ids)[0] sale_quants = {} for line in obj.lines: prod = line.product_id if not prod or prod.type == "service": continue uom = line.uom_id sale_quants.setdefault((prod.id, uom.id), 0) sale_quants[(prod.id, uom.id)] += line.qty # XXX: uom done_quants = {} for move in obj.stock_moves: if move.state == "cancelled": continue prod = move.product_id done_quants.setdefault(prod.id, 0) done_quants[prod.id] += move.qty # XXX: uom to_deliver = {} for (prod_id, uom_id), qty in sale_quants.items(): qty_done = done_quants.get(prod_id, 0) if qty_done < qty: to_deliver[(prod_id, uom_id)] = qty - qty_done return to_deliver def copy_to_picking(self, ids, context={}): id = ids[0] obj = self.browse(id) pick_vals = {} contact = obj.contact_id res = get_model("stock.location").search([["type", "=", "customer"]]) if not res: raise Exception("Customer location not found") cust_loc_id = res[0] res = get_model("stock.location").search([["type", "=", "internal"]]) if not res: raise Exception("Warehouse not found") wh_loc_id = res[0] for obj_line in obj.lines: picking_key = obj_line.ship_method_id and obj_line.ship_method_id.id or 0 if picking_key in pick_vals: continue if not obj.due_date: raise Exception("Missing due date in sales order %s"%obj.number) pick_vals[picking_key] = { "type": "out", "ref": obj.number, "related_id": "sale.order,%s" % obj.id, "contact_id": contact.id, "ship_address_id": obj.ship_address_id.id, "lines": [], "state": "draft", "ship_method_id": obj_line.ship_method_id.id or obj.ship_method_id.id, "company_id": obj.company_id.id, "date": obj.due_date+" 00:00:00", } if contact and contact.pick_out_journal_id: pick_vals[picking_key]["journal_id"] = contact.pick_out_journal_id.id for line in obj.lines: picking_key = line.ship_method_id and line.ship_method_id.id or 0 prod = line.product_id if not prod: continue if prod.type not in ("stock", "consumable"): continue if line.qty <= 0: continue qty_remain = line.qty - line.qty_delivered if qty_remain <= 0: continue line_vals = { "product_id": prod.id, "qty": qty_remain, "uom_id": prod.uom_id.id if line.qty_stock else line.uom_id.id, "location_from_id": line.location_id.id or wh_loc_id, "location_to_id": cust_loc_id, "related_id": "sale.order,%s" % obj.id, } pick_vals[picking_key]["lines"].append(("create", line_vals)) for picking_key, picking_value in pick_vals.items(): if not picking_value["lines"]: Exception("Nothing left to deliver") pick_id = get_model("stock.picking").create(picking_value, context={"pick_type": "out"}) pick = get_model("stock.picking").browse(pick_id) return { "next": { "name": "pick_out", "mode": "form", "active_id": pick_id, }, "flash": "Picking %s created from sales order %s" % (pick.number, obj.number), "picking_id": pick_id, } def copy_to_invoice(self, ids, context={}): print("sale.copy_to_invoice",ids) obj = self.browse(ids[0]) company_id=get_active_company() set_active_company(obj.company_id.id) # XXX try: ship_method_ids=[] ship_method_amts={} ship_amt_total=0 for line in obj.lines: ship_method_ids.append(line.ship_method_id.id) ship_method_amts.setdefault(line.ship_method_id.id,0) ship_method_amts[line.ship_method_id.id]+=line.amount ship_amt_total+=line.amount ship_method_ids=list(set(ship_method_ids)) inv_ids=[] for ship_method_id in ship_method_ids: contact = obj.contact_id inv_vals = { "type": "out", "inv_type": "invoice", "ref": obj.number, "related_id": "sale.order,%s" % obj.id, "contact_id": contact.id, "bill_address_id": obj.bill_address_id.id, "currency_id": obj.currency_id.id, "tax_type": obj.tax_type, "pay_method_id": obj.pay_method_id.id, "lines": [], "company_id": obj.company_id.id, } if contact.sale_journal_id: inv_vals["journal_id"] = contact.sale_journal_id.id if contact.sale_journal_id.sequence_id: inv_vals["sequence_id"] = contact.sale_journal_id.sequence_id.id for line in obj.lines: if line.unit_price is None: continue if line.ship_method_id.id!=ship_method_id: continue prod = line.product_id remain_qty = line.qty - line.qty_invoiced if remain_qty <= 0: continue # TODO: this get account should call from product.get_account()["sale_account_id"] sale_acc_id=None if prod: #1. get account from product sale_acc_id=prod.sale_account_id and prod.sale_account_id.id or None # 2. if not get from master/parent product if not sale_acc_id and prod.parent_id: sale_acc_id=prod.parent_id.sale_account_id.id # 3. if not get from product category categ=prod.categ_id if categ and not sale_acc_id: sale_acc_id=categ.sale_account_id and categ.sale_account_id.id or None #if not sale_acc_id: #raise Exception("Missing sale account for product [%s] " % prod.name ) line_vals = { "product_id": prod.id, "description": line.description, "qty": remain_qty, "uom_id": line.uom_id.id, "unit_price": line.unit_price, "discount": line.discount, "discount_amount": line.discount_amount, "account_id": sale_acc_id, "tax_id": line.tax_id.id, "amount": remain_qty*line.unit_price*(1-(line.discount or Decimal(0))/100)-(line.discount_amount or Decimal(0)), } inv_vals["lines"].append(("create", line_vals)) if line.promotion_amount: prom_acc_id=None if prod: prom_acc_id=prod.sale_promotion_account_id.id if not prom_acc_id and prod.parent_id: prom_acc_id=prod.parent_id.sale_promotion_account_id.id if not prom_acc_id: prom_acc_id=sale_acc_id line_vals = { "product_id": prod.id, "description": "Promotion on product %s"%prod.code, "account_id": prom_acc_id, "tax_id": line.tax_id.id, "amount": -line.promotion_amount, } inv_vals["lines"].append(("create", line_vals)) for line in obj.used_promotions: if line.product_id or line.percent: continue ratio=ship_method_amts[ship_method_id]/ship_amt_total if ship_amt_total else 0 prom=line.promotion_id prod = prom.product_id line_vals = { "product_id": prod.id, "description": prom.name, "account_id": prod and prod.sale_account_id.id or None, "tax_id": prod and prod.sale_tax_id.id or None, "amount": -line.amount*ratio, } inv_vals["lines"].append(("create", line_vals)) if not inv_vals["lines"]: continue inv_id = get_model("account.invoice").create(inv_vals, {"type": "out", "inv_type": "invoice"}) inv_ids.append(inv_id) if not inv_ids: raise Exception("Nothing to invoice") print("inv_ids",inv_ids) return { "next": { "name": "view_invoice", "active_id": inv_ids[0], }, "flash": "Invoice created from sales order %s" % obj.number, "invoice_id": inv_ids[0], } finally: set_active_company(company_id) def get_delivered(self, ids, context={}): vals = {} for obj in self.browse(ids): is_delivered = True for line in obj.lines: prod = line.product_id if prod.type not in ("stock", "consumable", "bundle", None): continue remain_qty = (line.qty or line.qty_stock) - line.qty_delivered if remain_qty > 0: is_delivered = False break vals[obj.id] = is_delivered return vals def get_paid(self, ids, context={}): vals = {} for obj in self.browse(ids): amt_paid = 0 for inv in obj.invoices: if inv.state != "paid": continue amt_paid += inv.amount_total is_paid = amt_paid >= obj.amount_total vals[obj.id] = is_paid return vals def void(self, ids, context={}): for obj in self.browse(ids): for pick in obj.pickings: if pick.state == "pending": raise Exception("There are still pending goods issues for this sales order") for inv in obj.invoices: if inv.state == "waiting_payment": raise Exception("There are still invoices waiting payment for this sales order") obj.write({"state": "voided"}) def copy(self, ids, context): obj = self.browse(ids)[0] vals = { "contact_id": obj.contact_id.id, "date": obj.date, "ref": obj.ref, "currency_id": obj.currency_id.id, "tax_type": obj.tax_type, "user_id": obj.user_id.id, "quot_id": obj.quot_id.id, "lines": [], } for line in obj.lines: line_vals = { "product_id": line.product_id.id, "description": line.description, "qty": line.qty, "discount": line.discount, "discount_amount": line.discount_amount, "uom_id": line.uom_id.id, "location_id": line.location_id.id, "unit_price": line.unit_price, "tax_id": line.tax_id.id, } vals["lines"].append(("create", line_vals)) new_id = self.create(vals) new_obj = self.browse(new_id) return { "next": { "name": "sale", "mode": "form", "active_id": new_id, }, "flash": "Sales order %s copied to %s" % (obj.number, new_obj.number), "sale_id": new_id, } def get_invoices(self, ids, context={}): vals = {} for obj in self.browse(ids): inv_ids = [] for inv_line in obj.invoice_lines: inv_id = inv_line.invoice_id.id if inv_id not in inv_ids: inv_ids.append(inv_id) vals[obj.id] = inv_ids return vals def get_pickings(self, ids, context={}): vals = {} for obj in self.browse(ids): pick_ids = [] for move in obj.stock_moves: pick_id = move.picking_id.id if pick_id not in pick_ids: pick_ids.append(pick_id) vals[obj.id] = pick_ids return vals def onchange_contact(self, context): data = context["data"] contact_id = data.get("contact_id") contact = get_model("contact").browse(contact_id) if contact_id else None data["payment_terms"] = contact.payment_terms if contact else None data["price_list_id"] = contact.sale_price_list_id.id if contact else None data["bill_address_id"] = contact.get_address(pref_type="billing") if contact else None data["ship_address_id"] = contact.get_address(pref_type="shipping") if contact else None if contact.currency_id: data["currency_id"] = contact.currency_id.id else: settings = get_model("settings").browse(1) data["currency_id"] = settings.currency_id.id return data def check_delivered_qtys(self, ids, context={}): obj = self.browse(ids)[0] for line in obj.lines: if line.qty < 0: continue if line.qty_delivered > line.qty: raise Exception("Can not deliver excess quantity for sales order %s and product %s (order qty: %s, delivered qty: %s)" % ( obj.number, line.product_id.code, line.qty, line.qty_delivered)) def copy_to_purchase(self, ids, context={}): obj = self.browse(ids)[0] suppliers = {} for line in obj.lines: prod = line.product_id if not prod: continue if prod.procure_method != "mto" or prod.supply_method != "purchase": continue if not prod.suppliers: raise Exception("Missing supplier for product '%s'" % prod.name) supplier_id = prod.suppliers[0].supplier_id.id suppliers.setdefault(supplier_id, []).append((prod.id, line.qty, line.uom_id.id, line.location_id.id)) if not suppliers: raise Exception("No purchase orders to create") po_ids = [] for supplier_id, lines in suppliers.items(): supplier = get_model("contact").browse(supplier_id) purch_vals = { "contact_id": supplier_id, "ref": obj.number, "lines": [], "payment_terms": obj.payment_terms or supplier.payment_terms, } for prod_id, qty, uom_id, location_id in lines: prod = get_model("product").browse(prod_id) line_vals = { "product_id": prod_id, "description": prod.description or "/", "qty": qty, "uom_id": uom_id, "unit_price": prod.purchase_price or 0, "tax_id": prod.purchase_tax_id.id, "sale_id": obj.id, 'location_id': location_id, } purch_vals["lines"].append(("create", line_vals)) po_id = get_model("purchase.order").create(purch_vals) po_ids.append(po_id) po_objs = get_model("purchase.order").browse(po_ids) return { "next": { "name": "purchase", "search_condition": [["ref", "=", obj.number]], }, "flash": "Purchase orders created successfully: " + ", ".join([po.number for po in po_objs]), } def copy_to_production(self, ids, context={}): order_ids = [] mfg_orders = {} for obj in self.browse(ids): for line in obj.lines: prod = line.product_id if not prod: continue if prod.procure_method != "mto" or prod.supply_method != "production": continue if line.production_id: raise Exception("Production order already created for sales order %s, product %s"%(obj.number,prod.code)) if not obj.due_date: raise Exception("Missing due date in sales order %s"%obj.number) if not prod.mfg_lead_time: raise Exception("Missing manufacturing lead time in product %s"%prod.code) k=(prod.id,obj.due_date) mfg_orders.setdefault(k,[]).append(line.id) for (prod_id,due_date),sale_line_ids in mfg_orders.items(): prod=get_model("product").browse(prod_id) res=get_model("bom").search([["product_id","=",prod.id]]) # TODO: select bom in separate function if not res: raise Exception("BoM not found for product '%s'" % prod.name) bom_id = res[0] bom = get_model("bom").browse(bom_id) loc_id = bom.location_id.id if not loc_id: raise Exception("Missing FG location in BoM %s" % bom.number) routing = bom.routing_id if not routing: raise Exception("Missing routing in BoM %s" % bom.number) loc_prod_id = routing.location_id.id if not loc_prod_id: raise Exception("Missing production location in routing %s" % routing.number) uom = prod.uom_id mfg_qty=0 for line in get_model("sale.order.line").browse(sale_line_ids): if line.qty_stock: qty = line.qty_stock else: qty = get_model("uom").convert(line.qty, line.uom_id.id, uom.id) mfg_qty+=qty if not prod.mfg_lead_time: raise Exception("Missing manufacturing lead time for product %s"%prod.code) mfg_date=(datetime.strptime(due_date,"%Y-%m-%d")-timedelta(days=prod.mfg_lead_time)).strftime("%Y-%m-%d") order_vals = { "product_id": prod.id, "qty_planned": mfg_qty, "uom_id": uom.id, "bom_id": bom_id, "routing_id": routing.id, "production_location_id": loc_prod_id, "location_id": loc_id, "order_date": mfg_date, "due_date": due_date, "state": "waiting_confirm", } order_id = get_model("production.order").create(order_vals) get_model("production.order").create_components([order_id]) get_model("production.order").create_operations([order_id]) order_ids.append(order_id) get_model("sale.order.line").write(sale_line_ids,{"production_id":order_id}) if not order_ids: return { "flash": "No production orders to create", } get_model("production.order").copy_to_production_all(order_ids) return { "flash": "Production orders created successfully", } def get_production_status(self, ids, context={}): vals = {} for obj in self.browse(ids): num_done = 0 num_total = 0 for prod in obj.production_orders: if prod.state == "done": num_done += 1 if prod.state not in ("voided", "split"): num_total += 1 if num_total != 0: percent = num_done * 100 / num_total vals[obj.id] = { "percent": percent, "string": "%d / %d" % (num_done, num_total) } else: vals[obj.id] = None return vals def get_overdue(self, ids, context={}): vals = {} for obj in self.browse(ids): if obj.due_date: vals[obj.id] = obj.due_date < time.strftime("%Y-%m-%d") and obj.state in ("draft", "waiting", "ready") else: vals[obj.id] = False return vals def search_overdue(self, clause, context={}): return [["due_date", "<", time.strftime("%Y-%m-%d")], ["state", "in", ["draft", "waiting", "ready"]]] def get_amount_total_words(self, ids, context={}): vals = {} for obj in self.browse(ids): amount_total_words = utils.num2word(obj.amount_total) vals[obj.id] = amount_total_words return vals def approve(self, ids, context={}): if not check_permission_other("sale_approve_done"): raise Exception("Permission denied") obj = self.browse(ids)[0] user_id = get_active_user() obj.write({"approved_by_id": user_id}) return { "next": { "name": "sale", "mode": "form", "active_id": obj.id, }, "flash": "Sales order approved successfully", } def find_sale_line(self, ids, product_id, context={}): obj = self.browse(ids)[0] for line in obj.lines: if line.product_id.id == product_id: return line.id return None def onchange_sequence(self, context={}): data = context["data"] context['date'] = data['date'] seq_id = data["sequence_id"] if not seq_id: return None while 1: num = get_model("sequence").get_next_number(seq_id, context=context) res = self.search([["number", "=", num]]) if not res: break get_model("sequence").increment_number(seq_id, context=context) data["number"] = num return data def get_state_label(self, ids, context={}): vals = {} for obj in self.browse(ids): if obj.state == "draft": s = "Draft" if obj.state == "confirmed": s = "Confirmed" elif obj.state == "done": s = "Completed" elif obj.state == "voided": s = "Voided" else: s = "/" vals[obj.id] = s return vals def get_ship_tracking(self, ids, context={}): vals = {} for obj in self.browse(ids): track_nos = [] for pick in obj.pickings: if pick.ship_tracking: if pick.ship_tracking: track_nos.append(pick.ship_tracking) vals[obj.id] = ",".join(track_nos) return vals def get_pickings(self, ids, context={}): vals = {} for obj in self.browse(ids): pick_ids = [] for move in obj.stock_moves: pick_ids.append(move.picking_id.id) pick_ids = sorted(list(set(pick_ids))) vals[obj.id] = pick_ids return vals def copy_to_job(self, ids, context={}): obj = self.browse(ids)[0] tmpl = obj.job_template_id if not tmpl: raise Exception("Missing service order template in sales order") #job_id = tmpl.create_job(sale_id=obj.id) sale = get_model("sale.order").browse(obj.id) contact_id = sale.contact_id.id vals = { "number": get_model("job")._get_number(), "contact_id": contact_id, "template_id": obj.job_template_id.id, "service_type_id": obj.job_template_id.service_type_id.id, "state": "planned", "related_id": "sale.order,%s" % obj.id, "lines": [], } template_products = [] for line in obj.job_template_id.lines: line_vals = { "sequence": line.sequence, "type": line.type, "product_id": line.product_id.id, "description": line.description, "qty": line.qty, "uom_id": line.uom_id.id, "unit_price": line.unit_price, "amount": line.amount, "payment_type": "job", } vals["lines"].append(("create", line_vals)) template_products.append((line.product_id.id,line.description)) for line in obj.lines: if (line.product_id.id,line.description) not in template_products: line_vals = { "sequence": line.sequence, "type": "parts" if line.product_id.type == "stockable" else "other", "product_id": line.product_id.id, "description": line.description, "qty": line.qty, "uom_id": line.uom_id.id, "unit_price": line.unit_price, "amount": line.amount, "payment_type": "job", } vals["lines"].append(("create", line_vals)) job_id = get_model("job").create(vals) job = get_model("job").browse(job_id) return { "flash": "Service order %s created from sales order %s" % (job.number, obj.number), "next": { "name": "job", "mode": "form", "active_id": job_id, }, } def get_profit(self, ids, context={}): vals = {} for obj in self.browse(ids): est_cost_total = 0 act_cost_total = 0 for cost in obj.costs: amt = cost.amount or 0 if cost.currency_id: amt = get_model("currency").convert(amt, cost.currency_id.id, obj.currency_id.id) est_cost_total += amt act_amt = cost.actual_amount or 0 if cost.currency_id: act_amt = get_model("currency").convert(act_amt, cost.currency_id.id, obj.currency_id.id) act_cost_total += act_amt est_profit = obj.amount_subtotal - est_cost_total est_profit_percent = est_profit * 100 / obj.amount_subtotal if obj.amount_subtotal else None act_profit = obj.amount_subtotal - act_cost_total act_profit_percent = act_profit * 100 / obj.amount_subtotal if obj.amount_subtotal else None vals[obj.id] = { "est_cost_total": est_cost_total, "est_profit": est_profit, "est_profit_percent": est_profit_percent, "act_cost_total": act_cost_total, "act_profit": act_profit, "act_profit_percent": act_profit_percent, } return vals def onchange_cost_product(self, context): data = context["data"] path = context["path"] line = get_data_path(data, path, parent=True) prod_id = line.get("product_id") if prod_id: prod = get_model("product").browse(prod_id) line["description"] = prod.description line["unit_price"] = prod.landed_cost line["qty"] = 1 line["uom_id"] = prod.uom_id.id line["currency_id"] = prod.purchase_currency_id.id line["purchase_duty_percent"] = prod.purchase_duty_percent line["purchase_ship_percent"] = prod.purchase_ship_percent line["landed_cost"] = prod.landed_cost line["purchase_price"] = prod.purchase_price if prod.suppliers: line["supplier_id"] = prod.suppliers[0].supplier_id.id return data def get_cost_per_supplier(self, ids, context): vals = {} for obj in self.browse(ids): sup_cost = {} for line in obj.costs: sup = line.supplier_id.name if line.supplier_id else "/" sup_cost.setdefault(sup, [0, 0]) sup_cost[sup][0] += line.amount or 0 sup_cost[sup][1] += line.actual_amount or 0 data = [] for sup in sorted(sup_cost): data.append({ "name": sup, "est_cost_total": sup_cost[sup][0], "act_cost_total": sup_cost[sup][1], }) vals[obj.id] = data return vals def cancel_unpaid_order(self, num_days=7): exp_date = datetime.now() - timedelta(days=num_days) exp_date = exp_date.strftime("%Y-%m-%d") res = self.search([["date", "<", exp_date], ["state", "=", "confirmed"]]) number = "Expired Date-" + exp_date + " Order -" for obj in self.browse(res): if not obj.is_paid: number += obj.number + "-" for pick in obj.pickings: pick.void() for inv in obj.invoices: if inv.state == "waiting_payment": inv.void() obj.void() print(number) def get_est_profit(self, ids, context={}): vals = {} for obj in self.browse(ids): cost=0 for line in obj.lines: cost+=line.est_cost_amount or 0 profit=obj.amount_subtotal-cost margin=profit*100/obj.amount_subtotal if obj.amount_subtotal else None vals[obj.id] = { "est_cost_amount": cost, "est_profit_amount": profit, "est_margin_percent": margin, } return vals def get_track_entries(self,ids,context={}): vals={} for obj in self.browse(ids): if not obj.track_id: vals[obj.id]=[] continue res=get_model("account.track.entry").search([["track_id","child_of",obj.track_id.id]]) vals[obj.id]=res return vals def write_track_entries(self,ids,field,val,context={}): for op in val: if op[0]=="create": rel_vals=op[1] for obj in self.browse(ids): if not obj.track_id: continue rel_vals["track_id"]=obj.track_id.id get_model("account.track.entry").create(rel_vals,context=context) elif op[0]=="write": rel_ids=op[1] rel_vals=op[2] get_model("account.track.entry").write(rel_ids,rel_vals,context=context) elif op[0]=="delete": rel_ids=op[1] get_model("account.track.entry").delete(rel_ids,context=context) def get_act_profit(self, ids, context={}): vals = {} for obj in self.browse(ids): cost=0 for line in obj.track_entries: cost-=line.amount subtotal=obj.amount_subtotal or 0 profit=subtotal-cost margin=profit*100/subtotal if subtotal else None vals[obj.id] = { "act_cost_amount": cost, "act_profit_amount": profit, "act_margin_percent": margin, } return vals def create_track(self,ids,context={}): obj=self.browse(ids[0]) count=0 code=obj.number res=get_model("account.track.categ").search([["code","=",code]]) if res: sale_track_id=res[0] else: sale_track_id=get_model("account.track.categ").create({ "code": code, "name": code, "type": "1", }) count+=1 obj.write({"track_id":sale_track_id}) for line in obj.lines: if not line.sequence: raise Exception("Missing sequence in sales order line") code="%s / %s"%(obj.number,line.sequence) res=get_model("account.track.categ").search([["code","=",code]]) if res: continue vals={ "code": code, "parent_id": sale_track_id, "name": obj.number, #XXX "type": "1", } get_model("account.track.categ").create(vals) count+=1 return { "next": { "name": "sale", "mode": "form", "active_id": obj.id, }, "flash": "%d tracking codes created"%count, } def create_est_costs(self,ids,context={}): obj=self.browse(ids[0]) obj.write({"est_costs":[("delete_all",)]}) line_sequence = 1 for line in obj.lines: cur_line_sequence = line_sequence prod=line.product_id if not prod: continue if not prod.purchase_price and prod.type != "service": continue if not prod.cost_price and prod.type == "service": continue if "bundle" == prod.type: continue # update line seqence if not line.sequence: line.write({"sequence": cur_line_sequence}) line_sequence += 1 else: line_sequence = round(Decimal(line.sequence)) + Decimal(1) landed_cost = prod.landed_cost # compute cost if product is service if prod.type == "service": if prod.uom_id.type=='time': #day landed_cost = prod.cost_price or 0 elif prod.uom_id.type=='unit': #job landed_cost = (prod.sale_price or 0) * (prod.cost_price or 0) elif prod.type == "stock" and prod.supply_method == 'production': landed_cost = prod.cost_price or 0 vals={ "sale_id": obj.id, "sequence": line.sequence, "product_id": prod.id, "description": prod.name, "supplier_id": prod.suppliers[0].supplier_id.id if prod.suppliers else None, "list_price": prod.purchase_price, "purchase_price": prod.purchase_price, "landed_cost": landed_cost, "purchase_duty_percent": prod.purchase_duty_percent, "purchase_ship_percent": prod.purchase_ship_percent, "qty": line.qty, "currency_id": prod.purchase_currency_id.id, "currency_rate": prod.purchase_currency_rate, } get_model("sale.cost").create(vals) if not obj.track_id: obj.create_track() def copy_cost_to_purchase(self, ids, context={}): obj = self.browse(ids)[0] suppliers = {} for cost in obj.est_costs: prod = line.product_id if not prod: continue if not prod.suppliers: raise Exception("Missing supplier for product '%s'" % prod.name) supplier_id = prod.suppliers[0].supplier_id.id suppliers.setdefault(supplier_id, []).append((prod.id, line.qty, line.uom_id.id)) if not suppliers: raise Exception("No purchase orders to create") po_ids = [] for supplier_id, lines in suppliers.items(): purch_vals = { "contact_id": supplier_id, "ref": obj.number, "lines": [], } for prod_id, qty, uom_id in lines: prod = get_model("product").browse(prod_id) line_vals = { "product_id": prod_id, "description": prod.description or "/", "qty": qty, "uom_id": uom_id, "unit_price": prod.purchase_price or 0, "tax_id": prod.purchase_tax_id.id, "sale_id": obj.id, } purch_vals["lines"].append(("create", line_vals)) po_id = get_model("purchase.order").create(purch_vals) po_ids.append(po_id) po_objs = get_model("purchase.order").browse(po_ids) return { "next": { "name": "purchase", "search_condition": [["ref", "=", obj.number]], }, "flash": "Purchase orders created successfully: " + ", ".join([po.number for po in po_objs]), } def get_relative_currency_rate(self,ids,currency_id): obj=self.browse(ids[0]) rate=None for r in obj.currency_rates: if r.currency_id.id==currency_id: rate=r.rate break if rate is None: rate_from=get_model("currency").get_rate([currency_id],obj.date) or Decimal(1) rate_to=obj.currency_id.get_rate(obj.date) or Decimal(1) rate=rate_from/rate_to return rate def copy_to_sale_return(self,ids,context={}): for obj in self.browse(ids): order_vals = {} order_vals = { "contact_id":obj.contact_id.id, "date":obj.date, "ref":obj.number, "due_date":obj.due_date, "currency_id":obj.currency_id.id, "tax_type":obj.tax_type, "bill_address_id":obj.bill_address_id.id, "ship_address_id":obj.ship_address_id.id, "orig_sale_id": obj.id, "lines":[], } for line in obj.lines: line_vals = { "product_id":line.product_id.id, "description":line.description, "qty":line.qty, "uom_id":line.uom_id.id, "unit_price":line.unit_price, "discount":line.discount, "discount_amount":line.discount_amount, "tax_id":line.tax_id.id, "amount":line.amount, "location_id":line.location_id.id, } order_vals["lines"].append(("create", line_vals)) sale_id = get_model("sale.return").create(order_vals) sale = get_model("sale.return").browse(sale_id) return { "next": { "name": "sale_return", "mode": "form", "active_id": sale_id, }, "flash": "Sale Return %s created from sales order %s" % (sale.number, obj.number), "order_id": sale_id, } def get_template_sale_form(self, ids, context={}): #obj = self.browse(ids)[0] return "sale_form" def update_cost_amount(self,context={}): data=context['data'] path=context['path'] line=get_data_path(data,path,parent=True) line['amount']=(line['qty'] or 0) *(line['landed_cost'] or 0) return data SaleOrder.register()
#!/usr/bin/env python """A TestCase that initializes the library with standard API methods.""" import unittest import ee class ApiTestCase(unittest.TestCase): def setUp(self): self.InitializeApi() def InitializeApi(self): """Initializes the library with standard API methods. This is normally invoked during setUp(), but subclasses may invoke it manually instead if they prefer. """ self.last_download_call = None self.last_thumb_call = None self.last_table_call = None ee.data.send_ = self.MockSend ee.Reset() ee.Initialize(None, '') def MockSend(self, path, params, unused_method=None, unused_raw=None): if path == '/algorithms': return BUILTIN_FUNCTIONS elif path == '/value': return {'value': 'fakeValue'} elif path == '/mapid': return {'mapid': 'fakeMapId'} elif path == '/download': # Hang on to the call arguments. self.last_download_call = {'url': path, 'data': params} return {'docid': '1', 'token': '2'} elif path == '/thumb': # Hang on to the call arguments. self.last_thumb_call = {'url': path, 'data': params} return {'thumbid': '3', 'token': '4'} elif path == '/table': # Hang on to the call arguments. self.last_table_call = {'url': path, 'data': params} return {'docid': '5', 'token': '6'} else: raise Exception('Unexpected API call to %s with %s' % (path, params)) BUILTIN_FUNCTIONS = { 'Image.constant': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'value', 'type': 'Object' } ], 'description': '', 'returns': 'Image' }, 'Image.load': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'id', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'version', 'type': 'Long' } ], 'description': '', 'returns': 'Image' }, 'Image.addBands': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'dstImg', 'type': 'Image' }, { 'description': '', 'name': 'srcImg', 'type': 'Image' }, { 'default': None, 'description': '', 'optional': True, 'name': 'names', 'type': 'List<String>' }, { 'default': False, 'description': '', 'optional': True, 'name': 'overwrite', 'type': 'boolean' } ], 'description': '', 'returns': 'Image' }, 'Image.clip': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'input', 'type': 'Image' }, { 'default': None, 'description': '', 'optional': True, 'name': 'geometry', 'type': 'Object' } ], 'description': '', 'returns': 'Image' }, 'Image.select': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'input', 'type': 'Image' }, { 'description': '', 'name': 'bandSelectors', 'type': 'List<Object>' }, { 'default': None, 'description': '', 'optional': True, 'name': 'newNames', 'type': 'List<String>' } ], 'description': '', 'returns': 'Image' }, 'Image.parseExpression': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'expression', 'type': 'String' }, { 'default': 'image', 'description': '', 'optional': True, 'name': 'argName', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'vars', 'type': 'List<String>' } ], 'description': '', 'returns': 'Algorithm' }, 'Feature': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'geometry', 'type': 'Geometry' }, { 'default': {}, 'description': '', 'optional': True, 'name': 'metadata', 'type': 'Dictionary<Object>' } ], 'description': '', 'returns': 'Feature' }, 'Feature.get': { 'type': 'Algorithm', 'returns': '<any>', 'hidden': False, 'args': [ { 'type': 'Element', 'description': '', 'name': 'object' }, { 'type': 'String', 'description': '', 'name': 'property' } ], 'description': '' }, 'Collection': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'features', 'type': 'List<Feature>' } ], 'description': '', 'returns': 'FeatureCollection' }, 'Collection.loadTable': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'tableId', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'geometryColumn', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'version', 'type': 'Long' } ], 'description': '', 'returns': 'FeatureCollection' }, 'Collection.filter': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'FeatureCollection' }, { 'description': '', 'name': 'filter', 'type': 'Filter' } ], 'description': '', 'returns': 'FeatureCollection' }, 'Collection.limit': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'FeatureCollection' }, { 'default': -1, 'description': '', 'optional': True, 'name': 'limit', 'type': 'int' }, { 'default': None, 'description': '', 'optional': True, 'name': 'key', 'type': 'String' }, { 'default': True, 'description': '', 'optional': True, 'name': 'ascending', 'type': 'boolean' } ], 'description': '', 'returns': 'FeatureCollection' }, 'Collection.map': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'FeatureCollection' }, { 'description': '', 'name': 'baseAlgorithm', 'type': 'Algorithm' }, { 'default': None, 'description': '', 'optional': True, 'name': 'dynamicArgs', 'type': 'Dictionary<String>' }, { 'default': {}, 'description': '', 'optional': True, 'name': 'constantArgs', 'type': 'Dictionary<Object>' }, { 'default': None, 'description': '', 'optional': True, 'name': 'destination', 'type': 'String' } ], 'description': '', 'returns': 'FeatureCollection' }, 'Collection.iterate': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'FeatureCollection' }, { 'description': '', 'name': 'function', 'type': 'Algorithm' }, { 'default': None, 'description': '', 'optional': True, 'name': 'first', 'type': 'Object' } ], 'description': '', 'returns': 'Object', }, 'ImageCollection.load': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'id', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'version', 'type': 'Long' } ], 'description': '', 'returns': 'ImageCollection' }, 'ImageCollection.fromImages': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'images', 'type': 'List<Image>' } ], 'description': '', 'returns': 'ImageCollection' }, 'ImageCollection.mosaic': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'ImageCollection' } ], 'description': '', 'returns': 'Image' }, 'Collection.geometry': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'FeatureCollection' }, { 'default': { 'type': 'ErrorMargin', 'unit': 'meters', 'value': 0 }, 'description': '', 'optional': True, 'name': 'maxError', 'type': 'ErrorMargin' } ], 'description': '', 'returns': 'Geometry' }, 'Collection.draw': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'collection', 'type': 'FeatureCollection' }, { 'description': '', 'name': 'color', 'type': 'String' }, { 'default': 3, 'description': '', 'optional': True, 'name': 'pointRadius', 'type': 'int' }, { 'default': 2, 'description': '', 'optional': True, 'name': 'strokeWidth', 'type': 'int' } ], 'description': '', 'returns': 'Image' }, 'DateRange': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'start', 'type': 'Date' }, { 'default': None, 'description': '', 'optional': True, 'name': 'end', 'type': 'Date' } ], 'description': '', 'returns': 'DateRange' }, 'Date': { 'returns': 'Date', 'hidden': False, 'args': [ { 'type': 'Object', 'description': '', 'name': 'value' }, { 'type': 'String', 'default': None, 'description': '', 'optional': True, 'name': 'timeZone' } ], 'type': 'Algorithm', 'description': '' }, 'ErrorMargin': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'value', 'type': 'Double' }, { 'default': 'meters', 'description': '', 'optional': True, 'name': 'unit', 'type': 'String' } ], 'description': '', 'returns': 'ErrorMargin' }, 'Filter.intersects': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' }, { 'default': { 'type': 'ErrorMargin', 'unit': 'meters', 'value': 0.1 }, 'description': '', 'optional': True, 'name': 'maxError', 'type': 'ErrorMargin' } ], 'description': '', 'returns': 'Filter' }, 'Filter.dateRangeContains': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.or': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'filters', 'type': 'List<Filter>' } ], 'description': '', 'returns': 'Filter' }, 'Filter.and': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'filters', 'type': 'List<Filter>' } ], 'description': '', 'returns': 'Filter' }, 'Filter.not': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'filter', 'type': 'Filter' } ], 'description': '', 'returns': 'Filter' }, 'Filter.equals': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.lessThan': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.greaterThan': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.stringContains': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.stringStartsWith': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.stringEndsWith': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Filter.listContains': { 'type': 'Algorithm', 'args': [ { 'default': None, 'description': '', 'optional': True, 'name': 'leftField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightValue', 'type': 'Object' }, { 'default': None, 'description': '', 'optional': True, 'name': 'rightField', 'type': 'String' }, { 'default': None, 'description': '', 'optional': True, 'name': 'leftValue', 'type': 'Object' } ], 'description': '', 'returns': 'Filter' }, 'Image.mask': { 'type': 'Algorithm', 'args': [ { 'name': 'image', 'type': 'Image', 'description': '' }, { 'name': 'mask', 'type': 'Image', 'description': '', 'optional': True, 'default': None } ], 'description': '', 'returns': 'Image' }, # These two functions (Dictionary.get and Image.reduceRegion) are here # to force the creation of the Dictionary class. 'Dictionary.get': { 'returns': 'Object', 'args': [ { 'type': 'Dictionary<Object>', 'description': '', 'name': 'map' }, { 'type': 'String', 'description': '', 'name': 'property' } ], 'type': 'Algorithm', 'description': '', }, 'Image.reduceRegion': { 'returns': 'Dictionary<Object>', 'hidden': False, 'args': [ { 'type': 'Image', 'description': '', 'name': 'image' }, { 'type': 'ReducerOld', 'description': '', 'name': 'reducer' }, { 'default': None, 'type': 'Geometry', 'optional': True, 'description': '', 'name': 'geometry' }, { 'default': None, 'type': 'Double', 'optional': True, 'description': '', 'name': 'scale' }, { 'default': 'EPSG:4326', 'type': 'String', 'optional': True, 'description': '', 'name': 'crs' }, { 'default': None, 'type': 'double[]', 'optional': True, 'description': '', 'name': 'crsTransform' }, { 'default': False, 'type': 'boolean', 'optional': True, 'description': '', 'name': 'bestEffort' } ], 'type': 'Algorithm', 'description': '' }, # Algorithms for testing ee.String. 'String': { 'returns': 'String', 'hidden': False, 'args': [ { 'type': 'Object', 'description': '', 'name': 'input' } ], 'type': 'Algorithm', 'description': '' }, 'String.cat': { 'returns': 'String', 'hidden': False, 'args': [ { 'type': 'String', 'description': '', 'name': 'string1' }, { 'type': 'String', 'description': '', 'name': 'string2' } ], 'type': 'Algorithm', 'description': '' }, # An algorithm for testing computed Geometries. 'Geometry.bounds': { 'returns': 'Geometry', 'hidden': False, 'args': [ { 'type': 'Geometry', 'description': '', 'name': 'geometry' }, { 'default': None, 'type': 'ErrorMargin', 'optional': True, 'description': '', 'name': 'maxError' }, { 'default': None, 'type': 'Projection', 'optional': True, 'description': '', 'name': 'proj' } ], 'type': 'Algorithm', 'description': '' }, 'Geometry.centroid': { 'returns': 'Geometry', 'args': [ { 'description': '', 'name': 'geometry', 'type': 'Geometry' }, { 'default': None, 'description': '', 'optional': True, 'name': 'maxError', 'type': 'ErrorMargin' }, { 'default': None, 'description': '', 'optional': True, 'name': 'proj', 'type': 'Projection' } ], 'description': '', 'type': 'Algorithm', }, 'GeometryConstructors.Point': { 'returns': 'Geometry', 'args': [ { 'name': 'coordinates', 'type': 'List<Number>', 'description': '' }, { 'name': 'crs', 'type': 'Projection', 'description': '', 'optional': True, 'default': 'epsg:4326' } ], 'type': 'Algorithm', 'description': '' }, 'GeometryConstructors.LineString': { 'returns': 'Geometry', 'args': [ { 'name': 'coordinates', 'type': 'List<Object>', 'description': '' }, { 'name': 'crs', 'type': 'Projection', 'description': '', 'optional': True, 'default': 'epsg:4326' }, { 'default': None, 'description': '', 'optional': True, 'name': 'geodesic', 'type': 'Boolean' }, { 'default': None, 'description': '', 'optional': True, 'name': 'maxError', 'type': 'ErrorMargin' }, ], 'type': 'Algorithm', 'description': '' }, # Element property setting, used by the client-side override. 'Element.set': { 'returns': 'Element', 'hidden': False, 'args': [ { 'type': 'Element', 'description': '', 'name': 'object' }, { 'type': 'String', 'description': '', 'name': 'key' }, { 'type': 'Object', 'description': '', 'name': 'value' } ], 'type': 'Algorithm', 'description': '' }, 'Element.setMulti': { 'returns': 'Element', 'hidden': False, 'args': [ { 'type': 'Element', 'description': '', 'name': 'object' }, { 'type': 'Dictionary<Object>', 'description': '', 'name': 'properties' } ], 'type': 'Algorithm', 'description': '' }, 'Image.geometry': { 'returns': 'Geometry', 'args': [ { 'description': '', 'name': 'feature', 'type': 'Element' }, { 'default': None, 'description': '', 'optional': True, 'name': 'maxError', 'type': 'ErrorMargin' }, { 'default': None, 'description': '', 'optional': True, 'name': 'proj', 'type': 'Projection' }, { 'default': None, 'description': '', 'optional': True, 'name': 'geodesics', 'type': 'Boolean' } ], 'type': 'Algorithm', 'description': '', }, 'Number.add': { 'returns': 'Number', 'hidden': False, 'args': [ { 'type': 'Number', 'description': '', 'name': 'left' }, { 'type': 'Number', 'description': '', 'name': 'right' } ], 'type': 'Algorithm', 'description': '' }, 'Array': { 'returns': 'Array', 'hidden': False, 'args': [ { 'name': 'values', 'type': 'Object' }, { 'name': 'pixelType', 'type': 'PixelType', 'optional': True, 'default': None } ], 'type': 'Algorithm', 'description': '' }, 'List.slice': { 'returns': 'List<Object>', 'args': [ { 'type': 'List<Object>', 'name': 'list' }, { 'type': 'Integer', 'name': 'start' }, { 'default': None, 'type': 'Integer', 'optional': True, 'name': 'end' } ], 'type': 'Algorithm', 'description': '', }, 'List.map': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'list', 'type': 'List' }, { 'description': '', 'name': 'baseAlgorithm', 'type': 'Algorithm' }, ], 'description': '', 'returns': 'List' }, 'Profile.getProfiles': { 'args': [ { 'description': '', 'name': 'ids', 'type': 'List<String>' }, { 'default': 'text', 'description': '', 'name': 'format', 'optional': True, 'type': 'String' } ], 'description': '', 'returns': 'Object', 'type': 'Algorithm', 'hidden': True }, 'Profile.getProfilesInternal': { 'args': [ { 'description': '', 'name': 'ids', 'type': 'List<String>' }, { 'default': 'text', 'description': '', 'name': 'format', 'optional': True, 'type': 'String' } ], 'description': '', 'returns': 'Object', 'type': 'Algorithm', 'hidden': True }, 'Projection': { 'returns': 'Projection', 'type': 'Algorithm', 'description': '', 'args': [ { 'name': 'crs', 'type': 'Object', 'description': '' }, { 'name': 'transform', 'default': None, 'type': 'List<Number>', 'optional': True, 'description': '' }, { 'name': 'transformWkt', 'default': None, 'type': 'String', 'optional': True, 'description': '', } ] }, 'Image.cast': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'image', 'type': 'Image' }, { 'description': '', 'name': 'bandTypes', 'type': 'Dictionary' }, { 'default': None, 'description': '', 'optional': True, 'name': 'bandOrder', 'type': 'List' } ], 'description': '', 'returns': 'Image' }, 'Describe': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'input', 'type': 'Object' } ], 'description': '', 'returns': 'Object', }, 'Image.rename': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'input', 'type': 'Image' }, { 'description': '', 'name': 'names', 'type': 'List' } ], 'description': '', 'returns': 'Image' }, 'Dictionary': { 'type': 'Algorithm', 'args': [ { 'description': '', 'name': 'input', 'optional': 'true', 'type': 'Object' } ], 'returns': 'Dictionary' }, } # A sample of encoded EE API JSON, used by SerializerTest and DeserializerTest. ENCODED_JSON_SAMPLE = { 'type': 'CompoundValue', 'scope': [ ['0', { 'type': 'Invocation', 'functionName': 'Date', 'arguments': { 'value': 1234567890000 } }], ['1', { 'type': 'LineString', 'coordinates': [[1, 2], [3, 4]], 'crs': { 'type': 'name', 'properties': { 'name': 'SR-ORG:6974' } } }], ['2', { 'evenOdd': True, 'type': 'Polygon', 'coordinates': [ [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]], [[5, 6], [7, 6], [7, 8], [5, 8]], [[1, 1], [2, 1], [2, 2], [1, 2]] ] }], ['3', { 'type': 'Bytes', 'value': 'aGVsbG8=' }], ['4', { 'type': 'Invocation', 'functionName': 'String.cat', 'arguments': { 'string1': 'x', 'string2': 'y' } }], ['5', { 'type': 'Dictionary', 'value': { 'foo': 'bar', 'baz': {'type': 'ValueRef', 'value': '4'} } }], ['6', { 'type': 'Function', 'argumentNames': ['x', 'y'], 'body': {'type': 'ArgumentRef', 'value': 'y'} }], ['7', [ None, True, 5, 7, 3.4, 2.5, 'hello', {'type': 'ValueRef', 'value': '0'}, {'type': 'ValueRef', 'value': '1'}, {'type': 'ValueRef', 'value': '2'}, {'type': 'ValueRef', 'value': '3'}, {'type': 'ValueRef', 'value': '5'}, {'type': 'ValueRef', 'value': '4'}, {'type': 'ValueRef', 'value': '6'} ]] ], 'value': {'type': 'ValueRef', 'value': '7'} }
#!/usr/bin/env python #============================================================================== # Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use # this file except in compliance with the License. A copy of the License is # located at # # http://aws.amazon.com/asl/ # # or in the "license" file accompanying this file. This file is distributed on # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or # implied. See the License for the specific language governing permissions # and limitations under the License. #============================================================================== import re import logging from lib.elasticbeanstalk.request import TemplateSpecification from lib.utility import misc, shell_utils from scli import api_wrapper, config_file, prompt from scli.constants import DevToolsEndpoint, DevToolsDefault, DefaultAppSource, \ OptionSettingVPC, OptionSettingEnvironmentType, OptionSettingApplicationEnvironment, \ OptionSettingContainerPrefix, OptionSettingTemplatePrefix, \ ParameterName as PName, ParameterSource as PSource, ServiceDefault, ServiceEndpoint from scli.parameter import Parameter from scli.resources import DevToolsMessage, ValidationMessage from scli.terminal.base import TerminalBase log = logging.getLogger('eb') def generate_endpoint(parameter_pool, region, source, force = False): parameter_pool.put(Parameter(PName.ServiceEndpoint, ServiceEndpoint[region], source)) parameter_pool.put(Parameter(PName.DevToolsEndpoint, DevToolsEndpoint[region], source)) def has_default_app(parameter_pool, solution_stack, eb_client = None): appsource_options = {DefaultAppSource.Namespace : {DefaultAppSource.OptionName}} if not eb_client: eb_client = api_wrapper.create_eb_client(parameter_pool) spec = TemplateSpecification() spec.template_source.solution_stack_name = solution_stack, options = api_wrapper.retrieve_configuration_options(eb_client = eb_client, solution_stack = solution_stack, options = appsource_options, template_specification = spec) for option in options: if misc.string_equal_ignore_case(DefaultAppSource.Namespace, option.namespace) \ and misc.string_equal_ignore_case(DefaultAppSource.OptionName, option.name): return True return False def trim_vpc_options(parameter_pool, option_settings, option_to_remove): if OptionSettingVPC.Namespace in option_settings\ and OptionSettingVPC.MagicOptionName in option_settings[OptionSettingVPC.Namespace]\ and not misc.is_blank_string(option_settings[OptionSettingVPC.Namespace]\ [OptionSettingVPC.MagicOptionName]): # VPC enabled for namespace in OptionSettingVPC.TrimOption: for option in OptionSettingVPC.TrimOption[namespace]: remove_option_setting(option_settings, option_to_remove, namespace, option) # Reapply DBSubnets if RDS is enabled if parameter_pool.get_value(PName.RdsEnabled): option_location = parameter_pool.get_value(PName.OptionSettingFile, False) ori_option_settings = config_file.load_env_option_setting_file(option_location, quiet = True) if OptionSettingVPC.Namespace in ori_option_settings\ and OptionSettingVPC.DBSubnets in ori_option_settings[OptionSettingVPC.Namespace]: dbsubnets = ori_option_settings[OptionSettingVPC.Namespace][OptionSettingVPC.DBSubnets] if not misc.is_blank_string(dbsubnets): add_option_setting(option_settings, option_to_remove, OptionSettingVPC.Namespace, OptionSettingVPC.DBSubnets, dbsubnets) else: # VPC disabled remove_option_namespace(option_settings, option_to_remove, OptionSettingVPC.Namespace) def apply_environment_type(parameter_pool, template_spec, stack_name, env_name, option_settings, option_to_remove): # If not specified, skip envtype = parameter_pool.get_value(PName.EnvironmentType) if envtype: # Describe applicable option settings eb_client = api_wrapper.create_eb_client(parameter_pool) app_name = parameter_pool.get_value(PName.ApplicationName, False) if env_name: raw_option_defs = api_wrapper.retrieve_configuration_options(eb_client=eb_client, app_name=app_name, env_name=env_name, template_specification=template_spec, options=None) else: raw_option_defs = api_wrapper.retrieve_configuration_options(eb_client=eb_client, app_name=app_name, solution_stack=stack_name, template_specification=template_spec, options=None) option_defs = set() for raw_option_def in raw_option_defs: option_defs.add(raw_option_def.namespace + u'-' + raw_option_def.name) # Return if environment type option is not available if OptionSettingEnvironmentType.Namespace + u'-' + \ OptionSettingEnvironmentType.OptionName not in option_defs: prompt.result(ValidationMessage.EnvTypeInapplicable.format(envtype)) return # remove inapplicable option settings removed = False for namespace in option_settings.keys(): # TODO Fix this temporary hack to let environment tier options pass through if namespace == u'aws:elasticbeanstalk:sqsd': continue for option_name in option_settings[namespace].keys(): if not is_customizable_namespace(namespace)\ and namespace + u'-' + option_name not in option_defs: remove_option_setting(option_settings, option_to_remove, namespace, option_name, False) removed = True if removed: prompt.result(ValidationMessage.EnvTypeBlowAwayOptionSettings) # Set environment type add_option_setting(option_settings, option_to_remove, OptionSettingEnvironmentType.Namespace, OptionSettingEnvironmentType.OptionName, envtype) def check_app_version(parameter_pool, eb_client = None): #TODO: Do we need to blast version info away if this part is strong enough? if not parameter_pool.has(PName.ApplicationVersionName) \ or parameter_pool.get_source(PName.ApplicationVersionName) == PSource.Default: version_name = get_head_version(parameter_pool, eb_client=eb_client, quiet=True) if version_name is not None: log.info(u'Found a version from local repository: {0}. Using this version.'.\ format(version_name)) return version_name else: # Otherwise try push a new one if not parameter_pool.get_value(PName.Force) == ServiceDefault.ENABLED\ and not TerminalBase.ask_confirmation(DevToolsMessage.PushLocalHead): return ServiceDefault.DEFAULT_VERSION_NAME else: if shell_utils.git_aws_push(push_only=True, quiet=False): version_name = get_head_version(parameter_pool, eb_client=eb_client, quiet=False) if version_name: return version_name return ServiceDefault.DEFAULT_VERSION_NAME else: # Verify existence of version app_name = parameter_pool.get_value(PName.ApplicationName, False) version_names = api_wrapper.get_all_versions(parameter_pool, app_name, eb_client) version_name = parameter_pool.get_value(PName.ApplicationVersionName) if version_name in version_names: # Assume version is still valid and compatible with current solution stack return version_name else: # return ServiceDefault.DEFAULT_VERSION_NAME def get_head_version(parameter_pool, eb_client = None, quiet = True): # Get all versions app_name = parameter_pool.get_value(PName.ApplicationName, False) version_names = api_wrapper.get_all_versions(parameter_pool, app_name, eb_client) # Try get local commit HEAD hash head_hash = shell_utils.get_repo_head_hash(quiet) if head_hash is None: return ServiceDefault.DEFAULT_VERSION_NAME # Try find a version corresponding to local HEAD version_re = re.compile(DevToolsDefault.VersionNameRe.format(head_hash),re.UNICODE) timestamp = 0 for version in version_names: if version_re.match(version): cur_timestamp = int(version.split(DevToolsDefault.NameDelimiter)[2]) timestamp = cur_timestamp if cur_timestamp > timestamp else timestamp if timestamp > 0: # Found a version generated from local repos HEAD log.info(u'Found a version generated from local HEAD {0}. Using this version.'.\ format(head_hash)) return DevToolsDefault.VersionNameMask.format(head_hash, timestamp) else: return None # Add/update an option setting of specified value to option setting dict def add_option_setting(option_settings, option_remove, namespace, option, value): if namespace not in option_settings: option_settings[namespace] = dict() option_settings[namespace][option] = value if namespace in option_remove and option in option_remove[namespace]: option_remove[namespace].remove(option) # Remove an option setting from option setting dict def remove_option_setting(option_settings, option_remove, namespace, option, add_to_remove = True): if namespace in option_settings and option in option_settings[namespace]: del option_settings[namespace][option] if len(option_settings[namespace]) < 1: del option_settings[namespace] if add_to_remove: if namespace not in option_remove: option_remove[namespace] = set() option_remove[namespace].add(option) # Remove an entire option namespace from option setting dict def remove_option_namespace(option_settings, option_remove, namespace, add_to_remove = True): if namespace in option_settings: if add_to_remove: for option in option_settings[namespace].keys(): remove_option_setting(option_settings, option_remove, namespace, option, True) else: del option_settings[namespace] # Get definition for a particular option setting def get_option_def(eb_client, app_name, namespace, option_name, solution_stack = None, env_name = None): options = dict() options[namespace] = set() options[namespace].add(option_name) optionDef = api_wrapper.retrieve_configuration_options(eb_client = eb_client, app_name = app_name, solution_stack =solution_stack, options = options) if len(optionDef) > 0: return optionDef[0] else: return None def is_customizable_namespace(namespace): if namespace.startswith(OptionSettingApplicationEnvironment.Namespace)\ or namespace.startswith(OptionSettingContainerPrefix) \ or namespace.startswith(OptionSettingTemplatePrefix): return True else: return False
# -*- coding: utf-8 -*- ''' The Django Admin Generator is a project which can automatically generate (scaffold) a Django Admin for you. By doing this it will introspect your models and automatically generate an Admin with properties like: - `list_display` for all local fields - `list_filter` for foreign keys with few items - `raw_id_fields` for foreign keys with a lot of items - `search_fields` for name and `slug` fields - `prepopulated_fields` for `slug` fields - `date_hierarchy` for `created_at`, `updated_at` or `joined_at` fields The original source and latest version can be found here: https://github.com/WoLpH/django-admin-generator/ ''' import optparse import re import sys from django.conf import settings from django.core.management.base import BaseCommand from django.db import models from django_extensions.compat import get_apps, get_models_compat from django_extensions.management.color import color_style from django_extensions.management.utils import signalcommand # Configurable constants MAX_LINE_WIDTH = getattr(settings, 'MAX_LINE_WIDTH', 78) INDENT_WIDTH = getattr(settings, 'INDENT_WIDTH', 4) LIST_FILTER_THRESHOLD = getattr(settings, 'LIST_FILTER_THRESHOLD', 25) RAW_ID_THRESHOLD = getattr(settings, 'RAW_ID_THRESHOLD', 100) LIST_FILTER = getattr(settings, 'LIST_FILTER', ( models.DateField, models.DateTimeField, models.ForeignKey, models.BooleanField, )) SEARCH_FIELD_NAMES = getattr(settings, 'SEARCH_FIELD_NAMES', ( 'name', 'slug', )) DATE_HIERARCHY_NAMES = getattr(settings, 'DATE_HIERARCHY_NAMES', ( 'joined_at', 'updated_at', 'created_at', )) PREPOPULATED_FIELD_NAMES = getattr(settings, 'PREPOPULATED_FIELD_NAMES', ( 'slug=name', )) PRINT_IMPORTS = getattr(settings, 'PRINT_IMPORTS', '''# -*- coding: utf-8 -*- from django.contrib import admin from .models import %(models)s ''') PRINT_ADMIN_CLASS = getattr(settings, 'PRINT_ADMIN_CLASS', ''' class %(name)sAdmin(admin.ModelAdmin):%(class_)s admin.site.register(%(name)s, %(name)sAdmin) ''') PRINT_ADMIN_PROPERTY = getattr(settings, 'PRINT_ADMIN_PROPERTY', ''' %(key)s = %(value)s''') class UnicodeMixin(object): """Mixin class to handle defining the proper __str__/__unicode__ methods in Python 2 or 3.""" if sys.version_info[0] >= 3: # Python 3 def __str__(self): return self.__unicode__() else: # Python 2 def __str__(self): return self.__unicode__().encode('utf8') class AdminApp(UnicodeMixin): def __init__(self, app, model_res, **options): self.app = app self.model_res = model_res self.options = options def __iter__(self): for model in get_models_compat(self.app): admin_model = AdminModel(model, **self.options) for model_re in self.model_res: if model_re.search(admin_model.name): break else: if self.model_res: continue yield admin_model def __unicode__(self): return ''.join(self._unicode_generator()) def _unicode_generator(self): models_list = [admin_model.name for admin_model in self] yield PRINT_IMPORTS % dict(models=', '.join(models_list)) admin_model_names = [] for admin_model in self: yield PRINT_ADMIN_CLASS % dict( name=admin_model.name, class_=admin_model, ) admin_model_names.append(admin_model.name) def __repr__(self): return '<%s[%s]>' % ( self.__class__.__name__, self.app, ) class AdminModel(UnicodeMixin): PRINTABLE_PROPERTIES = ( 'list_display', 'list_filter', 'raw_id_fields', 'search_fields', 'prepopulated_fields', 'date_hierarchy', ) def __init__(self, model, raw_id_threshold=RAW_ID_THRESHOLD, list_filter_threshold=LIST_FILTER_THRESHOLD, search_field_names=SEARCH_FIELD_NAMES, date_hierarchy_names=DATE_HIERARCHY_NAMES, prepopulated_field_names=PREPOPULATED_FIELD_NAMES, **options): self.model = model self.list_display = [] self.list_filter = [] self.raw_id_fields = [] self.search_fields = [] self.prepopulated_fields = {} self.date_hierarchy = None self.search_field_names = search_field_names self.raw_id_threshold = raw_id_threshold self.list_filter_threshold = list_filter_threshold self.date_hierarchy_names = date_hierarchy_names self.prepopulated_field_names = prepopulated_field_names def __repr__(self): return '<%s[%s]>' % ( self.__class__.__name__, self.name, ) @property def name(self): return self.model.__name__ def _process_many_to_many(self, meta): raw_id_threshold = self.raw_id_threshold for field in meta.local_many_to_many: related_model = getattr(field.related, 'related_model', field.related.model) related_objects = related_model.objects.all() if(related_objects[:raw_id_threshold].count() < raw_id_threshold): yield field.name def _process_fields(self, meta): parent_fields = meta.parents.values() for field in meta.fields: name = self._process_field(field, parent_fields) if name: yield name def _process_foreign_key(self, field): raw_id_threshold = self.raw_id_threshold list_filter_threshold = self.list_filter_threshold max_count = max(list_filter_threshold, raw_id_threshold) related_model = getattr(field.related, 'related_model', field.related.model) related_count = related_model.objects.all() related_count = related_count[:max_count].count() if related_count >= raw_id_threshold: self.raw_id_fields.append(field.name) elif related_count < list_filter_threshold: self.list_filter.append(field.name) else: # pragma: no cover pass # Do nothing :) def _process_field(self, field, parent_fields): if field in parent_fields: return self.list_display.append(field.name) if isinstance(field, LIST_FILTER): if isinstance(field, models.ForeignKey): self._process_foreign_key(field) else: self.list_filter.append(field.name) if field.name in self.search_field_names: self.search_fields.append(field.name) return field.name def __unicode__(self): return ''.join(self._unicode_generator()) def _yield_value(self, key, value): if isinstance(value, (list, set, tuple)): return self._yield_tuple(key, tuple(value)) elif isinstance(value, dict): return self._yield_dict(key, value) elif isinstance(value, str): return self._yield_string(key, value) else: # pragma: no cover raise TypeError('%s is not supported in %r' % (type(value), value)) def _yield_string(self, key, value, converter=repr): return PRINT_ADMIN_PROPERTY % dict( key=key, value=converter(value), ) def _yield_dict(self, key, value): row_parts = [] row = self._yield_string(key, value) if len(row) > MAX_LINE_WIDTH: row_parts.append(self._yield_string(key, '{', str)) for k, v in value.items(): row_parts.append('%s%r: %r' % (2 * INDENT_WIDTH * ' ', k, v)) row_parts.append(INDENT_WIDTH * ' ' + '}') row = '\n'.join(row_parts) return row def _yield_tuple(self, key, value): row_parts = [] row = self._yield_string(key, value) if len(row) > MAX_LINE_WIDTH: row_parts.append(self._yield_string(key, '(', str)) for v in value: row_parts.append(2 * INDENT_WIDTH * ' ' + repr(v) + ',') row_parts.append(INDENT_WIDTH * ' ' + ')') row = '\n'.join(row_parts) return row def _unicode_generator(self): self._process() for key in self.PRINTABLE_PROPERTIES: value = getattr(self, key) if value: yield self._yield_value(key, value) def _process(self): meta = self.model._meta self.raw_id_fields += list(self._process_many_to_many(meta)) field_names = list(self._process_fields(meta)) for field_name in self.date_hierarchy_names[::-1]: if field_name in field_names and not self.date_hierarchy: self.date_hierarchy = field_name break for k in sorted(self.prepopulated_field_names): k, vs = k.split('=', 1) vs = vs.split(',') if k in field_names: incomplete = False for v in vs: if v not in field_names: incomplete = True break if not incomplete: self.prepopulated_fields[k] = vs self.processed = True class Command(BaseCommand): help = '''Generate a `admin.py` file for the given app (models)''' option_list = BaseCommand.option_list + ( optparse.make_option( '-s', '--search-field', action='append', default=SEARCH_FIELD_NAMES, help='Fields named like this will be added to `search_fields`' ' [default: %default]'), optparse.make_option( '-d', '--date-hierarchy', action='append', default=DATE_HIERARCHY_NAMES, help='A field named like this will be set as `date_hierarchy`' ' [default: %default]'), optparse.make_option( '-p', '--prepopulated-fields', action='append', default=PREPOPULATED_FIELD_NAMES, help='These fields will be prepopulated by the other field.' 'The field names can be specified like `spam=eggA,eggB,eggC`' ' [default: %default]'), optparse.make_option( '-l', '--list-filter-threshold', type='int', default=LIST_FILTER_THRESHOLD, metavar='LIST_FILTER_THRESHOLD', help='If a foreign key has less than LIST_FILTER_THRESHOLD items ' 'it will be added to `list_filter` [default: %default]'), optparse.make_option( '-r', '--raw-id-threshold', type='int', default=RAW_ID_THRESHOLD, metavar='RAW_ID_THRESHOLD', help='If a foreign key has more than RAW_ID_THRESHOLD items ' 'it will be added to `list_filter` [default: %default]'), ) can_import_settings = True @signalcommand def handle(self, *args, **kwargs): self.style = color_style() installed_apps = dict((a.__name__.rsplit('.', 1)[0], a) for a in get_apps()) # Make sure we always have args if not args: args = [False] app = installed_apps.get(args[0]) if not app: print(self.style.WARN('This command requires an existing app name as argument')) print(self.style.WARN('Available apps:')) for app in sorted(installed_apps): print(self.style.WARN(' %s' % app)) sys.exit(1) model_res = [] for arg in args[1:]: model_res.append(re.compile(arg, re.IGNORECASE)) self.handle_app(app, model_res, **kwargs) def handle_app(self, app, model_res, **options): print(AdminApp(app, model_res, **options))
from gi.repository import Gtk, Gio, GLib from gi.repository import AppIndicator3 as appindicator from xml.dom import minidom import json, os, webbrowser, datetime, urlparse import pytz import dateutil.parser class Main(object): def __init__(self): icon_path = os.path.normpath(os.path.abspath(os.path.split(__file__)[0])) icon_path = os.path.join(icon_path, "icons") self.ind = appindicator.Indicator.new_with_path ( "syncthing-indicator", "syncthing-client-idle", appindicator.IndicatorCategory.APPLICATION_STATUS, icon_path) self.ind.set_attention_icon ("syncthing-client-updating") self.ind.set_status (appindicator.IndicatorStatus.ACTIVE) self.connected_nodes = [] self.downloading_files = [] self.uploading_files = [] self.recent_files = [] self.menu = Gtk.Menu() self.last_checked_menu = Gtk.MenuItem("Last checked: ?") self.last_checked_menu.show() self.last_checked_menu.set_sensitive(False) self.menu.append(self.last_checked_menu) self.update_last_checked(datetime.datetime.now(pytz.utc).isoformat()) self.connected_nodes_menu = Gtk.MenuItem("Connected to: ?") self.connected_nodes_menu.show() self.connected_nodes_menu.set_sensitive(False) self.menu.append(self.connected_nodes_menu) self.update_connected_nodes() self.current_files_menu = Gtk.MenuItem("Current files") self.current_files_menu.show() self.menu.append(self.current_files_menu) self.current_files_submenu = Gtk.Menu() self.current_files_menu.set_submenu(self.current_files_submenu) self.recent_files_menu = Gtk.MenuItem("Recently synced") self.menu.append(self.recent_files_menu) self.recent_files_submenu = Gtk.Menu() self.recent_files_menu.set_submenu(self.recent_files_submenu) self.update_current_files() open_web_ui = Gtk.MenuItem("Open web interface") open_web_ui.connect("activate", self.open_web_ui) open_web_ui.show() self.menu.append(open_web_ui) self.ind.set_menu(self.menu) self.syncthing_update_menu = Gtk.MenuItem("Update check") self.syncthing_update_menu.connect("activate", self.open_releases_page) self.menu.append(self.syncthing_update_menu) self.syncthing_base = "http://localhost:8080" GLib.idle_add(self.start_load_config) def start_load_config(self): confdir = GLib.get_user_config_dir() if not confdir: confdir = os.path.expanduser("~/.config") conffile = os.path.join(confdir, "syncthing", "config.xml") if not os.path.isfile(conffile): print "Couldn't find config file." f = Gio.file_new_for_path(conffile) f.load_contents_async(None, self.finish_load_config) def finish_load_config(self, fp, async_result): try: success, data, etag = fp.load_contents_finish(async_result) except: return self.bail_releases("Couldn't open config file") try: dom = minidom.parseString(data) except: return self.bail_releases("Couldn't parse config file") conf = dom.getElementsByTagName("configuration") if not conf: return self.bail_releases("No configuration element in config") gui = conf[0].getElementsByTagName("gui") if not gui: return self.bail_releases("No gui element in config") address = gui[0].getElementsByTagName("address") if not address: return self.bail_releases("No address element in config") if not address[0].hasChildNodes(): return self.bail_releases("No address specified in config") self.syncthing_base = "http://%s" % address[0].firstChild.nodeValue GLib.idle_add(self.start_poll) GLib.idle_add(self.check_for_syncthing_update) def syncthing(self, url): return urlparse.urljoin(self.syncthing_base, url) def open_web_ui(self, *args): webbrowser.open(self.syncthing("")) def open_releases_page(self, *args): webbrowser.open('https://github.com/calmh/syncthing/releases') def check_for_syncthing_update(self): f = Gio.file_new_for_uri("https://github.com/calmh/syncthing/releases.atom") f.load_contents_async(None, self.fetch_releases) def bail_releases(self, message): print message GLib.timeout_add_seconds(600, self.check_for_syncthing_update) def fetch_releases(self, fp, async_result): try: success, data, etag = fp.load_contents_finish(async_result) except: return self.bail_releases("Request for github releases list failed: error") try: dom = minidom.parseString(data) except: return self.bail_releases("Couldn't parse github release xml") entries = dom.getElementsByTagName("entry") if not entries: return self.bail_releases("Github release list had no entries") title = entries[0].getElementsByTagName("title") if not title: return self.bail_releases("Github release list first entry had no title") title = title[0] if not title.hasChildNodes(): return self.bail_releases("Github release list first entry had empty title") title = title.firstChild.nodeValue f = Gio.file_new_for_uri(self.syncthing("/rest/version")) f.load_contents_async(None, self.fetch_local_version, title) def fetch_local_version(self, fp, async_result, most_recent_release): try: success, local_version, etag = fp.load_contents_finish(async_result) except: return self.bail_releases("Request for local version failed") if most_recent_release != local_version: self.syncthing_update_menu.set_label("New version %s available!" % (most_recent_release,)) self.syncthing_update_menu.show() else: self.syncthing_update_menu.hide() GLib.timeout_add_seconds(28800, self.check_for_syncthing_update) def start_poll(self): # when this is actually in syncthing, this is what to use # f = Gio.file_new_for_uri(self.syncthing("/rest/events/0")) f = Gio.file_new_for_uri("http://localhost:5115") f.load_contents_async(None, self.fetch_poll) def fetch_poll(self, fp, async_result): try: success, data, etag = fp.load_contents_finish(async_result) except: print "request failed: error" GLib.timeout_add_seconds(10, self.start_poll) self.ind.set_icon_full("syncthing-client-error", "Couldn't connect to syncthing") return if success: try: queue = json.loads(data) except ValueError: print "request failed to parse json: error" GLib.timeout_add_seconds(10, self.start_poll) self.ind.set_icon_full("syncthing-client-error", "Couldn't connect to syncthing") for qitem in queue: self.process_event(qitem) else: print "request failed" if self.downloading_files or self.uploading_files: self.ind.set_icon_full("syncthing-client-updating", "Updating %s files" % ( len(self.downloading_files) + len(self.uploading_files))) else: self.ind.set_icon_full("syncthing-client-idle", "Up to date") GLib.idle_add(self.start_poll) def process_event(self, event): t = event.get("type", "unknown_event").lower() fn = getattr(self, "event_%s" % t, self.event_unknown_event)(event) self.update_last_checked(event["timestamp"]) def event_timeout(self, event): #print "event timeout; re-polling." pass def event_unknown_event(self, event): print "got unknown event", event def event_node_connected(self, event): self.connected_nodes.append(event["params"]["node"]) self.update_connected_nodes() def event_node_disconnected(self, event): try: self.connected_nodes.remove(event["params"]["node"]) except ValueError: print "A node %s disconnected but we didn't know about it" self.update_connected_nodes() def event_pull_start(self, event): file_details = {"repo": event["params"].get("repo"), "file": event["params"].get("file")} self.downloading_files.append(file_details) self.update_current_files() def event_pull_complete(self, event): file_details = {"repo": event["params"].get("repo"), "file": event["params"].get("file")} try: self.downloading_files.remove(file_details) except ValueError: print "Completed a file %s which we didn't know about" % (event["params"]["file"],) self.recent_files.append({"file": event["params"]["file"], "direction": "down", "time": datetime.datetime.now()}) self.recent_files = self.recent_files[-5:] self.update_current_files() def update_last_checked(self, isotime): dt = dateutil.parser.parse(isotime) self.last_checked_menu.set_label("Last checked: %s" % (dt.strftime("%H.%M"),)) def update_connected_nodes(self): self.connected_nodes_menu.set_label("Connected machines: %s" % ( len(self.connected_nodes),)) def update_current_files(self): self.current_files_menu.set_label(u"Syncing \u21d1 %s \u21d3 %s" % ( len(self.uploading_files), len(self.downloading_files))) if (len(self.uploading_files), len(self.downloading_files)) == (0,0): self.current_files_menu.hide() else: # repopulate the current files menu for child in self.current_files_submenu.get_children(): self.current_files_submenu.remove(child) for f in self.uploading_files: mi = Gtk.MenuItem(u"\u21d1 %s" % f["file"]) self.current_files_submenu.append(mi) mi.show() for f in self.downloading_files: mi = Gtk.MenuItem(u"\u21d3 %s" % f["file"]) self.current_files_submenu.append(mi) mi.show() self.current_files_menu.show() # repopulate the recent files menu if not self.recent_files: self.recent_files_menu.hide() else: for child in self.recent_files_submenu.get_children(): self.recent_files_submenu.remove(child) for f in self.recent_files: if f["direction"] == "down": updown = u"\u21d3" elif f["direction"] == "up": updown = u"\u21d1" else: updown = u"?" mi = Gtk.MenuItem(u"%s %s (%s)" % ( updown, f["file"], f["time"].strftime("%H.%M"))) self.recent_files_submenu.append(mi) mi.show() self.recent_files_menu.show() if __name__ == "__main__": import signal signal.signal(signal.SIGINT, signal.SIG_DFL) app = Main() Gtk.main()
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import re import sys import subprocess def RunCmdAndCheck(cmd, err_string, output_api, cwd=None): results = [] p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_stdout, p_stderr) = p.communicate() if p.returncode: results.append( output_api.PresubmitError(err_string, long_text=p_stderr)) return results def RunUnittests(input_api, output_api): # Run some Generator unittests if the generator source was changed. results = [] files = input_api.LocalPaths() generator_files = [] for filename in files: name_parts = filename.split(os.sep) if name_parts[0:2] == ['ppapi', 'generators']: generator_files.append(filename) if generator_files != []: cmd = [ sys.executable, 'idl_gen_pnacl.py', '--wnone', '--test'] ppapi_dir = input_api.PresubmitLocalPath() results.extend(RunCmdAndCheck(cmd, 'PPAPI IDL Pnacl unittest failed.', output_api, os.path.join(ppapi_dir, 'generators'))) return results # If any .srpc files were changed, run run_srpcgen.py --diff_mode. def CheckSrpcChange(input_api, output_api): if [True for filename in input_api.LocalPaths() if os.path.splitext(filename)[1] == '.srpc']: return RunCmdAndCheck([sys.executable, os.path.join(input_api.PresubmitLocalPath(), 'native_client', 'src', 'shared', 'ppapi_proxy', 'run_srpcgen.py'), '--diff_mode'], 'PPAPI SRPC Diff detected: Run run_srpcgen.py.', output_api) return [] # Verify that the files do not contain a 'TODO' in them. RE_TODO = re.compile(r'\WTODO\W', flags=re.I) def CheckTODO(input_api, output_api): files = input_api.LocalPaths() todo = [] for filename in files: name, ext = os.path.splitext(filename) name_parts = name.split(os.sep) # Only check normal build sources. if ext not in ['.h', '.cc', '.idl']: continue # Only examine the ppapi directory. if name_parts[0] != 'ppapi': continue # Only examine public plugin facing directories. if name_parts[1] not in ['api', 'c', 'cpp', 'utility']: continue # Only examine public stable interfaces. if name_parts[2] in ['dev', 'private', 'trusted']: continue filepath = os.path.join('..', filename) if RE_TODO.search(open(filepath, 'rb').read()): todo.append(filename) if todo: return [output_api.PresubmitError( 'TODOs found in stable public PPAPI files:', long_text='\n'.join(todo))] return [] # Verify that no CPP wrappers use un-versioned PPB interface name macros. RE_UNVERSIONED_PPB = re.compile(r'\bPPB_\w+_INTERFACE\b') def CheckUnversionedPPB(input_api, output_api): files = input_api.LocalPaths() todo = [] for filename in files: name, ext = os.path.splitext(filename) name_parts = name.split(os.sep) # Only check C++ sources. if ext not in ['.cc']: continue # Only examine the public plugin facing ppapi/cpp directory. if name_parts[0:2] != ['ppapi', 'cpp']: continue # Only examine public stable and trusted interfaces. if name_parts[2] in ['dev', 'private']: continue filepath = os.path.join('..', filename) if RE_UNVERSIONED_PPB.search(open(filepath, 'rb').read()): todo.append(filename) if todo: return [output_api.PresubmitError( 'Unversioned PPB interface references found in PPAPI C++ wrappers:', long_text='\n'.join(todo))] return [] def CheckChange(input_api, output_api): results = [] results.extend(CheckSrpcChange(input_api, output_api)) results.extend(RunUnittests(input_api, output_api)) results.extend(CheckTODO(input_api, output_api)) results.extend(CheckUnversionedPPB(input_api, output_api)) # Verify all modified *.idl have a matching *.h files = input_api.LocalPaths() h_files = [] idl_files = [] # Find all relevant .h and .idl files. for filename in files: name, ext = os.path.splitext(filename) name_parts = name.split(os.sep) if name_parts[0:2] == ['ppapi', 'c'] and ext == '.h': h_files.append('/'.join(name_parts[2:])) if name_parts[0:2] == ['ppapi', 'api'] and ext == '.idl': idl_files.append('/'.join(name_parts[2:])) # Generate a list of all appropriate *.h and *.idl changes in this CL. both = h_files + idl_files # If there aren't any, we are done checking. if not both: return results missing = [] for filename in idl_files: if filename not in set(h_files): missing.append('ppapi/api/%s.idl' % filename) # An IDL change that includes [generate_thunk] doesn't need to have # an update to the corresponding .h file. new_thunk_files = [] for filename in missing: lines = input_api.RightHandSideLines(lambda f: f.LocalPath() == filename) for line in lines: if line[2].strip() == '[generate_thunk]': new_thunk_files.append(filename) for filename in new_thunk_files: missing.remove(filename) if missing: results.append( output_api.PresubmitPromptWarning( 'Missing PPAPI header, no change or skipped generation?', long_text='\n '.join(missing))) missing_dev = [] missing_stable = [] missing_priv = [] for filename in h_files: if filename not in set(idl_files): name_parts = filename.split(os.sep) if 'trusted' in name_parts: missing_priv.append(' ppapi/c/%s.h' % filename) continue if 'private' in name_parts: missing_priv.append(' ppapi/c/%s.h' % filename) continue if 'dev' in name_parts: missing_dev.append(' ppapi/c/%s.h' % filename) continue missing_stable.append(' ppapi/c/%s.h' % filename) if missing_priv: results.append( output_api.PresubmitPromptWarning( 'Missing PPAPI IDL for private interface, please generate IDL:', long_text='\n'.join(missing_priv))) if missing_dev: results.append( output_api.PresubmitPromptWarning( 'Missing PPAPI IDL for DEV, required before moving to stable:', long_text='\n'.join(missing_dev))) if missing_stable: results.append( output_api.PresubmitError( 'Missing PPAPI IDL for stable interface:', long_text='\n'.join(missing_stable))) # Verify all *.h files match *.idl definitions, use: # --test to prevent output to disk # --diff to generate a unified diff # --out to pick which files to examine (only the ones in the CL) ppapi_dir = input_api.PresubmitLocalPath() cmd = [sys.executable, 'generator.py', '--wnone', '--diff', '--test','--cgen', '--range=start,end'] # Only generate output for IDL files references (as *.h or *.idl) in this CL cmd.append('--out=' + ','.join([name + '.idl' for name in both])) cmd_results = RunCmdAndCheck(cmd, 'PPAPI IDL Diff detected: Run the generator.', output_api, os.path.join(ppapi_dir, 'generators')) if cmd_results: results.extend(cmd_results) return results def CheckChangeOnUpload(input_api, output_api): return CheckChange(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return CheckChange(input_api, output_api)
import os import platform import subprocess import pytest from topaz.main import _entry_point class TestMain(object): def run(self, space, tmpdir, source=None, status=0, ruby_args=[], argv=[]): args = ["topaz"] args += ruby_args if source is not None: f = tmpdir.join("test.rb") f.write(source) args.append(str(f)) else: f = None args += argv res = _entry_point(space, args) assert res == status return f def assert_traceback(self, space, tmpdir, capfd, src, expected): f = self.run(space, tmpdir, src, status=1) out, err = capfd.readouterr() assert not out actual_lines = err.splitlines() expected_lines = [] for line in expected: expected_lines.append(line.format(f)) assert actual_lines == expected_lines def test_simple(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts 5") out, err = capfd.readouterr() assert out == "5\n" assert not err def test_expr(self, space, tmpdir, capfd): self.run(space, tmpdir, None, ruby_args=["-e", "puts 5", "-e", "puts 6"]) out, err = capfd.readouterr() assert out == "5\n6\n" self.run(space, tmpdir, None, ruby_args=["-eputs 'hi'"]) out, err = capfd.readouterr() assert out == "hi\n" def test_no_expr(self, space, tmpdir, capfd): self.run(space, tmpdir, None, ruby_args=["-e"], status=1) out, err = capfd.readouterr() assert err == u"no code specified for -e (RuntimeError)\n" assert out == "" def test___FILE__(self, space, tmpdir, capfd): f = self.run(space, tmpdir, "puts __FILE__") out, err = capfd.readouterr() assert out == "{}\n".format(f) def test_verbose(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts 5", ruby_args=["-v"]) out, err = capfd.readouterr() [version, out] = out.splitlines() assert version.startswith("topaz") assert "1.9.3" in version assert os.uname()[4] in version assert platform.system().lower() in version assert subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).rstrip() in version assert out == "5" self.run(space, tmpdir, ruby_args=["-v"]) out, err = capfd.readouterr() [version] = out.splitlines() assert version.startswith("topaz") def test_debug_defaults_to_false(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts $DEBUG") out, _ = capfd.readouterr() assert out.strip() == "false" def test_debug_sets_verbose(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts $VERBOSE", ruby_args=["-d"]) out, _ = capfd.readouterr() assert out.strip() == "true" def test_debug_sets_dash_d(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts $-d", ruby_args=["-d"]) out, _ = capfd.readouterr() assert out.strip() == "true" def test_dash_w_defaults_to_false(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts $-w") out, _ = capfd.readouterr() assert out.strip() == "false" def test_warnings_sets_dash_w(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts $-w", ruby_args=["-w"]) out, _ = capfd.readouterr() assert out.strip() == "true" def test_warning_level_defaults_to_verbose_true(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts $VERBOSE", ruby_args=["-W"]) out, _ = capfd.readouterr() assert out.strip() == "true" def test_help(self, space, tmpdir, capfd): self.run(space, tmpdir, ruby_args=["-h"]) out, _ = capfd.readouterr() assert out.splitlines()[0] == "Usage: topaz [switches] [--] [programfile] [arguments]" def test_copyright(self, space, tmpdir, capfd): self.run(space, tmpdir, ruby_args=["--copyright"]) out, _ = capfd.readouterr() [copyright] = out.splitlines() assert copyright.startswith("topaz") assert "Alex Gaynor" in copyright def test_version(self, space, tmpdir, capfd): self.run(space, tmpdir, ruby_args=["--version"]) out, _ = capfd.readouterr() [version] = out.splitlines() assert version.startswith("topaz") assert "1.9.3" in version assert os.uname()[4] in version assert platform.system().lower() in version assert subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).rstrip() in version def test_stop_consuming_args(self, space, tmpdir, capfd): self.run(space, tmpdir, ruby_args=["-e", "puts ARGV.join(' ')", "--", "--help", "-e"]) out, _ = capfd.readouterr() assert out == "--help -e\n" def test_load_path_multiple_args(self, space, tmpdir, capfd): d = tmpdir.mkdir("sub") f1 = d.join("f.rb") f1.write(""" Const = 5 """) self.run(space, tmpdir, """ require "f" puts Const """, ruby_args=["-I", str(d)]) out, _ = capfd.readouterr() assert out == "5\n" def test_load_path_joined_args(self, space, tmpdir, capfd): d = tmpdir.mkdir("sub") f1 = d.join("f.rb") f1.write(""" Const = 10 """) self.run(space, tmpdir, """ require "f" puts Const """, ruby_args=["-I%s" % d]) out, _ = capfd.readouterr() assert out == "10\n" def test_load_path_path_separated(self, space, tmpdir, capfd): d1 = tmpdir.mkdir("sub") d2 = tmpdir.mkdir("sub2") f1 = d1.join("f1.rb") f1.write(""" Const1 = 20 """) f2 = d2.join("f2.rb") f2.write(""" require "f1" Const2 = 3 """) self.run(space, tmpdir, """ require "f2" puts Const1 + Const2 """, ruby_args=["-I%s:%s" % (d1, d2)]) out, _ = capfd.readouterr() assert out == "23\n" def test_require_multiple_args(self, space, tmpdir, capfd): d = tmpdir.mkdir("sub") f = d.join("zyx.rb") f.write(""" Zyx = 9 """) self.run(space, tmpdir, "puts Zyx", ruby_args=["-r", "zyx", "-I", str(d)]) out, _ = capfd.readouterr() assert out == "9\n" def test_require_joined_args(self, space, tmpdir, capfd): d = tmpdir.mkdir("sub") f = d.join("zyx.rb") f.write(""" Zyx = 7 """) self.run(space, tmpdir, "puts Zyx", ruby_args=["-rzyx", "-I", str(d)]) out, _ = capfd.readouterr() assert out == "7\n" def test_search_path(self, space, tmpdir, capfd, monkeypatch): f = tmpdir.join("a") f.write("puts 17") monkeypatch.setenv("PATH", "%s:%s" % (tmpdir, os.environ["PATH"])) self.run(space, tmpdir, ruby_args=["-S", "a"]) out, _ = capfd.readouterr() assert out == "17\n" def test_arguments(self, space, tmpdir, capfd): self.run(space, tmpdir, """ ARGV.each_with_index do |arg, i| puts i.to_s + ": " + arg end """, argv=["abc", "123", "easy"]) out, err = capfd.readouterr() lines = out.splitlines() assert lines == [ "0: abc", "1: 123", "2: easy", ] def test_traceback_printed(self, space, tmpdir, capfd): self.assert_traceback(space, tmpdir, capfd, """ def f yield end f { 1 / 0} """, [ "{}:6:in `/': divided by 0 (ZeroDivisionError)", "\tfrom {}:6:in `block in <main>'", "\tfrom {}:3:in `f'", "\tfrom {}:6:in `<main>'", ]) def test_syntax_error(self, space, tmpdir, capfd): self.assert_traceback(space, tmpdir, capfd, """ while do """, [ "{}: line 2 (SyntaxError)", ]) def test_traceback_load_const(self, space, tmpdir, capfd): self.assert_traceback(space, tmpdir, capfd, """ UnknownConst """, [ "{}:2:in `const_missing': uninitialized constant UnknownConst (NameError)", "\tfrom {}:2:in `<main>'", ]) def test_traceback_class(self, space, tmpdir, capfd): self.assert_traceback(space, tmpdir, capfd, """ class X 1 / 0 end """, [ "{}:3:in `/': divided by 0 (ZeroDivisionError)", "\tfrom {}:3:in `<class:X>'", "\tfrom {}:1:in `<main>'", ]) @pytest.mark.xfail def test_traceback_default_arg(self, space, tmpdir, capfd): self.assert_traceback(space, tmpdir, capfd, """ def f(a=1 / 0) end f """, [ "{}:2:in `/': divided by 0 (ZeroDivisionError)", "\tfrom {}:2:in `f'", "\tfrom {}:4:in `<main>'", ]) def test_ruby_engine(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts RUBY_ENGINE") out, err = capfd.readouterr() assert out == "topaz\n" def test_ruby_description(self, space, tmpdir, capfd): self.run(space, tmpdir, "puts RUBY_DESCRIPTION") out1, err1 = capfd.readouterr() self.run(space, tmpdir, """ puts "#{RUBY_ENGINE} (ruby-#{RUBY_VERSION}p#{RUBY_PATCHLEVEL}) (git rev #{RUBY_REVISION}) [#{RUBY_PLATFORM}]" """) out2, err2 = capfd.readouterr() assert out1 == out2 def test_system_exit(self, space, tmpdir): self.run(space, tmpdir, "raise SystemExit", 0) self.run(space, tmpdir, "raise SystemExit.new('exit', 1)", 1) def test_at_exit(self, space, tmpdir, capfd): f = self.run(space, tmpdir, """ at_exit { puts "1" } at_exit { 1 / 0 } at_exit { puts "2" } 1 / 0 """, status=1) out, err = capfd.readouterr() assert out.splitlines() == [ "2", "1", ] assert err.splitlines() == [ "{}:3:in `/': divided by 0 (ZeroDivisionError)".format(f), "\tfrom {}:3:in `block in <main>'".format(f), "{}:5:in `/': divided by 0 (ZeroDivisionError)".format(f), "\tfrom {}:5:in `<main>'".format(f), ] def test_program_global(self, space, tmpdir, capfd): self.run(space, tmpdir, None, ruby_args=["-e", "puts $0"]) out1, err1 = capfd.readouterr() assert out1 == "-e\n" f = self.run(space, tmpdir, "puts $0") out2, err2 = capfd.readouterr() assert out2 == "{}\n".format(f) f = self.run(space, tmpdir, "puts $PROGRAM_NAME") out3, _ = capfd.readouterr() assert out3 == "{}\n".format(f) def test_non_existent_file(self, space, tmpdir, capfd): self.run(space, tmpdir, None, ruby_args=[str(tmpdir.join("t.rb"))], status=1) out, err = capfd.readouterr() assert err == "No such file or directory -- %s (LoadError)\n" % tmpdir.join("t.rb")
from ..encoding import wif_to_secret_exponent from ..convention import tx_fee from .Spendable import Spendable from .Tx import Tx from .TxOut import TxOut, standard_tx_out_script from .pay_to import build_hash160_lookup from ..networks import wif_prefix_for_netcode class SecretExponentMissing(Exception): pass class LazySecretExponentDB(object): """ The pycoin pure python implementation that converts secret exponents into public pairs is very slow, so this class does the conversion lazily and caches the results to optimize for the case of a large number of secret exponents. """ def __init__(self, wif_iterable, secret_exponent_db_cache, netcode = 'BTC'): self.wif_iterable = iter(wif_iterable) self.secret_exponent_db_cache = secret_exponent_db_cache self.netcode = netcode def get(self, v): if v in self.secret_exponent_db_cache: return self.secret_exponent_db_cache[v] for wif in self.wif_iterable: secret_exponent = wif_to_secret_exponent(wif, allowable_wif_prefixes=wif_prefix_for_netcode(self.netcode)) d = build_hash160_lookup([secret_exponent]) self.secret_exponent_db_cache.update(d) if v in self.secret_exponent_db_cache: return self.secret_exponent_db_cache[v] self.wif_iterable = [] return None def create_tx(spendables, payables, fee="standard", lock_time=0, version=1): """ This function provides the easiest way to create an unsigned transaction. All coin values are in satoshis. spendables: a list of Spendable objects, which act as inputs. These can be either a Spendable or a Spendable.as_text or a Spendable.as_dict if you prefer a non-object-based input (which might be easier for airgapped transactions, for example). payables: a list where each entry is a bitcoin address, or a tuple of (bitcoin address, coin_value). If the coin_value is missing or zero, this address is thrown into the "split pool". Funds not explicitly claimed by the fee or a bitcoin address are shared as equally as possible among the split pool. [Minor point: if the amount to be split does not divide evenly, some of the earlier bitcoin addresses will get an extra satoshi.] fee: a value, or "standard" for it to be calculated. version: the version to use in the transaction. Normally 1. lock_time: the lock_time to use in the transaction. Normally 0. Returns the unsigned Tx transaction. Note that unspents are set, so the transaction can be immediately signed. Example: tx = create_tx( spendables_for_address("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"), ["1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP"], fee=0) This will move all available reported funds from 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH to 1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP, with no transaction fees (which means it might take a while to confirm, possibly never). """ def _fix_spendable(s): if isinstance(s, Spendable): return s if not hasattr(s, "keys"): return Spendable.from_text(s) return Spendable.from_dict(s) spendables = [_fix_spendable(s) for s in spendables] txs_in = [spendable.tx_in() for spendable in spendables] txs_out = [] for payable in payables: if len(payable) == 2: bitcoin_address, coin_value = payable else: bitcoin_address = payable coin_value = 0 script = standard_tx_out_script(bitcoin_address) txs_out.append(TxOut(coin_value, script)) tx = Tx(version=version, txs_in=txs_in, txs_out=txs_out, lock_time=lock_time) tx.set_unspents(spendables) distribute_from_split_pool(tx, fee) return tx def distribute_from_split_pool(tx, fee): """ This function looks at TxOut items of a transaction tx and and puts TxOut items with a coin value of zero into a "split pool". Funds not explicitly claimed by the fee or other TxOut items are shared as equally as possible among the split pool. If the amount to be split does not divide evenly, some of the earlier TxOut items will get an extra satoshi. tx: the transaction fee: the reserved fee set aside """ # calculate fees if fee == 'standard': # TODO: improve this # 1: the tx is not fully built out, so it will actually be larger than implied at this point # 2: recommended_fee_for_tx gives estimates that are too high fee = tx_fee.recommended_fee_for_tx(tx) zero_count = sum(1 for tx_out in tx.txs_out if tx_out.coin_value == 0) if zero_count > 0: total_coin_value = sum(spendable.coin_value for spendable in tx.txs_in_as_spendable()) coins_allocated = sum(tx_out.coin_value for tx_out in tx.txs_out) + fee remaining_coins = total_coin_value - coins_allocated if remaining_coins < 0: raise ValueError("insufficient inputs for outputs") value_each, extra_count = divmod(remaining_coins, zero_count) if value_each < 1: raise ValueError("not enough to pay nonzero amounts to at least one of the unspecified outputs") for tx_out in tx.txs_out: if tx_out.coin_value == 0: tx_out.coin_value = value_each + (1 if extra_count > 0 else 0) extra_count -= 1 return zero_count def sign_tx(tx, wifs=[], secret_exponent_db={}, **kwargs): """ This function provides an convenience method to sign a transaction. The transaction must have "unspents" set by, for example, calling tx.unspents_from_db. wifs: the list of WIFs required to sign this transaction. secret_exponent_db: an optional dictionary (or any object with a .get method) that contains a bitcoin address => (secret_exponent, public_pair, is_compressed) tuple. This will be built automatically lazily with the list of WIFs. You can pass in an empty dictionary and as WIFs are processed, they will be cached here. If you have multiple transactions to sign, each with the same WIF list, passing a cache dictionary in may speed things up a bit. Returns the signed Tx transaction, or raises an exception. At least one of "wifs" and "secret_exponent_db" must be included for there to be any hope of signing the transaction. Example: sign_tx(wifs=["KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"]) """ tx.sign(LazySecretExponentDB(wifs, secret_exponent_db), **kwargs) def create_signed_tx(spendables, payables, wifs=[], fee="standard", lock_time=0, version=1, secret_exponent_db={}, **kwargs): """ This function provides an easy way to create and sign a transaction. All coin values are in satoshis. spendables, payables, fee, lock_time, version are as in create_tx, above. wifs, secret_exponent_db are as in sign_tx, above. Returns the signed Tx transaction, or raises an exception. At least one of "wifs" and "secret_exponent_db" must be included for there to be any hope of signing the transaction. Example: tx = create_signed_tx( spendables_for_address("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"), ["1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP"], wifs=["KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"], fee=0) This will move all available reported funds from 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH to 1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP, with no transaction fees (which means it might take a while to confirm, possibly never). """ tx = create_tx(spendables, payables, fee=fee, lock_time=lock_time, version=version) sign_tx(tx, wifs=wifs, secret_exponent_db=secret_exponent_db, **kwargs) for idx, tx_out in enumerate(tx.txs_in): if not tx.is_signature_ok(idx): raise SecretExponentMissing("failed to sign spendable for %s" % tx.unspents[idx].bitcoin_address()) return tx
# 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 datetime from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class MonitorsOperations(object): """MonitorsOperations 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: ~workload_monitor_api.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): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, subscription_id, # type: str resource_group_name, # type: str resource_namespace, # type: str resource_type, # type: str resource_name, # type: str filter=None, # type: Optional[str] expand=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> Iterable["models.MonitorList"] """Get list of a monitors of a resource (with optional filter). Get list of a monitors of a resource (with optional filter). :param subscription_id: The subscriptionId of the resource. :type subscription_id: str :param resource_group_name: The resourceGroupName of the resource. :type resource_group_name: str :param resource_namespace: The resourceNamespace of the resource. :type resource_namespace: str :param resource_type: The resourceType of the resource. :type resource_type: str :param resource_name: The resourceType of the resource. :type resource_name: str :param filter: list example: $filter=monitorName eq 'logical-disks|C:|disk-free-space-mb'; history example: $filter=isHeartbeat eq false. :type filter: str :param expand: ex: $expand=evidence,configuration. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MonitorList or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~workload_monitor_api.models.MonitorList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.MonitorList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-01-13-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceNamespace': self._serialize.url("resource_namespace", resource_namespace, 'str'), 'resourceType': self._serialize.url("resource_type", resource_type, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('MonitorList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize(models.DefaultError, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors'} # type: ignore def get( self, subscription_id, # type: str resource_group_name, # type: str resource_namespace, # type: str resource_type, # type: str resource_name, # type: str monitor_id, # type: str expand=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> "models.Monitor" """Get the current status of a monitor of a resource. Get the current status of a monitor of a resource. :param subscription_id: The subscriptionId of the resource. :type subscription_id: str :param resource_group_name: The resourceGroupName of the resource. :type resource_group_name: str :param resource_namespace: The resourceNamespace of the resource. :type resource_namespace: str :param resource_type: The resourceType of the resource. :type resource_type: str :param resource_name: The resourceType of the resource. :type resource_name: str :param monitor_id: The monitorId of the resource (url encoded). :type monitor_id: str :param expand: ex: $expand=evidence,configuration. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Monitor, or the result of cls(response) :rtype: ~workload_monitor_api.models.Monitor :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Monitor"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-01-13-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceNamespace': self._serialize.url("resource_namespace", resource_namespace, 'str'), 'resourceType': self._serialize.url("resource_type", resource_type, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), 'monitorId': self._serialize.url("monitor_id", monitor_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = 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) error = self._deserialize(models.DefaultError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Monitor', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors/{monitorId}'} # type: ignore def list_state_changes( self, subscription_id, # type: str resource_group_name, # type: str resource_namespace, # type: str resource_type, # type: str resource_name, # type: str monitor_id, # type: str filter=None, # type: Optional[str] expand=None, # type: Optional[str] start_timestamp_utc=None, # type: Optional[datetime.datetime] end_timestamp_utc=None, # type: Optional[datetime.datetime] **kwargs # type: Any ): # type: (...) -> Iterable["models.MonitorStateChangeList"] """Get history of a monitor of a resource (with optional filter). Get history of a monitor of a resource (with optional filter). :param subscription_id: The subscriptionId of the resource. :type subscription_id: str :param resource_group_name: The resourceGroupName of the resource. :type resource_group_name: str :param resource_namespace: The resourceNamespace of the resource. :type resource_namespace: str :param resource_type: The resourceType of the resource. :type resource_type: str :param resource_name: The resourceType of the resource. :type resource_name: str :param monitor_id: The monitorId of the resource (url encoded). :type monitor_id: str :param filter: list example: $filter=monitorName eq 'logical-disks|C:|disk-free-space-mb'; history example: $filter=isHeartbeat eq false. :type filter: str :param expand: ex: $expand=evidence,configuration. :type expand: str :param start_timestamp_utc: The start Timestamp for the desired history. :type start_timestamp_utc: ~datetime.datetime :param end_timestamp_utc: The end Timestamp for the desired history. :type end_timestamp_utc: ~datetime.datetime :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MonitorStateChangeList or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~workload_monitor_api.models.MonitorStateChangeList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.MonitorStateChangeList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-01-13-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_state_changes.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceNamespace': self._serialize.url("resource_namespace", resource_namespace, 'str'), 'resourceType': self._serialize.url("resource_type", resource_type, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), 'monitorId': self._serialize.url("monitor_id", monitor_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') if start_timestamp_utc is not None: query_parameters['startTimestampUtc'] = self._serialize.query("start_timestamp_utc", start_timestamp_utc, 'iso-8601') if end_timestamp_utc is not None: query_parameters['endTimestampUtc'] = self._serialize.query("end_timestamp_utc", end_timestamp_utc, 'iso-8601') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('MonitorStateChangeList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize(models.DefaultError, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_state_changes.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors/{monitorId}/history'} # type: ignore def get_state_change( self, subscription_id, # type: str resource_group_name, # type: str resource_namespace, # type: str resource_type, # type: str resource_name, # type: str monitor_id, # type: str timestamp_unix, # type: str expand=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> "models.MonitorStateChange" """Get the status of a monitor at a specific timestamp in history. Get the status of a monitor at a specific timestamp in history. :param subscription_id: The subscriptionId of the resource. :type subscription_id: str :param resource_group_name: The resourceGroupName of the resource. :type resource_group_name: str :param resource_namespace: The resourceNamespace of the resource. :type resource_namespace: str :param resource_type: The resourceType of the resource. :type resource_type: str :param resource_name: The resourceType of the resource. :type resource_name: str :param monitor_id: The monitorId of the resource (url encoded). :type monitor_id: str :param timestamp_unix: The timestamp of the state change (Unix format). :type timestamp_unix: str :param expand: ex: $expand=evidence,configuration. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: MonitorStateChange, or the result of cls(response) :rtype: ~workload_monitor_api.models.MonitorStateChange :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.MonitorStateChange"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-01-13-preview" accept = "application/json" # Construct URL url = self.get_state_change.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceNamespace': self._serialize.url("resource_namespace", resource_namespace, 'str'), 'resourceType': self._serialize.url("resource_type", resource_type, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), 'monitorId': self._serialize.url("monitor_id", monitor_id, 'str'), 'timestampUnix': self._serialize.url("timestamp_unix", timestamp_unix, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = 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) error = self._deserialize(models.DefaultError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MonitorStateChange', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_state_change.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors/{monitorId}/history/{timestampUnix}'} # type: ignore
# Copyright 2015 Mirantis, 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. import os import random import six from contextlib import contextmanager from cinderclient import client as cinder_client from keystoneclient import discover as keystone_discover from keystoneclient.v2_0 import client as keystone_client_v2 from keystoneclient.v3 import client as keystone_client_v3 from novaclient import client as nova_client from nailgun import consts from nailgun.db import db from nailgun.logger import logger from nailgun.network import manager from nailgun import objects from nailgun.settings import settings from nailgun.statistics.oswl_resources_description import resources_description class ClientProvider(object): """Initialize clients for OpenStack components and expose them as attributes """ clients_version_attr_path = { "nova": ["client", "version"], "cinder": ["client", "version"], "keystone": ["version"] } def __init__(self, cluster): self.cluster = cluster self._nova = None self._cinder = None self._keystone = None self._credentials = None @property def nova(self): if self._nova is None: self._nova = nova_client.Client( settings.OPENSTACK_API_VERSION["nova"], *self.credentials, service_type=consts.NOVA_SERVICE_TYPE.compute ) return self._nova @property def cinder(self): if self._cinder is None: self._cinder = cinder_client.Client( settings.OPENSTACK_API_VERSION["cinder"], *self.credentials ) return self._cinder @property def keystone(self): if self._keystone is None: # kwargs are universal for v2 and v3 versions of # keystone client that are different only in accepting # of tenant/project keyword name auth_kwargs = { "username": self.credentials[0], "password": self.credentials[1], "tenant_name": self.credentials[2], "project_name": self.credentials[2], "auth_url": self.credentials[3] } self._keystone = self._get_keystone_client(auth_kwargs) return self._keystone def _get_keystone_client(self, auth_creds): """Instantiate client based on returned from keystone server version data. :param auth_creds: credentials for authentication which also are parameters for client's instance initialization :returns: instance of keystone client of appropriate version :raises: exception if response from server contains version other than 2.x and 3.x """ discover = keystone_discover.Discover(**auth_creds) for version_data in discover.version_data(): version = version_data["version"][0] if version <= 2: return keystone_client_v2.Client(**auth_creds) elif version == 3: return keystone_client_v3.Client(**auth_creds) raise Exception("Failed to discover keystone version " "for auth_url {0}".format( auth_creds.get("auth_url")) ) @property def credentials(self): if self._credentials is None: access_data = objects.Cluster.get_editable_attributes( self.cluster )['editable']['workloads_collector'] os_user = access_data["username"]["value"] os_password = access_data["password"]["value"] os_tenant = access_data["tenant"]["value"] auth_host = _get_host_for_auth(self.cluster) auth_url = "http://{0}:{1}/{2}/".format( auth_host, settings.AUTH_PORT, settings.OPENSTACK_API_VERSION["keystone"]) self._credentials = (os_user, os_password, os_tenant, auth_url) return self._credentials def _get_host_for_auth(cluster): return manager.NetworkManager._get_ip_by_network_name( _get_online_controller(cluster), consts.NETWORKS.management ).ip_addr def get_proxy_for_cluster(cluster): proxy_host = _get_online_controller(cluster).ip proxy_port = settings.OPENSTACK_INFO_COLLECTOR_PROXY_PORT proxy = "http://{0}:{1}".format(proxy_host, proxy_port) return proxy def _get_online_controller(cluster): return filter( lambda node: ( "controller" in node.roles and node.online is True), cluster.nodes )[0] def _get_data_from_resource_manager(resource_manager, attr_names_mapping, additional_display_options): data = [] display_options = {} display_options.update(additional_display_options) instances_list = resource_manager.list(**display_options) for inst in instances_list: inst_details = {} for attr_name, attr_path in six.iteritems(attr_names_mapping): obj_dict = \ inst.to_dict() if hasattr(inst, "to_dict") else inst.__dict__ inst_details[attr_name] = _get_value_from_nested_dict( obj_dict, attr_path ) data.append(inst_details) return data def get_info_from_os_resource_manager(client_provider, resource_name): """Utilize clients provided by client_provider instance to retrieve data for resource_name, description of which is stored in resources_description data structure. :param client_provider: objects that provides instances of openstack clients as its attributes :param resource_name: string that contains name of resource for which info should be collected from installation :returns: data that store collected info """ resource_description = resources_description[resource_name] client_name = resource_description["retrieved_from_component"] client_inst = getattr(client_provider, client_name) client_api_version = _get_nested_attr( client_inst, client_provider.clients_version_attr_path[client_name] ) matched_api = \ resource_description["supported_api_versions"][client_api_version] resource_manager_name = matched_api["resource_manager_name"] resource_manager = getattr(client_inst, resource_manager_name) attributes_names_mapping = matched_api["retrieved_attr_names_mapping"] additional_display_options = \ matched_api.get("additional_display_options", {}) resource_info = _get_data_from_resource_manager( resource_manager, attributes_names_mapping, additional_display_options ) return resource_info def _get_value_from_nested_dict(obj_dict, key_path): if not isinstance(obj_dict, dict) or not key_path: return None value = obj_dict.get(key_path[0]) if isinstance(value, dict): return _get_value_from_nested_dict(value, key_path[1:]) return value def _get_nested_attr(obj, attr_path): # prevent from error in case of empty list and # None object if not all([obj, attr_path]): return None attr_name = attr_path[0] attr_value = getattr(obj, attr_name, None) # stop recursion as we already are on last level of attributes nesting if len(attr_path) == 1: return attr_value return _get_nested_attr(attr_value, attr_path[1:]) @contextmanager def set_proxy(proxy): """Replace http_proxy environment variable for the scope of context execution. After exit from context old proxy value (if any) is restored :param proxy: - proxy url """ proxy_old_value = None if os.environ.get("http_proxy"): proxy_old_value = os.environ["http_proxy"] logger.warning("http_proxy variable is already set with " "value: {0}. Change to {1}. Old value " "will be restored after exit from script's " "execution context" .format(proxy_old_value, proxy)) os.environ["http_proxy"] = proxy try: yield except Exception as e: logger.exception("Error while talking to proxy. Details: {0}" .format(six.text_type(e))) finally: if proxy_old_value: logger.info("Restoring old value for http_proxy") os.environ["http_proxy"] = proxy_old_value else: logger.info("Deleting set http_proxy environment variable") del os.environ["http_proxy"] def dithered(medium, interval=(0.9, 1.1)): return random.randint(int(medium * interval[0]), int(medium * interval[1])) def delete_expired_oswl_entries(): try: deleted_rows_count = \ objects.OpenStackWorkloadStatsCollection.clean_expired_entries() if deleted_rows_count == 0: logger.info("There are no expired OSWL entries in db.") db().commit() logger.info("Expired OSWL entries are " "successfully cleaned from db") except Exception as e: logger.exception("Exception while cleaning oswls entries from " "db. Details: {0}".format(six.text_type(e))) finally: db.remove()
# notify.py - email notifications for mercurial # # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. '''hooks for sending email notifications at commit/push time Subscriptions can be managed through a hgrc file. Default mode is to print messages to stdout, for testing and configuring. To use, configure the notify extension and enable it in hgrc like this:: [extensions] notify = [hooks] # one email for each incoming changeset incoming.notify = python:hgext.notify.hook # batch emails when many changesets incoming at one time changegroup.notify = python:hgext.notify.hook [notify] # config items go here Required configuration items:: config = /path/to/file # file containing subscriptions Optional configuration items:: test = True # print messages to stdout for testing strip = 3 # number of slashes to strip for url paths domain = example.com # domain to use if committer missing domain style = ... # style file to use when formatting email template = ... # template to use when formatting email incoming = ... # template to use when run as incoming hook changegroup = ... # template when run as changegroup hook maxdiff = 300 # max lines of diffs to include (0=none, -1=all) maxsubject = 67 # truncate subject line longer than this diffstat = True # add a diffstat before the diff content sources = serve # notify if source of incoming changes in this list # (serve == ssh or http, push, pull, bundle) merge = False # send notification for merges (default True) [email] from = user@host.com # email address to send as if none given [web] baseurl = http://hgserver/... # root of hg web site for browsing commits The notify config file has same format as a regular hgrc file. It has two sections so you can express subscriptions in whatever way is handier for you. :: [usersubs] # key is subscriber email, value is ","-separated list of glob patterns user@host = pattern [reposubs] # key is glob pattern, value is ","-separated list of subscriber emails pattern = user@host Glob patterns are matched against path to repository root. If you like, you can put notify config file in repository that users can push changes to, they can manage their own subscriptions. ''' from mercurial.i18n import _ from mercurial import patch, cmdutil, templater, util, mail import email.Parser, email.Errors, fnmatch, socket, time # template for single changeset can include email headers. single_template = ''' Subject: changeset in {webroot}: {desc|firstline|strip} From: {author} changeset {node|short} in {root} details: {baseurl}{webroot}?cmd=changeset;node={node|short} description: \t{desc|tabindent|strip} '''.lstrip() # template for multiple changesets should not contain email headers, # because only first set of headers will be used and result will look # strange. multiple_template = ''' changeset {node|short} in {root} details: {baseurl}{webroot}?cmd=changeset;node={node|short} summary: {desc|firstline} ''' deftemplates = { 'changegroup': multiple_template, } class notifier(object): '''email notification class.''' def __init__(self, ui, repo, hooktype): self.ui = ui cfg = self.ui.config('notify', 'config') if cfg: self.ui.readconfig(cfg, sections=['usersubs', 'reposubs']) self.repo = repo self.stripcount = int(self.ui.config('notify', 'strip', 0)) self.root = self.strip(self.repo.root) self.domain = self.ui.config('notify', 'domain') self.test = self.ui.configbool('notify', 'test', True) self.charsets = mail._charsets(self.ui) self.subs = self.subscribers() self.merge = self.ui.configbool('notify', 'merge', True) mapfile = self.ui.config('notify', 'style') template = (self.ui.config('notify', hooktype) or self.ui.config('notify', 'template')) self.t = cmdutil.changeset_templater(self.ui, self.repo, False, None, mapfile, False) if not mapfile and not template: template = deftemplates.get(hooktype) or single_template if template: template = templater.parsestring(template, quoted=False) self.t.use_template(template) def strip(self, path): '''strip leading slashes from local path, turn into web-safe path.''' path = util.pconvert(path) count = self.stripcount while count > 0: c = path.find('/') if c == -1: break path = path[c + 1:] count -= 1 return path def fixmail(self, addr): '''try to clean up email addresses.''' addr = util.email(addr.strip()) if self.domain: a = addr.find('@localhost') if a != -1: addr = addr[:a] if '@' not in addr: return addr + '@' + self.domain return addr def subscribers(self): '''return list of email addresses of subscribers to this repo.''' subs = set() for user, pats in self.ui.configitems('usersubs'): for pat in pats.split(','): if fnmatch.fnmatch(self.repo.root, pat.strip()): subs.add(self.fixmail(user)) for pat, users in self.ui.configitems('reposubs'): if fnmatch.fnmatch(self.repo.root, pat): for user in users.split(','): subs.add(self.fixmail(user)) return [mail.addressencode(self.ui, s, self.charsets, self.test) for s in sorted(subs)] def url(self, path=None): return self.ui.config('web', 'baseurl') + (path or self.root) def node(self, ctx, **props): '''format one changeset, unless it is a suppressed merge.''' if not self.merge and len(ctx.parents()) > 1: return False self.t.show(ctx, changes=ctx.changeset(), baseurl=self.ui.config('web', 'baseurl'), root=self.repo.root, webroot=self.root, **props) return True def skipsource(self, source): '''true if incoming changes from this source should be skipped.''' ok_sources = self.ui.config('notify', 'sources', 'serve').split() return source not in ok_sources def send(self, ctx, count, data): '''send message.''' p = email.Parser.Parser() try: msg = p.parsestr(data) except email.Errors.MessageParseError, inst: raise util.Abort(inst) # store sender and subject sender, subject = msg['From'], msg['Subject'] del msg['From'], msg['Subject'] if not msg.is_multipart(): # create fresh mime message from scratch # (multipart templates must take care of this themselves) headers = msg.items() payload = msg.get_payload() # for notification prefer readability over data precision msg = mail.mimeencode(self.ui, payload, self.charsets, self.test) # reinstate custom headers for k, v in headers: msg[k] = v msg['Date'] = util.datestr(format="%a, %d %b %Y %H:%M:%S %1%2") # try to make subject line exist and be useful if not subject: if count > 1: subject = _('%s: %d new changesets') % (self.root, count) else: s = ctx.description().lstrip().split('\n', 1)[0].rstrip() subject = '%s: %s' % (self.root, s) maxsubject = int(self.ui.config('notify', 'maxsubject', 67)) if maxsubject and len(subject) > maxsubject: subject = subject[:maxsubject - 3] + '...' msg['Subject'] = mail.headencode(self.ui, subject, self.charsets, self.test) # try to make message have proper sender if not sender: sender = self.ui.config('email', 'from') or self.ui.username() if '@' not in sender or '@localhost' in sender: sender = self.fixmail(sender) msg['From'] = mail.addressencode(self.ui, sender, self.charsets, self.test) msg['X-Hg-Notification'] = 'changeset %s' % ctx if not msg['Message-Id']: msg['Message-Id'] = ('<hg.%s.%s.%s@%s>' % (ctx, int(time.time()), hash(self.repo.root), socket.getfqdn())) msg['To'] = ', '.join(self.subs) msgtext = msg.as_string() if self.test: self.ui.write(msgtext) if not msgtext.endswith('\n'): self.ui.write('\n') else: self.ui.status(_('notify: sending %d subscribers %d changes\n') % (len(self.subs), count)) mail.sendmail(self.ui, util.email(msg['From']), self.subs, msgtext) def diff(self, ctx, ref=None): maxdiff = int(self.ui.config('notify', 'maxdiff', 300)) prev = ctx.parents()[0].node() ref = ref and ref.node() or ctx.node() chunks = patch.diff(self.repo, prev, ref, opts=patch.diffopts(self.ui)) difflines = ''.join(chunks).splitlines() if self.ui.configbool('notify', 'diffstat', True): s = patch.diffstat(difflines) # s may be nil, don't include the header if it is if s: self.ui.write('\ndiffstat:\n\n%s' % s) if maxdiff == 0: return elif maxdiff > 0 and len(difflines) > maxdiff: msg = _('\ndiffs (truncated from %d to %d lines):\n\n') self.ui.write(msg % (len(difflines), maxdiff)) difflines = difflines[:maxdiff] elif difflines: self.ui.write(_('\ndiffs (%d lines):\n\n') % len(difflines)) self.ui.write("\n".join(difflines)) def hook(ui, repo, hooktype, node=None, source=None, **kwargs): '''send email notifications to interested subscribers. if used as changegroup hook, send one email for all changesets in changegroup. else send one email per changeset.''' n = notifier(ui, repo, hooktype) ctx = repo[node] if not n.subs: ui.debug('notify: no subscribers to repository %s\n' % n.root) return if n.skipsource(source): ui.debug('notify: changes have source "%s" - skipping\n' % source) return ui.pushbuffer() data = '' count = 0 if hooktype == 'changegroup': start, end = ctx.rev(), len(repo) for rev in xrange(start, end): if n.node(repo[rev]): count += 1 else: data += ui.popbuffer() ui.note(_('notify: suppressing notification for merge %d:%s\n') % (rev, repo[rev].hex()[:12])) ui.pushbuffer() if count: n.diff(ctx, repo['tip']) else: if not n.node(ctx): ui.popbuffer() ui.note(_('notify: suppressing notification for merge %d:%s\n') % (ctx.rev(), ctx.hex()[:12])) return count += 1 n.diff(ctx) data += ui.popbuffer() if count: n.send(ctx, count, data)
# 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. import uuid from keystone import catalog from keystone.tests import unit from keystone.tests.unit.ksfixtures import database from keystone.tests.unit import rest BASE_URL = 'http://127.0.0.1:35357/v2' SERVICE_FIXTURE = object() class V2CatalogTestCase(rest.RestfulTestCase): def setUp(self): super(V2CatalogTestCase, self).setUp() self.useFixture(database.Database()) self.service_id = uuid.uuid4().hex self.service = unit.new_service_ref() self.service['id'] = self.service_id self.catalog_api.create_service( self.service_id, self.service.copy()) # TODO(termie): add an admin user to the fixtures and use that user # override the fixtures, for now self.assignment_api.add_role_to_user_and_project( self.user_foo['id'], self.tenant_bar['id'], self.role_admin['id']) def config_overrides(self): super(V2CatalogTestCase, self).config_overrides() self.config_fixture.config(group='catalog', driver='sql') def _get_token_id(self, r): """Applicable only to JSON.""" return r.result['access']['token']['id'] def _endpoint_create(self, expected_status=200, service_id=SERVICE_FIXTURE, publicurl='http://localhost:8080', internalurl='http://localhost:8080', adminurl='http://localhost:8080'): if service_id is SERVICE_FIXTURE: service_id = self.service_id # FIXME(dolph): expected status should actually be 201 Created path = '/v2.0/endpoints' body = { 'endpoint': { 'adminurl': adminurl, 'service_id': service_id, 'region': 'RegionOne', 'internalurl': internalurl, 'publicurl': publicurl } } r = self.admin_request(method='POST', token=self.get_scoped_token(), path=path, expected_status=expected_status, body=body) return body, r def test_endpoint_create(self): req_body, response = self._endpoint_create() self.assertIn('endpoint', response.result) self.assertIn('id', response.result['endpoint']) for field, value in req_body['endpoint'].items(): self.assertEqual(response.result['endpoint'][field], value) def test_endpoint_create_with_null_adminurl(self): req_body, response = self._endpoint_create(adminurl=None) self.assertIsNone(req_body['endpoint']['adminurl']) self.assertNotIn('adminurl', response.result['endpoint']) def test_endpoint_create_with_empty_adminurl(self): req_body, response = self._endpoint_create(adminurl='') self.assertEqual('', req_body['endpoint']['adminurl']) self.assertNotIn("adminurl", response.result['endpoint']) def test_endpoint_create_with_null_internalurl(self): req_body, response = self._endpoint_create(internalurl=None) self.assertIsNone(req_body['endpoint']['internalurl']) self.assertNotIn('internalurl', response.result['endpoint']) def test_endpoint_create_with_empty_internalurl(self): req_body, response = self._endpoint_create(internalurl='') self.assertEqual('', req_body['endpoint']['internalurl']) self.assertNotIn("internalurl", response.result['endpoint']) def test_endpoint_create_with_null_publicurl(self): self._endpoint_create(expected_status=400, publicurl=None) def test_endpoint_create_with_empty_publicurl(self): self._endpoint_create(expected_status=400, publicurl='') def test_endpoint_create_with_null_service_id(self): self._endpoint_create(expected_status=400, service_id=None) def test_endpoint_create_with_empty_service_id(self): self._endpoint_create(expected_status=400, service_id='') def test_endpoint_create_with_valid_url(self): """Create endpoint with valid URL should be tested, too.""" # list one valid url is enough, no need to list too much valid_url = 'http://127.0.0.1:8774/v1.1/$(tenant_id)s' # baseline tests that all valid URLs works self._endpoint_create(expected_status=200, publicurl=valid_url, internalurl=valid_url, adminurl=valid_url) def test_endpoint_create_with_invalid_url(self): """Test the invalid cases: substitutions is not exactly right.""" invalid_urls = [ # using a substitution that is not whitelisted - KeyError 'http://127.0.0.1:8774/v1.1/$(nonexistent)s', # invalid formatting - ValueError 'http://127.0.0.1:8774/v1.1/$(tenant_id)', 'http://127.0.0.1:8774/v1.1/$(tenant_id)t', 'http://127.0.0.1:8774/v1.1/$(tenant_id', # invalid type specifier - TypeError # admin_url is a string not an int 'http://127.0.0.1:8774/v1.1/$(admin_url)d', ] # list one valid url is enough, no need to list too much valid_url = 'http://127.0.0.1:8774/v1.1/$(tenant_id)s' # Case one: publicurl, internalurl and adminurl are # all invalid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=invalid_url, internalurl=invalid_url, adminurl=invalid_url) # Case two: publicurl, internalurl are invalid # and adminurl is valid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=invalid_url, internalurl=invalid_url, adminurl=valid_url) # Case three: publicurl, adminurl are invalid # and internalurl is valid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=invalid_url, internalurl=valid_url, adminurl=invalid_url) # Case four: internalurl, adminurl are invalid # and publicurl is valid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=valid_url, internalurl=invalid_url, adminurl=invalid_url) # Case five: publicurl is invalid, internalurl # and adminurl are valid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=invalid_url, internalurl=valid_url, adminurl=valid_url) # Case six: internalurl is invalid, publicurl # and adminurl are valid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=valid_url, internalurl=invalid_url, adminurl=valid_url) # Case seven: adminurl is invalid, publicurl # and internalurl are valid for invalid_url in invalid_urls: self._endpoint_create(expected_status=400, publicurl=valid_url, internalurl=valid_url, adminurl=invalid_url) class TestV2CatalogAPISQL(unit.TestCase): def setUp(self): super(TestV2CatalogAPISQL, self).setUp() self.useFixture(database.Database()) self.catalog_api = catalog.Manager() self.service_id = uuid.uuid4().hex service = {'id': self.service_id, 'name': uuid.uuid4().hex} self.catalog_api.create_service(self.service_id, service) endpoint = self.new_endpoint_ref(service_id=self.service_id) self.catalog_api.create_endpoint(endpoint['id'], endpoint) def config_overrides(self): super(TestV2CatalogAPISQL, self).config_overrides() self.config_fixture.config(group='catalog', driver='sql') def new_endpoint_ref(self, service_id): return { 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'interface': uuid.uuid4().hex[:8], 'service_id': service_id, 'url': uuid.uuid4().hex, 'region': uuid.uuid4().hex, } def test_get_catalog_ignores_endpoints_with_invalid_urls(self): user_id = uuid.uuid4().hex tenant_id = uuid.uuid4().hex # the only endpoint in the catalog is the one created in setUp catalog = self.catalog_api.get_catalog(user_id, tenant_id) self.assertEqual(1, len(catalog)) # it's also the only endpoint in the backend self.assertEqual(1, len(self.catalog_api.list_endpoints())) # create a new, invalid endpoint - malformed type declaration endpoint = self.new_endpoint_ref(self.service_id) endpoint['url'] = 'http://keystone/%(tenant_id)' self.catalog_api.create_endpoint(endpoint['id'], endpoint) # create a new, invalid endpoint - nonexistent key endpoint = self.new_endpoint_ref(self.service_id) endpoint['url'] = 'http://keystone/%(you_wont_find_me)s' self.catalog_api.create_endpoint(endpoint['id'], endpoint) # verify that the invalid endpoints don't appear in the catalog catalog = self.catalog_api.get_catalog(user_id, tenant_id) self.assertEqual(1, len(catalog)) # all three endpoints appear in the backend self.assertEqual(3, len(self.catalog_api.list_endpoints())) def test_get_catalog_always_returns_service_name(self): user_id = uuid.uuid4().hex tenant_id = uuid.uuid4().hex # create a service, with a name named_svc = { 'id': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, } self.catalog_api.create_service(named_svc['id'], named_svc) endpoint = self.new_endpoint_ref(service_id=named_svc['id']) self.catalog_api.create_endpoint(endpoint['id'], endpoint) # create a service, with no name unnamed_svc = { 'id': uuid.uuid4().hex, 'type': uuid.uuid4().hex } self.catalog_api.create_service(unnamed_svc['id'], unnamed_svc) endpoint = self.new_endpoint_ref(service_id=unnamed_svc['id']) self.catalog_api.create_endpoint(endpoint['id'], endpoint) region = None catalog = self.catalog_api.get_catalog(user_id, tenant_id) self.assertEqual(named_svc['name'], catalog[region][named_svc['type']]['name']) self.assertEqual('', catalog[region][unnamed_svc['type']]['name'])
""" Module to build experiments (worlds, agents, etc.). """ import random import pygame import model.interaction import model.agent import experiment import agentprogram.agentprogram from elements import Elements class LoadWorldExperiment(experiment.Experiment): """ Load a world to this experiment. Note: experiment control setup is not saved and loaded. """ def __init__(self, world_file_name): """ :param world_file_name: The file name of the world to load. """ super(LoadWorldExperiment, self).__init__() self.world = self.load_world(world_file_name) class BasicExperiment(experiment.Experiment): world_representation = [ "wwwwwwwwwwwwwww", "w.............w", "w.wwwwwww.....w", "w.......wwwww.w", "w.wwwww.......w", "w.w.......w...w", "w.w.wwwww.w...w", "w.w.w...w.ww..w", "w.www.....w...w", "w.....wwwww.a.w", "wwwwwwwwwwwwwww" ] def __init__(self): super(BasicExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Rgister enact logic enact_logic = Elements.get_enact_logic() # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.feel) primitives.append(Elements.feel_fail) # Set intrinsic motivation values. motivation = {} motivation[Elements.step] = 1 motivation[Elements.step_fail] = -10 motivation[Elements.turn_right] = -2 motivation[Elements.turn_left] = -2 motivation[Elements.wait] = -1 motivation[Elements.feel] = 0 motivation[Elements.feel_fail] = -1 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) class BasicHomeostaticExperiment(experiment.Experiment): world_representation = [ "wwwwwwwwwwwwwww", "w.............w", "w.wwwwwww.....w", "w.......wwwww.w", "w.wwwww.......w", "w.w.......w...w", "w.w.wwwww.w...w", "w.w.w...w.ww.ww", "w.www.....w...w", "w.....wwwww.h.w", "wwwwwwwwwwwwwww" ] def __init__(self): super(BasicHomeostaticExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Define environment logic for primitives, these functions will be # registered to the primitive interactions and will be called once # the agent attempts to enact the primitive interaction. # The function can manipulate the world and the agents. # The return value is the actual enacted interaction (i.e., can be # different form the attempted interaction). def _step(world, agent, interaction): if world.can_step(agent): agent.step() agent.add_to_homeostatic_value("energy", -0.1) return Elements.step else: return Elements.step_fail # Register the previously defined functions. enact_logic = {} enact_logic[Elements.step.get_name()] = _step enact_logic[Elements.turn_right.get_name()] = Elements._turn_right enact_logic[Elements.turn_left.get_name()] = Elements._turn_left enact_logic[Elements.feel.get_name()] = Elements._feel # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.feel) primitives.append(Elements.feel_fail) # Set intrinsic homeostatic motivation values. motivation = {} motivation[Elements.step] = lambda agent: agent.get_homeostatic_value("energy") * 0.1 motivation[Elements.step_fail] = lambda agent: -10 motivation[Elements.turn_right] = lambda agent: -2 motivation[Elements.turn_left] = lambda agent: -2 motivation[Elements.wait] = lambda agent: -1 motivation[Elements.feel] = lambda agent: 0 motivation[Elements.feel_fail] = lambda agent: -1 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) if isinstance(entity, model.agent.HomeostaticConstructiveAgent): entity.set_homeostatic_value("energy", 100) def calculate_metrics(self): metrics = {} for a in self.world.get_entities_of_type(model.agent.Agent): metrics[a.get_name()] = a.get_homeostatic_value("energy") return metrics def halt(self, t): return t > 150 class BasicCoexsistenceExperiment(experiment.Experiment): world_representation = [ "wwwww", "w..aw", "w.w.w", "w.w.w", "wa..w", "wwwww" ] def __init__(self): super(BasicCoexsistenceExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Register the previously defined functions. enact_logic = Elements.get_enact_logic() # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.feel) primitives.append(Elements.feel_fail) primitives.append(Elements.cuddle) primitives.append(Elements.cuddle_fail) # Set intrinsic motivation values. motivation = {} motivation[Elements.step] = 1 motivation[Elements.step_fail] = -10 motivation[Elements.turn_right] = -2 motivation[Elements.turn_left] = -2 motivation[Elements.wait] = -1 motivation[Elements.feel] = 0 motivation[Elements.feel_fail] = -1 motivation[Elements.cuddle] = 50 motivation[Elements.cuddle_fail] = -1 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) class BasicVisionExperiment(experiment.Experiment): world_representation = [ "wwwwwwwwwwwwwww", "w....p........w", "wwwwwwwwwwwwwww" ] def __init__(self): super(BasicVisionExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Register the previously defined functions. enact_logic = Elements.get_enact_logic() # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) # Set intrinsic motivation values. motivation = {} motivation[Elements.step] = 25 motivation[Elements.step_fail] = -10 motivation[Elements.turn_right] = -2 motivation[Elements.turn_left] = -2 motivation[Elements.wait] = -1 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) class BasicVisionExperimentLoad(experiment.Experiment): world_representation = [ "wwwwwwwwwwwwwww", "w.............w", "wwwwwwwwwwwwwww" ] def __init__(self): super(BasicVisionExperimentLoad, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Load the agent. (Note: the file must exist. Create it by running # the BasicVisionExperiment for some time, and then saving the agent.) a = self.load_agent("20161118T041955 - Agent 3T7U8G.p") self.world.add_entity(a) # Register the previously defined functions. enact_logic = Elements.get_enact_logic() for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) class BasicHomeostaticVisionExperiment(experiment.Experiment): world_representation = [ "wwwwwwww", "w......w", "w...w..w", "w...w..w", "w...w..w", "w...w..w", "w..ww..w", "w..w...w", "w.....hw", "wwwwwwww", ] def __init__(self): super(BasicHomeostaticVisionExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Define environment logic for primitives, these functions will be # registered to the primitive interactions and will be called once # the agent attempts to enact the primitive interaction. # The function can manipulate the world and the agents. # The return value is the actual enacted interaction (i.e., can be # different form the attempted interaction). def _step(world, agent, interaction): if world.can_step(agent): agent.step() agent.add_to_homeostatic_value("energy", -0.1) return Elements.step else: return Elements.step_fail def _eat(world, agent, interaction): entities = world.get_entities_in_front(agent) for entity in entities: if isinstance(entity, model.structure.Food): world.remove_entity(entity) agent.add_to_homeostatic_value("energy", 10) return Elements.eat return Elements.eat_fail # Register the previously defined functions. enact_logic = {} enact_logic[Elements.step.get_name()] = _step enact_logic[Elements.turn_right.get_name()] = Elements._turn_right enact_logic[Elements.turn_left.get_name()] = Elements._turn_left enact_logic[Elements.eat.get_name()] = _eat enact_logic[Elements.destroy.get_name()] = Elements._destroy # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.eat) primitives.append(Elements.eat_fail) primitives.append(Elements.destroy) primitives.append(Elements.destroy_fail) # Set intrinsic homeostatic motivation values. motivation = {} motivation[Elements.step] = lambda agent: agent.get_homeostatic_value("energy") * 0.1 motivation[Elements.step_fail] = lambda agent: -10 motivation[Elements.turn_right] = lambda agent: -2 motivation[Elements.turn_left] = lambda agent: -2 motivation[Elements.wait] = lambda agent: -1 motivation[Elements.eat] = lambda agent: 10 - agent.get_homeostatic_value("energy") * 0.1 motivation[Elements.eat_fail] = lambda agent: -20 motivation[Elements.destroy] = lambda agent: 30 motivation[Elements.destroy_fail] = lambda agent: -2 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) if isinstance(entity, model.agent.HomeostaticConstructiveAgent): entity.set_homeostatic_value("energy", 100) entity.set_perception_handler(model.perceptionhandler.BasicPerceptionHandler()) def controller(self, event, coords): if event.type == pygame.KEYDOWN: if event.key == pygame.K_f: food = model.structure.Food() food.set_position(coords) self.world.add_entity(food) elif event.key == pygame.K_b: block = model.structure.Block() block.set_position(coords) self.world.add_entity(block) class BasicRandomExperiment(BasicHomeostaticVisionExperiment): def __init__(self): super(BasicRandomExperiment, self).__init__() def add_food(world, t): if len(world.get_entities_of_type(model.structure.Food)) == 0: # Add food positions = world.get_free_positions() p = random.choice(positions) food = model.structure.Food() food.set_position(p) world.add_entity(food) self.world.add_mutate_callback(add_food) class BasicVisionPushExperiment(experiment.Experiment): world_representation = [ "wwwwwwwwwwwwwww", "w............pw", "wwwwwwwwwwwwwww" ] def __init__(self): super(BasicVisionPushExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Register the previously defined functions. enact_logic = Elements.get_enact_logic() # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.push) primitives.append(Elements.push_fail) # Set intrinsic motivation values. motivation = {} motivation[Elements.step] = -1 motivation[Elements.step_fail] = -10 motivation[Elements.turn_right] = -2 motivation[Elements.turn_left] = -2 motivation[Elements.wait] = -1 motivation[Elements.push] = 500 motivation[Elements.push_fail] = -1 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) class BasicVisionCoexsistenceExperiment(experiment.Experiment): world_representation = [ "wwwww", "w..pw", "w.w.w", "w.w.w", "wp..w", "wwwww" ] def __init__(self): super(BasicVisionCoexsistenceExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Register the previously defined functions. enact_logic = Elements.get_enact_logic() # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.cuddle) primitives.append(Elements.cuddle_fail) # Set intrinsic motivation values. motivation = {} motivation[Elements.step] = -1 motivation[Elements.step_fail] = -10 motivation[Elements.turn_right] = -2 motivation[Elements.turn_left] = -2 motivation[Elements.wait] = -1 motivation[Elements.cuddle] = 50 motivation[Elements.cuddle_fail] = -1 for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) class BasicVisionCoexsistenceDestroyExperiment(experiment.Experiment): world_representation = [ "wwwwwwwwwwww", "wp.........w", "w..........w", "wwwwwwwwwwww" ] def __init__(self): super(BasicVisionCoexsistenceDestroyExperiment, self).__init__() # Parse world self.world = self.parse_world(self.world_representation) # Add programmed agent a = agentprogram.agentprogram.create_programmable_agent(agentprogram.agentprogram.SimpleEatingAndDestroyingAgent, self.world) a.set_position((1,2)) self.world.add_entity(a) # Set up primitives collaborative_destroy = model.interaction.PrimitiveInteraction("Collaborative Destroy", "Succeed") collaborative_destroy_fail = model.interaction.PrimitiveInteraction("Collaborative Destroy", "Fail") def _collaborative_destroy(world, agents_interactions): enacted = {} for agent_1, interaction_1 in agents_interactions.iteritems(): if agent_1 in enacted: continue else: enacted[agent_1] = collaborative_destroy_fail # Set fail as default, we will now see whether it succeeded entities = world.get_entities_in_front(agent_1) for entity in entities: if isinstance(entity, model.structure.Block): # There is a block at agent 1's position, try to find a second agent attempting to destroy the same block: for agent_2, interaction_2 in agents_interactions.iteritems(): if agent_1 == agent_2: continue if agent_2.get_position() == agent_1.get_position(): # The agents are at the same position, so the action fails continue if entity in world.get_entities_in_front(agent_2): # Agent 2 is enacting on the same block as agent 1, so the action succeeded world.remove_entity(entity) pos = entity.get_position() pos_2 = (pos.get_x(), pos.get_y() + 1) food_1 = model.structure.Food() food_2 = model.structure.Food() food_1.set_position(pos) food_2.set_position(pos_2) self.world.add_entity(food_1) self.world.add_entity(food_2) enacted[agent_1] = collaborative_destroy enacted[agent_2] = collaborative_destroy return enacted # Register the basic encation logic. enact_logic = Elements.get_enact_logic() # Register the complex enaction logic just defined. self.world.add_complex_enact_logic(_collaborative_destroy, collaborative_destroy.get_name()) # Set primitives known/enactable by the agents. primitives = [] primitives.append(Elements.step) primitives.append(Elements.step_fail) primitives.append(Elements.turn_right) primitives.append(Elements.turn_left) primitives.append(Elements.wait) primitives.append(Elements.eat) primitives.append(Elements.eat_fail) primitives.append(collaborative_destroy) primitives.append(collaborative_destroy_fail) # Set intrinsic motivation values. motivation = {} motivation[Elements.step] = -1 motivation[Elements.step_fail] = -10 motivation[Elements.turn_right] = -2 motivation[Elements.turn_left] = -2 motivation[Elements.wait] = -1 motivation[Elements.eat] = 20 motivation[Elements.eat_fail] = -2 motivation[collaborative_destroy] = 50 motivation[collaborative_destroy_fail] = -1 # Add the logic to all agents present in the world. for entity in self.world.get_entities(): if isinstance(entity, model.agent.Agent): self.world.add_enact_logic(entity, enact_logic) entity.add_primitives(primitives) entity.add_motivations(motivation) def controller(self, event, coords): if event.type == pygame.KEYDOWN: if event.key == pygame.K_f: food = model.structure.Food() food.set_position(coords) self.world.add_entity(food) elif event.key == pygame.K_b: block = model.structure.Block() block.set_position(coords) block.height = 2 self.world.add_entity(block)
# coding=utf-8 # Copyright 2022 The Google Research 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. """Defines the resnet model. Adapted from https://github.com/tensorflow/models/tree/master/official/vision/image_classification/resnet. The following code is based on its v1 version. """ import tensorflow.compat.v1 as tf _BATCH_NORM_DECAY = 0.9 _BATCH_NORM_EPSILON = 1e-5 DEFAULT_VERSION = 2 DEFAULT_DTYPE = tf.float32 CASTABLE_TYPES = (tf.float16,) ALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES NUM_CLASSES = 10 ################################################################################ # Convenience functions for building the ResNet model. ################################################################################ def batch_norm(inputs, training, data_format, name=''): """Performs a batch normalization using a standard set of parameters.""" # We set fused=True for a significant performance boost. See # https://www.tensorflow.org/performance/performance_guide#common_fused_ops return tf.compat.v1.layers.batch_normalization( inputs=inputs, axis=1 if data_format == 'channels_first' else 3, momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True, scale=True, training=training, fused=True, name=name) # add name later if necessary def fixed_padding(inputs, kernel_size, data_format): """Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. Should be a positive integer. data_format: The input format ('channels_last' or 'channels_first'). Returns: A tensor with the same format as the input with the data either intact (if kernel_size == 1) or padded (if kernel_size > 1). """ pad_total = kernel_size - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg if data_format == 'channels_first': padded_inputs = tf.pad( tensor=inputs, paddings=[[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]]) else: padded_inputs = tf.pad( tensor=inputs, paddings=[[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]]) return padded_inputs def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format, name): """Strided 2-D convolution with explicit padding.""" # The padding is consistent and is based only on `kernel_size`, not on the # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). if strides > 1: inputs = fixed_padding(inputs, kernel_size, data_format) return tf.compat.v1.layers.conv2d( inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, padding=('SAME' if strides == 1 else 'VALID'), use_bias=False, reuse=tf.AUTO_REUSE, kernel_initializer=tf.compat.v1.variance_scaling_initializer(), data_format=data_format, name=name) ################################################################################ # ResNet block definitions. ################################################################################ def _building_block_v2(inputs, filters, training, projection_shortcut, strides, data_format, name): """A single block for ResNet v2, without a bottleneck. Batch normalization then ReLu then convolution as described by: Identity Mappings in Deep Residual Networks https://arxiv.org/pdf/1603.05027.pdf by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, Jul 2016. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. filters: The number of filters for the convolutions. training: A Boolean for whether the model is in training or inference mode. Needed for batch normalization. projection_shortcut: The function to use for projection shortcuts (typically a 1x1 convolution when downsampling the input). strides: The block's stride. If greater than 1, this block will ultimately downsample the input. data_format: The input format ('channels_last' or 'channels_first'). name: Block name. Returns: The output tensor of the block; shape should match inputs. """ shortcut = inputs first_name = name + 'first' inputs = batch_norm( inputs, training, data_format, name=first_name + 'batch_norm') inputs = tf.nn.relu(inputs, name=first_name + 'relu') # The projection shortcut should come after the first batch norm and ReLU # since it performs a 1x1 convolution. if projection_shortcut is not None: shortcut = projection_shortcut(inputs, name=first_name + 'proj') second_name = name + 'second' inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=strides, data_format=data_format, name=second_name + 'input') inputs = batch_norm( inputs, training, data_format, name=second_name + 'batch_norm') inputs = tf.nn.relu(inputs, name=second_name + 'relu') third_name = name + 'third' inputs = conv2d_fixed_padding( inputs=inputs, filters=filters, kernel_size=3, strides=1, data_format=data_format, name=third_name + 'input') return inputs + shortcut def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides, training, name, data_format, shortcut=True): """Creates one layer of blocks for the ResNet model. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. filters: The number of filters for the first convolution of the layer. bottleneck: Is the block created a bottleneck block. block_fn: The block to use within the model, either `building_block` or `bottleneck_block`. blocks: The number of blocks contained in the layer. strides: The stride to use for the first convolution of the layer. If greater than 1, this layer will ultimately downsample the input. training: Either True or False, whether we are currently training the model. Needed for batch norm. name: A string name for the tensor output of the block layer. data_format: The input format ('channels_last' or 'channels_first'). shortcut: Whether to use projection shortcut in the first block. Returns: The output tensor of the block layer. """ # Bottleneck blocks end with 4x the number of filters as they start with filters_out = filters * 4 if bottleneck else filters def projection_shortcut(inputs, name): return conv2d_fixed_padding( inputs=inputs, filters=filters_out, kernel_size=1, strides=strides, data_format=data_format, name=name) # Only the first block per block_layer uses projection_shortcut and strides. # Skip the projection shortcut in the first block layer. shortcut_fn = projection_shortcut if shortcut else None inputs = block_fn( inputs, filters, training, shortcut_fn, strides, data_format, name=name + 'input') for j in range(1, blocks): inputs = block_fn( inputs, filters, training, None, 1, data_format, name=name + 'block' + str(j)) return tf.identity(inputs, name) class Model(object): """Base class for building the Resnet Model.""" def __init__(self, resnet_size, bottleneck, num_classes, num_filters, kernel_size, conv_stride, first_pool_size, first_pool_stride, block_sizes, block_strides, resnet_version=DEFAULT_VERSION, data_format=None, dtype=DEFAULT_DTYPE): """Creates a model for classifying an image. Args: resnet_size: A single integer for the size of the ResNet model. bottleneck: Use regular blocks or bottleneck blocks. num_classes: The number of classes used as labels. num_filters: The number of filters to use for the first block layer of the model. This number is then doubled for each subsequent block layer. kernel_size: The kernel size to use for convolution. conv_stride: stride size for the initial convolutional layer first_pool_size: Pool size to be used for the first pooling layer. If none, the first pooling layer is skipped. first_pool_stride: stride size for the first pooling layer. Not used if first_pool_size is None. block_sizes: A list containing n values, where n is the number of sets of block layers desired. Each value should be the number of blocks in the i-th set. block_strides: List of integers representing the desired stride size for each of the sets of block layers. Should be same length as block_sizes. resnet_version: Integer representing which version of the ResNet network to use. See README for details. Valid values: [1, 2] data_format: Input format ('channels_last', 'channels_first', or None). If set to None, the format is dependent on whether a GPU is available. dtype: The TensorFlow dtype to use for calculations. If not specified tf.float32 is used. Raises: ValueError: if invalid version is selected. """ self.resnet_size = resnet_size if not data_format: data_format = ('channels_first' if tf.test.is_built_with_cuda() else 'channels_last') self.resnet_version = resnet_version if resnet_version not in (1, 2): raise ValueError( 'Resnet version should be 1 or 2. See README for citations.') self.bottleneck = bottleneck self.block_fn = _building_block_v2 if dtype not in ALLOWED_TYPES: raise ValueError('dtype must be one of: {}'.format(ALLOWED_TYPES)) self.data_format = data_format self.num_classes = num_classes self.num_filters = num_filters self.kernel_size = kernel_size self.conv_stride = conv_stride self.first_pool_size = first_pool_size self.first_pool_stride = first_pool_stride self.block_sizes = block_sizes self.block_strides = block_strides self.dtype = dtype self.pre_activation = resnet_version == 2 def _custom_dtype_getter(self, # pylint: disable=keyword-arg-before-vararg getter, name, shape=None, dtype=DEFAULT_DTYPE, *args, **kwargs): """Creates variables in fp32, then casts to fp16 if necessary. This function is a custom getter. A custom getter is a function with the same signature as tf.get_variable, except it has an additional getter parameter. Custom getters can be passed as the `custom_getter` parameter of tf.variable_scope. Then, tf.get_variable will call the custom getter, instead of directly getting a variable itself. This can be used to change the types of variables that are retrieved with tf.get_variable. The `getter` parameter is the underlying variable getter, that would have been called if no custom getter was used. Custom getters typically get a variable with `getter`, then modify it in some way. This custom getter will create an fp32 variable. If a low precision (e.g. float16) variable was requested it will then cast the variable to the requested dtype. The reason we do not directly create variables in low precision dtypes is that applying small gradients to such variables may cause the variable not to change. Args: getter: The underlying variable getter, that has the same signature as tf.get_variable and returns a variable. name: The name of the variable to get. shape: The shape of the variable to get. dtype: The dtype of the variable to get. Note that if this is a low precision dtype, the variable will be created as a tf.float32 variable, then cast to the appropriate dtype *args: Additional arguments to pass unmodified to getter. **kwargs: Additional keyword arguments to pass unmodified to getter. Returns: A variable which is cast to fp16 if necessary. """ if dtype in CASTABLE_TYPES: var = getter(name, shape, tf.float32, *args, **kwargs) return tf.cast(var, dtype=dtype, name=name + '_cast') else: return getter(name, shape, dtype, *args, **kwargs) def _model_variable_scope(self): """Returns a variable scope that the model should be created under. If self.dtype is a castable type, model variable will be created in fp32 then cast to self.dtype before being used. Returns: A variable scope for the model. """ return tf.compat.v1.variable_scope( 'resnet_model', custom_getter=self._custom_dtype_getter, reuse=tf.AUTO_REUSE) def __call__(self, inputs, training): """Add operations to classify a batch of input images. Args: inputs: A Tensor representing a batch of input images. training: A boolean. Set to True to add operations required only when training the classifier. Returns: A logits Tensor with shape [<batch_size>, self.num_classes]. """ with self._model_variable_scope(): if self.data_format == 'channels_first': # Convert the inputs from channels_last (NHWC) to channels_first (NCHW). # This provides a large performance boost on GPU. See # https://www.tensorflow.org/performance/performance_guide#data_formats inputs = tf.transpose(a=inputs, perm=[0, 3, 1, 2]) inputs = conv2d_fixed_padding( inputs=inputs, filters=self.num_filters, kernel_size=self.kernel_size, strides=self.conv_stride, data_format=self.data_format, name='initial_input') inputs = tf.identity(inputs, 'initial_conv') # We do not include batch normalization or activation functions in V2 # for the initial conv1 because the first ResNet unit will perform these # for both the shortcut and non-shortcut paths as part of the first # block's projection. Cf. Appendix of [2]. if self.resnet_version == 1: inputs = batch_norm(inputs, training, self.data_format) inputs = tf.nn.relu(inputs) if self.first_pool_size: inputs = tf.compat.v1.layers.max_pooling2d( inputs=inputs, pool_size=self.first_pool_size, strides=self.first_pool_stride, padding='SAME', data_format=self.data_format) inputs = tf.identity(inputs, 'initial_max_pool') for i, num_blocks in enumerate(self.block_sizes): # We now have 4 block layers, but the last does not # double the number of filters. # We also skip the projection shortcut in the first block layer. num_filters = self.num_filters * min((2**i), 4) shortcut = i != 0 inputs = block_layer( inputs=inputs, filters=num_filters, bottleneck=self.bottleneck, block_fn=self.block_fn, blocks=num_blocks, strides=self.block_strides[i], training=training, name='block_layer{}'.format(i + 1), data_format=self.data_format, shortcut=shortcut) # Skip the last BN+relu. # Only apply the BN and ReLU for model that does pre_activation in each # building/bottleneck block, eg resnet V2. # if self.pre_activation: # inputs = batch_norm(inputs, training, self.data_format, # name='pre_act'+'batch_norm') # inputs = tf.nn.relu(inputs,name='pre_act'+'relu') # The current top layer has shape # `batch_size x pool_size x pool_size x final_size`. # ResNet does an Average Pooling layer over pool_size, # but that is the same as doing a reduce_mean. We do a reduce_mean # here because it performs better than AveragePooling2D. # Also perform max-pooling, and concat results. axes = [2, 3] if self.data_format == 'channels_first' else [1, 2] avg_pooled = tf.reduce_mean(input_tensor=inputs, axis=axes, keepdims=True) avg_pooled = tf.squeeze(avg_pooled, axes) max_pooled = tf.reduce_max(input_tensor=inputs, axis=axes, keepdims=True) max_pooled = tf.squeeze(max_pooled, axes) inputs = tf.concat([avg_pooled, max_pooled], axis=1) inputs = tf.identity(inputs, 'final_pooling') inputs = tf.compat.v1.layers.dense( inputs=inputs, units=self.num_classes, reuse=tf.AUTO_REUSE) inputs = tf.identity(inputs, 'final_dense') return inputs ############################################################################### # Running the model ############################################################################### class FastCifar10Model(Model): """Model class with appropriate defaults for CIFAR-10 data.""" def __init__(self, resnet_size, data_format=None, num_classes=NUM_CLASSES, resnet_version=DEFAULT_VERSION, dtype=DEFAULT_DTYPE): """These are the parameters that work for CIFAR-10 data. Args: resnet_size: The number of convolutional layers needed in the model. data_format: Either 'channels_first' or 'channels_last', specifying which data format to use when setting up the model. num_classes: The number of output classes needed from the model. This enables users to extend the same model to their own datasets. resnet_version: Integer representing which version of the ResNet network to use. See README for details. Valid values: [1, 2] dtype: The TensorFlow dtype to use for calculations. Raises: ValueError: if invalid resnet_size is chosen """ # 4 block layers, so change to 8n+2. if resnet_size % 8 != 2: raise ValueError('resnet_size must be 8n + 2:', resnet_size) num_blocks = (resnet_size - 2) // 8 # Switch to 4 block layers. Use 64, 128, 256, 256 filters. super(FastCifar10Model, self).__init__( resnet_size=resnet_size, bottleneck=False, num_classes=num_classes, num_filters=64, kernel_size=3, conv_stride=1, first_pool_size=None, first_pool_stride=None, block_sizes=[num_blocks] * 4, block_strides=[1, 2, 2, 2], resnet_version=resnet_version, data_format=data_format, dtype=dtype)
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from ctypes import * import re from pyglet.gl import * import pyglet.font from layout.base import * from layout.frame import * from layout.locator import * from pyglet import image class GLRenderDevice(RenderDevice): _stock_font_names = { 'serif': 'Bitstream Vera Serif', 'sans-serif': 'Bitstream Vera Sans', 'monospace': 'Bitstream Vera Sans Mono', 'fantasy': 'Bistream Vera Serif', 'cursive': 'Bistream Vera Serif', } def __init__(self, locator=LocalFileLocator): self.locator = locator self.texture_cache = {} def get_font(self, names, size, style, weight): names = names[:] for i, name in enumerate(names): if isinstance(name, Ident) and name in self._stock_font_names: names[i] = self._stock_font_names[name] italic = style == 'italic' bold = weight >= 700 assert type(size) == Dimension and size.unit == 'pt' return pyglet.font.load(names, size, italic=italic, bold=bold) def create_text_frame(self, style, element, text): return GLTextFrame(style, element, text) def draw_solid_border(self, x1, y1, x2, y2, x3, y3, x4, y4, color, style): '''Draw one side of a border, which is not 'dotted' or 'dashed'. ''' glColor4f(*color) glBegin(GL_QUADS) glVertex2f(x1, y1) glVertex2f(x2, y2) glVertex2f(x3, y3) glVertex2f(x4, y4) glEnd() def draw_vertical_border(self, x1, y1, x2, y2, x3, y3, x4, y4, color, style): '''Draw one vertical edge of a border. Order of vertices is inner-top, inner-bottom, outer-bottom, outer-top ''' if style in ('dotted', 'dashed'): width = max(abs(x1 - x4), 1) height = y1 - y2 if style == 'dotted': period = width else: period = width * 3 cycles = int(height / period) padding = (height - cycles * period) / 2 vertices = [ # Top cap x1, y1, x1, y1 - padding, x4, y1 - padding, x4, y4, # Bottom cap x2, y2, x2, y2 + padding, x3, y2 + padding, x3, y3] y = y1 - padding phase = cycles % 2 if phase == 0: y -= period / 2 for i in range(cycles): if i % 2 == phase: vertices += [x1, y, x1, y - period, x3, y - period, x3, y] y -= period self.vertices = (c_float * len(vertices))(*vertices) glColor4f(*color) glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glEnableClientState(GL_VERTEX_ARRAY) glVertexPointer(2, GL_FLOAT, 0, self.vertices) glDrawArrays(GL_QUADS, 0, len(self.vertices)/2) glPopClientAttrib() else: self.draw_solid_border(x1, y1, x2, y2, x3, y3, x4, y4, color, style) def draw_horizontal_border(self, x1, y1, x2, y2, x3, y3, x4, y4, color, style): '''Draw one horizontal edge of a border. Order of vertices is inner-left, inner-right, outer-right, outer-left. ''' if style in ('dotted', 'dashed'): height = max(abs(y1 - y4), 1) width = x2 - x1 if style == 'dotted': period = height else: period = height * 3 cycles = int(width / period) padding = (width - cycles * period) / 2 vertices = [ # Left cap x1, y1, x1 + padding, y1, x1 + padding, y4, x4, y4, # Right cap x2, y2, x2 - padding, y2, x2 - padding, y3, x3, y3] x = x1 + padding phase = cycles % 2 if phase == 0: x += period / 2 for i in range(cycles): if i % 2 == phase: vertices += [x, y1, x + period, y1, x + period, y3, x, y3] x += period self.vertices = (c_float * len(vertices))(*vertices) glColor4f(*color) glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glEnableClientState(GL_VERTEX_ARRAY) glVertexPointer(2, GL_FLOAT, 0, self.vertices) glDrawArrays(GL_QUADS, 0, len(self.vertices)/2) glPopClientAttrib() else: self.draw_solid_border(x1, y1, x2, y2, x3, y3, x4, y4, color, style) def draw_background(self, x1, y1, x2, y2, frame): compute = frame.get_computed_property background_color = compute('background-color') if background_color != 'transparent': glPushAttrib(GL_CURRENT_BIT) glColor4f(*background_color) glBegin(GL_QUADS) glVertex2f(x1, y1) glVertex2f(x1, y2) glVertex2f(x2, y2) glVertex2f(x2, y1) glEnd() glPopAttrib() background_image = compute('background-image') if background_image != 'none': repeat = compute('background-repeat') # TODO tileable texture in cache vs non-tileable, vice-versa if background_image not in self.texture_cache: self.texture_cache[background_image] = None stream = self.locator.get_stream(background_image) if stream: img = image.load('', file=stream) if repeat != 'no-repeat': texture = image.TileableTexture.create_for_image(img) else: texture = img.texture self.texture_cache[background_image] = texture texture = self.texture_cache[background_image] if texture: glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT) glColor3f(1, 1, 1) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if isinstance(texture, image.TileableTexture): width, height = texture.width, texture.height if repeat in ('repeat', 'repeat-x'): width = x2 - x1 if repeat in ('repeat', 'repeat-y'): height = y1 - y2 texture.blit_tiled(x1, y2, 0, width, height) else: texture.blit(x1, y2, 0) glPopAttrib() class GLTextFrame(TextFrame): glyph_string = None from_index = 0 to_index = None content_ascent = 0 def __init__(self, style, element, text): super(GLTextFrame, self).__init__(style, element, text) def lstrip(self): text = self.text[self.from_index:self.to_index] old_index = self.from_index self.from_index += len(text) - len(text.lstrip()) if old_index != self.from_index: self.border_edge_width -= self.glyph_string.get_subwidth( old_index, self.from_index) contains_ws = re.compile(u'[\n\u0020\u200b]') def purge_style_cache(self, properties): super(GLTextFrame, self).purge_style_cache(properties) if ('font-name' in properties or 'font-size' in properties or 'font-weight' in properties or 'font-style' in properties): self.glyph_string = None def flow_inline(self, context): context = context.copy() # Reset after last flow self.from_index = 0 self.strip_next = False self.continuation = None self.close_border = True # Final white-space processing step (besides line beginning strip) # from 16.6.1 step 4. if context.strip_next and \ self.get_computed_property('white-space') in \ ('normal', 'nowrap', 'pre-line'): self.from_index = len(self.text) - len(self.text.lstrip()) # Get GL glyph sequence if not already cached font = self.get_computed_property('--font') if not self.glyph_string: self.glyph_string = pyglet.font.GlyphString( self.text, font.get_glyphs(self.text)) computed = self.get_computed_property def used(property): value = computed(property) if type(value) == Percentage: value = value * self.containing_block.width return value # Calculate computed and used values of box properties when # relative to containing block width. # margin top/bottom remain at class default 0 content_right = computed('border-right-width') + used('padding-right') content_bottom = computed('border-bottom-width') + \ used('padding-bottom') self.content_top = computed('border-top-width') + used('padding-top') self.margin_right = used('margin-right') self.margin_left = used('margin-left') self.content_left = computed('border-left-width') + used('padding-left') # Calculate text metrics (actually not dependent on flow, could # optimise out). self.content_ascent = font.ascent self.content_descent = font.descent line_height = self.get_computed_property('line-height') if line_height != 'normal': half_leading = (line_height - \ (self.content_ascent - self.content_descent)) / 2 else: half_leading = 0 self.line_ascent = self.content_ascent + half_leading self.line_descent = self.content_descent - half_leading self.border_edge_height = self.content_ascent - self.content_descent +\ self.content_top + content_bottom self.border_edge_width = self.content_left self.baseline = self.content_ascent + self.content_top context.add(self.margin_left + self.content_left) context.reserve(content_right + self.margin_right) # Break into continuations frame = self while True: frame.to_index = self.glyph_string.get_break_index( frame.from_index, context.remaining_width - context.reserved_width) if frame.to_index == frame.from_index: ws = self.contains_ws.search(self.text[frame.from_index:]) if ws: frame.to_index = frame.from_index + ws.start() + 1 else: frame.to_index = len(self.text) text_width = self.glyph_string.get_subwidth( frame.from_index, frame.to_index) frame.border_edge_width += text_width if frame.to_index < len(self.text): continuation = GLTextFrame( self.style, self.element, self.text) continuation.parent = self.parent continuation.glyph_string = self.glyph_string continuation.open_border = False continuation.from_index = continuation.to_index = frame.to_index continuation.border_edge_height = self.border_edge_height continuation.border_edge_width = 0 continuation.margin_right = self.margin_right continuation.line_ascent = self.line_ascent continuation.line_descent = self.line_descent continuation.content_ascent = self.content_ascent continuation.content_descent = self.content_descent continuation.baseline = self.baseline # Remove right-margin from continued frame frame.margin_right = 0 if not context.can_add(text_width, True): context.newline() context.add(text_width) context.breakpoint() frame.soft_break = True # Force line break if frame.to_index and self.text[frame.to_index-1] == '\n': frame.to_index -= 1 frame.line_break = True context.newline() # Ready for next iteration frame.continuation = continuation frame.close_border = False frame = continuation context.newline() if frame.to_index >= len(self.text): break frame.strip_next = self.text[-1] == ' ' frame.soft_break = self.text[-1] == ' ' frame.border_edge_width += content_right self.flow_dirty = False def draw_text(self, x, y, render_context): glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT) glEnable(GL_TEXTURE_2D) glColor4f(*self.get_computed_property('color')) glPushMatrix() glTranslatef(x, y, 0) self.glyph_string.draw(self.from_index, self.to_index) glPopMatrix() glPopAttrib() def __repr__(self): return '%s(%r)' % \ (self.__class__.__name__, self.text[self.from_index:self.to_index])
from json import loads as json_loads, dumps as json_dumps from urllib.parse import urlparse import os import ssl import pytest from sanic import Sanic from sanic.exceptions import ServerError from sanic.response import json, text from sanic.testing import HOST, PORT # ------------------------------------------------------------ # # GET # ------------------------------------------------------------ # def test_sync(): app = Sanic('test_text') @app.route('/') def handler(request): return text('Hello') request, response = app.test_client.get('/') assert response.text == 'Hello' def test_text(): app = Sanic('test_text') @app.route('/') async def handler(request): return text('Hello') request, response = app.test_client.get('/') assert response.text == 'Hello' def test_headers(): app = Sanic('test_text') @app.route('/') async def handler(request): headers = {"spam": "great"} return text('Hello', headers=headers) request, response = app.test_client.get('/') assert response.headers.get('spam') == 'great' def test_non_str_headers(): app = Sanic('test_text') @app.route('/') async def handler(request): headers = {"answer": 42} return text('Hello', headers=headers) request, response = app.test_client.get('/') assert response.headers.get('answer') == '42' def test_invalid_response(): app = Sanic('test_invalid_response') @app.exception(ServerError) def handler_exception(request, exception): return text('Internal Server Error.', 500) @app.route('/') async def handler(request): return 'This should fail' request, response = app.test_client.get('/') assert response.status == 500 assert response.text == "Internal Server Error." def test_json(): app = Sanic('test_json') @app.route('/') async def handler(request): return json({"test": True}) request, response = app.test_client.get('/') results = json_loads(response.text) assert results.get('test') == True def test_empty_json(): app = Sanic('test_json') @app.route('/') async def handler(request): assert request.json == None return json(request.json) request, response = app.test_client.get('/') assert response.status == 200 assert response.text == 'null' def test_invalid_json(): app = Sanic('test_json') @app.route('/') async def handler(request): return json(request.json) data = "I am not json" request, response = app.test_client.get('/', data=data) assert response.status == 400 def test_query_string(): app = Sanic('test_query_string') @app.route('/') async def handler(request): return text('OK') request, response = app.test_client.get( '/', params=[("test1", "1"), ("test2", "false"), ("test2", "true")]) assert request.args.get('test1') == '1' assert request.args.get('test2') == 'false' def test_uri_template(): app = Sanic('test_uri_template') @app.route('/foo/<id:int>/bar/<name:[A-z]+>') async def handler(request): return text('OK') request, response = app.test_client.get('/foo/123/bar/baz') assert request.uri_template == '/foo/<id:int>/bar/<name:[A-z]+>' def test_token(): app = Sanic('test_post_token') @app.route('/') async def handler(request): return text('OK') # uuid4 generated token. token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf' headers = { 'content-type': 'application/json', 'Authorization': '{}'.format(token) } request, response = app.test_client.get('/', headers=headers) assert request.token == token token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf' headers = { 'content-type': 'application/json', 'Authorization': 'Token {}'.format(token) } request, response = app.test_client.get('/', headers=headers) assert request.token == token token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf' headers = { 'content-type': 'application/json', 'Authorization': 'Bearer Token {}'.format(token) } request, response = app.test_client.get('/', headers=headers) assert request.token == token # ------------------------------------------------------------ # # POST # ------------------------------------------------------------ # def test_post_json(): app = Sanic('test_post_json') @app.route('/', methods=['POST']) async def handler(request): return text('OK') payload = {'test': 'OK'} headers = {'content-type': 'application/json'} request, response = app.test_client.post( '/', data=json_dumps(payload), headers=headers) assert request.json.get('test') == 'OK' assert response.text == 'OK' def test_post_form_urlencoded(): app = Sanic('test_post_form_urlencoded') @app.route('/', methods=['POST']) async def handler(request): return text('OK') payload = 'test=OK' headers = {'content-type': 'application/x-www-form-urlencoded'} request, response = app.test_client.post('/', data=payload, headers=headers) assert request.form.get('test') == 'OK' def test_post_form_multipart_form_data(): app = Sanic('test_post_form_multipart_form_data') @app.route('/', methods=['POST']) async def handler(request): return text('OK') payload = '------sanic\r\n' \ 'Content-Disposition: form-data; name="test"\r\n' \ '\r\n' \ 'OK\r\n' \ '------sanic--\r\n' headers = {'content-type': 'multipart/form-data; boundary=----sanic'} request, response = app.test_client.post(data=payload, headers=headers) assert request.form.get('test') == 'OK' @pytest.mark.parametrize( 'path,query,expected_url', [ ('/foo', '', 'http://{}:{}/foo'), ('/bar/baz', '', 'http://{}:{}/bar/baz'), ('/moo/boo', 'arg1=val1', 'http://{}:{}/moo/boo?arg1=val1') ]) def test_url_attributes_no_ssl(path, query, expected_url): app = Sanic('test_url_attrs_no_ssl') async def handler(request): return text('OK') app.add_route(handler, path) request, response = app.test_client.get(path + '?{}'.format(query)) assert request.url == expected_url.format(HOST, PORT) parsed = urlparse(request.url) assert parsed.scheme == request.scheme assert parsed.path == request.path assert parsed.query == request.query_string assert parsed.netloc == request.host @pytest.mark.parametrize( 'path,query,expected_url', [ ('/foo', '', 'https://{}:{}/foo'), ('/bar/baz', '', 'https://{}:{}/bar/baz'), ('/moo/boo', 'arg1=val1', 'https://{}:{}/moo/boo?arg1=val1') ]) def test_url_attributes_with_ssl(path, query, expected_url): app = Sanic('test_url_attrs_with_ssl') current_dir = os.path.dirname(os.path.realpath(__file__)) context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) context.load_cert_chain( os.path.join(current_dir, 'certs/selfsigned.cert'), keyfile=os.path.join(current_dir, 'certs/selfsigned.key')) async def handler(request): return text('OK') app.add_route(handler, path) request, response = app.test_client.get( 'https://{}:{}'.format(HOST, PORT) + path + '?{}'.format(query), server_kwargs={'ssl': context}) assert request.url == expected_url.format(HOST, PORT) parsed = urlparse(request.url) assert parsed.scheme == request.scheme assert parsed.path == request.path assert parsed.query == request.query_string assert parsed.netloc == request.host
""" Tests the different linear regression models and chooses best model using AIC, BIC, and Adjusted R2 Averages the criteria for all voxels across 3 subjects Run with: python model_selection.py """ from __future__ import absolute_import, division, print_function import numpy as np import numpy.linalg as npl import nibabel as nib import pandas as pd # new import sys # instead of os import os # Relative path to subjects project_path = "../../../" path_to_data = project_path+"data/ds009/" location_of_images = project_path+"images/" location_of_functions = project_path+"code/utils/functions/" final_data = "../../../final/data/" smooth_data = final_data + 'smooth/' hrf_data = final_data + 'hrf/' behav_suffix = "/behav/task001_run001/behavdata.txt" sys.path.append(location_of_functions) sub_list = os.listdir(path_to_data) sub_list = [i for i in sub_list if 'sub' in i] from event_related_fMRI_functions import hrf_single, np_convolve_30_cuts from time_shift import time_shift, make_shift_matrix, time_correct from glm import glm_multiple, glm_diagnostics from noise_correction import mean_underlying_noise, fourier_predict_underlying_noise,fourier_creation from Image_Visualizing import present_3d, make_mask from mask_phase_2_dimension_change import masking_reshape_start, masking_reshape_end from model_comparison import adjR2, BIC, AIC from hypothesis import t_stat_mult_regression #Choose which criteria input_var = 'AIC' ################################## # Functions for different models # ################################## if input_var == 'adjR2': def model(MRSS,y_1d,df, rank): return adjR2(MRSS,y_1d, df, rank) elif input_var == 'BIC': def model(MRSS,y_1d,df, rank): return BIC(MRSS, y_1d, df, rank) elif input_var == 'AIC': def model(MRSS,y_1d,df, rank): return AIC(MRSS, y_1d, df, rank) #List to include all of the models model1=[] model2=[] model3=[] model4=[] model4_5=[] model5=[] model6=[] model7=[] model8=[] model9=[] model9_5=[] model10=[] #Average for subject 2,3,and 14 for i in ['sub002','sub003','sub014']: img = nib.load(smooth_data+ i +"_bold_smoothed.nii") data = img.get_data() behav=pd.read_table(path_to_data+i+behav_suffix,sep=" ") num_TR = float(behav["NumTRs"]) #CREATE THE CONVOLVE STUFF cond1=np.loadtxt(path_to_data+ i+ "/model/model001/onsets/task001_run001/cond001.txt") cond2=np.loadtxt(path_to_data+ i+ "/model/model001/onsets/task001_run001/cond002.txt") cond3=np.loadtxt(path_to_data+ i+ "/model/model001/onsets/task001_run001/cond003.txt") TR = 2 tr_times = np.arange(0, 30, TR) hrf_at_trs = np.array([hrf_single(x) for x in tr_times]) # creating the .txt file for the events2neural function cond_all=np.row_stack((cond1,cond2,cond3)) cond_all=sorted(cond_all,key= lambda x:x[0]) cond_all=np.array(cond_all)[:,0] delta_y=2*(np.arange(34))/34 shifted_all=make_shift_matrix(cond_all,delta_y) shifted_1= make_shift_matrix(cond1[:,0],delta_y) shifted_2= make_shift_matrix(cond2[:,0],delta_y) shifted_3= make_shift_matrix(cond3[:,0],delta_y) ######################################### #Create convovled HRF for each condition# ######################################### def make_convolve_lambda(hrf_function,TR,num_TRs): convolve_lambda=lambda x: np_convolve_30_cuts(x,np.ones(x.shape[0]),hrf_function,TR,np.linspace(0,(num_TRs-1)*TR,num_TRs),15) return convolve_lambda convolve_lambda=make_convolve_lambda(hrf_single,TR,num_TR) hrf_matrix_all=time_correct(convolve_lambda,shifted_all,num_TR) hrf_matrix_1=time_correct(convolve_lambda,shifted_1,num_TR) hrf_matrix_2=time_correct(convolve_lambda,shifted_2,num_TR) hrf_matrix_3=time_correct(convolve_lambda,shifted_3,num_TR) n_vols = data.shape[-1] ########################################## # Create PCA features for our regression # ########################################## mask = nib.load(path_to_data+i+'/anatomy/inplane001_brain_mask.nii.gz') mask_data = mask.get_data() mask_data = make_mask(np.ones(data.shape[:-1]), mask_data, fit=True) mask_data = mask_data!=0 mask_data = mask_data.astype(int) to_2d= masking_reshape_start(data,mask) # double_centered_2d X_pca= to_2d - np.mean(to_2d,0) - np.mean(to_2d,1)[:,None] cov = X_pca.T.dot(X_pca) U, S, V = npl.svd(cov) pca_addition= U[:,:6] # ~40% coverage #Run GLM Per slice for j in range(data.shape[2]): data_slice = data[:,:,j,:] mask_slice = mask_data[:,:,j] data_slice = data_slice.reshape((-1,num_TR)) mask_slice = np.ravel(mask_slice) data_slice = data_slice[mask_slice==1] # all conditions in 1 roof (cond_all) X = np.ones((n_vols,13)) X[:,1] = hrf_matrix_all[:,j] # 1 more X[:,2] = np.linspace(-1,1,num=X.shape[0]) #drift # one X[:,3:7] = fourier_creation(X.shape[0],2)[:,1:] # four more X[:,7:] = pca_addition # all conditions seperate (cond1,cond2,cond3) X_cond = np.ones((n_vols,15)) X_cond[:,1] = hrf_matrix_1[:,j] X_cond[:,2] = hrf_matrix_2[:,j] X_cond[:,3] = hrf_matrix_3[:,j] X_cond[:,4] = np.linspace(-1,1,num=X.shape[0]) #drift # one X_cond[:,5:9] = fourier_creation(X.shape[0],2)[:,1:] # four more X_cond[:,9:] = pca_addition #START CREATING MODELS ################### # MODEL 1 # ################### # 1.1 hrf (simple) beta1,t,df1,p = t_stat_mult_regression(data_slice, X[:,0:2]) MRSS1, fitted, residuals = glm_diagnostics(beta1, X[:,0:2], data_slice) model1_slice = np.zeros(len(MRSS1)) rank1 = npl.matrix_rank(X[:,0:2]) count = 0 for value in MRSS1: model1_slice[count] = model(value, np.array(data_slice[count,:]) ,df1, rank1) count+=1 model1=model1+model1_slice.tolist() ################### # MODEL 2 # ################### # 1.2 hrf + drift beta2,t,df2,p = t_stat_mult_regression(data_slice, X[:,0:3]) MRSS2, fitted, residuals = glm_diagnostics(beta2, X[:,0:3], data_slice) model2_slice = np.zeros(len(MRSS2)) rank2 = npl.matrix_rank(X[:,0:3]) count = 0 for value in MRSS2: model2_slice[count] = model(value, np.array(data_slice[count,:]) ,df2, rank2) count+=1 model2=model2+model2_slice.tolist() ################### # MODEL 3 # ################### # 1.3 hrf + drift + fourier beta3,t,df3,p = t_stat_mult_regression(data_slice, X[:,0:7]) MRSS3, fitted, residuals = glm_diagnostics(beta3, X[:,0:7], data_slice) model3_slice = np.zeros(len(MRSS3)) rank3 = npl.matrix_rank(X[:,0:7]) count = 0 for value in MRSS3: model3_slice[count] = model(value, np.array(data_slice[count,:]) ,df3, rank3) count+=1 model3=model3+model3_slice.tolist() ################### # MODEL 4 # ################### # 1.4 hrf + drift + pca beta4,t,df4,p = t_stat_mult_regression(data_slice, X[:,[0,1,2,7,8,9,10,11,12]]) MRSS4, fitted, residuals = glm_diagnostics(beta4, X[:,[0,1,2,7,8,9,10,11,12]], data_slice) model4_slice = np.zeros(len(MRSS4)) rank4 = npl.matrix_rank(X[:,[0,1,2,7,8,9,10,11,12]]) count = 0 for value in MRSS4: model4_slice[count] = model(value, np.array(data_slice[count,:]) ,df4, rank4) count+=1 model4=model4+model4_slice.tolist() ##################### # MODEL 4_5 # ##################### # 1.4 hrf + drift + pca beta4_5,t,df4_5,p = t_stat_mult_regression(data_slice, X[:,[0,1,2,7,8,9,10]]) MRSS4_5, fitted, residuals = glm_diagnostics(beta4_5, X[:,[0,1,2,7,8,9,10]], data_slice) model4_5_slice = np.zeros(len(MRSS4_5)) rank4_5 = npl.matrix_rank(X[:,[0,1,2,7,8,9,10,11,12]]) count = 0 for value in MRSS4_5: model4_5_slice[count] = model(value, np.array(data_slice[count,:]) ,df4_5, rank4_5) count+=1 model4_5=model4_5+model4_5_slice.tolist() ################### # MODEL 5 # ################### # 1.5 hrf + drift + pca + fourier beta5,t,df5,p = t_stat_mult_regression(data_slice, X) MRSS5, fitted, residuals = glm_diagnostics(beta5, X, data_slice) model5_slice = np.zeros(len(MRSS5)) rank5 = npl.matrix_rank(X) count = 0 for value in MRSS5: model5_slice[count] = model(value, np.array(data_slice[count,:]) ,df5, rank5) count+=1 model5=model5+model5_slice.tolist() ################### # MODEL 6 # ################### # 2.1 hrf beta6,t,df6,p = t_stat_mult_regression(data_slice, X_cond[:,0:4]) MRSS6, fitted, residuals = glm_diagnostics(beta6, X_cond[:,0:4], data_slice) model6_slice = np.zeros(len(MRSS6)) rank6 = npl.matrix_rank(X_cond[:,0:4]) count = 0 for value in MRSS6: model6_slice[count] = model(value, np.array(data_slice[count,:]) ,df6, rank6) count+=1 model6=model6+model6_slice.tolist() ################### # MODEL 7 # ################### # 2.2 hrf + drift beta7,t,df7,p = t_stat_mult_regression(data_slice, X_cond[:,0:5]) MRSS7, fitted, residuals = glm_diagnostics(beta7, X_cond[:,0:5], data_slice) model7_slice = np.zeros(len(MRSS7)) rank7 = npl.matrix_rank(X_cond[:,0:5]) count = 0 for value in MRSS7: model7_slice[count] = model(value, np.array(data_slice[count,:]) ,df7, rank7) count+=1 model7=model7+model7_slice.tolist() ################### # MODEL 8 # ################### # 2.3 hrf + drift + fourier beta8,t,df8,p = t_stat_mult_regression(data_slice, X_cond[:,0:9]) MRSS8, fitted, residuals = glm_diagnostics(beta8, X_cond[:,0:9], data_slice) model8_slice = np.zeros(len(MRSS8)) rank8 = npl.matrix_rank(X_cond[:,0:9]) count = 0 for value in MRSS8: model8_slice[count] = model(value, np.array(data_slice[count,:]) ,df8, rank8) count+=1 model8=model8+model8_slice.tolist() ################### # MODEL 9 # ################### # 2.4 hrf + drift + pca beta9,t,df9,p = t_stat_mult_regression(data_slice, X_cond[:,list(range(5))+list(range(9,15))]) MRSS9, fitted, residuals = glm_diagnostics(beta9,X_cond[:,list(range(5))+list(range(9,15))], data_slice) model9_slice = np.zeros(len(MRSS9)) rank9 = npl.matrix_rank(X_cond[:,list(range(5))+list(range(9,15))]) count = 0 for value in MRSS9: model9_slice[count] = model(value, np.array(data_slice[count,:]) ,df9, rank9) count+=1 model9=model9+model9_slice.tolist() ##################### # MODEL 9_5 # ##################### # 2.4 hrf + drift + pca beta9_5,t,df9_5,p = t_stat_mult_regression(data_slice, X_cond[:,list(range(5))+list(range(9,13))]) MRSS9_5, fitted, residuals = glm_diagnostics(beta9_5,X_cond[:,list(range(5))+list(range(9,13))], data_slice) model9_5_slice = np.zeros(len(MRSS9_5)) rank9_5 = npl.matrix_rank(X_cond[:,list(range(5))+list(range(9,13))]) count = 0 for value in MRSS9_5: model9_5_slice[count] = model(value, np.array(data_slice[count,:]) ,df9_5, rank9_5) count+=1 model9_5=model9_5+model9_5_slice.tolist() #################### # MODEL 10 # #################### # 2.5 hrf + drift + pca + fourier beta10,t,df10,p = t_stat_mult_regression(data_slice, X_cond) MRSS10, fitted, residuals = glm_diagnostics(beta10, X_cond, data_slice) model10_slice = np.zeros(len(MRSS10)) rank10 = npl.matrix_rank(X_cond) count = 0 for value in MRSS10: model10_slice[count] = model(value, np.array(data_slice[count,:]) ,df10, rank10) count+=1 model10=model10+model10_slice.tolist() final = np.array([np.mean(model1), np.mean(model2), np.mean(model3), np.mean(model4), np.mean(model5), np.mean(model6), np.mean(model7), np.mean(model8), np.mean(model9), np.mean(model10)]) final = final.reshape((2,5)) print(final)
"""Provides interfaces to various commands provided by FreeSurfer Change directory to provide relative paths for doctests >>> import os >>> filepath = os.path.dirname( os.path.realpath( __file__ ) ) >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) >>> os.chdir(datadir) """ from __future__ import absolute_import import os, string from os import path from glob import glob from nipype.interfaces.base import (TraitedSpec, DynamicTraitedSpec, InputMultiPath, File, Directory, traits, BaseInterface, ) import nibabel as nb from nipype.interfaces.traits_extension import isdefined, Undefined have_dcmstack = True try: import dicom import dcmstack from dcmstack.dcmmeta import NiftiWrapper except ImportError: have_dcmstack = False def sanitize_path_comp(path_comp): result = [] for char in path_comp: if not char in string.letters + string.digits + '-_.': result.append('_') else: result.append(char) return ''.join(result) class NiftiGeneratorBaseInputSpec(TraitedSpec): out_format = traits.Str(desc="String which can be formatted with " "meta data to create the output filename(s)") out_ext = traits.Str('.nii.gz', usedefault=True, desc="Determines output file type") class NiftiGeneratorBase(BaseInterface): '''Base class for interfaces that produce Nifti files, potentially with embeded meta data.''' def _get_out_path(self, meta, idx=None): '''Return the output path for the gernerated Nifti.''' if self.inputs.out_format: out_fmt = self.inputs.out_format else: #If no out_format is specified, use a sane default that will work #with the provided meta data. out_fmt = [] if not idx is None: out_fmt.append('%03d' % idx) if 'SeriesNumber' in meta: out_fmt.append('%(SeriesNumber)03d') if 'ProtocolName' in meta: out_fmt.append('%(ProtocolName)s') elif 'SeriesDescription' in meta: out_fmt.append('%(SeriesDescription)s') else: out_fmt.append('sequence') out_fmt = '-'.join(out_fmt) out_fn = (out_fmt % meta) + self.inputs.out_ext out_fn = sanitize_path_comp(out_fn) return path.join(os.getcwd(), out_fn) class DcmStackInputSpec(NiftiGeneratorBaseInputSpec): dicom_files = traits.Either(InputMultiPath(File(exists=True)), Directory(exists=True), traits.Str(), mandatory=True) embed_meta = traits.Bool(desc="Embed DICOM meta data into result") exclude_regexes = traits.List(desc="Meta data to exclude, suplementing " "any default exclude filters") include_regexes = traits.List(desc="Meta data to include, overriding any " "exclude filters") class DcmStackOutputSpec(TraitedSpec): out_file = File(exists=True) class DcmStack(NiftiGeneratorBase): '''Create one Nifti file from a set of DICOM files. Can optionally embed meta data. Example ------- >>> from nipype.interfaces.dcmstack import DcmStack >>> stacker = DcmStack() >>> stacker.inputs.dicom_files = 'path/to/series/' >>> stacker.run() # doctest: +SKIP >>> result.outputs.out_file # doctest: +SKIP '/path/to/cwd/sequence.nii.gz' ''' input_spec = DcmStackInputSpec output_spec = DcmStackOutputSpec def _get_filelist(self, trait_input): if isinstance(trait_input, str): if path.isdir(trait_input): return glob(path.join(trait_input, '*.dcm')) else: return glob(trait_input) return trait_input def _run_interface(self, runtime): src_paths = self._get_filelist(self.inputs.dicom_files) include_regexes = dcmstack.default_key_incl_res if isdefined(self.inputs.include_regexes): include_regexes += self.inputs.include_regexes exclude_regexes = dcmstack.default_key_excl_res if isdefined(self.inputs.exclude_regexes): exclude_regexes += self.inputs.exclude_regexes meta_filter = dcmstack.make_key_regex_filter(exclude_regexes, include_regexes) stack = dcmstack.DicomStack(meta_filter=meta_filter) for src_path in src_paths: src_dcm = dicom.read_file(src_path, force=True) stack.add_dcm(src_dcm) nii = stack.to_nifti(embed_meta=True) nw = NiftiWrapper(nii) self.out_path = \ self._get_out_path(nw.meta_ext.get_class_dict(('global', 'const'))) if not self.inputs.embed_meta: nw.remove_extension() nb.save(nii, self.out_path) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs["out_file"] = self.out_path return outputs class GroupAndStackOutputSpec(TraitedSpec): out_list = traits.List(desc="List of output nifti files") class GroupAndStack(DcmStack): '''Create (potentially) multiple Nifti files for a set of DICOM files. ''' input_spec = DcmStackInputSpec output_spec = GroupAndStackOutputSpec def _run_interface(self, runtime): src_paths = self._get_filelist(self.inputs.dicom_files) stacks = dcmstack.parse_and_stack(src_paths) self.out_list = [] for key, stack in stacks.iteritems(): nw = NiftiWrapper(stack.to_nifti(embed_meta=True)) const_meta = nw.meta_ext.get_class_dict(('global', 'const')) out_path = self._get_out_path(const_meta) if not self.inputs.embed_meta: nw.remove_extension() nb.save(nw.nii_img, out_path) self.out_list.append(out_path) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs["out_list"] = self.out_list return outputs class LookupMetaInputSpec(TraitedSpec): in_file = File(mandatory=True, exists=True, desc='The input Nifti file') meta_keys = traits.Either(traits.List(), traits.Dict(), mandatory=True, desc=("List of meta data keys to lookup, or a " "dict where keys specify the meta data keys to " "lookup and the values specify the output names") ) class LookupMeta(BaseInterface): '''Lookup meta data values from a Nifti with embeded meta data. Example ------- >>> from nipype.interfaces import dcmstack >>> lookup = dcmstack.LookupMeta() >>> lookup.inputs.in_file = 'functional.nii' >>> lookup.inputs.meta_keys = {'RepetitionTime' : 'TR', \ 'EchoTime' : 'TE'} >>> result = lookup.run() # doctest: +SKIP >>> result.outputs.TR # doctest: +SKIP 9500.0 >>> result.outputs.TE # doctest: +SKIP 95.0 ''' input_spec = LookupMetaInputSpec output_spec = DynamicTraitedSpec def _make_name_map(self): if isinstance(self.inputs.meta_keys, list): self._meta_keys = {} for key in self.inputs.meta_keys: self._meta_keys[key] = key else: self._meta_keys = self.inputs.meta_keys def _outputs(self): self._make_name_map() outputs = super(LookupMeta, self)._outputs() undefined_traits = {} for out_name in self._meta_keys.values(): outputs.add_trait(out_name, traits.Any) undefined_traits[out_name] = Undefined outputs.trait_set(trait_change_notify=False, **undefined_traits) #Not sure why this is needed for out_name in self._meta_keys.values(): _ = getattr(outputs, out_name) return outputs def _run_interface(self, runtime): #If the 'meta_keys' input is a list, covert it to a dict self._make_name_map() nw = NiftiWrapper.from_filename(self.inputs.in_file) self.result = {} for meta_key, out_name in self._meta_keys.iteritems(): self.result[out_name] = nw.meta_ext.get_values(meta_key) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs.update(self.result) return outputs class CopyMetaInputSpec(TraitedSpec): src_file = File(mandatory=True, exists=True) dest_file = File(mandatory=True, exists=True) include_classes = traits.List(desc="List of specific meta data " "classifications to include. If not " "specified include everything.") exclude_classes = traits.List(desc="List of meta data " "classifications to exclude") class CopyMetaOutputSpec(TraitedSpec): dest_file = File(exists=True) class CopyMeta(BaseInterface): '''Copy meta data from one Nifti file to another. Useful for preserving meta data after some processing steps.''' input_spec = CopyMetaInputSpec output_spec = CopyMetaOutputSpec def _run_interface(self, runtime): src_nii = nb.load(self.inputs.src_file) src = NiftiWrapper(src_nii, make_empty=True) dest_nii = nb.load(self.inputs.dest_file) dest = NiftiWrapper(dest_nii, make_empty=True) classes = src.meta_ext.get_valid_classes() if self.inputs.include_classes: classes = [cls for cls in classes if cls in self.inputs.include_classes ] if self.inputs.exclude_classes: classes = [cls for cls in classes if not cls in self.inputs.exclude_classes ] for cls in classes: src_dict = src.meta_ext.get_class_dict(cls) dest_dict = dest.meta_ext.get_class_dict(cls) dest_dict.update(src_dict) # Update the shape and slice dimension to reflect the meta extension update. dest.meta_ext.slice_dim = src.meta_ext.slice_dim dest.meta_ext.shape = src.meta_ext.shape self.out_path = path.join(os.getcwd(), path.basename(self.inputs.dest_file)) dest.to_filename(self.out_path) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs['dest_file'] = self.out_path return outputs class MergeNiftiInputSpec(NiftiGeneratorBaseInputSpec): in_files = traits.List(mandatory=True, desc="List of Nifti files to merge") sort_order = traits.Either(traits.Str(), traits.List(), desc="One or more meta data keys to " "sort files by.") merge_dim = traits.Int(desc="Dimension to merge along. If not " "specified, the last singular or " "non-existant dimension is used.") class MergeNiftiOutputSpec(TraitedSpec): out_file = File(exists=True, desc="Merged Nifti file") def make_key_func(meta_keys, index=None): def key_func(src_nii): result = [src_nii.get_meta(key, index) for key in meta_keys] return result return key_func class MergeNifti(NiftiGeneratorBase): '''Merge multiple Nifti files into one. Merges together meta data extensions as well.''' input_spec = MergeNiftiInputSpec output_spec = MergeNiftiOutputSpec def _run_interface(self, runtime): niis = [nb.load(fn) for fn in self.inputs.in_files ] nws = [NiftiWrapper(nii, make_empty=True) for nii in niis ] if self.inputs.sort_order: sort_order = self.inputs.sort_order if isinstance(sort_order, str): sort_order = [sort_order] nws.sort(key=make_key_func(sort_order)) if self.inputs.merge_dim == traits.Undefined: merge_dim = None else: merge_dim = self.inputs.merge_dim merged = NiftiWrapper.from_sequence(nws, merge_dim) const_meta = merged.meta_ext.get_class_dict(('global', 'const')) self.out_path = self._get_out_path(const_meta) nb.save(merged.nii_img, self.out_path) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs['out_file'] = self.out_path return outputs class SplitNiftiInputSpec(NiftiGeneratorBaseInputSpec): in_file = File(exists=True, mandatory=True, desc="Nifti file to split") split_dim = traits.Int(desc="Dimension to split along. If not " "specified, the last dimension is used.") class SplitNiftiOutputSpec(TraitedSpec): out_list = traits.List(File(exists=True), desc="Split Nifti files") class SplitNifti(NiftiGeneratorBase): '''Split one Nifti file into many along the specified dimension. Each result has an updated meta data extension as well.''' input_spec = SplitNiftiInputSpec output_spec = SplitNiftiOutputSpec def _run_interface(self, runtime): self.out_list = [] nii = nb.load(self.inputs.in_file) nw = NiftiWrapper(nii, make_empty=True) split_dim = None if self.inputs.split_dim == traits.Undefined: split_dim = None else: split_dim = self.inputs.split_dim for split_idx, split_nw in enumerate(nw.split(split_dim)): const_meta = split_nw.meta_ext.get_class_dict(('global', 'const')) out_path = self._get_out_path(const_meta, idx=split_idx) nb.save(split_nw.nii_img, out_path) self.out_list.append(out_path) return runtime def _list_outputs(self): outputs = self._outputs().get() outputs['out_list'] = self.out_list return outputs
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import mock import warnings from django.core.urlresolvers import NoReverseMatch, set_urlconf from django.template import Context, Template from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from subdomains.middleware import ( SubdomainMiddleware, SubdomainURLRoutingMiddleware ) from subdomains.utils import reverse, urljoin def prefix_values(dictionary, prefix): return dict((key, '%s.%s' % (prefix, value)) for key, value in dictionary.items()) class SubdomainTestMixin(object): DOMAIN = 'example.com' URL_MODULE_PATH = 'subdomains.tests.urls' @override_settings( DEFAULT_URL_SCHEME='http', ROOT_URLCONF='%s.application' % URL_MODULE_PATH, BASE_DOMAIN='example.com', SUBDOMAIN_URLCONFS=prefix_values({ None: 'marketing', 'api': 'api', 'www': 'marketing', }, prefix=URL_MODULE_PATH), MIDDLEWARE_CLASSES=( 'subdomains.middleware.SubdomainURLRoutingMiddleware', 'django.middleware.common.CommonMiddleware', ) ) def run(self, *args, **kwargs): super(SubdomainTestMixin, self).run(*args, **kwargs) def get_path_to_urlconf(self, name): """ Returns the full path to the given urlconf. """ return '.'.join((self.URL_MODULE_PATH, name)) def get_host_for_subdomain(self, subdomain=None): """ Returns the hostname for the provided subdomain. """ if subdomain is not None: host = '%s.%s' % (subdomain, self.DOMAIN) else: host = '%s' % self.DOMAIN return host class SubdomainMiddlewareTestCase(SubdomainTestMixin, TestCase): def setUp(self): super(SubdomainMiddlewareTestCase, self).setUp() self.middleware = SubdomainMiddleware() def test_subdomain_attribute(self): def subdomain(subdomain): """ Returns the subdomain associated with the request by the middleware for the given subdomain. """ host = self.get_host_for_subdomain(subdomain) request = RequestFactory().get('/', HTTP_HOST=host) self.middleware.process_request(request) return request.subdomain self.assertEqual(subdomain(None), None) self.assertEqual(subdomain('www'), 'www') self.assertEqual(subdomain('www.subdomain'), 'www.subdomain') self.assertEqual(subdomain('subdomain'), 'subdomain') self.assertEqual(subdomain('another.subdomain'), 'another.subdomain') def test_www_domain(self): def host(host): """ Returns the subdomain for the provided HTTP Host. """ request = RequestFactory().get('/', HTTP_HOST=host) self.middleware.process_request(request) return request.subdomain with override_settings(BASE_DOMAIN='www.example.com', REMOVE_WWW_FROM_DOMAIN=False): self.assertEqual(host('www.%s' % self.DOMAIN), None) # Squelch the subdomain warning for cleaner test output, since we # already know that this is an invalid subdomain. with warnings.catch_warnings(record=True) as warnlist: self.assertEqual(host('www.subdomain.%s' % self.DOMAIN), None) self.assertEqual(host('subdomain.%s' % self.DOMAIN), None) # Trick pyflakes into not warning us about variable usage. del warnlist self.assertEqual(host('subdomain.www.%s' % self.DOMAIN), 'subdomain') self.assertEqual(host('www.subdomain.www.%s' % self.DOMAIN), 'www.subdomain') with override_settings(BASE_DOMAIN='www.example.com', REMOVE_WWW_FROM_DOMAIN=True): self.assertEqual(host('www.%s' % self.DOMAIN), 'www') self.assertEqual(host('subdomain.%s' % self.DOMAIN), 'subdomain') self.assertEqual(host('subdomain.www.%s' % self.DOMAIN), 'subdomain.www') def test_case_insensitive_subdomain(self): host = 'WWW.%s' % self.DOMAIN request = RequestFactory().get('/', HTTP_HOST=host) self.middleware.process_request(request) self.assertEqual(request.subdomain, 'www') host = 'www.%s' % self.DOMAIN.upper() request = RequestFactory().get('/', HTTP_HOST=host) self.middleware.process_request(request) self.assertEqual(request.subdomain, 'www') class SubdomainURLRoutingTestCase(SubdomainTestMixin, TestCase): def setUp(self): super(SubdomainURLRoutingTestCase, self).setUp() self.middleware = SubdomainURLRoutingMiddleware() def test_url_routing(self): def urlconf(subdomain): """ Returns the URLconf associated with this request. """ host = self.get_host_for_subdomain(subdomain) request = RequestFactory().get('/', HTTP_HOST=host) self.middleware.process_request(request) return getattr(request, 'urlconf', None) self.assertEqual(urlconf(None), self.get_path_to_urlconf('marketing')) self.assertEqual(urlconf('www'), self.get_path_to_urlconf('marketing')) self.assertEqual(urlconf('api'), self.get_path_to_urlconf('api')) # Falls through to the actual ROOT_URLCONF. self.assertEqual(urlconf('subdomain'), None) def test_appends_slash(self): for subdomain in (None, 'api', 'wildcard'): host = self.get_host_for_subdomain(subdomain) response = self.client.get('/example', HTTP_HOST=host) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], 'http://%s/example/' % host) class SubdomainURLReverseTestCase(SubdomainTestMixin, TestCase): def test_url_join(self): self.assertEqual(urljoin(self.DOMAIN), 'http://%s' % self.DOMAIN) self.assertEqual(urljoin(self.DOMAIN, scheme='https'), 'https://%s' % self.DOMAIN) with override_settings(DEFAULT_URL_SCHEME='https'): self.assertEqual(urljoin(self.DOMAIN), 'https://%s' % self.DOMAIN) self.assertEqual(urljoin(self.DOMAIN, path='/example/'), 'http://%s/example/' % self.DOMAIN) def test_implicit_reverse(self): # Uses settings.SUBDOMAIN_URLCONFS[None], if it exists. # Otherwise would perform the same behavior as `test_wildcard_reverse`. self.assertEqual(reverse('home'), 'http://%s/' % self.DOMAIN) def test_explicit_reverse(self): # Uses explicitly provided settings.SUBDOMAIN_URLCONF[subdomain] self.assertEqual(reverse('home', subdomain='api'), 'http://api.%s/' % self.DOMAIN) self.assertEqual(reverse('view', subdomain='api'), 'http://api.%s/view/' % self.DOMAIN) def test_wildcard_reverse(self): # Falls through to settings.ROOT_URLCONF subdomain = 'wildcard' self.assertEqual(reverse('home', subdomain), 'http://%s.%s/' % (subdomain, self.DOMAIN)) self.assertEqual(reverse('view', subdomain), 'http://%s.%s/view/' % (subdomain, self.DOMAIN)) def test_reverse_subdomain_mismatch(self): self.assertRaises(NoReverseMatch, lambda: reverse('view')) def test_reverse_invalid_urlconf_argument(self): self.assertRaises( TypeError, lambda: reverse( 'home', urlconf=self.get_path_to_urlconf('marketing'))) def test_using_not_default_urlconf(self): # Ensure that changing the currently active URLconf to something other # than the default still resolves wildcard subdomains correctly. set_urlconf(self.get_path_to_urlconf('api')) subdomain = 'wildcard' # This will raise NoReverseMatch if we're using the wrong URLconf for # the provided subdomain. self.assertEqual( reverse('application', subdomain=subdomain), 'http://%s.%s/application/' % (subdomain, self.DOMAIN) ) class SubdomainTemplateTagTestCase(SubdomainTestMixin, TestCase): def make_template(self, template): return Template('{% load subdomainurls %}' + template) def test_without_subdomain(self): defaults = {'view': 'home'} template = self.make_template('{% url view %}') context = Context(defaults) rendered = template.render(context).strip() self.assertEqual(rendered, 'http://%s/' % self.DOMAIN) def test_with_subdomain(self): defaults = {'view': 'home'} template = self.make_template('{% url view subdomain=subdomain %}') for subdomain in ('www', 'api', 'wildcard'): context = Context(dict(defaults, subdomain=subdomain)) rendered = template.render(context).strip() self.assertEqual(rendered, 'http://%s.%s/' % (subdomain, self.DOMAIN)) def test_no_reverse(self): template = self.make_template('{% url view subdomain=subdomain %}') context = Context({'view': '__invalid__'}) self.assertRaises(NoReverseMatch, lambda: template.render(context)) def test_implied_subdomain_from_request(self): template = self.make_template('{% url view %}') defaults = {'view': 'home'} request = mock.Mock() request.subdomain = None context = Context(dict(defaults, request=request)) rendered = template.render(context).strip() self.assertEqual(rendered, 'http://%s/' % self.DOMAIN) for subdomain in ('www', 'api', 'wildcard'): request = mock.Mock() request.subdomain = subdomain context = Context(dict(defaults, request=request)) rendered = template.render(context).strip() self.assertEqual( rendered, 'http://%s.%s/' % (subdomain, self.DOMAIN) )
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, print_function """ This module implements plotter for DOS and band structure. """ __author__ = "Shyue Ping Ong, Geoffroy Hautier" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "May 1, 2012" import logging import math import itertools from collections import OrderedDict import numpy as np from monty.json import jsanitize from pymatgen.electronic_structure.core import Spin from pymatgen.electronic_structure.bandstructure import BandStructureSymmLine logger = logging.getLogger('BSPlotter') class DosPlotter(object): """ Class for plotting DOSs. Note that the interface is extremely flexible given that there are many different ways in which people want to view DOS. The typical usage is:: # Initializes plotter with some optional args. Defaults are usually # fine, plotter = DosPlotter() # Adds a DOS with a label. plotter.add_dos("Total DOS", dos) # Alternatively, you can add a dict of DOSs. This is the typical # form returned by CompleteDos.get_spd/element/others_dos(). plotter.add_dos_dict({"dos1": dos1, "dos2": dos2}) plotter.add_dos_dict(complete_dos.get_spd_dos()) Args: zero_at_efermi: Whether to shift all Dos to have zero energy at the fermi energy. Defaults to True. stack: Whether to plot the DOS as a stacked area graph key_sort_func: function used to sort the dos_dict keys. sigma: A float specifying a standard deviation for Gaussian smearing the DOS for nicer looking plots. Defaults to None for no smearing. """ def __init__(self, zero_at_efermi=True, stack=False, sigma=None): self.zero_at_efermi = zero_at_efermi self.stack = stack self.sigma = sigma self._doses = OrderedDict() def add_dos(self, label, dos): """ Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: Dos object """ energies = dos.energies - dos.efermi if self.zero_at_efermi \ else dos.energies densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities efermi = dos.efermi self._doses[label] = {'energies': energies, 'densities': densities, 'efermi': efermi} def add_dos_dict(self, dos_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_func: keys = sorted(dos_dict.keys(), key=key_sort_func) else: keys = dos_dict.keys() for label in keys: self.add_dos(label, dos_dict[label]) def get_dos_dict(self): """ Returns the added doses as a json-serializable dict. Note that if you have specified smearing for the DOS plot, the densities returned will be the smeared densities, not the original densities. Returns: Dict of dos data. Generally of the form, {label: {'energies':.., 'densities': {'up':...}, 'efermi':efermi}} """ return jsanitize(self._doses) def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ import prettyplotlib as ppl from prettyplotlib import brewer2mpl from pymatgen.util.plotting_utils import get_publication_quality_plot ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allenergies = [] plt = get_publication_quality_plot(12, 8) # Note that this complicated processing of energies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): energies = dos['energies'] densities = dos['densities'] if not y: y = {Spin.up: np.zeros(energies.shape), Spin.down: np.zeros(energies.shape)} newdens = {} for spin in [Spin.up, Spin.down]: if spin in densities: if self.stack: y[spin] += densities[spin] newdens[spin] = y[spin].copy() else: newdens[spin] = densities[spin] allenergies.append(energies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allenergies.reverse() allpts = [] for i, key in enumerate(keys): x = [] y = [] for spin in [Spin.up, Spin.down]: if spin in alldensities[i]: densities = list(int(spin) * alldensities[i][spin]) energies = list(allenergies[i]) if spin == Spin.down: energies.reverse() densities.reverse() x.extend(energies) y.extend(densities) allpts.extend(list(zip(x, y))) if self.stack: plt.fill(x, y, color=colors[i % ncolors], label=str(key)) else: ppl.plot(x, y, color=colors[i % ncolors], label=str(key), linewidth=3) if not self.zero_at_efermi: ylim = plt.ylim() ppl.plot([self._doses[key]['efermi'], self._doses[key]['efermi']], ylim, color=colors[i % ncolors], linestyle='--', linewidth=2) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) if self.zero_at_efermi: ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Energies (eV)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt def save_plot(self, filename, img_format="eps", xlim=None, ylim=None): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = self.get_plot(xlim, ylim) plt.savefig(filename, format=img_format) def show(self, xlim=None, ylim=None): """ Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = self.get_plot(xlim, ylim) plt.show() class BSPlotter(object): """ Class to plot or get data to facilitate the plot of band structure objects. Args: bs: A BandStructureSymmLine object. """ def __init__(self, bs): if not isinstance(bs, BandStructureSymmLine): raise ValueError( "BSPlotter only works with BandStructureSymmLine objects. " "A BandStructure object (on a uniform grid for instance and " "not along symmetry lines won't work)") self._bs = bs # TODO: come with an intelligent way to cut the highest unconverged # bands self._nb_bands = self._bs._nb_bands def _maketicks(self, plt): """ utility private method to add ticks to a band structure """ ticks = self.get_ticks() # Sanitize only plot the uniq values uniq_d = [] uniq_l = [] temp_ticks = list(zip(ticks['distance'], ticks['label'])) for i in range(len(temp_ticks)): if i == 0: uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) else: if temp_ticks[i][1] == temp_ticks[i - 1][1]: logger.debug("Skipping label {i}".format( i=temp_ticks[i][1])) else: logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Unique labels are %s" % list(zip(uniq_d, uniq_l))) plt.gca().set_xticks(uniq_d) plt.gca().set_xticklabels(uniq_l) for i in range(len(ticks['label'])): if ticks['label'][i] is not None: # don't print the same label twice if i != 0: if ticks['label'][i] == ticks['label'][i - 1]: logger.debug("already print label... " "skipping label {i}".format( i=ticks['label'][i])) else: logger.debug("Adding a line at {d}" " for label {l}".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') else: logger.debug("Adding a line at {d} for label {l}".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') return plt def bs_plot_data(self, zero_to_efermi=True): """ Get the data nicely formatted for a plot Args: zero_to_efermi: Automatically subtract off the Fermi energy from the eigenvalues and plot. Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a kpoint (the x axis) and the labels (None if no label) energy: A dict storing bands for spin up and spin down data [{Spin:[band_index][k_point_index]}] as a list (one element for each branch) of energy for each kpoint. The data is stored by branch to facilitate the plotting vbm: A list of tuples (distance,energy) marking the vbms. The energies are shifted with respect to the fermi level is the option has been selected. cbm: A list of tuples (distance,energy) marking the cbms. The energies are shifted with respect to the fermi level is the option has been selected. lattice: The reciprocal lattice. zero_energy: This is the energy used as zero for the plot. band_gap:A string indicating the band gap and its nature (empty if it's a metal). is_metal: True if the band structure is metallic (i.e., there is at least one band crossing the fermi level). """ distance = [] energy = [] if self._bs.is_metal(): zero_energy = self._bs.efermi else: zero_energy = self._bs.get_vbm()['energy'] if not zero_to_efermi: zero_energy = 0.0 for b in self._bs._branches: if self._bs.is_spin_polarized: energy.append({str(Spin.up): [], str(Spin.down): []}) else: energy.append({str(Spin.up): []}) distance.append([self._bs._distance[j] for j in range(b['start_index'], b['end_index'] + 1)]) ticks = self.get_ticks() for i in range(self._nb_bands): energy[-1][str(Spin.up)].append( [self._bs._bands[Spin.up][i][j] - zero_energy for j in range(b['start_index'], b['end_index'] + 1)]) if self._bs.is_spin_polarized: for i in range(self._nb_bands): energy[-1][str(Spin.down)].append( [self._bs._bands[Spin.down][i][j] - zero_energy for j in range(b['start_index'], b['end_index'] + 1)]) vbm = self._bs.get_vbm() cbm = self._bs.get_cbm() vbm_plot = [] cbm_plot = [] for index in cbm['kpoint_index']: cbm_plot.append((self._bs._distance[index], cbm['energy'] - zero_energy if zero_to_efermi else cbm['energy'])) for index in vbm['kpoint_index']: vbm_plot.append((self._bs._distance[index], vbm['energy'] - zero_energy if zero_to_efermi else vbm['energy'])) bg = self._bs.get_band_gap() direct = "Indirect" if bg['direct']: direct = "Direct" return {'ticks': ticks, 'distances': distance, 'energy': energy, 'vbm': vbm_plot, 'cbm': cbm_plot, 'lattice': self._bs._lattice_rec.as_dict(), 'zero_energy': zero_energy, 'is_metal': self._bs.is_metal(), 'band_gap': "{} {} bandgap = {}".format(direct, bg['transition'], bg['energy']) if not self._bs.is_metal() else ""} def get_plot(self, zero_to_efermi=True, ylim=None, smooth=False, vbm_cbm_marker=False): """ get a matplotlib object for the bandstructure plot. Blue lines are up spin, red lines are down spin. Args: zero_to_efermi: Automatically subtract off the Fermi energy from the eigenvalues and plot (E-Ef). ylim: Specify the y-axis (energy) limits; by default None let the code choose. It is vbm-4 and cbm+4 if insulator efermi-10 and efermi+10 if metal smooth: interpolates the bands by a spline cubic """ from pymatgen.util.plotting_utils import get_publication_quality_plot plt = get_publication_quality_plot(12, 8) from matplotlib import rc import scipy.interpolate as scint rc('text', usetex=True) # main internal config options e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 #band_linewidth = 3 band_linewidth = 1 data = self.bs_plot_data(zero_to_efermi) if not smooth: for d in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][d], [data['energy'][d][str(Spin.up)][i][j] for j in range(len(data['distances'][d]))], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(data['distances'][d], [data['energy'][d][str(Spin.down)][i][j] for j in range(len(data['distances'][d]))], 'r--', linewidth=band_linewidth) else: for d in range(len(data['distances'])): for i in range(self._nb_bands): tck = scint.splrep( data['distances'][d], [data['energy'][d][str(Spin.up)][i][j] for j in range(len(data['distances'][d]))]) step = (data['distances'][d][-1] - data['distances'][d][0]) / 1000 plt.plot([x * step + data['distances'][d][0] for x in range(1000)], [scint.splev(x * step + data['distances'][d][0], tck, der=0) for x in range(1000)], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: tck = scint.splrep( data['distances'][d], [data['energy'][d][str(Spin.down)][i][j] for j in range(len(data['distances'][d]))]) step = (data['distances'][d][-1] - data['distances'][d][0]) / 1000 plt.plot([x * step + data['distances'][d][0] for x in range(1000)], [scint.splev( x * step + data['distances'][d][0], tck, der=0) for x in range(1000)], 'r--', linewidth=band_linewidth) self._maketicks(plt) # Main X and Y Labels plt.xlabel(r'$\mathrm{Wave\ Vector}$', fontsize=30) ylabel = r'$\mathrm{E\ -\ E_f\ (eV)}$' if zero_to_efermi \ else r'$\mathrm{Energy\ (eV)}$' plt.ylabel(ylabel, fontsize=30) # Draw Fermi energy, only if not the zero if not zero_to_efermi: ef = self._bs.efermi plt.axhline(ef, linewidth=2, color='k') # X range (K) # last distance point x_max = data['distances'][-1][-1] plt.xlim(0, x_max) if ylim is None: if self._bs.is_metal(): # Plot A Metal if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs._efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) plt.tight_layout() return plt def show(self, zero_to_efermi=True, ylim=None, smooth=False): """ Show the plot using matplotlib. Args: zero_to_efermi: Automatically subtract off the Fermi energy from the eigenvalues and plot (E-Ef). ylim: Specify the y-axis (energy) limits; by default None let the code choose. It is vbm-4 and cbm+4 if insulator efermi-10 and efermi+10 if metal smooth: interpolates the bands by a spline cubic """ plt = self.get_plot(zero_to_efermi, ylim, smooth) plt.show() def save_plot(self, filename, img_format="eps", ylim=None, zero_to_efermi=True, smooth=False): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. """ plt = self.get_plot(ylim=ylim, zero_to_efermi=zero_to_efermi, smooth=smooth) plt.savefig(filename, format=img_format) plt.close() def get_ticks(self): """ Get all ticks and labels for a band structure plot. Returns: A dict with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks. """ tick_distance = [] tick_labels = [] previous_label = self._bs._kpoints[0].label previous_branch = self._bs._branches[0]['name'] for i, c in enumerate(self._bs._kpoints): if c.label is not None: tick_distance.append(self._bs._distance[i]) this_branch = None for b in self._bs._branches: if b['start_index'] <= i <= b['end_index']: this_branch = b['name'] break if c.label != previous_label \ and previous_branch != this_branch: label1 = c.label if label1.startswith("\\") or label1.find("_") != -1: label1 = "$" + label1 + "$" label0 = previous_label if label0.startswith("\\") or label0.find("_") != -1: label0 = "$" + label0 + "$" tick_labels.pop() tick_distance.pop() tick_labels.append(label0 + "$\mid$" + label1) else: if c.label.startswith("\\") or c.label.find("_") != -1: tick_labels.append("$" + c.label + "$") else: tick_labels.append(c.label) previous_label = c.label previous_branch = this_branch return {'distance': tick_distance, 'label': tick_labels} def plot_compare(self, other_plotter): """ plot two band structure for comparison. One is in red the other in blue (no difference in spins). The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the BSPlotter Args: another band structure object defined along the same symmetry lines Returns: a matplotlib object with both band structures """ # TODO: add exception if the band structures are not compatible plt = self.get_plot() data_orig = self.bs_plot_data() data = other_plotter.bs_plot_data() band_linewidth = 3 for i in range(other_plotter._nb_bands): plt.plot(data_orig['distances'], [e for e in data['energy'][str(Spin.up)][i]], 'r-', linewidth=band_linewidth) if other_plotter._bs.is_spin_polarized: plt.plot(data_orig['distances'], [e for e in data['energy'][str(Spin.down)][i]], 'r-', linewidth=band_linewidth) return plt def plot_brillouin(self): """ plot the Brillouin zone """ import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = Axes3D(fig) vec1 = self._bs.lattice.matrix[0] vec2 = self._bs.lattice.matrix[1] vec3 = self._bs.lattice.matrix[2] # make the grid max_x = -1000 max_y = -1000 max_z = -1000 min_x = 1000 min_y = 1000 min_z = 1000 list_k_points = [] for i in [-1, 0, 1]: for j in [-1, 0, 1]: for k in [-1, 0, 1]: list_k_points.append(i * vec1 + j * vec2 + k * vec3) if list_k_points[-1][0] > max_x: max_x = list_k_points[-1][0] if list_k_points[-1][1] > max_y: max_y = list_k_points[-1][1] if list_k_points[-1][2] > max_z: max_z = list_k_points[-1][0] if list_k_points[-1][0] < min_x: min_x = list_k_points[-1][0] if list_k_points[-1][1] < min_y: min_y = list_k_points[-1][1] if list_k_points[-1][2] < min_z: min_z = list_k_points[-1][0] vertex = _qvertex_target(list_k_points, 13) lines = get_lines_voronoi(vertex) for i in range(len(lines)): vertex1 = lines[i]['start'] vertex2 = lines[i]['end'] ax.plot([vertex1[0], vertex2[0]], [vertex1[1], vertex2[1]], [vertex1[2], vertex2[2]], color='k') for b in self._bs._branches: vertex1 = self._bs.kpoints[b['start_index']].cart_coords vertex2 = self._bs.kpoints[b['end_index']].cart_coords ax.plot([vertex1[0], vertex2[0]], [vertex1[1], vertex2[1]], [vertex1[2], vertex2[2]], color='r', linewidth=3) for k in self._bs.kpoints: if k.label: label = k.label if k.label.startswith("\\") or k.label.find("_") != -1: label = "$" + k.label + "$" off = 0.01 ax.text(k.cart_coords[0] + off, k.cart_coords[1] + off, k.cart_coords[2] + off, label, color='b', size='25') ax.scatter([k.cart_coords[0]], [k.cart_coords[1]], [k.cart_coords[2]], color='b') # make ticklabels and ticklines invisible for a in ax.w_xaxis.get_ticklines() + ax.w_xaxis.get_ticklabels(): a.set_visible(False) for a in ax.w_yaxis.get_ticklines() + ax.w_yaxis.get_ticklabels(): a.set_visible(False) for a in ax.w_zaxis.get_ticklines() + ax.w_zaxis.get_ticklabels(): a.set_visible(False) ax.grid(False) plt.show() ax.axis("off") class BSPlotterProjected(BSPlotter): """ Class to plot or get data to facilitate the plot of band structure objects projected along orbitals, elements or sites. Args: bs: A BandStructureSymmLine object with projections. """ def __init__(self, bs): if len(bs._projections) == 0: raise ValueError("try to plot projections" " on a band structure without any") super(BSPlotterProjected, self).__init__(bs) def _get_projections_by_branches(self, dictio): proj = self._bs.get_projections_on_elts_and_orbitals(dictio) proj_br = [] print(len(proj[Spin.up])) print(len(proj[Spin.up][0])) for c in proj[Spin.up][0]: print(c) for b in self._bs._branches: print(b) if self._bs.is_spin_polarized: proj_br.append( {str(Spin.up): [[] for l in range(self._nb_bands)], str(Spin.down): [[] for l in range(self._nb_bands)]}) else: proj_br.append( {str(Spin.up): [[] for l in range(self._nb_bands)]}) print((len(proj_br[-1][str(Spin.up)]), self._nb_bands)) for i in range(self._nb_bands): for j in range(b['start_index'], b['end_index'] + 1): proj_br[-1][str(Spin.up)][i].append( {e: {o: proj[Spin.up][i][j][e][o] for o in proj[Spin.up][i][j][e]} for e in proj[Spin.up][i][j]}) if self._bs.is_spin_polarized: for b in self._bs._branches: for i in range(self._nb_bands): for j in range(b['start_index'], b['end_index'] + 1): proj_br[-1][str(Spin.down)][i].append( {e: {o: proj[Spin.down][i][j][e][o] for o in proj[Spin.down][i][j][e]} for e in proj[Spin.down][i][j]}) return proj_br def get_projected_plots_dots(self, dictio, zero_to_efermi=True, ylim=None, vbm_cbm_marker=False): """ Method returning a plot composed of subplots along different elements and orbitals. Args: dictio: The element and orbitals you want a projection on. The format is {Element:[Orbitals]} for instance {'Cu':['d','s'],'O':['p']} will give projections for Cu on d and s orbitals and on oxygen p. Returns: a pylab object with different subfigures for each projection The blue and red colors are for spin up and spin down. The bigger the red or blue dot in the band structure the higher character for the corresponding element and orbital. """ from pymatgen.util.plotting_utils import get_publication_quality_plot band_linewidth = 1.0 fig_number = sum([len(v) for v in dictio.values()]) proj = self._get_projections_by_branches(dictio) data = self.bs_plot_data(zero_to_efermi) plt = get_publication_quality_plot(12, 8) e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 count = 1 for el in dictio: for o in dictio[el]: plt.subplot(100 * math.ceil(fig_number / 2) + 20 + count) self._maketicks(plt) for b in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][b], [data['energy'][b][str(Spin.up)][i][j] for j in range(len(data['distances'][b]))], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(data['distances'][b], [data['energy'][b][str(Spin.down)][i][j] for j in range(len(data['distances'][b]))], 'r--', linewidth=band_linewidth) for j in range( len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.down)][i][ j], 'ro', markersize= proj[b][str(Spin.down)][i][j][str(el)][ o] * 15.0) for j in range(len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.up)][i][j], 'bo', markersize= proj[b][str(Spin.up)][i][j][str(el)][ o] * 15.0) if ylim is None: if self._bs.is_metal(): if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs._efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) plt.title(str(el) + " " + str(o)) count += 1 return plt def get_elt_projected_plots(self, zero_to_efermi=True, ylim=None, vbm_cbm_marker=False): """ Method returning a plot composed of subplots along different elements Returns: a pylab object with different subfigures for each projection The blue and red colors are for spin up and spin down The bigger the red or blue dot in the band structure the higher character for the corresponding element and orbital """ band_linewidth = 1.0 proj = self._get_projections_by_branches({e.symbol: ['s', 'p', 'd'] for e in self._bs._structure.composition.elements}) data = self.bs_plot_data(zero_to_efermi) from pymatgen.util.plotting_utils import get_publication_quality_plot plt = get_publication_quality_plot(12, 8) e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 count = 1 for el in self._bs._structure.composition.elements: plt.subplot(220 + count) self._maketicks(plt) for b in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][b], [data['energy'][b][str(Spin.up)][i][j] for j in range(len(data['distances'][b]))], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(data['distances'][b], [data['energy'][b][str(Spin.down)][i][j] for j in range(len(data['distances'][b]))], 'r--', linewidth=band_linewidth) for j in range(len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.down)][i][j], 'ro', markersize=sum([proj[b][str(Spin.down)][i][ j][str(el)][o] for o in proj[b] [str(Spin.down)][i][j][ str(el)]]) * 15.0) for j in range(len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.up)][i][j], 'bo', markersize=sum( [proj[b][str(Spin.up)][i][j][str(el)][o] for o in proj[b] [str(Spin.up)][i][j][str(el)]]) * 15.0) if ylim is None: if self._bs.is_metal(): if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs._efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) plt.title(str(el)) count += 1 return plt def get_elt_projected_plots_color(self, zero_to_efermi=True, elt_ordered=None): """ returns a pylab plot object with one plot where the band structure line color depends on the character of the band (along different elements). Each element is associated with red, green or blue and the corresponding rgb color depending on the character of the band is used. The method can only deal with binary and ternary compounds spin up and spin down are differientiated by a '-' and a '--' line Args: elt_ordered: A list of Element ordered. The first one is red, second green, last blue Returns: a pylab object """ band_linewidth = 3.0 if len(self._bs._structure.composition.elements) > 3: raise ValueError if elt_ordered is None: elt_ordered = self._bs._structure.composition.elements proj = self._get_projections_by_branches( {e.symbol: ['s', 'p', 'd'] for e in self._bs._structure.composition.elements}) data = self.bs_plot_data(zero_to_efermi) from pymatgen.util.plotting_utils import get_publication_quality_plot plt = get_publication_quality_plot(12, 8) spins = [Spin.up] if self._bs.is_spin_polarized: spins = [Spin.up, Spin.down] self._maketicks(plt) for s in spins: for b in range(len(data['distances'])): for i in range(self._nb_bands): for j in range(len(data['energy'][b][str(s)][i]) - 1): sum_e = 0.0 for el in elt_ordered: sum_e = sum_e + \ sum([proj[b][str(s)][i][j][str(el)][o] for o in proj[b][str(s)][i][j][str(el)]]) if sum_e == 0.0: color = [0.0] * len(elt_ordered) else: color = [sum([proj[b][str(s)][i][j][str(el)][o] for o in proj[b][str(s)][i][j][str(el)]]) / sum_e for el in elt_ordered] if len(color) == 2: color.append(0.0) color[2] = color[1] color[1] = 0.0 sign = '-' if s == Spin.down: sign = '--' plt.plot([data['distances'][b][j], data['distances'][b][j + 1]], [data['energy'][b][str(s)][i][j], data['energy'][b][str(s)][i][j + 1]], sign, color=color, linewidth=band_linewidth) plt.ylim(data['vbm'][0][1] - 4.0, data['cbm'][0][1] + 2.0) return plt def _qvertex_target(data, index): """ Input data should be in the form of a list of a list of floats. index is the index of the targeted point Returns the vertices of the voronoi construction around this target point. """ from pyhull import qvoronoi output = qvoronoi("p QV" + str(index), data) output.pop(0) output.pop(0) return [[float(i) for i in row.split()] for row in output] def get_lines_voronoi(data): from pyhull import qconvex output = qconvex("o", data) nb_points = int(output[1].split(" ")[0]) list_lines = [] list_points = [] for i in range(2, 2 + nb_points): list_points.append([float(c) for c in output[i].strip().split()]) facets = [] for i in range(2 + nb_points, len(output)): if output[i] != '': tmp = output[i].strip().split(" ") facets.append([int(tmp[j]) for j in range(1, len(tmp))]) for i in range(len(facets)): for line in itertools.combinations(facets[i], 2): for j in range(len(facets)): if i != j and line[0] in facets[j] and line[1] in facets[j]: # check if the two facets i and j are not coplanar vector1 = np.array(list_points[facets[j][0]]) \ - np.array(list_points[facets[j][1]]) vector2 = np.array(list_points[facets[j][0]]) \ - np.array(list_points[facets[j][2]]) n1 = np.cross(vector1, vector2) vector1 = np.array(list_points[facets[i][0]]) \ - np.array(list_points[facets[i][1]]) vector2 = np.array(list_points[facets[i][0]]) \ - np.array(list_points[facets[i][2]]) n2 = np.cross(vector1, vector2) dot = math.fabs(np.dot(n1, n2) / (np.linalg.norm(n1) * np.linalg.norm(n2))) if 1.05 > dot > 0.95: continue list_lines.append({'start': list_points[line[0]], 'end': list_points[line[1]]}) break return list_lines
from __future__ import unicode_literals import difflib import os import textwrap import six from six.moves import input from rbtools.commands import Command, CommandError from rbtools.utils.console import confirm, confirm_select from rbtools.utils.filesystem import CONFIG_FILE from rbtools.utils.repository import get_repository_resource class SetupRepo(Command): """Configure a repository to point to a Review Board server. Interactively creates the configuration file .reviewboardrc in the current working directory. The user is prompted for the Review Board server url if it's not supplied as an option. Upon a successful server connection, an attempt is made to match the local repository to a repository on the Review Board server. If no match is found or if the user declines the match, the user is prompted to choose from other repositories on the Review Board server. If the client supports it, it attempts to guess the branch name on the server. """ name = 'setup-repo' author = 'The Review Board Project' description = ('Configure an existing repository to point to a Review ' 'Board server by generating the configuration file %s' % CONFIG_FILE) args = '' option_list = [ Command.server_options, Command.perforce_options, Command.tfs_options, ] def prompt_rb_repository(self, local_tool_name, server_tool_names, repository_paths, api_root): """Interactively prompt to select a matching repository. The user is prompted to choose a matching repository found on the Review Board server. Args: local_tool_name (unicode): The local name of the detected tool. server_tool_names (unicode): A comma-separated list of potentially matching SCMTool names in the Review Board server. repository_paths (list or unicode, optional): A list of potential paths to match for the repository. api_root (rbtools.api.resource.RootResource): The root resource for the Review Board server. Returns: rbtools.api.resource.ItemResource: The selected repository resource. """ # Go through each matching repo and prompt for a selection. If a # selection is made, immediately return the selected repo. repo_paths = {} repositories = api_root.get_repositories(tool=server_tool_names) for repository in repositories.all_items: repo_paths[repository['path']] = repository if 'mirror_path' in repository: repo_paths[repository['mirror_path']] = repository closest_paths = difflib.get_close_matches(repository_paths, six.iterkeys(repo_paths), n=4, cutoff=0.4) if closest_paths: self.stdout.new_line() self.stdout.write( '%(num)s matching %(repo_type)s repositories found:' % { 'num': len(closest_paths), 'repo_type': local_tool_name, }) self._display_rb_repositories(closest_paths, repo_paths) repo_chosen = confirm_select('Select a %s repository to use' % local_tool_name, len(closest_paths)) if repo_chosen: repo_chosen = int(repo_chosen) - 1 current_repo_index = closest_paths[repo_chosen] current_repo = repo_paths[current_repo_index] self.stdout.new_line() self.stdout.write('Selecting "%s" (%s)...' % (current_repo['name'], current_repo['path'])) self.stdout.new_line() return current_repo return None def _get_output(self, config): """Returns a string output based on the the provided config.""" settings = [] for setting, value in config: settings.append('%s = "%s"' % (setting, value)) settings.append('') return '\n'.join(settings) def generate_config_file(self, file_path, config): """Generates the config file in the current working directory.""" try: with open(file_path, 'w') as outfile: output = self._get_output(config) outfile.write(output) except IOError as e: raise CommandError('I/O error generating config file (%s): %s' % (e.errno, e.strerror)) self.stdout.write('%s creation successful! Config written to %s' % (CONFIG_FILE, file_path)) def main(self, *args): server = self.options.server api_client = None api_root = None self.stdout.new_line() self.stdout.write(textwrap.fill( 'This command is intended to help users create a %s file in ' 'the current directory to connect a repository and Review ' 'Board server.') % CONFIG_FILE) self.stdout.new_line() self.stdout.write(textwrap.fill( 'Repositories must currently exist on your server (either ' 'hosted internally or via RBCommons) to successfully ' 'generate this file.')) self.stdout.write(textwrap.fill( 'Repositories can be added using the Admin Dashboard in ' 'Review Board or under your team administration settings in ' 'RBCommons.')) self.stdout.new_line() self.stdout.write(textwrap.fill( 'Press CTRL + C anytime during this command to cancel ' 'generating your config file.')) self.stdout.new_line() while True: if server: try: # Validate the inputted server. api_client, api_root = self.get_api(server) break except CommandError as e: self.stdout.new_line() self.stdout.write('%s' % e) self.stdout.write('Please try again.') self.stdout.new_line() server = input('Enter the Review Board server URL: ') repository_info, tool = self.initialize_scm_tool() self.capabilities = self.get_capabilities(api_root) tool.capabilities = self.capabilities # Go through standard detection mechanism first. If we find a match # this way, we'll set the local repository_info path to be the same as # the remote, which will improve matching. repository, info = get_repository_resource( api_root, tool=tool, repository_paths=repository_info.path) if repository: repository_info.update_from_remote(repository, info) # While a repository is not chosen, keep the repository selection # prompt displayed until the prompt is cancelled. while True: self.stdout.new_line() self.stdout.write('Current server: %s' % server) selected_repo = self.prompt_rb_repository( local_tool_name=tool.name, server_tool_names=tool.server_tool_names, repository_paths=repository_info.path, api_root=api_root) if not selected_repo: self.stdout.new_line() self.stdout.write('No %s repository found for the Review ' 'Board server %s' % (tool.name, server)) self.stdout.new_line() self.stdout.write('Cancelling %s creation...' % CONFIG_FILE) self.stdout.new_line() self.stdout.write(textwrap.fill( 'Please make sure your repositories ' 'currently exist on your server. ' 'Repositories can be configured using the ' 'Review Board Admin Dashboard or under your ' 'team administration settings in RBCommons. ' 'For more information, see `rbt help ' 'setup-repo` or the official docs at ' 'https://www.reviewboard.org/docs/.')) return config = [ ('REVIEWBOARD_URL', server), ('REPOSITORY', selected_repo['name']), ('REPOSITORY_TYPE', tool.entrypoint_name), ] try: branch = tool.get_current_branch() config.append(('BRANCH', branch)) config.append(('LAND_DEST_BRANCH', branch)) except NotImplementedError: pass outfile_path = os.path.join(os.getcwd(), CONFIG_FILE) output = self._get_output(config) if not os.path.exists(outfile_path): question = ('Create "%s" with the following?\n\n%s\n' % (outfile_path, output)) else: question = ( '"%s" exists. Overwrite with the following?\n\n%s\n' % (outfile_path, output) ) if confirm(question): break self.generate_config_file(outfile_path, config) def _display_rb_repositories(self, closest_paths, repo_paths): """Display all repositories found for a Review Board server. Args: closest_paths (list of unicode) A list of best-matching repositories from a valid Review Board server. repo_paths (dict) A dictionary containing repository metadata. """ for i, repo_url in enumerate(closest_paths): repo = repo_paths[repo_url] self.stdout.write( '%(num)d) "%(repo_name)s" (%(repo_url)s)' % { 'num': i + 1, 'repo_name': repo['name'], 'repo_url': repo_url, })
# -*- coding: utf-8 -*- import datetime import mock import time from django.test import override_settings from django.utils.timezone import now as timezone_now from zerver.lib.actions import create_stream_if_needed, do_create_user from zerver.lib.digest import gather_new_streams, handle_digest_email, enqueue_emails, \ gather_new_users from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import queries_captured from zerver.models import get_client, get_realm, flush_per_request_caches, \ Realm, Message, UserActivity, UserProfile class TestDigestEmailMessages(ZulipTestCase): @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_receive_digest_email_messages(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: # build dummy messages for missed messages email reply # have Hamlet send Othello a PM. Othello will reply via email # Hamlet will receive the message. hamlet = self.example_user('hamlet') self.login(hamlet.email) result = self.client_post("/json/messages", {"type": "private", "content": "test_receive_missed_message_email_messages", "client": "test suite", "to": self.example_email('othello')}) self.assert_json_success(result) user_profile = self.example_user('othello') cutoff = time.mktime(datetime.datetime(year=2016, month=1, day=1).timetuple()) handle_digest_email(user_profile.id, cutoff) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_ids'], [user_profile.id]) html = kwargs['context']['unread_pms'][0]['header']['html'] expected_url = "'http://zulip.testserver/#narrow/pm-with/{id}-hamlet'".format(id=hamlet.id) self.assertIn(expected_url, html) @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_huddle_urls(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: email = self.example_email('hamlet') self.login(email) huddle_emails = [ self.example_email('cordelia'), self.example_email('othello'), ] payload = dict( type='private', content='huddle message', client='test suite', to=','.join(huddle_emails), ) result = self.client_post("/json/messages", payload) self.assert_json_success(result) user_profile = self.example_user('othello') cutoff = time.mktime(datetime.datetime(year=2016, month=1, day=1).timetuple()) handle_digest_email(user_profile.id, cutoff) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_ids'], [user_profile.id]) html = kwargs['context']['unread_pms'][0]['header']['html'] other_user_ids = sorted([ self.example_user('cordelia').id, self.example_user('hamlet').id, ]) slug = ','.join(str(user_id) for user_id in other_user_ids) + '-group' expected_url = "'http://zulip.testserver/#narrow/pm-with/" + slug + "'" self.assertIn(expected_url, html) @mock.patch('zerver.lib.digest.enough_traffic') @mock.patch('zerver.lib.digest.send_future_email') def test_multiple_stream_senders(self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: client = 'website' # this makes `sent_by_human` return True othello = self.example_user('othello') self.subscribe(othello, 'Verona') one_day_ago = timezone_now() - datetime.timedelta(days=1) Message.objects.all().update(pub_date=one_day_ago) one_sec_ago = timezone_now() - datetime.timedelta(seconds=1) cutoff = time.mktime(one_sec_ago.timetuple()) senders = ['hamlet', 'cordelia', 'iago', 'prospero', 'ZOE'] for sender_name in senders: email = self.example_email(sender_name) self.login(email) content = 'some content for ' + email payload = dict( type='stream', client=client, to='Verona', topic='lunch', content=content, ) result = self.client_post("/json/messages", payload) self.assert_json_success(result) flush_per_request_caches() with queries_captured() as queries: handle_digest_email(othello.id, cutoff) self.assertTrue(29 <= len(queries) <= 30) self.assertEqual(mock_send_future_email.call_count, 1) kwargs = mock_send_future_email.call_args[1] self.assertEqual(kwargs['to_user_ids'], [othello.id]) hot_convo = kwargs['context']['hot_conversations'][0] expected_participants = { self.example_user(sender).full_name for sender in senders } self.assertEqual(set(hot_convo['participants']), expected_participants) self.assertEqual(hot_convo['count'], 5 - 2) # 5 messages, but 2 shown teaser_messages = hot_convo['first_few_messages'][0]['senders'] self.assertIn('some content', teaser_messages[0]['content'][0]['plain']) self.assertIn(teaser_messages[0]['sender'], expected_participants) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_inactive_users_queued_for_digest(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # Test Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) all_user_profiles = UserProfile.objects.filter( is_active=True, is_bot=False, enable_digest_emails=True) # Check that all users without an a UserActivity entry are considered # inactive users and get enqueued. enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, all_user_profiles.count()) mock_queue_digest_recipient.reset_mock() for realm in Realm.objects.filter(deactivated=False, digest_emails_enabled=True): user_profiles = all_user_profiles.filter(realm=realm) for user_profile in user_profiles: UserActivity.objects.create( last_visit=cutoff - datetime.timedelta(days=1), user_profile=user_profile, count=0, client=get_client('test_client')) # Check that inactive users are enqueued enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, all_user_profiles.count()) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') def test_disabled(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) enqueue_emails(cutoff) mock_queue_digest_recipient.assert_not_called() @mock.patch('zerver.lib.digest.enough_traffic', return_value=True) @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_active_users_not_enqueued(self, mock_django_timezone: mock.MagicMock, mock_enough_traffic: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) realms = Realm.objects.filter(deactivated=False, digest_emails_enabled=True) for realm in realms: user_profiles = UserProfile.objects.filter(realm=realm) for counter, user_profile in enumerate(user_profiles, 1): UserActivity.objects.create( last_visit=cutoff + datetime.timedelta(days=1), user_profile=user_profile, count=0, client=get_client('test_client')) # Check that an active user is not enqueued with mock.patch('zerver.lib.digest.queue_digest_recipient') as mock_queue_digest_recipient: enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, 0) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_only_enqueue_on_valid_day(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: # Not a Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=6) # Check that digests are not sent on days other than Tuesday. cutoff = timezone_now() enqueue_emails(cutoff) self.assertEqual(mock_queue_digest_recipient.call_count, 0) @mock.patch('zerver.lib.digest.queue_digest_recipient') @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_no_email_digest_for_bots(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) bot = do_create_user('some_bot@example.com', 'password', get_realm('zulip'), 'some_bot', '', bot_type=UserProfile.DEFAULT_BOT) UserActivity.objects.create( last_visit=cutoff - datetime.timedelta(days=1), user_profile=bot, count=0, client=get_client('test_client')) # Check that bots are not sent emails enqueue_emails(cutoff) for arg in mock_queue_digest_recipient.call_args_list: user = arg[0][0] self.assertNotEqual(user.id, bot.id) @mock.patch('zerver.lib.digest.timezone_now') @override_settings(SEND_DIGEST_EMAILS=True) def test_new_stream_link(self, mock_django_timezone: mock.MagicMock) -> None: cutoff = datetime.datetime(year=2017, month=11, day=1) mock_django_timezone.return_value = datetime.datetime(year=2017, month=11, day=5) cordelia = self.example_user('cordelia') stream_id = create_stream_if_needed(cordelia.realm, 'New stream')[0].id new_stream = gather_new_streams(cordelia, cutoff)[1] expected_html = "<a href='http://zulip.testserver/#narrow/stream/{stream_id}-New-stream'>New stream</a>".format(stream_id=stream_id) self.assertIn(expected_html, new_stream['html']) @mock.patch('zerver.lib.digest.timezone_now') def test_gather_new_users(self, mock_django_timezone: mock.MagicMock) -> None: cutoff = timezone_now() do_create_user('abc@example.com', password='abc', realm=get_realm('zulip'), full_name='abc', short_name='abc') # Normal users get info about new users user = self.example_user('aaron') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 1) # Definitely, admin users get info about new users user = self.example_user('iago') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 1) # Guest users don't get info about new users user = self.example_user('polonius') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 0) # Zephyr users also don't get info about new users in their realm user = self.mit_user('starnine') do_create_user('abc@mit.edu', password='abc', realm=user.realm, full_name='abc', short_name='abc') gathered_no_of_user, _ = gather_new_users(user, cutoff) self.assertEqual(gathered_no_of_user, 0)
# File: Scanner.py # Author: Marvin Smith # Date: 6/13/2015 # # Purpose: Manage and manipulate LLNMS Scanner entries. # __author__ = 'Marvin Smith' # System Libraries import subprocess, logging, os, xml.etree.ElementTree as ET import multiprocessing, itertools, sys from multiprocessing import Pool def Run_Scanner(args): scanner = args[0] address = args[1] args = args[2] return scanner.Run_Scan( address, args) # -------------------------------------------- # # - Scanner Command-Line Argument - # # -------------------------------------------- # class ScannerArgument(object): # ID id = None # Value value = None # Type type = None # Type value type_value = None # Default value default = None # ------------------------- # # - Constructor - # # ------------------------- # def __init__(self, id = None, value = None): # Set internals self.type = None self.type_value = None self.default = None # Set the ID if id is not None: self.id = id # Set the value if value is not None: self.value = value # -------------------------------------- # # - Format to Debugging String - # # -------------------------------------- # def To_Debug_String(self, offset=0): gap = ' ' * offset output = gap + str(self.__class__) + '\n' output += gap + ' ID : ' + self.id + '\n' output += gap + ' Value : ' + str(self.value) + '\n' return output # ---------------------------- # # - Scanner Class - # # ---------------------------- # class Scanner(object): # Scanner ID id = None # Name name = None # Description description = None # Command Name command = None # Base Path base_path = None # Argument List arguments = [] # Filename filename = None # LLNMS HOME llnms_home = None # --------------------------- # # - Constructor - # # --------------------------- # def __init__( self, id = None, name = None, description = None, filename=None, LLNMS_HOME = None): # Set the ID self.id = id # Set the name self.name = name # Set the description self.description = description # Set LLNMS_HOME if LLNMS_HOME is not None: self.llnms_home = LLNMS_HOME else: self.llnms_home = os.environ['LLNMS_HOME'] # Set the filename if filename is not None: self.Load_From_File(filename) # ---------------------------------- # # - Load the Scanner File - # # ---------------------------------- # def Load_From_File(self, filename): # Set the filename self.filename = filename # Make sure the file exists if os.path.exists(self.filename) is False: return # Parse the file root = ET.parse(self.filename) # Get the ID idnode = root.find('id') if idnode is not None: self.id = idnode.text # Get the name namenode = root.find('name') if namenode is not None: self.name = namenode.text # Get the description dnode = root.find('description') if dnode is not None: self.description = dnode.text # Get the config node confignode = root.find('configuration') # Get the linux node lnode = confignode.find('linux') if lnode is not None: # Get the command self.command = lnode.find('command').text # Get the base path self.base_path = lnode.find('base-path').text # Get the argnode for argnode in lnode.findall('argument'): # Create the temp node temp_arg = ScannerArgument() # Get the id temp_arg.id = argnode.get('id') temp_arg.name = argnode.get('name') temp_arg.type = argnode.get('type') temp_arg.type_value = argnode.get('value') temp_arg.default = argnode.get('default') # Add the argument self.arguments.append(temp_arg) # ----------------------------------- # # - Print to Debug String - # # ----------------------------------- # def To_Debug_String(self): # Print output output = str(self.__class__) + '\n' output += ' ID : ' + self.id + '\n' output += ' Name : ' + self.name + '\n' output += ' Description : ' + self.description + '\n' output += ' Command : ' + self.command + '\n' for argument in self.arguments: output += ' Argument : ' + argument.To_Debug_String(offset=4) + '\n' return output # -------------------------------- # # - Run the scan - # # -------------------------------- # def Run_Scan(self, endpoint, arg_list ): # Create Command To Run command = self.llnms_home + '/' + self.base_path + '/' + self.command # Append the arguments for x in xrange(0, len(arg_list)): # Add the argument name command += ' --' + arg_list[x][0] # Check the type if str(self.arguments[x].type) == 'ASSET_ELEMENT': if arg_list[x][0] == 'ip4-address': command += ' ' + endpoint else: command += ' ' + arg_list[x][1] # Run the process proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() # Get the output if out.strip() == "PASSED": return True else: return False # ------------------------------------------------------ # # - Run the scan on a range of elements - # # ------------------------------------------------------ # def Run_Scan_Range(self, endpoint_list, arg_list, num_threads=1 ): # Run the multiprocessing module pool = Pool( processes=num_threads ) # Return the scan result output = pool.map( Run_Scanner, itertools.izip(itertools.repeat(self), endpoint_list, itertools.repeat(arg_list))) return output # ----------------------------------- # # - Load the list of scanners - # # ----------------------------------- # def llnms_load_scanners( llnms_home ): output = [] # Build the command cmd = 'llnms-list-scanners -l -f' # Get the list of scanners p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) # Get the data out, err = p.communicate() # Split the list logging.info('Command: ' + cmd + '\n stdout: ' + out.strip() + '\n stderr: ' + err.strip()) lst = filter( ( lambda a : len(str(a).strip()) > 0 ), str(out).split("\n")) for ls in lst: # Create the temp scanner output.append(Scanner(filename=ls)) # Return the output return output # ---------------------------------------- # # - Find a particular scanner - # # ---------------------------------------- # def find_scanner( scanner_id, llnms_home ): # Get the list of networks scanner_list = llnms_load_scanners(llnms_home) # Iterate over networks for scanner_item in scanner_list: # Compare the scanner id if scanner_item.id == scanner_id: return scanner_item # Otherwise, return none return None
# Copyright 2018 Guanshuo Wang. 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. # ============================================================================== # Reference: # @inproceedings{shufflenetv2, # title={ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design}, # author={Ningning Ma and Xiangyu Zhang and Hai-Tao Zheng and Jian Sun}, # booktitle={ECCV}, # year={2018} # } from collections import OrderedDict import tensorflow as tf from tensorflow.contrib import layers from tensorflow.contrib.framework import arg_scope from model_parallel import * import net_base class ShuffleNet_v2_small(net_base.Network): def __init__(self, alpha=1.0, se=False, residual=False, weight_decay=0.0005, data_format='NCHW', name='ShuffleNet_v2_small'): super(ShuffleNet_v2_small, self).__init__(weight_decay, data_format, name) if alpha == 0.5: self.num_outputs = [24, 48, 96, 1024] self.name += '_x0_5' elif alpha == 1.0: self.num_outputs = [58, 116, 232, 1024] elif alpha == 1.5: self.num_outputs = [88, 176, 352, 1024] self.name += '_x1_5' elif alpha == 2.0: self.num_outputs = [122, 244, 488, 2048] self.name += '_x2' self.se = se if se: self.name += '_se' self.residual = residual if residual: self.name += '_res' def _channel_split(self, x): num_channels = x.get_shape().as_list()[self.channel_axis] split_size = int(0.5*num_channels) shortcut, x = tf.split(x, [split_size, num_channels-split_size], axis=self.channel_axis) return shortcut, x def _channel_shuffle(self, x): input_height, input_width = x.get_shape().as_list()[2:4] if self.data_format=='NCHW' else x.get_shape().as_list()[1:3] num_channels = x.get_shape().as_list()[self.channel_axis] if self.data_format == 'NCHW': x = tf.reshape(x, [-1, 2, num_channels/2, input_height, input_width]) x = tf.transpose(x, [0, 2, 1, 3, 4]) x = tf.reshape(x, [-1, num_channels, input_height, input_width]) else: x = tf.reshape(x, [-1, input_height, input_width, num_channels/2, 2]) x = tf.transpose(x, [0, 1, 2, 4, 3]) x = tf.reshape(x, [-1, input_height, input_width, num_channels]) return x def _squeeze_excitation(self, x): num_channels = x.get_shape().as_list()[self.channel_axis] w = tf.reduce_mean(x, axis=self.spatial_axis, keepdims=True) w = layers.conv2d(w, num_channels/2, kernel_size=1, normalizer_fn=None) w = layers.conv2d(w, num_channels, kernel_size=1, normalizer_fn=None, activation_fn=tf.nn.sigmoid) x = x*w return x def separable_resBlock(self, x, num_outputs, stride=1, activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm, scope=None): residual_flag = self.residual and (stride == 1 and num_outputs == x.get_shape().as_list()[self.channel_axis]) with tf.variable_scope(scope, 'resBlock'): # channel_split shortcut, x = self._channel_split(x) if stride != 1: shortcut = layers.separable_conv2d(shortcut, num_outputs, kernel_size=3, stride=stride, scope='separable_conv_shortcut_3x3') shortcut = layers.conv2d(shortcut, num_outputs, kernel_size=1, stride=1, scope='conv_shortcut_1x1') if residual_flag: res_shortcut = x x = layers.conv2d(x, num_outputs, kernel_size=1, stride=1, scope='conv1_1x1',) x = layers.separable_conv2d(x, num_outputs, kernel_size=3, stride=stride, scope='separable_conv2_3x3') x = layers.conv2d(x, num_outputs, kernel_size=1, stride=1, scope='conv3_1x1') if self.se: x = self._squeeze_excitation(x) if residual_flag: x += res_shortcut # concat x = tf.concat([shortcut, x], axis=self.channel_axis) x = self._channel_shuffle(x) return x def backbone(self, inputs, is_training=False, reuse=None): end_points = OrderedDict() with tf.variable_scope(self.name, values=[inputs], reuse=reuse): with arg_scope([layers.batch_norm], scale=True, fused=True, data_format=self.data_format, is_training=is_training): with arg_scope([layers.conv2d], activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm, biases_initializer=None, weights_regularizer=layers.l2_regularizer(self.weight_decay), data_format=self.data_format): with arg_scope([layers.separable_conv2d], depth_multiplier=1, activation_fn=None, normalizer_fn=layers.batch_norm, biases_initializer=None, weights_regularizer=layers.l2_regularizer(self.weight_decay), data_format=self.data_format): if self.data_format == 'NCHW': inputs = tf.transpose(inputs, [0, 3, 1, 2]) with tf.variable_scope('conv1'): net = layers.conv2d(inputs, num_outputs=24, kernel_size=3, stride=2, scope='conv_3x3') end_points['conv1/conv_3x3'] = net net = layers.max_pool2d(net, kernel_size=3, stride=2, padding='SAME', data_format=self.data_format, scope='maxpool_3x3_2') end_points['conv1/maxpool_3x3_2'] = net with tf.variable_scope('conv2'): for idx in xrange(4): net = self.separable_resBlock(net, num_outputs=self.num_outputs[0], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv2/resBlock_%d'%idx] = net with tf.variable_scope('conv3'): for idx in xrange(8): net = self.separable_resBlock(net, num_outputs=self.num_outputs[1], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv3/resBlock_%d'%idx] = net with tf.variable_scope('conv4'): for idx in xrange(4): net = self.separable_resBlock(net, num_outputs=self.num_outputs[2], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv4/resBlock_%d'%idx] = net with tf.variable_scope('conv5'): net = layers.conv2d(net, num_outputs=self.num_outputs[3], kernel_size=1, stride=1, scope='conv_1x1') end_points['conv5/conv_1x1'] = net net = tf.reduce_mean(net, self.spatial_axis) return net, end_points def forward(self, images, num_classes=None, is_training=True): # Forward features, end_points = self.backbone(images, is_training=is_training) # Logits if is_training: assert num_classes is not None, 'num_classes must be given when is_training=True' with tf.variable_scope('classifier'): features_drop = layers.dropout(features, keep_prob=0.5, is_training=is_training) logit = layers.fully_connected(features_drop, num_classes, activation_fn=None, weights_initializer=tf.random_normal_initializer(stddev=0.001), weights_regularizer=layers.l2_regularizer(self.weight_decay), biases_initializer=None, scope='fc_classifier') logits = {} logits['logits'] = logit logits['features'] = features return logits else: # for _, var in end_points.items(): # print(var) return features def loss_function(self, scope, labels, **logits): losses = [] losses_name = [] others = {} cross_entropy_loss = tf.losses.sparse_softmax_cross_entropy(logits=logits['logits'], labels=labels, scope='cross_entropy') losses.append(cross_entropy_loss) losses_name.append('cross_entropy') # Regularization losses, losses_name = self._regularize(scope, losses, losses_name) return losses, losses_name, others def param_list(self, is_training, trainable, scope=None): var_fn = tf.trainable_variables if trainable else tf.global_variables scope_name = scope.name+'/' if scope is not None else '' if is_training: return [var_fn(scope_name+self.name), var_fn(scope_name+'classifier')] else: return [var_fn(scope_name+self.name)] def pretrained_param(self, scope=None): pretrained_param = [] for param in self.param_list(is_training=False, trainable=False, scope=scope): for v in param: if self.name in v.name: pretrained_param.append(v) return pretrained_param class ShuffleNet_v2_middle(ShuffleNet_v2_small): def __init__(self, se=False, residual=False, weight_decay=0.0005, data_format='NCHW', name='ShuffleNet_v2_middle'): super(ShuffleNet_v2_middle, self).__init__(1.0, se, residual, weight_decay, data_format, name) self.num_outputs = [244, 488, 976, 1952, 2048] def backbone(self, inputs, is_training=False, reuse=None): end_points = OrderedDict() with tf.variable_scope(self.name, reuse=reuse): with arg_scope([layers.batch_norm], scale=True, fused=True, data_format=self.data_format, is_training=is_training): with arg_scope([layers.conv2d], activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm, biases_initializer=None, weights_regularizer=layers.l2_regularizer(self.weight_decay), data_format=self.data_format): with arg_scope([layers.separable_conv2d], depth_multiplier=1, activation_fn=None, normalizer_fn=layers.batch_norm, biases_initializer=None, weights_regularizer=layers.l2_regularizer(self.weight_decay), data_format=self.data_format): if self.data_format == 'NCHW': inputs = tf.transpose(inputs, [0, 3, 1, 2]) with tf.variable_scope('conv1'): net = layers.conv2d(inputs, num_outputs=64, kernel_size=3, stride=2, scope='conv_3x3') end_points['conv1/conv_3x3'] = net net = layers.max_pool2d(net, kernel_size=3, stride=2, padding='SAME', data_format=self.data_format, scope='maxpool_3x3_2') end_points['conv1/maxpool_3x3_2'] = net with tf.variable_scope('conv2'): for idx in xrange(3): net = self.separable_resBlock(net, num_outputs=self.num_outputs[0], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv2/resBlock_%d'%idx] = net with tf.variable_scope('conv3'): for idx in xrange(4): net = self.separable_resBlock(net, num_outputs=self.num_outputs[1], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv3/resBlock_%d'%idx] = net with tf.variable_scope('conv4'): for idx in xrange(6): net = self.separable_resBlock(net, num_outputs=self.num_outputs[2], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv4/resBlock_%d'%idx] = net with tf.variable_scope('conv5'): for idx in xrange(3): net = self.separable_resBlock(net, num_outputs=self.num_outputs[3], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv4/resBlock_%d'%idx] = net with tf.variable_scope('conv5'): net = layers.conv2d(net, num_outputs=self.num_outputs[4], kernel_size=1, stride=1, scope='conv_1x1') end_points['conv6/conv_1x1'] = net net = tf.reduce_mean(net, self.spatial_axis) return net, end_points class ShuffleNet_v2_large(ShuffleNet_v2_small): def __init__(self, weight_decay=0.0005, data_format='NCHW', name='ShuffleNet_v2_large'): super(ShuffleNet_v2_large, self).__init__(1.0, True, True, weight_decay, data_format, name) self.num_outputs = [340, 680, 1360, 2720, 2048] def backbone(self, inputs, is_training=False, reuse=None): end_points = OrderedDict() with tf.variable_scope(self.name, reuse=reuse): with arg_scope([layers.batch_norm], scale=True, fused=True, data_format=self.data_format, is_training=is_training): with arg_scope([layers.conv2d], activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm, biases_initializer=None, weights_regularizer=layers.l2_regularizer(self.weight_decay), data_format=self.data_format): with arg_scope([layers.separable_conv2d], depth_multiplier=1, activation_fn=None, normalizer_fn=layers.batch_norm, biases_initializer=None, weights_regularizer=layers.l2_regularizer(self.weight_decay), data_format=self.data_format): if self.data_format == 'NCHW': inputs = tf.transpose(inputs, [0, 3, 1, 2]) with tf.variable_scope('conv1'): net = layers.conv2d(inputs, num_outputs=64, kernel_size=3, stride=2, scope='conv1_3x3') end_points['conv1/conv1_3x3'] = net net = layers.conv2d(inputs, num_outputs=64, kernel_size=3, scope='conv2_3x3') end_points['conv1/conv2_3x3'] = net net = layers.conv2d(inputs, num_outputs=128, kernel_size=3, scope='conv3_3x3') end_points['conv1/conv3_3x3'] = net net = layers.max_pool2d(net, kernel_size=3, stride=2, padding='SAME', data_format=self.data_format, scope='maxpool_3x3_2') end_points['conv1/maxpool_3x3_2'] = net with tf.variable_scope('conv2'): for idx in xrange(10): net = self.separable_resBlock(net, num_outputs=self.num_outputs[0], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv2/resBlock_%d'%idx] = net with tf.variable_scope('conv3'): for idx in xrange(10): net = self.separable_resBlock(net, num_outputs=self.num_outputs[1], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv3/resBlock_%d'%idx] = net with tf.variable_scope('conv4'): for idx in xrange(23): net = self.separable_resBlock(net, num_outputs=self.num_outputs[2], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv4/resBlock_%d'%idx] = net with tf.variable_scope('conv5'): for idx in xrange(10): net = self.separable_resBlock(net, num_outputs=self.num_outputs[3], stride=2 if not idx else 1, scope='resBlock_%d'%idx) end_points['conv4/resBlock_%d'%idx] = net with tf.variable_scope('conv5'): net = layers.conv2d(net, num_outputs=self.num_outputs[4], kernel_size=1, stride=1, scope='conv_1x1') end_points['conv6/conv_1x1'] = net net = tf.reduce_mean(net, self.spatial_axis) return net, end_points
from django.db import models from wagtail.core import blocks from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField, StreamField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.blocks import ImageChooserBlock from wagtail.images.models import Image from wagtail.snippets.models import register_snippet from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import ( FieldPanel, MultiFieldPanel, InlinePanel, PageChooserPanel, StreamFieldPanel) from wagtail.search import index from utils.models import LinkFields, RelatedLink, CarouselItem from wagtail.contrib.settings.models import BaseSetting, register_setting @register_setting class SocialMediaSettings(BaseSetting): facebook = models.URLField( help_text='Your Facebook page URL', null=True, blank=True) instagram = models.URLField( max_length=255, help_text='Your Instagram URL', null=True, blank=True) twitter = models.URLField( max_length=255, help_text='Your Twitter URL', null=True, blank=True) youtube = models.URLField( help_text='Your YouTube Channel URL', null=True, blank=True) linkedin = models.URLField( max_length=255, help_text='Your Linkedin URL', null=True, blank=True) github = models.URLField( max_length=255, help_text='Your Github URL', null=True, blank=True) facebook_appid = models.CharField( max_length=255, help_text='Your Facbook AppID', null=True, blank=True) @register_setting class SiteBranding(BaseSetting): logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) site_name = models.CharField(max_length=250, null=True, blank=True) panels = [ ImageChooserPanel('logo'), FieldPanel('site_name'), ] class HomePageContentItem(Orderable, LinkFields): page = ParentalKey('pages.HomePage', related_name='content_items') image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) title = models.CharField(max_length=100) content = RichTextField(null=True, blank=True,) summary = RichTextField(blank=True) slug = models.SlugField() panels = [ FieldPanel('title'), ImageChooserPanel('image'), FieldPanel('summary'), FieldPanel('content'), FieldPanel('slug'), MultiFieldPanel(LinkFields.panels, "Link"), ] class HomePageCarouselItem(Orderable, CarouselItem): page = ParentalKey('pages.HomePage', related_name='carousel_items') class HomePageRelatedLink(Orderable, RelatedLink): page = ParentalKey('pages.HomePage', related_name='related_links') class HomePage(Page): title_text = RichTextField(null=True, blank=True) body = RichTextField(null=True, blank=True) feed_image = models.ForeignKey( Image, help_text="An optional image to represent the page", null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) indexed_fields = ('body', ) class Meta: verbose_name = "Homepage" HomePage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('title_text', classname="full"), FieldPanel('body', classname="full"), InlinePanel('carousel_items', label="Carousel items"), InlinePanel('content_items', label="Content Blocks"), InlinePanel('related_links', label="Related links"), ] HomePage.promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] class StandardIndexPageRelatedLink(Orderable, RelatedLink): page = ParentalKey('pages.StandardIndexPage', related_name='related_links') class StandardIndexPage(Page): TEMPLATE_CHOICES = [ ('pages/standard_index_page.html', 'Default Template'), ('pages/standard_index_page_grid.html', 'Grid Also In This Section'), ] subtitle = models.CharField(max_length=255, blank=True) intro = RichTextField(blank=True) template_string = models.CharField( max_length=255, choices=TEMPLATE_CHOICES, default='pages/standard_index_page.html' ) feed_image = models.ForeignKey( Image, help_text="An optional image to represent the page", null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) indexed_fields = ('intro', ) @property def template(self): return self.template_string StandardIndexPage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('subtitle', classname="full title"), FieldPanel('intro', classname="full"), FieldPanel('template_string'), InlinePanel('related_links', label="Related links"), ] StandardIndexPage.promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] # Standard page class StandardPageCarouselItem(Orderable, CarouselItem): page = ParentalKey('pages.StandardPage', related_name='carousel_items') class StandardPageRelatedLink(Orderable, RelatedLink): page = ParentalKey('pages.StandardPage', related_name='related_links') class StandardPage(Page): TEMPLATE_CHOICES = [ ('pages/standard_page.html', 'Default Template'), ('pages/standard_page_full.html', 'Standard Page Full'), ] subtitle = models.CharField(max_length=255, blank=True) intro = RichTextField(blank=True) body = StreamField([ ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ('html', blocks.RawHTMLBlock()), ]) template_string = models.CharField( max_length=255, choices=TEMPLATE_CHOICES, default='pages/standard_page.html' ) feed_image = models.ForeignKey( Image, null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] @property def template(self): return self.template_string StandardPage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('subtitle', classname="full title"), FieldPanel('intro', classname="full"), StreamFieldPanel('body'), FieldPanel('template_string'), InlinePanel('carousel_items', label="Carousel items"), InlinePanel('related_links', label="Related links"), ] StandardPage.promote_panels = Page.promote_panels + [ ImageChooserPanel('feed_image'), ] class VideoGalleryPageCarouselItem(Orderable, CarouselItem): page = ParentalKey('pages.VideoGalleryPage', related_name='carousel_items') class VideoGalleryPage(Page): intro = RichTextField(blank=True) feed_image = models.ForeignKey( Image, null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), ] VideoGalleryPage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('intro', classname="full"), InlinePanel('carousel_items', label="Carousel items"), ] VideoGalleryPage.promote_panels = Page.promote_panels + [ ImageChooserPanel('feed_image'), ] class TestimonialPage(Page): intro = RichTextField(blank=True) feed_image = models.ForeignKey( Image, null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), ] TestimonialPage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('intro', classname="full"), ] TestimonialPage.promote_panels = Page.promote_panels + [ ImageChooserPanel('feed_image'), ] class ContentBlock(LinkFields): page = models.ForeignKey( Page, related_name='contentblocks', null=True, blank=True, on_delete=models.SET_NULL ) title = models.CharField(max_length=255) body = RichTextField() summary = RichTextField(blank=True) slug = models.SlugField() panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('summary'), FieldPanel('body', classname="full"), FieldPanel('slug'), MultiFieldPanel(LinkFields.panels, "Link"), ] def __str__(self): return u"{0}[{1}]".format(self.title, self.slug) register_snippet(ContentBlock) class Testimonial(LinkFields): page = models.ForeignKey( Page, related_name='testimonials', null=True, blank=True, on_delete=models.SET_NULL ) name = models.CharField(max_length=150) photo = models.ForeignKey( Image, null=True, blank=True, on_delete=models.SET_NULL ) text = RichTextField(blank=True) panels = [ PageChooserPanel('page'), FieldPanel('name'), ImageChooserPanel('photo'), FieldPanel('text'), MultiFieldPanel(LinkFields.panels, "Link"), ] def __str__(self): return self.name register_snippet(Testimonial) class Advert(LinkFields): page = models.ForeignKey( Page, related_name='adverts', null=True, blank=True, on_delete=models.SET_NULL, ) title = models.CharField(max_length=150, null=True) image = models.ForeignKey( Image, null=True, blank=True, on_delete=models.SET_NULL ) button_text = models.CharField(max_length=150, null=True) text = RichTextField(blank=True) panels = [ PageChooserPanel('page'), FieldPanel('title'), ImageChooserPanel('image'), FieldPanel('text'), FieldPanel('button_text'), MultiFieldPanel(LinkFields.panels, "Link"), ] def __str__(self): return self.title register_snippet(Advert) # Faqs Page class FaqsPage(Page): body = StreamField([ ('faq_question', blocks.CharBlock(classname="full title")), ('faq_answer', blocks.RichTextBlock()), ]) FaqsPage.content_panels = [ FieldPanel('title', classname="full title"), StreamFieldPanel('body'), ]
# jsb/eventbase.py # # """ base class of all events. """ ## jsb imports from channelbase import ChannelBase from jsb.utils.lazydict import LazyDict from jsb.utils.generic import splittxt, stripped, waitforqueue from errors import NoSuchUser from jsb.utils.opts import makeeventopts from jsb.utils.trace import whichmodule from jsb.utils.locking import lockdec from jsb.lib.config import Config ## basic imports from xml.sax.saxutils import unescape import copy import logging import Queue import types import socket import threading import time import thread ## defines cpy = copy.deepcopy lock = thread.allocate_lock() locked = lockdec(lock) ## classes class EventBase(LazyDict): """ basic event class. """ def __init__(self, input={}, bot=None): LazyDict.__init__(self) if bot: self.bot = bot self.bottype = "botbase" self.relayed = [] self.copyin(input) def __deepcopy__(self, a): """ deepcopy an event. """ logging.debug("eventbase - cpy - %s" % type(self)) e = EventBase(self) return e def ready(self, finish=True): """ signal the event as ready - push None to all queues. """ logging.debug("%s - %s - ready called from %s" % (self.cbtype, self.txt, whichmodule())) time.sleep(0.01) if self.closequeue and self.queues: for q in self.queues: q.put_nowait(None) if not self.dontclose: self.outqueue.put_nowait(None) self.resqueue.put_nowait(None) self.inqueue.put_nowait(None) if finish: self.finished.set() def prepare(self, bot=None): """ prepare the event for dispatch. """ if bot: self.bot = bot assert(self.bot) self.origin = self.channel self.origtxt = self.txt self.makeargs() logging.debug("%s - prepared event - %s" % (self.auth, self.cbtype)) def bind(self, bot=None, user=None, chan=None): """ bind event.bot event.user and event.chan to execute a command on it. """ target = self.auth assert target bot = bot or self.bot assert bot if not self.user and target: cfg = Config() if cfg.auto_register: bot.users.addguest(target) self.user = user or bot.users.getuser(target) logging.info("eventbase - binding user - %s - from %s" % (str(self.user), whichmodule())) if not self.chan: if chan: self.chan = chan elif self.channel: self.chan = ChannelBase(self.channel, bot.botname) elif self.userhost: self.chan = ChannelBase(self.userhost, bot.botname) logging.info("eventbase - binding channel - %s" % str(self.chan)) if not self.user: logging.info("eventbase - no %s user found .. setting nodispatch" % target) ; self.nodispatch = True self.prepare(bot) return self def parse(self, event, *args, **kwargs): """ overload this. """ self.bot = event.bot self.origin = event.origin self.ruserhost = self.origin self.userhost = self.origin self.channel = event.channel self.auth = stripped(self.userhost) def waitfor(self, millisec=10000): """ wait for the event to finish. """ logging.warn("eventbase - waiting for %s" % self.txt) self.finished.wait(5) return waitforqueue(self.resqueue , millisec) def copyin(self, eventin): """ copy in an event. """ self.update(eventin) self.threads = self.threads or [] self.queues = self.queues or [] self.finished = self.finished or threading.Event() self.resqueue = self.resqueue or Queue.Queue() self.inqueue = self.inqueue or Queue.Queue() self.outqueue = self.outqueue or Queue.Queue() return self @locked def reply(self, txt, result=[], event=None, origin="", dot=u", ", nr=375, extend=0, *args, **kwargs): """ reply to this event """ if self.checkqueues(result): return self if self.silent: self.msg = True self.bot.say(self.nick, txt, result, self.userhost, extend=extend, event=self, *args, **kwargs) elif self.isdcc: self.bot.say(self.sock, txt, result, self.userhost, extend=extend, event=self, *args, **kwargs) else: self.bot.say(self.channel, txt, result, self.userhost, extend=extend, event=self, *args, **kwargs) return self def missing(self, txt): """ display missing arguments. """ self.reply("%s %s" % (self.usercmnd, txt), event=self) return self def done(self): """ tell the user we are done. """ self.reply('<b>done</b> - %s' % self.txt, event=self) return self def leave(self): """ lower the time to leave. """ self.ttl -= 1 if self.ttl <= 0 : self.status = "done" logging.info("======== STOP handling event ========") def makeoptions(self): """ check the given txt for options. """ try: self.options = makeeventopts(self.txt) except: return if not self.options: return logging.debug("eventbase - options - %s" % unicode(self.options)) self.txt = ' '.join(self.options.args) self.makeargs() def makeargs(self): """ make arguments and rest attributes from self.txt. """ if not self.txt: self.args = [] self.rest = "" else: args = self.txt.split() self.chantag = args[0] if len(args) > 1: self.args = args[1:] self.rest = ' '.join(self.args) else: self.args = [] self.rest = "" def checkqueues(self, resultlist): """ check if resultlist is to be sent to the queues. if so do it. """ if self.queues: for queue in self.queues: for item in resultlist: if item: queue.put_nowait(item) for item in resultlist: if item: self.outqueue.put_nowait(item) return True return False def makeresponse(self, txt, result, dot=u", ", *args, **kwargs): """ create a response from a string and result list. """ return self.bot.makeresponse(txt, result, dot, *args, **kwargs) def less(self, what, nr=365): """ split up in parts of <nr> chars overflowing on word boundaries. """ return self.bot.less(what, nr) def isremote(self): """ check whether the event is off remote origin. """ if self.txt: return self.txt.startswith('{"') or self.txt.startswith("{&") def iscmnd(self): """ check if event is a command. """ if not self.txt: logging.warn("eventbase - no txt set.") ; return if self.iscommand: return self.txt if self.isremote(): logging.info("eventbase - event is remote") ; return logging.debug("eventbase - trying to match %s" % self.txt) cc = "!" if not self.chan: self.chan = ChannelBase(self.channel, self.bot.botname) cc = self.chan.data.cc if not cc: self.chan.data.cc = "!" ; self.chan.save() if not cc: cc = "!" if self.type == "DISPATCH": cc += "!" if not self.bot: logging.warn("eventbase - bot is not bind into event.") ; return False logging.debug("eventbase - cc for %s is %s (%s)" % (self.title or self.channel or self.userhost, cc, self.bot.nick)) if self.txt[0] in cc: return self.txt[1:] matchnick = unicode(self.bot.nick + u":") if self.txt.startswith(matchnick): return self.txt[len(matchnick):] return False
#!/usr/bin/env python # Copyright (c) 2014-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import os import subprocess import sys import time try: import argparse except ImportError: print("Cannot import argparse.") exit(1) # Import the testing utils sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../tests/") import utils KB = 1024 * 1024 RANGES = { "colors": (utils.blue, utils.green, utils.yellow, utils.red), "utilization": (8, 20, 50), "cpu_time": (0.4, 1, 10), "memory": (8 * KB, 12 * KB, 24 * KB), "fds": (10, 20, 50), "duration": (0.8, 1, 3), } def check_leaks_linux(shell, query, count=1, supp_file=None): """Run valgrind using the shell and a query, parse leak reports.""" suppressions = "" if supp_file is None else "--suppressions=%s" % supp_file cmd = [ "valgrind", "--tool=memcheck", suppressions, shell, "--profile", "%d" % count, query, "--disable_extensions", ] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) _, stderr = proc.communicate() summary = { "definitely": None, "indirectly": None, "possibly": None, } if args.verbose: print(stderr) for line in stderr.split("\n"): for key in summary: if line.find(key) >= 0: summary[key] = line.split(":")[1].strip() if summary["definitely"] is None: raise Exception("Could not execute valgrind correctly") return summary def check_leaks_darwin(shell, query, count=1): # Run the shell with a --delay flag such that leaks can attach before exit. proc = subprocess.Popen( [shell, "--profile", str(count), "--profile_delay", "1", query], stdout=subprocess.PIPE, stderr=subprocess.PIPE) leak_checks = None while proc.poll() is None: # Continue to run leaks until the monitored shell exits. leaks = subprocess.Popen( ["leaks", "%s" % proc.pid], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, _ = leaks.communicate() if args.verbose: print(stdout) try: for line in stdout.split("\n"): if line.find("total leaked bytes") >= 0: leak_checks = line.split(":")[1].strip() except: print("Encountered exception while running leaks:") print(stdout) return {"definitely": leak_checks} def check_leaks(shell, query, count=1, supp_file=None): if utils.platform() == "darwin": return check_leaks_darwin(shell, query, count=count) else: return check_leaks_linux(shell, query, count=count, supp_file=supp_file) def profile_leaks(shell, queries, count=1, rounds=1, supp_file=None): report = {} for name, query in queries.iteritems(): print("Analyzing leaks in query: %s" % query) # Apply count (optionally run the query several times). summary = check_leaks(shell, query, count, supp_file) display = [] for key in summary: output = summary[key] if output is not None and output[0] != "0": # Add some fun colored output if leaking. if key == "definitely": output = utils.red(output) report[name] = "LEAKING" if key == "indirectly": output = utils.yellow(output) report[name] = "WARNING" else: report[name] = "SAFE" display.append("%s: %s" % (key, output)) print(" %s" % "; ".join(display)) return report def run_query(shell, query, timeout=0, count=1): """Execute the osqueryi shell in profile mode with a setup/teardown delay.""" start_time = time.time() return utils.profile_cmd([ shell, "--profile", str(count), "--profile_delay", "1", query, "--disable_extensions", ], timeout=timeout, count=count) def summary_line(name, result): if not args.n: for key, v in result.iteritems(): print("%s" % ( RANGES["colors"][v[0]]("%s:%s" % ( key[0].upper(), v[0]))), end="") print(" ", end="") print("%s:" % name, end=" ") for key, v in result.iteritems(): print("%s: %s" % (key, v[1]), end=" ") print("") def summary(results, display=False): """Map the results to simple thresholds.""" def rank(value, ranges): for i, r in enumerate(ranges): if value < r: return i return len(ranges) summary_results = {} for name, result in results.iteritems(): failed = "exit" in result and result["exit"] > 0 summary_result = {} for key in RANGES: if key == "colors": continue if key not in result: continue if failed: summary_result[key] = (len(RANGES["colors"]) - 1, -1) else: summary_result[key] = (rank(result[key], RANGES[key]), result[key]) if display and not args.check: summary_line(name, summary_result) summary_results[name] = summary_result return summary_results def profile(shell, queries, timeout=0, count=1, rounds=1): report = {} for name, query in queries.iteritems(): forced = True if name == "force" else False if not forced: print("Profiling query: %s" % query) results = {} for i in range(rounds): if forced: result = utils.profile_cmd(shell, shell=True, timeout=timeout, count=count) else: result = run_query(shell, query, timeout=timeout, count=count) summary( {"%s (%d/%d)" % (name, i + 1, rounds): result}, display=True) # Store each result round to return an average. for k, v in result.iteritems(): results[k] = results.get(k, []) results[k].append(v) average_results = {} for k in results: average_results[k] = sum(results[k]) / len(results[k]) report[name] = average_results if rounds > 1: summary({"%s avg" % name: report[name]}, display=True) return report def compare(profile1, profile2): """Compare two jSON profile outputs.""" for table in profile1: if table not in profile2: # No comparison possible continue summary_line(table, profile1[table]) summary_line(table, profile2[table]) def regress_check(profile1, profile2): regressed = False for table in profile1: if table not in profile2: continue for measure in profile1[table]: if profile2[table][measure][0] > profile1[table][measure][0]: print("%s %s has regressed (%s->%s)!" % (table, measure, profile1[table][measure][0], profile2[table][measure][0])) regressed = True if not regressed: print("No regressions!") return 0 return 1 if __name__ == "__main__": parser = argparse.ArgumentParser(description=( "Profile osquery, individual tables, " "or a set of osqueryd config queries." )) parser.add_argument( "-n", action="store_true", default=False, help="Do not output colored ranks." ) parser.add_argument( "--verbose", action="store_true", default=False, help="Be verbose.") parser.add_argument( "--leaks", default=False, action="store_true", help="Check for memory leaks instead of performance." ) group = parser.add_argument_group("Query Options:") group.add_argument( "--restrict", metavar="LIST", default="", help="Limit to a list of comma-separated tables." ) group.add_argument( "--tables", metavar="PATH", default="./specs", help="Path to the osquery table specs." ) group.add_argument( "--config", metavar="FILE", default=None, help="Use scheduled queries from a config." ) group.add_argument( "--query", metavar="STRING", default=None, help="Profile a single query." ) group = parser.add_argument_group("Run Options:") group.add_argument( "--timeout", metavar="N", default=0, type=int, help="Max seconds a query may run --count times." ) group.add_argument( "--count", metavar="N", default=1, type=int, help="Run the query N times serially." ) group.add_argument( "--rounds", metavar="N", default=1, type=int, help="Run the profile for N rounds and use the average." ) group.add_argument( "--shell", metavar="PATH", default="./build/%s/osquery/osqueryi" % ( utils.platform()), help="Path to osqueryi shell (./build/<sys>/osquery/osqueryi)." ) group.add_argument( "--force", action="store_true", default=False, help="Force run the target of shell", ) group = parser.add_argument_group("Performance Options:") group.add_argument( "--output", metavar="FILE", default=None, help="Write JSON performance output to file." ) group.add_argument( "--check", metavar="OLD_OUTPUT", nargs=1, help="Check regressions using an existing output." ) group.add_argument( "--compare", metavar="FILE", nargs=2, help="Compare existing performance outputs (old, new)." ) group = parser.add_argument_group("Memory Options:") group.add_argument( "--suppressions", metavar="SUPP", default="./tools/analysis/valgrind.supp", help="Add a suppressions files to memory leak checking (linux only)." ) args = parser.parse_args() if args.compare: with open(args.compare[0]) as fh: profile1 = json.loads(fh.read()) with open(args.compare[1]) as fh: profile2 = json.loads(fh.read()) compare(profile1, profile2) exit(0) if args.check: with open(args.check[0]) as fh: profile1 = json.loads(fh.read()) if not args.force and not os.path.exists(args.shell): print("Cannot find --shell: %s" % (args.shell)) exit(1) if args.config is None and not os.path.exists(args.tables): print("Cannot find --tables: %s" % (args.tables)) exit(1) queries = {} if args.config is not None: if not os.path.exists(args.config): print("Cannot find --config: %s" % (args.config)) exit(1) queries = utils.queries_from_config(args.config) elif args.query is not None: queries["manual"] = args.query elif args.force: queries["force"] = True else: queries = utils.queries_from_tables(args.tables, args.restrict) if args.leaks: results = profile_leaks( args.shell, queries, count=args.count, rounds=args.rounds, supp_file=args.suppressions ) else: # Start the profiling! results = profile( args.shell, queries, timeout=args.timeout, count=args.count, rounds=args.rounds ) # Only apply checking/regressions to performance, not leaks. if args.check: exit(regress_check(profile1, summary(results))) if args.output is not None: with open(args.output, "w") as fh: if args.leaks: # Leaks report does not need a summary view. fh.write(json.dumps(results, indent=1)) else: fh.write(json.dumps(summary(results), indent=1)) print("Wrote output summary: %s" % args.output)
from __future__ import print_function, division from sympy import (Basic, sympify, symbols, Dummy, Lambda, summation, Piecewise, S, cacheit, Sum, exp, I, Ne, Eq, poly, series, factorial, And) from sympy.polys.polyerrors import PolynomialError from sympy.solvers.solveset import solveset from sympy.stats.crv import reduce_rational_inequalities_wrap from sympy.stats.rv import (NamedArgsMixin, SinglePSpace, SingleDomain, random_symbols, PSpace, ConditionalDomain, RandomDomain, ProductDomain) from sympy.stats.symbolic_probability import Probability from sympy.functions.elementary.integers import floor from sympy.sets.fancysets import Range, FiniteSet from sympy.sets.sets import Union from sympy.sets.contains import Contains from sympy.utilities import filldedent import random class DiscreteDistribution(Basic): def __call__(self, *args): return self.pdf(*args) class SingleDiscreteDistribution(DiscreteDistribution, NamedArgsMixin): """ Discrete distribution of a single variable Serves as superclass for PoissonDistribution etc.... Provides methods for pdf, cdf, and sampling See Also: sympy.stats.crv_types.* """ set = S.Integers def __new__(cls, *args): args = list(map(sympify, args)) return Basic.__new__(cls, *args) @staticmethod def check(*args): pass def sample(self): """ A random realization from the distribution """ icdf = self._inverse_cdf_expression() while True: sample_ = floor(list(icdf(random.uniform(0, 1)))[0]) if sample_ >= self.set.inf: return sample_ @cacheit def _inverse_cdf_expression(self): """ Inverse of the CDF Used by sample """ x = Dummy('x', positive=True, integer=True) z = Dummy('z', positive=True) cdf_temp = self.cdf(x) # Invert CDF try: inverse_cdf = solveset(cdf_temp - z, x, domain=S.Reals) except NotImplementedError: inverse_cdf = None if not inverse_cdf or len(inverse_cdf.free_symbols) != 1: raise NotImplementedError("Could not invert CDF") return Lambda(z, inverse_cdf) @cacheit def compute_cdf(self, **kwargs): """ Compute the CDF from the PDF Returns a Lambda """ x, z = symbols('x, z', integer=True, cls=Dummy) left_bound = self.set.inf # CDF is integral of PDF from left bound to z pdf = self.pdf(x) cdf = summation(pdf, (x, left_bound, z), **kwargs) # CDF Ensure that CDF left of left_bound is zero cdf = Piecewise((cdf, z >= left_bound), (0, True)) return Lambda(z, cdf) def _cdf(self, x): return None def cdf(self, x, **kwargs): """ Cumulative density function """ if not kwargs: cdf = self._cdf(x) if cdf is not None: return cdf return self.compute_cdf(**kwargs)(x) @cacheit def compute_characteristic_function(self, **kwargs): """ Compute the characteristic function from the PDF Returns a Lambda """ x, t = symbols('x, t', real=True, cls=Dummy) pdf = self.pdf(x) cf = summation(exp(I*t*x)*pdf, (x, self.set.inf, self.set.sup)) return Lambda(t, cf) def _characteristic_function(self, t): return None def characteristic_function(self, t, **kwargs): """ Characteristic function """ if not kwargs: cf = self._characteristic_function(t) if cf is not None: return cf return self.compute_characteristic_function(**kwargs)(t) @cacheit def compute_moment_generating_function(self, **kwargs): t = Dummy('t', real=True) x = Dummy('x', integer=True) pdf = self.pdf(x) mgf = summation(exp(t*x)*pdf, (x, self.set.inf, self.set.sup)) return Lambda(t, mgf) def _moment_generating_function(self, t): return None def moment_generating_function(self, t, **kwargs): if not kwargs: mgf = self._moment_generating_function(t) if mgf is not None: return mgf return self.compute_moment_generating_function(**kwargs)(t) @cacheit def compute_quantile(self, **kwargs): """ Compute the Quantile from the PDF Returns a Lambda """ x = Dummy('x', integer=True) p = Dummy('p', real=True) left_bound = self.set.inf pdf = self.pdf(x) cdf = summation(pdf, (x, left_bound, x), **kwargs) set = ((x, p <= cdf), ) return Lambda(p, Piecewise(*set)) def _quantile(self, x): return None def quantile(self, x, **kwargs): """ Cumulative density function """ if not kwargs: quantile = self._quantile(x) if quantile is not None: return quantile return self.compute_quantile(**kwargs)(x) def expectation(self, expr, var, evaluate=True, **kwargs): """ Expectation of expression over distribution """ # TODO: support discrete sets with non integer stepsizes if evaluate: try: p = poly(expr, var) t = Dummy('t', real=True) mgf = self.moment_generating_function(t) deg = p.degree() taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t) result = 0 for k in range(deg+1): result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k) return result except PolynomialError: return summation(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs) else: return Sum(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs) def __call__(self, *args): return self.pdf(*args) class DiscreteDistributionHandmade(SingleDiscreteDistribution): _argnames = ('pdf',) @property def set(self): return self.args[1] def __new__(cls, pdf, set=S.Integers): return Basic.__new__(cls, pdf, set) class DiscreteDomain(RandomDomain): """ A domain with discrete support with step size one. Represented using symbols and Range. """ is_Discrete = True class SingleDiscreteDomain(DiscreteDomain, SingleDomain): def as_boolean(self): return Contains(self.symbol, self.set) class ConditionalDiscreteDomain(DiscreteDomain, ConditionalDomain): """ Domain with discrete support of step size one, that is restricted by some condition. """ @property def set(self): rv = self.symbols if len(self.symbols) > 1: raise NotImplementedError(filldedent(''' Multivariate conditional domains are not yet implemented.''')) rv = list(rv)[0] return reduce_rational_inequalities_wrap(self.condition, rv).intersect(self.fulldomain.set) class DiscretePSpace(PSpace): is_real = True is_Discrete = True @property def pdf(self): return self.density(*self.symbols) def where(self, condition): rvs = random_symbols(condition) assert all(r.symbol in self.symbols for r in rvs) if len(rvs) > 1: raise NotImplementedError(filldedent('''Multivariate discrete random variables are not yet supported.''')) conditional_domain = reduce_rational_inequalities_wrap(condition, rvs[0]) conditional_domain = conditional_domain.intersect(self.domain.set) return SingleDiscreteDomain(rvs[0].symbol, conditional_domain) def probability(self, condition): complement = isinstance(condition, Ne) if complement: condition = Eq(condition.args[0], condition.args[1]) try: _domain = self.where(condition).set if condition == False or _domain is S.EmptySet: return S.Zero if condition == True or _domain == self.domain.set: return S.One prob = self.eval_prob(_domain) except NotImplementedError: from sympy.stats.rv import density expr = condition.lhs - condition.rhs dens = density(expr) if not isinstance(dens, DiscreteDistribution): dens = DiscreteDistributionHandmade(dens) z = Dummy('z', real=True) space = SingleDiscretePSpace(z, dens) prob = space.probability(condition.__class__(space.value, 0)) if prob is None: prob = Probability(condition) return prob if not complement else S.One - prob def eval_prob(self, _domain): sym = list(self.symbols)[0] if isinstance(_domain, Range): n = symbols('n', integer=True) inf, sup, step = (r for r in _domain.args) summand = ((self.pdf).replace( sym, n*step)) rv = summation(summand, (n, inf/step, (sup)/step - 1)).doit() return rv elif isinstance(_domain, FiniteSet): pdf = Lambda(sym, self.pdf) rv = sum(pdf(x) for x in _domain) return rv elif isinstance(_domain, Union): rv = sum(self.eval_prob(x) for x in _domain.args) return rv def conditional_space(self, condition): # XXX: Converting from set to tuple. The order matters to Lambda # though so we should be starting with a set... density = Lambda(tuple(self.symbols), self.pdf/self.probability(condition)) condition = condition.xreplace(dict((rv, rv.symbol) for rv in self.values)) domain = ConditionalDiscreteDomain(self.domain, condition) return DiscretePSpace(domain, density) class ProductDiscreteDomain(ProductDomain, DiscreteDomain): def as_boolean(self): return And(*[domain.as_boolean for domain in self.domains]) class SingleDiscretePSpace(DiscretePSpace, SinglePSpace): """ Discrete probability space over a single univariate variable """ is_real = True @property def set(self): return self.distribution.set @property def domain(self): return SingleDiscreteDomain(self.symbol, self.set) def sample(self): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ return {self.value: self.distribution.sample()} def compute_expectation(self, expr, rvs=None, evaluate=True, **kwargs): rvs = rvs or (self.value,) if self.value not in rvs: return expr expr = expr.xreplace(dict((rv, rv.symbol) for rv in rvs)) x = self.value.symbol try: return self.distribution.expectation(expr, x, evaluate=evaluate, **kwargs) except NotImplementedError: return Sum(expr * self.pdf, (x, self.set.inf, self.set.sup), **kwargs) def compute_cdf(self, expr, **kwargs): if expr == self.value: x = Dummy("x", real=True) return Lambda(x, self.distribution.cdf(x, **kwargs)) else: raise NotImplementedError() def compute_density(self, expr, **kwargs): if expr == self.value: return self.distribution raise NotImplementedError() def compute_characteristic_function(self, expr, **kwargs): if expr == self.value: t = Dummy("t", real=True) return Lambda(t, self.distribution.characteristic_function(t, **kwargs)) else: raise NotImplementedError() def compute_moment_generating_function(self, expr, **kwargs): if expr == self.value: t = Dummy("t", real=True) return Lambda(t, self.distribution.moment_generating_function(t, **kwargs)) else: raise NotImplementedError() def compute_quantile(self, expr, **kwargs): if expr == self.value: p = Dummy("p", real=True) return Lambda(p, self.distribution.quantile(p, **kwargs)) else: raise NotImplementedError()
from contextlib import closing from contextlib import suppress from io import StringIO import uuid import html from sklearn import config_context class _VisualBlock: """HTML Representation of Estimator Parameters ---------- kind : {'serial', 'parallel', 'single'} kind of HTML block estimators : list of estimators or `_VisualBlock`s or a single estimator If kind != 'single', then `estimators` is a list of estimators. If kind == 'single', then `estimators` is a single estimator. names : list of str, default=None If kind != 'single', then `names` corresponds to estimators. If kind == 'single', then `names` is a single string corresponding to the single estimator. name_details : list of str, str, or None, default=None If kind != 'single', then `name_details` corresponds to `names`. If kind == 'single', then `name_details` is a single string corresponding to the single estimator. dash_wrapped : bool, default=True If true, wrapped HTML element will be wrapped with a dashed border. Only active when kind != 'single'. """ def __init__(self, kind, estimators, *, names=None, name_details=None, dash_wrapped=True): self.kind = kind self.estimators = estimators self.dash_wrapped = dash_wrapped if self.kind in ('parallel', 'serial'): if names is None: names = (None, ) * len(estimators) if name_details is None: name_details = (None, ) * len(estimators) self.names = names self.name_details = name_details def _sk_visual_block_(self): return self def _write_label_html(out, name, name_details, outer_class="sk-label-container", inner_class="sk-label", checked=False): """Write labeled html with or without a dropdown with named details""" out.write(f'<div class="{outer_class}">' f'<div class="{inner_class} sk-toggleable">') name = html.escape(name) if name_details is not None: checked_str = 'checked' if checked else '' est_id = uuid.uuid4() out.write(f'<input class="sk-toggleable__control sk-hidden--visually" ' f'id="{est_id}" type="checkbox" {checked_str}>' f'<label class="sk-toggleable__label" for="{est_id}">' f'{name}</label>' f'<div class="sk-toggleable__content"><pre>{name_details}' f'</pre></div>') else: out.write(f'<label>{name}</label>') out.write('</div></div>') # outer_class inner_class def _get_visual_block(estimator): """Generate information about how to display an estimator. """ with suppress(AttributeError): return estimator._sk_visual_block_() if isinstance(estimator, str): return _VisualBlock('single', estimator, names=estimator, name_details=estimator) elif estimator is None: return _VisualBlock('single', estimator, names='None', name_details='None') # check if estimator looks like a meta estimator wraps estimators if hasattr(estimator, 'get_params'): estimators = [] for key, value in estimator.get_params().items(): # Only look at the estimators in the first layer if '__' not in key and hasattr(value, 'get_params'): estimators.append(value) if len(estimators): return _VisualBlock('parallel', estimators, names=None) return _VisualBlock('single', estimator, names=estimator.__class__.__name__, name_details=str(estimator)) def _write_estimator_html(out, estimator, estimator_label, estimator_label_details, first_call=False): """Write estimator to html in serial, parallel, or by itself (single). """ if first_call: est_block = _get_visual_block(estimator) else: with config_context(print_changed_only=True): est_block = _get_visual_block(estimator) if est_block.kind in ('serial', 'parallel'): dashed_wrapped = first_call or est_block.dash_wrapped dash_cls = " sk-dashed-wrapped" if dashed_wrapped else "" out.write(f'<div class="sk-item{dash_cls}">') if estimator_label: _write_label_html(out, estimator_label, estimator_label_details) kind = est_block.kind out.write(f'<div class="sk-{kind}">') est_infos = zip(est_block.estimators, est_block.names, est_block.name_details) for est, name, name_details in est_infos: if kind == 'serial': _write_estimator_html(out, est, name, name_details) else: # parallel out.write('<div class="sk-parallel-item">') # wrap element in a serial visualblock serial_block = _VisualBlock('serial', [est], dash_wrapped=False) _write_estimator_html(out, serial_block, name, name_details) out.write('</div>') # sk-parallel-item out.write('</div></div>') elif est_block.kind == 'single': _write_label_html(out, est_block.names, est_block.name_details, outer_class="sk-item", inner_class="sk-estimator", checked=first_call) _STYLE = """ div.sk-top-container { color: black; background-color: white; } div.sk-toggleable { background-color: white; } label.sk-toggleable__label { cursor: pointer; display: block; width: 100%; margin-bottom: 0; padding: 0.2em 0.3em; box-sizing: border-box; text-align: center; } div.sk-toggleable__content { max-height: 0; max-width: 0; overflow: hidden; text-align: left; background-color: #f0f8ff; } div.sk-toggleable__content pre { margin: 0.2em; color: black; border-radius: 0.25em; background-color: #f0f8ff; } input.sk-toggleable__control:checked~div.sk-toggleable__content { max-height: 200px; max-width: 100%; overflow: auto; } div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: #d4ebff; } div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: #d4ebff; } input.sk-hidden--visually { border: 0; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } div.sk-estimator { font-family: monospace; background-color: #f0f8ff; margin: 0.25em 0.25em; border: 1px dotted black; border-radius: 0.25em; box-sizing: border-box; } div.sk-estimator:hover { background-color: #d4ebff; } div.sk-parallel-item::after { content: ""; width: 100%; border-bottom: 1px solid gray; flex-grow: 1; } div.sk-label:hover label.sk-toggleable__label { background-color: #d4ebff; } div.sk-serial::before { content: ""; position: absolute; border-left: 1px solid gray; box-sizing: border-box; top: 2em; bottom: 0; left: 50%; } div.sk-serial { display: flex; flex-direction: column; align-items: center; background-color: white; } div.sk-item { z-index: 1; } div.sk-parallel { display: flex; align-items: stretch; justify-content: center; background-color: white; } div.sk-parallel-item { display: flex; flex-direction: column; position: relative; background-color: white; } div.sk-parallel-item:first-child::after { align-self: flex-end; width: 50%; } div.sk-parallel-item:last-child::after { align-self: flex-start; width: 50%; } div.sk-parallel-item:only-child::after { width: 0; } div.sk-dashed-wrapped { border: 1px dashed gray; margin: 0.2em; box-sizing: border-box; padding-bottom: 0.1em; background-color: white; position: relative; } div.sk-label label { font-family: monospace; font-weight: bold; background-color: white; display: inline-block; line-height: 1.2em; } div.sk-label-container { position: relative; z-index: 2; text-align: center; } div.sk-container { display: inline-block; position: relative; } """.replace(' ', '').replace('\n', '') # noqa def estimator_html_repr(estimator): """Build a HTML representation of an estimator. Read more in the :ref:`User Guide <visualizing_composite_estimators>`. Parameters ---------- estimator : estimator object The estimator to visualize. Returns ------- html: str HTML representation of estimator. """ with closing(StringIO()) as out: out.write(f'<style>{_STYLE}</style>' f'<div class="sk-top-container"><div class="sk-container">') _write_estimator_html(out, estimator, estimator.__class__.__name__, str(estimator), first_call=True) out.write('</div></div>') html_output = out.getvalue() return html_output
#!/usr/bin/python """ Domain model for NED, NewsReader project. @author: U{Filip Ilievski<filipilievski.wordpress.com>} @author: U{Antske Fokkens<http://wordpress.let.vupr.nl/antske/>} @version: 0.1 @contact: U{f.ilievski@vu.nl<mailto:f.ilievski@vu.nl>} @contact: U{antske.fokkens@vu.nl<mailto:antske.fokkens@vu.nl>} @since: 08-Jul-2015 """ __version__ = '0.1' __modified__ = '08Jul2015' __author__ = 'Filip Ilievski, Antske Fokkens' from KafNafParserPy import * import os import sys import json import time sys.path.append('./') from dbpediaEnquirerPy import * ########################################################################################## ################################### HELPER FUNCTIONS ##################################### ########################################################################################## def get_start_term(parser): # Find the start of sentence 2 (after title) for token in parser.get_tokens(): if token.get_sent()=="2": token_after_title=int(token.get_id().replace("w", "")) break # Process from sentence 2 on # First find the appropriate term where sentence 2 starts for term in parser.get_terms(): target_ids=term.get_span().get_span_ids() if int(target_ids[0].replace("w", ""))>=token_after_title: term_after_title=int(term.get_id().replace("t", "")) break return term_after_title def get_most_confident_link(e): maxconf=-0.1 maxref=None for ref in e.get_external_references(): if ref.get_resource()=="spotlight_v1" and float(ref.get_confidence())>maxconf: maxconf=float(ref.get_confidence()) maxref=ref.get_reference() return maxref def get_entity_terms(entity): for ref in entity.get_references(): terms=ref.get_span().get_span_ids() return terms def get_terms_mention(parser, terms): term_text=[] c=0 new_terms=terms for t in terms: term=parser.get_term(t) target_ids=term.get_span().get_span_ids() for tid in target_ids: c+=1 word=parser.get_token(tid).get_text() if (c==1 or c==len(terms)) and (word=="'" or word=="''" or word=="\""): new_terms.remove(t) continue term_text.append(word) res=(" ").join(term_text) return res, new_terms def get_entity_mention(parser, entity): terms=get_entity_terms(entity) return get_terms_mention(parser, terms) def get_initials(entity_string): initials="" ent_split=entity_string.split() if len(ent_split)>1: for word in ent_split: #if word.isupper(): # initials+=word if word[0].isupper(): initials+=word[0] else: initials=None return initials def is_person(dblink): return not dblink or my_dbpedia.is_person(dblink) def add_entity_extref(entity, extref): #print entity, extref my_ext_ref = CexternalReference() my_ext_ref.set_reference(extref) my_ext_ref.set_resource('domain_model') my_ext_ref.set_confidence('1.0') entity.add_external_reference(my_ext_ref) return entity def prestore_terms_and_tokens(parser): global term_for_token term_for_token = {} global tokens_for_term tokens_for_term = {} global term_sentences term_sentences={} for term in parser.get_terms(): token_arr=[] for token_id in term.get_span().get_span_ids(): term_for_token[token_id] = term.get_id() token_arr.append(token_id) token=parser.get_token(token_id) term_sentences[term.get_id()]=token.get_sent() tokens_for_term[term.get_id()]=token_arr #def get_id_not_used(used_ids): # n = 1 # while True: # possible_id = 'f'+str(n) # if possible_id not in used_ids: # return possible_id # n += 1 ########################################################################################## #################################### Recognition ######################################### ########################################################################################## def extend_string_with_numbers_and_nnps(entity_string, ts, parser): sentence=term_sentences[ts[0]] begin=int(ts[0].replace("t","")) end=int(ts[len(ts)-1].replace("t", "")) new_terms=list(ts) num_terms=len(term_sentences) # prepend ext_string="" # Append ext_string= ext_string.strip() + " " + entity_string temp=end while True: temp+=1 if temp>num_terms: break new_term="t" + str(temp) try: addition, added_terms = get_terms_mention(parser, [new_term]) if term_sentences[new_term]==sentence and (parser.get_term(new_term).get_pos() in ["NNP", "NNPS"] or (addition!="" and addition.isdigit())): ext_string = ext_string + " " + addition new_terms.append(new_term) else: break except KeyError: #out of bounds break return ext_string.strip(), new_terms ########################################################################################## ####################################### MODULES ########################################## ########################################################################################## def get_previous_occurrence(e, all_entities, entity_string): #1 other_ref=None for ent in all_entities: if e!=ent and (((int(e["eid"][1:])>int(ent["eid"][1:])) and (e["title"] is ent["title"])) or (e["title"] and not ent["title"])): # Entities that are different AND either (entities that passed from the same text type (main or title) OR entities in title) ekey=None #print ent["eid"] if "extended" in ent and ent["extended"]["extref"]: ekey=ent["extended"]["mention"].lower() if entity_string==ekey or ((entity_string in ekey.split()) and is_person(ent["extended"]["extref"])): other_ref=ent["extended"]["extref"] if other_ref: # Stop after one match break #print "D1", entity_string, ekey, other_ref if ent["original"]["extref"] or ent["original"]["nwr_extref"]: #if entity_string=="smith": # print ent["eid"], entity_string, e["original"]["mention"] ekey=ent["original"]["mention"].lower() if entity_string==ekey: #print "D1", entity_string, ekey, other_ref other_ref=ent["original"]["extref"] if other_ref: break elif entity_string in ekey.split(): if ent["original"]["extref"] is not None: this_extref=ent["original"]["extref"] else: # NOTE: THIS SHOULD NEVER BE THE CASE this_extref=ent["original"]["nwr_extref"] if is_person(this_extref): other_ref=this_extref if other_ref: break #if entity_string=="smith": # print other_ref return other_ref def solve_initials_and_abbreviations(entity, entity_string, all_entities): #3 #2 Initials and abbreviations extref=None for other_entity in all_entities: if other_entity!=entity: if "extended" in other_entity and other_entity["extended"]["extref"]: initials=other_entity["extended"]["initials"] other_ref=other_entity["extended"]["extref"] if entity_string==initials: extref=other_ref elif other_entity["original"]["extref"]: initials=other_entity["original"]["initials"] other_ref=other_entity["original"]["extref"] if entity_string==initials: extref=other_ref else: initials=other_entity["original"]["initials"] other_ref=other_entity["original"]["nwr_extref"] if entity_string==initials: extref=other_ref return extref def do_disambiguation(entity, entity_string, all_entities): extref=get_previous_occurrence(entity, all_entities, entity_string.lower()); #D1 Get previous occurrence if not extref: if len(entity_string.split())==1 and entity_string.isupper(): # If one term, all-upper, then it may be an abbreviation extref = solve_initials_and_abbreviations(entity, entity_string, all_entities) return extref def occurred_in_article(extname, all_entities): for ent in all_entities: if extname==ent["original"]["mention"]: return ent["original"]["nwr_extref"] def get_from_es(pattern): max_occurrences=0 best_candidate=None total=0 if pattern in lemma_to_entity: for candidate in lemma_to_entity[pattern]: num_occurrences=lemma_to_entity[pattern][candidate] if num_occurrences>max_occurrences: max_occurrences=lemma_to_entity[pattern][candidate] best_candidate=candidate total+=num_occurrences if max_occurrences>10 and max_occurrences/float(total)>=0.5: return best_candidate else: return None return None def create_dbpedia_uri(t): dburl="http://dbpedia.org/resource/" + t.replace(" ", "_") return dburl def get_from_dbpedia(mention): dblink=create_dbpedia_uri(e["extended"]["mention"]) results=my_dbpedia.query_dbpedia_for_unique_dblink(dblink) return dblink if (results is not None and len(results)>0) else None ########################################################################################## ####################################### MAIN ############################################# ########################################################################################## global term_for_token global tokens_for_term global term_sentences global lemma_to_entity fname="lemma.json" f=open(fname, "r") for line in f: lemma_to_entity=json.loads(line) if __name__=="__main__": #if len(sys.argv)<2: # print "Please specify input file" # sys.exit(1) #changed: using stdin now file=sys.stdin # file=open("/Users/filipilievski/Processed/corpus_airbus/3835_Chinese_airlines_agree_purchase_of_Boeing_787_Dreamliners.naf", "r") #get begin time begintime = time.strftime('%Y-%m-%dT%H:%M:%S%Z') if len(sys.argv)>1: # Local instance is specified my_dbpedia = Cdbpedia_enquirer(sys.argv[1]) else: # default remote dbpedia my_dbpedia = Cdbpedia_enquirer() #path="NWR_EvalSet/" #path="eval_corpus/" #out_path="POCUS_EvalSet/" count_all = 0 count_dis=0 #for file in os.listdir(path): parser=KafNafParser(file) #putting the actual process in a try, except #if this module breaks it should return the original naf file (and print a warning) try: prestore_terms_and_tokens(parser) #we're using stdin now #out_file=file + ".out" all_entities=[] max_id=0 for entity in parser.get_entities(): if entity.get_id()[0]!="e": continue if int(entity.get_id()[1:])>max_id: max_id=int(entity.get_id()[1:]) entity_string, terms = get_entity_mention(parser, entity) # Normalization step if len(terms)==1 and entity_string.endswith("-based"): norm_entity_string=entity_string[:-6] else: norm_entity_string=entity_string ext_norm_entity_string, ext_terms=extend_string_with_numbers_and_nnps(norm_entity_string, terms, parser) istitle = (term_sentences[terms[0]]=="1") if ext_norm_entity_string==norm_entity_string: entity_entry = {"eid": entity.get_id(), "original": {"raw": entity_string, "mention": norm_entity_string, "terms": terms, "nwr_extref": get_most_confident_link(entity), "extref": None, "initials": get_initials(norm_entity_string)}, "title": istitle} else: entity_entry = {"eid": entity.get_id(), "original": {"raw": entity_string, "mention": norm_entity_string, "terms": terms, "nwr_extref": get_most_confident_link(entity), "extref": None, "initials": get_initials(entity_string)}, "extended": {"mention": ext_norm_entity_string, "terms": ext_terms, "initials": get_initials(ext_norm_entity_string), "extref": None}, "title": istitle} all_entities.append(entity_entry) for consider_title_entities in [False, True]: for e in all_entities: if e["title"] is consider_title_entities: # 1) Extended mention - This line ensures title entities get processed in a second iteration if "extended" in e: # 1) extension #e["extended"]["extref"]=occurred_in_article(e["extended"]["mention"], all_entities) or get_from_es(e["extended"]["mention"]) or get_from_dbpedia(e["extended"]["mention"]) # TODO: Try without ES e["extended"]["extref"]=occurred_in_article(e["extended"]["mention"], all_entities) or get_from_es(e["extended"]["mention"]) or get_from_dbpedia(e["extended"]["mention"]) # TODO: Try without ES for e in all_entities: if e["title"] is consider_title_entities: # 2) original mention - This line ensures title entities get processed in a second iteration e["original"]["extref"]=do_disambiguation(e, e["original"]["mention"], all_entities) #or get_from_es(e["original"]["mention"]) # TODO: Try without ES for e in all_entities: if e["title"] is consider_title_entities: # 3) original mention, last resort - This line ensures title entities get processed in a second iteration if e["original"]["extref"] is None: # TODO: Enable this block later! #if consider_title_entities: # e["original"]["extref"]="--NME--" #else: e["original"]["extref"]=e["original"]["nwr_extref"] for e in all_entities: sextref="" mention="" single=True if "extended" in e and e["extended"]["extref"]: sextref=e["extended"]["extref"] mention=e["extended"]["mention"] er = sextref new_entity = Centity() new_id = 'e' + str(max_id + 1) max_id+=1 new_entity.set_id(new_id) new_entity.set_comment(mention) ref = Creferences() ref.add_span(e["extended"]["terms"]) new_entity.add_reference(ref) ext_ref = CexternalReference() ext_ref.set_resource("dbp") ext_ref.set_source("POCUS") ext_ref.set_reference(er) ext_ref.set_confidence("1.0") new_entity.add_external_reference(ext_ref) new_entity.set_source("POCUS") parser.add_entity(new_entity) elif sextref=="" and e["original"]["extref"]: sextref=e["original"]["extref"] mention=e["original"]["mention"] ext_ref = CexternalReference() ext_ref.set_resource("dbp") ext_ref.set_source("POCUS") ext_ref.set_reference(sextref) ext_ref.set_confidence("1.0") parser.add_external_reference_to_entity(e["eid"], ext_ref) endtime = time.strftime('%Y-%m-%dT%H:%M:%S%Z') lp = Clp(name="VUA-popen-ned-reranker",version="1.0",btimestamp=begintime,etimestamp=endtime) parser.add_linguistic_processor('entities', lp) except: print >> sys.stderr, 'ERROR: unkown error occurred in the process. No additional disambiguations added.' parser.dump()
from abc import ABCMeta, abstractmethod, abstractproperty from contextlib import contextmanager from functools import wraps import gzip from inspect import getargspec from itertools import ( combinations, count, product, ) import operator import os from os.path import abspath, dirname, join, realpath import shutil import tempfile from logbook import TestHandler from mock import patch from nose.tools import nottest from numpy.testing import assert_allclose, assert_array_equal import pandas as pd from six import itervalues, iteritems, with_metaclass from six.moves import filter, map from sqlalchemy import create_engine from testfixtures import TempDirectory from toolz import concat from zipline.assets import AssetFinder, AssetDBWriter from zipline.assets.synthetic import make_simple_equity_info from zipline.data.data_portal import DataPortal from zipline.data.minute_bars import ( BcolzMinuteBarReader, BcolzMinuteBarWriter, US_EQUITIES_MINUTES_PER_DAY ) from zipline.data.us_equity_pricing import ( BcolzDailyBarReader, BcolzDailyBarWriter, SQLiteAdjustmentWriter, ) from zipline.finance.trading import TradingEnvironment from zipline.finance.order import ORDER_STATUS from zipline.lib.labelarray import LabelArray from zipline.pipeline.engine import SimplePipelineEngine from zipline.pipeline.loaders.testing import make_seeded_random_loader from zipline.utils import security_list from zipline.utils.input_validation import expect_dimensions from zipline.utils.sentinel import sentinel from zipline.utils.tradingcalendar import trading_days import numpy as np from numpy import float64 EPOCH = pd.Timestamp(0, tz='UTC') def seconds_to_timestamp(seconds): return pd.Timestamp(seconds, unit='s', tz='UTC') def to_utc(time_str): """Convert a string in US/Eastern time to UTC""" return pd.Timestamp(time_str, tz='US/Eastern').tz_convert('UTC') def str_to_seconds(s): """ Convert a pandas-intelligible string to (integer) seconds since UTC. >>> from pandas import Timestamp >>> (Timestamp('2014-01-01') - Timestamp(0)).total_seconds() 1388534400.0 >>> str_to_seconds('2014-01-01') 1388534400 """ return int((pd.Timestamp(s, tz='UTC') - EPOCH).total_seconds()) def drain_zipline(test, zipline): output = [] transaction_count = 0 msg_counter = 0 # start the simulation for update in zipline: msg_counter += 1 output.append(update) if 'daily_perf' in update: transaction_count += \ len(update['daily_perf']['transactions']) return output, transaction_count def check_algo_results(test, results, expected_transactions_count=None, expected_order_count=None, expected_positions_count=None, sid=None): if expected_transactions_count is not None: txns = flatten_list(results["transactions"]) test.assertEqual(expected_transactions_count, len(txns)) if expected_positions_count is not None: raise NotImplementedError if expected_order_count is not None: # de-dup orders on id, because orders are put back into perf packets # whenever they a txn is filled orders = set([order['id'] for order in flatten_list(results["orders"])]) test.assertEqual(expected_order_count, len(orders)) def flatten_list(list): return [item for sublist in list for item in sublist] def assert_single_position(test, zipline): output, transaction_count = drain_zipline(test, zipline) if 'expected_transactions' in test.zipline_test_config: test.assertEqual( test.zipline_test_config['expected_transactions'], transaction_count ) else: test.assertEqual( test.zipline_test_config['order_count'], transaction_count ) # the final message is the risk report, the second to # last is the final day's results. Positions is a list of # dicts. closing_positions = output[-2]['daily_perf']['positions'] # confirm that all orders were filled. # iterate over the output updates, overwriting # orders when they are updated. Then check the status on all. orders_by_id = {} for update in output: if 'daily_perf' in update: if 'orders' in update['daily_perf']: for order in update['daily_perf']['orders']: orders_by_id[order['id']] = order for order in itervalues(orders_by_id): test.assertEqual( order['status'], ORDER_STATUS.FILLED, "") test.assertEqual( len(closing_positions), 1, "Portfolio should have one position." ) sid = test.zipline_test_config['sid'] test.assertEqual( closing_positions[0]['sid'], sid, "Portfolio should have one position in " + str(sid) ) return output, transaction_count class ExceptionSource(object): def __init__(self): pass def get_hash(self): return "ExceptionSource" def __iter__(self): return self def next(self): 5 / 0 def __next__(self): 5 / 0 @contextmanager def security_list_copy(): old_dir = security_list.SECURITY_LISTS_DIR new_dir = tempfile.mkdtemp() try: for subdir in os.listdir(old_dir): shutil.copytree(os.path.join(old_dir, subdir), os.path.join(new_dir, subdir)) with patch.object(security_list, 'SECURITY_LISTS_DIR', new_dir), \ patch.object(security_list, 'using_copy', True, create=True): yield finally: shutil.rmtree(new_dir, True) def add_security_data(adds, deletes): if not hasattr(security_list, 'using_copy'): raise Exception('add_security_data must be used within ' 'security_list_copy context') directory = os.path.join( security_list.SECURITY_LISTS_DIR, "leveraged_etf_list/20150127/20150125" ) if not os.path.exists(directory): os.makedirs(directory) del_path = os.path.join(directory, "delete") with open(del_path, 'w') as f: for sym in deletes: f.write(sym) f.write('\n') add_path = os.path.join(directory, "add") with open(add_path, 'w') as f: for sym in adds: f.write(sym) f.write('\n') def all_pairs_matching_predicate(values, pred): """ Return an iterator of all pairs, (v0, v1) from values such that `pred(v0, v1) == True` Parameters ---------- values : iterable pred : function Returns ------- pairs_iterator : generator Generator yielding pairs matching `pred`. Examples -------- >>> from zipline.testing import all_pairs_matching_predicate >>> from operator import eq, lt >>> list(all_pairs_matching_predicate(range(5), eq)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> list(all_pairs_matching_predicate("abcd", lt)) [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')] """ return filter(lambda pair: pred(*pair), product(values, repeat=2)) def product_upper_triangle(values, include_diagonal=False): """ Return an iterator over pairs, (v0, v1), drawn from values. If `include_diagonal` is True, returns all pairs such that v0 <= v1. If `include_diagonal` is False, returns all pairs such that v0 < v1. """ return all_pairs_matching_predicate( values, operator.le if include_diagonal else operator.lt, ) def all_subindices(index): """ Return all valid sub-indices of a pandas Index. """ return ( index[start:stop] for start, stop in product_upper_triangle(range(len(index) + 1)) ) def chrange(start, stop): """ Construct an iterable of length-1 strings beginning with `start` and ending with `stop`. Parameters ---------- start : str The first character. stop : str The last character. Returns ------- chars: iterable[str] Iterable of strings beginning with start and ending with stop. Example ------- >>> chrange('A', 'C') ['A', 'B', 'C'] """ return list(map(chr, range(ord(start), ord(stop) + 1))) def make_trade_data_for_asset_info(dates, asset_info, price_start, price_step_by_date, price_step_by_sid, volume_start, volume_step_by_date, volume_step_by_sid, frequency, writer=None): """ Convert the asset info dataframe into a dataframe of trade data for each sid, and write to the writer if provided. Write NaNs for locations where assets did not exist. Return a dict of the dataframes, keyed by sid. """ trade_data = {} sids = asset_info.index price_sid_deltas = np.arange(len(sids), dtype=float64) * price_step_by_sid price_date_deltas = (np.arange(len(dates), dtype=float64) * price_step_by_date) prices = (price_sid_deltas + price_date_deltas[:, None]) + price_start volume_sid_deltas = np.arange(len(sids)) * volume_step_by_sid volume_date_deltas = np.arange(len(dates)) * volume_step_by_date volumes = (volume_sid_deltas + volume_date_deltas[:, None]) + volume_start for j, sid in enumerate(sids): start_date, end_date = asset_info.loc[sid, ['start_date', 'end_date']] # Normalize here so the we still generate non-NaN values on the minutes # for an asset's last trading day. for i, date in enumerate(dates.normalize()): if not (start_date <= date <= end_date): prices[i, j] = 0 volumes[i, j] = 0 df = pd.DataFrame( { "open": prices[:, j], "high": prices[:, j], "low": prices[:, j], "close": prices[:, j], "volume": volumes[:, j], }, index=dates, ) if writer: writer.write_sid(sid, df) trade_data[sid] = df return trade_data def check_allclose(actual, desired, rtol=1e-07, atol=0, err_msg='', verbose=True): """ Wrapper around np.testing.assert_allclose that also verifies that inputs are ndarrays. See Also -------- np.assert_allclose """ if type(actual) != type(desired): raise AssertionError("%s != %s" % (type(actual), type(desired))) return assert_allclose( actual, desired, atol=atol, rtol=rtol, err_msg=err_msg, verbose=verbose, ) def check_arrays(x, y, err_msg='', verbose=True, check_dtypes=True): """ Wrapper around np.testing.assert_array_equal that also verifies that inputs are ndarrays. See Also -------- np.assert_array_equal """ assert type(x) == type(y), "{x} != {y}".format(x=type(x), y=type(y)) assert x.dtype == y.dtype, "{x.dtype} != {y.dtype}".format(x=x, y=y) if isinstance(x, LabelArray): # Check that both arrays have missing values in the same locations... assert_array_equal( x.is_missing(), y.is_missing(), err_msg=err_msg, verbose=verbose, ) # ...then check the actual values as well. x = x.as_string_array() y = y.as_string_array() return assert_array_equal(x, y, err_msg=err_msg, verbose=verbose) class UnexpectedAttributeAccess(Exception): pass class ExplodingObject(object): """ Object that will raise an exception on any attribute access. Useful for verifying that an object is never touched during a function/method call. """ def __getattribute__(self, name): raise UnexpectedAttributeAccess(name) def write_minute_data(env, tempdir, minutes, sids): write_bcolz_minute_data( env, env.days_in_range(minutes[0], minutes[-1]), tempdir.path, create_minute_bar_data(minutes, sids), ) return tempdir.path def create_minute_bar_data(minutes, sids): length = len(minutes) for sid_idx, sid in enumerate(sids): yield sid, pd.DataFrame( { 'open': np.arange(length) + 10 + sid_idx, 'high': np.arange(length) + 15 + sid_idx, 'low': np.arange(length) + 8 + sid_idx, 'close': np.arange(length) + 10 + sid_idx, 'volume': np.arange(length) + 100 + sid_idx, }, index=minutes, ) def create_daily_bar_data(trading_days, sids): length = len(trading_days) for sid_idx, sid in enumerate(sids): yield sid, pd.DataFrame( { "open": (np.array(range(10, 10 + length)) + sid_idx), "high": (np.array(range(15, 15 + length)) + sid_idx), "low": (np.array(range(8, 8 + length)) + sid_idx), "close": (np.array(range(10, 10 + length)) + sid_idx), "volume": np.array(range(100, 100 + length)) + sid_idx, "day": [day.value for day in trading_days] }, index=trading_days, ) def write_daily_data(tempdir, sim_params, sids): path = os.path.join(tempdir.path, "testdaily.bcolz") BcolzDailyBarWriter(path, sim_params.trading_days).write( create_daily_bar_data(sim_params.trading_days, sids), ) return path def create_data_portal(env, tempdir, sim_params, sids, adjustment_reader=None): if sim_params.data_frequency == "daily": daily_path = write_daily_data(tempdir, sim_params, sids) equity_daily_reader = BcolzDailyBarReader(daily_path) return DataPortal( env, first_trading_day=equity_daily_reader.first_trading_day, equity_daily_reader=equity_daily_reader, adjustment_reader=adjustment_reader ) else: minutes = env.minutes_for_days_in_range( sim_params.first_open, sim_params.last_close ) minute_path = write_minute_data(env, tempdir, minutes, sids) equity_minute_reader = BcolzMinuteBarReader(minute_path) return DataPortal( env, first_trading_day=equity_minute_reader.first_trading_day, equity_minute_reader=equity_minute_reader, adjustment_reader=adjustment_reader ) def write_bcolz_minute_data(env, days, path, data): market_opens = env.open_and_closes.market_open.loc[days] market_closes = env.open_and_closes.market_close.loc[days] BcolzMinuteBarWriter( days[0], path, market_opens, market_closes, US_EQUITIES_MINUTES_PER_DAY ).write(data) def create_minute_df_for_asset(env, start_dt, end_dt, interval=1, start_val=1, minute_blacklist=None): asset_minutes = env.minutes_for_days_in_range(start_dt, end_dt) minutes_count = len(asset_minutes) minutes_arr = np.array(range(start_val, start_val + minutes_count)) df = pd.DataFrame( { "open": minutes_arr + 1, "high": minutes_arr + 2, "low": minutes_arr - 1, "close": minutes_arr, "volume": 100 * minutes_arr, }, index=asset_minutes, ) if interval > 1: counter = 0 while counter < len(minutes_arr): df[counter:(counter + interval - 1)] = 0 counter += interval if minute_blacklist is not None: for minute in minute_blacklist: df.loc[minute] = 0 return df def create_daily_df_for_asset(env, start_day, end_day, interval=1): days = env.days_in_range(start_day, end_day) days_count = len(days) days_arr = np.arange(days_count) + 2 df = pd.DataFrame( { "open": days_arr + 1, "high": days_arr + 2, "low": days_arr - 1, "close": days_arr, "volume": days_arr * 100, }, index=days, ) if interval > 1: # only keep every 'interval' rows for idx, _ in enumerate(days_arr): if (idx + 1) % interval != 0: df["open"].iloc[idx] = 0 df["high"].iloc[idx] = 0 df["low"].iloc[idx] = 0 df["close"].iloc[idx] = 0 df["volume"].iloc[idx] = 0 return df def trades_by_sid_to_dfs(trades_by_sid, index): for sidint, trades in iteritems(trades_by_sid): opens = [] highs = [] lows = [] closes = [] volumes = [] for trade in trades: opens.append(trade["open_price"]) highs.append(trade["high"]) lows.append(trade["low"]) closes.append(trade["close_price"]) volumes.append(trade["volume"]) yield sidint, pd.DataFrame( { "open": opens, "high": highs, "low": lows, "close": closes, "volume": volumes, }, index=index, ) def create_data_portal_from_trade_history(env, tempdir, sim_params, trades_by_sid): if sim_params.data_frequency == "daily": path = os.path.join(tempdir.path, "testdaily.bcolz") BcolzDailyBarWriter(path, sim_params.trading_days).write( trades_by_sid_to_dfs(trades_by_sid, sim_params.trading_days), ) equity_daily_reader = BcolzDailyBarReader(path) return DataPortal( env, first_trading_day=equity_daily_reader.first_trading_day, equity_daily_reader=equity_daily_reader, ) else: minutes = env.minutes_for_days_in_range( sim_params.first_open, sim_params.last_close ) length = len(minutes) assets = {} for sidint, trades in iteritems(trades_by_sid): opens = np.zeros(length) highs = np.zeros(length) lows = np.zeros(length) closes = np.zeros(length) volumes = np.zeros(length) for trade in trades: # put them in the right place idx = minutes.searchsorted(trade.dt) opens[idx] = trade.open_price * 1000 highs[idx] = trade.high * 1000 lows[idx] = trade.low * 1000 closes[idx] = trade.close_price * 1000 volumes[idx] = trade.volume assets[sidint] = pd.DataFrame({ "open": opens, "high": highs, "low": lows, "close": closes, "volume": volumes, "dt": minutes }).set_index("dt") write_bcolz_minute_data( env, env.days_in_range( sim_params.first_open, sim_params.last_close ), tempdir.path, assets ) equity_minute_reader = BcolzMinuteBarReader(tempdir.path) return DataPortal( env, first_trading_day=equity_minute_reader.first_trading_day, equity_minute_reader=equity_minute_reader, ) class FakeDataPortal(DataPortal): def __init__(self, env=None, first_trading_day=None): if env is None: env = TradingEnvironment() super(FakeDataPortal, self).__init__(env, first_trading_day) def get_spot_value(self, asset, field, dt, data_frequency): if field == "volume": return 100 else: return 1.0 def get_history_window(self, assets, end_dt, bar_count, frequency, field, ffill=True): if frequency == "1d": end_idx = self.env.trading_days.searchsorted(end_dt) days = \ self.env.trading_days[(end_idx - bar_count + 1):(end_idx + 1)] df = pd.DataFrame( np.full((bar_count, len(assets)), 100), index=days, columns=assets ) return df class FetcherDataPortal(DataPortal): """ Mock dataportal that returns fake data for history and non-fetcher spot value. """ def __init__(self, env, first_trading_day=None): super(FetcherDataPortal, self).__init__(env, first_trading_day) def get_spot_value(self, asset, field, dt, data_frequency): # if this is a fetcher field, exercise the regular code path if self._is_extra_source(asset, field, self._augmented_sources_map): return super(FetcherDataPortal, self).get_spot_value( asset, field, dt, data_frequency) # otherwise just return a fixed value return int(asset) def _get_daily_window_for_sid(self, asset, field, days_in_window, extra_slot=True): return np.arange(days_in_window, dtype=np.float64) def _get_minute_window_for_asset(self, asset, field, minutes_for_window): return np.arange(minutes_for_window, dtype=np.float64) class tmp_assets_db(object): """Create a temporary assets sqlite database. This is meant to be used as a context manager. Parameters ---------- **frames The frames to pass to the AssetDBWriter. By default this maps equities: ('A', 'B', 'C') -> map(ord, 'ABC') See Also -------- empty_assets_db tmp_asset_finder """ _default_equities = sentinel('_default_equities') def __init__(self, equities=_default_equities, **frames): self._eng = None if equities is self._default_equities: equities = make_simple_equity_info( list(map(ord, 'ABC')), pd.Timestamp(0), pd.Timestamp('2015'), ) frames['equities'] = equities self._frames = frames self._eng = None # set in enter and exit def __enter__(self): self._eng = eng = create_engine('sqlite://') AssetDBWriter(eng).write(**self._frames) return eng def __exit__(self, *excinfo): assert self._eng is not None, '_eng was not set in __enter__' self._eng.dispose() self._eng = None def empty_assets_db(): """Context manager for creating an empty assets db. See Also -------- tmp_assets_db """ return tmp_assets_db(equities=None) class tmp_asset_finder(tmp_assets_db): """Create a temporary asset finder using an in memory sqlite db. Parameters ---------- finder_cls : type, optional The type of asset finder to create from the assets db. **frames Forwarded to ``tmp_assets_db``. See Also -------- tmp_assets_db """ def __init__(self, finder_cls=AssetFinder, **frames): self._finder_cls = finder_cls super(tmp_asset_finder, self).__init__(**frames) def __enter__(self): return self._finder_cls(super(tmp_asset_finder, self).__enter__()) def empty_asset_finder(): """Context manager for creating an empty asset finder. See Also -------- empty_assets_db tmp_assets_db tmp_asset_finder """ return tmp_asset_finder(equities=None) class tmp_trading_env(tmp_asset_finder): """Create a temporary trading environment. Parameters ---------- finder_cls : type, optional The type of asset finder to create from the assets db. **frames Forwarded to ``tmp_assets_db``. See Also -------- empty_trading_env tmp_asset_finder """ def __enter__(self): return TradingEnvironment( asset_db_path=super(tmp_trading_env, self).__enter__().engine, ) def empty_trading_env(): return tmp_trading_env(equities=None) class SubTestFailures(AssertionError): def __init__(self, *failures): self.failures = failures def __str__(self): return 'failures:\n %s' % '\n '.join( '\n '.join(( ', '.join('%s=%r' % item for item in scope.items()), '%s: %s' % (type(exc).__name__, exc), )) for scope, exc in self.failures, ) def subtest(iterator, *_names): """ Construct a subtest in a unittest. Consider using ``zipline.testing.parameter_space`` when subtests are constructed over a single input or over the cross-product of multiple inputs. ``subtest`` works by decorating a function as a subtest. The decorated function will be run by iterating over the ``iterator`` and *unpacking the values into the function. If any of the runs fail, the result will be put into a set and the rest of the tests will be run. Finally, if any failed, all of the results will be dumped as one failure. Parameters ---------- iterator : iterable[iterable] The iterator of arguments to pass to the function. *name : iterator[str] The names to use for each element of ``iterator``. These will be used to print the scope when a test fails. If not provided, it will use the integer index of the value as the name. Examples -------- :: class MyTest(TestCase): def test_thing(self): # Example usage inside another test. @subtest(([n] for n in range(100000)), 'n') def subtest(n): self.assertEqual(n % 2, 0, 'n was not even') subtest() @subtest(([n] for n in range(100000)), 'n') def test_decorated_function(self, n): # Example usage to parameterize an entire function. self.assertEqual(n % 2, 1, 'n was not odd') Notes ----- We use this when we: * Will never want to run each parameter individually. * Have a large parameter space we are testing (see tests/utils/test_events.py). ``nose_parameterized.expand`` will create a test for each parameter combination which bloats the test output and makes the travis pages slow. We cannot use ``unittest2.TestCase.subTest`` because nose, pytest, and nose2 do not support ``addSubTest``. See Also -------- zipline.testing.parameter_space """ def dec(f): @wraps(f) def wrapped(*args, **kwargs): names = _names failures = [] for scope in iterator: scope = tuple(scope) try: f(*args + scope, **kwargs) except Exception as e: if not names: names = count() failures.append((dict(zip(names, scope)), e)) if failures: raise SubTestFailures(*failures) return wrapped return dec class MockDailyBarReader(object): def spot_price(self, col, sid, dt): return 100 def create_mock_adjustment_data(splits=None, dividends=None, mergers=None): if splits is None: splits = create_empty_splits_mergers_frame() elif not isinstance(splits, pd.DataFrame): splits = pd.DataFrame(splits) if mergers is None: mergers = create_empty_splits_mergers_frame() elif not isinstance(mergers, pd.DataFrame): mergers = pd.DataFrame(mergers) if dividends is None: dividends = create_empty_dividends_frame() elif not isinstance(dividends, pd.DataFrame): dividends = pd.DataFrame(dividends) return splits, mergers, dividends def create_mock_adjustments(tempdir, days, splits=None, dividends=None, mergers=None): path = tempdir.getpath("test_adjustments.db") SQLiteAdjustmentWriter(path, MockDailyBarReader(), days).write( *create_mock_adjustment_data(splits, dividends, mergers) ) return path def assert_timestamp_equal(left, right, compare_nat_equal=True, msg=""): """ Assert that two pandas Timestamp objects are the same. Parameters ---------- left, right : pd.Timestamp The values to compare. compare_nat_equal : bool, optional Whether to consider `NaT` values equal. Defaults to True. msg : str, optional A message to forward to `pd.util.testing.assert_equal`. """ if compare_nat_equal and left is pd.NaT and right is pd.NaT: return return pd.util.testing.assert_equal(left, right, msg=msg) def powerset(values): """ Return the power set (i.e., the set of all subsets) of entries in `values`. """ return concat(combinations(values, i) for i in range(len(values) + 1)) def to_series(knowledge_dates, earning_dates): """ Helper for converting a dict of strings to a Series of datetimes. This is just for making the test cases more readable. """ return pd.Series( index=pd.to_datetime(knowledge_dates), data=pd.to_datetime(earning_dates), ) def gen_calendars(start, stop, critical_dates): """ Generate calendars to use as inputs. """ all_dates = pd.date_range(start, stop, tz='utc') for to_drop in map(list, powerset(critical_dates)): # Have to yield tuples. yield (all_dates.drop(to_drop),) # Also test with the trading calendar. yield (trading_days[trading_days.slice_indexer(start, stop)],) @contextmanager def temp_pipeline_engine(calendar, sids, random_seed, symbols=None): """ A contextManager that yields a SimplePipelineEngine holding a reference to an AssetFinder generated via tmp_asset_finder. Parameters ---------- calendar : pd.DatetimeIndex Calendar to pass to the constructed PipelineEngine. sids : iterable[int] Sids to use for the temp asset finder. random_seed : int Integer used to seed instances of SeededRandomLoader. symbols : iterable[str], optional Symbols for constructed assets. Forwarded to make_simple_equity_info. """ equity_info = make_simple_equity_info( sids=sids, start_date=calendar[0], end_date=calendar[-1], symbols=symbols, ) loader = make_seeded_random_loader(random_seed, calendar, sids) get_loader = lambda column: loader with tmp_asset_finder(equities=equity_info) as finder: yield SimplePipelineEngine(get_loader, calendar, finder) def parameter_space(__fail_fast=False, **params): """ Wrapper around subtest that allows passing keywords mapping names to iterables of values. The decorated test function will be called with the cross-product of all possible inputs Usage ----- >>> from unittest import TestCase >>> class SomeTestCase(TestCase): ... @parameter_space(x=[1, 2], y=[2, 3]) ... def test_some_func(self, x, y): ... # Will be called with every possible combination of x and y. ... self.assertEqual(somefunc(x, y), expected_result(x, y)) See Also -------- zipline.testing.subtest """ def decorator(f): argspec = getargspec(f) if argspec.varargs: raise AssertionError("parameter_space() doesn't support *args") if argspec.keywords: raise AssertionError("parameter_space() doesn't support **kwargs") if argspec.defaults: raise AssertionError("parameter_space() doesn't support defaults.") # Skip over implicit self. argnames = argspec.args if argnames[0] == 'self': argnames = argnames[1:] extra = set(params) - set(argnames) if extra: raise AssertionError( "Keywords %s supplied to parameter_space() are " "not in function signature." % extra ) unspecified = set(argnames) - set(params) if unspecified: raise AssertionError( "Function arguments %s were not " "supplied to parameter_space()." % extra ) param_sets = product(*(params[name] for name in argnames)) if __fail_fast: @wraps(f) def wrapped(self): for args in param_sets: f(self, *args) return wrapped else: return subtest(param_sets, *argnames)(f) return decorator def create_empty_dividends_frame(): return pd.DataFrame( np.array( [], dtype=[ ('ex_date', 'datetime64[ns]'), ('pay_date', 'datetime64[ns]'), ('record_date', 'datetime64[ns]'), ('declared_date', 'datetime64[ns]'), ('amount', 'float64'), ('sid', 'int32'), ], ), index=pd.DatetimeIndex([], tz='UTC'), ) def create_empty_splits_mergers_frame(): return pd.DataFrame( np.array( [], dtype=[ ('effective_date', 'int64'), ('ratio', 'float64'), ('sid', 'int64'), ], ), index=pd.DatetimeIndex([]), ) @expect_dimensions(array=2) def permute_rows(seed, array): """ Shuffle each row in ``array`` based on permutations generated by ``seed``. Parameters ---------- seed : int Seed for numpy.RandomState array : np.ndarray[ndim=2] Array over which to apply permutations. """ rand = np.random.RandomState(seed) return np.apply_along_axis(rand.permutation, 1, array) @nottest def make_test_handler(testcase, *args, **kwargs): """ Returns a TestHandler which will be used by the given testcase. This handler can be used to test log messages. Parameters ---------- testcase: unittest.TestCase The test class in which the log handler will be used. *args, **kwargs Forwarded to the new TestHandler object. Returns ------- handler: logbook.TestHandler The handler to use for the test case. """ handler = TestHandler(*args, **kwargs) testcase.addCleanup(handler.close) return handler def write_compressed(path, content): """ Write a compressed (gzipped) file to `path`. """ with gzip.open(path, 'wb') as f: f.write(content) def read_compressed(path): """ Write a compressed (gzipped) file from `path`. """ with gzip.open(path, 'rb') as f: return f.read() zipline_git_root = abspath( join(realpath(dirname(__file__)), '..', '..'), ) @nottest def test_resource_path(*path_parts): return os.path.join(zipline_git_root, 'tests', 'resources', *path_parts) @contextmanager def patch_os_environment(remove=None, **values): """ Context manager for patching the operating system environment. """ old_values = {} remove = remove or [] for key in remove: old_values[key] = os.environ.pop(key) for key, value in values.iteritems(): old_values[key] = os.getenv(key) os.environ[key] = value try: yield finally: for old_key, old_value in old_values.iteritems(): if old_value is None: # Value was not present when we entered, so del it out if it's # still present. try: del os.environ[key] except KeyError: pass else: # Restore the old value. os.environ[old_key] = old_value class tmp_dir(TempDirectory, object): """New style class that wrapper for TempDirectory in python 2. """ pass class _TmpBarReader(with_metaclass(ABCMeta, tmp_dir)): """A helper for tmp_bcolz_minute_bar_reader and tmp_bcolz_daily_bar_reader. Parameters ---------- env : TradingEnvironment The trading env. days : pd.DatetimeIndex The days to write for. data : dict[int -> pd.DataFrame] The data to write. path : str, optional The path to the directory to write the data into. If not given, this will be a unique name. """ @abstractproperty def _reader_cls(self): raise NotImplementedError('_reader') @abstractmethod def _write(self, env, days, path, data): raise NotImplementedError('_write') def __init__(self, env, days, data, path=None): super(_TmpBarReader, self).__init__(path=path) self._env = env self._days = days self._data = data def __enter__(self): tmpdir = super(_TmpBarReader, self).__enter__() env = self._env try: self._write( env, self._days, tmpdir.path, self._data, ) return self._reader_cls(tmpdir.path) except: self.__exit__(None, None, None) raise class tmp_bcolz_minute_bar_reader(_TmpBarReader): """A temporary BcolzMinuteBarReader object. Parameters ---------- env : TradingEnvironment The trading env. days : pd.DatetimeIndex The days to write for. data : iterable[(int, pd.DataFrame)] The data to write. path : str, optional The path to the directory to write the data into. If not given, this will be a unique name. See Also -------- tmp_bcolz_daily_bar_reader """ _reader_cls = BcolzMinuteBarReader _write = staticmethod(write_bcolz_minute_data) class tmp_bcolz_daily_bar_reader(_TmpBarReader): """A temporary BcolzDailyBarReader object. Parameters ---------- env : TradingEnvironment The trading env. days : pd.DatetimeIndex The days to write for. data : dict[int -> pd.DataFrame] The data to write. path : str, optional The path to the directory to write the data into. If not given, this will be a unique name. See Also -------- tmp_bcolz_daily_bar_reader """ _reader_cls = BcolzDailyBarReader @staticmethod def _write(env, days, path, data): BcolzDailyBarWriter(path, days).write(data) @contextmanager def patch_read_csv(url_map, module=pd, strict=False): """Patch pandas.read_csv to map lookups from url to another. Parameters ---------- url_map : mapping[str or file-like object -> str or file-like object] The mapping to use to redirect read_csv calls. module : module, optional The module to patch ``read_csv`` on. By default this is ``pandas``. This should be set to another module if ``read_csv`` is early-bound like ``from pandas import read_csv`` instead of late-bound like: ``import pandas as pd; pd.read_csv``. strict : bool, optional If true, then this will assert that ``read_csv`` is only called with elements in the ``url_map``. """ read_csv = pd.read_csv def patched_read_csv(filepath_or_buffer, *args, **kwargs): if filepath_or_buffer in url_map: return read_csv(url_map[filepath_or_buffer], *args, **kwargs) elif not strict: return read_csv(filepath_or_buffer, *args, **kwargs) else: raise AssertionError( 'attempted to call read_csv on %r which not in the url map' % filepath_or_buffer, ) with patch.object(module, 'read_csv', patched_read_csv): yield
__version__ = "1.3" __author__ = "phpsh@googlegroups.com" __date__ = "Nov 20, 2008" from subprocess import Popen, PIPE from threading import Thread import ansicolor as clr import cmd_util as cu import ctags import ConfigParser import os import re import readline import select import signal import sys import tempfile import time comm_poll_timeout = 0.01 PHP_RESERVED_WORDS = [ # Include reserved words from # http://us3.php.net/manual/en/reserved.keywords.php "abstract", "and", "array", "as", "break", "case", "catch", "cfunction", "class", "clone", "const", "else", "continue", "declare", "default", "do", "else", "elseif", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "extends", "final", "for", "foreach", "function", "global", "goto", # (!) "if", "implements", "interface", "instanceof", "namespace", "new", "old_function", "or", "private", "protected", "public", "static", "switch", "throw", "try", "use", "var", "while", "xor", "__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__METHOD__", "__NAMESPACE__", "die", "echo", "empty", "exit", "eval", "include", "include_once", "isset", "list", "require", "require_once", "return", "print", "unset", ] def help_message(): return """\ -- Help -- Type php commands and they will be evaluted each time you hit enter. Ex: php> $msg = "hello world" Put = at the beginning of a line as syntactic sugar for return. Ex: php> = 2 + 2 4 phpsh will print any returned value (in yellow) and also assign the last returned value to the variable $_. Anything printed to stdout shows up blue, and anything sent to stderr shows up red. You can enter multiline input, such as a multiline if statement. phpsh will accept further lines until you complete a full statement, or it will error if your partial statement has no syntactic completion. You may also use ^C to cancel a partial statement. You can use tab to autocomplete function names, global variable names, constants, classes, and interfaces. If you are using ctags, then you can hit tab again after you've entered the name of a function, and it will show you the signature for that function. phpsh also supports all the normal readline features, like ctrl-e, ctrl-a, and history (up, down arrows). Note that stdout and stderr from the underlying php process are line-buffered; so php> for ($i = 0; $i < 3; $i++) {echo "."; sleep(1);} will print the three dots all at once after three seconds. (echo ".\n" would print one a second.) See phpsh -h for invocation options. -- phpsh quick command list -- h Display this help text. r Reload (e.g. after a code change). args to r append to add includes, like: php> r ../lib/username.php (use absolute paths or relative paths from where you start phpsh) R Like 'r', but change includes instead of appending. d Get documentation for a function or other identifier. ex: php> d my_function D Like 'd', but gives more extensive documentation for builtins. v Open vim read-only where a function or other identifer is defined. ex: php> v some_function V Open vim (not read-only) and reload (r) upon return to phpsh. e Open emacs where a function or other identifer is defined. ex: php> e some_function x [=]function([args]) Execute function() with args under debugger c Append new includes without restarting; display includes. C Change includes without restarting; display includes. ! Execute a shell command. ex: php> ! pwd q Quit (ctrl-D also quits) """ def do_sugar(line): line = line.lstrip() if line.startswith("="): line = "return " + line[1:] if line: line += ";" return line def line_encode(line): return cu.multi_sub({"\n": "\\n", "\\": "\\\\"}, line) + "\n" def inc_args(s): """process a string of includes to a set of them""" return set([inc.strip() for inc in s.split(" ") if inc.strip()]) def get_php_ext_path(): extension_dir = Popen("php-config | grep extension-dir", shell=True, stdout=PIPE, stderr=PIPE).communicate()[0] if extension_dir: lbr = extension_dir.find("[") rbr = extension_dir.find("]") if 0 < lbr < rbr: return extension_dir[lbr+1:rbr] def sigalrm_handler(sig, frame): raise OSError, "Alarm" class PhpMultiliner: """This encapsulates the process and state of intaking multiple input lines until a complete php expression is formed, or detecting a syntax error. Note: this is not perfectly encapsulated while the parser has global state """ complete = "complete" incomplete = "incomplete" syntax_error = "syntax_error" def __init__(self): self.partial = "" def check_syntax(self, line): p = Popen(["php", "-r", "return;" + line], stdout=PIPE, stderr=PIPE) p.wait() # "php -r" lint errors seem to only use stdout, but it might (idk) # depend on configuration or change later, so just grab everything. ls = p.stdout.readlines() + p.stderr.readlines() # hack so that missing extensions etc don't halt all phpsh use. # these php startup errors will still show at phpsh start up. ls = [l for l in ls if l.find("PHP Startup:") == -1] l = "".join(ls) if l: if l.find("unexpected $end") != -1: return (self.incomplete, "") return (self.syntax_error, l) return (self.complete, "") def input_line(self, line): if self.partial: self.partial += "\n" self.partial += line partial_mod = do_sugar(self.partial) if not partial_mod: return (self.complete, "") (syntax_info, _) = self.check_syntax(partial_mod) if syntax_info == self.complete: # Multiline inputs are encoded to one line. partial_mod = line_encode(partial_mod) self.clear() return (syntax_info, partial_mod) # We need to pull off the syntactic sugar ; to see if the line failed # the syntax check because of syntax_error, or because of incomplete. return self.check_syntax(partial_mod[:-1]) def clear(self): self.partial = "" class ProblemStartingPhp(Exception): def __init__(self, file_name=None, line_num=None, stdout_lines=None, stderr_lines=None): self.file_name = file_name self.line_num = line_num self.stdout_lines = stdout_lines self.stderr_lines = stderr_lines class PhpshConfig: def __init__(self): self.config = ConfigParser.RawConfigParser({ "UndefinedFunctionCheck": "yes", "Xdebug" : None, "DebugClient" : "emacs", "ClientTimeout" : 60, "ClientHost" : "localhost", "ClientPort" : None, "ProxyPort" : None, "Help" : "no", "LogDBGp" : "no", "ForegroundColor" : "black", "BackgroundColor" : "white", "InactiveColor" : "grey75", "InactiveMinimize": "yes", "FontFamily" : None, "FontSize" : None, "XdebugClientPath": "debugclient", "X11" : "yes"}) self.config.add_section("General") self.config.add_section("Debugging") self.config.add_section("Emacs") def read(self): config_files = ["/etc/phpsh/config"] home = os.getenv("HOME") if home: homestr = home.strip() if homestr: config_files.append(os.path.join(homestr, ".phpsh/config")) self.config.read(config_files) return self.config def get_option(self, s, o): if self.config.has_option(s, o): return self.config.get(s, o) else: return None def until_paren_close_balanced(s): lparens = 1 for i in range(len(s)): if s[i] == "(": lparens += 1 elif s[i] == ")": lparens -= 1 if lparens == 0: return s[:i] return s class LoadCtags(Thread): def __init__(self, phpsh_state): Thread.__init__(self) self.phpsh_state = phpsh_state def run(self): try: tags_file_path = None try: tags_file_path = ctags.find_tags_file() except ctags.CantFindTagsFile, e: return print self.phpsh_state.clr_cmd + \ "Loading ctags (in background)" + \ self.phpsh_state.clr_default self.phpsh_state.ctags = ctags.Ctags(tags_file_path) try: self.phpsh_state.function_signatures = \ ctags.CtagsFunctionSignatures().function_signatures except Exception, e: self.phpsh_state.function_signatures = {} print self.phpsh_state.clr_err + \ "Problem loading function signatures" + \ self.phpsh_state.clr_default except Exception, e: if tags_file_path: path = tags_file_path else: path = "" print self.phpsh_state.clr_err + \ "Problem loading ctags %(path)s\n(%(e)s)\n" % locals() + \ self.phpsh_state.clr_default class PhpshState: """This doesn't perfectly encapsulate state (e.g. the readline module has global state), but it is a step in the right direction and it already fulfills its primary objective of simplifying the notion of throwing a line of input (possibly only part of a full php line) at phpsh. """ php_prompt = "php> " php_more_prompt = " ... " no_command = "no_command" yes_command = "yes_command" quit_command = "quit_command" debug_command = "x " def __init__(self, cmd_incs, do_color, do_echo, codebase_mode, do_autocomplete, do_ctags, interactive, with_xdebug, verbose): """start phpsh.php and do other preparations (colors, ctags) """ self.phpsh_root = os.path.dirname(os.path.realpath(__file__)) self.do_echo = do_echo self.p_dbgp = None; # debugging proxy self.dbgp_port = 9000; # default port on which dbgp proxy listens self.temp_file_name = tempfile.mkstemp()[1] self.output_tempfile = None # tempfile to buffer php output self.with_xdebug = with_xdebug; self.verbose = verbose self.xdebug_path = None # path to xdebug.so read from config file self.xdebug_disabled_reason = None # why debugging was disabled self.to_dbgp = None # fds of pipe endpoints for writing commands self.from_dbgp = None # to dbgp proxy and reading replies # so many colors, so much awesome if not do_color: self.clr_cmd = "" self.clr_err = "" self.clr_help = "" self.clr_announce = "" self.clr_default = "" else: self.clr_cmd = clr.Green self.clr_err = clr.Red self.clr_help = clr.Green self.clr_announce = clr.Magenta self.clr_default = clr.Default self.config = PhpshConfig() try: self.config.read() except Exception, msg: self.print_error("Failed to load config file, using default "\ "settings: " + str(msg)) if self.with_xdebug: xdebug = self.config.get_option("Debugging", "Xdebug") if xdebug and xdebug != "yes": if xdebug == "no": self.with_xdebug = False self.xdebug_disabled_reason = \ "Xdebug is set to 'no' in config file" else: self.xdebug_path = xdebug self.comm_base = "php " if self.with_xdebug: xdebug_comm_base = self.comm_base php_ext_dir = get_php_ext_path() if php_ext_dir: if not self.xdebug_path: self.xdebug_path = php_ext_dir + "/xdebug.so" try: os.stat(self.xdebug_path) xdebug_comm_base += " -d \'zend_extension" if php_ext_dir.find("php/extensions/debug") >= 0: xdebug_comm_base += "_debug" xdebug_comm_base += "=\"" + self.xdebug_path + "\"\' " # The following is a workaround if role.ini is overly # restrictive. role.ini currently sets max nesting level # to 50 at facebook. xdebug_comm_base += "-d xdebug.max_nesting_level=500 " try: xdebug_version = self.get_xdebug_version( xdebug_comm_base) if xdebug_version < [2, 0, 3]: self.xdebug_disabled_reason = "\ Xdebug version %s is too low. xdebug-2.0.3 or above required." % \ xdebug_version self.with_xdebug = False except Exception, msg: self.xdebug_disabled_reason = self.xdebug_path + \ " is incompatible with your php build" self.with_xdebug = False except OSError: self.xdebug_disabled_reason = \ "xdebug.so not found, tried " + self.xdebug_path self.with_xdebug = False self.xdebug_path = None else: self.xdebug_disabled_reason = """\ Could not identify PHP extensions directory. Make sure php-config is in your PATH.""" self.with_xdebug = False self.xdebug_path = None if self.verbose and not self.with_xdebug and \ self.xdebug_disabled_reason: self.print_warning("PHP debugging will be disabled:\n" + self.xdebug_disabled_reason) if self.with_xdebug: self.comm_base = xdebug_comm_base self.start_xdebug_proxy() self.comm_base += self.phpsh_root + "/phpsh.php " + \ self.temp_file_name + " " + cu.arg_esc(codebase_mode) if not do_color: self.comm_base += " -c" if not do_autocomplete: self.comm_base += " -A" if self.config.get_option("General", "UndefinedFunctionCheck") == "no": self.comm_base += " -u" if not self.with_xdebug: self.comm_base += " -f" self.cmd_incs = cmd_incs # ctags integration self.ctags = None if do_ctags: LoadCtags(self).start() else: self.function_signatures = {} import rlcompleter input_rc_file = os.path.join(os.environ["HOME"], ".inputrc") if os.path.isfile(input_rc_file): readline.read_init_file(input_rc_file) readline.parse_and_bind("tab: complete") # persistent readline history # we set the history length to be something reasonable # so that we don't write a ridiculously huge file every time # someone executes a command home_phpsh_dir = os.path.join(os.environ["HOME"], ".phpsh") if not os.path.exists(home_phpsh_dir): os.mkdir(home_phpsh_dir) self.history_file = os.path.join(home_phpsh_dir, "history") readline.set_history_length(1000) try: readline.read_history_file(self.history_file) except IOError: # couldn't read history (probably one hasn't been created yet) pass self.autocomplete_identifiers = list(PHP_RESERVED_WORDS) self.autocomplete_cache = None self.autocomplete_match = None self.autocomplete_signature = None self.show_incs(start=True) self.php_open_and_check() def tab_complete(text, state): """The completer function is called as function(text, state), for state in 0, 1, 2, ..., until it returns a non-string value.""" if not text: # currently there is a segfault in readline when you complete # on nothing. so just don't allow completing on that for now. # in the long term, we may use ipython's prompt code instead # of readline return None if state == 0: self.autocomplete_cache = [] for identifier in self.autocomplete_identifiers: if identifier.startswith(text): self.autocomplete_cache.append(identifier) if self.function_signatures.has_key(text): for sig in self.function_signatures[text]: func_str = sig[1] if func_str[-1] == ",": file_contents = "".join( l[:-1] for l in file(sig[0]).readlines()) # this is not perfect but it should be good enough look_for = "function " + text + "(" i = file_contents.find(look_for) if i != -1: i_paren = func_str.find("(") if i_paren != -1: func_str = func_str[:i_paren + 1] i_end = i + len(look_for) s = until_paren_close_balanced( file_contents[i_end:]) s = re.sub(", +", ", ", s, 1000) func_str += s + ")" self.autocomplete_cache.append(func_str) try: return self.autocomplete_cache[state] except IndexError: return None readline.set_completer(tab_complete) # print welcome message if interactive: print self.clr_help + \ "type 'h' or 'help' to see instructions & features" + \ self.clr_default def get_xdebug_version(self, comm_base): vline, err = Popen(comm_base + \ " -r 'phpinfo();' | grep '^ *with Xdebug v[0-9][0-9.]*'", shell=True, stdout=PIPE, stderr=PIPE).communicate() if not vline: raise Exception, "Failed to load Xdebug\n" + err m = re.compile(" *with Xdebug v([0-9.]+)").match(vline) if not m: raise Exception, \ "Could not find xdebug version number in phpinfo() output" try: return [int(s) for s in m.group(1).strip(".").split(".")] except ValueError: raise ValueError, "invalid Xdebug version format: " + m.group(1) def start_xdebug_proxy(self): try: to_r, to_w = os.pipe() from_r, from_w = os.pipe() dbgp_py = ["dbgp-phpsh.py", str(to_r), str(to_w), str(from_r), str(from_w)] self.p_dbgp = Popen(dbgp_py) os.close(to_r) os.close(from_w) self.to_dbgp = os.fdopen(to_w, "w", 0) self.from_dbgp = os.fdopen(from_r, "r", 0) try: dbgp_status = self.from_dbgp.readline() if dbgp_status.startswith("initialized"): r = re.compile(".*port=([0-9]+).*") m = r.match(dbgp_status) if m: self.dbgp_port = m.group(1) else: self.to_dbgp.close() self.from_dbgp.close() self.p_dbgp = None self.with_xdebug = False self.xdebug_disabled_reason = "xdebug proxy " + dbgp_status except Exception, msg: self.print_error("\ Could not obtain initialization status from xdebug proxy: %s" % msg) self.to_dbgp.close() self.from_dbgp.close() self.p_dbgp = None self.with_xdebug = False except Exception, msg: self.print_error("Failed to start xdebug proxy: " + str(msg)) self.with_xdebug = False if self.verbose and not self.with_xdebug and \ self.xdebug_disabled_reason: self.print_warning("PHP debugging will be disabled:\n" + self.xdebug_disabled_reason) def print_error(self, msg): print self.clr_err + msg + self.clr_default def print_warning(self, msg): print self.clr_announce + msg + self.clr_default # pass expr to php for evaluation, wait for completion # if debug_funcall is True, the expression is being run under # debugger. def do_expr(self, expr, debug_funcall=False): defer_output = debug_funcall and (not os.getenv("DISPLAY") or \ self.config.get_option("Debugging", "X11") == "no") # if we are executing a function call under debugger and debug # client is running in the same terminal as phpsh, do not print # the output we get from php in terminal until evaluation is done # and debug client exits, so that we do not mess up the debug # client UI. self.p.stdin.write(expr) self.wait_for_comm_finish(defer_output) return self.result def wait_on_ready(self): while True: a = self.comm_file.readline() if a: break time.sleep(comm_poll_timeout) def php_open_and_check(self): self.p = None while not self.p: try: self.php_open() except ProblemStartingPhp, e: self.end_process() print(self.clr_cmd + """\ phpsh failed to initialize PHP. Fix the problem and hit enter to reload or ctrl-C to quit.""") if e.stdout_lines: print("PHP output: %(output)s" % {'output' : "\n".join(e.stdout_lines)}) if e.stderr_lines: print("PHP error output: %(output)s" % {'output' : "\n".join(e.stderr_lines)}) if e.line_num: print("\ Type 'e' to open emacs or 'V' to open vim to %s: %s" % (e.file_name, e.line_num)) print self.clr_default response = raw_input() if response == "V": editor = "vim" elif response == "e": editor = "emacs -nw" else: editor = "" if editor != "": Popen(editor + " +" + str(e.line_num) + " " + e.file_name, shell=True).wait() else: print self.clr_default raw_input() # this file is how phpsh.php tells us it is done with a command self.comm_file = open(self.temp_file_name) self.wait_on_ready() self.wait_for_comm_finish() def php_restart(self): if self.with_xdebug and self.p_dbgp: self.to_dbgp.write("run php\n") self.initialized_successfully = False self.end_process() return self.php_open_and_check() def php_open(self): self.autocomplete_identifiers = list(PHP_RESERVED_WORDS) cmd = " ".join([self.comm_base] + list(self.cmd_incs)) if self.with_xdebug: os.putenv("XDEBUG_CONFIG", "remote_port=" + str(self.dbgp_port) + " remote_enable=1"); self.p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) if self.with_xdebug: # disable remote debugging for other instances of php started by # this script, such as the multiline syntax verifyer os.putenv("XDEBUG_CONFIG", "remote_enable=0"); p_line = self.p.stdout.readline().rstrip() if p_line != "#start_autocomplete_identifiers": err_lines = self.p.stderr.readlines() out_lines = self.p.stdout.readlines() err_str = "\ UNKNOWN ERROR (maybe php build does not support signals/tokenizer?)" parse_error_re = re.compile( "PHP Parse error: .* in (.*) on line ([0-9]*)") m = None for line in reversed(err_lines): err_line = line.rstrip() m = parse_error_re.match(err_line) if m: err_str = err_line break print self.clr_err for err_line in err_lines: print err_line, print self.clr_default if m: file_name, line_num = m.groups() raise ProblemStartingPhp(file_name, line_num, stdout_lines=out_lines, stderr_lines=err_lines) else: raise ProblemStartingPhp(stdout_lines=out_lines, stderr_lines=err_lines) while True: p_line = self.p.stdout.readline().rstrip() if p_line == "#end_autocomplete_identifiers": break self.autocomplete_identifiers.append(p_line) def wait_for_comm_finish(self, defer_output=False): try: if defer_output: if self.output_tempfile: self.output_tempfile.truncate(0) else: self.output_tempfile = tempfile.TemporaryFile() out = self.output_tempfile err = self.output_tempfile else: out = sys.stdout err = sys.stderr # wait for signal that php command is done # keep checking for death out_buff = ["", ""] buffer_size = 4096 self.result = "" died = False debug = False #debug = True while True: if debug: print "polling" ret_code = self.p.poll() if debug: print "ret_code: " + str(ret_code) if ret_code != None: if debug: print "NOOOOO" print "subprocess died with return code: " + repr(ret_code) died = True break while not died: # line-buffer stdout and stderr if debug: print "start loop" s = select.select([self.p.stdout, self.p.stderr], [], [], comm_poll_timeout) if s == ([], [], []): if debug: print "empty" break if debug: print s[0] for r in s[0]: if r is self.p.stdout: out_buff_i = 0 else: out_buff_i = 1 buff = os.read(r.fileno(), buffer_size) if not buff: died = True break out_buff[out_buff_i] += buff last_nl_pos = out_buff[out_buff_i].rfind("\n") if last_nl_pos != -1: l = out_buff[out_buff_i][:last_nl_pos + 1] self.result += l if self.do_echo: if r is self.p.stdout: out.write(l) else: l = self.clr_err + l + self.clr_default err.write(l) out_buff[out_buff_i] = \ out_buff[out_buff_i][last_nl_pos + 1:] # at this point either: # the php instance died # select timed out l = self.comm_file.readline() if l.startswith("child"): ret_code = self.p.poll() os.kill(self.p.pid, signal.SIGHUP) self.p.pid = int(l.split()[1]) elif l.startswith("ready"): break time.sleep(comm_poll_timeout) if defer_output and self.output_tempfile.tell() > 0: self.output_tempfile.seek(0, os.SEEK_SET) for line in self.output_tempfile: print line if died: self.show_incs("PHP died. ") self.php_open_and_check() except KeyboardInterrupt: self.show_incs("Interrupt! ") if defer_output and self.output_tempfile.tell() > 0: self.output_tempfile.seek(0, os.SEEK_SET) for line in self.output_tempfile: print line self.php_restart() def show_incs(self, pre_str="", restart=True, start=False): s = self.clr_cmd + pre_str inc_str = str(list(self.cmd_incs)) if start or restart: if start: start_word = "Starting" else: start_word = "Restarting" if self.cmd_incs: s += start_word + " php with extra includes: " + inc_str else: s += start_word + " php" else: s += "Extra includes are: " + inc_str print s + self.clr_default def try_command(self, line): if line == "r" or line.startswith("r "): # add args to phpsh.php (includes), reload self.cmd_incs = self.cmd_incs.union(inc_args(line[2:])) self.show_incs() self.php_restart() elif line == "R" or line.startswith("R "): # change args to phpsh.php (includes), reload self.cmd_incs = inc_args(line[2:]) self.show_incs() self.php_restart() elif line == "c" or line.startswith("c "): # add args to phpsh.php (includes) self.cmd_incs = self.cmd_incs.union(inc_args(line[2:])) self.show_incs(restart=False) self.p.stdin.write("\n") elif line == "C" or line.startswith("C "): # change args to phpsh.php (includes) self.cmd_incs = inc_args(line[2:]) self.show_incs(restart=False) self.p.stdin.write("\n") elif line.startswith("d ") or line.startswith("D "): identifier = line[2:] if identifier.startswith("$"): identifier = identifier[1:] print self.clr_help lookup_tag = False ctags_error = "ctags not enabled" try: if self.ctags: tags = self.ctags.py_tags[identifier] ctags_error = None lookup_tag = True except KeyError: ctags_error = "no ctag info found for '" + identifier + "'" if lookup_tag: print repr(tags) for t in tags: try: file = self.ctags.tags_root + os.path.sep + t["file"] doc = "" append = False line_num = 0 for line in open(file): line_num += 1 if not append: if line.find("/*") != -1: append = True doc_start_line = line_num if append: if line.find(t["context"]) != -1: print ("%s, lines %d-%d:" % (file, doc_start_line, line_num)) print doc break if line.find("*") == -1: append = False doc = "" else: doc += line except: pass import manual manual_ret = manual.get_documentation_for_identifier(identifier, short=line.startswith("d ")) if manual_ret: print manual_ret if not manual_ret and ctags_error: print "could not find in php manual and " + ctags_error print self.clr_default elif line.startswith("v "): self.editor_tag(line[2:], "vim", read_only=True) elif line.startswith("V "): self.editor_tag(line[2:], "vim") elif line.startswith("e "): self.editor_tag(line[2:], "emacs") elif line.startswith("x "): if self.with_xdebug and self.p_dbgp: return PhpshState.debug_command else: self.print_warning("PHP debugging is disabled") if self.xdebug_disabled_reason: self.print_warning(self.xdebug_disabled_reason) return PhpshState.yes_command elif line.startswith("!"): # shell command Popen(line[1:], shell=True).wait() elif line == "h" or line == "help": print self.clr_help + help_message() + self.clr_default elif line == "q" or line == "exit" or line == "exit;": return self.quit_command else: return self.no_command return self.yes_command # check if line is of the form "=?<function-name>(<args>?)" # if it is, send it to the DBGp proxy and if the proxy reports # that it is ready to start debugging, return True. Otherwise # return False. def setup_debug_client(self, funcall): # extract function name and optional leading "=" from line if funcall.startswith("return "): funcall = funcall[6:].lstrip() m = re.compile(" *([A-Za-z_][A-Za-z0-9_]*) *[(]").match(funcall) if not m: self.print_error("Invalid function call syntax") return False dbgp_cmd = "x " + m.group(1) try: self.to_dbgp.write(dbgp_cmd + "\n") # TODO: put a timeout on this: dbgp_reply = self.from_dbgp.readline() if dbgp_reply != "ready\n": self.print_error("xdebug proxy error: " + dbgp_reply) return False except Exception, msg: self.print_error("Failed to communicate with xdebug proxy, "\ "disabling PHP debugging: " + str(msg)) self.to_dbgp.close() self.from_dbgp.close() self.p_dbgp = None self.with_xdebug = False return False # return PHP code to pass to PHP for eval return True def editor_tag(self, tag, editor, read_only=False): if tag.startswith("$"): tag = tag[1:] def not_found(): print self.clr_cmd + "no tag '" + tag + "' found" + self.clr_default self.p.stdin.write("\n") if not self.ctags.py_tags.has_key(tag): not_found() return if editor == "emacs": t = self.ctags.py_tags[tag][0] # get line number (or is there a way to start emacs at a # particular tag location?) try: file = self.ctags.tags_root + os.path.sep + t["file"] doc = "" append = False line_num = 1 found_tag = False for line in open(file): line_num += 1 if line.find(t["context"]) != -1: emacs_line = line_num found_tag = True break except: pass if found_tag: # -nw opens it in the terminal instead of using X cmd = "emacs -nw +%d %s" % (emacs_line, file) p_emacs = Popen(cmd, shell=True) p_emacs.wait() self.p.stdin.write("\n") else: not_found() return else: if read_only: vim = "vim -R" else: vim = "vim" vim += ' -c "set tags=' + self.ctags.tags_file + '" -t ' p_vim = Popen(vim + tag, shell=True) p_vim.wait() self.p.stdin.write("\n") if not read_only: self.show_incs() self.php_open_and_check() def write(self): try: readline.write_history_file(self.history_file) except IOError, e: print >> sys.stderr, \ "Could not write history file %s: %s" % \ (self.history_file, e) def close(self): self.write() print self.clr_default os.remove(self.temp_file_name) self.end_process(True) def end_process(self, alarm=False): # shutdown php, if it doesn't exit in 5s, kill -9 if alarm: signal.signal(signal.SIGALRM, sigalrm_handler) # if we have fatal-restart prevention, the child proess can't be waited # on since it's no longer a child of this process try: self.p.stdout.close() self.p.stderr.close() self.p.stdin.close() if alarm: signal.alarm(5) os.waitpid(self.p.pid, 0) except (IOError, OSError, KeyboardInterrupt): os.kill(self.p.pid, signal.SIGKILL) # collect the zombie try: os.waitpid(self.p.pid, 0) except (OSError): pass self.p = None
""" Functions: binreg binreg_raw check_output find_binreg_20 format_data_files format_pref_file format_exec_file format_predictions is_logged_array_data log_matrix_if_needed ## Moved to matrixlib. #align_rows # WAS align_matrices #align_cols #are_rows_aligned # is_matrices_aligned #are_cols_aligned #describe_unaligned_rows # #read_matrices #merge_gct_matrices #merge_matrices strip_affx_control_probes Classes: BinregParams """ import os class BinregParams: def __init__( self, binreg_version=None, cross_validate=None, make_plots=None, num_genes=None, num_metagenes=None, quantile_normalize=None, shift_scale_normalize=None, num_burnin=None, num_iterations=None, num_skips=None, credible_interval=None): # Set defaults if binreg_version is None: binreg_version = 2 if cross_validate is None: cross_validate = 1 if make_plots is None: make_plots = 0 if num_genes is None: num_genes = 100 if num_metagenes is None: num_metagenes = 2 if quantile_normalize is None: quantile_normalize = 1 if shift_scale_normalize is None: shift_scale_normalize = 1 if num_burnin is None: num_burnin = 1000 if num_iterations is None: num_iterations = 5000 if num_skips is None: num_skips = 1 if credible_interval is None: credible_interval = 95 # Make sure inputs are valid. assert binreg_version in [1, 2] assert cross_validate in [0, 1] assert make_plots in [0, 1] assert num_genes > 0 assert num_metagenes > 0 assert quantile_normalize in [0, 1] assert shift_scale_normalize in [0, 1] assert num_burnin >= 0 assert num_iterations > 0 assert num_skips >= 0 assert credible_interval >= 0 and credible_interval <= 100 self.binreg_version = binreg_version self.cross_validate = cross_validate self.make_plots = make_plots self.num_genes = num_genes self.num_metagenes = num_metagenes self.quantile_normalize = quantile_normalize self.shift_scale_normalize = shift_scale_normalize self.num_burnin = num_burnin self.num_iterations = num_iterations self.num_skips = num_skips self.credible_interval = credible_interval def binreg(train0, train1, test, is_logged, params, matlab=None, binreg_path=None, outpath=None): outpath = outpath or "." desc_file = os.path.join(outpath, "description.txt") express_file = os.path.join(outpath, "expression.txt") x = format_data_files(train0, train1, test) open(desc_file, 'w').write(x[0]) open(express_file, 'w').write(x[1]) x = binreg_raw( express_file, desc_file, is_logged, params, matlab=matlab, binreg_path=binreg_path, outpath=outpath) return x def binreg_raw(expression_file, description_file, is_logged, params, matlab=None, binreg_path=None, outpath=None): # expression_file contains a gene x sample matrix of the # expression values. There should be no headers. The first row # contains 0/1/2 depending on whether the sample is train0, # train1, or test. The description_file contains a list of the # gene names or probeset IDs and should be parallel to the # expression_file. import subprocess # Set defaults. matlab = matlab or "matlab" outpath = outpath or "." binreg_path = find_binreg_20(binreg_path) pref_file = os.path.join(outpath, "preferences.dat") assert binreg_path is not None, "I could not find Binreg 2.0" binreg_path = os.path.realpath(binreg_path) pref_file = os.path.realpath(pref_file) # Check parameters. assert os.path.exists(expression_file), "Missing: %s" % expression_file assert os.path.exists(description_file), "Missing: %s" % description_file assert is_logged in [0, 1] assert binreg_path, "I could not find a complete BinReg 2.0 distribution." x = format_pref_file(expression_file, description_file, is_logged, params) open(pref_file, 'w').write(x) # Run Binreg from Matlab. cwd = os.getcwd() try: os.chdir(outpath) matlab_args = [ "-nosplash", "-nodesktop", "-nodisplay", "-nojvm"] x = " ".join(matlab_args) cmd = "%s %s" % (matlab, x) #w, r = os.popen4(cmd, bufsize=0) p = subprocess.Popen( cmd, shell=True, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) w, r = p.stdin, p.stdout x = format_exec_file(binreg_path, pref_file) w.write(x) w.close() finally: os.chdir(cwd) return r def check_output(output): if output.find("??? Index exceeds matrix dimensions.") >= 0 and \ output.find("Error in ==> select_genes_cor at 9") >= 0: raise AssertionError, "Not enough genes for model." def find_binreg_20(default_path): # Return the path to BinReg2.0 or None. import config search_paths = [ default_path, config.binreg20_path, "BinReg2.0", ] path = None for spath in search_paths: assert path is None if spath is None or not os.path.exists(spath): continue # Test for some well-known Binreg files. files = [ "binreg.m", "binreg_batch.m", "Mbinregsvd.m", "README.txt", "quantnorm.m", "std_rows_to_y.m", "Binreg2.0.Matlab.tutorial.ppt"] complete = True # Is this distribution complete. for file_ in files: filename = os.path.join(spath, file_) if not os.path.exists(filename): complete = False break if not complete: continue path = spath break return path def format_data_files(train0, train1, test): # test can be None. from StringIO import StringIO import arrayio import matrixlib assert train0.nrow() > 0 and train0.ncol() > 0 assert train1.nrow() > 0 and train1.ncol() > 0 assert not test or (test.nrow() > 0 and test.ncol() > 0) assert matrixlib.are_rows_aligned(train0, train1), "matrices not aligned" assert not test or matrixlib.are_rows_aligned(train0, test), \ "matrices not aligned" X_train0 = train0.value() X_train1 = train1.value() if test: X_test = test.value() # Merge the matrices. X_all = [] x = [0]*len(X_train0[0]) + [1]*len(X_train1[0]) if test: x = x + [2]*len(X_test[0]) X_all.append(x) for i in range(len(X_train0)): x = X_train0[i] + X_train1[i] if test: x = x + X_test[i] X_all.append(x) # Write the description file. ids = train0.row_names(arrayio.ROW_ID) desc_handle = StringIO() for id_ in ids: print >>desc_handle, id_ desc_handle.seek(0) desc_str = desc_handle.read() # Write the expression_file express_handle = StringIO() for x in X_all: print >>express_handle, "\t".join(map(str, x)) express_handle.seek(0) express_str = express_handle.read() return desc_str, express_str #def _escape_filename(filename): # if " " in filename: # return "'%s'" % filename # return filename def format_pref_file(expression_file, description_file, is_logged, params): # Return a string with the formatted preference file. expression_file = os.path.realpath(expression_file) description_file = os.path.realpath(description_file) # Don't need to escape spaces in filename. Filenames are one per # line, so delimited by newlines. #e = _escape_filename x = [ expression_file, description_file, params.num_genes, params.num_metagenes, params.num_burnin, params.num_iterations, params.num_skips, params.credible_interval, is_logged, params.quantile_normalize, params.shift_scale_normalize, params.binreg_version, params.cross_validate, params.make_plots, ] x = map(str, x) x = "\n".join(x) + "\n" return x def format_exec_file(binreg_path, pref_file): from StringIO import StringIO handle = StringIO() w = handle.write # The BinReg gamrnd needs to mask the Matlab builtin, so add the # binreg path to the beginning. The functions give different # results. w("addpath '%s' -begin;\n" % binreg_path) #w("addpath '%s' -end;\n" % binreg_path) w("binreg_batch('%s');\n" % pref_file) w("quit;\n") handle.seek(0) return handle.read() def format_predictions(train0, train1, test, outpath=None): # Return a string. test can be None. from StringIO import StringIO import arrayio import filelib outpath = outpath or "." opj = os.path.join fitted_file = opj(outpath, "trainingcases.txt") xval_file = opj(outpath, "crossvalidation.txt") predict_file = opj(outpath, "validationcases.txt") assert os.path.exists(fitted_file), "Missing trainingcases.txt." assert os.path.exists(xval_file), "Missing crossvalidation.txt." if test: assert os.path.exists(predict_file), "Missing validationcases.txt." samples = train0.col_names(arrayio.COL_ID)+train1.col_names(arrayio.COL_ID) if test: samples = samples + test.col_names(arrayio.COL_ID) format_ = "index:d type:d prob:f lower_ci:f upper_ci:f mgene:f" d_fit = [d for d in filelib.read_row(fitted_file, format_)] d_xval = [d for d in filelib.read_row(xval_file, format_)] d_pred = [] if test: d_pred = [d for d in filelib.read_row(predict_file, format_)] assert len(d_fit) == len(d_xval) # crossvalidation.txt + validationcases.txt assert len(d_xval)+len(d_pred) == len(samples) # Make the types pretty. type_str = ["train0", "train1", "test"] for d in d_fit+d_xval+d_pred: assert d.type in [0, 1, 2], "Unknown type: %d" % d.Type d.type = type_str[d.type] # Add the method. for d in d_xval+d_pred: d.method = "PREDICTED" for d in d_fit: d.method = "FITTED" # Add the sample names. for i in range(len(d_fit)): d_fit[i].sample = samples[i] d_xval[i].sample = samples[i] for i in range(len(d_pred)): d_pred[i].sample = samples[i+len(d_fit)] # Indexes here are 0-based. handle = StringIO() header = ["Index", "Sample", "Type", "Method", "Probability", "Lower CI", "Upper CI", "Metagene"] print >>handle, "\t".join(header) for i, d in enumerate(d_fit+d_xval+d_pred): x = (d.index-1, d.sample, d.type, d.method, d.prob, d.lower_ci, d.upper_ci, d.mgene) print >>handle, "\t".join(map(str, x)) handle.seek(0) return handle.read() def is_logged_array_data(data): CUTOFF = 1000 # Count the number of scores greater than the cutoff. nrow, ncol = data.dim() assert nrow >= 2000, "No enough genes to determine log status." X = data.slice() total = nrow * ncol num_greater = 0 for i in range(nrow): for j in range(ncol): if X[i][j] >= CUTOFF: num_greater += 1 # If all scores < CUTOFF, then is logged. if num_greater == 0: return True # If a portion of the scores >= CUTOFF, then is not logged. #if num_greater >= 10 or float(num_greater)/total >= 0.10: if num_greater >= 10 or float(num_greater)/total >= 0.01: return False # If only a few scores >= CUTOFF, then maybe there's an error in the file. raise AssertionError, "Detected some outliers [%d:%d]. Log?" % ( num_greater, total) def log_matrix_if_needed(DATA): import jmath if is_logged_array_data(DATA): return DATA DATA = DATA.matrix() DATA._X = jmath.log(DATA._X, base=2, safe=1) return DATA def strip_affx_control_probes(DATA, psid_header=None): # psid_header should be the header that contains the Probe Set IDs. import arrayio import hashlib header = psid_header or arrayio.ROW_ID ID = hashlib.hash_many_geneids(DATA.row_names(header)) ID_at = [x for x in ID if x.endswith("_at")] ID_good = [x for x in ID if not x.startswith("affx")] assert ID, "No IDs." assert ID_at, "IDs do not look like Affymetrix IDs." assert ID_good, "I could not find any non-control probes." # Get the non-AFFX IDs. DATA_s = DATA.matrix(row=ID_good, row_header=header) return DATA_s
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import logging import os import signal import sys import time from swift import gettext_ as _ from random import random, shuffle from tempfile import mkstemp from eventlet import spawn, patcher, Timeout import swift.common.db from swift.container.backend import ContainerBroker, DATADIR from swift.common.bufferedhttp import http_connect from swift.common.exceptions import ConnectionTimeout from swift.common.ring import Ring from swift.common.utils import get_logger, config_true_value, ismount, \ dump_recon_cache, quorum_size, Timestamp from swift.common.daemon import Daemon from swift.common.http import is_success, HTTP_INTERNAL_SERVER_ERROR class ContainerUpdater(Daemon): """Update container information in account listings.""" def __init__(self, conf): self.conf = conf self.logger = get_logger(conf, log_route='container-updater') self.devices = conf.get('devices', '/srv/node') self.mount_check = config_true_value(conf.get('mount_check', 'true')) self.swift_dir = conf.get('swift_dir', '/etc/swift') self.interval = int(conf.get('interval', 300)) self.account_ring = None self.concurrency = int(conf.get('concurrency', 4)) self.slowdown = float(conf.get('slowdown', 0.01)) self.node_timeout = float(conf.get('node_timeout', 3)) self.conn_timeout = float(conf.get('conn_timeout', 0.5)) self.no_changes = 0 self.successes = 0 self.failures = 0 self.account_suppressions = {} self.account_suppression_time = \ float(conf.get('account_suppression_time', 60)) self.new_account_suppressions = None swift.common.db.DB_PREALLOCATION = \ config_true_value(conf.get('db_preallocation', 'f')) self.recon_cache_path = conf.get('recon_cache_path', '/var/cache/swift') self.rcache = os.path.join(self.recon_cache_path, "container.recon") self.user_agent = 'container-updater %s' % os.getpid() def get_account_ring(self): """Get the account ring. Load it if it hasn't been yet.""" if not self.account_ring: self.account_ring = Ring(self.swift_dir, ring_name='account') return self.account_ring def _listdir(self, path): try: return os.listdir(path) except OSError as e: self.logger.error(_('ERROR: Failed to get paths to drive ' 'partitions: %s') % e) return [] def get_paths(self): """ Get paths to all of the partitions on each drive to be processed. :returns: a list of paths """ paths = [] for device in self._listdir(self.devices): dev_path = os.path.join(self.devices, device) if self.mount_check and not ismount(dev_path): self.logger.warning(_('%s is not mounted'), device) continue con_path = os.path.join(dev_path, DATADIR) if not os.path.exists(con_path): continue for partition in self._listdir(con_path): paths.append(os.path.join(con_path, partition)) shuffle(paths) return paths def _load_suppressions(self, filename): try: with open(filename, 'r') as tmpfile: for line in tmpfile: account, until = line.split() until = float(until) self.account_suppressions[account] = until except Exception: self.logger.exception( _('ERROR with loading suppressions from %s: ') % filename) finally: os.unlink(filename) def run_forever(self, *args, **kwargs): """ Run the updator continuously. """ time.sleep(random() * self.interval) while True: self.logger.info(_('Begin container update sweep')) begin = time.time() now = time.time() expired_suppressions = \ [a for a, u in self.account_suppressions.items() if u < now] for account in expired_suppressions: del self.account_suppressions[account] pid2filename = {} # read from account ring to ensure it's fresh self.get_account_ring().get_nodes('') for path in self.get_paths(): while len(pid2filename) >= self.concurrency: pid = os.wait()[0] try: self._load_suppressions(pid2filename[pid]) finally: del pid2filename[pid] fd, tmpfilename = mkstemp() os.close(fd) pid = os.fork() if pid: pid2filename[pid] = tmpfilename else: signal.signal(signal.SIGTERM, signal.SIG_DFL) patcher.monkey_patch(all=False, socket=True, select=True, thread=True) self.no_changes = 0 self.successes = 0 self.failures = 0 self.new_account_suppressions = open(tmpfilename, 'w') forkbegin = time.time() self.container_sweep(path) elapsed = time.time() - forkbegin self.logger.debug( _('Container update sweep of %(path)s completed: ' '%(elapsed).02fs, %(success)s successes, %(fail)s ' 'failures, %(no_change)s with no changes'), {'path': path, 'elapsed': elapsed, 'success': self.successes, 'fail': self.failures, 'no_change': self.no_changes}) sys.exit() while pid2filename: pid = os.wait()[0] try: self._load_suppressions(pid2filename[pid]) finally: del pid2filename[pid] elapsed = time.time() - begin self.logger.info(_('Container update sweep completed: %.02fs'), elapsed) dump_recon_cache({'container_updater_sweep': elapsed}, self.rcache, self.logger) if elapsed < self.interval: time.sleep(self.interval - elapsed) def run_once(self, *args, **kwargs): """ Run the updater once. """ patcher.monkey_patch(all=False, socket=True, select=True, thread=True) self.logger.info(_('Begin container update single threaded sweep')) begin = time.time() self.no_changes = 0 self.successes = 0 self.failures = 0 for path in self.get_paths(): self.container_sweep(path) elapsed = time.time() - begin self.logger.info(_( 'Container update single threaded sweep completed: ' '%(elapsed).02fs, %(success)s successes, %(fail)s failures, ' '%(no_change)s with no changes'), {'elapsed': elapsed, 'success': self.successes, 'fail': self.failures, 'no_change': self.no_changes}) dump_recon_cache({'container_updater_sweep': elapsed}, self.rcache, self.logger) def container_sweep(self, path): """ Walk the path looking for container DBs and process them. :param path: path to walk """ for root, dirs, files in os.walk(path): for file in files: if file.endswith('.db'): self.process_container(os.path.join(root, file)) time.sleep(self.slowdown) def process_container(self, dbfile): """ Process a container, and update the information in the account. :param dbfile: container DB to process """ start_time = time.time() broker = ContainerBroker(dbfile, logger=self.logger) info = broker.get_info() # Don't send updates if the container was auto-created since it # definitely doesn't have up to date statistics. if Timestamp(info['put_timestamp']) <= 0: return if self.account_suppressions.get(info['account'], 0) > time.time(): return if info['put_timestamp'] > info['reported_put_timestamp'] or \ info['delete_timestamp'] > info['reported_delete_timestamp'] \ or info['object_count'] != info['reported_object_count'] or \ info['bytes_used'] != info['reported_bytes_used']: container = '/%s/%s' % (info['account'], info['container']) part, nodes = self.get_account_ring().get_nodes(info['account']) events = [spawn(self.container_report, node, part, container, info['put_timestamp'], info['delete_timestamp'], info['object_count'], info['bytes_used'], info['storage_policy_index']) for node in nodes] successes = 0 for event in events: if is_success(event.wait()): successes += 1 if successes >= quorum_size(len(events)): self.logger.increment('successes') self.successes += 1 self.logger.debug( _('Update report sent for %(container)s %(dbfile)s'), {'container': container, 'dbfile': dbfile}) broker.reported(info['put_timestamp'], info['delete_timestamp'], info['object_count'], info['bytes_used']) else: self.logger.increment('failures') self.failures += 1 self.logger.debug( _('Update report failed for %(container)s %(dbfile)s'), {'container': container, 'dbfile': dbfile}) self.account_suppressions[info['account']] = until = \ time.time() + self.account_suppression_time if self.new_account_suppressions: print(info['account'], until, file=self.new_account_suppressions) # Only track timing data for attempted updates: self.logger.timing_since('timing', start_time) else: self.logger.increment('no_changes') self.no_changes += 1 def container_report(self, node, part, container, put_timestamp, delete_timestamp, count, bytes, storage_policy_index): """ Report container info to an account server. :param node: node dictionary from the account ring :param part: partition the account is on :param container: container name :param put_timestamp: put timestamp :param delete_timestamp: delete timestamp :param count: object count in the container :param bytes: bytes used in the container :param storage_policy_index: the policy index for the container """ with ConnectionTimeout(self.conn_timeout): try: headers = { 'X-Put-Timestamp': put_timestamp, 'X-Delete-Timestamp': delete_timestamp, 'X-Object-Count': count, 'X-Bytes-Used': bytes, 'X-Account-Override-Deleted': 'yes', 'X-Backend-Storage-Policy-Index': storage_policy_index, 'user-agent': self.user_agent} conn = http_connect( node['ip'], node['port'], node['device'], part, 'PUT', container, headers=headers) except (Exception, Timeout): self.logger.exception(_( 'ERROR account update failed with ' '%(ip)s:%(port)s/%(device)s (will retry later): '), node) return HTTP_INTERNAL_SERVER_ERROR with Timeout(self.node_timeout): try: resp = conn.getresponse() resp.read() return resp.status except (Exception, Timeout): if self.logger.getEffectiveLevel() <= logging.DEBUG: self.logger.exception( _('Exception with %(ip)s:%(port)s/%(device)s'), node) return HTTP_INTERNAL_SERVER_ERROR finally: conn.close()
import Cookie import datetime import sys import time import traceback from wsgiref.handlers import format_date_time from gevent import event from . import protocol DEFAULT_DELTA = datetime.timedelta(days=365) def enable_cors(environ, headers): """ Return a list of HTTP headers that will support cross domain requests. :param environ: The WSGI environ dict. :param headers: List of current HTTP headers. Headers are passed in via reference rather than returning as an optimisation. """ origin = environ.get('HTTP_ORIGIN', '*') if origin == 'null': origin = '*' request_headers = environ.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', None) if request_headers: headers.append(('Access-Control-Allow-Headers', request_headers)) headers.extend([ ('Access-Control-Allow-Origin', origin), ('Access-Control-Allow-Credentials', 'true') ]) def disable_cache(headers): """ Return a list of HTTP Headers that will ensure the response is not cached. :param headers: List of HTTP headers. """ headers.append( ('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ) def enable_cache(headers, delta=None, now=datetime.datetime.utcnow): """ Return a list of HTTP Headers that will ensure the response is cached. :param delta: A timedelta instance. Will default to 1 year if not specified. """ delta = delta or DEFAULT_DELTA delta_seconds = delta.total_seconds() expires = now() + delta expires_timestamp = time.mktime(expires.timetuple()) headers.extend([ ('Cache-Control', 'max-age=%d, public' % (delta_seconds,)), ('Expires', format_date_time(expires_timestamp)), ('Access-Control-Max-Age', str(int(delta_seconds))) ]) def enable_cookie(environ, headers): """ Return a list of HTTP Headers that will ensure a sticky cookie that load balancers can use to ensure that the request goes to the same backend server. """ cookies = Cookie.SimpleCookie(environ.get('HTTP_COOKIE')) c = cookies.get('JSESSIONID') if not c: cookies['JSESSIONID'] = 'dummy' c = cookies.get('JSESSIONID') c['path'] = '/' headers.append( ('Set-Cookie', cookies.output(header='').strip()) ) def get_headers(environ, content_type=None, cors=False, cache=None, cookie=False): headers = [] if content_type: if ';' not in content_type: content_type += '; encoding=UTF-8' headers.append( ('Content-Type', content_type) ) if cors: enable_cors(environ, headers) if cache is not None: if cache: enable_cache(headers) else: disable_cache(headers) if cookie: enable_cookie(environ, headers) return headers class BaseHandler(object): """ Wraps a WSGI environ dict and start_response combo with a nice api. """ __slots__ = ( 'environ', 'start_response', ) def __init__(self, environ, start_response): self.environ = environ self.start_response = start_response def write_response(self, content, status='200 OK', headers=None, **kwargs): headers = get_headers(self.environ, **kwargs) + (headers or []) writer = self.start_response(status, headers) writer(content or '') return writer def handle_options(self, *allowed_methods, **kwargs): method = self.environ['REQUEST_METHOD'].upper() allowed_methods = ['OPTIONS'] + list(allowed_methods) if method != 'OPTIONS': if method in allowed_methods: return False self.not_allowed(allowed_methods) return True headers = kwargs.pop('headers', None) or [] headers.append( ('Access-Control-Allow-Methods', ', '.join(allowed_methods)) ) self.write_nothing( cache=True, cookie=True, cors=True, headers=headers, **kwargs ) return True def write_text(self, content, **kwargs): return self.write_response( content, content_type='text/plain', **kwargs ) def write_html(self, content, **kwargs): return self.write_response( content, content_type='text/html', **kwargs ) def write_js(self, content, **kwargs): if not isinstance(content, basestring): content = protocol.encode(content) return self.write_response( content, content_type='application/json', **kwargs ) def write_nothing(self, **kwargs): return self.write_response(None, status='204 No Content', **kwargs) def not_allowed(self, valid_methods, **kwargs): headers = kwargs.pop('headers', []) headers.extend([ ('Allow', ', '.join(valid_methods)), ('Connection', 'close'), ]) kwargs['headers'] = headers return self.write_response(None, status='405 Not Allowed', **kwargs) def bad_request(self, msg=None, **kwargs): """ Return a 400 Bad Request response """ return self.write_response(msg, status='400 Bad Request', **kwargs) def not_modified(self, **kwargs): """ Return a 304 Not Modified response """ return self.write_response(None, status='304 Not Modified', **kwargs) def not_found(self, message=None, status='404 Not Found', cookie=True, content_type='text/plain'): """ Do a 404 NOT FOUND response. """ return self.write_response( message or '404 Error: Not Found', status=status, content_type=content_type, cookie=cookie ) def format_exception(self, exc_type, exc_value, exc_tb): stack_trace = traceback.format_exception(exc_type, exc_value, exc_tb) return str('\n'.join(stack_trace)) def internal_error(self, message=None, exc_info=None, trace=False, **kwargs): """ Return a 500 Internal Server Error response. """ if not message: if trace: if not exc_info: exc_info = sys.exc_info() if exc_info: message = self.format_exception(*exc_info) return self.write_response( message, status='500 Internal Server Error', content_type='text/plain', **kwargs ) def waitany(events, timeout=None, result_class=event.AsyncResult): result = result_class() update = result.set try: for event in events: if not event.started: event.start() if event.ready(): return event else: event.rawlink(update) return result.get(timeout=timeout) finally: for event in events: event.unlink(update)
""" @file comm_bt_command_mnode.py """ ## # @addtogroup bluetooth bluetooth # @brief This is bluetooth component # @{ # @addtogroup comm_bt_command comm_bt_command # @brief This is comm_bt_command module # @{ ## import os import time import subprocess from oeqa.runtime.bluetooth import bluetooth from oeqa.oetest import oeRuntimeTest from oeqa.utils.helper import shell_cmd_timeout from oeqa.utils.helper import get_files_dir from oeqa.utils.decorators import tag @tag(TestType="FVT") class CommBTTestMNode(oeRuntimeTest): """ @class CommBTTestMNode """ @classmethod def setUpClass(cls): '''Copy gatttool to /tmp/ folder @fn setUpClass @param cls @return ''' bt1=bluetooth.BTFunction(cls.tc.targets[0]) bt2=bluetooth.BTFunction(cls.tc.targets[1]) copy_to_path = os.path.join(get_files_dir(), 'gatttool') cls.tc.targets[0].copy_to(copy_to_path, "/tmp/") bt1.target.run('chmod +x /tmp/gatttool') bt2.target.run('chmod +x /tmp/gatttool') def setUp(self): """ @fn setUp @param self @return """ self.bt1 = bluetooth.BTFunction(self.targets[0]) self.bt2 = bluetooth.BTFunction(self.targets[1]) self.bt1.target_hciconfig_init() self.bt2.target_hciconfig_init() @tag(FeatureID="IOTOS-456") def test_bt_gatt_read_primary(self): '''Use gatttool to show remote primary attr handles @fn test_bt_gatt_read_primary @param self @return ''' for i in range(3): self.bt2.target_hciconfig_init() self.bt2.set_leadv() (status, output) = self.bt1.gatt_basic_check(self.bt2.get_bt_mac(), 'primary') if status == 0: break self.assertEqual(status, 0, msg="gatttool Primary is wrong: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_gatt_read_characteristics(self): '''Use gatttool to show target characteristics handles @fn test_bt_gatt_read_characteristics @param self @return ''' for i in range(3): self.bt2.target_hciconfig_init() self.bt2.set_leadv() (status, output) = self.bt1.gatt_basic_check(self.bt2.get_bt_mac(), 'characteristics') if status == 0: break self.assertEqual(status, 0, msg="gatttool characteristics fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_gatt_read_handle(self): '''Use gatttool to read target handle value @fn test_bt_gatt_read_handle @param self @return ''' for i in range(3): self.bt2.target_hciconfig_init() self.bt2.set_leadv() (status, output) = self.bt1.gatt_basic_check(self.bt2.get_bt_mac(), 'handle') if status == 0: break self.assertEqual(status, 0, msg="gatttool read handle fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_gatt_connect(self): '''Use gatttool interactive mode to do connect @fn test_bt_gatt_connect @param self @return ''' for i in range(3): self.bt2.target_hciconfig_init() self.bt2.set_leadv() (status, output) = self.bt1.gatt_basic_check(self.bt2.get_bt_mac(), 'connect') if status == 2: break self.assertEqual(status, 2, msg="gatttool connect fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_remote_gatt_read_primary(self): '''Use gatttool to show host primary attr handles @fn test_bt_remote_gatt_read_primary @param self @return ''' for i in range(3): self.bt1.target_hciconfig_init() self.bt1.set_leadv() (status, output) = self.bt2.gatt_basic_check(self.bt1.get_bt_mac(), 'primary') if status == 0: break self.assertEqual(status, 0, msg="gatttool be read primary fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_remote_gatt_read_characteristics(self): '''Use gatttool to show host characteristics handles @fn test_bt_remote_gatt_read_characteristics @param self @return ''' for i in range(3): self.bt1.target_hciconfig_init() self.bt1.set_leadv() (status, output) = self.bt2.gatt_basic_check(self.bt1.get_bt_mac(), 'characteristics') if status == 0: break self.assertEqual(status, 0, msg="gatttool be read characteristics fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_remote_gatt_read_handle(self): '''Use gatttool to read host handle value @fn test_bt_remote_gatt_read_handle @param self @return ''' for i in range(3): self.bt1.target_hciconfig_init() self.bt1.set_leadv() (status, output) = self.bt2.gatt_basic_check(self.bt1.get_bt_mac(), 'handle') if status == 0: break self.assertEqual(status, 0, msg="gatttool be read handle fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_remote_gatt_connect(self): '''Use gatttool interactive mode to do connect to host @fn test_bt_remote_gatt_connect @param self @return ''' for i in range(3): self.bt1.target_hciconfig_init() self.bt1.set_leadv() (status, output) = self.bt2.gatt_basic_check(self.bt1.get_bt_mac(), 'connect') if status == 2: break self.assertEqual(status, 2, msg="gatttool be connected fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_visible(self): '''Do traditional visible and be scanned by other (not ble scan) @fn test_bt_visible @param self @return ''' self.bt1.target.run('hciconfig hci0 noleadv') for i in range(3): # For init function already set visible status, directly be scanned. exp = os.path.join(os.path.dirname(__file__), "files/bt_scan.exp") cmd = "expect %s %s %s" % (exp, self.bt2.target.ip, self.bt1.get_bt_mac()) status, output = shell_cmd_timeout(cmd, timeout=100) if status == 2: break if type(output) is bytes: output = output.decode("ascii") self.assertEqual(status, 2, msg="Scan remote device fails: %s" % output) @tag(FeatureID="IOTOS-456") def test_bt_scan(self): '''Scan nearby bluetooth devices (not ble scan) @fn test_bt_scan @param self @return ''' self.bt2.target.run('hciconfig hci0 noleadv') for i in range(3): # For init function already set visible status, directly be scanned. exp = os.path.join(os.path.dirname(__file__), "files/bt_scan.exp") cmd = "expect %s %s %s" % (exp, self.bt1.target.ip, self.bt2.get_bt_mac()) status, output = shell_cmd_timeout(cmd, timeout=100) if status == 2: break if type(output) is bytes: output = output.decode("ascii") self.assertEqual(status, 2, msg="Scan remote device fails: %s" % output) @tag(FeatureID="IOTOS-759") def test_bt_le_advertising(self): '''Target does LE advertising, another device scans it @fn test_bt_le_advertising @param self @return ''' for i in range(3): # close legacy iscan mode self.bt1.target.run('hciconfig hci0 noscan') # begin low-energy scan self.bt1.target.run('hciconfig hci0 leadv') time.sleep(1) # Another device starts bluetoothctl to scan target exp = os.path.join(os.path.dirname(__file__), "files/bt_scan.exp") cmd = "expect %s %s %s" % (exp, self.bt2.target.ip, self.bt1.get_bt_mac()) status, output = shell_cmd_timeout(cmd, timeout=100) if status == 2: break else: self.bt1.target.run('hciconfig hci0 reset') time.sleep(3) if type(output) is bytes: output = output.decode("ascii") self.assertEqual(status, 2, msg="Be LE-scanned fails: %s" % output) @tag(FeatureID="IOTOS-770") def test_bt_le_scan(self): '''Another device (host) does LE advertising, target scans it @fn test_bt_le_scan @param self @return ''' for i in range(3): # close legacy iscan mode self.bt2.target.run('hciconfig hci0 noscan') # begin low-energy scan self.bt2.target.run('hciconfig hci0 leadv') time.sleep(1) # Device starts bluetoothctl to scan others exp = os.path.join(os.path.dirname(__file__), "files/bt_scan.exp") cmd = "expect %s %s %s" % (exp, self.bt1.target.ip, self.bt2.get_bt_mac()) status, output = shell_cmd_timeout(cmd, timeout=100) if status == 2: break else: self.bt2.target.run('hciconfig hci0 reset') time.sleep(3) if type(output) is bytes: output = output.decode("utf-8") self.assertEqual(status, 2, msg="LE Scan other fails: %s" % output) @tag(FeatureID="IOTOS-453") def test_bt_pairing(self): '''Use bluetoothctl to pair IoT device with host @fn test_bt_pairing @param self @return ''' # On remote, start pair_slave in back-ground slave_exp = os.path.join(os.path.dirname(__file__), "files/bt_pair_slave_on_iot.exp") cmd = "%s %s %s" % (slave_exp, self.bt2.target.ip, self.bt1.get_bt_mac()) subprocess.Popen(cmd, shell=True) # On target, perform pair_master master_exp = os.path.join(os.path.dirname(__file__), "files/bt_pair_master.exp") cmd = "expect %s %s %s" % (master_exp, self.bt1.target.ip, self.bt2.get_bt_mac()) for i in range(3): (status, output) = shell_cmd_timeout(cmd, timeout=200) if status == 2: break if type(output) is bytes: output = output.decode("utf-8") self.assertEqual(status, 2, msg="expect excution fail: %s" % output) # On target, check paired devices to see if IoT is in check_exp = os.path.join(os.path.dirname(__file__), "files/bt_list_paired_device.exp") (status, output) = shell_cmd_timeout("%s %s | grep '^Device %s'" % (check_exp, self.bt1.target.ip, self.bt2.get_bt_mac()), timeout=20) self.assertEqual(status, 0, msg="Not found IoT device paired") ## # @} # @} ##
#!/usr/bin/env python import platform if platform.python_implementation() == "PyPy": import sys sys.path.insert(0, '/usr/lib/python2.7/dist-packages') import argparse import csv import fileinput import itertools import json import logging import logging.config import networkx as nx import sys from distances import * from clean_text import clean_text def load_bigrams(unigrams_path, bigrams_path): unigrams = {} bigrams = {} with open(unigrams_path) as f: first = False for row in csv.reader(f): if not first: first = True continue unigrams[row[0]] = (int(row[1]), float(row[3])) with open(bigrams_path) as f: first = False for row in csv.reader(f): if not first: first = True continue bigrams[tuple(map(int, row[0:2]))] = float(row[2]) return unigrams, bigrams def load_tweets(path): tweets = [] tweet_ids = set() with open(path) as f: for row in f.readlines(): tweet = json.loads(row) if tweet['id'] in tweet_ids: continue else: tweet_ids.add(tweet['id']) tweets.append(tweet) return tweets def distance_matrix(unigrams, bigrams, tweets): # Prepare tweets prepare = lambda t: clean_text(t['text']).split() tweet_text = map(prepare, tweets) # Build the distance matrix # distances = [[(x, y, compute_distance(unigrams, bigrams, tweets[x], tweets[y])) for y in xrange(len(tweets)) if y > x] for x in xrange(len(tweets))] distances = [[(x, y, compute_shared_proba(unigrams, bigrams, tweet_text[x], tweet_text[y])) for y in xrange(len(tweets)) if x < y] for x in xrange(len(tweets))] return distances def write_to_file(): data = list(itertools.chain(*distances)) with open("tweets-dists.csv", "w") as f: for x, y, dist in data: f.write("%d, %d, %f\n" % (x, y, dist)) with open("tweets-dists.dot", "w") as f: f.write("graph G {\n") f.write("overlap=false;\n") for x, y, dist in data: f.write("%d -- %d [label=\"%f\"];\n" % (x, y, dist)) f.write("}\n") def graph_cutting(tweets, distances, skip, selector, cutoff): data = list(itertools.chain(*distances)) G = nx.Graph() for x, y, dist in data: if x not in skip and y not in skip and x < y and selector(x) and selector(y) and dist > cutoff: G.add_edge(x, y, weight=dist) components = nx.connected_components(G) clusters = filter(lambda c: len(c) > 2, components) def from_many_users(cluster): return len(set(map(lambda c: tweets[c]['user']['id'], cluster))) > 1 clusters = filter(from_many_users, clusters) skip.update(itertools.chain(*clusters)) return clusters def compute_clusters(old_tweets, new_tweets, distances): #data.sort(key=lambda x: x[2]) N_old_tweets = len(old_tweets) N_new_tweets = len(new_tweets) all_tweets = old_tweets + new_tweets is_old = lambda x: x<N_old_tweets is_new = lambda x: x>=N_old_tweets # Compute old clusters skip = set() old_clusters = graph_cutting(all_tweets, distances, skip, is_old, 50) if len(old_clusters) < 10: old_clusters.extend(graph_cutting(all_tweets, distances, skip, is_old, 30)) logger.debug("#old clusters@30: %d", len(old_clusters)) if len(old_clusters) < 10: old_clusters.extend(graph_cutting(all_tweets, distances, skip, is_old, 20)) logger.debug("#old clusters@20: %d", len(old_clusters)) base = len(old_clusters) if len(old_clusters) < 5: for i in range(N_old_tweets): if i not in skip: old_clusters.append([i]) skip.add(i) logger.info("#old clusters: %d", len(old_clusters)) logger.debug("tweets in old clusters: %d", len(skip)) # Compute new clusters new_clusters = graph_cutting(all_tweets, distances, skip, is_new, 100) if len(new_clusters) < 10: new_clusters.extend(graph_cutting(all_tweets, distances, skip, is_new, 50)) logger.debug("#new clusters@50: %d", len(new_clusters)) if len(new_clusters) < 10: new_clusters.extend(graph_cutting(all_tweets, distances, skip, is_new, 30)) logger.debug("#new clusters@30: %d", len(new_clusters)) if len(new_clusters) < 10: new_clusters.extend(graph_cutting(all_tweets, distances, skip, is_new, 20)) logger.info("#new clusters: %d", len(new_clusters)) logger.debug("tweets in new clusters: %d", len(skip)) return old_clusters, new_clusters def get_distance(x, y, distances): if x > y: return get_distance(y, x, distances) return distances[x][y-x-1][2] def mean_cluster_distance(cluster1, old_tweet, distances): distance = 0 for n1 in cluster1: distance += get_distance(n1, old_tweet, distances) return distance / float(len(cluster1)) def reverse_clusters(clusters): reverse = {} for i in range(len(clusters)): for t in clusters[i]: reverse[t] = i return reverse class MatchingStats(object): def __init__(self): self.cluster_distances = [] self.new_cluster_old_cluster_match = 0 self.new_cluster_no_old_match = 0 self.old_cluster_no_new_match = 0 def add_distance(self, d): self.cluster_distances.append(d) def add_match(self, new_index, old_index): if new_index >= 0 and old_index >= 0: self.new_cluster_old_cluster_match += 1 elif new_index < 0: self.old_cluster_no_new_match += 1 elif old_index < 0: self.new_cluster_no_old_match += 1 def log(self, logger): logger.info("Clusters matched: new-old %d, new-0 %d, 0-old %d", self.new_cluster_old_cluster_match, self.new_cluster_no_old_match, self.old_cluster_no_new_match) self.cluster_distances.sort() logger.debug("Distance distribution: min %f, 1st quartile %f, " "median %f, mean %f, 3rd quartile %f, max %f", min(self.cluster_distances), self.cluster_distances[len(self.cluster_distances)/4], self.cluster_distances[len(self.cluster_distances)/2], sum(self.cluster_distances)/float(len(self.cluster_distances)), self.cluster_distances[(3*len(self.cluster_distances))/4], max(self.cluster_distances)) def matching_clusters(new_clusters, old_tweets, old_clusters, distances): reversed_old = reverse_clusters(old_clusters) matches = {} skip = set() stats = MatchingStats() for new_index in range(len(new_clusters)): cluster_matches = [] for old_tweet in range(len(old_tweets)): d = mean_cluster_distance( new_clusters[new_index], old_tweet, distances) stats.add_distance(d) if d > 10: old_cluster = -1 if old_tweet in reversed_old: old_cluster = reversed_old[old_tweet] skip.add(old_cluster) cluster_matches.append((old_tweet, d, new_index, old_cluster)) stats.add_match(new_index, old_cluster) matches[new_index] = cluster_matches for old_index in range(len(old_clusters)): if old_index in skip: continue matches[-old_index] = map(lambda t: (t, 1, -1, old_index), old_clusters[old_index]) stats.add_match(-1, old_index) stats.log(logger) return matches def print_matched_tweets(output_path, old_tweets, matches): output = [] for matched_old_tweets in matches.values(): for tweet_index, val, new_index, old_index in matched_old_tweets: output.append((old_tweets[tweet_index], val, new_index, old_index)) with open(output_path, "w") as f: json.dump(output, f) parser = argparse.ArgumentParser(description="Selects tweets") parser.add_argument("--unigrams", default="data/unigrams.csv", help="Unigram input file") parser.add_argument("--bigrams", default="data/bigrams.csv", help="Bigrams input file") parser.add_argument("--input_old", default="data/tweets.json", help="Old tweets input file") parser.add_argument("--input_new", default="data/tweets.json", help="New tweets input file") parser.add_argument("--output", default="data/output.json", help="Tweets output file") parser.add_argument("--debug", action='store_true', default=False, help="Log debug information") args = parser.parse_args() logging.config.fileConfig('data/logging.conf') logger = logging.getLogger('selection') unigrams, bigrams = load_bigrams(args.unigrams, args.bigrams) old_tweets = load_tweets(args.input_old) new_tweets = load_tweets(args.input_new) distances = distance_matrix(unigrams, bigrams, old_tweets+new_tweets) #write_to_file() #hierarchical_clusters() old_clusters, new_clusters = compute_clusters(old_tweets, new_tweets, distances) matches = matching_clusters(new_clusters, old_tweets, old_clusters, distances) print_matched_tweets(args.output, old_tweets, matches)
# -*- coding: utf-8 -*- ''' @author: Gabriele Girelli @contact: gigi.ga90@gmail.com @description: statistic operations library. ''' # DEPENDENCIES ================================================================= import math import matplotlib.pyplot as plt import numpy as np from scipy import stats from pygpseq import const from pygpseq.tools import vector as vt # FUNCTIONS ==================================================================== def angle_between_points( p0, c, p1 ): ''' c is the center point; result is in degrees From http://phrogz.net/angle-between-three-points ''' p0 = np.array(p0) c = np.array(c) p1 = np.array(p1) p0c = np.sqrt(np.sum((p0 - c)**2)) p1c = np.sqrt(np.sum((p1 - c)**2)) p01 = np.sqrt(np.sum((p0 - p1)**2)) tetha = math.acos( (p0c**2 + p1c**2 - p01**2) / (2 * p0c * p1c) ) return(tetha / math.pi * 180) def binned_mode(x, nbins): """Identify binned mode. Args: x (np.array): dataset. nbins (int): number of bins. Returns: int: the most occupied bin in the provided dataset. """ if 0 == len(x): return(np.nan) # Bin breaks breaks = np.linspace(0, max(x), nbins) # Assign data to the bins assigned_bins = np.digitize(x, breaks) # Count bins occurrences occ = vt.uniquec(assigned_bins) counts = np.array([e[1] for e in occ]) # Order counts ordered = np.argsort(counts).tolist() ordered.reverse() occ = [occ[i] for i in ordered] # Return mode return(breaks[occ[0][0] - 1]) def binned_profile(x, y, nbins = None): """Produce an approximation of sparse data by binning it. Args: x (numeric): x coordinates. y (numeric): y coordinates. nbins (int): curve precision (opt, def: 200). Returns: np.array: profiles. """ if None == nbins: nbins = 200 # Check format y = np.array(y) # Bin breaks breaks = np.linspace(0, max(x), nbins) # Assign data to the bins assigned_bins = np.digitize(x, breaks) # Get mean and median for every bin data = np.zeros((len(breaks),), dtype = [('breaks', 'f'), ('mean', 'f'), ('median', 'f'), ('std', 'f'), ('mode', 'f'), ('max', 'f'), ('mean_raw', 'f'), ('median_raw', 'f'), ('std_raw', 'f'), ('mode_raw', 'f'), ('max_raw', 'f'), ('n', 'f')]) for bin_id in range(assigned_bins.max()): where = np.where(assigned_bins == bin_id) data['breaks'][bin_id] = breaks[bin_id] if 0 != where[0].shape[0]: data['mean'][bin_id] = np.mean(y[where]) data['median'][bin_id] = np.median(y[where]) data['mode'][bin_id] = binned_mode(y[where], nbins) data['std'][bin_id] = np.std(y[where]) data['max'][bin_id] = np.max(y[where]) data['n'][bin_id] = len(y[where]) else: data['mean'][bin_id] = np.nan data['median'][bin_id] = np.nan data['mode'][bin_id] = np.nan data['std'][bin_id] = np.nan data['max'][bin_id] = np.nan data['n'][bin_id] = 0 # Output return(data) def calc_density(data, **kwargs): """ Calculate the Gaussian KDE of the provided data series. Args: sigma_density (float): standard deviation used for covariance calculation. nbins (int): #steps for the density curve calculation (opt, def: 1000). Returns: dict: density curve (x, y) and function (f). """ # Default values if not 'sigma_density' in kwargs.keys(): sigma_density = .1 else: sigma_density = kwargs['sigma_density'] if not 'nbins' in kwargs.keys(): nbins = 1000 else: nbins = kwargs['nbins'] # If only one nucleus was found if 1 == len(data): f = eval('lambda x: 1 if x == ' + str(data[0]) + ' else 0') f = np.vectorize(f) return({ 'x' : np.array([data[0]]), 'y' : np.array([1]), 'f' : f }) # Prepare density function density = stats.gaussian_kde(data) # Re-compute covariance density.covariance_factor = lambda : sigma_density density._compute_covariance() # Output out = {} out['x'] = np.linspace(min(data), max(data), nbins) out['f'] = density out['y'] = density(out['x']) return(out) def calc_theta(a, b): ''' Calculate rotation angle based on a (opposite) and b (adjacent) sides. Return: float: theta in rad. ''' c = np.sqrt(a**2 + b**2) if a > 0 and b < 0: return(np.arccos(a / c)) elif a < 0 and b > 0: return(-np.arccos(a / c)) elif a < 0 and b < 0: return(np.arccos(a / c)) else: return(-np.arccos(a / c)) def centered_coords_3d(img, dot_coords = None): ''' Extract coordinates from binary image and center them on the origin. Args: img (nd.array): binary image. ''' z, x, y = np.nonzero(img) if not type(None) == type(dot_coords): zd, xd, yd = dot_coords xd = xd - np.mean(x) yd = yd - np.mean(y) zd = zd - np.mean(z) x = x - np.mean(x) y = y - np.mean(y) z = z - np.mean(z) if not type(None) == type(dot_coords): return((x, y, z, xd, yd, zd)) else: return((x, y, z, None, None, None)) def extract_3ev(coords): ''' Extract 3 major eigen vectors. Args: coords (nd.array): coordinates table with one point per row. Returns: tuple: major 3 eigen vectors. Coordinate order matches input columns. ''' cov = np.cov(coords) evals, evecs = np.linalg.eig(cov) sort_indices = np.argsort(evals)[::-1] a_v1, b_v1, c_v1 = evecs[:, sort_indices[0]] a_v2, b_v2, c_v2 = evecs[:, sort_indices[1]] a_v3, b_v3, c_v3 = evecs[:, sort_indices[2]] av = [a_v1, a_v2, a_v3] bv = [b_v1, b_v2, b_v3] cv = [c_v1, c_v2, c_v3] return((av, bv, cv)) def get_fwhm(xs, ys): """Calculate FWHM of highest peak in a curve. Args: xs (np.array): x-coordinates of the curve. ys (np.array): y-coordinates of the curve. Returns: list: FWHM interval x-coords of highest peak. """ # CHECK PARAMS ============================================================= # Must have the same length if len(xs) != len(ys): return(None) if 1 == len(ys): return([xs[0] - 1, xs[0] + 1]) # GET FWHM ================================================================= # Identify highest peak xmaxi = ys.tolist().index(max(ys)) # Get FWHM range [left] ---------------------------------------------------- if 0 != xmaxi: # Get absolute difference to HM value x1 = abs(ys[range(xmaxi)] - max(ys) / 2) # Get threshold based on average distance of consecutive points if 1 == len(x1): thr = x1[0] else: thr = np.max(abs(np.diff(x1))) # Select values close to the HM (based on threshold and abs difference) selected = [i for i in range(len(x1)) if x1[i] <= thr] # Select left boundary if 0 == len(selected): x1 = xs[range(xmaxi)][x1.tolist().index(min(x1))] else: x1 = xs[range(xmaxi)][max(selected)] else: x1 = min(xs) # Get FWHM range [right] --------------------------------------------------- if len(xs) != (xmaxi + 1): # Get absolute difference to HM value x2 = abs(ys[range(xmaxi + 1, len(ys))] - max(ys) / 2) # Get threshold based on average distance of consecutive points if 1 == len(x2): thr = x2[0] else: thr = np.max(abs(np.diff(x2))) # Select values close to the HM (based on threshold and abs difference) selected = [i for i in range(len(x2)) if x2[i] <= thr] # Select right boundary if 0 == len(selected): x2 = xs[range(xmaxi + 1, len(xs))][x2.tolist().index(min(x2))] else: x2 = xs[range(xmaxi + 1, len(xs))][min(selected)] else: x2 = max(xs) # Output return([x1, x2]) def get_intercepts(ys, xs = None): """Given a series of y coordinates, identify the x-axis intercept. Args: ys (numeric): y coordinates series. xs (numeric): x coordinates series (optional). Returns: int: index of x-axis intercepting y (if xs == None). numeric: x coordinates interpolated point of intersection with x-axis. """ # Return no intercept if no data was provided if 0 == len(ys): return([]) # Will contain the intercepts (pairs of) indexes out = [] # Reformat coordinate series ys = np.array(ys) # Count ys nys = ys.shape[0] # Checking matching ys/xs size if not type(None) == type(xs): xs = np.array(xs) if ys.shape[0] != xs.shape[0]: print(ys.shape[0]) print(xs.shape[0]) print('Discarded provided X coordinates.') xs = None # Perfect intersections ---------------------------------------------------- # Identify zero-holding cells bys = ys == 0 if 0 != bys.sum(): # Save zero-holding cells index out.extend([i for i in range(nys) if bys[i]]) # Interpolate intersections ------------------------------------------------ # Identify positive/negative ys (convert to boolean) bys = np.zeros(ys.shape) bys[ys == 0] = np.nan bys[ys > 0] = 1 bys[ys < 0] = -1 # Identify intercepts by summing previous boolean cell value bys = np.array([bys[i] + bys[i+1] for i in range(bys.shape[0] - 1)]) bysi = [i for i in range(len(bys)) if (bys == 0)[i]] if type(None) == type(xs): # Interpolate index of intercepts out.extend([i + .5 for i in bysi]) else: # Interpolate x of intercepts out = [xs[i] for i in out] out.extend([(xs[i] + xs[i+1]) / 2.0 for i in bysi]) # Output return(out) def get_norm_pdf(mu, sigma, x): """Normal distribution N(mu, sigma) probability value at x. Args: mu (float): normal distribution mean. sigma (float): normal distribution standard deviation. x (float): x-coordinate. Returns: float: N(mu, sigma) probability value at x. """ return(1 / np.sqrt(2 * sigma**2 * np.pi) * np.exp(-(x - mu)**2 / (2 * sigma**2))) def get_outliers(x, non = None, fig = None, close = None): """Identifies the outliers in a data set. Args: x (np.array): data set. non (bool): whether to return outliers or non-outliers. fig (plt.figure): for boxplot purposes. close (bool): whether to close the figure before return. Returns: list: (non-)outlier indexes. """ if None == non: non = False if None == fig: fig = plt.figure() ax = fig.gca() if None == close: close = False # If no dataset is provided if 0 == len(x): return([]) # Identify outliers through boxplot bp = ax.boxplot(x) # Close figure if close: plt.close(tmp_fig) # Retrieve outliers outliers = [] outliers.extend(bp['fliers'][0].get_data()[0].tolist()) outliers.extend(bp['fliers'][0].get_data()[1].tolist()) # Unique outliers outliers = set(outliers) # Output if not non: return([i for i in range(len(x)) if x[i] in outliers]) else: return([i for i in range(len(x)) if not x[i] in outliers]) def r_to_size(r_interval, size_type): """Convert radius interval to size (Area/Volume) interval. Args: r_interval (tuple[float]): radius interval. size_type (int): segmentation type (according to pygpseq.const). Returns: tuple(float): size (volume of area) interval. """ if const.SEG_3D == size_type: # Volume interval o_interval = (4 / float(3)) * np.pi o_interval *= np.power(np.array(r_interval), 3) else: # Area interval o_interval = np.pi * np.square(np.array(r_interval)) return(o_interval) def rotate3d(coords, theta, axis): ''' Rotate coordinates around an axis. Args: coords (nd.array): coordinate table. theta (float): rotation angle. axis (int): rotation axis, axis order matches coordinate columns. Returns: tuple: rotated coordinates. ''' rotation_mat = False if 0 == axis: # X axis rotation rotation_mat = np.matrix([ [1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)] ]) if 1 == axis: # Y axis rotation rotation_mat = np.matrix([ [np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)] ]) if 2 == axis: # Z axis rotation rotation_mat = np.matrix([ [np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1] ]) if axis < 0 or axis > 2: # Unrecognized axis return() transformed_mat = rotation_mat * coords a, b, c = transformed_mat.A return((a, b, c)) def round_unicode(n, nsig): """Round operation on unicode number in scientific notation. Args: n (unicode): number in scientific notation. nsig (int): number of significant digits. Returns: unicode: rounded unicode number in scientific notation. """ # Convert unicode to string n = str(n.replace(u'\u2212', '-')) # Split on the exponent if 'e' in n: n = n.split('e') else: n = [n] # Round the float part n[0] = str(round(float(n[0]), nsig)) # Re-join with the exponent and return return(unicode('e'.join(n))) def smooth_gaussian(x, y, sigma_smooth = None, nbins = None): """Smoothen a curve. Args: x (numeric): x coordinates. y (numeric): y coordinates. nbins (int): curve precision (opt, def: 500). sigma_smooth (float): smoothing factor (opt, def: 0.01). Returns: np.array: smoothened curve. """ # SET PARAMS =============================================================== if None == nbins: nbins = 500 if None == sigma_smooth: sigma_smooth = .1 # SMOOTHEN ================================================================= # Evenly sampled domain xs = np.linspace(0, max(x), nbins) # Initialize output ynum = np.zeros(len(xs)) ysum = np.zeros(len(xs)) # Weighted moving average for i in [i for i in range(len(x)) if not np.isnan(y[i])]: norm = get_norm_pdf(x[i], sigma_smooth, xs) ynum += norm ysum += norm * y[i] # Output return(ysum / ynum) def smooth_sparse_gaussian(x, y, nbins = None, sigma_smooth = None, rescale_sigma = None, **kwargs): """Produce a smooth approximation of sparse data. Basically a smoothened binned distribution. Args: x (float): x coordinates. y (float): y coordinates. nbins (int): curve precision (opt, def: 200). sigma_smooth (float): smoothing factor (opt, def: 0.01). rescale_sigma (bool): whether to multiply sigma_smooth to max(x). Returns: dict: various metrics profiles (mean, median, mode, std). """ if None == nbins: nbins = 200 if None == sigma_smooth: sigma_smooth = .01 if None == rescale_sigma: rescale_sigma = True if rescale_sigma: sigma_smooth *= max(x) # Bin data data = binned_profile(x, y, nbins) # Prepare output out = { 'x' : data['breaks'].tolist(), 'n' : data['n'].tolist() } # Smoothen profiles for field in ['mean', 'median', 'mode', 'std', 'max']: out[field + '_raw'] = data[field] out[field] = smooth_gaussian(data['breaks'], data[field], sigma_smooth, nbins) # Output return(out) def wilcox_sets(df, groupkey, setkey): """Perform Wilcoxon-Mann-Whitney U test on the provided list of sets. Args: df (pandas.DataFrame): data frame with distributions to be compared. groupkey (string): df column of set labels. setkey (string): df column with distributions to be compared. Returns: np.array: dataset with WMW U-test p-value of compared distribution. Examples: >>> dd = [('condition', 'S100'), ('y', 'float')] >>> p = np.array([('c1', 1), ('c2', 2)], dtype = dd) >>> p = pd.DataFrame(p) >>> print(wilcox_sets(p, 'condition', 'y')) [('y', 'c2', 'c1', 1.0, '')] """ # Identify sets set_names = [c for c in set(df[groupkey])] n_sets = len(set_names) grouped = df.groupby(groupkey) # Initialize output dtype_definition = [('field', 'S100'), ('i', 'S100'), ('j', 'S100'), ('p', 'float'), ('sig', 'S5')] p_vals = np.zeros((n_sets * (n_sets - 1) / 2,), dtype = dtype_definition) # Cycle counter c = 0 for i in range(n_sets): for j in range(i + 1, n_sets): # Run Wilcoxon-Mann-Whitney U test p = stats.mannwhitneyu( grouped.get_group(set_names[i])[setkey], grouped.get_group(set_names[j])[setkey], alternative = 'two-sided' ).pvalue # Significance string sig = '' if p <= .0001: sig = '***' elif p <= .001: sig = '**' elif p <= .01: sig = '*' elif p <= .05: sig = '.' # Append result p_vals[c] = np.array((setkey, set_names[i], set_names[j], p, sig), dtype = dtype_definition) # Increase cycle counter c += 1 # Output return(p_vals) # END ========================================================================== ################################################################################
# Copyright 2017 Veritas Technologies LLC. # # 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. """ Veritas Access Driver for manila shares. Limitation: 1) single tenant """ import hashlib import json from oslo_config import cfg from oslo_log import log as logging from oslo_utils import units from random import shuffle import requests import requests.auth import six from six.moves import http_client from manila.common import constants as const from manila import exception from manila.share import driver LOG = logging.getLogger(__name__) va_share_opts = [ cfg.StrOpt('va_server_ip', help='Console IP of Veritas Access server.'), cfg.IntOpt('va_port', default=14161, help='Veritas Access server REST port.'), cfg.StrOpt('va_user', help='Veritas Access server REST login name.'), cfg.StrOpt('va_pwd', secret=True, help='Veritas Access server REST password.'), cfg.StrOpt('va_pool', help='Veritas Access storage pool from which' 'shares are served.'), cfg.StrOpt('va_fstype', default='simple', help='Type of VA file system to be created.') ] CONF = cfg.CONF CONF.register_opts(va_share_opts) class NoAuth(requests.auth.AuthBase): """This is a 'authentication' handler. It exists for use with custom authentication systems, such as the one for the Access API, it simply passes the Authorization header as-is. The default authentication handler for requests will clobber the Authorization header. """ def __call__(self, r): return r class ACCESSShareDriver(driver.ExecuteMixin, driver.ShareDriver): """ACCESS Share Driver. Executes commands relating to Manila Shares. Supports creation of shares on ACCESS. API version history: 1.0 - Initial version. """ VA_SHARE_PATH_STR = '/vx/' def __init__(self, *args, **kwargs): """Do initialization.""" super(ACCESSShareDriver, self).__init__(False, *args, **kwargs) self.configuration.append_config_values(va_share_opts) self.backend_name = self.configuration.safe_get( 'share_backend_name') or "VeritasACCESS" self._va_ip = None self._va_url = None self._pool = None self._fstype = None self._port = None self._user = None self._pwd = None self._cred = None self._connect_resp = None self._verify_ssl_cert = None self._fs_create_str = '/fs/create' self._fs_list_str = '/fs' self._fs_delete_str = '/fs/destroy' self._fs_extend_str = '/fs/grow' self._fs_shrink_str = '/fs/shrink' self._snap_create_str = '/snapshot/create' self._snap_delete_str = '/snapshot/delete' self._snap_list_str = '/snapshot/getSnapShotList' self._nfs_add_str = '/share/create' self._nfs_delete_str = '/share/delete' self._nfs_share_list_str = '/share/all_shares_details_by_path/?path=' self._ip_addr_show_str = '/common/get_all_ips' self._pool_free_str = '/storage/pool' self._update_object = '/objecttags' self.session = None self.host = None LOG.debug("ACCESSShareDriver called") def do_setup(self, context): """Any initialization the share driver does while starting.""" super(ACCESSShareDriver, self).do_setup(context) self._va_ip = self.configuration.va_server_ip self._pool = self.configuration.va_pool self._user = self.configuration.va_user self._pwd = self.configuration.va_pwd self._port = self.configuration.va_port self._fstype = self.configuration.va_fstype self.session = self._authenticate_access(self._va_ip, self._user, self._pwd) def _get_va_share_name(self, name): length = len(name) index = int(length / 2) name1 = name[:index] name2 = name[index:] crc1 = hashlib.md5(name1.encode('utf-8')).hexdigest()[:8] crc2 = hashlib.md5(name2.encode('utf-8')).hexdigest()[:8] return crc1 + '-' + crc2 def _get_va_snap_name(self, name): return self._get_va_share_name(name) def _get_va_share_path(self, name): return self.VA_SHARE_PATH_STR + name def _does_item_exist_at_va_backend(self, item_name, path_given): """Check given share is exists on backend""" path = path_given provider = '%s:%s' % (self.host, self._port) data = {} item_list = self._access_api(self.session, provider, path, json.dumps(data), 'GET') for item in item_list: if item['name'] == item_name: return True return False def _return_access_lists_difference(self, list_a, list_b): """Returns a list of elements in list_a that are not in list_b""" sub_list = [{"access_to": s.get('access_to'), "access_type": s.get('access_type'), "access_level": s.get('access_level')} for s in list_b] return [r for r in list_a if ( {"access_to": r.get("access_to"), "access_type": r.get("access_type"), "access_level": r.get("access_level")} not in sub_list)] def _fetch_existing_rule(self, share_name): """Return list of access rules on given share""" share_path = self._get_va_share_path(share_name) path = self._nfs_share_list_str + share_path provider = '%s:%s' % (self.host, self._port) data = {} share_list = self._access_api(self.session, provider, path, json.dumps(data), 'GET') va_access_list = [] for share in share_list: if share['shareType'] == 'NFS': for share_info in share['shares']: if share_info['name'] == share_path: access_to = share_info['host_name'] a_level = const.ACCESS_LEVEL_RO if const.ACCESS_LEVEL_RW in share_info['privilege']: a_level = const.ACCESS_LEVEL_RW va_access_list.append({ 'access_to': access_to, 'access_level': a_level, 'access_type': 'ip' }) return va_access_list def create_share(self, ctx, share, share_server=None): """Create an ACCESS file system that will be represented as share.""" sharename = share['name'] sizestr = '%sg' % share['size'] LOG.debug("ACCESSShareDriver create_share sharename %s sizestr %r", sharename, sizestr) va_sharename = self._get_va_share_name(sharename) va_sharepath = self._get_va_share_path(va_sharename) va_fs_type = self._fstype path = self._fs_create_str provider = '%s:%s' % (self.host, self._port) data1 = { "largefs": "no", "blkSize": "blksize=8192", "pdirEnable": "pdir_enable=yes" } data1["layout"] = va_fs_type data1["fs_name"] = va_sharename data1["fs_size"] = sizestr data1["pool_disks"] = self._pool result = self._access_api(self.session, provider, path, json.dumps(data1), 'POST') if not result: message = (('ACCESSShareDriver create share failed %s'), sharename) LOG.error(message) raise exception.ShareBackendException(msg=message) data2 = {"type": "FS", "key": "manila"} data2["id"] = va_sharename data2["value"] = 'manila_fs' path = self._update_object result = self._access_api(self.session, provider, path, json.dumps(data2), 'POST') vip = self._get_vip() location = vip + ':' + va_sharepath LOG.debug("ACCESSShareDriver create_share location %s", location) return location def _get_vip(self): """Get a virtual IP from ACCESS.""" ip_list = self._get_access_ips(self.session, self.host) vip = [] for ips in ip_list: if ips['isconsoleip'] == 1: continue if ips['type'] == 'Virtual' and ips['status'] == 'ONLINE': vip.append(ips['ip']) shuffle(vip) return six.text_type(vip[0]) def delete_share(self, context, share, share_server=None): """Delete a share from ACCESS.""" sharename = share['name'] va_sharename = self._get_va_share_name(sharename) LOG.debug("ACCESSShareDriver delete_share %s called", sharename) if share['snapshot_id']: message = (('ACCESSShareDriver delete share %s' ' early return'), sharename) LOG.debug(message) return ret_val = self._does_item_exist_at_va_backend(va_sharename, self._fs_list_str) if not ret_val: return path = self._fs_delete_str provider = '%s:%s' % (self.host, self._port) data = {} data["fs_name"] = va_sharename result = self._access_api(self.session, provider, path, json.dumps(data), 'POST') if not result: message = (('ACCESSShareDriver delete share failed %s'), sharename) LOG.error(message) raise exception.ShareBackendException(msg=message) data2 = {"type": "FS", "key": "manila"} data2["id"] = va_sharename path = self._update_object result = self._access_api(self.session, provider, path, json.dumps(data2), 'DELETE') def extend_share(self, share, new_size, share_server=None): """Extend existing share to new size.""" sharename = share['name'] size = '%s%s' % (six.text_type(new_size), 'g') va_sharename = self._get_va_share_name(sharename) path = self._fs_extend_str provider = '%s:%s' % (self.host, self._port) data1 = {"operationOption": "growto", "tier": "primary"} data1["fs_name"] = va_sharename data1["fs_size"] = size result = self._access_api(self.session, provider, path, json.dumps(data1), 'POST') if not result: message = (('ACCESSShareDriver extend share failed %s'), sharename) LOG.error(message) raise exception.ShareBackendException(msg=message) LOG.debug('ACCESSShareDriver extended share' ' successfully %s', sharename) def shrink_share(self, share, new_size, share_server=None): """Shrink existing share to new size.""" sharename = share['name'] va_sharename = self._get_va_share_name(sharename) size = '%s%s' % (six.text_type(new_size), 'g') path = self._fs_extend_str provider = '%s:%s' % (self.host, self._port) data1 = {"operationOption": "shrinkto", "tier": "primary"} data1["fs_name"] = va_sharename data1["fs_size"] = size result = self._access_api(self.session, provider, path, json.dumps(data1), 'POST') if not result: message = (('ACCESSShareDriver shrink share failed %s'), sharename) LOG.error(message) raise exception.ShareBackendException(msg=message) LOG.debug('ACCESSShareDriver shrunk share successfully %s', sharename) def _allow_access(self, context, share, access, share_server=None): """Give access of a share to an IP.""" access_type = access['access_type'] server = access['access_to'] if access_type != 'ip': raise exception.InvalidShareAccess('Only ip access type ' 'supported.') access_level = access['access_level'] if access_level not in (const.ACCESS_LEVEL_RW, const.ACCESS_LEVEL_RO): raise exception.InvalidShareAccessLevel(level=access_level) export_path = share['export_locations'][0]['path'].split(':', 1) va_sharepath = six.text_type(export_path[1]) access_level = '%s,%s' % (six.text_type(access_level), 'sync,no_root_squash') path = self._nfs_add_str provider = '%s:%s' % (self.host, self._port) data = {} va_share_info = ("{\"share\":[{\"fileSystemPath\":\""+va_sharepath + "\",\"shareType\":\"NFS\",\"shareDetails\":" + "[{\"client\":\""+server+"\",\"exportOptions\":\"" + access_level+"\"}]}]}") data["shareDetails"] = va_share_info result = self._access_api(self.session, provider, path, json.dumps(data), 'POST') if not result: message = (('ACCESSShareDriver access failed sharepath %s' 'server %s'), va_sharepath, server) LOG.error(message) raise exception.ShareBackendException(msg=message) LOG.debug("ACCESSShareDriver allow_access sharepath %s server %s", va_sharepath, server) data2 = {"type": "SHARE", "key": "manila"} data2["id"] = va_sharepath data2["value"] = 'manila_share' path = self._update_object result = self._access_api(self.session, provider, path, json.dumps(data2), 'POST') def _deny_access(self, context, share, access, share_server=None): """Deny access to the share.""" server = access['access_to'] access_type = access['access_type'] if access_type != 'ip': return export_path = share['export_locations'][0]['path'].split(':', 1) va_sharepath = six.text_type(export_path[1]) LOG.debug("ACCESSShareDriver deny_access sharepath %s server %s", va_sharepath, server) path = self._nfs_delete_str provider = '%s:%s' % (self.host, self._port) data = {} va_share_info = ("{\"share\":[{\"fileSystemPath\":\""+va_sharepath + "\",\"shareType\":\"NFS\",\"shareDetails\":" + "[{\"client\":\""+server+"\"}]}]}") data["shareDetails"] = va_share_info result = self._access_api(self.session, provider, path, json.dumps(data), 'DELETE') if not result: message = (('ACCESSShareDriver deny failed' ' sharepath %s server %s'), va_sharepath, server) LOG.error(message) raise exception.ShareBackendException(msg=message) LOG.debug("ACCESSShareDriver deny_access sharepath %s server %s", va_sharepath, server) data2 = {"type": "SHARE", "key": "manila"} data2["id"] = va_sharepath path = self._update_object result = self._access_api(self.session, provider, path, json.dumps(data2), 'DELETE') def update_access(self, context, share, access_rules, add_rules, delete_rules, share_server=None): """Update access to the share.""" if (add_rules or delete_rules): # deleting rules for rule in delete_rules: self._deny_access(context, share, rule, share_server) # adding rules for rule in add_rules: self._allow_access(context, share, rule, share_server) else: if not access_rules: LOG.warning("No access rules provided in update_access.") else: sharename = self._get_va_share_name(share['name']) existing_a_rules = self._fetch_existing_rule(sharename) d_rule = self._return_access_lists_difference(existing_a_rules, access_rules) for rule in d_rule: LOG.debug("Removing rule %s in recovery.", six.text_type(rule)) self._deny_access(context, share, rule, share_server) a_rule = self._return_access_lists_difference(access_rules, existing_a_rules) for rule in a_rule: LOG.debug("Adding rule %s in recovery.", six.text_type(rule)) self._allow_access(context, share, rule, share_server) def create_snapshot(self, context, snapshot, share_server=None): """create snapshot of a share.""" LOG.debug('ACCESSShareDriver create_snapshot called ' 'for snapshot ID %s.', snapshot['snapshot_id']) sharename = snapshot['share_name'] va_sharename = self._get_va_share_name(sharename) snapname = snapshot['name'] va_snapname = self._get_va_snap_name(snapname) path = self._snap_create_str provider = '%s:%s' % (self.host, self._port) data = {} data["snapShotname"] = va_snapname data["fileSystem"] = va_sharename data["removable"] = 'yes' result = self._access_api(self.session, provider, path, json.dumps(data), 'PUT') if not result: message = (('ACCESSShareDriver create snapshot failed snapname %s' ' sharename %s'), snapname, va_sharename) LOG.error(message) raise exception.ShareBackendException(msg=message) data2 = {"type": "SNAPSHOT", "key": "manila"} data2["id"] = va_snapname data2["value"] = 'manila_snapshot' path = self._update_object result = self._access_api(self.session, provider, path, json.dumps(data2), 'POST') def delete_snapshot(self, context, snapshot, share_server=None): """Deletes a snapshot.""" sharename = snapshot['share_name'] va_sharename = self._get_va_share_name(sharename) snapname = snapshot['name'] va_snapname = self._get_va_snap_name(snapname) ret_val = self._does_item_exist_at_va_backend(va_snapname, self._snap_list_str) if not ret_val: return path = self._snap_delete_str provider = '%s:%s' % (self.host, self._port) data = {} data["name"] = va_snapname data["fsName"] = va_sharename data_to_send = {"snapShotDetails": {"snapshot": [data]}} result = self._access_api(self.session, provider, path, json.dumps(data_to_send), 'DELETE') if not result: message = (('ACCESSShareDriver delete snapshot failed snapname %s' ' sharename %s'), snapname, va_sharename) LOG.error(message) raise exception.ShareBackendException(msg=message) data2 = {"type": "SNAPSHOT", "key": "manila"} data2["id"] = va_snapname path = self._update_object result = self._access_api(self.session, provider, path, json.dumps(data2), 'DELETE') def create_share_from_snapshot(self, ctx, share, snapshot, share_server=None): """create share from a snapshot.""" sharename = snapshot['share_name'] va_sharename = self._get_va_share_name(sharename) snapname = snapshot['name'] va_snapname = self._get_va_snap_name(snapname) va_sharepath = self._get_va_share_path(va_sharename) LOG.debug(('ACCESSShareDriver create_share_from_snapshot snapname %s' ' sharename %s'), va_snapname, va_sharename) vip = self._get_vip() location = vip + ':' + va_sharepath + ':' + va_snapname LOG.debug("ACCESSShareDriver create_share location %s", location) return location def _get_api(self, provider, tail): api_root = 'https://%s/api' % (provider) return api_root + tail def _access_api(self, session, provider, path, input_data, method): """Returns False if failure occurs.""" kwargs = {'data': input_data} if not isinstance(input_data, dict): kwargs['headers'] = {'Content-Type': 'application/json'} full_url = self._get_api(provider, path) response = session.request(method, full_url, **kwargs) if response.status_code != http_client.OK: LOG.debug('Access API operation Failed.') return False if path == self._update_object: return True result = response.json() return result def _get_access_ips(self, session, host): path = self._ip_addr_show_str provider = '%s:%s' % (host, self._port) data = {} ip_list = self._access_api(session, provider, path, json.dumps(data), 'GET') return ip_list def _authenticate_access(self, address, username, password): session = requests.session() session.verify = False session.auth = NoAuth() response = session.post('https://%s:%s/api/rest/authenticate' % (address, self._port), data={'username': username, 'password': password}) if response.status_code != http_client.OK: LOG.debug(('failed to authenticate to remote cluster at %s as %s'), address, username) raise exception.NotAuthorized('Authentication failure.') result = response.json() session.headers.update({'Authorization': 'Bearer {}' .format(result['token'])}) session.headers.update({'Content-Type': 'application/json'}) return session def _get_access_pool_details(self): """Get access pool details.""" path = self._pool_free_str provider = '%s:%s' % (self.host, self._port) data = {} pool_details = self._access_api(self.session, provider, path, json.dumps(data), 'GET') for pool in pool_details: if pool['device_group_name'] == six.text_type(self._pool): total_capacity = (int(pool['capacity']) / units.Gi) used_size = (int(pool['used_size']) / units.Gi) return (total_capacity, (total_capacity - used_size)) message = 'Fetching pool details operation failed.' LOG.error(message) raise exception.ShareBackendException(msg=message) def _update_share_stats(self): """Retrieve status info from share volume group.""" LOG.debug("VRTSISA Updating share status.") self.host = six.text_type(self._va_ip) self.session = self._authenticate_access(self._va_ip, self._user, self._pwd) total_capacity, free_capacity = self._get_access_pool_details() data = { 'share_backend_name': self.backend_name, 'vendor_name': 'Veritas', 'driver_version': '1.0', 'storage_protocol': 'NFS', 'total_capacity_gb': total_capacity, 'free_capacity_gb': free_capacity, 'reserved_percentage': 0, 'QoS_support': False, 'snapshot_support': True, 'create_share_from_snapshot_support': True } super(ACCESSShareDriver, self)._update_share_stats(data)
import datetime as dt import pytest try: import dateutil except ImportError: dateutil = None from mongoengine import * from mongoengine import connection from tests.utils import MongoDBTestCase class TestDateTimeField(MongoDBTestCase): def test_datetime_from_empty_string(self): """ Ensure an exception is raised when trying to cast an empty string to datetime. """ class MyDoc(Document): dt = DateTimeField() md = MyDoc(dt="") with pytest.raises(ValidationError): md.save() def test_datetime_from_whitespace_string(self): """ Ensure an exception is raised when trying to cast a whitespace-only string to datetime. """ class MyDoc(Document): dt = DateTimeField() md = MyDoc(dt=" ") with pytest.raises(ValidationError): md.save() def test_default_value_utcnow(self): """Ensure that default field values are used when creating a document. """ class Person(Document): created = DateTimeField(default=dt.datetime.utcnow) utcnow = dt.datetime.utcnow() person = Person() person.validate() person_created_t0 = person.created assert person.created - utcnow < dt.timedelta(seconds=1) assert person_created_t0 == person.created # make sure it does not change assert person._data["created"] == person.created def test_handling_microseconds(self): """Tests showing pymongo datetime fields handling of microseconds. Microseconds are rounded to the nearest millisecond and pre UTC handling is wonky. See: http://api.mongodb.org/python/current/api/bson/son.html#dt """ class LogEntry(Document): date = DateTimeField() LogEntry.drop_collection() # Test can save dates log = LogEntry() log.date = dt.date.today() log.save() log.reload() assert log.date.date() == dt.date.today() # Post UTC - microseconds are rounded (down) nearest millisecond and # dropped d1 = dt.datetime(1970, 1, 1, 0, 0, 1, 999) d2 = dt.datetime(1970, 1, 1, 0, 0, 1) log = LogEntry() log.date = d1 log.save() log.reload() assert log.date != d1 assert log.date == d2 # Post UTC - microseconds are rounded (down) nearest millisecond d1 = dt.datetime(1970, 1, 1, 0, 0, 1, 9999) d2 = dt.datetime(1970, 1, 1, 0, 0, 1, 9000) log.date = d1 log.save() log.reload() assert log.date != d1 assert log.date == d2 def test_regular_usage(self): """Tests for regular datetime fields""" class LogEntry(Document): date = DateTimeField() LogEntry.drop_collection() d1 = dt.datetime(1970, 1, 1, 0, 0, 1) log = LogEntry() log.date = d1 log.validate() log.save() for query in (d1, d1.isoformat(" ")): log1 = LogEntry.objects.get(date=query) assert log == log1 if dateutil: log1 = LogEntry.objects.get(date=d1.isoformat("T")) assert log == log1 # create additional 19 log entries for a total of 20 for i in range(1971, 1990): d = dt.datetime(i, 1, 1, 0, 0, 1) LogEntry(date=d).save() assert LogEntry.objects.count() == 20 # Test ordering logs = LogEntry.objects.order_by("date") i = 0 while i < 19: assert logs[i].date <= logs[i + 1].date i += 1 logs = LogEntry.objects.order_by("-date") i = 0 while i < 19: assert logs[i].date >= logs[i + 1].date i += 1 # Test searching logs = LogEntry.objects.filter(date__gte=dt.datetime(1980, 1, 1)) assert logs.count() == 10 logs = LogEntry.objects.filter(date__lte=dt.datetime(1980, 1, 1)) assert logs.count() == 10 logs = LogEntry.objects.filter( date__lte=dt.datetime(1980, 1, 1), date__gte=dt.datetime(1975, 1, 1) ) assert logs.count() == 5 def test_datetime_validation(self): """Ensure that invalid values cannot be assigned to datetime fields. """ class LogEntry(Document): time = DateTimeField() log = LogEntry() log.time = dt.datetime.now() log.validate() log.time = dt.date.today() log.validate() log.time = dt.datetime.now().isoformat(" ") log.validate() log.time = "2019-05-16 21:42:57.897847" log.validate() if dateutil: log.time = dt.datetime.now().isoformat("T") log.validate() log.time = -1 with pytest.raises(ValidationError): log.validate() log.time = "ABC" with pytest.raises(ValidationError): log.validate() log.time = "2019-05-16 21:GARBAGE:12" with pytest.raises(ValidationError): log.validate() log.time = "2019-05-16 21:42:57.GARBAGE" with pytest.raises(ValidationError): log.validate() log.time = "2019-05-16 21:42:57.123.456" with pytest.raises(ValidationError): log.validate() def test_parse_datetime_as_str(self): class DTDoc(Document): date = DateTimeField() date_str = "2019-03-02 22:26:01" # make sure that passing a parsable datetime works dtd = DTDoc() dtd.date = date_str assert isinstance(dtd.date, str) dtd.save() dtd.reload() assert isinstance(dtd.date, dt.datetime) assert str(dtd.date) == date_str dtd.date = "January 1st, 9999999999" with pytest.raises(ValidationError): dtd.validate() class TestDateTimeTzAware(MongoDBTestCase): def test_datetime_tz_aware_mark_as_changed(self): # Reset the connections connection._connection_settings = {} connection._connections = {} connection._dbs = {} connect(db="mongoenginetest", tz_aware=True) class LogEntry(Document): time = DateTimeField() LogEntry.drop_collection() LogEntry(time=dt.datetime(2013, 1, 1, 0, 0, 0)).save() log = LogEntry.objects.first() log.time = dt.datetime(2013, 1, 1, 0, 0, 0) assert ["time"] == log._changed_fields
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.15 (https://github.com/warner/python-versioneer) import errno import os import re import subprocess import sys def get_keywords(): # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" keywords = {"refnames": git_refnames, "full": git_full} return keywords class VersioneerConfig: pass def get_config(): # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "pyannote-core-" cfg.versionfile_source = "pyannote/core/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): pass LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator def decorate(f): if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) return None return stdout def versions_from_parentdir(parentdir_prefix, root, verbose): # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%s', but '%s' doesn't start with " "prefix '%s'" % (root, dirname, parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None} @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): if not keywords: raise NotThisMethod("no keywords at all, weird") refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags"} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' keywords were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) raise NotThisMethod("no .git directory") GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # if there is a tag, this yields TAG-NUM-gHEX[-dirty] # if there are no tags, this yields HEX[-dirty] (no NUM) describe_out = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long"], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits return pieces def plus_or_dot(pieces): if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): # now build up version string, with post-release "local version # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty # exceptions: # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): # TAG[.post.devDISTANCE] . No -dirty # exceptions: # 1: no tags. 0.post.devDISTANCE if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that # .dev0 sorts backwards (a dirty tree will appear "older" than the # corresponding clean one), but you shouldn't be releasing software with # -dirty anyways. # exceptions: # 1: no tags. 0.postDISTANCE[.dev0] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. # exceptions: # 1: no tags. 0.postDISTANCE[.dev0] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty # --always' # exceptions: # 1: no tags. HEX[-dirty] (note: no 'g' prefix) if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty # --always -long'. The distance/hash is unconditional. # exceptions: # 1: no tags. HEX[-dirty] (note: no 'g' prefix) if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None} def get_versions(): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree"} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version"}
from In.field.field import Field, FieldFielder, FieldModel from In.field.field_formatter import FieldFormatter class FieldEntityReference(Field): '''EntityReference field''' __input_field_type__ = 'TextBox' def __init__(self, data = None, items = None, **args): super().__init__(data, items, **args) # check and set to 0 for None, '' if self.value: for lang, langitems in self.value.items(): for idx, idxitems in langitems.items(): if 'value' in idxitems and not idxitems['value']: self.value[lang][idx]['value'] = 0 @IN.register('FieldEntityReference', type = 'Fielder') class FieldEntityReferenceFielder(FieldFielder): '''Base Field Fielder''' def form_field(self, field_config, field_value = None, args = None): '''returns form field based on field type, data, language''' language = args.get('language', '') field_name = field_config['field_name'] field_data = field_config['data'] if field_data is None: field_data = {} if field_value is None: field_value = {} title = s(field_data.get('title', field_name)) max_allowed = int(field_data.get('max_allowed', 1)) # 0, unlimited new_empty_fields = int(field_data.get('new_empty_fields', 1)) # '': field is available to all language field_languages = field_data.get('languages', ['']) if field_languages is None: field_languages = [''] # all language # return if field is not for this language if language not in field_languages: return # wrapper obj = Object.new('HTMLField', { 'id' : field_name, 'title' : title, 'weight': field_config['weight'], 'css' : ['field form-field'], 'item_wrapper' : Object.new('TextDiv', { 'css' : ['field-wrapper'] }) }) for lang, idx_val in field_value.items(): if lang not in field_languages: continue for idx, value in idx_val.items(): # TODO name = ''.join((field_name, '[', lang, '][', str(idx), '][value]')) id = '_'.join((field_name, lang, str(idx), 'value')) obj.add(self.field_class.__input_field_type__, { 'id' : id, 'name' : name, 'value' : value['value'], 'placeholder' : title, #'validation_rule' : ['Length', 6, '>', 0, 'The loginname length should be greater than 6.'], 'css' : ['i-width-1-1 i-form-large'], 'weight' : int(idx), }) added = len(obj) # add remaining new/empty fields if max_allowed != 0: new_empty_fields = max_allowed - added if new_empty_fields > 0: # add new empty for added_idx in range(added, new_empty_fields + added): name = ''.join((field_name, '[', language, '][', str(added_idx), '][value]')) id = '_'.join((field_name, language, str(added_idx), 'value')) obj.add(self.field_class.__input_field_type__, { 'id' : id, 'name' : name, 'value' : '', 'placeholder' : title, #'validation_rule' : ['Length', 6, '>', 0, 'The loginname length should be greater than 6.'], 'css' : ['i-width-1-1 i-form-large'], 'weight' : added_idx, }) return obj def prepare_insert(self, field): '''prepare the field submit values to db insert''' value = field.value entity = field.entity entitier = IN.entitier if value: for lang, lang_items in value.items(): for idx, idx_items in lang_items.items(): field_value = idx_items['value'] if not field_value: idx_items['value'] = 0 @IN.register('FieldEntityReference', type = 'Model') class FieldEntityReferenceModel(FieldModel): def __create_field_table__(self, field_name): '''Creates table in DB for this field''' field_type = self.field_type table = IN.fielder.field_table(field_name) q = ['CREATE TABLE IF NOT EXISTS '] q.append(table) q.append(''' ( id bigserial PRIMARY KEY, entity_type character varying(64), entity_id bigint, language character varying(5), weight smallint, value bigint, created timestamp without time zone, status smallint DEFAULT 1 );''') ## index #q.append('CREATE INDEX ') #index_name = table.split('.')[-1] #q.append(index_name + '_idx ') #q.append(' ON ' + table) #q.append(' USING btree ') #q.append(''' ( #entity_type, #entity_id, #weight #);''') IN.db.execute(''.join(q)) # caller will commit @IN.register('FieldEntityReference', type = 'FieldFormatter') class FieldEntityReferenceFieldFormatter(FieldFormatter): '''FieldEntityReference. ''' __info__ = s('Entity') def format_value(self, field, format, view_mode, args, config): return self.format_entity(field, format, view_mode, args, config) def format_entity_id(self, field, format, view_mode, args, config): output_value = '' field_values = field.value if field_values is not None: values = [] for lang, lang_value in field_values.items(): # sort by weight si = sorted(lang_value.items(), key = lambda o: int(o[0])) for idx_value in si: entity_id = idx_value[1]['value'] if not entity_id: continue values.append(entity_id) output_value = ', '.join(values) return output_value def format_entity(self, field, format, view_mode, args, config): output_value = '' try: field_config = IN.fielder.entity_field_config[field.entity_type][field.entity_bundle][field.field_name]['data']['field_config'] except KeyError as e: field_config = {} if 'entity_type' not in field_config: return '' field_entity_type = field_config['entity_type'] field_view_mode = config.get('view_mode', view_mode) field_values = field.value if field_values is not None: values = [] for lang, lang_value in field_values.items(): si = sorted(lang_value.items(), key = lambda o: int(o[0])) # sort by weight for idx_value in si: entity_id = idx_value[1]['value'] if not entity_id: continue entity = IN.entitier.load_single(field_entity_type, entity_id) if not entity: continue themed_output = IN.themer.theme(entity, format, field_view_mode) values.append(themed_output) output_value = ' '.join(values) return output_value @IN.hook def field_model(): # default model return { 'FieldEntityReference' : { # field type 'columns' : { # table columns 'id' : {'type' : 'bigserial'}, 'entity_type' : {'type' : 'varchar', 'length' : 64}, 'entity_id' : {'type' : 'bigint'}, 'language' : {'type' : 'varchar', 'length' : 4, 'default' : 'lang'}, 'weight' : {'type' : 'smallint'}, 'value' : {'type' : 'bigint'}, # big int 'created' : {}, }, 'keys' : { 'primary' : 'id', }, }, }
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'UserInfo.power_level' db.delete_column('canvas_userinfo', 'power_level') def backwards(self, orm): # Adding field 'UserInfo.power_level' db.add_column('canvas_userinfo', 'power_level', self.gf('django.db.models.fields.IntegerField')(default=0), keep_default=False) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '254', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'canvas.apiapp': { 'Meta': {'object_name': 'APIApp'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'canvas.apiauthtoken': { 'Meta': {'unique_together': "(('user', 'app'),)", 'object_name': 'APIAuthToken'}, 'app': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.APIApp']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.bestof': { 'Meta': {'object_name': 'BestOf'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'best_of'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}), 'chosen_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'best_of'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}) }, 'canvas.category': { 'Meta': {'object_name': 'Category'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}), 'founded': ('django.db.models.fields.FloatField', [], {'default': '1298956320'}), 'founder': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'founded_groups'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderators': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'moderated_categories'", 'symmetrical': 'False', 'to': "orm['auth.User']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.comment': { 'Meta': {'object_name': 'Comment'}, 'anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}), 'judged': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'ot_hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'replies'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Comment']"}), 'parent_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'replied_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}), 'reply_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'used_in_comments'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'reply_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}), 'score': ('django.db.models.fields.FloatField', [], {'default': '0', 'db_index': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.commentflag': { 'Meta': {'object_name': 'CommentFlag'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'type_id': ('django.db.models.fields.IntegerField', [], {}), 'undone': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['auth.User']"}) }, 'canvas.commentmoderationlog': { 'Meta': {'object_name': 'CommentModerationLog'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'note': ('django.db.models.fields.TextField', [], {}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderated_comments_log'", 'to': "orm['auth.User']"}), 'visibility': ('django.db.models.fields.IntegerField', [], {}) }, 'canvas.commentpin': { 'Meta': {'object_name': 'CommentPin'}, 'auto': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.commentsticker': { 'Meta': {'object_name': 'CommentSticker'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stickers'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'type_id': ('django.db.models.fields.IntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'canvas.content': { 'Meta': {'object_name': 'Content'}, 'alpha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'animated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}), 'remix_of': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'remixes'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'remix_text': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1000', 'blank': 'True'}), 'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'blank': 'True'}), 'stamps_used': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'used_as_stamp'", 'blank': 'True', 'to': "orm['canvas.Content']"}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'url_mapping': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.ContentUrlMapping']", 'null': 'True', 'blank': 'True'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.contenturlmapping': { 'Meta': {'object_name': 'ContentUrlMapping'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'canvas.emailunsubscribe': { 'Meta': {'object_name': 'EmailUnsubscribe'}, 'email': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'canvas.externalcontent': { 'Meta': {'object_name': 'ExternalContent'}, '_data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'content_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'external_content'", 'to': "orm['canvas.Comment']"}), 'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'null': 'True', 'blank': 'True'}) }, 'canvas.facebookinvite': { 'Meta': {'object_name': 'FacebookInvite'}, 'fb_message_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invited_fbid': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}) }, 'canvas.facebookuser': { 'Meta': {'object_name': 'FacebookUser'}, 'email': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'fb_uid': ('django.db.models.fields.BigIntegerField', [], {'unique': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'gender': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_invited': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'canvas.followcategory': { 'Meta': {'unique_together': "(('user', 'category'),)", 'object_name': 'FollowCategory'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followers'", 'to': "orm['canvas.Category']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'following'", 'to': "orm['auth.User']"}) }, 'canvas.invitecode': { 'Meta': {'object_name': 'InviteCode'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}) }, 'canvas.remixplugin': { 'Meta': {'object_name': 'RemixPlugin'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 's3md5': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}) }, 'canvas.stashcontent': { 'Meta': {'object_name': 'StashContent'}, 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Content']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.userinfo': { 'Meta': {'object_name': 'UserInfo'}, 'free_invites': ('django.db.models.fields.IntegerField', [], {'default': '10'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invite_bypass': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'is_qa': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'post_anonymously': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'canvas.usermoderationlog': { 'Meta': {'object_name': 'UserModerationLog'}, 'action': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'note': ('django.db.models.fields.TextField', [], {}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderation_log'", 'to': "orm['auth.User']"}) }, 'canvas.userwarning': { 'Meta': {'object_name': 'UserWarning'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}), 'confirmed': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'custom_message': ('django.db.models.fields.TextField', [], {}), 'disable_user': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issued': ('canvas.util.UnixTimestampField', [], {}), 'stock_message': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_warnings'", 'to': "orm['auth.User']"}), 'viewed': ('canvas.util.UnixTimestampField', [], {'default': '0'}) }, 'canvas.welcomeemailrecipient': { 'Meta': {'object_name': 'WelcomeEmailRecipient'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'canvas_auth.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'} }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['canvas']
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA """ import errno import os import socket import sys import six from ._exceptions import * from ._logging import * from ._socket import* from ._ssl_compat import * from ._url import * if six.PY3: from base64 import encodebytes as base64encode else: from base64 import encodestring as base64encode __all__ = ["proxy_info", "connect", "read_headers"] class proxy_info(object): def __init__(self, **options): self.host = options.get("http_proxy_host", None) if self.host: self.port = options.get("http_proxy_port", 0) self.auth = options.get("http_proxy_auth", None) self.no_proxy = options.get("http_no_proxy", None) else: self.port = 0 self.auth = None self.no_proxy = None def connect(url, options, proxy, socket): hostname, port, resource, is_secure = parse_url(url) if socket: return socket, (hostname, port, resource) addrinfo_list, need_tunnel, auth = _get_addrinfo_list( hostname, port, is_secure, proxy) if not addrinfo_list: raise WebSocketException( "Host not found.: " + hostname + ":" + str(port)) sock = None try: sock = _open_socket(addrinfo_list, options.sockopt, options.timeout) if need_tunnel: sock = _tunnel(sock, hostname, port, auth) if is_secure: if HAVE_SSL: sock = _ssl_socket(sock, options.sslopt, hostname) else: raise WebSocketException("SSL not available.") return sock, (hostname, port, resource) except: if sock: sock.close() raise def _get_addrinfo_list(hostname, port, is_secure, proxy): phost, pport, pauth = get_proxy_info( hostname, is_secure, proxy.host, proxy.port, proxy.auth, proxy.no_proxy) if not phost: addrinfo_list = socket.getaddrinfo( hostname, port, 0, 0, socket.SOL_TCP) return addrinfo_list, False, None else: pport = pport and pport or 80 addrinfo_list = socket.getaddrinfo(phost, pport, 0, 0, socket.SOL_TCP) return addrinfo_list, True, pauth def _open_socket(addrinfo_list, sockopt, timeout): err = None for addrinfo in addrinfo_list: family = addrinfo[0] sock = socket.socket(family) sock.settimeout(timeout) for opts in DEFAULT_SOCKET_OPTION: sock.setsockopt(*opts) for opts in sockopt: sock.setsockopt(*opts) address = addrinfo[4] try: sock.connect(address) except socket.error as error: error.remote_ip = str(address[0]) if error.errno in (errno.ECONNREFUSED, ): err = error continue else: raise else: break else: raise err return sock def _can_use_sni(): return six.PY2 and sys.version_info >= (2, 7, 9) or sys.version_info >= (3, 2) def _wrap_sni_socket(sock, sslopt, hostname, check_hostname): context = ssl.SSLContext(sslopt.get('ssl_version', ssl.PROTOCOL_SSLv23)) if sslopt.get('cert_reqs', ssl.CERT_NONE) != ssl.CERT_NONE: context.load_verify_locations(cafile=sslopt.get('ca_certs', None)) if sslopt.get('certfile', None): context.load_cert_chain( sslopt['certfile'], sslopt.get('keyfile', None), sslopt.get('password', None), ) # see # https://github.com/liris/websocket-client/commit/b96a2e8fa765753e82eea531adb19716b52ca3ca#commitcomment-10803153 context.verify_mode = sslopt['cert_reqs'] if HAVE_CONTEXT_CHECK_HOSTNAME: context.check_hostname = check_hostname if 'ciphers' in sslopt: context.set_ciphers(sslopt['ciphers']) if 'cert_chain' in sslopt: certfile, keyfile, password = sslopt['cert_chain'] context.load_cert_chain(certfile, keyfile, password) return context.wrap_socket( sock, do_handshake_on_connect=sslopt.get('do_handshake_on_connect', True), suppress_ragged_eofs=sslopt.get('suppress_ragged_eofs', True), server_hostname=hostname, ) def _ssl_socket(sock, user_sslopt, hostname): sslopt = dict(cert_reqs=ssl.CERT_REQUIRED) sslopt.update(user_sslopt) if os.environ.get('WEBSOCKET_CLIENT_CA_BUNDLE'): certPath = os.environ.get('WEBSOCKET_CLIENT_CA_BUNDLE') else: certPath = os.path.join( os.path.dirname(__file__), "cacert.pem") if os.path.isfile(certPath) and user_sslopt.get('ca_certs', None) is None: sslopt['ca_certs'] = certPath check_hostname = sslopt["cert_reqs"] != ssl.CERT_NONE and sslopt.pop( 'check_hostname', True) if _can_use_sni(): sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname) else: sslopt.pop('check_hostname', True) sock = ssl.wrap_socket(sock, **sslopt) if not HAVE_CONTEXT_CHECK_HOSTNAME and check_hostname: match_hostname(sock.getpeercert(), hostname) return sock def _tunnel(sock, host, port, auth): debug("Connecting proxy...") connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port) # TODO: support digest auth. if auth and auth[0]: auth_str = auth[0] if auth[1]: auth_str += ":" + auth[1] encoded_str = base64encode(auth_str.encode()).strip().decode() connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str connect_header += "\r\n" dump("request header", connect_header) send(sock, connect_header) try: status, resp_headers = read_headers(sock) except Exception as e: raise WebSocketProxyException(str(e)) if status != 200: raise WebSocketProxyException( "failed CONNECT via proxy status: %r" % status) return sock def read_headers(sock): status = None headers = {} trace("--- response header ---") while True: line = recv_line(sock) line = line.decode('utf-8').strip() if not line: break trace(line) if not status: status_info = line.split(" ", 2) status = int(status_info[1]) else: kv = line.split(":", 1) if len(kv) == 2: key, value = kv headers[key.lower()] = value.strip() else: raise WebSocketException("Invalid header") trace("-----------------------") return status, headers
from unittest import TestCase import matrix_vector as m class TestMatrix(TestCase): def test_rows(self): self.assertEqual(m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]).rows(), 3) def test_colums(self): self.assertEqual(m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]).colums(), 3) def test_get_row(self): a = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a.get_row(1), m.Vector(5, 6, 7)) def test_get_row_out_of_range(self): a = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) with self.assertRaises(IndexError): a.get_row(3) def test_get_colum(self): a = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a.get_colum(1), m.Vector(2, 6, 9)) def test_get_colum_out_of_range(self): a = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) with self.assertRaises(IndexError): a.get_colum(3) def test_same_dimension_true(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a2 = m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) self.assertEqual(a1.is_same_dimension(a2), True) def test_same_dimension_false(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7]) a2 = m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) self.assertEqual(a1.is_same_dimension(a2), False) def test_add_number(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a1 + 2, m.Matrix([3, 4, 5], [7, 8, 9], [10, 11, 12])) self.assertEqual(a1, m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10])) def test_add_matrix(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a2 = m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) self.assertEqual(a1 + a2, m.Matrix([2, 0, 6], [10, 9, 14], [0, 18, 20])) self.assertEqual(a1, m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10])) def test_add_different_dimension(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7]) a2 = m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) with self.assertRaises(m.matrix.MatrixDimensionError): a1 + a2 def test_i_add_number(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a1 += 2 self.assertEqual(a1, m.Matrix([3, 4, 5], [7, 8, 9], [10, 11, 12])) def test_i_add_matrix(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a1 += m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) self.assertEqual(a1, m.Matrix([2, 0, 6], [10, 9, 14], [0, 18, 20])) def test_sub_number(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a1 - 2, m.Matrix([-1, 0, 1], [3, 4, 5], [6, 7, 8])) self.assertEqual(a1, m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10])) def test_sub_matrix(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a2 = m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) self.assertEqual(a1 - a2, m.Matrix([0, 4, 0], [0, 3, 0], [16, 0, 0])) self.assertEqual(a1, m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10])) def test_sub_different_dimension(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7]) a2 = m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) with self.assertRaises(m.matrix.MatrixDimensionError): a1 - a2 def test_i_sub_number(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a1 -= 2 self.assertEqual(a1, m.Matrix([-1, 0, 1], [3, 4, 5], [6, 7, 8])) def test_i_sub_matrix(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a1 -= m.Matrix([1, -2, 3], [5, 3, 7], [-8, 9, 10]) self.assertEqual(a1, m.Matrix([0, 4, 0], [0, 3, 0], [16, 0, 0])) def test_get_item_1(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a1[1], m.Vector(5, 6, 7)) def test_get_item_2(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a1[1][2], 7) def test_transpose(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) a1.transpose() self.assertEqual(a1, m.Matrix([1, 5, 8], [2, 6, 9], [3, 7, 10])) def test_transposed(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a1.transposed(), m.Matrix([1, 5, 8], [2, 6, 9], [3, 7, 10])) self.assertEqual(a1, m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10])) def test_multiply_number(self): a1 = m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10]) self.assertEqual(a1 * 2, m.Matrix([2, 4, 6], [10, 12, 14], [16, 18, 20])) self.assertEqual(a1, m.Matrix([1, 2, 3], [5, 6, 7], [8, 9, 10])) def test_multiply_matrix_1(self): a1 = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) self.assertEqual(a1 * a1, m.Matrix([30, 36, 42], [66, 81, 96], [102, 126, 150])) def test_multiply_matrix_2(self): a1 = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) a2 = m.Matrix([1, 2], [3, 4], [5, 6]) self.assertEqual(a1 * a2, m.Matrix([22, 28], [49, 64], [76, 100])) self.assertEqual(a1, m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9])) def test_multiply_matrix_unsutable(self): a1 = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) a2 = m.Matrix([1, 2], [3, 4]) with self.assertRaises(m.matrix.MatrixDimensionError): a1 * a2 def test_multiply_vector(self): a1 = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) a2 = m.Vector(1, 2, 3) self.assertEqual(a1 * a2, m.Vector(14, 32, 50)) def test_multiply_vector_unsutable(self): a = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) v = m.Vector(1, 2, 3, 4) with self.assertRaises(m.matrix.MatrixDimensionError): a * v def test_minor(self): a = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) self.assertEqual(a.minor(1, 1), m.Matrix([1, 3], [7, 9])) def test_minor_out_of_range(self): a = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) with self.assertRaises(IndexError): a.minor(3, 3) def test_determinant_1(self): a = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) self.assertEqual(a.determinant(), 0) def test_determinant_2(self): a = m.Matrix([1, 3, 5], [-4, 7, 1], [5, -2, 1]) self.assertEqual(a.determinant(), -99) def test_determinant_3(self): a = m.Matrix([5, 4, 9, -1], [-2, 5, 1, 3], [2, -3, 4, 1], [8, 3, -3, 0]) self.assertEqual(a.determinant(), 1943) def test_determinant_not_square(self): a = m.Matrix([1, 3], [-4, 7], [5, -2]) with self.assertRaises(m.matrix.MatrixDimensionError): a.determinant() def test_inversed(self): a = m.Matrix([1, 3, 5], [-4, 7, 1], [5, -2, 1]) self.assertEqual(a.inversed().round(2), m.Matrix([-0.09, 0.13, 0.32], [-0.09, 0.24, 0.21], [0.27, -0.17, -0.19])) self.assertEqual(a, m.Matrix([1, 3, 5], [-4, 7, 1], [5, -2, 1])) def test_inversed_zero_det(self): a = m.Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) with self.assertRaises(ZeroDivisionError): a.inversed() def test_round(self): a = m.Matrix([-0.093, 0.131, 0.323], [-0.092, 0.242, 0.211], [0.272, -0.173, -0.192]).round(2) self.assertEqual(a.round(2), m.Matrix([-0.09, 0.13, 0.32], [-0.09, 0.24, 0.21], [0.27, -0.17, -0.19]))
''' Script to generate input jsons for miRNA-seq pipeline GitHub info about inputs: https://github.com/ENCODE-DCC/mirna-seq-pipeline/blob/master/docs/reference.md#inputs This script takes experiment accessions as inputs, pulls required metadata for those experiments, and then generates an input.json file for each one as output. It will also output a caper_submit_commands.txt file that contains the Caper commands to process each experiment on Google Cloud. Example command: python generate_mirna_input_json.py -i ENCSR000ABC -o /Users/mypath -g gs://my/path -s https://test.encodedcc.org -r 2 3 -e ''' import argparse import json import os import pandas as pd import requests def get_parser(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) input_group = parser.add_mutually_exclusive_group(required=True) input_group.add_argument('-i', "--infile", action='store', help="""Path to .txt file containing accessions of experiments to process.""") input_group.add_argument("--accessions", action='store', help="""List of accessions separated by commas.""") parser.add_argument('-o', '--outputpath', action='store', default='', help="""Optional path to output folder. Defaults to current path.""") parser.add_argument('-g', '--gcpath', action='store', default='', help="""Optional path where the input.json will be uploaded to the Google Cloud instance. Only affects the list of caper commands that is generated.""") parser.add_argument('-s', '--server', action='store', default='https://www.encodeproject.org/', help="""Optional specification of server using the full URL. Defaults to production server.""") parser.add_argument('--s3_uri', action='store_true', default=False, help="""Optional flag to use s3_uri links from the ENCODE portal. Otherwise, defaults to using http links.""") parser.add_argument('--custom-message', action='store', help="""An additional custom string to be appended to the messages in the caper submit commands.""") parser.add_argument('--caper-commands-file-message', action='store', default='', help="""An additional custom string to be appended to the file name of the caper submit commands.""") parser.add_argument('--wdl', action='store', default=False, help="""Path to .wdl file.""") return parser def parse_infile(infile): try: infile_df = pd.read_csv(infile, '\t') return infile_df except FileNotFoundError as e: print(e) exit() def build_experiment_report_query(experiment_list, server): joined_list = '&accession='.join(experiment_list) return server + '/report/?type=Experiment' + \ '&accession={}'.format(joined_list) + \ '&field=@id' + \ '&field=accession' + \ '&field=assay_title' + \ '&field=files.@id' + \ '&field=replicates.status' + \ '&field=replicates.library.biosample.organism.scientific_name' + \ '&field=documents' + \ '&field=files.s3_uri' + \ '&field=files.href' + \ '&limit=all' + \ '&format=json' def build_file_report_query(experiment_list, server): joined_list = '&dataset='.join(experiment_list) return server + '/report/?type=File' + \ '&dataset={}'.format(joined_list) + \ '&file_format=fastq' + \ '&field=@id' + \ '&field=dataset' + \ '&field=biological_replicates' + \ '&field=replicate.library.adapters' + \ '&field=status' + \ '&field=s3_uri' + \ '&field=href' + \ '&field=replicate.status' + \ '&limit=all' + \ '&format=json' def check_path_trailing_slash(path): if path.endswith('/'): return path.rstrip('/') else: return path def get_data_from_portal(infile_df, server, keypair, link_prefix, link_src): # Retrieve experiment report view json with necessary fields and store as DataFrame. experiment_input_df = pd.DataFrame() experiment_accessions = infile_df['accession'].tolist() # Chunk the list to avoid sending queries longer than the character limit chunked_experiment_accessions = [experiment_accessions[x:x+100] for x in range(0, len(experiment_accessions), 100)] for chunk in chunked_experiment_accessions: experiment_report = requests.get( build_experiment_report_query(chunk, server), auth=keypair, headers={'content-type': 'application/json'}) experiment_report_json = json.loads(experiment_report.text) experiment_df_temp = pd.json_normalize(experiment_report_json['@graph']) experiment_input_df = experiment_input_df.append(experiment_df_temp, ignore_index=True, sort=True) experiment_input_df.sort_values(by=['accession'], inplace=True) # Gather list of controls from the list of experiments to query for their files. datasets_to_retrieve = experiment_input_df.get('@id').tolist() # Retrieve file report view json with necessary fields and store as DataFrame. file_input_df = pd.DataFrame() chunked_dataset_accessions = [datasets_to_retrieve[x:x+100] for x in range(0, len(datasets_to_retrieve), 100)] for chunk in chunked_dataset_accessions: file_report = requests.get( build_file_report_query(chunk, server), auth=keypair, headers={'content-type': 'application/json'}) file_report_json = json.loads(file_report.text) file_df_temp = pd.json_normalize(file_report_json['@graph']) file_input_df = file_input_df.append(file_df_temp, ignore_index=True, sort=True) file_input_df.set_index(link_src, inplace=True) file_input_df['biorep_scalar'] = [x[0] for x in file_input_df['biological_replicates']] return experiment_input_df, file_input_df def main(): keypair = (os.environ.get('DCC_API_KEY'), os.environ.get('DCC_SECRET_KEY')) parser = get_parser() args = parser.parse_args() # Check encodeurl flag and define the link source to use. server = check_path_trailing_slash(args.server) use_s3 = args.s3_uri if use_s3: link_prefix = '' link_src = 's3_uri' else: link_prefix = server link_src = 'href' # Set the output paths and load the list of experiments to process. gc_path = check_path_trailing_slash(args.gcpath) output_path = check_path_trailing_slash(args.outputpath) caper_commands_file_message = args.caper_commands_file_message wdl = args.wdl if args.infile: infile_df = parse_infile(args.infile) infile_df.sort_values(by=['accession'], inplace=True) elif args.accessions: accession_list = args.accessions.split(',') message = args.custom_message.split(',') infile_df = pd.DataFrame({ 'accession': accession_list, 'custom_message': message }) infile_df.sort_values(by=['accession'], inplace=True) # Fetch data from the ENCODE portal experiment_input_df, file_input_df = get_data_from_portal(infile_df, server, keypair, link_prefix, link_src) # Create output DataFrame to store all data for the input.json files. output_df = pd.DataFrame() # Assign experiment_prefix values. For simplicity, this is the same as the experiment accession. output_df['mirna_seq_pipeline.experiment_prefix'] = experiment_input_df['accession'] if 'custom_message' in infile_df: output_df['custom_message'] = infile_df['custom_message'] output_df['custom_message'].fillna('', inplace=True) else: output_df['custom_message'] = '' output_df.set_index('mirna_seq_pipeline.experiment_prefix', inplace=True, drop=False) # To correctly get the information for fastqs and adapters, this script looks up fastq files associated with each specified experiment in a 2nd table containing only file metadata. final_input_fastq_links = [] final_input_five_prime_adapters = [] allowed_statuses = ['released', 'in progress'] # List to store Experiment accessions with more than 1 fastq found per replicate. extra_adapters_detected = [] for experiment_files in experiment_input_df.get('files'): fastqs_by_rep = { 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] } adapters_by_rep = { 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] } # Iterate over each file in the current experiment and collect data on fastq files for file in experiment_files: link = file[link_src] # Check fastq files for correct status and replicate # if link.endswith('fastq.gz') \ and link in file_input_df.index \ and file_input_df.loc[link].at['status'] in allowed_statuses \ and file_input_df.loc[link].at['replicate.status'] in allowed_statuses: for rep_num in fastqs_by_rep: if file_input_df.loc[link].at['biorep_scalar'] == rep_num: fastqs_by_rep[rep_num].append(link_prefix + link) adapter_accession = None for adapter in file_input_df.loc[link].at['replicate.library.adapters']: if adapter['type'] == "read1 5' adapter" and adapter_accession is None: adapter_accession = '{}{}@@download/{}.txt.gz'.format( server, adapter['file'], adapter['file'].split('/')[2]) elif adapter['type'] == "read1 3' adapter": continue else: extra_adapters_detected.append(file_input_df.loc[link].at['dataset'][13:24]) adapters_by_rep[rep_num].append(adapter_accession) formatted_fastq_links = [] formatted_adapter_links = [] for key in fastqs_by_rep: if len(fastqs_by_rep[key]) > 0: formatted_fastq_links.append(fastqs_by_rep[key]) formatted_adapter_links.append(adapters_by_rep[key]) # Append the list of lists to (yet another) list, which is the experiment level one. final_input_fastq_links.append(formatted_fastq_links) final_input_five_prime_adapters.append(formatted_adapter_links) output_df['mirna_seq_pipeline.fastqs'] = final_input_fastq_links output_df['mirna_seq_pipeline.five_prime_adapters'] = final_input_five_prime_adapters # Same 3' adapters were used for all experiments. output_df['mirna_seq_pipeline.three_prime_adapters'] = server + '/files/ENCFF937TEF/@@download/ENCFF937TEF.txt.gz' # Specify star_index, mirna_annotation, and chrom_size. star_indices = [] mirna_annotations = [] chrom_sizes = [] for replicates in experiment_input_df.get('replicates'): organism = set() for rep in replicates: # Store species name. organism.add(rep['library']['biosample']['organism']['scientific_name']) if ''.join(organism) == 'Homo sapiens': star_indices.append(server + '/files/ENCFF123QLG/@@download/ENCFF123QLG.tar.gz') mirna_annotations.append(server + '/files/ENCFF470CZH/@@download/ENCFF470CZH.gtf.gz') chrom_sizes.append(server + '/files/GRCh38_EBV.chrom.sizes/@@download/GRCh38_EBV.chrom.sizes.tsv') elif ''.join(organism) == 'Mus musculus': star_indices.append(server + '/files/ENCFF795AAA/@@download/ENCFF795AAA.tar.gz') mirna_annotations.append(server + '/files/ENCFF094ICJ/@@download/ENCFF094ICJ.gtf.gz') chrom_sizes.append(server + '/files/mm10_no_alt.chrom.sizes/@@download/mm10_no_alt.chrom.sizes.tsv') else: star_indices.append('') mirna_annotations.append('') chrom_sizes.append('') output_df['mirna_seq_pipeline.star_index'] = star_indices output_df['mirna_seq_pipeline.mirna_annotation'] = mirna_annotations output_df['mirna_seq_pipeline.chrom_sizes'] = chrom_sizes # Assign other parameters, which are identical for all runs. output_df['mirna_seq_pipeline.cutadapt_ncpus'] = 2 output_df['mirna_seq_pipeline.cutadapt_ramGB'] = 7 output_df['mirna_seq_pipeline.cutadapt_disk'] = 'local-disk 200 SSD' output_df['mirna_seq_pipeline.star_ncpus'] = 16 output_df['mirna_seq_pipeline.star_ramGB'] = 60 output_df['mirna_seq_pipeline.star_disk'] = 'local-disk 200 SSD' output_df['mirna_seq_pipeline.wigtobigwig_ncpus'] = 2 output_df['mirna_seq_pipeline.wigtobigwig_ramGB'] = 7 output_df['mirna_seq_pipeline.wigtobigwig_disk'] = 'local-disk 200 SSD' # Identify missing or incorrect data. missing_fastqs_filter = output_df['mirna_seq_pipeline.fastqs'].apply(lambda x: [] in x) missing_fastqs_detected = output_df[missing_fastqs_filter]['mirna_seq_pipeline.experiment_prefix'].to_list() no_adapters_filter = output_df['mirna_seq_pipeline.five_prime_adapters'].apply(lambda x: [None] in x) no_adapters_detected = output_df[no_adapters_filter]['mirna_seq_pipeline.experiment_prefix'].to_list() no_organism_detected = output_df.loc[output_df['mirna_seq_pipeline.star_index'] == '']['mirna_seq_pipeline.experiment_prefix'].to_list() # Print error messages to terminal. for accession in missing_fastqs_detected: print('ERROR: Missing fastqs in experiment {}.'.format(accession)) for accession in extra_adapters_detected: print('ERROR: More than 1 5\' adapter detected for library in experiment {}.'.format(accession)) for accession in no_adapters_detected: print('ERROR: Missing adapters in experiment {}.'.format(accession)) for accession in no_organism_detected: print('ERROR: Missing star_index, mirna_annotation, and chrom_sizes in experiment {}.'.format(accession)) # Drop items which had errors from the table. output_df.drop( missing_fastqs_detected + extra_adapters_detected + no_adapters_detected + no_organism_detected, inplace=True) # Convert data frame to a dictionary in which each key corresponds to one row (experiment) of the table output_dict = output_df.to_dict('index') command_output = '' for experiment in output_dict: accession = output_dict[experiment]['mirna_seq_pipeline.experiment_prefix'] file_name = f'{accession}_mirna_{len(output_dict[experiment]["mirna_seq_pipeline.fastqs"])}rep.json' # Write a corresponding caper command. command_output = command_output + 'caper submit {} -i {}{} -s {}{}\nsleep 1\n'.format( wdl, (gc_path + '/' if not gc_path.endswith('/') else gc_path), file_name, file_name[:-5], ('_' + output_dict[experiment]['custom_message'] if output_dict[experiment]['custom_message'] != '' else '') ) # Write as .json file for prop in list(output_dict[experiment]): if output_dict[experiment][prop] in (None, [], '') or (type(output_dict[experiment][prop]) == list and None in output_dict[experiment][prop]): output_dict[experiment].pop(prop) output_dict[experiment].pop('custom_message') with open(f'{output_path}{"/" if output_path else ""}{file_name}', 'w') as output_file: output_file.write(json.dumps(output_dict[experiment], indent=4)) if command_output != '': commands_file_path = ( f'{output_path}{"/" if output_path else ""}' f'caper_submit{"_" if caper_commands_file_message else ""}{caper_commands_file_message}.sh' ) with open(commands_file_path, 'w') as command_output_file: command_output_file.write(command_output) if __name__ == '__main__': main()
"""HMAC-based One-time Password auth module. Sending HOTP through notify service """ import asyncio from collections import OrderedDict import logging from typing import Any, Dict, List, Optional import attr import voluptuous as vol from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ServiceNotFound from homeassistant.helpers import config_validation as cv from . import ( MULTI_FACTOR_AUTH_MODULE_SCHEMA, MULTI_FACTOR_AUTH_MODULES, MultiFactorAuthModule, SetupFlow, ) REQUIREMENTS = ["pyotp==2.3.0"] CONF_MESSAGE = "message" CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend( { vol.Optional(CONF_INCLUDE): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_EXCLUDE): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_MESSAGE, default="{} is your Home Assistant login code"): str, }, extra=vol.PREVENT_EXTRA, ) STORAGE_VERSION = 1 STORAGE_KEY = "auth_module.notify" STORAGE_USERS = "users" STORAGE_USER_ID = "user_id" INPUT_FIELD_CODE = "code" _LOGGER = logging.getLogger(__name__) def _generate_secret() -> str: """Generate a secret.""" import pyotp return str(pyotp.random_base32()) def _generate_random() -> int: """Generate a 8 digit number.""" import pyotp return int(pyotp.random_base32(length=8, chars=list("1234567890"))) def _generate_otp(secret: str, count: int) -> str: """Generate one time password.""" import pyotp return str(pyotp.HOTP(secret).at(count)) def _verify_otp(secret: str, otp: str, count: int) -> bool: """Verify one time password.""" import pyotp return bool(pyotp.HOTP(secret).verify(otp, count)) @attr.s(slots=True) class NotifySetting: """Store notify setting for one user.""" secret = attr.ib(type=str, factory=_generate_secret) # not persistent counter = attr.ib(type=int, factory=_generate_random) # not persistent notify_service = attr.ib(type=Optional[str], default=None) target = attr.ib(type=Optional[str], default=None) _UsersDict = Dict[str, NotifySetting] @MULTI_FACTOR_AUTH_MODULES.register("notify") class NotifyAuthModule(MultiFactorAuthModule): """Auth module send hmac-based one time password by notify service.""" DEFAULT_TITLE = "Notify One-Time Password" def __init__(self, hass: HomeAssistant, config: Dict[str, Any]) -> None: """Initialize the user data store.""" super().__init__(hass, config) self._user_settings: Optional[_UsersDict] = None self._user_store = hass.helpers.storage.Store( STORAGE_VERSION, STORAGE_KEY, private=True ) self._include = config.get(CONF_INCLUDE, []) self._exclude = config.get(CONF_EXCLUDE, []) self._message_template = config[CONF_MESSAGE] self._init_lock = asyncio.Lock() @property def input_schema(self) -> vol.Schema: """Validate login flow input data.""" return vol.Schema({INPUT_FIELD_CODE: str}) async def _async_load(self) -> None: """Load stored data.""" async with self._init_lock: if self._user_settings is not None: return data = await self._user_store.async_load() if data is None: data = {STORAGE_USERS: {}} self._user_settings = { user_id: NotifySetting(**setting) for user_id, setting in data.get(STORAGE_USERS, {}).items() } async def _async_save(self) -> None: """Save data.""" if self._user_settings is None: return await self._user_store.async_save( { STORAGE_USERS: { user_id: attr.asdict( notify_setting, filter=attr.filters.exclude( attr.fields(NotifySetting).secret, attr.fields(NotifySetting).counter, ), ) for user_id, notify_setting in self._user_settings.items() } } ) @callback def aync_get_available_notify_services(self) -> List[str]: """Return list of notify services.""" unordered_services = set() for service in self.hass.services.async_services().get("notify", {}): if service not in self._exclude: unordered_services.add(service) if self._include: unordered_services &= set(self._include) return sorted(unordered_services) async def async_setup_flow(self, user_id: str) -> SetupFlow: """Return a data entry flow handler for setup module. Mfa module should extend SetupFlow """ return NotifySetupFlow( self, self.input_schema, user_id, self.aync_get_available_notify_services() ) async def async_setup_user(self, user_id: str, setup_data: Any) -> Any: """Set up auth module for user.""" if self._user_settings is None: await self._async_load() assert self._user_settings is not None self._user_settings[user_id] = NotifySetting( notify_service=setup_data.get("notify_service"), target=setup_data.get("target"), ) await self._async_save() async def async_depose_user(self, user_id: str) -> None: """Depose auth module for user.""" if self._user_settings is None: await self._async_load() assert self._user_settings is not None if self._user_settings.pop(user_id, None): await self._async_save() async def async_is_user_setup(self, user_id: str) -> bool: """Return whether user is setup.""" if self._user_settings is None: await self._async_load() assert self._user_settings is not None return user_id in self._user_settings async def async_validate(self, user_id: str, user_input: Dict[str, Any]) -> bool: """Return True if validation passed.""" if self._user_settings is None: await self._async_load() assert self._user_settings is not None notify_setting = self._user_settings.get(user_id, None) if notify_setting is None: return False # user_input has been validate in caller return await self.hass.async_add_executor_job( _verify_otp, notify_setting.secret, user_input.get(INPUT_FIELD_CODE, ""), notify_setting.counter, ) async def async_initialize_login_mfa_step(self, user_id: str) -> None: """Generate code and notify user.""" if self._user_settings is None: await self._async_load() assert self._user_settings is not None notify_setting = self._user_settings.get(user_id, None) if notify_setting is None: raise ValueError("Cannot find user_id") def generate_secret_and_one_time_password() -> str: """Generate and send one time password.""" assert notify_setting # secret and counter are not persistent notify_setting.secret = _generate_secret() notify_setting.counter = _generate_random() return _generate_otp(notify_setting.secret, notify_setting.counter) code = await self.hass.async_add_executor_job( generate_secret_and_one_time_password ) await self.async_notify_user(user_id, code) async def async_notify_user(self, user_id: str, code: str) -> None: """Send code by user's notify service.""" if self._user_settings is None: await self._async_load() assert self._user_settings is not None notify_setting = self._user_settings.get(user_id, None) if notify_setting is None: _LOGGER.error("Cannot find user %s", user_id) return await self.async_notify( code, notify_setting.notify_service, # type: ignore notify_setting.target, ) async def async_notify( self, code: str, notify_service: str, target: Optional[str] = None ) -> None: """Send code by notify service.""" data = {"message": self._message_template.format(code)} if target: data["target"] = [target] await self.hass.services.async_call("notify", notify_service, data) class NotifySetupFlow(SetupFlow): """Handler for the setup flow.""" def __init__( self, auth_module: NotifyAuthModule, setup_schema: vol.Schema, user_id: str, available_notify_services: List[str], ) -> None: """Initialize the setup flow.""" super().__init__(auth_module, setup_schema, user_id) # to fix typing complaint self._auth_module: NotifyAuthModule = auth_module self._available_notify_services = available_notify_services self._secret: Optional[str] = None self._count: Optional[int] = None self._notify_service: Optional[str] = None self._target: Optional[str] = None async def async_step_init( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Let user select available notify services.""" errors: Dict[str, str] = {} hass = self._auth_module.hass if user_input: self._notify_service = user_input["notify_service"] self._target = user_input.get("target") self._secret = await hass.async_add_executor_job(_generate_secret) self._count = await hass.async_add_executor_job(_generate_random) return await self.async_step_setup() if not self._available_notify_services: return self.async_abort(reason="no_available_service") schema: Dict[str, Any] = OrderedDict() schema["notify_service"] = vol.In(self._available_notify_services) schema["target"] = vol.Optional(str) return self.async_show_form( step_id="init", data_schema=vol.Schema(schema), errors=errors ) async def async_step_setup( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Verify user can recevie one-time password.""" errors: Dict[str, str] = {} hass = self._auth_module.hass if user_input: verified = await hass.async_add_executor_job( _verify_otp, self._secret, user_input["code"], self._count ) if verified: await self._auth_module.async_setup_user( self._user_id, {"notify_service": self._notify_service, "target": self._target}, ) return self.async_create_entry(title=self._auth_module.name, data={}) errors["base"] = "invalid_code" # generate code every time, no retry logic assert self._secret and self._count code = await hass.async_add_executor_job( _generate_otp, self._secret, self._count ) assert self._notify_service try: await self._auth_module.async_notify( code, self._notify_service, self._target ) except ServiceNotFound: return self.async_abort(reason="notify_service_not_exist") return self.async_show_form( step_id="setup", data_schema=self._setup_schema, description_placeholders={"notify_service": self._notify_service}, errors=errors, )
# Copyright 2016 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. # ============================================================================== """Base classes for probability distributions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import contextlib import types import numpy as np import six from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops.distributions import kullback_leibler from tensorflow.python.ops.distributions import util from tensorflow.python.util import tf_inspect from tensorflow.python.util.tf_export import tf_export __all__ = [ "ReparameterizationType", "FULLY_REPARAMETERIZED", "NOT_REPARAMETERIZED", "Distribution", ] _DISTRIBUTION_PUBLIC_METHOD_WRAPPERS = [ "batch_shape", "batch_shape_tensor", "cdf", "covariance", "cross_entropy", "entropy", "event_shape", "event_shape_tensor", "kl_divergence", "log_cdf", "log_prob", "log_survival_function", "mean", "mode", "prob", "sample", "stddev", "survival_function", "variance", ] @six.add_metaclass(abc.ABCMeta) class _BaseDistribution(object): """Abstract base class needed for resolving subclass hierarchy.""" pass def _copy_fn(fn): """Create a deep copy of fn. Args: fn: a callable Returns: A `FunctionType`: a deep copy of fn. Raises: TypeError: if `fn` is not a callable. """ if not callable(fn): raise TypeError("fn is not callable: %s" % fn) # The blessed way to copy a function. copy.deepcopy fails to create a # non-reference copy. Since: # types.FunctionType == type(lambda: None), # and the docstring for the function type states: # # function(code, globals[, name[, argdefs[, closure]]]) # # Create a function object from a code object and a dictionary. # ... # # Here we can use this to create a new function with the old function's # code, globals, closure, etc. return types.FunctionType( code=fn.__code__, globals=fn.__globals__, name=fn.__name__, argdefs=fn.__defaults__, closure=fn.__closure__) def _update_docstring(old_str, append_str): """Update old_str by inserting append_str just before the "Args:" section.""" old_str = old_str or "" old_str_lines = old_str.split("\n") # Step 0: Prepend spaces to all lines of append_str. This is # necessary for correct markdown generation. append_str = "\n".join(" %s" % line for line in append_str.split("\n")) # Step 1: Find mention of "Args": has_args_ix = [ ix for ix, line in enumerate(old_str_lines) if line.strip().lower() == "args:"] if has_args_ix: final_args_ix = has_args_ix[-1] return ("\n".join(old_str_lines[:final_args_ix]) + "\n\n" + append_str + "\n\n" + "\n".join(old_str_lines[final_args_ix:])) else: return old_str + "\n\n" + append_str def _convert_to_tensor(value, name=None, preferred_dtype=None): """Converts to tensor avoiding an eager bug that loses float precision.""" # TODO(b/116672045): Remove this function. if (context.executing_eagerly() and preferred_dtype is not None and (preferred_dtype.is_integer or preferred_dtype.is_bool)): v = ops.convert_to_tensor(value, name=name) if v.dtype.is_floating: return v return ops.convert_to_tensor( value, name=name, preferred_dtype=preferred_dtype) class _DistributionMeta(abc.ABCMeta): def __new__(mcs, classname, baseclasses, attrs): """Control the creation of subclasses of the Distribution class. The main purpose of this method is to properly propagate docstrings from private Distribution methods, like `_log_prob`, into their public wrappers as inherited by the Distribution base class (e.g. `log_prob`). Args: classname: The name of the subclass being created. baseclasses: A tuple of parent classes. attrs: A dict mapping new attributes to their values. Returns: The class object. Raises: TypeError: If `Distribution` is not a subclass of `BaseDistribution`, or the new class is derived via multiple inheritance and the first parent class is not a subclass of `BaseDistribution`. AttributeError: If `Distribution` does not implement e.g. `log_prob`. ValueError: If a `Distribution` public method lacks a docstring. """ if not baseclasses: # Nothing to be done for Distribution raise TypeError("Expected non-empty baseclass. Does Distribution " "not subclass _BaseDistribution?") which_base = [ base for base in baseclasses if base == _BaseDistribution or issubclass(base, Distribution)] base = which_base[0] if base == _BaseDistribution: # Nothing to be done for Distribution return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs) if not issubclass(base, Distribution): raise TypeError("First parent class declared for %s must be " "Distribution, but saw '%s'" % (classname, base.__name__)) for attr in _DISTRIBUTION_PUBLIC_METHOD_WRAPPERS: special_attr = "_%s" % attr class_attr_value = attrs.get(attr, None) if attr in attrs: # The method is being overridden, do not update its docstring continue base_attr_value = getattr(base, attr, None) if not base_attr_value: raise AttributeError( "Internal error: expected base class '%s' to implement method '%s'" % (base.__name__, attr)) class_special_attr_value = attrs.get(special_attr, None) if class_special_attr_value is None: # No _special method available, no need to update the docstring. continue class_special_attr_docstring = tf_inspect.getdoc(class_special_attr_value) if not class_special_attr_docstring: # No docstring to append. continue class_attr_value = _copy_fn(base_attr_value) class_attr_docstring = tf_inspect.getdoc(base_attr_value) if class_attr_docstring is None: raise ValueError( "Expected base class fn to contain a docstring: %s.%s" % (base.__name__, attr)) class_attr_value.__doc__ = _update_docstring( class_attr_value.__doc__, ("Additional documentation from `%s`:\n\n%s" % (classname, class_special_attr_docstring))) attrs[attr] = class_attr_value return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs) @tf_export("distributions.ReparameterizationType") class ReparameterizationType(object): """Instances of this class represent how sampling is reparameterized. Two static instances exist in the distributions library, signifying one of two possible properties for samples from a distribution: `FULLY_REPARAMETERIZED`: Samples from the distribution are fully reparameterized, and straight-through gradients are supported. `NOT_REPARAMETERIZED`: Samples from the distribution are not fully reparameterized, and straight-through gradients are either partially unsupported or are not supported at all. In this case, for purposes of e.g. RL or variational inference, it is generally safest to wrap the sample results in a `stop_gradients` call and use policy gradients / surrogate loss instead. """ def __init__(self, rep_type): self._rep_type = rep_type def __repr__(self): return "<Reparameteriation Type: %s>" % self._rep_type def __eq__(self, other): """Determine if this `ReparameterizationType` is equal to another. Since RepaparameterizationType instances are constant static global instances, equality checks if two instances' id() values are equal. Args: other: Object to compare against. Returns: `self is other`. """ return self is other # Fully reparameterized distribution: samples from a fully # reparameterized distribution support straight-through gradients with # respect to all parameters. FULLY_REPARAMETERIZED = ReparameterizationType("FULLY_REPARAMETERIZED") tf_export("distributions.FULLY_REPARAMETERIZED").export_constant( __name__, "FULLY_REPARAMETERIZED") # Not reparameterized distribution: samples from a non- # reparameterized distribution do not support straight-through gradients for # at least some of the parameters. NOT_REPARAMETERIZED = ReparameterizationType("NOT_REPARAMETERIZED") tf_export("distributions.NOT_REPARAMETERIZED").export_constant( __name__, "NOT_REPARAMETERIZED") @six.add_metaclass(_DistributionMeta) @tf_export("distributions.Distribution") class Distribution(_BaseDistribution): """A generic probability distribution base class. `Distribution` is a base class for constructing and organizing properties (e.g., mean, variance) of random variables (e.g, Bernoulli, Gaussian). #### Subclassing Subclasses are expected to implement a leading-underscore version of the same-named function. The argument signature should be identical except for the omission of `name="..."`. For example, to enable `log_prob(value, name="log_prob")` a subclass should implement `_log_prob(value)`. Subclasses can append to public-level docstrings by providing docstrings for their method specializations. For example: ```python @util.AppendDocstring("Some other details.") def _log_prob(self, value): ... ``` would add the string "Some other details." to the `log_prob` function docstring. This is implemented as a simple decorator to avoid python linter complaining about missing Args/Returns/Raises sections in the partial docstrings. #### Broadcasting, batching, and shapes All distributions support batches of independent distributions of that type. The batch shape is determined by broadcasting together the parameters. The shape of arguments to `__init__`, `cdf`, `log_cdf`, `prob`, and `log_prob` reflect this broadcasting, as does the return value of `sample` and `sample_n`. `sample_n_shape = [n] + batch_shape + event_shape`, where `sample_n_shape` is the shape of the `Tensor` returned from `sample_n`, `n` is the number of samples, `batch_shape` defines how many independent distributions there are, and `event_shape` defines the shape of samples from each of those independent distributions. Samples are independent along the `batch_shape` dimensions, but not necessarily so along the `event_shape` dimensions (depending on the particulars of the underlying distribution). Using the `Uniform` distribution as an example: ```python minval = 3.0 maxval = [[4.0, 6.0], [10.0, 12.0]] # Broadcasting: # This instance represents 4 Uniform distributions. Each has a lower bound at # 3.0 as the `minval` parameter was broadcasted to match `maxval`'s shape. u = Uniform(minval, maxval) # `event_shape` is `TensorShape([])`. event_shape = u.event_shape # `event_shape_t` is a `Tensor` which will evaluate to []. event_shape_t = u.event_shape_tensor() # Sampling returns a sample per distribution. `samples` has shape # [5, 2, 2], which is [n] + batch_shape + event_shape, where n=5, # batch_shape=[2, 2], and event_shape=[]. samples = u.sample_n(5) # The broadcasting holds across methods. Here we use `cdf` as an example. The # same holds for `log_cdf` and the likelihood functions. # `cum_prob` has shape [2, 2] as the `value` argument was broadcasted to the # shape of the `Uniform` instance. cum_prob_broadcast = u.cdf(4.0) # `cum_prob`'s shape is [2, 2], one per distribution. No broadcasting # occurred. cum_prob_per_dist = u.cdf([[4.0, 5.0], [6.0, 7.0]]) # INVALID as the `value` argument is not broadcastable to the distribution's # shape. cum_prob_invalid = u.cdf([4.0, 5.0, 6.0]) ``` #### Shapes There are three important concepts associated with TensorFlow Distributions shapes: - Event shape describes the shape of a single draw from the distribution; it may be dependent across dimensions. For scalar distributions, the event shape is `[]`. For a 5-dimensional MultivariateNormal, the event shape is `[5]`. - Batch shape describes independent, not identically distributed draws, aka a "collection" or "bunch" of distributions. - Sample shape describes independent, identically distributed draws of batches from the distribution family. The event shape and the batch shape are properties of a Distribution object, whereas the sample shape is associated with a specific call to `sample` or `log_prob`. For detailed usage examples of TensorFlow Distributions shapes, see [this tutorial]( https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Understanding_TensorFlow_Distributions_Shapes.ipynb) #### Parameter values leading to undefined statistics or distributions. Some distributions do not have well-defined statistics for all initialization parameter values. For example, the beta distribution is parameterized by positive real numbers `concentration1` and `concentration0`, and does not have well-defined mode if `concentration1 < 1` or `concentration0 < 1`. The user is given the option of raising an exception or returning `NaN`. ```python a = tf.exp(tf.matmul(logits, weights_a)) b = tf.exp(tf.matmul(logits, weights_b)) # Will raise exception if ANY batch member has a < 1 or b < 1. dist = distributions.beta(a, b, allow_nan_stats=False) mode = dist.mode().eval() # Will return NaN for batch members with either a < 1 or b < 1. dist = distributions.beta(a, b, allow_nan_stats=True) # Default behavior mode = dist.mode().eval() ``` In all cases, an exception is raised if *invalid* parameters are passed, e.g. ```python # Will raise an exception if any Op is run. negative_a = -1.0 * a # beta distribution by definition has a > 0. dist = distributions.beta(negative_a, b, allow_nan_stats=True) dist.mean().eval() ``` """ def __init__(self, dtype, reparameterization_type, validate_args, allow_nan_stats, parameters=None, graph_parents=None, name=None): """Constructs the `Distribution`. **This is a private method for subclass use.** Args: dtype: The type of the event samples. `None` implies no type-enforcement. reparameterization_type: Instance of `ReparameterizationType`. If `distributions.FULLY_REPARAMETERIZED`, this `Distribution` can be reparameterized in terms of some standard distribution with a function whose Jacobian is constant for the support of the standard distribution. If `distributions.NOT_REPARAMETERIZED`, then no such reparameterization is available. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. parameters: Python `dict` of parameters used to instantiate this `Distribution`. graph_parents: Python `list` of graph prerequisites of this `Distribution`. name: Python `str` name prefixed to Ops created by this class. Default: subclass name. Raises: ValueError: if any member of graph_parents is `None` or not a `Tensor`. """ graph_parents = [] if graph_parents is None else graph_parents for i, t in enumerate(graph_parents): if t is None or not tensor_util.is_tensor(t): raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t)) if not name or name[-1] != "/": # `name` is not a name scope non_unique_name = name or type(self).__name__ with ops.name_scope(non_unique_name) as name: pass self._dtype = dtype self._reparameterization_type = reparameterization_type self._allow_nan_stats = allow_nan_stats self._validate_args = validate_args self._parameters = parameters or {} self._graph_parents = graph_parents self._name = name @property def _parameters(self): return self._parameter_dict @_parameters.setter def _parameters(self, value): """Intercept assignments to self._parameters to avoid reference cycles. Parameters are often created using locals(), so we need to clean out any references to `self` before assigning it to an attribute. Args: value: A dictionary of parameters to assign to the `_parameters` property. """ if "self" in value: del value["self"] self._parameter_dict = value @classmethod def param_shapes(cls, sample_shape, name="DistributionParamShapes"): """Shapes of parameters given the desired shape of a call to `sample()`. This is a class method that describes what key/value arguments are required to instantiate the given `Distribution` so that a particular shape is returned for that instance's call to `sample()`. Subclasses should override class method `_param_shapes`. Args: sample_shape: `Tensor` or python list/tuple. Desired shape of a call to `sample()`. name: name to prepend ops with. Returns: `dict` of parameter name to `Tensor` shapes. """ with ops.name_scope(name, values=[sample_shape]): return cls._param_shapes(sample_shape) @classmethod def param_static_shapes(cls, sample_shape): """param_shapes with static (i.e. `TensorShape`) shapes. This is a class method that describes what key/value arguments are required to instantiate the given `Distribution` so that a particular shape is returned for that instance's call to `sample()`. Assumes that the sample's shape is known statically. Subclasses should override class method `_param_shapes` to return constant-valued tensors when constant values are fed. Args: sample_shape: `TensorShape` or python list/tuple. Desired shape of a call to `sample()`. Returns: `dict` of parameter name to `TensorShape`. Raises: ValueError: if `sample_shape` is a `TensorShape` and is not fully defined. """ if isinstance(sample_shape, tensor_shape.TensorShape): if not sample_shape.is_fully_defined(): raise ValueError("TensorShape sample_shape must be fully defined") sample_shape = sample_shape.as_list() params = cls.param_shapes(sample_shape) static_params = {} for name, shape in params.items(): static_shape = tensor_util.constant_value(shape) if static_shape is None: raise ValueError( "sample_shape must be a fully-defined TensorShape or list/tuple") static_params[name] = tensor_shape.TensorShape(static_shape) return static_params @staticmethod def _param_shapes(sample_shape): raise NotImplementedError("_param_shapes not implemented") @property def name(self): """Name prepended to all ops created by this `Distribution`.""" return self._name @property def dtype(self): """The `DType` of `Tensor`s handled by this `Distribution`.""" return self._dtype @property def parameters(self): """Dictionary of parameters used to instantiate this `Distribution`.""" # Remove "self", "__class__", or other special variables. These can appear # if the subclass used: # `parameters = dict(locals())`. return {k: v for k, v in self._parameters.items() if not k.startswith("__") and k != "self"} @property def reparameterization_type(self): """Describes how samples from the distribution are reparameterized. Currently this is one of the static instances `distributions.FULLY_REPARAMETERIZED` or `distributions.NOT_REPARAMETERIZED`. Returns: An instance of `ReparameterizationType`. """ return self._reparameterization_type @property def allow_nan_stats(self): """Python `bool` describing behavior when a stat is undefined. Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined. Returns: allow_nan_stats: Python `bool`. """ return self._allow_nan_stats @property def validate_args(self): """Python `bool` indicating possibly expensive checks are enabled.""" return self._validate_args def copy(self, **override_parameters_kwargs): """Creates a deep copy of the distribution. Note: the copy distribution may continue to depend on the original initialization arguments. Args: **override_parameters_kwargs: String/value dictionary of initialization arguments to override with new values. Returns: distribution: A new instance of `type(self)` initialized from the union of self.parameters and override_parameters_kwargs, i.e., `dict(self.parameters, **override_parameters_kwargs)`. """ parameters = dict(self.parameters, **override_parameters_kwargs) return type(self)(**parameters) def _batch_shape_tensor(self): raise NotImplementedError( "batch_shape_tensor is not implemented: {}".format(type(self).__name__)) def batch_shape_tensor(self, name="batch_shape_tensor"): """Shape of a single sample from a single event index as a 1-D `Tensor`. The batch dimensions are indexes into independent, non-identical parameterizations of this distribution. Args: name: name to give to the op Returns: batch_shape: `Tensor`. """ with self._name_scope(name): if self.batch_shape.is_fully_defined(): return ops.convert_to_tensor(self.batch_shape.as_list(), dtype=dtypes.int32, name="batch_shape") return self._batch_shape_tensor() def _batch_shape(self): return tensor_shape.TensorShape(None) @property def batch_shape(self): """Shape of a single sample from a single event index as a `TensorShape`. May be partially defined or unknown. The batch dimensions are indexes into independent, non-identical parameterizations of this distribution. Returns: batch_shape: `TensorShape`, possibly unknown. """ return tensor_shape.as_shape(self._batch_shape()) def _event_shape_tensor(self): raise NotImplementedError( "event_shape_tensor is not implemented: {}".format(type(self).__name__)) def event_shape_tensor(self, name="event_shape_tensor"): """Shape of a single sample from a single batch as a 1-D int32 `Tensor`. Args: name: name to give to the op Returns: event_shape: `Tensor`. """ with self._name_scope(name): if self.event_shape.is_fully_defined(): return ops.convert_to_tensor(self.event_shape.as_list(), dtype=dtypes.int32, name="event_shape") return self._event_shape_tensor() def _event_shape(self): return tensor_shape.TensorShape(None) @property def event_shape(self): """Shape of a single sample from a single batch as a `TensorShape`. May be partially defined or unknown. Returns: event_shape: `TensorShape`, possibly unknown. """ return tensor_shape.as_shape(self._event_shape()) def is_scalar_event(self, name="is_scalar_event"): """Indicates that `event_shape == []`. Args: name: Python `str` prepended to names of ops created by this function. Returns: is_scalar_event: `bool` scalar `Tensor`. """ with self._name_scope(name): return ops.convert_to_tensor( self._is_scalar_helper(self.event_shape, self.event_shape_tensor), name="is_scalar_event") def is_scalar_batch(self, name="is_scalar_batch"): """Indicates that `batch_shape == []`. Args: name: Python `str` prepended to names of ops created by this function. Returns: is_scalar_batch: `bool` scalar `Tensor`. """ with self._name_scope(name): return ops.convert_to_tensor( self._is_scalar_helper(self.batch_shape, self.batch_shape_tensor), name="is_scalar_batch") def _sample_n(self, n, seed=None): raise NotImplementedError("sample_n is not implemented: {}".format( type(self).__name__)) def _call_sample_n(self, sample_shape, seed, name, **kwargs): with self._name_scope(name, values=[sample_shape]): sample_shape = ops.convert_to_tensor( sample_shape, dtype=dtypes.int32, name="sample_shape") sample_shape, n = self._expand_sample_shape_to_vector( sample_shape, "sample_shape") samples = self._sample_n(n, seed, **kwargs) batch_event_shape = array_ops.shape(samples)[1:] final_shape = array_ops.concat([sample_shape, batch_event_shape], 0) samples = array_ops.reshape(samples, final_shape) samples = self._set_sample_static_shape(samples, sample_shape) return samples def sample(self, sample_shape=(), seed=None, name="sample"): """Generate samples of the specified shape. Note that a call to `sample()` without arguments will generate a single sample. Args: sample_shape: 0D or 1D `int32` `Tensor`. Shape of the generated samples. seed: Python integer seed for RNG name: name to give to the op. Returns: samples: a `Tensor` with prepended dimensions `sample_shape`. """ return self._call_sample_n(sample_shape, seed, name) def _log_prob(self, value): raise NotImplementedError("log_prob is not implemented: {}".format( type(self).__name__)) def _call_log_prob(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) try: return self._log_prob(value, **kwargs) except NotImplementedError as original_exception: try: return math_ops.log(self._prob(value, **kwargs)) except NotImplementedError: raise original_exception def log_prob(self, value, name="log_prob"): """Log probability density/mass function. Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: log_prob: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_log_prob(value, name) def _prob(self, value): raise NotImplementedError("prob is not implemented: {}".format( type(self).__name__)) def _call_prob(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) try: return self._prob(value, **kwargs) except NotImplementedError as original_exception: try: return math_ops.exp(self._log_prob(value, **kwargs)) except NotImplementedError: raise original_exception def prob(self, value, name="prob"): """Probability density/mass function. Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: prob: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_prob(value, name) def _log_cdf(self, value): raise NotImplementedError("log_cdf is not implemented: {}".format( type(self).__name__)) def _call_log_cdf(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) try: return self._log_cdf(value, **kwargs) except NotImplementedError as original_exception: try: return math_ops.log(self._cdf(value, **kwargs)) except NotImplementedError: raise original_exception def log_cdf(self, value, name="log_cdf"): """Log cumulative distribution function. Given random variable `X`, the cumulative distribution function `cdf` is: ```none log_cdf(x) := Log[ P[X <= x] ] ``` Often, a numerical approximation can be used for `log_cdf(x)` that yields a more accurate answer than simply taking the logarithm of the `cdf` when `x << -1`. Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: logcdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_log_cdf(value, name) def _cdf(self, value): raise NotImplementedError("cdf is not implemented: {}".format( type(self).__name__)) def _call_cdf(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) try: return self._cdf(value, **kwargs) except NotImplementedError as original_exception: try: return math_ops.exp(self._log_cdf(value, **kwargs)) except NotImplementedError: raise original_exception def cdf(self, value, name="cdf"): """Cumulative distribution function. Given random variable `X`, the cumulative distribution function `cdf` is: ```none cdf(x) := P[X <= x] ``` Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: cdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_cdf(value, name) def _log_survival_function(self, value): raise NotImplementedError( "log_survival_function is not implemented: {}".format( type(self).__name__)) def _call_log_survival_function(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) try: return self._log_survival_function(value, **kwargs) except NotImplementedError as original_exception: try: return math_ops.log1p(-self.cdf(value, **kwargs)) except NotImplementedError: raise original_exception def log_survival_function(self, value, name="log_survival_function"): """Log survival function. Given random variable `X`, the survival function is defined: ```none log_survival_function(x) = Log[ P[X > x] ] = Log[ 1 - P[X <= x] ] = Log[ 1 - cdf(x) ] ``` Typically, different numerical approximations can be used for the log survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_log_survival_function(value, name) def _survival_function(self, value): raise NotImplementedError("survival_function is not implemented: {}".format( type(self).__name__)) def _call_survival_function(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) try: return self._survival_function(value, **kwargs) except NotImplementedError as original_exception: try: return 1. - self.cdf(value, **kwargs) except NotImplementedError: raise original_exception def survival_function(self, value, name="survival_function"): """Survival function. Given random variable `X`, the survival function is defined: ```none survival_function(x) = P[X > x] = 1 - P[X <= x] = 1 - cdf(x). ``` Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_survival_function(value, name) def _entropy(self): raise NotImplementedError("entropy is not implemented: {}".format( type(self).__name__)) def entropy(self, name="entropy"): """Shannon entropy in nats.""" with self._name_scope(name): return self._entropy() def _mean(self): raise NotImplementedError("mean is not implemented: {}".format( type(self).__name__)) def mean(self, name="mean"): """Mean.""" with self._name_scope(name): return self._mean() def _quantile(self, value): raise NotImplementedError("quantile is not implemented: {}".format( type(self).__name__)) def _call_quantile(self, value, name, **kwargs): with self._name_scope(name, values=[value]): value = _convert_to_tensor( value, name="value", preferred_dtype=self.dtype) return self._quantile(value, **kwargs) def quantile(self, value, name="quantile"): """Quantile function. Aka "inverse cdf" or "percent point function". Given random variable `X` and `p in [0, 1]`, the `quantile` is: ```none quantile(p) := x such that P[X <= x] == p ``` Args: value: `float` or `double` `Tensor`. name: Python `str` prepended to names of ops created by this function. Returns: quantile: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type `self.dtype`. """ return self._call_quantile(value, name) def _variance(self): raise NotImplementedError("variance is not implemented: {}".format( type(self).__name__)) def variance(self, name="variance"): """Variance. Variance is defined as, ```none Var = E[(X - E[X])**2] ``` where `X` is the random variable associated with this distribution, `E` denotes expectation, and `Var.shape = batch_shape + event_shape`. Args: name: Python `str` prepended to names of ops created by this function. Returns: variance: Floating-point `Tensor` with shape identical to `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. """ with self._name_scope(name): try: return self._variance() except NotImplementedError as original_exception: try: return math_ops.square(self._stddev()) except NotImplementedError: raise original_exception def _stddev(self): raise NotImplementedError("stddev is not implemented: {}".format( type(self).__name__)) def stddev(self, name="stddev"): """Standard deviation. Standard deviation is defined as, ```none stddev = E[(X - E[X])**2]**0.5 ``` where `X` is the random variable associated with this distribution, `E` denotes expectation, and `stddev.shape = batch_shape + event_shape`. Args: name: Python `str` prepended to names of ops created by this function. Returns: stddev: Floating-point `Tensor` with shape identical to `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. """ with self._name_scope(name): try: return self._stddev() except NotImplementedError as original_exception: try: return math_ops.sqrt(self._variance()) except NotImplementedError: raise original_exception def _covariance(self): raise NotImplementedError("covariance is not implemented: {}".format( type(self).__name__)) def covariance(self, name="covariance"): """Covariance. Covariance is (possibly) defined only for non-scalar-event distributions. For example, for a length-`k`, vector-valued distribution, it is calculated as, ```none Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] ``` where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` denotes expectation. Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices under some vectorization of the events, i.e., ```none Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] ``` where `Cov` is a (batch of) `k' x k'` matrices, `0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function mapping indices of this distribution's event dimensions to indices of a length-`k'` vector. Args: name: Python `str` prepended to names of ops created by this function. Returns: covariance: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` where the first `n` dimensions are batch coordinates and `k' = reduce_prod(self.event_shape)`. """ with self._name_scope(name): return self._covariance() def _mode(self): raise NotImplementedError("mode is not implemented: {}".format( type(self).__name__)) def mode(self, name="mode"): """Mode.""" with self._name_scope(name): return self._mode() def _cross_entropy(self, other): return kullback_leibler.cross_entropy( self, other, allow_nan_stats=self.allow_nan_stats) def cross_entropy(self, other, name="cross_entropy"): """Computes the (Shannon) cross entropy. Denote this distribution (`self`) by `P` and the `other` distribution by `Q`. Assuming `P, Q` are absolutely continuous with respect to one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) cross entropy is defined as: ```none H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) ``` where `F` denotes the support of the random variable `X ~ P`. Args: other: `tfp.distributions.Distribution` instance. name: Python `str` prepended to names of ops created by this function. Returns: cross_entropy: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` representing `n` different calculations of (Shanon) cross entropy. """ with self._name_scope(name): return self._cross_entropy(other) def _kl_divergence(self, other): return kullback_leibler.kl_divergence( self, other, allow_nan_stats=self.allow_nan_stats) def kl_divergence(self, other, name="kl_divergence"): """Computes the Kullback--Leibler divergence. Denote this distribution (`self`) by `p` and the `other` distribution by `q`. Assuming `p, q` are absolutely continuous with respect to reference measure `r`, the KL divergence is defined as: ```none KL[p, q] = E_p[log(p(X)/q(X))] = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) = H[p, q] - H[p] ``` where `F` denotes the support of the random variable `X ~ p`, `H[., .]` denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. Args: other: `tfp.distributions.Distribution` instance. name: Python `str` prepended to names of ops created by this function. Returns: kl_divergence: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` representing `n` different calculations of the Kullback-Leibler divergence. """ with self._name_scope(name): return self._kl_divergence(other) def __str__(self): return ("tfp.distributions.{type_name}(" "\"{self_name}\"" "{maybe_batch_shape}" "{maybe_event_shape}" ", dtype={dtype})".format( type_name=type(self).__name__, self_name=self.name, maybe_batch_shape=(", batch_shape={}".format(self.batch_shape) if self.batch_shape.ndims is not None else ""), maybe_event_shape=(", event_shape={}".format(self.event_shape) if self.event_shape.ndims is not None else ""), dtype=self.dtype.name)) def __repr__(self): return ("<tfp.distributions.{type_name} " "'{self_name}'" " batch_shape={batch_shape}" " event_shape={event_shape}" " dtype={dtype}>".format( type_name=type(self).__name__, self_name=self.name, batch_shape=self.batch_shape, event_shape=self.event_shape, dtype=self.dtype.name)) @contextlib.contextmanager def _name_scope(self, name=None, values=None): """Helper function to standardize op scope.""" with ops.name_scope(self.name): with ops.name_scope(name, values=( ([] if values is None else values) + self._graph_parents)) as scope: yield scope def _expand_sample_shape_to_vector(self, x, name): """Helper to `sample` which ensures input is 1D.""" x_static_val = tensor_util.constant_value(x) if x_static_val is None: prod = math_ops.reduce_prod(x) else: prod = np.prod(x_static_val, dtype=x.dtype.as_numpy_dtype()) ndims = x.get_shape().ndims # != sample_ndims if ndims is None: # Maybe expand_dims. ndims = array_ops.rank(x) expanded_shape = util.pick_vector( math_ops.equal(ndims, 0), np.array([1], dtype=np.int32), array_ops.shape(x)) x = array_ops.reshape(x, expanded_shape) elif ndims == 0: # Definitely expand_dims. if x_static_val is not None: x = ops.convert_to_tensor( np.array([x_static_val], dtype=x.dtype.as_numpy_dtype()), name=name) else: x = array_ops.reshape(x, [1]) elif ndims != 1: raise ValueError("Input is neither scalar nor vector.") return x, prod def _set_sample_static_shape(self, x, sample_shape): """Helper to `sample`; sets static shape info.""" # Set shape hints. sample_shape = tensor_shape.TensorShape( tensor_util.constant_value(sample_shape)) ndims = x.get_shape().ndims sample_ndims = sample_shape.ndims batch_ndims = self.batch_shape.ndims event_ndims = self.event_shape.ndims # Infer rank(x). if (ndims is None and sample_ndims is not None and batch_ndims is not None and event_ndims is not None): ndims = sample_ndims + batch_ndims + event_ndims x.set_shape([None] * ndims) # Infer sample shape. if ndims is not None and sample_ndims is not None: shape = sample_shape.concatenate([None]*(ndims - sample_ndims)) x.set_shape(x.get_shape().merge_with(shape)) # Infer event shape. if ndims is not None and event_ndims is not None: shape = tensor_shape.TensorShape( [None]*(ndims - event_ndims)).concatenate(self.event_shape) x.set_shape(x.get_shape().merge_with(shape)) # Infer batch shape. if batch_ndims is not None: if ndims is not None: if sample_ndims is None and event_ndims is not None: sample_ndims = ndims - batch_ndims - event_ndims elif event_ndims is None and sample_ndims is not None: event_ndims = ndims - batch_ndims - sample_ndims if sample_ndims is not None and event_ndims is not None: shape = tensor_shape.TensorShape([None]*sample_ndims).concatenate( self.batch_shape).concatenate([None]*event_ndims) x.set_shape(x.get_shape().merge_with(shape)) return x def _is_scalar_helper(self, static_shape, dynamic_shape_fn): """Implementation for `is_scalar_batch` and `is_scalar_event`.""" if static_shape.ndims is not None: return static_shape.ndims == 0 shape = dynamic_shape_fn() if (shape.get_shape().ndims is not None and shape.get_shape()[0].value is not None): # If the static_shape is correctly written then we should never execute # this branch. We keep it just in case there's some unimagined corner # case. return shape.get_shape().as_list() == [0] return math_ops.equal(array_ops.shape(shape)[0], 0)
import sendgrid import json import os sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) ################################################## # Create a domain authentication. # # POST /whitelabel/domains # data = { "automatic_security": False, "custom_spf": True, "default": True, "domain": "example.com", "ips": [ "192.168.1.1", "192.168.1.2" ], "subdomain": "news", "username": "john@example.com" } response = sg.client.whitelabel.domains.post(request_body=data) print(response.status_code) print(response.body) print(response.headers) ################################################## # List all domain authentications. # # GET /whitelabel/domains # params = {'username': 'test_string', 'domain': 'test_string', 'exclude_subusers': 'true', 'limit': 1, 'offset': 1} response = sg.client.whitelabel.domains.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Get the default domain authentication. # # GET /whitelabel/domains/default # response = sg.client.whitelabel.domains.default.get() print(response.status_code) print(response.body) print(response.headers) ################################################## # List the domain authentication associated with the given user. # # GET /whitelabel/domains/subuser # response = sg.client.whitelabel.domains.subuser.get() print(response.status_code) print(response.body) print(response.headers) ################################################## # Disassociate a domain authentication from a given user. # # DELETE /whitelabel/domains/subuser # response = sg.client.whitelabel.domains.subuser.delete() print(response.status_code) print(response.body) print(response.headers) ################################################## # Update a domain authentication. # # PATCH /whitelabel/domains/{domain_id} # data = { "custom_spf": True, "default": False } domain_id = "test_url_param" response = sg.client.whitelabel.domains._(domain_id).patch(request_body=data) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve a domain authentication. # # GET /whitelabel/domains/{domain_id} # domain_id = "test_url_param" response = sg.client.whitelabel.domains._(domain_id).get() print(response.status_code) print(response.body) print(response.headers) ################################################## # Delete a domain authentication. # # DELETE /whitelabel/domains/{domain_id} # domain_id = "test_url_param" response = sg.client.whitelabel.domains._(domain_id).delete() print(response.status_code) print(response.body) print(response.headers) ################################################## # Associate a domain authentication with a given user. # # POST /whitelabel/domains/{domain_id}/subuser # data = { "username": "jane@example.com" } domain_id = "test_url_param" response = sg.client.whitelabel.domains._( domain_id).subuser.post(request_body=data) print(response.status_code) print(response.body) print(response.headers) ################################################## # Add an IP to a domain authentication. # # POST /whitelabel/domains/{id}/ips # data = { "ip": "192.168.0.1" } id_ = "test_url_param" response = sg.client.whitelabel.domains._(id_).ips.post(request_body=data) print(response.status_code) print(response.body) print(response.headers) ################################################## # Remove an IP from a domain authentication. # # DELETE /whitelabel/domains/{id}/ips/{ip} # id_ = "test_url_param" ip = "test_url_param" response = sg.client.whitelabel.domains._(id_).ips._(ip).delete() print(response.status_code) print(response.body) print(response.headers) ################################################## # Validate a domain authentication. # # POST /whitelabel/domains/{id}/validate # id_ = "test_url_param" response = sg.client.whitelabel.domains._(id_).validate.post() print(response.status_code) print(response.body) print(response.headers) ################################################## # Create a reverse DNS record # # POST /whitelabel/ips # data = { "domain": "example.com", "ip": "192.168.1.1", "subdomain": "email" } response = sg.client.whitelabel.ips.post(request_body=data) print(response.status_code) print(response.body) print(response.headers) ################################################## # Create a reverse DNS record # # GET /whitelabel/ips # params = {'ip': 'test_string', 'limit': 1, 'offset': 1} response = sg.client.whitelabel.ips.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve a reverse DNS record # # GET /whitelabel/ips/{id} # id_ = "test_url_param" response = sg.client.whitelabel.ips._(id_).get() print(response.status_code) print(response.body) print(response.headers) ################################################## # Delete a reverse DNS record # # DELETE /whitelabel/ips/{id} # id_ = "test_url_param" response = sg.client.whitelabel.ips._(id_).delete() print(response.status_code) print(response.body) print(response.headers) ################################################## # Validate a reverse DNS record # # POST /whitelabel/ips/{id}/validate # id_ = "test_url_param" response = sg.client.whitelabel.ips._(id_).validate.post() print(response.status_code) print(response.body) print(response.headers) ################################################## # Create a Link Branding # # POST /whitelabel/links # data = { "default": True, "domain": "example.com", "subdomain": "mail" } params = {'limit': 1, 'offset': 1} response = sg.client.whitelabel.links.post( request_body=data, query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve all link brandings # # GET /whitelabel/links # params = {'limit': 1} response = sg.client.whitelabel.links.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve a Default Link Branding # # GET /whitelabel/links/default # params = {'domain': 'test_string'} response = sg.client.whitelabel.links.default.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve Associated Link Branding # # GET /whitelabel/links/subuser # params = {'username': 'test_string'} response = sg.client.whitelabel.links.subuser.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Disassociate a Link Branding # # DELETE /whitelabel/links/subuser # params = {'username': 'test_string'} response = sg.client.whitelabel.links.subuser.delete(query_params=params) print(response.status_code) print(response.body) print(response.headers) ################################################## # Update a Link Branding # # PATCH /whitelabel/links/{id} # data = { "default": True } id_ = "test_url_param" response = sg.client.whitelabel.links._(id_).patch(request_body=data) print(response.status_code) print(response.body) print(response.headers) ################################################## # Retrieve a Link Branding # # GET /whitelabel/links/{id} # id_ = "test_url_param" response = sg.client.whitelabel.links._(id_).get() print(response.status_code) print(response.body) print(response.headers) ################################################## # Delete a Link Branding # # DELETE /whitelabel/links/{id} # id_ = "test_url_param" response = sg.client.whitelabel.links._(id_).delete() print(response.status_code) print(response.body) print(response.headers) ################################################## # Validate a Link Branding # # POST /whitelabel/links/{id}/validate # id_ = "test_url_param" response = sg.client.whitelabel.links._(id_).validate.post() print(response.status_code) print(response.body) print(response.headers) ################################################## # Associate a Link Branding # # POST /whitelabel/links/{link_id}/subuser # data = { "username": "jane@example.com" } link_id = "test_url_param" response = sg.client.whitelabel.links._( link_id).subuser.post(request_body=data) print(response.status_code) print(response.body) print(response.headers)
# Copyright (c) 2006-2013 Regents of the University of Minnesota. # For licensing terms, see the file LICENSE. import conf import g from grax.access_level import Access_Level from grax.user import User from gwis.exception.gwis_error import GWIS_Error from item import grac_record from item import item_base from item import item_versioned from item.grac import group from item.grac import groupy_base from item.util import revision from item.util.item_type import Item_Type from util_ import gml __all__ = ['One', 'Many'] log = g.log.getLogger('group_membership') class One(groupy_base.One): item_type_id = Item_Type.GROUP_MEMBERSHIP item_type_table = 'group_membership' item_gwis_abbrev = 'gmp' child_item_types = None local_defns = [ # FIXME: I think pkey? is really notnull? # py/psql name, deft, send?, pkey?, pytyp, reqv, abbrev # Group Membership details ('access_level_id', None, True, True, int, 2, 'alid'), ('opt_out', None, True, False, bool, 1), # User details # FIXME: User ID or name? Is using ID bad? Group ID or, is group name # unique, too? I don't know... maybe Group Description is really # Group Friendly Name? ('user_id', None, False, True, int, 0), ('username', None, True, True, str, 0), # Group details # NOTE: 'group_desc' is at group_.description. ('group_desc', None, True), # NOTE: 'group_scope' is at group_.access_scope_id. ('group_scope', None, True), ] attr_defns = groupy_base.One.attr_defns + local_defns psql_defns = groupy_base.One.psql_defns + local_defns gwis_defns = item_base.One.attr_defns_reduce_for_gwis(attr_defns) __slots__ = [] + [attr_defn[0] for attr_defn in local_defns] # *** Constructor def __init__(self, qb=None, row=None, req=None, copy_from=None): g.assurt(copy_from is None) # Not supported for this class. groupy_base.One.__init__(self, qb, row, req, copy_from) # *** GML/XML Processing # def from_gml(self, qb, elem): groupy_base.One.from_gml(self, qb, elem) # Resolve the user_id if self.user_id and self.username: raise GWIS_Error( 'Attr. confusions: Please specify just "user_id" or "username".') elif (not self.user_id) and (not self.username): raise GWIS_Error('Missing mandatory attr: "user_id" or "username".') elif not self.user_id: # FIXME: Should we have a qb passed in, e.g., qb.db and qb.username? self.user_id = User.user_id_from_username(self.req.db, self.username) log.debug('from_gml: resolved user_id %d from username "%s".' % (self.user_id, self.username,)) # Resolve the group_id self.from_gml_group_id(qb) # *** Saving to the Database # def group_ids_add_to(self, group_ids, rid): # FIXME: Care about rid? # I'm [lb isn't] convinced this is cool... mostly, if admin is doing lots # of changes, then admin should know changenote is readable by all # affected. group_ids.add(self.group_id) # # BUG nnnn: This adds duplicates records... # FIXME: Add group_name to group_membership table, for human benefit. # But that means you gotta UPDATE gm when group_ changes. def save_core(self, qb): groupy_base.One.save_core(self, qb) # Save to the 'group_membership' table self.save_insert(qb, One.item_type_table, One.psql_defns) # def version_finalize_preset_is_okay(self): return True # *** class Many(groupy_base.Many): one_class = One __slots__ = () # *** Constructor def __init__(self): groupy_base.Many.__init__(self) # *** Query Builder routines # This is the first call that flashclient makes. If the user is not logged # in, it simply returns the group ID of the public group. Otherwise, it # returns all of the groups IDs (and associated info) of the groups to which # the user belongs. def sql_context_user(self, qb, *args, **kwargs): g.assurt(isinstance(qb.revision, revision.Current) or isinstance(qb.revision, revision.Historic)) sql_user = ( """ SELECT gmp.stack_id , gmp.version , gmp.access_level_id , gmp.opt_out AS opt_out , grp.stack_id AS group_id , grp.version , grp.name AS group_name , grp.description AS group_desc , grp.access_scope_id AS group_scope , GREATEST(gmp.valid_start_rid, grp.valid_start_rid) AS valid_start_rid , LEAST(gmp.valid_until_rid, grp.valid_until_rid) AS valid_until_rid FROM user_ AS u JOIN group_membership AS gmp ON (u.id = gmp.user_id) JOIN group_ AS grp ON (gmp.group_id = grp.stack_id) WHERE u.username = %s AND %s -- group_membership revision AND %s -- group revision AND gmp.access_level_id <= %d GROUP BY gmp.stack_id , gmp.version , gmp.access_level_id , gmp.opt_out , grp.stack_id , grp.version , grp.name , grp.description , grp.access_scope_id , gmp.valid_start_rid , grp.valid_start_rid , gmp.valid_until_rid , grp.valid_until_rid """ % ( # WHERE qb.db.quoted(qb.username), # Given a certain user... qb.revision.as_sql_where_strict('gmp'), qb.revision.as_sql_where_strict('grp'), Access_Level.client, # ...with at least client access )) # The flashclient needs to know the stealth secret stack ID, so it can # locate the corresponding group_item_access records. # 2013.12.20: Also add the Session ID Group. # NOTE: The Stealth-Secret Group and Session ID Group do not have # group_membership records, since the server uses these # group IDs specially. (And if we wired a group_membership # to, e.g., the anon group, then we'd wrongfully give everyone # defacto access to these groups' permissions, rather than # verifying the session ID or stealth secret to give access). # As such, we return NULL values for the group_membership # attributes, like stack_id, version, access_level_id, and # opt_out. The client will remember the group IDs for these # special groups, but it won't create group_membership objects. sql_stealth = ( """ SELECT -- The first parms. are for the non-existant group_membership. NULL AS stack_id , NULL AS version , NULL AS access_level_id , NULL AS opt_out -- The group_ record values. , grp.stack_id AS group_id , grp.version , grp.name AS group_name , grp.description AS group_desc , grp.access_scope_id AS group_scope -- Here again we fake like there's a group_membership record. , 1 AS valid_start_rid , %d AS valid_until_rid FROM group_ AS grp WHERE grp.stack_id IN (%d, %d) """ % ( conf.rid_inf, # In sql, see: cp_group_stealth_id() # MEH: We could just return all group_ records # where access_scope_id = cp_access_scope_id('public') # but we don't plan on making more of these records. group.Many.session_group_id(qb.db), group.Many.stealth_group_id(qb.db), )) sql = ("%s UNION (%s)" % (sql_user, sql_stealth,)) return sql # def search_by_group_id(self, qb, group_stack_id): # Note that the group classes don't use local_defns and have a common # SQL fcn like item_user_access provides. Most of the group class SQL # fetches are pretty custom, though. group_memberships_sql = ( """ SELECT gmp.stack_id , gmp.version , gmp.deleted , gmp.access_level_id , gmp.opt_out AS opt_out , gmp.username , gmp.user_id , grp.stack_id AS group_id , grp.name AS group_name , grp.description AS group_desc , grp.access_scope_id AS group_scope , GREATEST(gmp.valid_start_rid, grp.valid_start_rid) AS valid_start_rid , LEAST(gmp.valid_until_rid, grp.valid_until_rid) AS valid_until_rid FROM group_membership AS gmp JOIN group_ AS grp ON (grp.stack_id = gmp.group_id) JOIN user_ AS u ON (u.id = gmp.user_id) WHERE grp.stack_id = %d AND %s -- group_membership revision AND %s -- group revision /* GROUP BY gmp.stack_id , gmp.version , gmp.access_level_id , gmp.opt_out -- , grp.stack_id , grp.version , grp.name , grp.description , grp.access_scope_id -- , gmp.valid_start_rid , grp.valid_start_rid , gmp.valid_until_rid , grp.valid_until_rid */ """ % (group_stack_id, qb.revision.as_sql_where_strict('gmp'), qb.revision.as_sql_where_strict('grp'),)) self.sql_search(qb, group_memberships_sql) # *** # ***
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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. """(DEPRECATED) Misc utilities for NQL.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from absl import logging import nql import tensorflow.compat.v2 as tf class Model(object): """(DEPRECATED) Help for building Estimator-friendly NQL models. To use this, subclass it, and implement config_* methods, so as to define a procedure for building an NQL model that can be used with tf.Estimators. Specifically you implement - config_context, which will configure a freshly-created NeuralQueryContext object. Usually this means declaring relations and types, loading KG triples, and etc. - config_model_prediction, which will configure a freshly-created Model. Usually this means adding attributes to the model that correspond to NQL or Tensorflow operations to perform the inference done by the model. You can assume that model.context points to the appropriate NeuralQueryContext, configured by config_context. - config_model_training, which adds additional attributes corresponding to a loss function and optimization step. You can assume here that config_model_prediction has been run on this model. - config_model_evaluation, which adds additional attributes for measures like accuracy, etc. You can assume all the other configuration has been done. The metrics should be from the tf.metrics package (or be compatible - i.e., be pairs of metric_uodate_op, metric). Each config_model_* step adds attributes to the Model instance indicating the final outputs of this phase: specifically config_model_prediction adds the attribute model.predictions, config_model_evaluation adds the attribute model.evaluations, and config_model_training adds model.loss and model.train_op. (By 'attribute' above we mean instance variables of the Model object.) """ def __init__(self): # these should all be set to real values in a functioning instance self.context = None self.predictions = None self.train_op = self.loss = None self.evaluations = None # default progress counters used in training self.num_batches = 0 self.num_examples = 0 self.total_loss = 0 def default_training_callback(fd, loss, elapsed_time): """Called after each training step is executed. Arguments: fd: feed dictionary used for the training step. loss: model's loss on the minibatch just used. elapsed_time: time that has elapsed since training started. Returns: string that is a status update. """ # All batches have the same shape. Pick the first one. minibatch_size = list(fd.values())[0].shape[0] self.num_examples += minibatch_size self.num_batches += 1 self.total_loss += loss return ('%d examples in %.2f sec batch loss %.4f avg loss %.4f' % (self.num_examples, elapsed_time, loss, self.total_loss / self.num_batches)) self.training_callback = default_training_callback class ModelBuilder(object): """(DEPRECATED) Help for building Estimator-friendly NQL models. To use this, subclass it, and implement config_* methods, so as to define a procedure for building an NQL model that can be used with tf.Estimators. Specifically you implement - config_context, which will configure a freshly-created NeuralQueryContext object. Usually this means declaring relations and types, loading KG triples, and etc. - config_model_prediction, which will configure a freshly-created model. Usually this means adding attributes to the model that correspond to NQL or Tensorflow operations to perform the inference done by the model. You can assume that model.context points to the appropriate context, configured by config_context. - config_model_training, which adds additional attributes corresponding to a loss function and optimization step. You can assume here that config_model_prediction has been run on this model. - config_model_evaluation, which adds additional attributes for measures like accuracy, etc. You can assume all the other configuration has been done. The metrics should be from the tf.metrics package (or be compatible). Each of the config_model_* steps adds some attributes that indicate the final outputs of this phase: specifically config_model_prediction adds the attribute model.predictions, config_model_evaluation adds the attribute model.evaluations, and config_model_training adds model.loss and model.train_op. """ def build_context(self, context_factory=nql.NeuralQueryContext, gpus=1, params=None): """Create a new NeuralQueryContext and configure it. Args: context_factory: factory to construct the NQL context gpus: number of gpus available for computation params: optional parameters to be passed to config_context Returns: The newly configured context. """ if gpus <= 1: context = context_factory() else: context = context_factory(gpus=gpus) self.config_context(context, params) return context def build_model(self, feature_ph_dict, labels_ph, params=None, context=None): """(DEPRECATED) Construct and return a Model. Args: feature_ph_dict: maps feature names to placeholders that will hold the corresponding inputs. labels_ph: a placeholder that will hold the target labels params: optional parameters to be passed to the config_* methods. context: if provided, use instead of building a fresh context Returns: a fully configured Model, where model.context is a freshly-built context produced by self.build_context(). """ model = Model() model.context = context or self.build_context(params=params) self.config_model(model, feature_ph_dict, labels_ph, params=params) self.check_model_completeness(model) return model def build_model_fn(self): """Return a function suitable for use in creating an Estimator. Will call self.build_model Returns: a Python function """ def model_fn(features, labels, mode, params): """Estimator model_fn produced by ModelBuilder. Args: features: passed to config_model_prediction labels: passed to config_model_[training|evaluation] mode: from tf.estimator.ModeKeys params: dict of options passed to config_* methods Returns: a Python function """ # initialize and partially configure the model m = Model() m.context = self.build_context(params=params) self.config_model_prediction(m, features, params=params) if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=m.predictions) self.config_model_training(m, labels, params) if mode == tf.estimator.ModeKeys.TRAIN: return tf.estimator.EstimatorSpec( mode=mode, train_op=m.train_op, loss=m.loss) self.config_model_evaluation(m, labels, params) if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec( mode=mode, loss=m.loss, eval_metric_ops=m.evaluations) raise ValueError('illegal mode %r' % mode) return model_fn def build_estimator(self, model_dir=None, params=None): """Produce an Estimator for this Model. Args: model_dir: passed in to Estimator - location of tmp files used by Estimator to checkpoint models params: passed in to estimator - dict of model_fn parameters Returns: a tf.estimator.Estimator """ return tf.estimator.Estimator( model_fn=self.build_model_fn(), model_dir=model_dir, params=params) def check_model_completeness(self, model): """Verify that the model has been fully configured. Args: model: a fully-configured Model """ for attr in ['context', 'predictions', 'train_op', 'loss', 'evaluations']: if getattr(model, attr, None) is None: raise ValueError('model has no %s set' % attr) # these are the abstract routines to specify when you subclass a model def config_model(self, model, feature_ph_dict, labels_ph, params=None): """Configure an existing Model. model.context should be already be set when this is called. Args: model: model to configure feature_ph_dict: maps feature names to placeholders that will hold the corresponding inputs. labels_ph: a placeholder that will hold the target labels params: optional parameters to be passed to the config_* methods. """ self.config_model_prediction(model, feature_ph_dict, params=params) self.config_model_training(model, labels_ph, params=params) self.config_model_evaluation(model, labels_ph, params=params) def config_context(self, context, params=None): """Configure a context object, to use to help build the model. Subclass this for a particular modeling task. Args: context: a NeuralQueryContext params: optional parameters """ raise NotImplementedError def config_model_prediction(self, model, feature_ph_dict, params=None): """Add additional attributes to model which make predictions. The model's inputs will be tf.Placeholders named in the feature_ph_dict dictionary, probably coerced into nql. It will produce some output values, which are are specified by the setting model.predictions to dictionary mapping strings to model attributes. Args: model: model to configure feature_ph_dict: maps feature names to placeholders that will hold the corresponding inputs. params: optional parameters """ raise NotImplementedError def config_model_training(self, model, labels_ph, params=None): """Add additional attributes to the model which allow training. These should include at least model.loss and model.train_op. For use with Estimators, model.train_op should include the option global_step=tf.train.get_global_step()). Args: model: model to configure labels_ph: a placeholder that will hold the target labels params: optional parameters """ raise NotImplementedError def config_model_evaluation(self, model, labels_ph, params=None): """Add additional attributes to the model which allow evaluation. This should also set model.evaluations to an appropriate dictionary. Args: model: a partly Model for which prediction has been configured. labels_ph: a placeholder that will hold the target labels params: optional parameters """ raise NotImplementedError class Trainer(object): """(DEPRECATED) Collects methods for training and testing Models.""" def __init__(self, session, model, feature_ph_dict, labels_ph, initialize=True): """Create a Trainer object for a task. Args: session: a tf.Session, used to run the dset's iterator model: a Model feature_ph_dict: maps feature names to placeholders that will hold the corresponding inputs. labels_ph: a placeholder that will hold the target labels initialize: If true, run initializers that erase current model parameters. """ self.session = session self.model = model self.feature_ph_dict = feature_ph_dict self.labels_ph = labels_ph if initialize: session.run([ tf.compat.v1.global_variables_initializer(), tf.compat.v1.local_variables_initializer(), tf.compat.v1.tables_initializer() ]) def as_read_head(self, dset): """Get the next minibatch from a dataset. Arguments: dset: a tf.data.Dataset Returns: a TF expression that evaluates to the next minibatch. """ return tf.compat.v1.data.make_one_shot_iterator(dset).get_next() def feed_dict_iterator(self, dset): """Iterator over feed_dict dictionaries. Args: dset: a tf.data.Dataset Yields: for each value produced by the datasets read's head, a dictionary mapping names of all placeholders in feature_ph_dict or labels_ph to appropriate alues. """ read_head = self.as_read_head(dset) try: while True: (feature_val_dict, labels_val) = self.session.run(read_head) feed_dict = {self.labels_ph.name: labels_val} for feature_name, feature_val in feature_val_dict.items(): feature_ph = self.feature_ph_dict[feature_name] feed_dict[feature_ph.name] = feature_val yield feed_dict except tf.errors.OutOfRangeError: pass def train(self, dset): """Train the model on this dataset over the examples in a dataset. Args: dset: a tf.data.Dataset """ start_time = time.time() for fd in self.feed_dict_iterator(dset): _, latest_loss = self.session.run([self.model.train_op, self.model.loss], feed_dict=fd) if self.model.training_callback is not None: status = self.model.training_callback(fd, latest_loss, time.time() - start_time) if status: logging.info(status) def evaluate(self, dset): """Test the model on this dataset over the examples in a dataset. Args: dset: a tf.data.Dataset Returns: a dictionary of results from model.evaluations """ named_metrics = sorted(self.model.evaluations.items()) metrics = [metric for (_, metric) in named_metrics] for fd in self.feed_dict_iterator(dset): self.session.run(metrics, feed_dict=fd) # tf metrics are pairs: current_value,update_op result = {} for (name, metric) in named_metrics: result[name] = self.session.run(metric[0]) return result def labels_of_top_ranked_predictions_in_batch(labels, predictions): """Applying tf.metrics.mean to this gives precision at 1. Args: labels: minibatch of dense 0/1 labels, shape [batch_size rows, num_classes] predictions: minibatch of predictions of the same shape Returns: one-dimension tensor top_labels, where top_labels[i]=1.0 iff the top-scoring prediction for batch element i has label 1.0 """ indices_of_top_preds = tf.cast(tf.argmax(input=predictions, axis=1), tf.int32) batch_size = tf.reduce_sum(input_tensor=tf.ones_like(indices_of_top_preds)) row_indices = tf.range(batch_size) thresholded_labels = tf.where(labels > 0.0, tf.ones_like(labels), tf.zeros_like(labels)) label_indices_to_gather = tf.transpose( a=tf.stack([row_indices, indices_of_top_preds])) return tf.gather_nd(thresholded_labels, label_indices_to_gather)
import inspect import itertools import six from . import util from . import magicnumbers def all_not_none_decider(function, incoming, accepted_keys): return all(incoming.get(key) is not None for key in accepted_keys) class Filters(object): """Registrar for functions that construct filters for submission in requests to okcupid.com """ def __init__(self, strict=True): self.builders = [] self.keys = set() self._key_to_type = {} self._key_to_values = {} self._key_to_string = {} self._strict = strict @util.cached_property def filter_meta(filters_instance): class FilterMeta(util.decorate_all(staticmethod)): acceptable_values = None keys = () types = None descriptions = None output_key = None def __init__(cls, name, bases, attributes_dict): super(FilterMeta, cls).__init__(name, bases, attributes_dict) cls._set_defaults() filters_instance.register_builder(cls) def decide(cls, kwargs): return all_not_none_decider(cls.transform, kwargs, cls.keys) def transform_from_kwargs(cls, kwargs): return cls.transform(*[kwargs.get(key) for key in cls.keys]) def _set_defaults(cls): if isinstance(cls.keys, six.string_types): cls.keys = [cls.keys] if not hasattr(cls, 'transform'): cls.transform = staticmethod(lambda x: x) function_arguments = inspect.getargspec(cls.transform).args if cls.keys: assert len(cls.keys) == len(function_arguments) else: cls.keys = function_arguments if not cls.output_key: cls.output_key = cls.keys[0] return FilterMeta @util.cached_property def filter_class(self): return six.with_metaclass(self.filter_meta) def build_documentation_lines(self): """Build a parameter documentation string that can appended to the docstring of a function that uses this :class:`~.Filters` instance to build filters. """ return [ line_string for key in sorted(self.keys) for line_string in self.build_paramter_string(key) ] def build_paramter_string(self, key): description_string = u'' if key in self._key_to_string: description_string = u' {0}'.format(self._key_to_string[key]) if key in self._key_to_values: description_string += u' expected values: {0}'.format( u', '.join([repr(value) for value in self._key_to_values[key]]) ) parameter_string_lines = [u':param {0}:{1}'.format( key, description_string )] if key in self._key_to_type: the_type = self._key_to_type[key] parameter_string_lines.append(u':type {0}: {1}'.format( key, the_type.__name__ if isinstance(the_type, type) else the_type )) return parameter_string_lines def add_to_docstring_of(self, target): target.__doc__ = '\n '.join( itertools.chain( (target.__doc__,), self.build_documentation_lines() ) ) all_not_none_decider = staticmethod(all_not_none_decider) @staticmethod def any_decider(function, incoming, accepted_keys): return bool(set(incoming).intersection(accepted_keys)) @staticmethod def all_decider(function, incoming, accepted_keys): return set(accepted_keys).issubset(set(incoming)) @staticmethod def any_not_none_decider(function, incoming, accepted_keys): return any(incoming.get(key) is not None for key in accepted_keys) def __repr__(self): return "{0}({1})".format(type(self).__name__, repr(self.builder_to_keys.keys())) def filters(self, **kwargs): builders = [ builder for builder in self.builders if self._handle_decide(builder, kwargs) ] return [ builder.transform( *[kwargs.get(key) for key in builder.keys] ) for builder in builders ] def _handle_decide(self, builder, kwargs): if len(inspect.getargspec(builder.decide).args) == 2: return builder.decide(kwargs) else: return builder.decide(builder.transform, kwargs, builder.keys) def _validate_incoming(self, kwargs): if self._strict and not self.keys.issuperset(kwargs.keys()): raise TypeError("build() got unexpected keyword arguments: " "{0}".format(', '.join( repr(k) for k in kwargs.keys() if k not in self.keys ))) def build(self, **kwargs): self._validate_incoming(kwargs) return { builder.output_key: builder.transform_from_kwargs(kwargs) for builder in self.builders if builder.decide(kwargs) } def legacy_build(self, **kwargs): self._validate_incoming(kwargs) return { u'filter{0}'.format(filter_number): filter_string for filter_number, filter_string in enumerate(self.filters(**kwargs), 1) } def register_builder(self, filter_object): self.builders.append(filter_object) self.keys.update(filter_object.keys) self._update_docs_dict( self._key_to_type, filter_object.types, filter_object.keys ) self._update_docs_dict( self._key_to_string, filter_object.descriptions, filter_object.keys ) self._update_docs_dict( self._key_to_values, filter_object.acceptable_values, filter_object.keys ) @util.curry def register_filter_builder(self, function, **kwargs): """Register a filter function with this :class:`~.Filters` instance. This function is curried with :class:`~okcupyd.util.currying.curry` -- that is, it can be invoked partially before it is fully evaluated. This allows us to pass kwargs to this function when it is used as a decorator: .. code-block:: python @register_filter_builder(keys=('real_name',), decider=Filters.any_decider) def my_filter_function(argument): return '4,{0}'.format(argument) :param function: The filter function to register. :param keys: Keys that should be used as the argument names for `function`, if none are provided, the filter functions argument names will be used instead. :param decider: a function of signature `(function, incoming_keys, accepted_keys)` that returns True if the filter function should be called and False otherwise. Defaults to :meth:`~.all_not_none_decider` :param acceptable_values: A list of acceptable values for the parameter of the filter function (or a list of lists if the filter function takes multiple parameters) :param types: The type of the parameter accepted by the incoming filter function (or a list of types if the function takes multiple parameters) :param descriptions: A description for the incoming filter function's argument (or a list of descriptions if the filter function takes multiple arguments) :param output_key: The key to use to output the provided value. Will default to the only value in keys if keys has length 1. """ kwargs['transform'] = function if kwargs.get('decider'): kwargs['decide'] = kwargs.get('decider') return type('filter', (self.filter_class,), kwargs) def _update_docs_dict(self, docs_dict, incoming, keys): if incoming: if not isinstance(incoming, dict): if len(keys) > 1: assert len(keys) == len(incoming), ( "Got {0}, for keys: {1}".format(incoming, keys) ) incoming = zip(keys, incoming) else: incoming = {key: incoming for key in keys} docs_dict.update(incoming) def gentation_filter(gentation): return u'0,{0}'.format( magicnumbers.gentation_to_number[gentation.strip().lower()] ) def age_filter(age_min=18, age_max=99): if age_min == None: age_min = 18 return u'2,{0},{1}'.format(age_min, age_max) def location_filter(radius): return u'3,{0}'.format(radius)
#!/usr/bin/env python """ Implementation of a simple indexed table type. """ import types, re, os.path, codecs, time True = 1 False = 0 class Table: def __init__(self, name, tableDef): self.__name = name self.__tableDef = tableDef self.__dict = {} self.__indexes = {} self.__regexpes = {} for index in tableDef.indexes + tableDef.unique_indexes: self.__indexes[tableDef.alias + "_" + index] = {} def getName(self): return self.__name def get(self, pk): return self.__dict[pk] def insert(self, dbRecord): pk = dbRecord.getPrimaryKey() if pk == None: try: pk = max(self.__dict.keys()) + 1 except ValueError, e: if len(self.__dict.keys()) == 0: pk = 1 else: raise e dbRecord.setPrimaryKey(pk) if self.__dict.has_key(pk): raise "Duplicate entry: " + str(dbRecord) if dbRecord.tableDef.fields.has_key("datestamp"): dbRecord.datestamp = time.time() self.__dict[pk] = dbRecord.getOwnerFields() # Add non-unique indexes for index in self.__tableDef.indexes: v = dbRecord.getFieldValue(index) #print "Adding non-unique index", index, "with value", v self.__indexes.setdefault(index, {}).setdefault(v, {})[pk] \ = self.__dict[pk] # Add unique indexes for index in self.__tableDef.unique_indexes: #print "Adding unique index", index, "with value", v v = dbRecord.getFieldValue(index) self.__indexes.setdefault(index, {}).setdefault(v, self.__dict[pk]) def update(self, dbRecord): """ Update a single record with the values in dbRecord """ pk = dbRecord.getPrimaryKey() if pk == None: raise "Empty primary key not allowed: " + str(dbRecord) self.__delete(pk) self.insert(dbRecord) def __delete(self, pk): oldRecord = self.__dict[pk] # clear old non-unique indexes for index in self.__tableDef.indexes: v = oldRecord[index] set = self.__indexes[index][v] if set != None: if pk in set.keys(): del set[pk] # clear old unique indexes for index in self.__tableDef.unique_indexes: v = oldRecord[index] del self.__indexes[index][v] # remove record del self.__dict[pk] def delete(self, dbRecord): records = self.select(dbRecord) for record in records: pk = record[self.__tableDef.primarykey] self.__delete(pk) def __regexpify(self, s): #print "regexp on %s " % s if s not in self.__regexpes.keys(): s2 = re.escape(s) s2 = "^" + s2 s2 = s2 + "$" s2 = s2.replace(r"\%", ".*") r = re.compile(s2) self.__regexpes[s] = r r = self.__regexpes[s] #print "regexp: ", r.pattern return r def __check(self, dbRecord, record): """ Check individual fields. """ #print "__check", record for k, v in record.items(): v2 = dbRecord.getFieldValue(k) #print "\tChecking k, v with target", k, v, v2 if v2 == None: continue if type(v2) in [types.StringType, types.UnicodeType]: if v2.find("%") > -1: regexp = self.__regexpify(v2) #print "\t\tMatching", regexp.pattern, v2 if regexp.match(v) == None: #print "\t\t\tMatch missed" return False else: #print "\t\t\tMatched" continue #print "\t\tFinished checking", v2, v if v2 != None and v2 != "" and v2 != v: #print "\tCheck failed" return False #print "\tCheck success" return True def __checkFullTableScan(self, dbRecord): # check whether there is any selection for value in dbRecord.getFields().values(): if value != None: #print "No full table copy" return False #print "Full table copy" return True def __selectByUniqueIndex(self, dbRecord): for unique_index in self.__tableDef.unique_indexes: #print "Checking unique index", unique_index unique_value = dbRecord.getFieldValue(unique_index) if unique_value != None: #print "Taking unique index", unique_index r = self.__indexes.get(unique_index).get(unique_value) if r == None: raise "No record where " + unique_index + " = " \ + dbRecord.getFieldValue(unique_index) else: if self.__check(dbRecord, r): return [r] return [] def __selectByIndex(self, dbRecord): resultSet = [] sets = {} # Search by index index_value = None for index in self.__tableDef.indexes: #print "Checking index", index index_value = dbRecord.getFieldValue(index) if index_value == None: #print "\tNo query on this index" continue if type(index_value) in [types.StringType, types.UnicodeType]: if index_value.find("%") != -1: #print "\tQuery on index %s contains wildcards" % index_value continue # These indexes are not unique: so more than one # record can be indexed by this value #print "\tRetrieving set for query value, ", index_value i = self.__indexes.get(index) if i == None: #print "\t\tRetrieved no index for", index return ([], True) set = i.get(index_value) if set == None: #print "\t\tRetrieved no value for query", index_value, "on index", index return ([], True) else: #print "\t\t", len(set), "candidates for query", index_value, "on index", index sets[len(set)] = set if len(sets) > 0: # Select the smallest resultset smallestSet = min(sets.keys()) #print "\t\tMinimal set has", smallestSet, "entries" for r in sets[smallestSet].values(): if self.__check(dbRecord, r): #print "\t\t\tRecord checks out ok" resultSet.append(r) return (resultSet, True) return ([], False) def __internalSelect(self, dbRecord): #print "Complex select on ", self.__name, "using", dbRecord if self.__checkFullTableScan(dbRecord): return self.__dict.values() resultSet = self.__selectByUniqueIndex(dbRecord) if resultSet != []: return resultSet (resultSet, index_used) = self.__selectByIndex(dbRecord) if index_used: # We have had a chance to find something by index, but # failed. A full table scan is useless now. return resultSet # If the resultset is still empty, we will do a full-table scan #print "Full table scan" for k, v in self.__dict.items(): #print "Checking", k, v if self.__check(dbRecord, v): resultSet.append(v) return resultSet def select(self, dbRecord): pk = dbRecord.getPrimaryKey() if pk == None: return self.__internalSelect(dbRecord) else: record = self.__dict.get(pk) if record == None: raise "No record in table %s with primary key %s " % (self.__name, str(pk)) else: return [record] def __repr__(self): return repr(self.__dict) def __len__(self): return len(self.__dict)
from getgauge.python import step import os import re import subprocess import time ASSET_ROOT = "/gevol/assets" BASE_ASSET_PATH = "gauge_tests" DATABASE_PATH = os.path.join(BASE_ASSET_PATH, "Databases") MAP_LAYER_PATH = os.path.join(BASE_ASSET_PATH, "MapLayers") IMAGERY_PROJECT_PATH = os.path.join(BASE_ASSET_PATH, "Projects", "Imagery") TERRAIN_PROJECT_PATH = os.path.join(BASE_ASSET_PATH, "Projects", "Terrain") VECTOR_PROJECT_PATH = os.path.join(BASE_ASSET_PATH, "Projects", "Vector") MAP_PROJECT_PATH = os.path.join(BASE_ASSET_PATH, "Projects", "Map") IMAGERY_RESOURCE_PATH = os.path.join(BASE_ASSET_PATH, "Resources", "Imagery") TERRAIN_RESOURCE_PATH = os.path.join(BASE_ASSET_PATH, "Resources", "Terrain") VECTOR_RESOURCE_PATH = os.path.join(BASE_ASSET_PATH, "Resources", "Vector") def get_env_value(sKey): return os.getenv(sKey, "unset") def get_asset_root(): return os.getenv('ge_asset_root') def get_src_data_path(): return os.getenv('ge_src_data_path') def call(command, errorMsg): result = subprocess.call(command) assert result == 0, errorMsg def make_list(data): if not isinstance(data, list): data = [data] return data def list_from_table(table): return [row[0] for row in table] def get_status(asset): return subprocess.check_output(["/opt/google/bin/gequery", "--status", asset]).strip() def do_create_imagery_proj(project, isMercator): commandLine = ["/opt/google/bin/genewimageryproject", "-o", os.path.join(IMAGERY_PROJECT_PATH, project)] if isMercator: commandLine.append("--mercator") call(commandLine, "Failed to create imagery project %s" % project) @step("Create imagery project <project>") def create_imagery_proj(project): do_create_imagery_proj(project, isMercator=False) @step("Create mercator imagery project <project>") def create_merc_imagery_proj(project): do_create_imagery_proj(project, isMercator=True) @step("Create terrain project <project>") def create_terrain_proj(project): call(["/opt/google/bin/genewterrainproject", "-o", os.path.join(TERRAIN_PROJECT_PATH, project)], "Failed to create terrain project %s" % project) @step("Create vector project <project>") def create_vector_proj(project): call(["/opt/google/bin/genewvectorproject", "-o", os.path.join(VECTOR_PROJECT_PATH, project)], "Failed to create vector project %s" % project) def do_create_imagery_resource(resource, srcPath, isMercator): srcPath = os.path.join(get_src_data_path(), srcPath) commandLine = ["/opt/google/bin/genewimageryresource", "-o", os.path.join(IMAGERY_RESOURCE_PATH, resource), "%s" % srcPath] if isMercator: commandLine.append("--mercator") call(commandLine, "Failed to create imagery resource %s from %s" % (resource, srcPath)) @step("Create imagery resource <resource> from <srcPath>") def create_imagery_resource(resource, srcPath): srcPath = os.path.join(get_src_data_path(), srcPath) do_create_imagery_resource(resource, srcPath, isMercator=False) @step("Create mercator imagery resource <resource> from <srcPath>") def create_merc_imagery_resource(resource, srcPath): srcPath = os.path.join(get_src_data_path(), srcPath) do_create_imagery_resource(resource, srcPath, isMercator=True) def do_add_imagery_resource_to_project(resource, project, isMercator): commandLine = ["/opt/google/bin/geaddtoimageryproject", "-o", os.path.join(IMAGERY_PROJECT_PATH, project), os.path.join(IMAGERY_RESOURCE_PATH, resource)] if isMercator: commandLine.append("--mercator") call(commandLine, "Failed to add imagery resource %s to project %s" % (resource, project)) @step("Add imagery resource <resource> to project <project>") def add_imagery_resource_to_project(resource, project): do_add_imagery_resource_to_project(resource, project, isMercator=False) @step("Drop imagery resource <resource> from project <project>") def drop_imagery_resource_to_project(resource, project): commandLine = ["/opt/google/bin/gedropfromimageryproject", "-o", os.path.join(IMAGERY_PROJECT_PATH, project), os.path.join(IMAGERY_RESOURCE_PATH, resource)] call(commandLine, "Failed to drop imagery resource %s from project %s" % (resource, project)) @step("Add mercator imagery resource <resource> to project <project>") def add_merc_imagery_resource_to_project(resource, project): do_add_imagery_resource_to_project(resource, project, isMercator=True) @step("Create imagery resource <resource> from <srcPath> and add to project <project>") def create_imagery_resource_add_to_proj(resource, srcPath, project): srcPath = os.path.join(get_src_data_path(), srcPath) create_imagery_resource(resource, srcPath) add_imagery_resource_to_project(resource, project) @step("Create terrain resource <resource> from <srcPath>") def create_terrain_resource(resource, srcPath): srcPath = os.path.join(get_src_data_path(), srcPath) call(["/opt/google/bin/genewterrainresource", "-o", os.path.join(TERRAIN_RESOURCE_PATH, resource), "%s" % srcPath], "Failed to create terrain resource %s from %s" % (resource, srcPath)) @step("Add terrain resource <resource> to project <project>") def add_terrain_resource_to_project(resource, project): call(["/opt/google/bin/geaddtoterrainproject", "-o", os.path.join(TERRAIN_PROJECT_PATH, project), os.path.join(TERRAIN_RESOURCE_PATH, resource)], "Failed to add terrain resource %s to project %s" % (resource, project)) @step("Create terrain resource <resource> from <srcPath> and add to project <project>") def create_terrain_resource_add_to_proj(resource, srcPath, project): srcPath = os.path.join(get_src_data_path(), srcPath) create_terrain_resource(resource, srcPath) add_terrain_resource_to_project(resource, project) @step("Create vector resource <resource> from <srcPath>") def create_vector_resource(resource, srcPath): srcPath = os.path.join(get_src_data_path(), srcPath) call(["/opt/google/bin/genewvectorresource", "-o", os.path.join(VECTOR_RESOURCE_PATH, resource), "%s" % srcPath], "Failed to create vector resource %s from %s" % (resource, srcPath)) @step("Add vector resource <resource> to project <project>") def add_vector_resource_to_project(resource, project): call(["/opt/google/bin/geaddtovectorproject", "-o", os.path.join(VECTOR_PROJECT_PATH, project), "--template", os.path.join(get_src_data_path(), "CA_POIs_template.khdsp"), os.path.join(VECTOR_RESOURCE_PATH, resource)], "Failed to add vector resource %s to project %s" % (resource, project)) @step("Create and build vector resource <resource> from <srcPath> and add to project <project>") def create_vector_resource_add_to_proj(resource, srcPath, project): srcPath = os.path.join(get_src_data_path(), srcPath) create_vector_resource(resource, srcPath) # Vector resources must be built before they can be added to projects build_vector_resource(resource) wait_for_vector_resource_state(resource, "Succeeded") verify_state_vector_resource(resource, "Succeeded") add_vector_resource_to_project(resource, project) @step("Verify that imagery project <project> has no versions") def verify_imagery_proj_no_versions(project): output = subprocess.check_output(["/opt/google/bin/gequery", "--versions", os.path.join(IMAGERY_PROJECT_PATH, project)]) assert output.strip() == "NO VERSIONS", "Imagery project %s has more than 0 versions. Output: %s" % (project, output) def asset_operation(operation, asset, assetType): call(["/opt/google/bin/ge%s" % operation, asset], "Failed to %s %s %s" % (operation, assetType, asset)) def imagery_project_operation(operation, project): asset_operation(operation, os.path.join(IMAGERY_PROJECT_PATH, project), "imagery project") @step("Build imagery project <project>") def build_imagery_project(project): imagery_project_operation("build", project) @step("Cancel imagery project <project>") def cancel_imagery_project(project): imagery_project_operation("cancel", project) @step("Resume imagery project <project>") def resume_imagery_project(project): imagery_project_operation("resume", project) @step("Clean imagery project <project>") def clean_imagery_project(project): imagery_project_operation("clean", project) def imagery_resource_operation(operation, resource): asset_operation(operation, os.path.join(IMAGERY_RESOURCE_PATH, resource), "imagery resource") @step("Cancel imagery resource <resource>") def cancel_imagery_resource(resource): imagery_resource_operation("cancel", resource) @step("Resume imagery resource <resource>") def resume_imagery_resource(resource): imagery_resource_operation("resume", resource) @step("Clean imagery resource <resource>") def clean_imagery_resource(resource): imagery_resource_operation("clean", resource) @step("Build imagery resource <resource>") def build_imagery_resource(resource): imagery_resource_operation("build", resource) def vector_resource_operation(operation, resource): asset_operation(operation, os.path.join(VECTOR_RESOURCE_PATH, resource), "vector resource") @step("Build vector resource <resource>") def build_vector_resource(resource): vector_resource_operation("build", resource) def database_operation(operation, database): asset_operation(operation, os.path.join(DATABASE_PATH, database), "database") @step("Build database <database>") def build_database(database): database_operation("build", database) @step("Cancel database <database>") def cancel_database(database): database_operation("cancel", database) @step("Clean database <database>") def clean_database(database): database_operation("clean", database) def map_project_operation(operation, project): asset_operation(operation, os.path.join(MAP_PROJECT_PATH, project), "map project") @step("Cancel map project <project>") def cancel_map_project(project): map_project_operation("cancel", project) def get_short_project_name(project): prefix = "StatePropagationTest_" if project.startswith(prefix): return project[len(prefix):] else: return project @step("Create and build default project <project>") def create_and_build_blue_marble_proj(project): shortName = get_short_project_name(project) create_imagery_proj(project) create_imagery_resource_add_to_proj("BlueMarble_" + shortName, os.path.join(get_src_data_path(), "Imagery/bluemarble_4km.tif"), project) create_imagery_resource_add_to_proj("i3SF15meter_" + shortName, os.path.join(get_src_data_path(), "Imagery/i3SF15-meter.tif"), project) create_imagery_resource_add_to_proj("USGSLanSat_" + shortName, os.path.join(get_src_data_path(), "Imagery/usgsLanSat.tif"), project) create_imagery_resource_add_to_proj("SFHiRes_" + shortName, os.path.join(get_src_data_path(), "Imagery/usgsSFHiRes.tif"), project) verify_imagery_proj_no_versions(project) build_imagery_project(project) def wait_until_state(asset, statuses): statuses = make_list(statuses) while True: status = get_status(asset) if status in statuses: break # Check for terminal states assert status not in ["Blocked", "Failed", "Canceled", "Offline", "Bad", "Succeeded"], \ "Asset %s entered terminal state %s while waiting for state %s" % (asset, status, " ".join(statuses)) time.sleep(1) @step("Wait for imagery project <project> to reach state <state>") def wait_for_imagery_project_state(project, state): wait_until_state(os.path.join(IMAGERY_PROJECT_PATH, project), state) verify_state_imagery_proj(project, state) @step("Wait for vector resource <resource> to reach state <state>") def wait_for_vector_resource_state(resource, state): wait_until_state(os.path.join(VECTOR_RESOURCE_PATH, resource), state) verify_state_vector_resource(resource, state) @step("Wait for database <database> to reach state <state>") def wait_for_database_state(database, state): wait_until_state(os.path.join(DATABASE_PATH, database), state) verify_state_database(database, state) @step("Wait for mercator database <database> to reach state <state>") def wait_for_mercator_database_state(database, state): wait_until_state(os.path.join(DATABASE_PATH, database), state) verify_state_mercator_database(database, state) def verify_state(path, states): states = make_list(states) status = get_status(path) assert status in states, "Asset %s in unexpected state. Expected: %s, actual: %s" % (path, " ".join(states), status) def get_one_input(path, project, extension): hasInput = re.compile(r".*/(\w*\." + extension + ").*") deps = subprocess.check_output(["/opt/google/bin/gequery", "--dependencies", os.path.join(path, project)]) depsIter = iter(deps.splitlines()) for line in depsIter: match = hasInput.match(line) if match: return match.group(1) assert False, "Could not find input for " + project def get_one_packlevel(path, resource, ext): fullPath = os.path.join(ASSET_ROOT, path, resource, "CombinedRP." + ext, "packgen." + ext) files = os.listdir(fullPath) for f in files: if f.startswith("packlevel"): return f assert False, "Could not find packlevel for " + resource def verify_state_imagery_proj_helper(project, state, projExt, resExt): verify_state(os.path.join(IMAGERY_PROJECT_PATH, project), state) if state == "Succeeded": # Check the states of the project's children verify_state(os.path.join(IMAGERY_PROJECT_PATH, project + "." + projExt, "layerjs"), state) verify_state(os.path.join(IMAGERY_PROJECT_PATH, project + "." + projExt, "dbroot"), state) verify_state(os.path.join(IMAGERY_PROJECT_PATH, project + "." + projExt, "geindex"), state) # Check the tasks that are built under the resource but only when the project is built (only check one resource) resource = get_one_input(IMAGERY_PROJECT_PATH, project, resExt) # In one test the CombinedRP ends up in a "cleaned" state even though the packgens # succeeded. I'm not sure why that happens, but if it's a bug it's been there for a while. verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource, "CombinedRP"), ["Succeeded", "Cleaned"]) verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource, "CombinedRP.kia", "packgen"), state) # Only check one pack level packlev = get_one_packlevel(IMAGERY_RESOURCE_PATH, resource, "kia") verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource, "CombinedRP.kia", "packgen.kia", packlev), state) @step("Verify that the state of imagery project <project> is <state>") def verify_state_imagery_proj(project, state): verify_state_imagery_proj_helper(project, state, "kiproject", "kiasset") @step("Verify that the state of mercator imagery project <project> is <state>") def verify_state_mercator_imagery_proj(project, state): verify_state_imagery_proj_helper(project, state, "kimproject", "kimasset") @step("Verify that the state of imagery project <project> is in <table>") def verify_state_imagery_project_table(project, table): states = list_from_table(table) verify_state(os.path.join(IMAGERY_PROJECT_PATH, project), states) def verify_state_imagery_resource_helper(resource, state, resExt): verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource), state) if state == "Succeeded": # Check the states of the resource's children verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource + "." + resExt, "maskgen"), state) verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource + "." + resExt, "maskproduct"), state) verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource + "." + resExt, "product"), state) verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource + "." + resExt, "source"), state) @step("Verify that the state of imagery resource <resource> is <state>") def verify_state_imagery_resource(resource, state): verify_state_imagery_resource_helper(resource, state, "kiasset") @step("Verify that the state of mercator imagery resource <resource> is <state>") def verify_state_mercator_imagery_resource(resource, state): verify_state_imagery_resource_helper(resource, state, "kimasset") @step("Verify that the state of imagery resource <resource> is in <table>") def verify_state_imagery_resource_table(resource, table): states = list_from_table(table) verify_state(os.path.join(IMAGERY_RESOURCE_PATH, resource), states) @step("Verify that the state of images for default project <project> is <state>") def verify_state_default_images(project, state): shortName = get_short_project_name(project) verify_state_imagery_resource("BlueMarble_" + shortName, state) verify_state_imagery_resource("i3SF15meter_" + shortName, state) verify_state_imagery_resource("USGSLanSat_" + shortName, state) verify_state_imagery_resource("SFHiRes_" + shortName, state) @step("Verify that the state of images for default project <project> is in <table>") def verify_state_default_images_table(project, table): states = list_from_table(table) verify_state_default_images(project, states) @step("Verify that the state of terrain project <project> is <state>") def verify_state_terrain_proj(project, state): verify_state(os.path.join(TERRAIN_PROJECT_PATH, project), state) if state == "Succeeded": # Check the states of the project's children verify_state(os.path.join(TERRAIN_PROJECT_PATH, project + ".ktproject", "dbroot"), state) verify_state(os.path.join(TERRAIN_PROJECT_PATH, project + ".ktproject", "geindex"), state) # Check the tasks that are built under the resource but only when the project is built (only check one resource) resource = get_one_input(TERRAIN_PROJECT_PATH, project, "ktasset") verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource, "CombinedRP"), state) verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource, "CombinedRP.kta", "packgen"), state) # Only check one pack level packlev = get_one_packlevel(TERRAIN_RESOURCE_PATH, resource, "kta") verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource, "CombinedRP.kta", "packgen.kta", packlev), state) @step("Verify that the state of terrain project <project> is in <table>") def verify_state_terrain_project_table(project, table): states = list_from_table(table) verify_state(os.path.join(TERRAIN_PROJECT_PATH, project), states) @step("Verify that the state of terrain resource <resource> is <state>") def verify_state_terrain_resource(resource, state): verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource), state) if state == "Succeeded": # Check the states of the resource's children verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource + ".ktasset", "maskgen"), state) verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource + ".ktasset", "maskproduct"), state) verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource + ".ktasset", "product"), state) verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource + ".ktasset", "source"), state) @step("Verify that the state of terrain resource <resource> is in <table>") def verify_state_terrain_resource_table(resource, table): states = list_from_table(table) verify_state(os.path.join(TERRAIN_RESOURCE_PATH, resource), states) @step("Verify that the state of vector project <project> is <state>") def verify_state_vector_proj(project, state): verify_state(os.path.join(VECTOR_PROJECT_PATH, project), state) if state == "Succeeded": # Check the states of the project's children verify_state(os.path.join(VECTOR_PROJECT_PATH, project + ".kvproject", "dbroot"), state) verify_state(os.path.join(VECTOR_PROJECT_PATH, project + ".kvproject", "geindex"), state) verify_state(os.path.join(VECTOR_PROJECT_PATH, project + ".kvproject", "layer005"), state) verify_state(os.path.join(VECTOR_PROJECT_PATH, project + ".kvproject", "layer005.kva", "layer005packet"), state) verify_state(os.path.join(VECTOR_PROJECT_PATH, project + ".kvproject", "layer005.kva", "query"), state) @step("Verify that the state of vector project <project> is in <table>") def verify_state_vector_project_table(project, table): states = list_from_table(table) verify_state(os.path.join(VECTOR_PROJECT_PATH, project), states) @step("Verify that the state of vector resource <resource> is <state>") def verify_state_vector_resource(resource, state): verify_state(os.path.join(VECTOR_RESOURCE_PATH, resource), state) if state == "Succeeded": # Check the states of the resource's children verify_state(os.path.join(VECTOR_RESOURCE_PATH, resource + ".kvasset", "source"), state) @step("Verify that the state of vector resource <resource> is in <table>") def verify_state_vector_resource_table(resource, table): states = list_from_table(table) verify_state(os.path.join(VECTOR_RESOURCE_PATH, resource), states) @step("Verify that the state of database <database> is <state>") def verify_state_database(database, state): verify_state(os.path.join(DATABASE_PATH, database), state) if state == "Succeeded": # Check the states of the database's children verify_state(os.path.join(DATABASE_PATH, database + ".kdatabase", "gedb"), state) verify_state(os.path.join(DATABASE_PATH, database + ".kdatabase", "unifiedindex"), state) verify_state(os.path.join(DATABASE_PATH, database + ".kdatabase", "qtpacket"), state) terrainPath = os.path.join(DATABASE_PATH, database + ".kdatabase", "terrain") if os.path.isdir(terrainPath + ".kta"): # Only check for the terrain task if it's there. Not all databases have terrain. verify_state(os.path.join(DATABASE_PATH, database + ".kdatabase", "terrain"), state) @step("Verify that the state of mercator database <database> is <state>") def verify_state_mercator_database(database, state): verify_state(os.path.join(DATABASE_PATH, database), state) if state == "Succeeded": # Check the states of the database's children verify_state(os.path.join(DATABASE_PATH, database + ".kmmdatabase", "mapdb"), state) verify_state(os.path.join(DATABASE_PATH, database + ".kmmdatabase", "unifiedindex"), state) @step("Verify that the state of map layer <layer> is <state>") def verify_state_map_layer(layer, state): verify_state(os.path.join(MAP_LAYER_PATH, layer), state) @step("Verify that the state of map layer <layer> is in <table>") def verify_state_map_layer(layer, table): states = list_from_table(table) verify_state(os.path.join(MAP_LAYER_PATH, layer), states) @step("Verify that the state of map project <project> is <state>") def verify_state_map_project(project, state): verify_state(os.path.join(MAP_PROJECT_PATH, project), state) @step("Create database <database> from imagery project <imagery>, terrain project <terrain>, and vector project <vector>") def create_database(database, imagery, terrain, vector): call(["/opt/google/bin/genewdatabase", "-o", os.path.join(DATABASE_PATH, database), "--imagery", os.path.join(IMAGERY_PROJECT_PATH, imagery), "--terrain", os.path.join(TERRAIN_PROJECT_PATH, terrain), "--vector", os.path.join(VECTOR_PROJECT_PATH, vector)], "Failed to create database %s" % database) @step("Create database <database> from imagery project <imagery>") def create_database_imagery(database, imagery): call(["/opt/google/bin/genewdatabase", "-o", os.path.join(DATABASE_PATH, database), "--imagery", os.path.join(IMAGERY_PROJECT_PATH, imagery)], "Failed to create database %s" % database) @step("Create map layer <layer> from resource <resource>") def create_map_layer_from_resource(layer, resource): call(["/opt/google/bin/genewmaplayer", "--legend", layer, "--output", os.path.join(MAP_LAYER_PATH, layer), "--template", os.path.join(get_src_data_path(), "CA_POIs_template.kmdsp"), os.path.join(VECTOR_RESOURCE_PATH, resource)], "Failed to create map layer %s" % layer) @step("Create map project <project> from layer <layer>") def create_map_project(project, layer): call(["/opt/google/bin/genewmapproject", "-o", os.path.join(MAP_PROJECT_PATH, project), os.path.join(MAP_LAYER_PATH, layer)], "Failed to create map project %s" % project) @step("Create map database <database> from imagery project <imagery> and map project <mapProject>") def create_map_database(database, imagery, mapProject): call(["/opt/google/bin/genewmapdatabase", "-o", os.path.join(DATABASE_PATH, database), "--imagery", os.path.join(IMAGERY_PROJECT_PATH, imagery), "--map", os.path.join(MAP_PROJECT_PATH, mapProject), "--mercator"], "Failed to create map database %s" % database) def mark_bad(asset): call(["/opt/google/bin/gesetbad", asset], "Failed to mark %s as bad" % asset) @step("Mark imagery resource <resource> bad") def mark_imagery_resource_bad(resource): mark_bad(os.path.join(IMAGERY_RESOURCE_PATH, resource)) @step("Mark imagery project <project> bad") def mark_imagery_project_bad(project): mark_bad(os.path.join(IMAGERY_PROJECT_PATH, project)) @step("Mark database <database> bad") def mark_database_bad(database): mark_bad(os.path.join(DATABASE_PATH, database)) def mark_good(asset): call(["/opt/google/bin/geclearbad", asset], "Failed to mark %s as good" % asset) @step("Mark imagery resource <resource> good") def mark_imagery_resource_good(resource): mark_good(os.path.join(IMAGERY_RESOURCE_PATH, resource)) @step("Mark imagery project <project> good") def mark_imagery_project_good(project): mark_good(os.path.join(IMAGERY_PROJECT_PATH, project)) @step("Mark database <database> good") def mark_database_good(database): mark_good(os.path.join(DATABASE_PATH, database))
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import logging import os import subprocess import time import common import remote_cmd from log_manager import LogManager from symbolizer import BuildIdsPaths, RunSymbolizer _SHUTDOWN_CMD = ['dm', 'poweroff'] _ATTACH_RETRY_INTERVAL = 1 _ATTACH_RETRY_SECONDS = 120 # Amount of time to wait for a complete package installation, as a # mitigation against hangs due to pkg/network-related failures. _INSTALL_TIMEOUT_SECS = 10 * 60 def _GetPackageUri(package_name): """Returns the URI for the specified package name.""" return 'fuchsia-pkg://fuchsia.com/%s' % (package_name) def _GetPackageInfo(package_path): """Returns a tuple with the name and version of a package.""" # Query the metadata file which resides next to the package file. package_info = json.load( open(os.path.join(os.path.dirname(package_path), 'package'))) return package_info['name'], package_info['version'], class _MapIsolatedPathsForPackage: """Callable object which remaps /data and /tmp paths to their component- specific locations, based on the package name and test realm path.""" def __init__(self, package_name, package_version, realms): realms_path_fragment = '/r/'.join(['r/sys'] + realms) package_sub_path = '{2}/fuchsia.com:{0}:{1}#meta:{0}.cmx/'.format( package_name, package_version, realms_path_fragment) self.isolated_format = '{0}' + package_sub_path + '{1}' def __call__(self, path): for isolated_directory in ['/data/' , '/tmp/']: if (path+'/').startswith(isolated_directory): return self.isolated_format.format(isolated_directory, path[len(isolated_directory):]) return path class FuchsiaTargetException(Exception): def __init__(self, message): super(FuchsiaTargetException, self).__init__(message) # TODO(crbug.com/1250803): Factor high level commands out of target. class Target(object): """Base class representing a Fuchsia deployment target.""" def __init__(self, out_dir, target_cpu, logs_dir): self._out_dir = out_dir self._target_cpu = target_cpu self._command_runner = None self._symbolizer_proc = None self._log_listener_proc = None self._dry_run = False self._started = False self._ffx_path = os.path.join(common.SDK_ROOT, 'tools', common.GetHostArchFromPlatform(), 'ffx') self._log_manager = LogManager(logs_dir) @staticmethod def CreateFromArgs(args): raise NotImplementedError() @staticmethod def RegisterArgs(arg_parser): pass # Functions used by the Python context manager for teardown. def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.Stop() def Start(self): """Handles the instantiation and connection process for the Fuchsia target instance.""" def IsStarted(self): """Returns True if the Fuchsia target instance is ready to accept commands.""" return self._started def Stop(self): """Stop all subprocesses and close log streams.""" if self._symbolizer_proc: self._symbolizer_proc.kill() if self._log_listener_proc: self._log_listener_proc.kill() self._log_manager.Stop() def IsNewInstance(self): """Returns True if the connected target instance is newly provisioned.""" return True def GetCommandRunner(self): """Returns CommandRunner that can be used to execute commands on the target. Most clients should prefer RunCommandPiped() and RunCommand().""" self._AssertIsStarted() if self._command_runner is None: host, port = self._GetEndpoint() self._command_runner = \ remote_cmd.CommandRunner(self._GetSshConfigPath(), host, port) return self._command_runner def StartSystemLog(self, package_paths): """Start a system log reader as a long-running SSH task.""" system_log = self._log_manager.Open('system_log') if package_paths: self._log_listener_proc = self.RunCommandPiped(['log_listener'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self._symbolizer_proc = RunSymbolizer(self._log_listener_proc.stdout, system_log, BuildIdsPaths(package_paths)) else: self._log_listener_proc = self.RunCommandPiped(['log_listener'], stdout=system_log, stderr=subprocess.STDOUT) def RunCommandPiped(self, command, **kwargs): """Starts a remote command and immediately returns a Popen object for the command. The caller may interact with the streams, inspect the status code, wait on command termination, etc. command: A list of strings representing the command and arguments. kwargs: A dictionary of parameters to be passed to subprocess.Popen(). The parameters can be used to override stdin and stdout, for example. Returns: a Popen object. Note: method does not block. """ logging.debug('running (non-blocking) \'%s\'.', ' '.join(command)) return self.GetCommandRunner().RunCommandPiped(command, **kwargs) def RunCommand(self, command, silent=False, timeout_secs=None): """Executes a remote command and waits for it to finish executing. Returns the exit code of the command. """ logging.debug('running \'%s\'.', ' '.join(command)) return self.GetCommandRunner().RunCommand(command, silent, timeout_secs=timeout_secs) def EnsureIsolatedPathsExist(self, for_package, for_realms): """Ensures that the package's isolated /data and /tmp exist.""" for isolated_directory in ['/data', '/tmp']: self.RunCommand([ 'mkdir', '-p', _MapIsolatedPathsForPackage(for_package, 0, for_realms)(isolated_directory) ]) def PutFile(self, source, dest, recursive=False, for_package=None, for_realms=()): """Copies a file from the local filesystem to the target filesystem. source: The path of the file being copied. dest: The path on the remote filesystem which will be copied to. recursive: If true, performs a recursive copy. for_package: If specified, isolated paths in the |dest| are mapped to their obsolute paths for the package, on the target. This currently affects the /data and /tmp directories. for_realms: If specified, identifies the sub-realm of 'sys' under which isolated paths (see |for_package|) are stored. """ assert type(source) is str self.PutFiles([source], dest, recursive, for_package, for_realms) def PutFiles(self, sources, dest, recursive=False, for_package=None, for_realms=()): """Copies files from the local filesystem to the target filesystem. sources: List of local file paths to copy from, or a single path. dest: The path on the remote filesystem which will be copied to. recursive: If true, performs a recursive copy. for_package: If specified, /data in the |dest| is mapped to the package's isolated /data location. for_realms: If specified, identifies the sub-realm of 'sys' under which isolated paths (see |for_package|) are stored. """ assert type(sources) is tuple or type(sources) is list if for_package: self.EnsureIsolatedPathsExist(for_package, for_realms) dest = _MapIsolatedPathsForPackage(for_package, 0, for_realms)(dest) logging.debug('copy local:%s => remote:%s', sources, dest) self.GetCommandRunner().RunScp(sources, dest, remote_cmd.COPY_TO_TARGET, recursive) def GetFile(self, source, dest, for_package=None, for_realms=(), recursive=False): """Copies a file from the target filesystem to the local filesystem. source: The path of the file being copied. dest: The path on the local filesystem which will be copied to. for_package: If specified, /data in paths in |sources| is mapped to the package's isolated /data location. for_realms: If specified, identifies the sub-realm of 'sys' under which isolated paths (see |for_package|) are stored. recursive: If true, performs a recursive copy. """ assert type(source) is str self.GetFiles([source], dest, for_package, for_realms, recursive) def GetFiles(self, sources, dest, for_package=None, for_realms=(), recursive=False): """Copies files from the target filesystem to the local filesystem. sources: List of remote file paths to copy. dest: The path on the local filesystem which will be copied to. for_package: If specified, /data in paths in |sources| is mapped to the package's isolated /data location. for_realms: If specified, identifies the sub-realm of 'sys' under which isolated paths (see |for_package|) are stored. recursive: If true, performs a recursive copy. """ assert type(sources) is tuple or type(sources) is list self._AssertIsStarted() if for_package: sources = map(_MapIsolatedPathsForPackage(for_package, 0, for_realms), sources) logging.debug('copy remote:%s => local:%s', sources, dest) return self.GetCommandRunner().RunScp(sources, dest, remote_cmd.COPY_FROM_TARGET, recursive) def GetFileAsString(self, source): """Reads a file on the device and returns it as a string. source: The remote file path to read. """ cat_proc = self.RunCommandPiped(['cat', source], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, _ = cat_proc.communicate() if cat_proc.returncode != 0: raise Exception('Could not read file %s on device.', source) return stdout def _GetEndpoint(self): """Returns a (host, port) tuple for the SSH connection to the target.""" raise NotImplementedError() def _GetTargetSdkArch(self): """Returns the Fuchsia SDK architecture name for the target CPU.""" if self._target_cpu == 'arm64' or self._target_cpu == 'x64': return self._target_cpu raise FuchsiaTargetException('Unknown target_cpu:' + self._target_cpu) def _AssertIsStarted(self): assert self.IsStarted() def _WaitUntilReady(self): logging.info('Connecting to Fuchsia using SSH.') host, port = self._GetEndpoint() end_time = time.time() + _ATTACH_RETRY_SECONDS ssh_diagnostic_log = self._log_manager.Open('ssh_diagnostic_log') while time.time() < end_time: runner = remote_cmd.CommandRunner(self._GetSshConfigPath(), host, port) ssh_proc = runner.RunCommandPiped(['true'], ssh_args=['-v'], stdout=ssh_diagnostic_log, stderr=subprocess.STDOUT) if ssh_proc.wait() == 0: logging.info('Connected!') self._started = True self._command_runner = runner return True time.sleep(_ATTACH_RETRY_INTERVAL) logging.error('Timeout limit reached.') raise FuchsiaTargetException('Couldn\'t connect using SSH.') def _GetSshConfigPath(self, path): raise NotImplementedError() def GetPkgRepo(self): """Returns an PkgRepo instance which serves packages for this Target. Callers should typically call GetPkgRepo() in a |with| statement, and install and execute commands inside the |with| block, so that the returned PkgRepo can teardown correctly, if necessary. """ raise NotImplementedError() def InstallPackage(self, package_paths): """Installs a package and it's dependencies on the device. If the package is already installed then it will be updated to the new version. package_paths: Paths to the .far files to install. """ with self.GetPkgRepo() as pkg_repo: # Publish all packages to the serving TUF repository under |tuf_root|. for package_path in package_paths: pkg_repo.PublishPackage(package_path) # Resolve all packages, to have them pulled into the device/VM cache. for package_path in package_paths: package_name, package_version = _GetPackageInfo(package_path) logging.info('Installing %s...', package_name) return_code = self.RunCommand( ['pkgctl', 'resolve', _GetPackageUri(package_name), '>/dev/null'], timeout_secs=_INSTALL_TIMEOUT_SECS) if return_code != 0: raise Exception( 'Error {} while resolving {}.'.format(return_code, package_name)) # Verify that the newly resolved versions of packages are reported. for package_path in package_paths: # Use pkgctl get-hash to determine which version will be resolved. package_name, package_version = _GetPackageInfo(package_path) pkgctl = self.RunCommandPiped( ['pkgctl', 'get-hash', _GetPackageUri(package_name)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pkgctl_out, pkgctl_err = pkgctl.communicate() # Read the expected version from the meta.far Merkel hash file alongside # the package's FAR. meta_far_path = os.path.join(os.path.dirname(package_path), 'meta.far') meta_far_merkel = subprocess.check_output( [common.GetHostToolPathFromPlatform('merkleroot'), meta_far_path]).split()[0] if pkgctl_out != meta_far_merkel: raise Exception('Hash mismatch for %s after resolve (%s vs %s).' % (package_name, pkgctl_out, meta_far_merkel)) def RunFFXCommand(self, ffx_args, **kwargs): """Automatically gets the FFX path and runs FFX based on the arguments provided. Extra args can be added to be used with Popen. ffx_args: The arguments for a ffx command. kwargs: A dictionary of parameters to be passed to subprocess.Popen(). Returns a Popen object for the command.""" command = [self._ffx_path] + ffx_args return subprocess.Popen(command, **kwargs)
"""Conversion tool from Neuroscan CNT to FIF.""" # Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi> # Joan Massich <mailsik@gmail.com> # # License: BSD-3-Clause from os import path import numpy as np from ...utils import warn, fill_doc, _check_option from ...channels.layout import _topo_to_sphere from ..constants import FIFF from ..utils import (_mult_cal_one, _find_channels, _create_chs, read_str) from ..meas_info import _empty_info from ..base import BaseRaw from ...annotations import Annotations from ._utils import (_read_teeg, _get_event_parser, _session_date_2_meas_date, _compute_robust_event_table_position, CNTEventType3) def _read_annotations_cnt(fname, data_format='int16'): """CNT Annotation File Reader. This method opens the .cnt files, searches all the metadata to construct the annotations and parses the event table. Notice that CNT files, can point to a different file containing the events. This case when the event table is separated from the main .cnt is not supported. Parameters ---------- fname: str path to cnt file containing the annotations. data_format : 'int16' | 'int32' Defines the data format the data is read in. Returns ------- annot : instance of Annotations The annotations. """ # Offsets from SETUP structure in http://paulbourke.net/dataformats/eeg/ SETUP_NCHANNELS_OFFSET = 370 SETUP_RATE_OFFSET = 376 def _translating_function(offset, n_channels, event_type, data_format=data_format): n_bytes = 2 if data_format == 'int16' else 4 if event_type == CNTEventType3: offset *= n_bytes * n_channels event_time = offset - 900 - (75 * n_channels) event_time //= n_channels * n_bytes return event_time - 1 with open(fname, 'rb') as fid: fid.seek(SETUP_NCHANNELS_OFFSET) (n_channels,) = np.frombuffer(fid.read(2), dtype='<u2') fid.seek(SETUP_RATE_OFFSET) (sfreq,) = np.frombuffer(fid.read(2), dtype='<u2') event_table_pos = _compute_robust_event_table_position( fid=fid, data_format=data_format) with open(fname, 'rb') as fid: teeg = _read_teeg(fid, teeg_offset=event_table_pos) event_parser = _get_event_parser(event_type=teeg.event_type) with open(fname, 'rb') as fid: fid.seek(event_table_pos + 9) # the real table stats at +9 buffer = fid.read(teeg.total_length) my_events = list(event_parser(buffer)) if not my_events: return Annotations(list(), list(), list(), None) else: onset = _translating_function(np.array([e.Offset for e in my_events], dtype=float), n_channels=n_channels, event_type=type(my_events[0]), data_format=data_format) duration = np.array([getattr(e, 'Latency', 0.) for e in my_events], dtype=float) description = np.array([str(e.StimType) for e in my_events]) return Annotations(onset=onset / sfreq, duration=duration, description=description, orig_time=None) @fill_doc def read_raw_cnt(input_fname, eog=(), misc=(), ecg=(), emg=(), data_format='auto', date_format='mm/dd/yy', preload=False, verbose=None): """Read CNT data as raw object. .. Note:: 2d spatial coordinates (x, y) for EEG channels are read from the file header and fit to a sphere to compute corresponding z-coordinates. If channels assigned as EEG channels have locations far away from the head (i.e. x and y coordinates don't fit to a sphere), all the channel locations will be distorted (all channels that are not assigned with keywords ``eog``, ``ecg``, ``emg`` and ``misc`` are assigned as EEG channels). If you are not sure that the channel locations in the header are correct, it is probably safer to replace them with :meth:`mne.io.Raw.set_montage`. Montages can be created/imported with: - Standard montages with :func:`mne.channels.make_standard_montage` - Montages for `Compumedics systems <https://compumedicsneuroscan.com/ scan-acquire-configuration-files/>`_ with :func:`mne.channels.read_dig_dat` - Other reader functions are listed under *See Also* at :class:`mne.channels.DigMontage` Parameters ---------- input_fname : str Path to the data file. eog : list | tuple | 'auto' | 'header' Names of channels or list of indices that should be designated EOG channels. If 'header', VEOG and HEOG channels assigned in the file header are used. If 'auto', channel names containing 'EOG' are used. Defaults to empty tuple. misc : list | tuple Names of channels or list of indices that should be designated MISC channels. Defaults to empty tuple. ecg : list | tuple | 'auto' Names of channels or list of indices that should be designated ECG channels. If 'auto', the channel names containing 'ECG' are used. Defaults to empty tuple. emg : list | tuple Names of channels or list of indices that should be designated EMG channels. If 'auto', the channel names containing 'EMG' are used. Defaults to empty tuple. data_format : 'auto' | 'int16' | 'int32' Defines the data format the data is read in. If 'auto', it is determined from the file header using ``numsamples`` field. Defaults to 'auto'. date_format : 'mm/dd/yy' | 'dd/mm/yy' Format of date in the header. Defaults to 'mm/dd/yy'. %(preload)s %(verbose)s Returns ------- raw : instance of RawCNT. The raw data. See Also -------- mne.io.Raw : Documentation of attribute and methods. Notes ----- .. versionadded:: 0.12 """ return RawCNT(input_fname, eog=eog, misc=misc, ecg=ecg, emg=emg, data_format=data_format, date_format=date_format, preload=preload, verbose=verbose) def _get_cnt_info(input_fname, eog, ecg, emg, misc, data_format, date_format): """Read the cnt header.""" data_offset = 900 # Size of the 'SETUP' header. cnt_info = dict() # Reading only the fields of interest. Structure of the whole header at # http://paulbourke.net/dataformats/eeg/ with open(input_fname, 'rb', buffering=0) as fid: fid.seek(21) patient_id = read_str(fid, 20) patient_id = int(patient_id) if patient_id.isdigit() else 0 fid.seek(121) patient_name = read_str(fid, 20).split() last_name = patient_name[0] if len(patient_name) > 0 else '' first_name = patient_name[-1] if len(patient_name) > 0 else '' fid.seek(2, 1) sex = read_str(fid, 1) if sex == 'M': sex = FIFF.FIFFV_SUBJ_SEX_MALE elif sex == 'F': sex = FIFF.FIFFV_SUBJ_SEX_FEMALE else: # can be 'U' sex = FIFF.FIFFV_SUBJ_SEX_UNKNOWN hand = read_str(fid, 1) if hand == 'R': hand = FIFF.FIFFV_SUBJ_HAND_RIGHT elif hand == 'L': hand = FIFF.FIFFV_SUBJ_HAND_LEFT else: # can be 'M' for mixed or 'U' hand = None fid.seek(205) session_label = read_str(fid, 20) session_date = ('%s %s' % (read_str(fid, 10), read_str(fid, 12))) meas_date = _session_date_2_meas_date(session_date, date_format) fid.seek(370) n_channels = np.fromfile(fid, dtype='<u2', count=1)[0] fid.seek(376) sfreq = np.fromfile(fid, dtype='<u2', count=1)[0] if eog == 'header': fid.seek(402) eog = [idx for idx in np.fromfile(fid, dtype='i2', count=2) if idx >= 0] fid.seek(438) lowpass_toggle = np.fromfile(fid, 'i1', count=1)[0] highpass_toggle = np.fromfile(fid, 'i1', count=1)[0] # Header has a field for number of samples, but it does not seem to be # too reliable. That's why we have option for setting n_bytes manually. fid.seek(864) n_samples = np.fromfile(fid, dtype='<i4', count=1)[0] fid.seek(869) lowcutoff = np.fromfile(fid, dtype='f4', count=1)[0] fid.seek(2, 1) highcutoff = np.fromfile(fid, dtype='f4', count=1)[0] event_offset = _compute_robust_event_table_position( fid=fid, data_format=data_format ) fid.seek(890) cnt_info['continuous_seconds'] = np.fromfile(fid, dtype='<f4', count=1)[0] if event_offset < data_offset: # no events data_size = n_samples * n_channels else: data_size = event_offset - (data_offset + 75 * n_channels) _check_option('data_format', data_format, ['auto', 'int16', 'int32']) if data_format == 'auto': if (n_samples == 0 or data_size // (n_samples * n_channels) not in [2, 4]): warn('Could not define the number of bytes automatically. ' 'Defaulting to 2.') n_bytes = 2 n_samples = data_size // (n_bytes * n_channels) else: n_bytes = data_size // (n_samples * n_channels) else: n_bytes = 2 if data_format == 'int16' else 4 n_samples = data_size // (n_bytes * n_channels) # Channel offset refers to the size of blocks per channel in the file. cnt_info['channel_offset'] = np.fromfile(fid, dtype='<i4', count=1)[0] if cnt_info['channel_offset'] > 1: cnt_info['channel_offset'] //= n_bytes else: cnt_info['channel_offset'] = 1 ch_names, cals, baselines, chs, pos = ( list(), list(), list(), list(), list() ) bads = list() for ch_idx in range(n_channels): # ELECTLOC fields fid.seek(data_offset + 75 * ch_idx) ch_name = read_str(fid, 10) ch_names.append(ch_name) fid.seek(data_offset + 75 * ch_idx + 4) if np.fromfile(fid, dtype='u1', count=1)[0]: bads.append(ch_name) fid.seek(data_offset + 75 * ch_idx + 19) xy = np.fromfile(fid, dtype='f4', count=2) xy[1] *= -1 # invert y-axis pos.append(xy) fid.seek(data_offset + 75 * ch_idx + 47) # Baselines are subtracted before scaling the data. baselines.append(np.fromfile(fid, dtype='i2', count=1)[0]) fid.seek(data_offset + 75 * ch_idx + 59) sensitivity = np.fromfile(fid, dtype='f4', count=1)[0] fid.seek(data_offset + 75 * ch_idx + 71) cal = np.fromfile(fid, dtype='f4', count=1)[0] cals.append(cal * sensitivity * 1e-6 / 204.8) info = _empty_info(sfreq) if lowpass_toggle == 1: info['lowpass'] = highcutoff if highpass_toggle == 1: info['highpass'] = lowcutoff subject_info = {'hand': hand, 'id': patient_id, 'sex': sex, 'first_name': first_name, 'last_name': last_name} if eog == 'auto': eog = _find_channels(ch_names, 'EOG') if ecg == 'auto': ecg = _find_channels(ch_names, 'ECG') if emg == 'auto': emg = _find_channels(ch_names, 'EMG') chs = _create_chs(ch_names, cals, FIFF.FIFFV_COIL_EEG, FIFF.FIFFV_EEG_CH, eog, ecg, emg, misc) eegs = [idx for idx, ch in enumerate(chs) if ch['coil_type'] == FIFF.FIFFV_COIL_EEG] coords = _topo_to_sphere(pos, eegs) locs = np.full((len(chs), 12), np.nan) locs[:, :3] = coords for ch, loc in zip(chs, locs): ch.update(loc=loc) cnt_info.update(baselines=np.array(baselines), n_samples=n_samples, n_bytes=n_bytes) session_label = None if str(session_label) == '' else str(session_label) info.update(meas_date=meas_date, description=session_label, bads=bads, subject_info=subject_info, chs=chs) info._update_redundant() return info, cnt_info @fill_doc class RawCNT(BaseRaw): """Raw object from Neuroscan CNT file. .. Note:: The channel positions are read from the file header. Channels that are not assigned with keywords ``eog``, ``ecg``, ``emg`` and ``misc`` are assigned as eeg channels. All the eeg channel locations are fit to a sphere when computing the z-coordinates for the channels. If channels assigned as eeg channels have locations far away from the head (i.e. x and y coordinates don't fit to a sphere), all the channel locations will be distorted. If you are not sure that the channel locations in the header are correct, it is probably safer to use a (standard) montage. See :func:`mne.channels.make_standard_montage` Parameters ---------- input_fname : str Path to the CNT file. eog : list | tuple Names of channels or list of indices that should be designated EOG channels. If 'auto', the channel names beginning with ``EOG`` are used. Defaults to empty tuple. misc : list | tuple Names of channels or list of indices that should be designated MISC channels. Defaults to empty tuple. ecg : list | tuple Names of channels or list of indices that should be designated ECG channels. If 'auto', the channel names beginning with ``ECG`` are used. Defaults to empty tuple. emg : list | tuple Names of channels or list of indices that should be designated EMG channels. If 'auto', the channel names beginning with ``EMG`` are used. Defaults to empty tuple. data_format : 'auto' | 'int16' | 'int32' Defines the data format the data is read in. If 'auto', it is determined from the file header using ``numsamples`` field. Defaults to 'auto'. date_format : 'mm/dd/yy' | 'dd/mm/yy' Format of date in the header. Defaults to 'mm/dd/yy'. %(preload)s stim_channel : bool | None Add a stim channel from the events. Defaults to None to trigger a future warning. .. warning:: This defaults to True in 0.18 but will change to False in 0.19 (when no stim channel synthesis will be allowed) and be removed in 0.20; migrate code to use :func:`mne.events_from_annotations` instead. .. versionadded:: 0.18 %(verbose)s See Also -------- mne.io.Raw : Documentation of attribute and methods. """ def __init__(self, input_fname, eog=(), misc=(), ecg=(), emg=(), data_format='auto', date_format='mm/dd/yy', preload=False, verbose=None): # noqa: D102 _check_option('date_format', date_format, ['mm/dd/yy', 'dd/mm/yy']) if date_format == 'dd/mm/yy': _date_format = '%d/%m/%y %H:%M:%S' else: _date_format = '%m/%d/%y %H:%M:%S' input_fname = path.abspath(input_fname) info, cnt_info = _get_cnt_info(input_fname, eog, ecg, emg, misc, data_format, _date_format) last_samps = [cnt_info['n_samples'] - 1] super(RawCNT, self).__init__( info, preload, filenames=[input_fname], raw_extras=[cnt_info], last_samps=last_samps, orig_format='int', verbose=verbose) data_format = 'int32' if cnt_info['n_bytes'] == 4 else 'int16' self.set_annotations( _read_annotations_cnt(input_fname, data_format=data_format)) def _read_segment_file(self, data, idx, fi, start, stop, cals, mult): """Take a chunk of raw data, multiply by mult or cals, and store.""" n_channels = self._raw_extras[fi]['orig_nchan'] if 'stim_channel' in self._raw_extras[fi]: f_channels = n_channels - 1 # Stim channel already read. stim_ch = self._raw_extras[fi]['stim_channel'] else: f_channels = n_channels stim_ch = None channel_offset = self._raw_extras[fi]['channel_offset'] baselines = self._raw_extras[fi]['baselines'] n_bytes = self._raw_extras[fi]['n_bytes'] dtype = '<i4' if n_bytes == 4 else '<i2' chunk_size = channel_offset * f_channels # Size of chunks in file. # The data is divided into blocks of samples / channel. # channel_offset determines the amount of successive samples. # Here we use sample offset to align the data because start can be in # the middle of these blocks. data_left = (stop - start) * f_channels # Read up to 100 MB of data at a time, block_size is in data samples block_size = ((int(100e6) // n_bytes) // chunk_size) * chunk_size block_size = min(data_left, block_size) s_offset = start % channel_offset with open(self._filenames[fi], 'rb', buffering=0) as fid: fid.seek(900 + f_channels * (75 + (start - s_offset) * n_bytes)) for sample_start in np.arange(0, data_left, block_size) // f_channels: sample_stop = sample_start + min((block_size // f_channels, data_left // f_channels - sample_start)) n_samps = sample_stop - sample_start one = np.zeros((n_channels, n_samps)) # In case channel offset and start time do not align perfectly, # extra sample sets are read here to cover the desired time # window. The whole (up to 100 MB) block is read at once and # then reshaped to (n_channels, n_samples). extra_samps = chunk_size if (s_offset != 0 or n_samps % channel_offset != 0) else 0 if s_offset >= (channel_offset / 2): # Extend at the end. extra_samps += chunk_size count = n_samps // channel_offset * chunk_size + extra_samps n_chunks = count // chunk_size samps = np.fromfile(fid, dtype=dtype, count=count) samps = samps.reshape((n_chunks, f_channels, channel_offset), order='C') # Intermediate shaping to chunk sizes. block = np.zeros((n_channels, channel_offset * n_chunks)) for set_idx, row in enumerate(samps): # Final shape. block_slice = slice(set_idx * channel_offset, (set_idx + 1) * channel_offset) block[:f_channels, block_slice] = row if 'stim_channel' in self._raw_extras[fi]: _data_start = start + sample_start _data_stop = start + sample_stop block[-1] = stim_ch[_data_start:_data_stop] one[idx] = block[idx, s_offset:n_samps + s_offset] one[idx] -= baselines[idx][:, None] _mult_cal_one(data[:, sample_start:sample_stop], one, idx, cals, mult)
# Copyright 2018 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. # ============================================================================== """Stateless random ops which take seed as a tensor input.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import gen_stateless_random_ops from tensorflow.python.ops import math_ops from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export ops.NotDifferentiable("StatelessMultinomial") ops.NotDifferentiable("StatelessRandomNormal") ops.NotDifferentiable("StatelessRandomUniform") ops.NotDifferentiable("StatelessRandomUniformInt") ops.NotDifferentiable("StatelessTruncatedNormal") @tf_export("random.stateless_uniform") def stateless_random_uniform(shape, seed, minval=0, maxval=None, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values from a uniform distribution. This is a stateless version of `tf.random.uniform`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] integer Tensor of seeds to the random number generator. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float16`, `float32`, `float64`, `int32`, or `int64`. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified. """ dtype = dtypes.as_dtype(dtype) if dtype not in (dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64): raise ValueError("Invalid dtype %r" % dtype) if maxval is None: if dtype.is_integer: raise ValueError("Must specify maxval for integer dtype %r" % dtype) maxval = 1 with ops.name_scope(name, "stateless_random_uniform", [shape, seed, minval, maxval]) as name: shape = tensor_util.shape_tensor(shape) minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") if dtype.is_integer: result = gen_stateless_random_ops.stateless_random_uniform_int( shape, seed=seed, minval=minval, maxval=maxval, name=name) else: rnd = gen_stateless_random_ops.stateless_random_uniform( shape, seed=seed, dtype=dtype) result = math_ops.add(rnd * (maxval - minval), minval, name=name) tensor_util.maybe_set_static_shape(result, shape) return result @tf_export("random.stateless_normal") def stateless_random_normal(shape, seed, mean=0.0, stddev=1.0, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values from a normal distribution. This is a stateless version of `tf.random.normal`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] integer Tensor of seeds to the random number generator. mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal distribution. stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation of the normal distribution. dtype: The type of the output. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random normal values. """ with ops.name_scope(name, "stateless_random_normal", [shape, seed, mean, stddev]) as name: shape = tensor_util.shape_tensor(shape) mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean") stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") rnd = gen_stateless_random_ops.stateless_random_normal(shape, seed, dtype) result = math_ops.add(rnd * stddev, mean, name=name) tensor_util.maybe_set_static_shape(result, shape) return result @tf_export("random.stateless_truncated_normal") def stateless_truncated_normal(shape, seed, mean=0.0, stddev=1.0, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values, truncated normally distributed. This is a stateless version of `tf.random.truncated_normal`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked. Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] integer Tensor of seeds to the random number generator. mean: A 0-D Tensor or Python value of type `dtype`. The mean of the truncated normal distribution. stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation of the normal distribution, before truncation. dtype: The type of the output. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random truncated normal values. """ with ops.name_scope(name, "stateless_truncated_normal", [shape, seed, mean, stddev]) as name: shape = tensor_util.shape_tensor(shape) mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean") stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") rnd = gen_stateless_random_ops.stateless_truncated_normal( shape, seed, dtype) result = math_ops.add(rnd * stddev, mean, name=name) tensor_util.maybe_set_static_shape(result, shape) return result @tf_export(v1=["random.stateless_multinomial"]) @deprecation.deprecated( date=None, instructions="Use `tf.random.stateless_categorical` instead.") def stateless_multinomial(logits, num_samples, seed, output_dtype=dtypes.int64, name=None): """Draws deterministic pseudorandom samples from a multinomial distribution. This is a stateless version of `tf.random.categorical`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. Example: ```python # samples has shape [1, 5], where each value is either 0 or 1 with equal # probability. samples = tf.random.stateless_categorical( tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17]) ``` Args: logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` represents the unnormalized log-probabilities for all classes. num_samples: 0-D. Number of independent samples to draw for each row slice. seed: A shape [2] integer Tensor of seeds to the random number generator. output_dtype: integer type to use for the output. Defaults to int64. name: Optional name for the operation. Returns: The drawn samples of shape `[batch_size, num_samples]`. """ with ops.name_scope(name, "stateless_multinomial", [logits, seed]): return stateless_multinomial_categorical_impl(logits, num_samples, output_dtype, seed) @tf_export("random.stateless_categorical") def stateless_categorical(logits, num_samples, seed, dtype=dtypes.int64, name=None): """Draws deterministic pseudorandom samples from a categorical distribution. This is a stateless version of `tf.categorical`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. Example: ```python # samples has shape [1, 5], where each value is either 0 or 1 with equal # probability. samples = tf.random.stateless_categorical( tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17]) ``` Args: logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` represents the unnormalized log-probabilities for all classes. num_samples: 0-D. Number of independent samples to draw for each row slice. seed: A shape [2] integer Tensor of seeds to the random number generator. dtype: integer type to use for the output. Defaults to int64. name: Optional name for the operation. Returns: The drawn samples of shape `[batch_size, num_samples]`. """ with ops.name_scope(name, "stateless_categorical", [logits, seed]): return stateless_multinomial_categorical_impl(logits, num_samples, dtype, seed) def stateless_multinomial_categorical_impl(logits, num_samples, dtype, seed): """Implementation for stateless multinomial/categorical ops (v1/v2).""" logits = ops.convert_to_tensor(logits, name="logits") return gen_stateless_random_ops.stateless_multinomial( logits, num_samples, seed, output_dtype=dtype)
import os class TicTacToeBoard: """ Since the value for X and O is arbitrary. It behooves us to make an effort to never hardcode these values. """ X = True O = False _ = None _d8 = [ lambda x: TicTacToeBoard._rotation(x, 0), lambda x: TicTacToeBoard._rotation(x, 1), lambda x: TicTacToeBoard._rotation(x, 2), lambda x: TicTacToeBoard._rotation(x, 3), lambda x: TicTacToeBoard._reflection(TicTacToeBoard._rotation(x, 0)), lambda x: TicTacToeBoard._reflection(TicTacToeBoard._rotation(x, 1)), lambda x: TicTacToeBoard._reflection(TicTacToeBoard._rotation(x, 2)), lambda x: TicTacToeBoard._reflection(TicTacToeBoard._rotation(x, 3)), ] def __init__(self, board): # Dihedral group on 8 objects. Used for symmetries between boards. if type(board) == int: self._boardAsNumber = board self._boardAsArray = self._numberToBoard(board) else: self._boardAsNumber = self._boardToNumber(board) self._boardAsArray = board def __int__(self): return self._boardAsNumber def __getitem__(self, key): return self._boardAsArray[key] def __setitem__(self, key, value): self._boardAsArray[key] = value self._boardAsNumber = self._boardToNumber(self._boardAsArray) def __str__(self): valueToString = { self.X: "X", self.O: "O", self._: "_" } board = [valueToString[i] for i in self._boardAsArray] board.insert(6, os.linesep) board.insert(3, os.linesep) return ''.join(board) def _boardToNumber(self, boardObject): """ There are three states of a nine squares, so a board can be described by a 9 digit trinary number. I could hardcode this, but I think the loop is more intuitive. Hopefully the interpreter is smart enough to optimize it. """ trinaryValue = { self.X: 2, self.O: 1, self._: 0 } theNumber = 0 for x in range(9): # We want the first element to be the most significant, # so we use 9 - x # The loop offset requires the x - 1 theNumber += trinaryValue[boardObject[x]] * 3 ** (9 - x - 1) return theNumber def _numberToBoard(self, theNumber): boardValue = { 2: self.X, 1: self.O, 0: self._ } theBoard = [] for x in range(9): trinaryDigit = int(theNumber / 3 ** (9 - x - 1)) theBoard.append(boardValue[trinaryDigit]) theNumber -= trinaryDigit * 3 ** (9 - x - 1) return theBoard # Dihedral group operations. Since this implementation is tic-tac-toe # specific, we don't have a separate DihedralGroup class. @staticmethod def _reflection(board): return [ board[2], board[1], board[0], board[5], board[4], board[3], board[8], board[7], board[6] ] @staticmethod def _rotation(board, steps): octogon = [ board[0], board[1], board[2], board[5], board[8], board[7], board[6], board[3] ] rotatedOctogon = [octogon[(x + steps*2) % 8] for x in range(8)] rotatedBoard = [ rotatedOctogon[0], rotatedOctogon[1], rotatedOctogon[2], rotatedOctogon[7], board[4], rotatedOctogon[3], rotatedOctogon[6], rotatedOctogon[5], rotatedOctogon[4] ] return rotatedBoard def getWhoseTurn(self): """ Count the number of X's and O's and figure out whose turn it is. """ numberOfXs = sum([1 for i in self._boardAsArray if i == self.X]) numberOfOs = sum([1 for i in self._boardAsArray if i == self.O]) if numberOfXs == numberOfOs: return self.X else: return self.O def getUniqueRepresentation(self): """ This returns the normalized board. See README.md for normalizing and why we do it. """ board = self._boardAsArray minBoard = self._boardAsNumber operation = 0 for x in range(1, len(self._d8)): boardPrime = self._boardToNumber(self._d8[x](board)) if boardPrime < minBoard: minBoard = boardPrime operation = x return minBoard, operation def getWhoWon(self): waysToWin = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [6, 4, 2] ] board = self._boardAsArray for x in waysToWin: if board[x[0]] == board[x[1]] == board[x[2]]: return board[x[0]] return None def createNextStep(self): """ Returns TicTacToeBoard Objects """ startingState = self._boardAsArray whoseTurn = self.getWhoseTurn() nextStates = [] for square in range(9): # For each square if startingState[square] is None: newState = list(startingState) newState[square] = whoseTurn nextStates += [TicTacToeBoard(newState)] return nextStates if __name__ == "__main__": X = TicTacToeBoard.X O = TicTacToeBoard.O _ = TicTacToeBoard._ # trinary 222, 110, 000 == decimal 19278 boardArray = [ X, X, X, O, O, _, _, _, _ ] boardNumber = 19278 board = TicTacToeBoard(boardArray) board2 = TicTacToeBoard(boardNumber) assert int(board) == int(board2) == boardNumber assert list(board) == list(board2) == boardArray assert TicTacToeBoard._d8[0](board) == [ X, X, X, O, O, _, _, _, _ ] assert TicTacToeBoard._d8[1](board) == [ X, _, _, X, O, _, X, O, _ ] assert TicTacToeBoard._d8[2](board) == [ _, _, _, _, O, O, X, X, X ] assert TicTacToeBoard._d8[3](board) == [ _, O, X, _, O, X, _, _, X ] assert TicTacToeBoard._d8[4](board) == [ X, X, X, _, O, O, _, _, _ ] assert TicTacToeBoard._d8[5](board) == [ _, _, X, _, O, X, _, O, X ] assert TicTacToeBoard._d8[6](board) == [ _, _, _, O, O, _, X, X, X ] assert TicTacToeBoard._d8[7](board) == [ X, O, _, X, O, _, X, _, _ ] assert board.getWhoseTurn() == O board[5] = O assert board.getWhoseTurn() == X board[5] = _ newline = os.linesep assert str(board) == "XXX" + newline + "OO_" + newline + "___" print "Tests pass."
""".. rubric:: Corrplot utilities :author: Thomas Cokelaer :references: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html """ import string from colormap import cmap_builder import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.patches import Ellipse, Circle, Rectangle, Wedge from matplotlib.collections import PatchCollection import pandas as pd import scipy.cluster.hierarchy as hierarchy from biokit.viz.linkage import Linkage __all__ = ['Corrplot'] class Corrplot(Linkage): """An implementation of correlation plotting tools (corrplot) Here is a simple example with a correlation matrix as an input (stored in a pandas dataframe): .. plot:: :width: 50% :include-source: # create a correlation-like data set stored in a Pandas' dataframe. import string # letters = string.uppercase[0:10] # python2 letters = string.ascii_uppercase[0:10] import pandas as pd df = pd.DataFrame(dict(( (k, np.random.random(10)+ord(k)-65) for k in letters))) # and use corrplot from biokit.viz import corrplot c = corrplot.Corrplot(df) c.plot() .. seealso:: All functionalities are covered in this `notebook <http://nbviewer.ipython.org/github/biokit/biokit/blob/master/notebooks/viz/corrplot.ipynb>`_ """ def __init__(self, data, na=0): """.. rubric:: Constructor Plots the content of square matrix that contains correlation values. :param data: input can be a dataframe (Pandas), or list of lists (python) or a numpy matrix. Note, however, that values must be between -1 and 1. If not, or if the matrix (or list of lists) is not squared, then correlation is computed. The data or computed correlation is stored in :attr:`df` attribute. :param bool compute_correlation: if the matrix is non-squared or values are not bounded in -1,+1, correlation is computed. If you do not want that behaviour, set this parameter to False. (True by default). :param na: replace NA values with this value (default 0) The :attr:`params` contains some tunable parameters for the colorbar in the :meth:`plot` method. :: # can be a list of lists, the correlation matrix is then a 2x2 matrix c = corrplot.Corrplot([[1,1], [2,4], [3,3], [4,4]]) """ super(Corrplot, self).__init__() #: The input data is stored in a dataframe and must therefore be #: compatible (list of lists, dictionary, matrices...) self.df = pd.DataFrame(data, copy=True) compute_correlation = False w, h = self.df.shape if self.df.max().max() > 1 or self.df.min().min()<-1: compute_correlation = True if w !=h: compute_correlation = True if list(self.df.index) != list(self.df.columns): compute_correlation = True if compute_correlation: print("Computing correlation") cor = self.df.fillna(na).corr() self.df = cor # replace NA with zero self.df.fillna(na, inplace=True) #: tunable parameters for the :meth:`plot` method. self.params = { 'colorbar.N': 100, 'colorbar.shrink': .8, 'colorbar.orientation':'vertical'} def _set_default_cmap(self): self.cm = cmap_builder('#AA0000','white','darkblue') def order(self, method='complete', metric='euclidean',inplace=False): """Rearrange the order of rows and columns after clustering :param method: any scipy method (e.g., single, average, centroid, median, ward). See scipy.cluster.hierarchy.linkage :param metric: any scipy distance (euclidean, hamming, jaccard) See scipy.spatial.distance or scipy.cluster.hieararchy :param bool inplace: if set to True, the dataframe is replaced You probably do not need to use that method. Use :meth:`plot` and the two parameters order_metric and order_method instead. """ Y = self.linkage(self.df, method=method, metric=metric) ind1 = hierarchy.fcluster(Y, 0.7*max(Y[:,2]), 'distance') Z = hierarchy.dendrogram(Y, no_plot=True) idx1 = Z['leaves'] cor2 = self.df.iloc[idx1,idx1] if inplace is True: self.df = cor2 else: return cor2 self.Y = Y self.Z = Z self.idx1 = idx1 self.ind1 = ind1 #treee$order == Z.leaves and c.idx1 # hc = c.ind1 #clustab <- table(hc)[unique(hc[tree$order])] #cu <- c(0, cumsum(clustab)) #mat <- cbind(cu[-(k + 1)] + 0.5, n - cu[-(k + 1)] + 0.5, #cu[-1] + 0.5, n - cu[-1] + 0.5) #rect(mat[,1], mat[,2], mat[,3], mat[,4], border = col, lwd = lwd) def plot(self, fig=None, grid=True, rotation=30, lower=None, upper=None, shrink=0.9, facecolor='white', colorbar=True, label_color='black', fontsize='small', edgecolor='black', method='ellipse', order_method='complete', order_metric='euclidean', cmap=None, ax=None, binarise_color=False): """plot the correlation matrix from the content of :attr:`df` (dataframe) By default, the correlation is shown on the upper and lower triangle and is symmetric wrt to the diagonal. The symbols are ellipses. The symbols can be changed to e.g. rectangle. The symbols are shown on upper and lower sides but you could choose a symbol for the upper side and another for the lower side using the **lower** and **upper** parameters. :param fig: Create a new figure by default. If an instance of an existing figure is provided, the corrplot is overlayed on the figure provided. Can also be the number of the figure. :param grid: add grid (Defaults to grey color). You can set it to False or a color. :param rotation: rotate labels on y-axis :param lower: if set to a valid method, plots the data on the lower left triangle :param upper: if set to a valid method, plots the data on the upper left triangle :param float shrink: maximum space used (in percent) by a symbol. If negative values are provided, the absolute value is taken. If greater than 1, the symbols wiill overlap. :param facecolor: color of the background (defaults to white). :param colorbar: add the colorbar (defaults to True). :param str label_color: (defaults to black). :param fontsize: size of the fonts defaults to 'small'. :param method: shape to be used in 'ellipse', 'square', 'rectangle', 'color', 'text', 'circle', 'number', 'pie'. :param order_method: see :meth:`order`. :param order_metric: see : meth:`order`. :param cmap: a valid cmap from matplotlib or colormap package (e.g., 'jet', or 'copper'). Default is red/white/blue colors. :param ax: a matplotlib axes. The colorbar can be tuned with the parameters stored in :attr:`params`. Here is an example. See notebook for other examples:: c = corrplot.Corrplot(dataframe) c.plot(cmap=('Orange', 'white', 'green')) c.plot(method='circle') c.plot(colorbar=False, shrink=.8, upper='circle' ) """ # default if cmap != None: try: if isinstance(cmap, str): self.cm = cmap_builder(cmap) else: self.cm = cmap_builder(*cmap) except: print("incorrect cmap. Use default one") self._set_default_cmap() else: self._set_default_cmap() self.shrink = abs(shrink) self.fontsize = fontsize self.edgecolor = edgecolor df = self.order(method=order_method, metric=order_metric) # figure can be a number or an instance; otherwise creates it if isinstance(fig, int): fig = plt.figure(num=fig, facecolor=facecolor) elif fig is not None: fig = plt.figure(num=fig.number, facecolor=facecolor) else: fig = plt.figure(num=None, facecolor=facecolor) # do we have an axes to plot the data in ? if ax is None: ax = plt.subplot(1, 1, 1, aspect='equal', facecolor=facecolor) else: # if so, clear the axes. Colorbar cannot be removed easily. plt.sca(ax) ax.clear() # subplot resets the bg color, let us set it again fig.set_facecolor(facecolor) width, height = df.shape labels = (df.columns) # add all patches to the figure # TODO check value of lower and upper if upper is None and lower is None: mode = 'method' diagonal = True elif upper and lower: mode = 'both' diagonal = False elif lower is not None: mode = 'lower' diagonal = True elif upper is not None: mode = 'upper' diagonal = True self.binarise_color = binarise_color if mode == 'upper': self._add_patches(df, upper, 'upper', ax, diagonal=True) elif mode == 'lower': self._add_patches(df, lower, 'lower', ax, diagonal=True) elif mode == 'method': self._add_patches(df, method, 'both', ax, diagonal=True) elif mode == 'both': self._add_patches(df, upper, 'upper', ax, diagonal=False) self._add_patches(df, lower, 'lower', ax, diagonal=False) # set xticks/xlabels on top ax.xaxis.tick_top() xtickslocs = np.arange(len(labels)) ax.set_xticks(xtickslocs) ax.set_xticklabels(labels, rotation=rotation, color=label_color, fontsize=fontsize, ha='left') ytickslocs = np.arange(len(labels)) ax.set_yticks(ytickslocs) ax.set_yticklabels(labels, fontsize=fontsize, color=label_color) plt.tight_layout() # shift the limits to englobe the patches correctly # This should be here afer set_xticks ax.set_xlim(-0.5, width-.5) ax.set_ylim(-0.5, height-.5) ax.invert_yaxis() if grid is not False: if grid is True: grid = 'grey' for i in range(0, width): ratio1 = float(i)/width ratio2 = float(i+2)/width # TODO 1- set axis off # 2 - set xlabels along the diagonal # set colorbar either on left or bottom if mode == 'lower': plt.axvline(i+.5, ymin=1-ratio1, ymax=0., color=grid) plt.axhline(i+.5, xmin=0, xmax=ratio2, color=grid) if mode == 'upper': plt.axvline(i+.5, ymin=1 - ratio2, ymax=1, color=grid) plt.axhline(i+.5, xmin=ratio1, xmax=1, color=grid) if mode in ['method', 'both']: plt.axvline(i+.5, color=grid) plt.axhline(i+.5, color=grid) # can probably be simplified if mode == 'lower': plt.axvline(-.5, ymin=0, ymax=1, color='grey') plt.axvline(width-.5, ymin=0, ymax=1./width, color='grey', lw=2) plt.axhline(width-.5, xmin=0, xmax=1, color='grey',lw=2) plt.axhline(-.5, xmin=0, xmax=1./width, color='grey',lw=2) plt.xticks([]) for i in range(0, width): plt.text(i, i-.6 ,labels[i],fontsize=fontsize, color=label_color, rotation=rotation, verticalalignment='bottom') plt.text(-.6, i ,labels[i],fontsize=fontsize, color=label_color, rotation=0, horizontalalignment='right') plt.axis('off') # can probably be simplified elif mode == 'upper': plt.axvline(width-.5, ymin=0, ymax=1, color='grey', lw=2) plt.axvline(-.5, ymin=1-1./width, ymax=1, color='grey', lw=2) plt.axhline(-.5, xmin=0, xmax=1, color='grey',lw=2) plt.axhline(width-.5, xmin=1-1./width, xmax=1, color='grey',lw=2) plt.yticks([]) for i in range(0, width): plt.text(-.6+i, i ,labels[i],fontsize=fontsize, color=label_color, horizontalalignment='right', rotation=0) plt.text(i, -.5 ,labels[i],fontsize=fontsize, color=label_color, rotation=rotation, verticalalignment='bottom') plt.axis('off') # set all ticks length to zero ax = plt.gca() ax.tick_params(axis='both',which='both', length=0) if colorbar: N = self.params['colorbar.N'] + 1 assert N >=2 # make sure the colorbar limits remains between the min (0) and the # max (1) (remember colormap are normalised) so that if data is # between -0.5 and let us say +1, the colors do not start at -0.5 # but -1 indeed. self.collection.set_clim(0,1) cb = plt.gcf().colorbar(self.collection, orientation=self.params['colorbar.orientation'], shrink=self.params['colorbar.shrink'], boundaries= np.linspace(0,1,N), ticks=[0,.25, 0.5, 0.75,1], ax=ax) cb.ax.set_yticklabels([-1,-.5,0,.5,1]) return cb def _add_patches(self, df, method, fill, ax, diagonal=True): width, height = df.shape labels = (df.columns) patches = [] colors = [] for x in range(width): for y in range(height): if fill == 'lower' and x > y: continue elif fill == 'upper' and x < y: continue if diagonal is False and x==y: continue datum = (df.iloc[x, y] +1.)/2. d = df.iloc[x, y] d_abs = np.abs(d) #c = self.pvalues[x, y] rotate = -45 if d > 0 else +45 #cmap = self.poscm if d >= 0 else self.negcm if method in ['ellipse', 'square', 'rectangle', 'color']: if method == 'ellipse': func = Ellipse patch = func((x, y), width=1 * self.shrink, height=(self.shrink - d_abs*self.shrink), angle=rotate) else: func = Rectangle w = h = d_abs * self.shrink #FIXME shring must be <=1 offset = (1-w)/2. if method == 'color': w = 1 h = 1 offset = 0 patch = func((x + offset-.5, y + offset-.5), width=w, height=h, angle=0) if self.edgecolor: patch.set_edgecolor(self.edgecolor) #patch.set_facecolor(cmap(d_abs)) colors.append(datum) if d_abs > 0.05: patch.set_linestyle('dotted') #ax.add_artist(patch) patches.append(patch) #FIXME edgecolor is always printed elif method=='circle': patch = Circle((x, y), radius=d_abs*self.shrink/2.) if self.edgecolor: patch.set_edgecolor(self.edgecolor) #patch.set_facecolor(cmap(d_abs)) colors.append(datum) if d_abs > 0.05: patch.set_linestyle('dotted') #ax.add_artist(patch) patches.append(patch) elif method in ['number', 'text']: from easydev import precision if d<0: edgecolor = 'red' elif d>=0: edgecolor = 'blue' ax.text(x,y, precision(d, 2), color=edgecolor, fontsize=self.fontsize, horizontalalignment='center', weight='bold', alpha=max(0.5, d_abs)) # withdash=False) elif method == 'pie': S = 360 * d_abs patch = [ Wedge((x,y), 1*self.shrink/2., -90, S-90), Wedge((x,y), 1*self.shrink/2., S-90, 360-90), ] #patch[0].set_facecolor(cmap(d_abs)) #patch[1].set_facecolor('white') colors.append(datum) colors.append(0.5) if self.edgecolor: patch[0].set_edgecolor(self.edgecolor) patch[1].set_edgecolor(self.edgecolor) #ax.add_artist(patch[0]) #ax.add_artist(patch[1]) patches.append(patch[0]) patches.append(patch[1]) else: raise ValueError('Method for the symbols is not known. Use e.g, square, circle') if self.binarise_color: colors = [1 if color >0.5 else -1 for color in colors] if len(patches): col1 = PatchCollection(patches, array=np.array(colors), cmap=self.cm) ax.add_collection(col1) self.collection = col1 # Somehow a release of matplotlib prevent the edge color # from working but the set_edgecolor on the collection itself does # work... if self.edgecolor: self.collection.set_edgecolor(self.edgecolor)
# Copyright 2014, Rackspace US, 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. # # (c) 2014, Kevin Carter <kevin.carter@rackspace.com> import os import traceback from distutils import version import yaml from ansible import utils, errors VERSION_DESCRIPTORS = ['>=', '<=', '==', '!=', '<', '>'] REQUIREMENTS_FILE_TYPES = [ 'requirements.txt', 'global-requirements.txt', 'test-requirements.txt', 'dev-requirements.txt' ] # List of variable names that could be used within the yaml files that # represent lists of python packages. BUILT_IN_PIP_PACKAGE_VARS = [ 'service_pip_dependencies', 'pip_common_packages', 'pip_container_packages', 'pip_packages' ] class DependencyFileProcessor(object): def __init__(self, local_path): """Find required files. :type local_path: ``str`` :return: """ self.pip = dict() self.pip['git_package'] = list() self.pip['py_package'] = list() self.git_pip_install = 'git+%s@%s' self.file_names = self._get_files(path=local_path) # Process everything simply by calling the method self._process_files(ext=('yaml', 'yml')) def _filter_files(self, file_names, ext): """Filter the files and return a sorted list. :type file_names: :type ext: ``str`` or ``tuple`` :returns: ``list`` """ _file_names = list() for file_name in file_names: if file_name.endswith(ext): if '/defaults/' in file_name or '/vars/' in file_name: _file_names.append(file_name) else: continue elif os.path.basename(file_name) in REQUIREMENTS_FILE_TYPES: with open(file_name, 'rb') as f: packages = [ i.split()[0] for i in f.read().splitlines() if i if not i.startswith('#') ] self.pip['py_package'].extend(packages) else: return sorted(_file_names, reverse=True) @staticmethod def _get_files(path): """Return a list of all files in the defaults/repo_packages directory. :type path: ``str`` :returns: ``list`` """ paths = os.walk(os.path.abspath(path)) files = list() for fpath, _, afiles in paths: for afile in afiles: files.append(os.path.join(fpath, afile)) else: return files def _check_plugins(self, git_repo_plugins, git_data): """Check if the git url is a plugin type. :type git_repo_plugins: ``dict`` :type git_data: ``dict`` """ for repo_plugin in git_repo_plugins: plugin = '%s/%s' % ( repo_plugin['path'].strip('/'), repo_plugin['package'].lstrip('/') ) package = self.git_pip_install % ( git_data['repo'], '%s#egg=%s&subdirectory=%s' % ( git_data['branch'], repo_plugin['package'].strip('/'), plugin ) ) self.pip['git_package'].append(package) def _process_git(self, loaded_yaml, git_item): """Process git repos. :type loaded_yaml: ``dict`` :type git_item: ``str`` """ git_data = dict() if git_item.split('_')[0] == 'git': var_name = 'git' else: var_name = git_item.split('_git_repo')[0] git_data['repo'] = loaded_yaml.get(git_item) git_data['branch'] = loaded_yaml.get( '%s_git_install_branch' % var_name.replace('.', '_') ) if not git_data['branch']: git_data['branch'] = loaded_yaml.get( 'git_install_branch', 'master' ) package = self.git_pip_install % ( git_data['repo'], git_data['branch'] ) self.pip['git_package'].append(package) git_repo_plugins = loaded_yaml.get('%s_repo_plugins' % var_name) if git_repo_plugins: self._check_plugins( git_repo_plugins=git_repo_plugins, git_data=git_data ) def _process_files(self, ext): """Process files. :type ext: ``tuple`` """ file_names = self._filter_files( file_names=self.file_names, ext=ext ) for file_name in file_names: with open(file_name, 'rb') as f: loaded_config = yaml.safe_load(f.read()) for key, values in loaded_config.items(): if key.endswith('git_repo'): self._process_git( loaded_yaml=loaded_config, git_item=key ) if [i for i in BUILT_IN_PIP_PACKAGE_VARS if i in key]: self.pip['py_package'].extend(values) def _abs_path(path): return os.path.abspath( os.path.expanduser( path ) ) class LookupModule(object): def __init__(self, basedir=None, **kwargs): """Run the lookup module. :type basedir: :type kwargs: """ self.basedir = basedir def run(self, terms, inject=None, **kwargs): """Run the main application. :type terms: ``str`` :type inject: ``str`` :type kwargs: ``dict`` :returns: ``list`` """ terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject) if isinstance(terms, basestring): terms = [terms] return_list = list() for term in terms: try: dfp = DependencyFileProcessor( local_path=_abs_path(str(term)) ) return_list.extend(dfp.pip['py_package']) return_list.extend(dfp.pip['git_package']) except Exception as exp: raise errors.AnsibleError( 'lookup_plugin.py_pkgs(%s) returned "%s" error "%s"' % ( term, str(exp), traceback.format_exc() ) ) else: return_data = { 'packages': list(), 'remote_packages': list() } for file_name in sorted(set(return_list)): is_url = file_name.startswith(('http:', 'https:', 'git+')) if is_url: if '@' not in file_name: return_data['packages'].append(file_name) else: return_data['remote_packages'].append(file_name) else: return_data['packages'].append(file_name) else: return_data['packages'] = ' '.join( ['"%s"' % i for i in set(return_data['packages'])] ) return_data['remote_packages'] = ' '.join( ['"%s"' % i for i in set(return_data['remote_packages'])] ) return [return_data]
import ast from itertools import combinations import tac import tac_analysis ivy_type_decls = open('ivy_type_decls.ivy').read() def test_function(): #lst = ((1,2), ('a','b')) #lst = [(1,2), ('a', 'b',) , ([],[]), (((),),), 1+x] lst = [] lst = lst + [(1,2)] lst = lst + [('a','b')] #lst.append((1,2)) #lst.append(('a','b')) for x in lst: y = x[0] + x[1] #x,y = z #v0 = 1 #v1 = 'a' #v2 = None #x = (v0, v1, v2) #1,'a',None) #y = x[2] def test_function(): # lst = [] # lst = lst + [(1,2)] # lst = lst + [('a',None)] # for x in lst: # i = x[0] # j = x[1] # k = i + 1 lst = [('a', 'b')] lst = lst + [(1,2)] lst = lst + [([1],['a'])] #lst = lst + [([1],'a')] for x in lst: k = x[0] + x[1] # lst = [] # lst = lst + [(1,2)] # lst = lst + [('a',None)] # for x in lst: # y = x[0] + x[1] # z = 'a' + None def test_function2(): x = 0 y = 1 < True while True: z = x + y x = "aaa" #y = "b" x = 2 if (x > 0): y = 1 else: y = 2 z = x + y # def test_function(): # x = 1 # y = '' #None # if (x > 0): # y = 1 # else: # y = 2 # z = x + y # def test_function(): # x1 = a + b # x2 = a ** b # x3 = x1 * x2 # y = not x1 # z1 = 1 # z2 = '1' # z3 = True # z4 = False # z5 = None # # if (ha>3): # # print('yes') # # z6 = -z1 # # if x: # # y = 1 # # else: # # x = 1 def parse_literal_expression(string_expr): if tac.is_stackvar(string_expr): return ast.Name body = ast.parse(string_expr).body assert len(body) == 1 expr = body[0] return type(expr.value) def ivy_and(*exprs): if len(exprs) == 0: return "true" else: return '(' + ' & '.join( '({})'.format(e) for e in exprs ) + ')' def ivy_or(*exprs): if len(exprs) == 0: return "false" else: return '(' + ' | '.join( '({})'.format(e) for e in exprs ) + ')' class TacToIvy(object): def ivy_type_of_lit(self, x): ast_class = parse_literal_expression(x) if ast_class is ast.Num: return 't_intbool' elif ast_class is ast.Str: return 't_str' elif ast_class is ast.NameConstant and x in ['True', 'False']: return 't_intbool' elif ast_class is ast.NameConstant and x == 'None': return 't_none' else: return None def ivy_obj_of(self, x): x = x.strip() ast_class = parse_literal_expression(x) if ast_class is ast.Name: if x not in self.python_vars: name = str(x) # get rid of '@' name = name.replace('@', 'tmp_') self.python_vars[x] = name return self.python_vars[x] elif self.ivy_type_of_lit(x) is not None: if x not in self.python_lits: self.python_lits[x] = 'lit_{}'.format(len(self.python_lits)) return self.python_lits[x] else: assert False, (x, ast_class) def instruction_to_ivy(self, instruction): # return instruction.fmt.format(**instruction._asdict()) + '\n' # print(instruction) op = instruction.opcode if op == tac.OP.NOP: result = self.no_change() elif op == tac.OP.ASSIGN: result = self.assign(instruction) elif op == tac.OP.IMPORT: result = self.no_change() elif op == tac.OP.BINARY: result = self.binary(instruction) elif op == tac.OP.INPLACE: assert False, str(instruction) elif op == tac.OP.CALL: result = self.call(instruction) elif op == tac.OP.JUMP: result = self.no_change() elif op == tac.OP.FOR: result = self.for_loop(instruction) elif op == tac.OP.RET: result = self.no_change() # assert False, "Function calls not supported" elif op == tac.OP.DEL: result = self.no_change() else: assert False, "Unknown Three Address Code instruction in {}".format(instruction) return result def no_change(self): return "" def assign(self, instruction): lhs = instruction.gens[0] rhs = instruction.uses[0] return "{} := {}".format(self.ivy_obj_of(lhs), self.ivy_obj_of(rhs)) def for_loop(self, instruction): assert len(instruction.gens) == 1 assert len(instruction.uses) == 1 return self.ivy_func(instruction.gens[0], 'for_loop', instruction.uses) def call(self, instruction): assert len(instruction.gens) == 1 result = instruction.gens[0] function_name = instruction.func.strip() arguments = instruction.uses[1:] # TODO: add kargs (see TAC) if function_name in self.python_vars: assert False, str(instruction) # The following is not needed after Elazar's fix: # # assert len(arguments) <= 2, "call_X only up to X=2" # return "{} := call_{}({})".format( # self.ivy_obj_of(result), # len(arguments), # ', '.join(self.ivy_obj_of(x) for x in [function_name] + list(arguments)) # ) else: return self.builtin_function(result, function_name, arguments) def binary(self, instruction): assert len(instruction.gens) == 1 assert len(instruction.uses) == 2 return self.builtin_function( result=instruction.gens[0], function_name=instruction.op, arguments=instruction.uses[:], ) def ivy_func(self, result, ivy_function_name, arguments): return "tmp_result := {}{}\n{} := tmp_result".format( ivy_function_name, '(' + ', '.join(self.ivy_obj_of(a) for a in arguments) + ')' if len(arguments) > 0 else '', self.ivy_obj_of(result) ) def builtin_function(self, result, function_name, arguments): function_name = function_name.strip() if function_name in ['**', '//', '%', '-', '<<', '>>', '&', '|', '^'] and len(arguments) == 2: return self.ivy_func(result, 'numeric_op', arguments) elif function_name == '+' and len(arguments) == 2: return self.ivy_func(result, 'addition', arguments) elif function_name == '+' and len(arguments) == 2: return self.ivy_func(result, 'multiply', arguments) elif function_name in ['>', '<', '>=', '<='] and len(arguments) == 2: return self.ivy_func(result, 'comparison', arguments) elif function_name == 'not' and len(arguments) == 1: return self.ivy_func(result, 'logical_not', arguments) elif function_name in ['>', '<', '>=', '<='] and len(arguments) == 2: return self.ivy_func(result, 'equal', arguments) elif function_name == 'LIST' and len(arguments) == 0: return self.ivy_func(result, 'new_empty_list', arguments) elif function_name == 'LIST' and len(arguments) == 1: return self.ivy_func(result, 'new_list_1', arguments) elif function_name == 'ITER' and len(arguments) == 1: return self.ivy_func(result, 'new_iter_of', arguments) elif function_name == 'BUILTINS.getitem' and len(arguments) == 2: return self.ivy_func(result, 'getitem', arguments) # The following is not needed after Elazar's fix: # # elif (function_name == 'BUILTINS.getattr' and # len(arguments) == 2 and # arguments[1] in ["'append'", "'__getitem__'"] # ): # func_name = ast.literal_eval(arguments[1]).replace('__','') # return "{} := getattr_{}({})".format( # self.ivy_obj_of(result), # func_name, # self.ivy_obj_of(arguments[0]), # ) elif function_name == 'TUPLE': return "\n".join([ "tmp_result := *", "assume type_of(tmp_result) = t_tuple", ] + [ "assume item(tmp_result,{},X) <-> X = {}".format( self.ivy_obj_of(str(i)), self.ivy_obj_of(arguments[i]), ) for i in range(len(arguments)) ] + [ "{} := tmp_result".format(self.ivy_obj_of(result)), ]) else: assert False, "builtin_function({!r}, {!r}, {!r})".format( result, function_name, arguments ) def block_instructions_to_ivy(self, block_instructions): instructions = [self.instruction_to_ivy(instruction) for instruction in block_instructions] instructions = [x for x in instructions if x != ''] instructions = [y for x in instructions for y in x.splitlines()] return instructions def tac_blocks_cfg_to_ivy(self, tac_blocks_cfg): self.python_vars = dict() self.python_lits = dict() block_ids = sorted(tac_blocks_cfg.nodes()) first_block_id = block_ids[0] # the smallest id is the first to run ivy_can_run_decls = "\n".join([ "type basic_block", "relation can_run(B:basic_block)", ] + [ "individual bb{}:basic_block".format(i) for i in block_ids ] + [ "axiom bb{} ~= bb{}".format(i, j) for i, j in combinations(block_ids, 2) ] + [ "axiom " + ivy_or(*("B = bb{}".format(i) for i in block_ids)), "init can_run(B) <-> B = bb{}".format(first_block_id) ]) + "\n\n" actions = [] for i in block_ids: block_instructions = tac_blocks_cfg.node[i][tac.BLOCKNAME] successor_ids = tac_blocks_cfg.successors(i) ivy_instructions = ( ["assume can_run(bb{})".format(i)] + self.block_instructions_to_ivy(block_instructions) + ["can_run(B) := {}".format(ivy_or(*( "B = bb{}".format(j) for j in successor_ids )))] ) actions.append( "action basic_block_{} = {{\n ".format(i) + ";\n ".join(ivy_instructions) + "\n}}\nexport basic_block_{}".format(i) ) python_vars = sorted((v, x) for x, v in self.python_vars.items()) ivy_python_vars_decls = "\n".join( "individual {}:python_object # {}".format(v, x) for v, x in python_vars ) python_lits = sorted((lit, x) for x, lit in self.python_lits.items()) ivy_python_lits_decls = "\n".join( "individual {}:python_object # {}\n".format(lit, x) + "axiom type_of({}) = {}".format(lit, self.ivy_type_of_lit(x)) for lit, x in python_lits ) return "\n\n\n".join( [ "#lang ivy1.3", "\n".join("# " + line for line in tac.cfg_to_lines(tac_blocks_cfg)), ivy_type_decls, ivy_can_run_decls, ivy_python_lits_decls, ivy_python_vars_decls, ] + actions ) def test(code_to_analyze): from pdb import set_trace # set_trace() #tac_blocks_cfg = tac_analysis.make_tacblock_cfg(code_to_analyze) tac_blocks_cfg = tac.make_tacblock_cfg(code_to_analyze) print("\n".join("# " + line for line in tac.cfg_to_lines(tac_blocks_cfg))) print() tac_to_ivy = TacToIvy() result = tac_to_ivy.tac_blocks_cfg_to_ivy(tac_blocks_cfg) open("ivy_file.ivy", 'w').write(result) #print(result) if __name__ == "__main__": test(test_function)
from deployer.cli import CLInterface, Handler, HandlerType from deployer.console import Console from deployer.console import NoInput from deployer.exceptions import ActionException from deployer.inspection import Inspector, PathType from deployer.node import Env, IsolationIdentifierType from inspect import getfile from itertools import groupby from pygments import highlight from pygments.formatters import TerminalFormatter from pygments.lexers import PythonLexer import deployer import inspect import socket import sys import termcolor __all__ = ('Shell', ) # Handler types class ActionType(HandlerType): def __init__(self, color): self.color = color self.postfix = '*' def type_of_node(node): group = Inspector(node).get_group() return NodeType(group.color) def type_of_action(action): group = action.node_group return ActionType(group.color) class NodeType(HandlerType): def __init__(self, color): self.color = color class BuiltinType(HandlerType): color = 'cyan' # Utils for navigation class ShellHandler(Handler): def __init__(self, shell): self.shell = shell class AUTOCOMPLETE_TYPE: NODE = 'NODE' ACTION = 'ACTION' ACTION_AND_ARGS = 'ACTION_AND_ARGS' QUERY_ATTRIBUTE = 'QUERY_ATTRIBUTE' PROPERTY_ATTRIBUTE = 'PROPERTY' CONSTANT_ATTRIBUTE = 'CONNSTANT' # TODO: inspection on this type. class NodeACHandler(ShellHandler): """ ShellHandler which implements node path completion. Depending on the ``autocomplete_types`` attribute, it can complete on nodes, actions, or any other attribute value. """ autocomplete_types = [AUTOCOMPLETE_TYPE.NODE] def __init__(self, shell, node=None, attr_name=None, args=None): ShellHandler.__init__(self, shell) self._root = node is None self.node = node or shell.state._node self.attr_name = attr_name self.args = args or [] @property def is_leaf(self): return self.get_type() is not None def get_type(self): """ Return the ``AUTOCOMPLETE_TYPE`` for this node. """ insp = Inspector(self.node) atypes = self.autocomplete_types if AUTOCOMPLETE_TYPE.NODE in atypes and not self.attr_name: return AUTOCOMPLETE_TYPE.NODE if AUTOCOMPLETE_TYPE.ACTION in atypes and not self.attr_name and insp.is_callable(): return AUTOCOMPLETE_TYPE.ACTION if AUTOCOMPLETE_TYPE.ACTION in atypes and insp.has_action(self.attr_name): return AUTOCOMPLETE_TYPE.ACTION if AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE in atypes and insp.has_query(self.attr_name): return AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE if AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE in atypes and insp.has_property(self.attr_name): return AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE @property def handler_type(self): if self._root: return BuiltinType() else: node_color = Inspector(self.node).get_group().color def get_postfix(): type_ = self.get_type() if type_ == AUTOCOMPLETE_TYPE.ACTION: return '*' if type_ == AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE: return '?' if type_ == AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE: return '@' return '' class Type(HandlerType): color = node_color postfix = get_postfix() return Type() def get_subhandler(self, name): parent = self.node.parent cls = self.__class__ # Current node if name == '.': return self # Previous location if name == '-' and self.shell.state.can_cdback: return cls(self.shell, self.shell.state.previous_node) # Root node if parent and name == '/': root = Inspector(parent).get_root() return cls(self.shell, root) # Parent node if parent and name == '..': return cls(self.shell, parent) # TODO: ~ --> home. # Isolation elif name.startswith(':'): ids = tuple(name[1:].split(':')) try: node = Inspector(self.node).get_isolation(ids, IsolationIdentifierType.HOSTS_SLUG) return cls(self.shell, node) except AttributeError: pass # Childnodes try: node = Inspector(self.node).get_childnode(name) return cls(self.shell, node) except AttributeError: pass # Actions if AUTOCOMPLETE_TYPE.ACTION in self.autocomplete_types: try: action = Inspector(self.node).get_action(name) return cls(self.shell, self.node, name) except AttributeError: pass if AUTOCOMPLETE_TYPE.ACTION_AND_ARGS in self.autocomplete_types and self.attr_name: return cls(self.shell, self.node, self.attr_name, self.args + [name]) # Queries if AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE in self.autocomplete_types: try: action = Inspector(self.node).get_query(name) return cls(self.shell, self.node, action.name) except AttributeError: pass # Properties if AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE in self.autocomplete_types: try: action = Inspector(self.node).get_property(name) return cls(self.shell, self.node, action.name) except AttributeError: pass def complete_subhandlers(self, part): parent = self.node.parent include_private = part.startswith('_') cls = self.__class__ # No autocompletion anymore after an action has been typed. if self.attr_name: return # Current node if '.'.startswith(part): yield '.', self # Previous location if '-'.startswith(part) and self.shell.state.can_cdback: yield '-', cls(self.shell, self.shell.state.previous_node) # Root node if parent and '/'.startswith(part): root = Inspector(parent).get_root() yield '/', cls(self.shell, root) # Parent node if parent and '..'.startswith(part): yield ('..', cls(self.shell, parent)) # TODO: ~ -->> Home # Isolation for i, n in Inspector(self.node).iter_isolations(IsolationIdentifierType.HOSTS_SLUG): if i: # Prefix all isolations with colons. name = ':%s' % ':'.join(i) if name.startswith(part): yield name, cls(self.shell, n) # Childnodes: # Note: when an underscore has been typed, include private too. for c in Inspector(self.node).get_childnodes(include_private=include_private): name = Inspector(c).get_name() if name.startswith(part): yield name, cls(self.shell, c) # Actions if AUTOCOMPLETE_TYPE.ACTION in self.autocomplete_types: for action in Inspector(self.node).get_actions(include_private=include_private): if action.name.startswith(part): yield action.name, cls(self.shell, self.node, action.name) # Queries if AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE in self.autocomplete_types: for action in Inspector(self.node).get_queries(include_private=include_private): if action.name.startswith(part): yield action.name, cls(self.shell, self.node, action.name) # Properties if AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE in self.autocomplete_types: for action in Inspector(self.node).get_properties(include_private=include_private): if action.name.startswith(part): yield action.name, cls(self.shell, self.node, action.name) def __call__(self): raise NotImplementedError # Handlers class Version(ShellHandler): is_leaf = True handler_type = BuiltinType() def __call__(self): print termcolor.colored(' deployer library, version: ', 'cyan'), print termcolor.colored(deployer.__version__, 'red') print termcolor.colored(' Host: ', 'cyan'), print termcolor.colored(socket.gethostname(), 'red') print termcolor.colored(' Root node class: ', 'cyan'), print termcolor.colored(self.shell.root_node.__module__, 'red'), print termcolor.colored(' <%s>' % self.shell.root_node.__class__.__name__, 'red') class Connect(NodeACHandler): """ Open interactive SSH connection with this host. """ def __call__(self): from deployer.contrib.nodes import connect class Connect(connect.Connect): class Hosts: host = self.node.hosts.get_hosts() env = Env(Connect(), self.shell.pty, self.shell.logger_interface) # Run as any other action. (Nice exception handling, e.g. in case of NoInput on host selection.) try: env.with_host() except ActionException as e: pass except Exception as e: self.shell.logger_interface.log_exception(e) class Run(NodeACHandler): """ Run a shell command on all hosts in the current node. """ use_sudo = False def get_command(self): try: text = '[SUDO] Enter command' if self.use_sudo else 'Enter command' return Console(self.shell.pty).input(text) except NoInput: return def __call__(self): from deployer.node import Node # Print info host_count = len(self.node.hosts) if host_count == 0: print 'No hosts found at this node. Nothing to execute.' return print 'Command will be executed on %i hosts:' % host_count for h in self.node.hosts: print ' - %s (%s)' % (h.slug, h.address) command = self.get_command() if not command: return # Run use_sudo = self.use_sudo class RunNode(Node): class Hosts: host = self.node.hosts.get_hosts() def run(self): if use_sudo: self.hosts.sudo(command) else: self.hosts.run(command) env = Env(RunNode(), self.shell.pty, self.shell.logger_interface) # Run as any other action. (Nice exception handling, e.g. in case of # NoInput on host selection.) try: env.run() except ActionException as e: pass except Exception as e: self.shell.logger_interface.log_exception(e) class RunWithSudo(Run): use_sudo = True class Find(NodeACHandler): def __call__(self): def _list_nested_nodes(node, prefix): for a in Inspector(node).get_actions(): yield '%s %s' % (prefix, termcolor.colored(a.name, Inspector(a.node).get_group().color)) for c in Inspector(node).get_childnodes(): # Check the parent, to avoid loops. if c.parent == node: name = Inspector(c).get_name() for i in _list_nested_nodes(c, '%s %s' % (prefix, termcolor.colored(name, Inspector(c).get_group().color))): yield i Console(self.shell.pty).lesspipe(_list_nested_nodes(self.node, '')) class Inspect(NodeACHandler): """ Inspection of the current node. Show host mappings and other information. """ autocomplete_types = [ AUTOCOMPLETE_TYPE.NODE, AUTOCOMPLETE_TYPE.ACTION, AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE, AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE ] def __call__(self): type_ = self.get_type() if type_ == AUTOCOMPLETE_TYPE.NODE: self._inspect_node() if type_ == AUTOCOMPLETE_TYPE.ACTION: self._inspect_action() if type_ == AUTOCOMPLETE_TYPE.QUERY_ATTRIBUTE: self._inspect_query_attribute() if type_ == AUTOCOMPLETE_TYPE.PROPERTY_ATTRIBUTE: self._inspect_property_attribute() def _inspect_node(self): console = Console(self.shell.pty) def inspect(): # Print full name yield termcolor.colored(' Node: ', 'cyan') + \ termcolor.colored(Inspector(self.node).get_full_name(), 'yellow') # Print mro yield termcolor.colored(' Mro:', 'cyan') i = 1 for m in self.node.__class__.__mro__: if m.__module__ != 'deployer.node' and m != object: yield termcolor.colored(' %i ' % i, 'cyan') + \ termcolor.colored('%s.' % m.__module__, 'red') + \ termcolor.colored('%s' % m.__name__, 'yellow') i += 1 # File names yield termcolor.colored(' Files:', 'cyan') i = 1 for m in self.node.__class__.__mro__: if m.__module__ != 'deployer.node' and m != object: yield termcolor.colored(' %i ' % i, 'cyan') + \ termcolor.colored(getfile(m), 'red') i += 1 # Print host mappings yield termcolor.colored(' Hosts:', 'cyan') for role in sorted(self.node.hosts._hosts.keys()): items = self.node.hosts._hosts[role] yield termcolor.colored(' "%s"' % role, 'yellow') i = 1 for host in sorted(items, key=lambda h:h.slug): yield termcolor.colored(' %3i ' % i, 'cyan') + \ termcolor.colored('%-25s (%s)' % (host.slug, getattr(host, 'address', '')), 'red') i += 1 # Print the first docstring (look to the parents) for m in self.node.__class__.__mro__: if m.__module__ != 'deployer.node' and m != object and m.__doc__: yield termcolor.colored(' Docstring:\n', 'cyan') + \ termcolor.colored(m.__doc__ or '<None>', 'red') break # Actions yield termcolor.colored(' Actions:', 'cyan') def item_iterator(): for a in Inspector(self.node).get_actions(): yield termcolor.colored(a.name, 'red'), len(a.name) for line in console.in_columns(item_iterator(), margin_left=13): yield line # Nodes yield termcolor.colored(' Sub nodes:', 'cyan') # Group by node group grouper = lambda c:Inspector(c).get_group() for group, nodes in groupby(sorted(Inspector(self.node).get_childnodes(), key=grouper), grouper): yield termcolor.colored(' "%s"' % group.name, 'yellow') # Create iterator for all the items in this group def item_iterator(): for n in nodes: name = Inspector(n).get_name() if n.parent == self.node: text = termcolor.colored(name, type_of_node(n).color) length = len(name) else: full_name = Inspector(n).get_full_name() text = termcolor.colored('%s -> %s' % (name, full_name), type_of_node(n).color) length = len('%s -> %s' % (name, full_name)) yield text, length # Show in columns for line in console.in_columns(item_iterator(), margin_left=13): yield line console.lesspipe(inspect()) def _inspect_action(self): console = Console(self.shell.pty) action = Inspector(self.node).get_action(self.attr_name) def run(): yield termcolor.colored(' Action name: ', 'cyan') + \ termcolor.colored(self.attr_name, 'yellow') yield termcolor.colored(' __repr__: ', 'cyan') + \ termcolor.colored(repr(action._func), 'yellow') yield termcolor.colored(' Node: ', 'cyan') + \ termcolor.colored(repr(self.node), 'yellow') console.lesspipe(run()) def _get_env(self): """ Created a sandboxed environment for evaluation of attributes. (attributes shouldn't have side effects on servers, so sandboxing is fine.) Returns an ``Env`` object. """ env = Env(self.node, self.shell.pty, self.shell.logger_interface, is_sandbox=True) return Console(self.shell.pty).select_node_isolation(env) def _inspect_query_attribute(self): console = Console(self.shell.pty) query = Inspector(self.node).get_query(self.attr_name).query def run(): yield termcolor.colored(' Node: ', 'cyan') + \ termcolor.colored(Inspector(self.node).get_full_name(), 'yellow') yield termcolor.colored(' Filename: ', 'cyan') + \ termcolor.colored(query._filename, 'yellow') yield termcolor.colored(' Line: ', 'cyan') + \ termcolor.colored(query._line, 'yellow') yield termcolor.colored(' Expression: ', 'cyan') + \ termcolor.colored(repr(query.query), 'yellow') yield '' # Execute query in sandboxed environment. yield 'Trace query:' try: insp = Inspector(self._get_env()) result = insp.trace_query(self.attr_name) except Exception as e: yield 'Failed to execute query: %r' % e return # Print query and all subqueries with their results. for subquery in result.walk_through_subqueries(): yield termcolor.colored(repr(subquery[0]), 'cyan') yield ' %s' % subquery[1] console.lesspipe(run()) def _inspect_property_attribute(self): console = Console(self.shell.pty) action = Inspector(self.node).get_property(self.attr_name) def run(): yield termcolor.colored(' Property name: ', 'cyan') + \ termcolor.colored(self.attr_name, 'yellow') yield termcolor.colored(' __repr__: ', 'cyan') + \ termcolor.colored(repr(action._func), 'yellow') yield termcolor.colored(' Node: ', 'cyan') + \ termcolor.colored(repr(self.node), 'yellow') # Value try: value = getattr(self._get_env(), self.attr_name) yield termcolor.colored(' Value: ', 'cyan') + \ termcolor.colored(repr(value), 'yellow') except Exception as e: yield termcolor.colored(' Value: ', 'cyan') + \ termcolor.colored('Failed to evaluate value...', 'yellow') console.lesspipe(run()) class Cd(NodeACHandler): def __call__(self): self.shell.state.cd(self.node) class Ls(NodeACHandler): """ List subnodes and actions in the current node. """ def __call__(self): w = self.shell.stdout.write console = Console(self.shell.pty) def run(): # Print nodes if Inspector(self.node).get_childnodes(): yield 'Child nodes:' def column_iterator(): for c in Inspector(self.node).get_childnodes(): name = Inspector(c).get_name() yield termcolor.colored(name, type_of_node(c).color), len(name) for line in console.in_columns(column_iterator()): yield line # Print actions if Inspector(self.node).get_actions(): yield 'Actions:' def column_iterator(): for a in Inspector(self.node).get_actions(): yield termcolor.colored(a.name, type_of_action(a).color), len(a.name) for line in console.in_columns(column_iterator()): yield line console.lesspipe(run()) class Pwd(NodeACHandler): """ Print current node path. ``pwd``, like "Print working Directory" in the Bash shell. """ def __call__(self): result = [ ] for node, name in Inspector(self.node).get_path(PathType.NODE_AND_NAME): color = Inspector(node).get_group().color result.append(termcolor.colored(name, color)) sys.stdout.write(termcolor.colored('/', 'cyan')) sys.stdout.write(termcolor.colored('.', 'cyan').join(result) + '\n') sys.stdout.flush() class SourceCode(NodeACHandler): """ Print the source code of a node. """ def __call__(self): options = [] for m in self.node.__class__.__mro__: if m.__module__ != 'deployer.node' and m != object: options.append( ('%s.%s' % ( termcolor.colored(m.__module__, 'red'), termcolor.colored(m.__name__, 'yellow')), m) ) if len(options) > 1: try: node_class = Console(self.shell.pty).choice('Choose node definition', options) except NoInput: return else: node_class = options[0][1] def run(): try: # Retrieve source source = inspect.getsource(node_class) # Highlight code source = highlight(source, PythonLexer(), TerminalFormatter()) for l in source.split('\n'): yield l.rstrip('\n') except IOError: yield 'Could not retrieve source code.' Console(self.shell.pty).lesspipe(run()) class Scp(NodeACHandler): """ Open a secure copy shell at this node. """ def __call__(self): # Choose host. hosts = self.node.hosts.get_hosts() if len(hosts) == 0: print 'No hosts found' return elif len(hosts) == 1: host = hosts.copy().pop() else: # Choose a host. options = [ (h.slug, h) for h in hosts ] try: host = Console(self.shell.pty).choice('Choose a host', options, allow_random=True) except NoInput: return # Start scp shell from deployer.scp_shell import Shell Shell(self.shell.pty, host, self.shell.logger_interface).cmdloop() class SetOption(ShellHandler): """ Change shell options. """ handler_type = BuiltinType() def complete_subhandlers(self, part): for option_name, option in self.shell.options.items(): if option_name.startswith(part): yield option_name, SetOptionName(self.shell, option) def get_subhandler(self, name): for option_name, option in self.shell.options.items(): if option_name == name: return SetOptionName(self.shell, option) class SetOptionName(ShellHandler): handler_type = BuiltinType() def __init__(self, shell, option): ShellHandler.__init__(self, shell) self.option = option def complete_subhandlers(self, part): for value in self.option.values: if value.startswith(part): yield value, SetOptionNameValue(self.shell, self.option, value) def get_subhandler(self, name): if name in self.option.values: return SetOptionNameValue(self.shell, self.option, name) class SetOptionNameValue(ShellHandler): is_leaf = True handler_type = BuiltinType() def __init__(self, shell, option, value): ShellHandler.__init__(self, shell) self.option = option self.value = value def __call__(self): self.option.set(self.value) class ShowOptions(ShellHandler): """ Show the current shell settings. """ is_leaf = True handler_type = BuiltinType() def __call__(self): for name, option in self.shell.options.items(): print '%-20s %s' % (name, option.get()) class Exit(ShellHandler): """ Quit the deployment shell. """ is_leaf = True handler_type = BuiltinType() def __call__(self): self.shell.exit() class Return(ShellHandler): """ Return from a subshell (which was spawned by a previous node.) """ is_leaf = True handler_type = BuiltinType() def __call__(self): self.shell.state = self.shell.state.return_state class Clear(ShellHandler): """ Clear window. """ is_leaf = True handler_type = BuiltinType() def __call__(self): sys.stdout.write('\033[2J\033[0;0H') sys.stdout.flush() class Node(NodeACHandler): """ Node node. """ sandbox = False autocomplete_types = [ AUTOCOMPLETE_TYPE.ACTION, AUTOCOMPLETE_TYPE.ACTION_AND_ARGS, ] def __call__(self): # Execute logger_interface = self.shell.logger_interface try: # Create env env = Env(self.node, self.shell.pty, logger_interface, is_sandbox=self.sandbox) # Call action if self.attr_name is not None: result = getattr(env, self.attr_name)(*self.args) suppress_result = Inspector(self.node).suppress_result_for_action(self.attr_name) else: result = env(*self.args) suppress_result = False # When the result is a subnode, start a subshell. def handle_result(result): if isinstance(result, deployer.node.Env): print '' print 'Starting subshell ...' self.shell.state = ShellState(result._node, return_state=self.shell.state) # Otherwise, print result elif result is not None and not suppress_result: print result if isinstance(result, list): for r in result: handle_result(r) else: handle_result(result) except ActionException as e: # Already sent to logger_interface in the Action itself. pass except Exception as e: logger_interface.log_exception(e) class Sandbox(Node): sandbox = True class RootHandler(ShellHandler): subhandlers = { 'cd': Cd, 'clear': Clear, 'exit': Exit, 'find': Find, 'ls': Ls, 'sandbox': Sandbox, 'pwd': Pwd, 'set-option': SetOption, 'show-options': ShowOptions, '--connect': Connect, '--inspect': Inspect, '--run': Run, '--run-with-sudo': RunWithSudo, '--version': Version, '--source-code': SourceCode, '--scp': Scp, } @property def sandboxed_current_node(self): return Sandbox(self.shell.state._node, self.shell) def complete_subhandlers(self, part): """ Return (name, Handler) subhandler pairs. """ # Default built-ins for name, h in self.subhandlers.items(): if name.startswith(part): yield name, h(self.shell) # Return when the shell supports it if self.shell.state.can_return and 'return'.startswith(part): yield 'return', Return(self.shell) # Extensions for name, h in self.shell.extensions.items(): if name.startswith(part): yield name, h(self.shell) # Nodes. for name, h in Node(self.shell).complete_subhandlers(part): yield name, h def get_subhandler(self, name): # Current node if name == '.': return Node(self.shell) # Default built-ins if name in self.subhandlers: return self.subhandlers[name](self.shell) if self.shell.state.can_return and name == 'return': return Return(self.shell) # Extensions if name in self.shell.extensions: return self.shell.extensions[name](self.shell) # Nodes. return Node(self.shell).get_subhandler(name) class ShellState(object): """ When we are moving to a certain position in the node tree. """ def __init__(self, subnode, return_state=None): self._return_state = return_state self._node = subnode self._prev_node = None def clone(self): s = ShellState(self._node, self._return_state) s._prev_node = self._prev_node return s def __repr__(self): return 'ShellState(node=%r)' % self._node @property def prompt(self): # Returns a list of (text,color) tuples for the prompt. result = [] for node in Inspector(self._node).get_path(path_type=PathType.NODE_ONLY): if result: result.append( ('.', None) ) name = Inspector(node).get_name() ii = Inspector(node).get_isolation_identifier() color = Inspector(node).get_group().color result.append( (name, color) ) if ii: result.append( ('[%s]' % ii, color) ) return result def cd(self, target_node): self._prev_node = self._node self._node = target_node @property def can_return(self): return bool(self._return_state) @property def return_state(self): return self._return_state @property def can_cdback(self): return bool(self._prev_node) @property def previous_node(self): return self._prev_node @property def node(self): return self._node class Shell(CLInterface): """ Deployment shell. """ def __init__(self, root_node, pty, options, logger_interface, clone_shell=None): self.root_node = root_node self.pty = pty self.options = options self.logger_interface = logger_interface if clone_shell: self.state = clone_shell.state.clone() else: self._reset_navigation() # CLI interface self.root_handler = RootHandler(self) CLInterface.__init__(self, self.pty, self.root_handler) def cd(self, cd_path): for p in cd_path: try: self.state.cd(Inspector(self.state._node).get_childnode(p)) except AttributeError: print 'Unknown path given.' return def open_scp_shell(self): self.root_handler.get_subhandler('--scp')() def run_action(self, action_name, *a, **kw): """ Run a deployment command at the current shell state. """ env = Env(self.state._node, self.pty, self.logger_interface, is_sandbox=False) return getattr(env, action_name)(*a, **kw) @property def extensions(self): # Dictionary with extensions to the root handler return { } def _reset_navigation(self): self.state = ShellState(self.root_node) def exit(self): """ Exit cmd loop. """ if self.state.can_return: self.state = self.state.return_state self.ctrl_c() else: super(Shell, self).exit() @property def prompt(self): """ Return a list of [ (text, color) ] tuples representing the prompt. """ return self.state.prompt + [ (' > ', 'cyan') ]
# Copyright 2013 IBM Corp. # # 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 mock from cinder.compute import nova from cinder import context from cinder import test from keystoneauth1 import loading as ks_loading from novaclient import exceptions as nova_exceptions from oslo_config import cfg CONF = cfg.CONF class NovaClientTestCase(test.TestCase): def setUp(self): super(NovaClientTestCase, self).setUp() # Register the Password auth plugin options, # so we can use CONF.set_override # reset() first, otherwise already registered CLI options will # prevent unregister in tearDown() # Use CONF.set_override(), because we'll unregister the opts, # no need (and not possible) to cleanup. CONF.reset() self.password_opts = \ ks_loading.get_auth_plugin_conf_options('password') CONF.register_opts(self.password_opts, group='nova') CONF.set_override('auth_url', 'http://keystonehost:5000', group='nova') CONF.set_override('username', 'adminuser', group='nova') CONF.set_override('password', 'strongpassword', group='nova') self.ctx = context.RequestContext('regularuser', 'e3f0833dc08b4cea', auth_token='token', is_admin=False) self.ctx.service_catalog = \ [{'type': 'compute', 'name': 'nova', 'endpoints': [{'publicURL': 'http://novahost:8774/v2/e3f0833dc08b4cea'}]}, {'type': 'identity', 'name': 'keystone', 'endpoints': [{'publicURL': 'http://keystonehostfromsc:5000/v3'}]}] self.override_config('auth_type', 'password', group='nova') self.override_config('cafile', 'my.ca', group='nova') def tearDown(self): super(NovaClientTestCase, self).tearDown() CONF.unregister_opts(self.password_opts, group='nova') @mock.patch('novaclient.api_versions.APIVersion') @mock.patch('novaclient.client.Client') @mock.patch('keystoneauth1.identity.Token') @mock.patch('keystoneauth1.session.Session') def test_nova_client_regular(self, p_session, p_token_plugin, p_client, p_api_version): self.override_config('token_auth_url', 'http://keystonehost:5000', group='nova') nova.novaclient(self.ctx) p_token_plugin.assert_called_once_with( auth_url='http://keystonehost:5000', token='token', project_name=None, project_domain_id=None ) p_client.assert_called_once_with( p_api_version(nova.NOVA_API_VERSION), session=p_session.return_value, region_name=None, insecure=False, endpoint_type='public', cacert='my.ca', global_request_id=self.ctx.request_id, timeout=None, extensions=nova.nova_extensions) @mock.patch('novaclient.api_versions.APIVersion') @mock.patch('novaclient.client.Client') @mock.patch('keystoneauth1.identity.Token') @mock.patch('keystoneauth1.session.Session') def test_nova_client_regular_service_catalog(self, p_session, p_token_plugin, p_client, p_api_version): nova.novaclient(self.ctx) p_token_plugin.assert_called_once_with( auth_url='http://keystonehostfromsc:5000/v3', token='token', project_name=None, project_domain_id=None ) p_client.assert_called_once_with( p_api_version(nova.NOVA_API_VERSION), session=p_session.return_value, region_name=None, insecure=False, endpoint_type='public', cacert='my.ca', global_request_id=self.ctx.request_id, timeout=None, extensions=nova.nova_extensions) @mock.patch('novaclient.api_versions.APIVersion') @mock.patch('novaclient.client.Client') @mock.patch('keystoneauth1.identity.Password') @mock.patch('keystoneauth1.session.Session') def test_nova_client_privileged_user(self, p_session, p_password_plugin, p_client, p_api_version): nova.novaclient(self.ctx, privileged_user=True) p_password_plugin.assert_called_once_with( auth_url='http://keystonehost:5000', default_domain_id=None, default_domain_name=None, domain_id=None, domain_name=None, password='strongpassword', project_domain_id=None, project_domain_name=None, project_id=None, project_name=None, trust_id=None, user_domain_id=None, user_domain_name=None, user_id=None, username='adminuser' ) p_client.assert_called_once_with( p_api_version(nova.NOVA_API_VERSION), session=p_session.return_value, region_name=None, insecure=False, endpoint_type='public', cacert='my.ca', global_request_id=self.ctx.request_id, timeout=None, extensions=nova.nova_extensions) @mock.patch('novaclient.api_versions.APIVersion') @mock.patch('novaclient.client.Client') @mock.patch('keystoneauth1.identity.Password') @mock.patch('keystoneauth1.session.Session') def test_nova_client_privileged_user_custom_auth_url(self, p_session, p_password_plugin, p_client, p_api_version): CONF.set_override('auth_url', 'http://privatekeystonehost:5000', group='nova') nova.novaclient(self.ctx, privileged_user=True) p_password_plugin.assert_called_once_with( auth_url='http://privatekeystonehost:5000', default_domain_id=None, default_domain_name=None, domain_id=None, domain_name=None, password='strongpassword', project_domain_id=None, project_domain_name=None, project_id=None, project_name=None, trust_id=None, user_domain_id=None, user_domain_name=None, user_id=None, username='adminuser' ) p_client.assert_called_once_with( p_api_version(nova.NOVA_API_VERSION), session=p_session.return_value, region_name=None, insecure=False, endpoint_type='public', cacert='my.ca', global_request_id=self.ctx.request_id, timeout=None, extensions=nova.nova_extensions) @mock.patch('novaclient.api_versions.APIVersion') @mock.patch('novaclient.client.Client') @mock.patch('keystoneauth1.identity.Password') @mock.patch('keystoneauth1.session.Session') def test_nova_client_custom_region(self, p_session, p_password_plugin, p_client, p_api_version): CONF.set_override('region_name', 'farfaraway', group='nova') nova.novaclient(self.ctx, privileged_user=True) p_password_plugin.assert_called_once_with( auth_url='http://keystonehost:5000', default_domain_id=None, default_domain_name=None, domain_id=None, domain_name=None, password='strongpassword', project_domain_id=None, project_domain_name=None, project_id=None, project_name=None, trust_id=None, user_domain_id=None, user_domain_name=None, user_id=None, username='adminuser' ) p_client.assert_called_once_with( p_api_version(nova.NOVA_API_VERSION), session=p_session.return_value, region_name='farfaraway', insecure=False, endpoint_type='public', cacert='my.ca', global_request_id=self.ctx.request_id, timeout=None, extensions=nova.nova_extensions) def test_novaclient_exceptions(self): # This is to prevent regression if exceptions are # removed from novaclient since the service catalog # code does not have thorough tests. self.assertTrue(hasattr(nova_exceptions, 'EndpointNotFound')) class FakeNovaClient(object): class ServerExternalEvents(object): def __getattr__(self, item): return None class Volumes(object): def __getattr__(self, item): return None def __init__(self): self.server_external_events = self.ServerExternalEvents() self.volumes = self.Volumes() def create_volume_snapshot(self, *args, **kwargs): pass def delete_volume_snapshot(self, *args, **kwargs): pass class NovaApiTestCase(test.TestCase): def setUp(self): super(NovaApiTestCase, self).setUp() self.api = nova.API() self.novaclient = FakeNovaClient() self.ctx = context.get_admin_context() def test_update_server_volume(self): with mock.patch.object(nova, 'novaclient') as mock_novaclient, \ mock.patch.object(self.novaclient.volumes, 'update_server_volume') as \ mock_update_server_volume: mock_novaclient.return_value = self.novaclient self.api.update_server_volume(self.ctx, 'server_id', 'attach_id', 'new_volume_id') mock_novaclient.assert_called_once_with(self.ctx, privileged_user=True) mock_update_server_volume.assert_called_once_with( 'server_id', 'attach_id', 'new_volume_id' ) def test_extend_volume(self): server_ids = ['server-id-1', 'server-id-2'] with mock.patch.object(nova, 'novaclient') as mock_novaclient, \ mock.patch.object(self.novaclient.server_external_events, 'create') as mock_create_event: mock_novaclient.return_value = self.novaclient self.api.extend_volume(self.ctx, server_ids, 'volume_id') mock_novaclient.assert_called_once_with(self.ctx, privileged_user=True, api_version='2.51') mock_create_event.assert_called_once_with([ {'name': 'volume-extended', 'server_uuid': 'server-id-1', 'tag': 'volume_id'}, {'name': 'volume-extended', 'server_uuid': 'server-id-2', 'tag': 'volume_id'}, ])
# -*- coding: UTF-8 -*- # Vehicle Type Definitions for Armoured Commander ########################################################################################## # # Copyright 2015 Gregory Adam Scott (sudasana@gmail.com) # # This file is part of Armoured Commander. # # Armoured Commander is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Armoured Commander is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Armoured Commander, in the form of a file named "gpl.txt". # If not, see <http://www.gnu.org/licenses/>. # ########################################################################################## # New Rarity Factor system, intended to work with any list of vehicle types: # (2.0 - ASL Model RF) * 100 * (portion) # 6 vs 14 # first item in the list is always a string unique to the vehicle type and sub-type # used for identifying the correct entry VEHICLE_TYPES = [ # American Tanks # M4 Sherman, Turret A ['M4 Turret A', ('vehicle_type', 'M4 Sherman'), ('sub_type', 'Turret A'), ('overhead_view', 'm4_a.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'None'), ('rarity', [6,5,3,1,1,1,1,1,1]), ('info_text', 'The M4 was one of the first Sherman variants to be approved, ' + 'distinguished from the M4A1 by its welded hull. This early turret design lacks ' + 'a loader hatch, smoke mortar, and vision cupola, features that ' + 'were later added or refitted to most models.')], # M4 Sherman, Turret B ['M4 Turret B', ('vehicle_type', 'M4 Sherman'), ('sub_type', 'Turret B'), ('overhead_view', 'm4_b.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'Oval'), ('smoke_mortar', ''), ('rarity', [14,10,7,3,3,2,1,1,1]), ('info_text', 'Based on combat experience, the M4 was enhanced with a smoke ' + "mortar starting from June 1943, and a hatch over the loader's " + 'position starting from December 1943.')], # M4 Sherman, Turret C ['M4 Turret C', ('vehicle_type', 'M4 Sherman'), ('sub_type', 'Turret C'), ('overhead_view', 'm4_c.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('rarity', [0,0,0,1,1,1,1,1,1]), ('info_text', "This represents an M4 produced with a smoke mortar and loader's " + "hatch, with the commander's hatch enhanced by a vision cupola, perhaps " + 'retrofitted in the field.')], # M4A1 Sherman, Turret A ['M4A1 Turret A', ('vehicle_type', 'M4A1 Sherman'), ('sub_type', 'Turret A'), ('overhead_view', 'm4_a1_a.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 83), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'None'), ('rarity', [7,6,5,2,1,1,1,1,1]), ('info_text', 'The M4A1 was the first variant of Sherman tank to be produced, ' + 'and is distinguished by its cast hull. This early turret design lacks ' + 'a loader hatch, smoke mortar, and vision cupola, features that ' + 'were later added or refitted to most models.')], # M4A1 Sherman, Turret B ['M4A1 Turret B', ('vehicle_type', 'M4A1 Sherman'), ('sub_type', 'Turret B'), ('overhead_view', 'm4_a1_b.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 83), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'Oval'), ('smoke_mortar', ''), ('rarity', [18,14,10,7,3,3,2,1,1]), ('info_text', 'This represents either a later M4A1 built with an oval loader ' + 'hatch, or an earlier model that had a loader hatch field-fitted.')], # M4A1 Sherman, Turret C ['M4A1 Turret C', ('vehicle_type', 'M4A1 Sherman'), ('sub_type', 'Turret C'), ('overhead_view', 'm4_a1_c.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 83), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('rarity', [0,0,0,1,1,1,1,1,1]), ('info_text', 'This is an M4A1 fitted with an oval loader hatch, a vision cupola ' + "for the commander's hatch, and a smoke mortar for the loader.")], # M4A3 Sherman, Turret A ['M4A3 Turret A', ('vehicle_type', 'M4A3 Sherman'), ('sub_type', 'Turret A'), ('overhead_view', 'm4_a3_a.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'None'), ('rarity', [2,2,2,1,1,1,1,1,1]), ('info_text', 'The M4A3 was the third variant of Sherman tank, similar to the ' + 'M4 but powered by a Ford V-8 engine. This early turret design lacks ' + 'a loader hatch, smoke mortar, and vision cupola, features that ' + 'were later added or refitted to most models.')], # M4A3 Sherman, Turret B ['M4A3 Turret B', ('vehicle_type', 'M4A3 Sherman'), ('sub_type', 'Turret B'), ('overhead_view', 'm4_a3_b.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'Oval'), ('smoke_mortar', ''), ('rarity', [2,2,3,2,2,2,3,2,1]), ('info_text', 'This represents an M4A3 with an oval loader hatch and a smoke ' + 'mortar.')], # M4A3 Sherman, Turret C ['M4A3 Turret C', ('vehicle_type', 'M4A3 Sherman'), ('sub_type', 'Turret C'), ('overhead_view', 'm4_a3_c.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('rarity', [0,0,0,1,1,1,1,1,1]), ('info_text', 'This represents an M4A3 fitted with an oval loader hatch, a ' + "commander's vision cupola, and a smoke mortar.")], # M4A3(75)W Sherman, Turret D ['M4A3(75)W Turret D', ('vehicle_type', 'M4A3(75)W Sherman'), ('sub_type', 'Turret D'), ('overhead_view', 'm4_a3_75_d.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 100), ('rr_size', 4), ('rof_num', 5), ('loader_hatch', 'Oval'), ('smoke_mortar', ''), ('wet_stowage', ''), ('rarity', [20,18,19,21,19,16,12,10,6]), ('info_text', 'The M4A3(75) W was a later modification of the M4A3 design, ' + 'with a thicker, single-piece front hull armour sheet. W indicates ' + 'wet stowage, meaning that ammunition is stored surrounded by liquid ' + 'to prevent fires. This turret design has an oval loader hatch and ' + 'a smoke mortar.')], # M4A3(75)W Sherman, Turret E ['M4A3(75)W Turret E', ('vehicle_type', 'M4A3(75)W Sherman'), ('sub_type', 'Turret E'), ('overhead_view', 'm4_a3_75_e.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 100), ('rr_size', 4), ('rof_num', 5), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('wet_stowage', ''), ('HVSS', 3), ('rarity', [0,1,5,9,13,16,19,24,28]), ('info_text', "This is an M4A3(75) W with a commander's vision cupola and " + 'possible Horizontal Volute Spring Suspension.')], # M4A3E2(75)W Sherman, Turret F ['M4A3E2(75)W Turret F', ('vehicle_type', 'M4A3E2(75)W Sherman'), ('sub_type', 'Turret F'), ('overhead_view', 'm4_a3_e2_75_f.xp'), ('vehicle_class', 'Medium Tank'), ('nickname', 'Jumbo'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 18), ('hull_side_armour', 8), ('turret_front_armour', 18), ('turret_side_armour', 11), ('main_gun_rounds', 100), ('rr_size', 4), ('rof_num', 5), ('loader_hatch', 'Oval'), ('smoke_mortar', ''), ('vision_cupola', ''), ('wet_stowage', ''), ('duckbills', ''), ('rarity', [0,5,5,5,5,5,5,5,5]), ('info_text', 'The "Jumbo" was an attempt to build an assault tank that could ' + 'stand up to heavy German anti-tank weapons. Extra armour plating was ' + 'welded on to an M4A3, at the expense of speed. The "Jumbo" was also ' + 'fitted with extended "Duckbill" tracks, which sacrificed speed for ' + 'traction and reliability.')], # M4A3E2(76)W Sherman, Turret F ['M4A3E2(76)W Turret F', ('vehicle_type', 'M4A3E2(76)W Sherman'), ('sub_type', 'Turret F'), ('overhead_view', 'm4_a3_e2_76_f.xp'), ('vehicle_class', 'Medium Tank'), ('nickname', 'Jumbo'), ('target_size', 'Large'), ('main_gun', '76L'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 18), ('hull_side_armour', 8), ('turret_front_armour', 18), ('turret_side_armour', 11), ('main_gun_rounds', 65), ('rr_size', 6), ('rof_num', 4), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('wet_stowage', ''), ('duckbills', ''), ('rarity', [0,0,1,1,1,1,1,1,1]), ('info_text', 'A few "Jumbo" Shermans were fitted with a 76mm gun, but these were ' + 'exceedingly rare.')], # M4A1(76)W Sherman, Turret G ['M4A1(76)W Turret G', ('vehicle_type', 'M4A1(76)W Sherman'), ('sub_type', 'Turret G'), ('overhead_view', 'm4_a1_76_g.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '76L'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 65), ('rr_size', 6), ('rof_num', 4), ('loader_hatch', 'Split'), ('loader_aa_mg', ''), ('vision_cupola', ''), ('smoke_mortar', ''), ('wet_stowage', ''), ('HVSS', 5), ('rarity', [10,10,15,14,12,10,9,7,5]), ('info_text', 'This represents an M4A1 upgraded with a 76mm gun. Because the ' + 'loader hatch is a split type, the loader cannot fire the AA MG.')], # M4A1(76)W Sherman, Turret H ['M4A1(76)W Turret H', ('vehicle_type', 'M4A1(76)W Sherman'), ('sub_type', 'Turret H'), ('overhead_view', 'm4_a1_76_h.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '76L'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 65), ('rr_size', 6), ('rof_num', 4), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('wet_stowage', ''), ('HVSS', 5), ('rarity', [0,0,0,1,3,5,6,7,9]), ('info_text', 'This represents an M4A1 upgraded with a 76mm gun, and fitted with ' + 'an oval loader hatch.')], # M4A3(76)W Sherman, Turret G ['M4A3(76)W Turret G', ('vehicle_type', 'M4A3(76)W Sherman'), ('sub_type', 'Turret G'), ('overhead_view', 'm4_a3_76_g.xp'), ('vehicle_class', 'Medium Tank'), ('nickname', 'Easy Eight'), ('target_size', 'Large'), ('main_gun', '76L'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 65), ('rr_size', 6), ('rof_num', 4), ('loader_hatch', 'Split'), ('loader_aa_mg', ''), ('vision_cupola', ''), ('smoke_mortar', ''), ('wet_stowage', ''), ('HVSS', 5), ('rarity', [20,25,25,25,26,23,21,18,15]), ('info_text', 'The "Easy Eight" is an M4A3 upgraded with a 76mm gun and often ' + 'has Horizontal Volute Spring Suspension has well. The combination of ' + 'speed, firepower, and reliability made this one of the most effective ' + 'models of Sherman tank in the war.')], # M4A3(76)W Sherman, Turret H ['M4A3(76)W Turret H', ('vehicle_type', 'M4A3(76)W Sherman'), ('sub_type', 'Turret H'), ('overhead_view', 'm4_a3_76_h.xp'), ('vehicle_class', 'Medium Tank'), ('nickname', 'Easy Eight'), ('target_size', 'Large'), ('main_gun', '76L'), ('co_ax_mg', 4), ('bow_mg', 2), ('aa_mg', 4), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 65), ('rr_size', 6), ('rof_num', 4), ('loader_hatch', 'Oval'), ('vision_cupola', ''), ('smoke_mortar', ''), ('wet_stowage', ''), ('HVSS', 5), ('rarity', [0,0,0,3,6,10,14,18,21]), ('info_text', 'An "Easy Eight" with an oval loader hatch.')], # British and Commonwealth Tanks # Sherman II (M4A1) ['Sherman II', ('vehicle_type', 'Sherman II'), ('overhead_view', 'm4_a1_a.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('hull_front_armour', 11), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 83), ('rr_size', 8), ('rof_num', 5), ('smoke_mortar', ''), ('loader_hatch', 'None'), ('rarity', [2,2,2,2,2,2,2,2,2]), ('info_text', 'The Sherman II was the British and Commonwealth designation for ' + 'the M4A1. This version has a smoke mortar but no loader hatch.')], # Sherman V (M4A4) ['Sherman V', ('vehicle_type', 'Sherman V'), ('overhead_view', 'm4_a3_a.xp'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '75'), ('co_ax_mg', 4), ('bow_mg', 2), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 89), ('rr_size', 8), ('rof_num', 5), ('smoke_mortar', ''), ('loader_hatch', 'None'), ('rarity', [2,2,2,2,2,2,2,2,2]), ('info_text', 'The Sherman V was the British and Commonwealth designation for ' + 'the M4A4.')], # Firefly (M4A4) ['Sherman VC Firefly', ('vehicle_type', 'Sherman VC'), ('overhead_view', 'm4_vc.xp'), ('sub_type', 'Firefly'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Large'), ('main_gun', '76LL'), ('co_ax_mg', 4), ('hull_front_armour', 8), ('hull_side_armour', 4), ('turret_front_armour', 8), ('turret_side_armour', 6), ('main_gun_rounds', 73), ('rr_size', 5), ('rof_num', 3), ('smoke_mortar', ''), ('no_asst_driver', ''), ('loader_hatch', 'Oval'), ('rarity', [1,1,1,1,1,2,2,2,2]), ('info_text', 'The Sherman VC (Firefly) was a Sherman V fitted with a 17-pounder ' + 'main gun, intended to defeat German heavy armour. To leave room to store ' + 'the larger main gun ammunition, the assistant driver position and the ' + 'bow MG were both removed. Unlike the standard Sherman V it does have a ' + 'loader hatch in the turret.')], # German Tanks # PzKw IV H (or J) ['PzKw IV H', ('vehicle_type', 'PzKw IV'), ('sub_type', 'H'), ('vehicle_class', 'Medium Tank'), ('target_size', 'Medium'), ('main_gun', '75L'), ('hull_front_armour', 8), ('hull_side_armour', 3), ('turret_front_armour', 6), ('turret_side_armour', 4), ('turret_traverse', 'Fast'), ('info_text', 'Panzer IV Tank. A medium tank armed with a 75L main gun. Roughly ' + 'equivalent to an M4 Sherman but with a better long range attack and ' + 'lighter side and turret armour.')], # PzKw V G, Panther ['PzKw V G', ('vehicle_type', 'PzKw V'), ('sub_type', 'G'), ('vehicle_class', 'Heavy Tank'), ('nickname', 'Panther'), ('target_size', 'Large'), ('main_gun', '75LL'), ('hull_front_armour', 18), ('hull_side_armour', 6), ('turret_front_armour', 14), ('turret_side_armour', 6), ('turret_traverse', 'Restricted Slow'), ('info_text', 'Panzer V "Panther". A medium tank armoured with a 75LL gun, ' + 'excellent at longer ranges. Very heavy front hull armour.')], # PzKw VI E, Tiger ['PzKw VI E', ('vehicle_type', 'PzKw VI'), ('sub_type', 'E'), ('vehicle_class', 'Heavy Tank'), ('nickname', 'Tiger'), ('target_size', 'Large'), ('main_gun', '88L'), ('hull_front_armour', 11), ('hull_side_armour', 8), ('turret_front_armour', 14), ('turret_side_armour', 8), ('turret_traverse', 'Restricted Slow'), ('info_text', 'Panzer VIe "Tiger I". A heavy tank mounting an 88L gun. Very ' + 'heavily armoured.')], # PzKw VI B, King Tiger ['PzKw VI B', ('vehicle_type', 'PzKw VI'), ('sub_type', 'B'), ('vehicle_class', 'Heavy Tank'), ('nickname', 'King Tiger'), ('target_size', 'Very Large'), ('main_gun', '88LL'), ('hull_front_armour', 26), ('hull_side_armour', 8), ('turret_front_armour', 18), ('turret_side_armour', 11), ('turret_traverse', 'Restricted Slow'), ('unreliable', ''), # no effect yet ('info_text', 'Panzer VIb "Tiger II". A heavy tank known as the "King Tiger" to ' + 'allied forces. Armed with an 88LL gun with excellent long-range power ' + 'and accuracy.')], # SPGs # STuG III G ['STuG III G', ('vehicle_type', 'STuG III'), ('sub_type', 'G'), ('vehicle_class', 'Self-Propelled Gun'), ('target_size', 'Small'), ('main_gun', '75L'), ('hull_front_armour', 8), ('hull_side_armour', 3), ('turret_front_armour', 8), ('turret_side_armour', 3), ('turret_traverse', 'None'), ('info_text', 'Sturmgeschutz III Assault Gun. Built on a Panzer III chassis, ' + 'initially intended as an infantry support gun but later used as a tank ' + 'destroyer. Mounts the same 75L gun as a Panzer IV. The main gun is ' + 'hull-mounted, so it must rotate to change its facing.')], # Marder II ['Marder II', ('vehicle_type', 'Marder II'), ('vehicle_class', 'Self-Propelled Gun'), ('target_size', 'Normal'), ('main_gun', '75L'), ('hull_front_armour', 3), ('hull_side_armour', 1), ('turret_front_armour', 2), ('turret_side_armour', 0), ('turret_traverse', 'None'), ('info_text', 'Marder II Tank Destroyer. Built on a Panzer II chassis, designed ' + 'to overcome heavy tanks on the Eastern Front. Mounts the same 75L gun ' + 'as a Panzer IV. Very light armour, largely obsolete by late 1944.')], # Marder III H ['Marder III H', ('vehicle_type', 'Marder III'), ('sub_type', 'H'), ('vehicle_class', 'Self-Propelled Gun'), ('target_size', 'Normal'), ('main_gun', '75L'), ('hull_front_armour', 4), ('hull_side_armour', 1), ('turret_front_armour', 3), ('turret_side_armour', 1), ('turret_traverse', 'None'), ('info_text', 'Marder III Tank Destroyer. Built on a Panzer 38(t) chassis. ' + 'Mounts the same 75L gun as a Panzer IV. Very light armour all around.')], # JgdPz IV ['JgdPzKw IV', ('vehicle_type', 'JgdPzKw IV'), ('vehicle_class', 'Self-Propelled Gun'), ('target_size', 'Small'), ('main_gun', '75L'), ('hull_front_armour', 14), ('hull_side_armour', 3), ('turret_front_armour', 14), ('turret_side_armour', 4), ('turret_traverse', 'None'), ('info_text', 'Jagdpanzer IV Tank Destroyer. Built on a Panzer IV chassis. ' + 'Mounts the same 75L gun as a Panzer IV. Very heavy front armour.')], # JgdPz 38(t) ['JgdPz 38(t)', ('vehicle_type', 'JgdPz 38(t)'), ('vehicle_class', 'Self-Propelled Gun'), ('target_size', 'Small'), ('main_gun', '75L'), ('hull_front_armour', 14), ('hull_side_armour', 3), ('turret_front_armour', 14), ('turret_side_armour', 3), ('turret_traverse', 'None'), ('info_text', 'Jagdpanzer 38 "Hetzer" Light Tank Destroyer. Built on a modified ' + 'Panzer 38(t) chassis, with a hull-mounted 75L gun. Very heavy front ' + 'armour, but side and rear armour are both very light.')], # Other German Vehicles # SPW 251 ['SPW 251', ('vehicle_type', 'SPW'), ('vehicle_class', 'Transport'), ('sub_type', '251'), ('target_size', 'Small'), ('main_gun', 'MG'), ('hull_front_armour', 1), ('hull_side_armour', 1), ('turret_front_armour', 1), ('turret_side_armour', 1), ('turret_traverse', 'None'), ('info_text', 'Schutzenpanzerwagen Armoured Personnel Carrier. Armed with ' + 'machine guns, it can attack and destroy friendly infantry. No threat ' + 'to your tank, unless it attacks you and a crew member has an open hatch.')], # PSW 232 ['PSW 232', ('vehicle_type', 'PSW'), ('sub_type', '232'), ('vehicle_class', 'Armoured Car'), ('target_size', 'Normal'), ('main_gun', '20L'), ('hull_front_armour', 3), ('hull_side_armour', 1), ('turret_front_armour', 3), ('turret_side_armour', 1), ('turret_traverse', 'Restricted Slow'), ('info_text', 'Schwerer Panzerspahwagen Armoured Reconnaissance Vehicle. Armed ' + 'with a light gun, can destroy friendly infantry teams and can wound any ' + 'crewmember with an open hatch. They are able to spot your tank and report ' + 'your position to other enemy units, improving their chance of hitting you.')], # Opel Truck ['Opel', ('vehicle_type', 'Truck'), ('vehicle_class', 'Transport'), ('target_size', 'Normal'), ('turret_traverse', 'None'), ('info_text', 'An Opel Blitz 3-ton Truck, used to transport infantry and war ' + 'materials. Cannot attack, but worth some VP if destroyed. HE is more ' + 'effective than AP, which may just punch through the vehicle without ' + 'doing any real damage.')] ]
#!/usr/bin/env python import os import sys import json import argparse import numpy as np import matplotlib import multiprocessing import logging matplotlib.use('agg') import matplotlib.pyplot as plt from pychemia.code.abinit import AbinitInput, AbinitOutput from pychemia.population.orbitaldftu import dmatpawu2params, params2dmatpawu, OrbitalDFTU from pychemia.population.orbitaldftu import get_final_abinit_out from pychemia.searcher import FireFly from pychemia.db import get_database def compare_params(path): if not os.path.isfile(path + os.sep + 'abinit.in'): print('ERROR: No abinit.in found at %s' % path) return # For making easier to see the values np.set_printoptions(linewidth=200, suppress=True) # Reading the INPUT abi = AbinitInput(path + os.sep + 'abinit.in') if 'lpawu' not in abi.variables: raise ValueError("Variable lpawu not found") ndim = 2 * max(abi['lpawu']) + 1 idmatpawu = np.array(abi['dmatpawu']).reshape(-1, ndim, ndim) iparams = dmatpawu2params(idmatpawu, ndim) # Reading the OUTPUT abinitout = get_final_abinit_out(path) abo = AbinitOutput(abinitout) dmatpawu = abo.get_final_dmatpawu() odmatpawu = np.array(dmatpawu).reshape(-1, ndim, ndim) oparams = dmatpawu2params(odmatpawu, ndim) print('DMATPAWU') print('input') print(idmatpawu) print('output') print(odmatpawu) print('PARAMETRIC REPRESENTATION found at %s' % abinitout) for i in sorted(list(iparams.keys())): print(i) print('input') print(iparams[i]) print('output') print(i) print(oparams[i]) abo = AbinitOutput(abinitout) if not abo.is_finished: print('This output is not finished') try: nres2 = abo.get_energetics()['nres2'][-1] etot = abo.get_energetics()['etot'][-1] nscf = len(abo.get_energetics()['etot']) print("%30s ETOT: %15.6f NRES2: %15.6e NumSCF: %3d" % (path, etot, nres2, nscf)) except: print("ERROR: Could not get energetics from %s" % abinitout) def check_status(basepath): dirs = [x for x in os.listdir(basepath) if os.path.isdir(basepath + os.sep + x) and os.path.isfile(basepath + os.sep + x + os.sep + 'abinit.in')] print("%-40s %15s %15s %4s" % ("ABINIT output", "ETOT", 'nres2', 'nSCF')) for i in dirs: path = basepath + os.sep + i abinitout = get_final_abinit_out(path) if abinitout is None: continue abo = AbinitOutput(abinitout) if not abo.is_finished: continue try: nres2 = abo.get_energetics()['nres2'][-1] etot = abo.get_energetics()['etot'][-1] nscf = len(abo.get_energetics()['etot']) print("%-40s %15.6f %15.6e %4d" % (abinitout, etot, nres2, nscf)) except: print("ERROR: Could not get final energetics from %s" % abinitout) def plot_polar(popu, basepath): print('Plotting Euler Angles...') dirs = [x for x in os.listdir(basepath) if os.path.isdir(basepath + os.sep + x) and os.path.isfile(basepath + os.sep + x + os.sep + 'abinit.in')] fig = plt.figure(figsize=(21, 1.2 * len(dirs))) plt.subplots_adjust(left=0.0, bottom=0.0, right=0.99, top=0.99, wspace=None, hspace=None) etots = [] for idir in dirs: pm, etot = popu.get_final_properties(basepath + os.sep + idir) etots.append(etot) etots = np.array(etots) sort_dirs = np.array(dirs)[etots.argsort()] index = 0.0 for idir in sort_dirs: pm, etot = popu.get_final_properties(basepath + os.sep + idir) ea = np.array(pm['final_dmat']['euler_angles']) # print(idir,etot) # print(ea.shape) nangles = ea.shape[1] for j in range(nangles): theta = ea[:, j] dim = len(theta) radii = np.ones(dim) colors = np.arange(dim) width = 0.1 * np.ones(dim) ax = fig.add_axes([float(j) / nangles, index / (len(dirs) + 1), 1.0 / nangles, 1.0 / nangles], projection='polar') ax.yaxis.set_tick_params(labelsize=0) ax.xaxis.set_tick_params(labelsize=0) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.spines['polar'].set_visible(True) bars = ax.bar(theta, radii, width=width, bottom=0.0) # Use custom colors and opacity for r, bar in zip(colors, bars): bar.set_facecolor(plt.cm.viridis(float(r) / nangles)) bar.set_alpha(0.9) index += 1.0 plt.savefig('OrbitalPolar.pdf') plt.show() def plot_status(basepath): dirs = [x for x in os.listdir(basepath) if os.path.isdir(basepath + os.sep + x) and os.path.isfile(basepath + os.sep + x + os.sep + 'abinit.in')] abi = AbinitInput(basepath + os.sep + 'abinit.in') nstep = abi['nstep'] print('Plotting Status...') xx = {} yy = {} # Get the data: max_nruns = 0 for path in dirs: xx[path] = np.array([]) yy[path] = {} yy[path]['nres2'] = np.array([]) yy[path]['etot'] = np.array([]) yy[path]['delta'] = np.array([]) for i in range(100): if os.path.isfile(basepath + os.sep + path + os.sep + 'abinit_%02d.txt' % i): abo = AbinitOutput(basepath + os.sep + path + os.sep + 'abinit_%02d.txt' % i) if not abo.is_finished: print('This output is not finished') continue if max_nruns < i: max_nruns = i try: energ = abo.get_energetics() except: raise RuntimeError( "Failed procesing: %s" % (basepath + os.sep + path + os.sep + 'abinit_%02d.txt' % i)) nres2 = energ['nres2'][-1] etot = energ['etot'][-1] nscf = len(energ['etot']) x = np.arange(nstep * i, nstep * i + len(energ['nres2'])) yetot = np.array(energ['etot']) ynres2 = np.array(energ['nres2']) ydelta = np.array(np.abs(energ['deltaEh'])) xx[path] = np.concatenate((xx[path], x)) yy[path]['etot'] = np.concatenate((yy[path]['etot'], yetot)) yy[path]['nres2'] = np.concatenate((yy[path]['nres2'], ynres2)) yy[path]['delta'] = np.concatenate((yy[path]['delta'], ydelta)) print("%s ETOT:%15.6f NRES2=%15.6e Num SCF=%3d" % (path, etot, nres2, nscf)) # RESIDUAL plt.figure(figsize=(8, 11)) miny = 1E-1 maxy = 1E-16 plt.subplots_adjust(left=0.1, bottom=0.05, right=0.99, top=0.99, wspace=None, hspace=None) for path in dirs: if len(xx) > 0: plt.semilogy(xx[path], yy[path]['nres2'], label=path[-4:], lw=0.1) if miny > min(yy[path]['nres2']): miny = min(yy[path]['nres2']) if maxy < max(yy[path]['nres2']): maxy = max(yy[path]['nres2']) plt.ylim(miny, maxy) for i in nstep * np.arange(max_nruns + 1): plt.semilogy([i, i], [miny, maxy], '0.5', lw=0.1) plt.xlim(0, max([max(xx[path]) for path in dirs])) plt.legend() plt.xlabel("SCF iteration") plt.ylabel("Density Residual$^2$") plt.savefig('Orbital_Residual.pdf') # ETOT miny = 1E6 maxy = -1E6 avg = 0 minlen = 100 plt.figure(figsize=(8, 11)) for path in dirs: if len(xx) > 0: plt.plot(xx[path], yy[path]['etot'], label=path[-4:]) if len(yy[path]['etot']) < minlen: minlen = len(yy[path]['etot']) avg = np.average(yy[path]['etot'][-int(minlen / 2):]) if miny > min(yy[path]['etot'][-int(minlen / 2):]): miny = min(yy[path]['etot'][-int(minlen / 2):]) if maxy < max(yy[path]['etot'][-int(minlen / 2):]): maxy = max(yy[path]['etot'][-int(minlen / 2):]) plt.subplots_adjust(left=0.15, bottom=0.05, right=0.95, top=0.95, wspace=None, hspace=None) newminy = miny - 0.1 * (maxy - miny) newmaxy = maxy + 0.1 * (maxy - miny) miny = newminy maxy = newmaxy plt.ylim(miny, maxy) for i in nstep * np.arange(max_nruns + 1): plt.plot([i, i], [miny, maxy], '0.5', lw=0.1) plt.xlim(0, max([max(xx[path]) for path in dirs])) plt.legend() plt.xlabel("SCF iteration") plt.ylabel("Energy") plt.savefig('Orbital_ETotal.pdf') # deltaEh plt.figure(figsize=(8, 11)) miny = 1E-1 for path in dirs: if len(xx) > 0: plt.semilogy(xx[path], yy[path]['delta'], label=path[-4:], lw=0.1) if miny > min(yy[path]['delta']): miny = min(yy[path]['delta']) plt.subplots_adjust(left=0.1, bottom=0.05, right=0.99, top=0.99, wspace=None, hspace=None) for i in nstep * np.arange(max_nruns + 1): plt.semilogy([i, i], [miny, 1E3], '0.5', lw=0.1) plt.ylim(miny, 1E3) plt.xlim(0, max([max(xx[path]) for path in dirs])) plt.legend() plt.xlabel("SCF iteration") plt.ylabel("Delta Energy") plt.savefig('Orbital_deltaEh.pdf') def create_population(num_candidates): popu.random_population(num_candidates) def safe_read_json(filename): """ Safely read a given filename, extract and returns the associated dictionary from the JSON file """ if not os.path.exists(filename): raise ValueError("ERROR: Could not read file: %s" % filename) rf = open(filename) try: data = json.load(rf) except ValueError: raise ValueError("ERROR: File is not in proper JSON format: %s" % filename) rf.close() return data def prepare_folders(scrpath): for i in popu.members: popu.prepare_folder(i, workdir=scrpath, source_dir=scrpath) def set_populations(parser): return parser.add_argument('-p', type=str, nargs='+', required=True, metavar='JSON_file', help='Population settings (JSON file), includes settings to connect to server and the ' 'population') def evaluate(db_settings, queue_settings, abipath): pcdb = get_database(db_settings) print("[%s] Path for abinit.in: %s" % (pcdb.name, abipath)) popu = OrbitalDFTU(pcdb, abipath + os.sep + 'abinit.in') popu.evaluator(queue_settings, abipath) def search(db_settings, search_settings, abipath): pcdb = get_database(db_settings) print("[%s] Path for abinit.in: %s" % (pcdb.name, abipath)) popu = OrbitalDFTU(pcdb, abipath + os.sep + 'abinit.in') if 'generation_size' in search_settings: generation_size = search_settings.pop('generation_size') else: generation_size = 32 if 'stabilization_limit' in search_settings: stabilization_limit = search_settings.pop('stabilization_limit') else: stabilization_limit = 10 fire = FireFly(popu, params=search_settings, generation_size=generation_size, stabilization_limit=stabilization_limit) fire.run() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Orbital DFTU Evaluator and Analysis Tool') subparsers = parser.add_subparsers(help='commands', dest='subparser_name') # The create command create_parser = subparsers.add_parser('create', help='Create the database') set_populations(create_parser) # The populate command populate_parser = subparsers.add_parser('populate', help='Add candidates to the population (used for testing)') set_populations(populate_parser) populate_parser.add_argument('-clean', action='store_true', help='If true, clean the entire database before populate', required=False, default=False) populate_parser.add_argument('-size', type=int, help='Number of candidates to populate (default: 16)', required=False, default=16) populate_parser.add_argument('-basepath', type=str, help='Path where calculations are performed', required=False, default='.') # A run command run_parser = subparsers.add_parser('run', help='Run Evaluator') set_populations(run_parser) run_parser.add_argument('-queue_settings', type=str, help='Filename with PBS settings for launching jobs', required=False, default='queue.json') run_parser.add_argument('-basepath', type=str, help='Path where calculations are performed (default: current folder)', required=False, default='.') # A searcher command searcher_parser = subparsers.add_parser('search', help='Run PyChemia Global Searcher') set_populations(searcher_parser) searcher_parser.add_argument('-search_settings', type=str, help='Filename with PBS settings for launching jobs', required=False, default='searcher.json') searcher_parser.add_argument('-basepath', type=str, help='Path where calculations are performed (default: current folder)', required=False, default='.') # The plot command plot_parser = subparsers.add_parser('plot', help='Generate several plots') set_populations(plot_parser) plot_parser.add_argument('-basepath', type=str, help='Path where calculations are performed', required=False, default='.') args = parser.parse_args() print(args) # check all settings in args.p dbs = [] for dbi_file in args.p: dbi = safe_read_json(dbi_file) print("DB settings: %s" % dbi) assert('name' in dbi) assert('u' in dbi) assert('j' in dbi) dbs.append(dbi) if args.subparser_name == 'create': pcdbs = [] for dbi in dbs: pcdb = get_database(dbi) pcdbs.append(pcdb) print(pcdb) print(pcdb.entries.count()) if args.subparser_name == 'run': queue_settings = safe_read_json(args.queue_settings) print("PBS settings: %s" % queue_settings) # General actions for 'populate', 'run', 'search' and 'plot' if args.subparser_name in ['run', 'plot', 'populate', 'search']: if not os.path.isdir(args.basepath) or not os.path.isfile(args.basepath + os.sep + 'abinit.in'): print('ERROR: Wrong basepath %s, directory must exist and contain a abinit.in file' % args.basepath) parser.print_help() sys.exit(1) popu = {} for dbi in dbs: name = dbi['name'] pcdb = get_database(dbi) if not os.path.isdir(args.basepath + os.sep + name): os.mkdir(args.basepath + os.sep + name) abi = AbinitInput(args.basepath + os.sep + 'abinit.in') abi['upawu'] = "" for i in dbi['u']: abi['upawu'] += str(i) + " " abi['upawu'] += 'eV' abi['jpawu'] = "" for i in dbi['j']: abi['jpawu'] += str(i) + " " abi['jpawu'] += 'eV' abipath = args.basepath + os.sep + name + os.sep + 'abinit.in' abi.write(abipath) abifiles = args.basepath + os.sep + name + os.sep + 'abinit.files' if os.path.lexists(abifiles): os.remove(abifiles) os.symlink(os.path.abspath(args.basepath + os.sep + 'abinit.files'), abifiles) for i in [x for x in os.listdir(args.basepath) if x[-3:] == 'xml']: psp = args.basepath + os.sep + name + os.sep + i if os.path.lexists(psp): os.remove(psp) os.symlink(os.path.abspath(args.basepath + os.sep + i), psp) popu[name] = OrbitalDFTU(pcdb, abipath) # Specific actions for 'populate', 'run', 'search' and 'plot' if args.subparser_name == 'populate': for dbi in dbs: name = dbi['name'] if args.clean: popu[name].clean() popu[name].random_population(args.size) print("[%s] Total number of candidates: %d" % (name, len(popu[name]))) elif args.subparser_name == 'run': sprocs = {} for dbi in dbs: name = dbi['name'] basepath = args.basepath + os.sep + name if os.path.exists(basepath + os.sep + 'ERROR'): print('ERROR: Something was wrong with %s' % abipath) else: sprocs[name] = multiprocessing.Process(target=evaluate, args=(dbi, queue_settings, basepath)) sprocs[name].start() for dbi in dbs: name = dbi['name'] sprocs[name].join() elif args.subparser_name == 'search': logging.basicConfig(level=logging.DEBUG) search_settings = safe_read_json(args.search_settings) print("Search settings from file: %s \n%s" % (args.search_settings, search_settings)) sprocs = {} for dbi in dbs: name = dbi['name'] basepath = args.basepath + os.sep + name sprocs[name] = multiprocessing.Process(target=search, args=(dbi, search_settings, basepath)) sprocs[name].start() print(list(sprocs.keys())) for dbi in dbs: name = dbi['name'] if name not in sprocs: print('ERRROR: %s' % str(sprocs)) sprocs[name].join() elif args.subparser_name == 'plot': check_status(args.basepath) plot_status(args.basepath) plot_polar(popu, args.basepath)
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/ # # 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR 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 boto.exception import SDBPersistenceError from boto.sdb.persist.checker import * from boto.utils import Password class Property(object): def __init__(self, checker_class, **params): self.name = '' self.checker = checker_class(**params) self.slot_name = '__' def set_name(self, name): self.name = name self.slot_name = '__' + self.name class ScalarProperty(Property): def save(self, obj): domain = obj._manager.domain domain.put_attributes(obj.id, {self.name : self.to_string(obj)}, replace=True) def to_string(self, obj): return self.checker.to_string(getattr(obj, self.name)) def load(self, obj): domain = obj._manager.domain a = domain.get_attributes(obj.id, self.name) # try to get the attribute value from SDB if self.name in a: value = self.checker.from_string(a[self.name], obj) setattr(obj, self.slot_name, value) # if it's not there, set the value to the default value else: self.__set__(obj, self.checker.default) def __get__(self, obj, objtype): if obj: try: value = getattr(obj, self.slot_name) except AttributeError: if obj._auto_update: self.load(obj) value = getattr(obj, self.slot_name) else: value = self.checker.default setattr(obj, self.slot_name, self.checker.default) return value def __set__(self, obj, value): self.checker.check(value) try: old_value = getattr(obj, self.slot_name) except: old_value = self.checker.default setattr(obj, self.slot_name, value) if obj._auto_update: try: self.save(obj) except: setattr(obj, self.slot_name, old_value) raise class StringProperty(ScalarProperty): def __init__(self, **params): ScalarProperty.__init__(self, StringChecker, **params) class PasswordProperty(ScalarProperty): """ Hashed password """ def __init__(self, **params): ScalarProperty.__init__(self, PasswordChecker, **params) def __set__(self, obj, value): p = Password() p.set(value) ScalarProperty.__set__(self, obj, p) def __get__(self, obj, objtype): return Password(ScalarProperty.__get__(self, obj, objtype)) class SmallPositiveIntegerProperty(ScalarProperty): def __init__(self, **params): params['size'] = 'small' params['signed'] = False ScalarProperty.__init__(self, IntegerChecker, **params) class SmallIntegerProperty(ScalarProperty): def __init__(self, **params): params['size'] = 'small' params['signed'] = True ScalarProperty.__init__(self, IntegerChecker, **params) class PositiveIntegerProperty(ScalarProperty): def __init__(self, **params): params['size'] = 'medium' params['signed'] = False ScalarProperty.__init__(self, IntegerChecker, **params) class IntegerProperty(ScalarProperty): def __init__(self, **params): params['size'] = 'medium' params['signed'] = True ScalarProperty.__init__(self, IntegerChecker, **params) class LargePositiveIntegerProperty(ScalarProperty): def __init__(self, **params): params['size'] = 'large' params['signed'] = False ScalarProperty.__init__(self, IntegerChecker, **params) class LargeIntegerProperty(ScalarProperty): def __init__(self, **params): params['size'] = 'large' params['signed'] = True ScalarProperty.__init__(self, IntegerChecker, **params) class BooleanProperty(ScalarProperty): def __init__(self, **params): ScalarProperty.__init__(self, BooleanChecker, **params) class DateTimeProperty(ScalarProperty): def __init__(self, **params): ScalarProperty.__init__(self, DateTimeChecker, **params) class ObjectProperty(ScalarProperty): def __init__(self, **params): ScalarProperty.__init__(self, ObjectChecker, **params) class S3KeyProperty(ScalarProperty): def __init__(self, **params): ScalarProperty.__init__(self, S3KeyChecker, **params) def __set__(self, obj, value): self.checker.check(value) try: old_value = getattr(obj, self.slot_name) except: old_value = self.checker.default if isinstance(value, str): value = self.checker.from_string(value, obj) setattr(obj, self.slot_name, value) if obj._auto_update: try: self.save(obj) except: setattr(obj, self.slot_name, old_value) raise class S3BucketProperty(ScalarProperty): def __init__(self, **params): ScalarProperty.__init__(self, S3BucketChecker, **params) def __set__(self, obj, value): self.checker.check(value) try: old_value = getattr(obj, self.slot_name) except: old_value = self.checker.default if isinstance(value, str): value = self.checker.from_string(value, obj) setattr(obj, self.slot_name, value) if obj._auto_update: try: self.save(obj) except: setattr(obj, self.slot_name, old_value) raise class MultiValueProperty(Property): def __init__(self, checker_class, **params): Property.__init__(self, checker_class, **params) def __get__(self, obj, objtype): if obj: try: value = getattr(obj, self.slot_name) except AttributeError: if obj._auto_update: self.load(obj) value = getattr(obj, self.slot_name) else: value = MultiValue(self, obj, []) setattr(obj, self.slot_name, value) return value def load(self, obj): if obj != None: _list = [] domain = obj._manager.domain a = domain.get_attributes(obj.id, self.name) if self.name in a: lst = a[self.name] if not isinstance(lst, list): lst = [lst] for value in lst: value = self.checker.from_string(value, obj) _list.append(value) setattr(obj, self.slot_name, MultiValue(self, obj, _list)) def __set__(self, obj, value): if not isinstance(value, list): raise SDBPersistenceError('Value must be a list') setattr(obj, self.slot_name, MultiValue(self, obj, value)) str_list = self.to_string(obj) domain = obj._manager.domain if obj._auto_update: if len(str_list) == 1: domain.put_attributes(obj.id, {self.name : str_list[0]}, replace=True) else: try: self.__delete__(obj) except: pass domain.put_attributes(obj.id, {self.name : str_list}, replace=True) setattr(obj, self.slot_name, MultiValue(self, obj, value)) def __delete__(self, obj): if obj._auto_update: domain = obj._manager.domain domain.delete_attributes(obj.id, [self.name]) setattr(obj, self.slot_name, MultiValue(self, obj, [])) def to_string(self, obj): str_list = [] for value in self.__get__(obj, type(obj)): str_list.append(self.checker.to_string(value)) return str_list class StringListProperty(MultiValueProperty): def __init__(self, **params): MultiValueProperty.__init__(self, StringChecker, **params) class SmallIntegerListProperty(MultiValueProperty): def __init__(self, **params): params['size'] = 'small' params['signed'] = True MultiValueProperty.__init__(self, IntegerChecker, **params) class SmallPositiveIntegerListProperty(MultiValueProperty): def __init__(self, **params): params['size'] = 'small' params['signed'] = False MultiValueProperty.__init__(self, IntegerChecker, **params) class IntegerListProperty(MultiValueProperty): def __init__(self, **params): params['size'] = 'medium' params['signed'] = True MultiValueProperty.__init__(self, IntegerChecker, **params) class PositiveIntegerListProperty(MultiValueProperty): def __init__(self, **params): params['size'] = 'medium' params['signed'] = False MultiValueProperty.__init__(self, IntegerChecker, **params) class LargeIntegerListProperty(MultiValueProperty): def __init__(self, **params): params['size'] = 'large' params['signed'] = True MultiValueProperty.__init__(self, IntegerChecker, **params) class LargePositiveIntegerListProperty(MultiValueProperty): def __init__(self, **params): params['size'] = 'large' params['signed'] = False MultiValueProperty.__init__(self, IntegerChecker, **params) class BooleanListProperty(MultiValueProperty): def __init__(self, **params): MultiValueProperty.__init__(self, BooleanChecker, **params) class ObjectListProperty(MultiValueProperty): def __init__(self, **params): MultiValueProperty.__init__(self, ObjectChecker, **params) class HasManyProperty(Property): def set_name(self, name): self.name = name self.slot_name = '__' + self.name def __get__(self, obj, objtype): return self class MultiValue: """ Special Multi Value for boto persistence layer to allow us to do obj.list.append(foo) """ def __init__(self, property, obj, _list): self.checker = property.checker self.name = property.name self.object = obj self._list = _list def __repr__(self): return repr(self._list) def __getitem__(self, key): return self._list.__getitem__(key) def __delitem__(self, key): item = self[key] self._list.__delitem__(key) domain = self.object._manager.domain domain.delete_attributes(self.object.id, {self.name: [self.checker.to_string(item)]}) def __len__(self): return len(self._list) def append(self, value): self.checker.check(value) self._list.append(value) domain = self.object._manager.domain domain.put_attributes(self.object.id, {self.name: self.checker.to_string(value)}, replace=False) def index(self, value): for x in self._list: if x.id == value.id: return self._list.index(x) def remove(self, value): del(self[self.index(value)])
# Copyright 2015 CloudByte 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. """ Test class for cloudbyte's cinder driver. This involves mocking of elasticenter's json responses when a method of this driver is unit tested. """ import json import mock import testtools from testtools import matchers from cinder import exception from cinder.volume import configuration as conf from cinder.volume.drivers.cloudbyte import cloudbyte # A fake list account response of cloudbyte's elasticenter FAKE_LIST_ACCOUNT_RESPONSE = """{ "listAccountResponse" : { "count":1 , "account" : [{ "id": "d13a4e9e-0c05-4d2d-8a5e-5efd3ef058e0", "name": "CustomerA", "simpleid": 1, "description": "None", "iqnname": "iqn.2014-05.cvsacc1", "availIOPS": 508, "totaliops": 2000, "usedIOPS": 1492, "volumes": [], "storageBuckets": [], "tsms": [], "qosgroups": [], "filesystemslist": [], "currentUsedSpace": 53179, "currentAvailableSpace": 1249349, "currentThroughput": 156, "currentIOPS": 33, "currentLatency": 0, "currentThrottle": 0, "numericquota": 3145728.0, "currentnumericquota": 1253376.0, "currentavailablequota": 1892352.0, "revisionnumber": 1 }] }}""" # A fake list tsm response of cloudbyte's elasticenter FAKE_LIST_TSM_RESPONSE = """{ "listTsmResponse" : { "count":1 , "listTsm" : [{ "id": "955eaf34-4221-3a77-82d0-99113b126fa8", "simpleid": 2, "name": "openstack", "ipaddress": "172.16.50.40", "accountname": "CustomerA", "sitename": "BLR", "clustername": "HAGrp1", "controllerName": "Controller", "controlleripaddress": "172.16.50.6", "clusterstatus": "Online", "hapoolstatus": "ONLINE", "hapoolname": "pool", "hapoolavailiops": 1700, "hapoolgrace": true, "hapoolavailtput": 6800, "poollatency": 10, "accountid": "d13a4e9e-0c05-4d2d-8a5e-5efd3ef058e0", "controllerid": "8c2f7084-99c0-36e6-9cb7-205e3ba4c813", "poolid": "adcbef8f-2193-3f2c-9bb1-fcaf977ae0fc", "datasetid": "87a23025-f2b2-39e9-85ac-9cda15bfed1a", "storageBuckets": [], "currentUsedSpace": 16384, "currentAvailableSpace": 188416, "currentTotalSpace": 204800, "currentThroughput": 12, "tpcontrol": "true", "currentIOPS": 0, "iopscontrol": "true", "gracecontrol": "false", "currentLatency": 0, "currentThrottle": 0, "iops": "1000", "availIOPS": "500", "availThroughput": "2000", "usedIOPS": "500", "usedThroughput": "2000", "throughput": "4000", "latency": "15", "graceallowed": true, "numericquota": 1048576.0, "currentnumericquota": 204800.0, "availablequota": 843776.0, "blocksize": "4", "type": "1", "iqnname": "iqn.2014-05.cvsacc1.openstack", "interfaceName": "em0", "revisionnumber": 0, "status": "Online", "subnet": "16", "managedstate": "Available", "configurationstate": "sync", "offlinenodes": "", "pooltakeover": "noTakeOver", "totalprovisionquota": "536576", "haNodeStatus": "Available", "ispooltakeoveronpartialfailure": true, "filesystemslist": [], "volumes": [], "qosgrouplist": [] }] }}""" # A fake add QOS group response of cloudbyte's elasticenter FAKE_ADD_QOS_GROUP_RESPONSE = """{ "addqosgroupresponse" : { "qosgroup" : { "id": "d73662ac-6db8-3b2c-981a-012af4e2f7bd", "name": "QoS_DS1acc1openstacktsm", "tsmid": "8146146e-f67b-3942-8074-3074599207a4", "controllerid": "f1603e87-d1e6-3dcb-a549-7a6e77f82d86", "poolid": "73b567c0-e57d-37b5-b765-9d70725f59af", "parentid": "81ebdcbb-f73b-3337-8f32-222820e6acb9", "tsmName": "openstacktsm", "offlinenodes": "", "sitename": "site1", "clustername": "HA1", "controllerName": "node1", "clusterstatus": "Online", "currentThroughput": 0, "currentIOPS": 0, "currentLatency": 0, "currentThrottle": 0, "iopsvalue": "(0/100)", "throughputvalue": "(0/400)", "iops": "100", "iopscontrol": "true", "throughput": "400", "tpcontrol": "true", "blocksize": "4k", "latency": "15", "graceallowed": false, "type": "1", "revisionnumber": 0, "managedstate": "Available", "configurationstate": "init", "standardproviops": 0, "operatingblocksize": 0, "operatingcachehit": 0, "operatingiops": 0, "standardoperatingiops": 0 } }}""" # A fake create volume response of cloudbyte's elasticenter FAKE_CREATE_VOLUME_RESPONSE = """{ "createvolumeresponse" : { "jobid": "f94e2257-9515-4a44-add0-4b16cb1bcf67" }}""" # A fake query async job response of cloudbyte's elasticenter FAKE_QUERY_ASYNC_JOB_RESULT_RESPONSE = """{ "queryasyncjobresultresponse" : { "accountid": "e8aca633-7bce-4ab7-915a-6d8847248467", "userid": "a83d1030-1b85-40f7-9479-f40e4dbdd5d5", "cmd": "com.cloudbyte.api.commands.CreateVolumeCmd", "msg": "5", "jobstatus": 1, "jobprocstatus": 0, "jobresultcode": 0, "jobresulttype": "object", "jobresult": { "storage": { "id": "92cfd601-bc1f-3fa7-8322-c492099f3326", "name": "DS1", "simpleid": 20, "compression": "off", "sync": "always", "noofcopies": 1, "recordsize": "4k", "deduplication": "off", "quota": "10G", "path": "devpool1/acc1openstacktsm/DS1", "tsmid": "8146146e-f67b-3942-8074-3074599207a4", "poolid": "73b567c0-e57d-37b5-b765-9d70725f59af", "mountpoint": "acc1DS1", "currentUsedSpace": 0, "currentAvailableSpace": 0, "currentTotalSpace": 0, "currentThroughput": 0, "currentIOPS": 0, "currentLatency": 0, "currentThrottle": 0, "tsmName": "openstacktsm", "hapoolname": "devpool1", "revisionnumber": 0, "blocklength": "512B", "nfsenabled": false, "cifsenabled": false, "iscsienabled": true, "fcenabled": false } }, "created": "2014-06-16 15:49:49", "jobid": "f94e2257-9515-4a44-add0-4b16cb1bcf67" }}""" # A fake list filesystem response of cloudbyte's elasticenter FAKE_LIST_FILE_SYSTEM_RESPONSE = """{ "listFilesystemResponse" : { "count":1 , "filesystem" : [{ "id": "c93df32e-3a99-3491-8e10-cf318a7f9b7f", "name": "c93df32e3a9934918e10cf318a7f9b7f", "simpleid": 34, "type": "filesystem", "revisionnumber": 1, "path": "/cvsacc1DS1", "clusterid": "8b404f12-7975-4e4e-8549-7abeba397fc9", "clusterstatus": "Online", "Tsmid": "955eaf34-4221-3a77-82d0-99113b126fa8", "tsmType": "1", "accountid": "d13a4e9e-0c05-4d2d-8a5e-5efd3ef058e0", "poolid": "adcbef8f-2193-3f2c-9bb1-fcaf977ae0fc", "controllerid": "8c2f7084-99c0-36e6-9cb7-205e3ba4c813", "groupid": "663923c9-084b-3778-b13d-72f23d046b8d", "parentid": "08de7c14-62af-3992-8407-28f5f053e59b", "compression": "off", "sync": "always", "noofcopies": 1, "recordsize": "4k", "deduplication": "off", "quota": "1T", "unicode": "off", "casesensitivity": "sensitive", "readonly": false, "nfsenabled": true, "cifsenabled": false, "iscsienabled": false, "fcenabled": false, "currentUsedSpace": 19968, "currentAvailableSpace": 1028608, "currentTotalSpace": 1048576, "currentThroughput": 0, "currentIOPS": 0, "currentLatency": 0, "currentThrottle": 0, "numericquota": 1048576.0, "status": "Online", "managedstate": "Available", "configurationstate": "sync", "tsmName": "cvstsm1", "ipaddress": "172.16.50.35", "sitename": "BLR", "clustername": "HAGrp1", "controllerName": "Controller", "hapoolname": "pool", "hapoolgrace": true, "tsmgrace": true, "tsmcontrolgrace": "false", "accountname": "CustomerA", "groupname": "QoS_DS1cvsacc1cvstsm1", "iops": "500", "blocksize": "4", "throughput": "2000", "latency": "15", "graceallowed": false, "offlinenodes": "", "tpcontrol": "true", "iopscontrol": "true", "tsmAvailIops": "8", "tsmAvailTput": "32", "iqnname": "", "mountpoint": "cvsacc1DS1", "pooltakeover": "noTakeOver", "volumeaccessible": "true", "localschedulecount": 0 }] }}""" # A fake list storage snapshot response of cloudbyte's elasticenter FAKE_LIST_STORAGE_SNAPSHOTS_RESPONSE = """{ "listDatasetSnapshotsResponse" : { "count":1 , "snapshot" : [{ "name": "snap_c60890b1f23646f29e6d51e6e592cee6", "path": "DS1@snap_c60890b1f23646f29e6d51e6e592cee6", "availMem": "-", "usedMem": "0", "refer": "26K", "mountpoint": "-", "timestamp": "Mon Jun 16 2014 14:41", "clones": 0, "pooltakeover": "noTakeOver", "managedstate": "Available" }] }}""" # A fake delete storage snapshot response of cloudbyte's elasticenter FAKE_DELETE_STORAGE_SNAPSHOT_RESPONSE = """{ "deleteSnapshotResponse" : { "DeleteSnapshot" : { "status": "success" } }}""" # A fake update volume iscsi service response of cloudbyte's elasticenter FAKE_UPDATE_VOLUME_ISCSI_SERVICE_RESPONSE = ( """{ "updatingvolumeiscsidetails" : { "viscsioptions" : { "id": "0426c04a-8fac-30e8-a8ad-ddab2f08013a", "volume_id": "12371e7c-392b-34b9-ac43-073b3c85f1d1", "ag_id": "4459248d-e9f1-3d2a-b7e8-b5d9ce587fc1", "ig_id": "527bd65b-ebec-39ce-a5e9-9dd1106cc0fc", "iqnname": "iqn.2014-06.acc1.openstacktsm:acc1DS1", "authmethod": "None", "status": true, "usn": "12371e7c392b34b9ac43073b3c85f1d1", "initialdigest": "Auto", "queuedepth": "32", "inqproduct": 0, "inqrevision": 0, "blocklength": "512B" }} }""") # A fake list iscsi initiator response of cloudbyte's elasticenter FAKE_LIST_ISCSI_INITIATOR_RESPONSE = """{ "listInitiatorsResponse" : { "count":2 , "initiator" : [{ "id": "527bd65b-ebec-39ce-a5e9-9dd1106cc0fc", "accountid": "86c5251a-9044-4690-b924-0d97627aeb8c", "name": "ALL", "netmask": "ALL", "initiatorgroup": "ALL" },{ "id": "203e0235-1d5a-3130-9204-98e3f642a564", "accountid": "86c5251a-9044-4690-b924-0d97627aeb8c", "name": "None", "netmask": "None", "initiatorgroup": "None" }] }}""" # A fake delete file system response of cloudbyte's elasticenter FAKE_DELETE_FILE_SYSTEM_RESPONSE = """{ "deleteFileSystemResponse" : { "jobid": "e1fe861a-17e3-41b5-ae7c-937caac62cdf" }}""" # A fake create storage snapshot response of cloudbyte's elasticenter FAKE_CREATE_STORAGE_SNAPSHOT_RESPONSE = ( """{ "createStorageSnapshotResponse" : { "StorageSnapshot" : { "id": "21d7a92a-f15e-3f5b-b981-cb30697b8028", "name": "snap_c60890b1f23646f29e6d51e6e592cee6", "usn": "21d7a92af15e3f5bb981cb30697b8028", "lunusn": "12371e7c392b34b9ac43073b3c85f1d1", "lunid": "12371e7c-392b-34b9-ac43-073b3c85f1d1", "scsiEnabled": false }} }""") # A fake list volume iscsi service response of cloudbyte's elasticenter FAKE_LIST_VOLUME_ISCSI_SERVICE_RESPONSE = ( """{ "listVolumeiSCSIServiceResponse" : { "count":1 , "iSCSIService" : [{ "id": "67ddcbf4-6887-3ced-8695-7b9cdffce885", "volume_id": "c93df32e-3a99-3491-8e10-cf318a7f9b7f", "ag_id": "4459248d-e9f1-3d2a-b7e8-b5d9ce587fc1", "ig_id": "203e0235-1d5a-3130-9204-98e3f642a564", "iqnname": "iqn.2014-06.acc1.openstacktsm:acc1DS1", "authmethod": "None", "status": true, "usn": "92cfd601bc1f3fa78322c492099f3326", "initialdigest": "Auto", "queuedepth": "32", "inqproduct": 0, "inqrevision": 0, "blocklength": "512B" }] }}""") # A fake clone dataset snapshot response of cloudbyte's elasticenter FAKE_CLONE_DATASET_SNAPSHOT_RESPONSE = """{ "cloneDatasetSnapshot" : { "filesystem" : { "id": "dcd46a57-e3f4-3fc1-8dd8-2e658d9ebb11", "name": "DS1Snap1clone1", "simpleid": 21, "type": "volume", "revisionnumber": 1, "path": "iqn.2014-06.acc1.openstacktsm:acc1DS1Snap1clone1", "clusterid": "0ff44329-9a69-4611-bac2-6eaf1b08bb18", "clusterstatus": "Online", "Tsmid": "8146146e-f67b-3942-8074-3074599207a4", "tsmType": "1", "accountid": "86c5251a-9044-4690-b924-0d97627aeb8c", "poolid": "73b567c0-e57d-37b5-b765-9d70725f59af", "controllerid": "f1603e87-d1e6-3dcb-a549-7a6e77f82d86", "groupid": "d73662ac-6db8-3b2c-981a-012af4e2f7bd", "parentid": "81ebdcbb-f73b-3337-8f32-222820e6acb9", "compression": "off", "sync": "always", "noofcopies": 1, "recordsize": "4k", "deduplication": "off", "quota": "10G", "unicode": "off", "casesensitivity": "sensitive", "readonly": false, "nfsenabled": false, "cifsenabled": false, "iscsienabled": true, "fcenabled": false, "currentUsedSpace": 0, "currentAvailableSpace": 10240, "currentTotalSpace": 10240, "currentThroughput": 0, "currentIOPS": 0, "currentLatency": 0, "currentThrottle": 0, "numericquota": 10240.0, "status": "Online", "managedstate": "Available", "configurationstate": "sync", "tsmName": "openstacktsm", "ipaddress": "20.10.22.56", "sitename": "site1", "clustername": "HA1", "controllerName": "node1", "hapoolname": "devpool1", "hapoolgrace": true, "tsmgrace": true, "tsmcontrolgrace": "false", "accountname": "acc1", "groupname": "QoS_DS1acc1openstacktsm", "iops": "100", "blocksize": "4k", "throughput": "400", "latency": "15", "graceallowed": false, "offlinenodes": "", "tpcontrol": "true", "iopscontrol": "true", "tsmAvailIops": "700", "tsmAvailTput": "2800", "iqnname": "iqn.2014-06.acc1.openstacktsm:acc1DS1Snap1clone1", "mountpoint": "acc1DS1Snap1clone1", "blocklength": "512B", "volumeaccessible": "true", "localschedulecount": 0 } }}""" # A fake update filesystem response of cloudbyte's elasticenter FAKE_UPDATE_FILE_SYSTEM_RESPONSE = """{ "updatefilesystemresponse" : { "count":1 , "filesystem" : [{ "id": "92cfd601-bc1f-3fa7-8322-c492099f3326", "name": "DS1", "simpleid": 20, "type": "volume", "revisionnumber": 1, "path": "iqn.2014-06.acc1.openstacktsm:acc1DS1", "clusterid": "0ff44329-9a69-4611-bac2-6eaf1b08bb18", "clusterstatus": "Online", "Tsmid": "8146146e-f67b-3942-8074-3074599207a4", "tsmType": "1", "accountid": "86c5251a-9044-4690-b924-0d97627aeb8c", "poolid": "73b567c0-e57d-37b5-b765-9d70725f59af", "controllerid": "f1603e87-d1e6-3dcb-a549-7a6e77f82d86", "groupid": "d73662ac-6db8-3b2c-981a-012af4e2f7bd", "parentid": "81ebdcbb-f73b-3337-8f32-222820e6acb9", "compression": "off", "sync": "always", "noofcopies": 1, "recordsize": "4k", "deduplication": "off", "quota": "12G", "unicode": "off", "casesensitivity": "sensitive", "readonly": false, "nfsenabled": false, "cifsenabled": false, "iscsienabled": true, "fcenabled": false, "currentUsedSpace": 0, "currentAvailableSpace": 10240, "currentTotalSpace": 10240, "currentThroughput": 0, "currentIOPS": 0, "currentLatency": 0, "currentThrottle": 0, "numericquota": 12288.0, "status": "Online", "managedstate": "Available", "configurationstate": "sync", "tsmName": "openstacktsm", "ipaddress": "20.10.22.56", "sitename": "site1", "clustername": "HA1", "controllerName": "node1", "hapoolname": "devpool1", "hapoolgrace": true, "tsmgrace": true, "tsmcontrolgrace": "false", "accountname": "acc1", "groupname": "QoS_DS1acc1openstacktsm", "iops": "100", "blocksize": "4k", "throughput": "400", "latency": "15", "graceallowed": false, "offlinenodes": "", "tpcontrol": "true", "iopscontrol": "true", "tsmAvailIops": "700", "tsmAvailTput": "2800", "iqnname": "iqn.2014-06.acc1.openstacktsm:acc1DS1", "mountpoint": "acc1DS1", "blocklength": "512B", "volumeaccessible": "true", "localschedulecount": 0 }] }}""" # A fake update QOS group response of cloudbyte's elasticenter FAKE_UPDATE_QOS_GROUP_RESPONSE = """{ "updateqosresponse" : { "count":1 , "qosgroup" : [{ "id": "d73662ac-6db8-3b2c-981a-012af4e2f7bd", "name": "QoS_DS1acc1openstacktsm", "tsmid": "8146146e-f67b-3942-8074-3074599207a4", "controllerid": "f1603e87-d1e6-3dcb-a549-7a6e77f82d86", "poolid": "73b567c0-e57d-37b5-b765-9d70725f59af", "parentid": "81ebdcbb-f73b-3337-8f32-222820e6acb9", "tsmName": "openstacktsm", "offlinenodes": "", "sitename": "site1", "clustername": "HA1", "controllerName": "node1", "clusterstatus": "Online", "currentThroughput": 0, "currentIOPS": 0, "currentLatency": 0, "currentThrottle": 0, "iopsvalue": "(0/101)", "throughputvalue": "(0/404)", "iops": "101", "iopscontrol": "true", "throughput": "404", "tpcontrol": "true", "blocksize": "4k", "latency": "15", "graceallowed": true, "type": "1", "revisionnumber": 2, "managedstate": "Available", "configurationstate": "sync", "status": "Online", "standardproviops": 0, "operatingblocksize": 0, "operatingcachehit": 0, "operatingiops": 0, "standardoperatingiops": 0 }] }}""" # A fake list iSCSI auth user response of cloudbyte's elasticenter FAKE_LIST_ISCSI_AUTH_USER_RESPONSE = """{ "listiSCSIAuthUsersResponse" : { "count":1 , "authuser" : [{ "id": "53d00164-a974-31b8-a854-bd346a8ea937", "accountid": "12d41531-c41a-4ab7-abe2-ce0db2570119", "authgroupid": "537744eb-c594-3145-85c0-96079922b894", "chapusername": "fakeauthgroupchapuser", "chappassword": "fakeauthgroupchapsecret", "mutualchapusername": "fakeauthgroupmutualchapuser", "mutualchappassword": "fakeauthgroupmutualchapsecret" }] }}""" # A fake list iSCSI auth group response of cloudbyte's elasticenter FAKE_LIST_ISCSI_AUTH_GROUP_RESPONSE = """{ "listiSCSIAuthGroupResponse" : { "count":2 , "authgroup" : [{ "id": "32d935ee-a60f-3681-b792-d8ccfe7e8e7f", "name": "None", "comment": "None" }, { "id": "537744eb-c594-3145-85c0-96079922b894", "name": "fakeauthgroup", "comment": "Fake Auth Group For Openstack " }] }}""" # This dict maps the http commands of elasticenter # with its respective fake responses MAP_COMMAND_TO_FAKE_RESPONSE = {} MAP_COMMAND_TO_FAKE_RESPONSE['deleteFileSystem'] = ( json.loads(FAKE_DELETE_FILE_SYSTEM_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["listFileSystem"] = ( json.loads(FAKE_LIST_FILE_SYSTEM_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["deleteSnapshot"] = ( json.loads(FAKE_DELETE_STORAGE_SNAPSHOT_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["updateVolumeiSCSIService"] = ( json.loads(FAKE_UPDATE_VOLUME_ISCSI_SERVICE_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["createStorageSnapshot"] = ( json.loads(FAKE_CREATE_STORAGE_SNAPSHOT_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["listAccount"] = ( json.loads(FAKE_LIST_ACCOUNT_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["listTsm"] = ( json.loads(FAKE_LIST_TSM_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["addQosGroup"] = ( json.loads(FAKE_ADD_QOS_GROUP_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["queryAsyncJobResult"] = ( json.loads(FAKE_QUERY_ASYNC_JOB_RESULT_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["createVolume"] = ( json.loads(FAKE_CREATE_VOLUME_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["listVolumeiSCSIService"] = ( json.loads(FAKE_LIST_VOLUME_ISCSI_SERVICE_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE["listiSCSIInitiator"] = ( json.loads(FAKE_LIST_ISCSI_INITIATOR_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE['cloneDatasetSnapshot'] = ( json.loads(FAKE_CLONE_DATASET_SNAPSHOT_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE['updateFileSystem'] = ( json.loads(FAKE_UPDATE_FILE_SYSTEM_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE['updateQosGroup'] = ( json.loads(FAKE_UPDATE_QOS_GROUP_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE['listStorageSnapshots'] = ( json.loads(FAKE_LIST_STORAGE_SNAPSHOTS_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE['listiSCSIAuthUser'] = ( json.loads(FAKE_LIST_ISCSI_AUTH_USER_RESPONSE)) MAP_COMMAND_TO_FAKE_RESPONSE['listiSCSIAuthGroup'] = ( json.loads(FAKE_LIST_ISCSI_AUTH_GROUP_RESPONSE)) class CloudByteISCSIDriverTestCase(testtools.TestCase): def setUp(self): super(CloudByteISCSIDriverTestCase, self).setUp() self._configure_driver() def _configure_driver(self): configuration = conf.Configuration(None, None) # initialize the elasticenter iscsi driver self.driver = cloudbyte.CloudByteISCSIDriver( configuration=configuration) # override some parts of driver configuration self.driver.configuration.cb_tsm_name = 'openstack' self.driver.configuration.cb_account_name = 'CustomerA' self.driver.configuration.cb_auth_group = 'fakeauthgroup' self.driver.configuration.cb_apikey = 'G4ZUB39WH7lbiZhPhL3nbd' self.driver.configuration.san_ip = '172.16.51.30' def _side_effect_api_req(self, cmd, params, version='1.0'): """This is a side effect function. The return value is determined based on cmd argument. The signature matches exactly with the method it tries to mock. """ return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_create_vol(self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'createVolume': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_delete_file_system( self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'deleteFileSystem': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_query_asyncjob_response( self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'queryAsyncJobResult': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_query_asyncjob( self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'queryAsyncJobResult': return {'queryasyncjobresultresponse': {'jobstatus': 0}} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_list_tsm(self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listTsm': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _none_response_to_list_tsm(self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listTsm': return {"listTsmResponse": {}} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_list_iscsi_auth_group(self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listiSCSIAuthGroup': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_list_iscsi_auth_user(self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listiSCSIAuthUser': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_enable_chap(self): """This is a side effect function.""" self.driver.cb_use_chap = True def _side_effect_disable_chap(self): """This is a side effect function.""" self.driver.cb_use_chap = False def _side_effect_api_req_to_list_filesystem( self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listFileSystem': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_list_vol_iscsi_service( self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listVolumeiSCSIService': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_api_req_to_list_iscsi_initiator( self, cmd, params, version='1.0'): """This is a side effect function.""" if cmd == 'listiSCSIInitiator': return {} return MAP_COMMAND_TO_FAKE_RESPONSE[cmd] def _side_effect_create_vol_from_snap(self, cloned_volume, snapshot): """This is a side effect function.""" return {} def _side_effect_create_snapshot(self, snapshot): """This is a side effect function.""" model_update = {} model_update['provider_id'] = "devpool1/acc1openstacktsm/DS1@DS1Snap1" return model_update def _side_effect_get_connection(self, host, url): """This is a side effect function.""" return_obj = {} return_obj['http_status'] = 200 # mock the response data return_obj['data'] = MAP_COMMAND_TO_FAKE_RESPONSE['listTsm'] return_obj['error'] = None return return_obj def _side_effect_get_err_connection(self, host, url): """This is a side effect function.""" return_obj = {} return_obj['http_status'] = 500 # mock the response data return_obj['data'] = None return_obj['error'] = "Http status: 500, Error: Elasticenter " "is not available." return return_obj def _side_effect_get_err_connection2(self, host, url): """This is a side effect function.""" msg = ("Error executing CloudByte API %(cmd)s , Error: %(err)s" % {'cmd': 'MockTest', 'err': 'Error'}) raise exception.VolumeBackendAPIException(msg) def _get_fake_volume_id(self): # Get the filesystems fs_list = MAP_COMMAND_TO_FAKE_RESPONSE['listFileSystem'] filesystems = fs_list['listFilesystemResponse']['filesystem'] # Get the volume id from the first filesystem volume_id = filesystems[0]['id'] return volume_id @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_execute_and_get_response_details') def test_api_request_for_cloudbyte(self, mock_conn): # Test - I # configure the mocks with respective side-effects mock_conn.side_effect = self._side_effect_get_connection # run the test data = self.driver._api_request_for_cloudbyte('listTsm', {}) # assert the data attributes self.assertEqual(1, data['listTsmResponse']['count']) # Test - II # configure the mocks with side-effects mock_conn.reset_mock() mock_conn.side_effect = self._side_effect_get_err_connection # run the test with testtools.ExpectedException( exception.VolumeBackendAPIException, 'Bad or unexpected response from the storage volume ' 'backend API: Failed to execute CloudByte API'): self.driver._api_request_for_cloudbyte('listTsm', {}) # Test - III # configure the mocks with side-effects mock_conn.reset_mock() mock_conn.side_effect = self._side_effect_get_err_connection2 # run the test with testtools.ExpectedException( exception.VolumeBackendAPIException, 'Error executing CloudByte API'): self.driver._api_request_for_cloudbyte('listTsm', {}) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_delete_volume(self, mock_api_req): # prepare the dependencies fake_volume_id = self._get_fake_volume_id() volume = {'id': fake_volume_id, 'provider_id': fake_volume_id} # Test-I mock_api_req.side_effect = self._side_effect_api_req # run the test self.driver.delete_volume(volume) # assert that 3 api calls were invoked self.assertEqual(3, mock_api_req.call_count) # Test-II # reset & re-configure mock volume['provider_id'] = None mock_api_req.reset_mock() mock_api_req.side_effect = self._side_effect_api_req # run the test self.driver.delete_volume(volume) # assert that no api calls were invoked self.assertEqual(0, mock_api_req.call_count) # Test-III # re-configure the dependencies volume['provider_id'] = fake_volume_id # reset & re-configure mock mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._side_effect_api_req_to_delete_file_system) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.delete_volume, volume) # assert that 2 api calls were invoked self.assertEqual(2, mock_api_req.call_count) # Test - IV # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._side_effect_api_req_to_query_asyncjob_response) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.delete_volume, volume) # assert that 3 api calls were invoked self.assertEqual(3, mock_api_req.call_count) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_delete_snapshot(self, mock_api_req): snapshot = { 'id': 'SomeID', 'provider_id': 'devpool1/acc1openstacktsm/DS1@DS1Snap1', 'display_name': 'DS1Snap1', 'volume_id': 'SomeVol', 'volume': { 'display_name': 'DS1' } } # Test - I # now run the test self.driver.delete_snapshot(snapshot) # assert that 1 api call was invoked self.assertEqual(1, mock_api_req.call_count) # Test - II # reconfigure the dependencies snapshot['provider_id'] = None # reset & reconfigure the mock mock_api_req.reset_mock() mock_api_req.side_effect = self._side_effect_api_req # now run the test self.driver.delete_snapshot(snapshot) # assert that no api calls were invoked self.assertEqual(0, mock_api_req.call_count) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_create_snapshot(self, mock_api_req): # prepare the dependencies fake_volume_id = self._get_fake_volume_id() snapshot = { 'id': 'c60890b1-f236-46f2-9e6d-51e6e592cee6', 'display_name': 'DS1Snap1', 'volume_id': 'SomeVol', 'volume': { 'display_name': 'DS1', 'provider_id': fake_volume_id } } # Test - I # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test model_update = self.driver.create_snapshot(snapshot) # assert that 2 api calls were invoked self.assertEqual(2, mock_api_req.call_count) self.assertEqual('DS1@snap_c60890b1f23646f29e6d51e6e592cee6', model_update['provider_id']) # Test - II # reconfigure the dependencies snapshot['volume']['provider_id'] = None # reset & reconfigure the mock mock_api_req.reset_mock() mock_api_req.side_effect = self._side_effect_api_req # now run the test & assert the exception with testtools.ExpectedException( exception.VolumeBackendAPIException, 'Bad or unexpected response from the storage volume ' 'backend API: Failed to create snapshot'): self.driver.create_snapshot(snapshot) # assert that no api calls were invoked self.assertEqual(0, mock_api_req.call_count) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_create_volume(self, mock_api_req): # prepare the dependencies fake_volume_id = self._get_fake_volume_id() volume = { 'id': fake_volume_id, 'size': 22 } # Test - I # enable CHAP self._side_effect_enable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test provider_details = self.driver.create_volume(volume) # assert equality checks for certain configuration attributes self.assertEqual( 'openstack', self.driver.configuration.cb_tsm_name) self.assertEqual( 'CustomerA', self.driver.configuration.cb_account_name) self.assertEqual( 'fakeauthgroup', self.driver.configuration.cb_auth_group) # assert the result self.assertEqual( 'CHAP fakeauthgroupchapuser fakeauthgroupchapsecret', provider_details['provider_auth']) self.assertThat( provider_details['provider_location'], matchers.Contains('172.16.50.35:3260')) # assert the invoked api calls to CloudByte Storage self.assertEqual(11, mock_api_req.call_count) # Test - II # reset the mock mock_api_req.reset_mock() # disable CHAP self._side_effect_disable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test provider_details = self.driver.create_volume(volume) # assert equality checks for certain configuration attributes self.assertEqual( 'openstack', self.driver.configuration.cb_tsm_name) self.assertEqual( 'CustomerA', self.driver.configuration.cb_account_name) # assert the result self.assertEqual( None, provider_details['provider_auth']) self.assertThat( provider_details['provider_location'], matchers.Contains('172.16.50.35:3260')) # assert the invoked api calls to CloudByte Storage self.assertEqual(9, mock_api_req.call_count) # Test - III # reconfigure the dependencies volume['id'] = 'NotExists' del volume['size'] # reset & reconfigure the mock mock_api_req.reset_mock() mock_api_req.side_effect = self._side_effect_api_req # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - IV # reconfigure the dependencies volume['id'] = 'abc' # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = self._side_effect_api_req_to_create_vol # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - V # reconfigure the dependencies # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = self._side_effect_api_req_to_list_filesystem # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - VI volume['id'] = fake_volume_id # reconfigure the dependencies # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._side_effect_api_req_to_list_vol_iscsi_service) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - VII # reconfigure the dependencies # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._side_effect_api_req_to_list_iscsi_initiator) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - VIII volume['id'] = fake_volume_id volume['size'] = 22 # reconfigure the dependencies # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._none_response_to_list_tsm) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - IX volume['id'] = fake_volume_id volume['size'] = 22 # reconfigure the dependencies # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._side_effect_api_req_to_create_vol) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) # Test - X # reset the mocks mock_api_req.reset_mock() # configure or re-configure the mocks mock_api_req.side_effect = ( self._side_effect_api_req_to_query_asyncjob_response) # Now run the test & assert the exception self.assertRaises(exception.VolumeBackendAPIException, self.driver.create_volume, volume) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') @mock.patch.object(cloudbyte.CloudByteISCSIDriver, 'create_volume_from_snapshot') @mock.patch.object(cloudbyte.CloudByteISCSIDriver, 'create_snapshot') def test_create_cloned_volume(self, mock_create_snapshot, mock_create_vol_from_snap, mock_api_req): # prepare the input test data fake_volume_id = self._get_fake_volume_id() src_volume = {'display_name': 'DS1Snap1'} cloned_volume = { 'source_volid': fake_volume_id, 'id': 'SomeNewID', 'display_name': 'CloneOfDS1Snap1' } # Test - I # configure the mocks with respective sideeffects mock_api_req.side_effect = self._side_effect_api_req mock_create_vol_from_snap.side_effect = ( self._side_effect_create_vol_from_snap) mock_create_snapshot.side_effect = ( self._side_effect_create_snapshot) # now run the test self.driver.create_cloned_volume(cloned_volume, src_volume) # assert that n api calls were invoked self.assertEqual(0, mock_api_req.call_count) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_create_volume_from_snapshot(self, mock_api_req): # prepare the input test data fake_volume_id = self._get_fake_volume_id() snapshot = { 'volume_id': fake_volume_id, 'provider_id': 'devpool1/acc1openstacktsm/DS1@DS1Snap1', 'id': 'SomeSnapID', 'volume': { 'provider_id': fake_volume_id } } cloned_volume = { 'display_name': 'CloneOfDS1Snap1', 'id': 'ClonedVolID' } # Test - I # enable CHAP self._side_effect_enable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test provider_details = ( self.driver.create_volume_from_snapshot(cloned_volume, snapshot)) # assert the result self.assertEqual( 'CHAP fakeauthgroupchapuser fakeauthgroupchapsecret', provider_details['provider_auth']) self.assertEqual( '20.10.22.56:3260 ' 'iqn.2014-06.acc1.openstacktsm:acc1DS1Snap1clone1 0', provider_details['provider_location']) # assert the invoked api calls to CloudByte Storage self.assertEqual(4, mock_api_req.call_count) # Test - II # reset the mocks mock_api_req.reset_mock() # disable CHAP self._side_effect_disable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test provider_details = ( self.driver.create_volume_from_snapshot(cloned_volume, snapshot)) # assert the result self.assertEqual( None, provider_details['provider_auth']) self.assertEqual( '20.10.22.56:3260 ' 'iqn.2014-06.acc1.openstacktsm:acc1DS1Snap1clone1 0', provider_details['provider_location']) # assert n api calls were invoked self.assertEqual(1, mock_api_req.call_count) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_extend_volume(self, mock_api_req): # prepare the input test data fake_volume_id = self._get_fake_volume_id() volume = { 'id': 'SomeID', 'provider_id': fake_volume_id } new_size = '2' # Test - I # configure the mock with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test self.driver.extend_volume(volume, new_size) # assert n api calls were invoked self.assertEqual(1, mock_api_req.call_count) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_create_export(self, mock_api_req): # Test - I # enable CHAP self._side_effect_enable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test model_update = self.driver.create_export({}, {}, {}) # assert the result self.assertEqual('CHAP fakeauthgroupchapuser fakeauthgroupchapsecret', model_update['provider_auth']) # Test - II # reset the mocks mock_api_req.reset_mock() # disable CHAP self._side_effect_disable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test model_update = self.driver.create_export({}, {}, {}) # assert the result self.assertEqual(None, model_update['provider_auth']) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_ensure_export(self, mock_api_req): # Test - I # enable CHAP self._side_effect_enable_chap() # configure the mock with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test model_update = self.driver.ensure_export({}, {}) # assert the result to have a provider_auth attribute self.assertEqual('CHAP fakeauthgroupchapuser fakeauthgroupchapsecret', model_update['provider_auth']) # Test - II # reset the mocks mock_api_req.reset_mock() # disable CHAP self._side_effect_disable_chap() # configure the mocks with respective side-effects mock_api_req.side_effect = self._side_effect_api_req # now run the test model_update = self.driver.create_export({}, {}, {}) # assert the result self.assertEqual(None, model_update['provider_auth']) @mock.patch.object(cloudbyte.CloudByteISCSIDriver, '_api_request_for_cloudbyte') def test_get_volume_stats(self, mock_api_req): # configure the mock with a side-effect mock_api_req.side_effect = self._side_effect_api_req # Test - I # run the test vol_stats = self.driver.get_volume_stats() # assert 0 api calls were invoked self.assertEqual(0, mock_api_req.call_count) # Test - II # run the test with refresh as True vol_stats = self.driver.get_volume_stats(refresh=True) # assert n api calls were invoked self.assertEqual(1, mock_api_req.call_count) # assert the result attributes with respective values self.assertEqual(1024.0, vol_stats['total_capacity_gb']) self.assertEqual(824.0, vol_stats['free_capacity_gb']) self.assertEqual(0, vol_stats['reserved_percentage']) self.assertEqual('CloudByte', vol_stats['vendor_name']) self.assertEqual('iSCSI', vol_stats['storage_protocol']) # Test - III # configure the mocks with side-effect mock_api_req.reset_mock() mock_api_req.side_effect = self._side_effect_api_req_to_list_tsm # run the test with refresh as True with testtools.ExpectedException( exception.VolumeBackendAPIException, "Bad or unexpected response from the storage volume " "backend API: No response was received from CloudByte " "storage list tsm API call."): self.driver.get_volume_stats(refresh=True)
# Copyright 2013-2014 The Meson development team # 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 io import sys import time import platform import typing as T from contextlib import contextmanager from pathlib import Path if T.TYPE_CHECKING: from ._typing import StringProtocol """This is (mostly) a standalone module used to write logging information about Meson runs. Some output goes to screen, some to logging dir and some goes to both.""" def _windows_ansi() -> bool: # windll only exists on windows, so mypy will get mad from ctypes import windll, byref # type: ignore from ctypes.wintypes import DWORD kernel = windll.kernel32 stdout = kernel.GetStdHandle(-11) mode = DWORD() if not kernel.GetConsoleMode(stdout, byref(mode)): return False # ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0x4 # If the call to enable VT processing fails (returns 0), we fallback to # original behavior return bool(kernel.SetConsoleMode(stdout, mode.value | 0x4) or os.environ.get('ANSICON')) def colorize_console() -> bool: _colorize_console = getattr(sys.stdout, 'colorize_console', None) # type: bool if _colorize_console is not None: return _colorize_console try: if platform.system().lower() == 'windows': _colorize_console = os.isatty(sys.stdout.fileno()) and _windows_ansi() else: _colorize_console = os.isatty(sys.stdout.fileno()) and os.environ.get('TERM', 'dumb') != 'dumb' except Exception: _colorize_console = False sys.stdout.colorize_console = _colorize_console # type: ignore[attr-defined] return _colorize_console def setup_console() -> None: # on Windows, a subprocess might call SetConsoleMode() on the console # connected to stdout and turn off ANSI escape processing. Call this after # running a subprocess to ensure we turn it on again. if platform.system().lower() == 'windows': try: delattr(sys.stdout, 'colorize_console') except AttributeError: pass log_dir = None # type: T.Optional[str] log_file = None # type: T.Optional[T.TextIO] log_fname = 'meson-log.txt' # type: str log_depth = [] # type: T.List[str] log_timestamp_start = None # type: T.Optional[float] log_fatal_warnings = False # type: bool log_disable_stdout = False # type: bool log_errors_only = False # type: bool _in_ci = 'CI' in os.environ # type: bool _logged_once = set() # type: T.Set[T.Tuple[str, ...]] log_warnings_counter = 0 # type: int def disable() -> None: global log_disable_stdout log_disable_stdout = True def enable() -> None: global log_disable_stdout log_disable_stdout = False def set_quiet() -> None: global log_errors_only log_errors_only = True def set_verbose() -> None: global log_errors_only log_errors_only = False def initialize(logdir: str, fatal_warnings: bool = False) -> None: global log_dir, log_file, log_fatal_warnings log_dir = logdir log_file = open(os.path.join(logdir, log_fname), 'w', encoding='utf-8') log_fatal_warnings = fatal_warnings def set_timestamp_start(start: float) -> None: global log_timestamp_start log_timestamp_start = start def shutdown() -> T.Optional[str]: global log_file if log_file is not None: path = log_file.name exception_around_goer = log_file log_file = None exception_around_goer.close() return path return None class AnsiDecorator: plain_code = "\033[0m" def __init__(self, text: str, code: str, quoted: bool = False): self.text = text self.code = code self.quoted = quoted def get_text(self, with_codes: bool) -> str: text = self.text if with_codes and self.code: text = self.code + self.text + AnsiDecorator.plain_code if self.quoted: text = f'"{text}"' return text def __len__(self) -> int: return len(self.text) def __str__(self) -> str: return self.get_text(colorize_console()) TV_Loggable = T.Union[str, AnsiDecorator, 'StringProtocol'] TV_LoggableList = T.List[TV_Loggable] class AnsiText: def __init__(self, *args: TV_LoggableList): self.args = args def __len__(self) -> int: return sum(len(x) for x in self.args) def __str__(self) -> str: return ''.join(str(x) for x in self.args) def bold(text: str, quoted: bool = False) -> AnsiDecorator: return AnsiDecorator(text, "\033[1m", quoted=quoted) def plain(text: str) -> AnsiDecorator: return AnsiDecorator(text, "") def red(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[1;31m") def green(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[1;32m") def yellow(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[1;33m") def blue(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[1;34m") def cyan(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[1;36m") def normal_red(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[31m") def normal_green(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[32m") def normal_yellow(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[33m") def normal_blue(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[34m") def normal_cyan(text: str) -> AnsiDecorator: return AnsiDecorator(text, "\033[36m") # This really should be AnsiDecorator or anything that implements # __str__(), but that requires protocols from typing_extensions def process_markup(args: T.Sequence[TV_Loggable], keep: bool) -> T.List[str]: arr = [] # type: T.List[str] if log_timestamp_start is not None: arr = ['[{:.3f}]'.format(time.monotonic() - log_timestamp_start)] for arg in args: if arg is None: continue if isinstance(arg, str): arr.append(arg) elif isinstance(arg, AnsiDecorator): arr.append(arg.get_text(keep)) else: arr.append(str(arg)) return arr def force_print(*args: str, nested: str, **kwargs: T.Any) -> None: if log_disable_stdout: return iostr = io.StringIO() kwargs['file'] = iostr print(*args, **kwargs) raw = iostr.getvalue() if log_depth: prepend = log_depth[-1] + '| ' if nested else '' lines = [] for l in raw.split('\n'): l = l.strip() lines.append(prepend + l if l else '') raw = '\n'.join(lines) # _Something_ is going to get printed. try: print(raw, end='') except UnicodeEncodeError: cleaned = raw.encode('ascii', 'replace').decode('ascii') print(cleaned, end='') # We really want a heterogeneous dict for this, but that's in typing_extensions def debug(*args: TV_Loggable, **kwargs: T.Any) -> None: arr = process_markup(args, False) if log_file is not None: print(*arr, file=log_file, **kwargs) log_file.flush() def _debug_log_cmd(cmd: str, args: T.List[str]) -> None: if not _in_ci: return args = [f'"{x}"' for x in args] # Quote all args, just in case debug('!meson_ci!/{} {}'.format(cmd, ' '.join(args))) def cmd_ci_include(file: str) -> None: _debug_log_cmd('ci_include', [file]) def log(*args: TV_Loggable, is_error: bool = False, once: bool = False, **kwargs: T.Any) -> None: if once: return log_once(*args, is_error=is_error, **kwargs) return _log(*args, is_error=is_error, **kwargs) def _log(*args: TV_Loggable, is_error: bool = False, **kwargs: T.Any) -> None: nested = kwargs.pop('nested', True) arr = process_markup(args, False) if log_file is not None: print(*arr, file=log_file, **kwargs) log_file.flush() if colorize_console(): arr = process_markup(args, True) if not log_errors_only or is_error: force_print(*arr, nested=nested, **kwargs) def log_once(*args: TV_Loggable, is_error: bool = False, **kwargs: T.Any) -> None: """Log variant that only prints a given message one time per meson invocation. This considers ansi decorated values by the values they wrap without regard for the AnsiDecorator itself. """ def to_str(x: TV_Loggable) -> str: if isinstance(x, str): return x if isinstance(x, AnsiDecorator): return x.text return str(x) t = tuple(to_str(a) for a in args) if t in _logged_once: return _logged_once.add(t) _log(*args, is_error=is_error, **kwargs) # This isn't strictly correct. What we really want here is something like: # class StringProtocol(typing_extensions.Protocol): # # def __str__(self) -> str: ... # # This would more accurately embody what this function can handle, but we # don't have that yet, so instead we'll do some casting to work around it def get_error_location_string(fname: str, lineno: str) -> str: return f'{fname}:{lineno}:' def _log_error(severity: str, *rargs: TV_Loggable, once: bool = False, fatal: bool = True, **kwargs: T.Any) -> None: from .mesonlib import MesonException, relpath # The typing requirements here are non-obvious. Lists are invariant, # therefore T.List[A] and T.List[T.Union[A, B]] are not able to be joined if severity == 'notice': label = [bold('NOTICE:')] # type: TV_LoggableList elif severity == 'warning': label = [yellow('WARNING:')] elif severity == 'error': label = [red('ERROR:')] elif severity == 'deprecation': label = [red('DEPRECATION:')] else: raise MesonException('Invalid severity ' + severity) # rargs is a tuple, not a list args = label + list(rargs) location = kwargs.pop('location', None) if location is not None: location_file = relpath(location.filename, os.getcwd()) location_str = get_error_location_string(location_file, location.lineno) # Unions are frankly awful, and we have to T.cast here to get mypy # to understand that the list concatenation is safe location_list = T.cast(TV_LoggableList, [location_str]) args = location_list + args log(*args, once=once, **kwargs) global log_warnings_counter log_warnings_counter += 1 if log_fatal_warnings and fatal: raise MesonException("Fatal warnings enabled, aborting") def error(*args: TV_Loggable, **kwargs: T.Any) -> None: return _log_error('error', *args, **kwargs, is_error=True) def warning(*args: TV_Loggable, **kwargs: T.Any) -> None: return _log_error('warning', *args, **kwargs, is_error=True) def deprecation(*args: TV_Loggable, **kwargs: T.Any) -> None: return _log_error('deprecation', *args, **kwargs, is_error=True) def notice(*args: TV_Loggable, **kwargs: T.Any) -> None: return _log_error('notice', *args, **kwargs, is_error=False) def get_relative_path(target: Path, current: Path) -> Path: """Get the path to target from current""" # Go up "current" until we find a common ancestor to target acc = ['.'] for part in [current, *current.parents]: try: path = target.relative_to(part) return Path(*acc, path) except ValueError: pass acc += ['..'] # we failed, should not get here return target def exception(e: Exception, prefix: T.Optional[AnsiDecorator] = None) -> None: if prefix is None: prefix = red('ERROR:') log() args = [] # type: T.List[T.Union[AnsiDecorator, str]] if all(getattr(e, a, None) is not None for a in ['file', 'lineno', 'colno']): # Mypy doesn't follow hasattr, and it's pretty easy to visually inspect # that this is correct, so we'll just ignore it. path = get_relative_path(Path(e.file), Path(os.getcwd())) # type: ignore args.append(f'{path}:{e.lineno}:{e.colno}:') # type: ignore if prefix: args.append(prefix) args.append(str(e)) log(*args) # Format a list for logging purposes as a string. It separates # all but the last item with commas, and the last with 'and'. def format_list(input_list: T.List[str]) -> str: l = len(input_list) if l > 2: return ' and '.join([', '.join(input_list[:-1]), input_list[-1]]) elif l == 2: return ' and '.join(input_list) elif l == 1: return input_list[0] else: return '' @contextmanager def nested(name: str = '') -> T.Generator[None, None, None]: global log_depth log_depth.append(name) try: yield finally: log_depth.pop()
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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 collections import OrderedDict from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.ads.googleads.v8.services.types import reach_plan_service from .transports.base import ReachPlanServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ReachPlanServiceGrpcTransport class ReachPlanServiceClientMeta(type): """Metaclass for the ReachPlanService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[ReachPlanServiceTransport]] _transport_registry["grpc"] = ReachPlanServiceGrpcTransport def get_transport_class( cls, label: str = None, ) -> Type[ReachPlanServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class ReachPlanServiceClient(metaclass=ReachPlanServiceClientMeta): """Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of people of specified demographics that can be reached by an ad in a given market by a campaign of certain duration with a defined budget. """ @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "googleads.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ReachPlanServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info( info ) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ReachPlanServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> ReachPlanServiceTransport: """Return the transport used by the client instance. Returns: ReachPlanServiceTransport: The transport used by the client instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Return a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str,) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str,) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str,) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str,) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match( r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path ) return m.groupdict() if m else {} def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ReachPlanServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the reach plan service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.ReachPlanServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool( util.strtobool( os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") ) ) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc # type: ignore cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, ReachPlanServiceTransport): # transport is a ReachPlanServiceTransport instance. if credentials: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = ReachPlanServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, ) def list_plannable_locations( self, request: reach_plan_service.ListPlannableLocationsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> reach_plan_service.ListPlannableLocationsResponse: r"""Returns the list of plannable locations (for example, countries & DMAs). List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.ListPlannableLocationsRequest`): The request object. Request message for [ReachPlanService.ListPlannableLocations][google.ads.googleads.v8.services.ReachPlanService.ListPlannableLocations]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.ListPlannableLocationsResponse: The list of plannable locations. """ # Create or coerce a protobuf request object. # Minor optimization to avoid making a copy if the user passes # in a reach_plan_service.ListPlannableLocationsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, reach_plan_service.ListPlannableLocationsRequest ): request = reach_plan_service.ListPlannableLocationsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.list_plannable_locations ] # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def list_plannable_products( self, request: reach_plan_service.ListPlannableProductsRequest = None, *, plannable_location_id: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> reach_plan_service.ListPlannableProductsResponse: r"""Returns the list of per-location plannable YouTube ad formats with allowed targeting. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.ListPlannableProductsRequest`): The request object. Request to list available products in a given location. plannable_location_id (:class:`str`): Required. The ID of the selected location for planning. To list the available plannable location ids use ListPlannableLocations. This corresponds to the ``plannable_location_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.ListPlannableProductsResponse: A response with all available products. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([plannable_location_id]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a reach_plan_service.ListPlannableProductsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, reach_plan_service.ListPlannableProductsRequest ): request = reach_plan_service.ListPlannableProductsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if plannable_location_id is not None: request.plannable_location_id = plannable_location_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.list_plannable_products ] # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def generate_product_mix_ideas( self, request: reach_plan_service.GenerateProductMixIdeasRequest = None, *, customer_id: str = None, plannable_location_id: str = None, currency_code: str = None, budget_micros: int = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> reach_plan_service.GenerateProductMixIdeasResponse: r"""Generates a product mix ideas given a set of preferences. This method helps the advertiser to obtain a good mix of ad formats and budget allocations based on its preferences. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `ReachPlanError <>`__ `RequestError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.GenerateProductMixIdeasRequest`): The request object. Request message for [ReachPlanService.GenerateProductMixIdeas][google.ads.googleads.v8.services.ReachPlanService.GenerateProductMixIdeas]. customer_id (:class:`str`): Required. The ID of the customer. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. plannable_location_id (:class:`str`): Required. The ID of the location, this is one of the ids returned by ListPlannableLocations. This corresponds to the ``plannable_location_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. currency_code (:class:`str`): Required. Currency code. Three-character ISO 4217 currency code. This corresponds to the ``currency_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. budget_micros (:class:`int`): Required. Total budget. Amount in micros. One million is equivalent to one unit. This corresponds to the ``budget_micros`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.GenerateProductMixIdeasResponse: The suggested product mix. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any( [customer_id, plannable_location_id, currency_code, budget_micros] ): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a reach_plan_service.GenerateProductMixIdeasRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, reach_plan_service.GenerateProductMixIdeasRequest ): request = reach_plan_service.GenerateProductMixIdeasRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if plannable_location_id is not None: request.plannable_location_id = plannable_location_id if currency_code is not None: request.currency_code = currency_code if budget_micros is not None: request.budget_micros = budget_micros # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.generate_product_mix_ideas ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def generate_reach_forecast( self, request: reach_plan_service.GenerateReachForecastRequest = None, *, customer_id: str = None, campaign_duration: reach_plan_service.CampaignDuration = None, planned_products: Sequence[reach_plan_service.PlannedProduct] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> reach_plan_service.GenerateReachForecastResponse: r"""Generates a reach forecast for a given targeting / product mix. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RangeError <>`__ `ReachPlanError <>`__ `RequestError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.GenerateReachForecastRequest`): The request object. Request message for [ReachPlanService.GenerateReachForecast][google.ads.googleads.v8.services.ReachPlanService.GenerateReachForecast]. customer_id (:class:`str`): Required. The ID of the customer. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. campaign_duration (:class:`google.ads.googleads.v8.services.types.CampaignDuration`): Required. Campaign duration. This corresponds to the ``campaign_duration`` field on the ``request`` instance; if ``request`` is provided, this should not be set. planned_products (:class:`Sequence[google.ads.googleads.v8.services.types.PlannedProduct]`): Required. The products to be forecast. The max number of allowed planned products is 15. This corresponds to the ``planned_products`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.GenerateReachForecastResponse: Response message containing the generated reach curve. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any( [customer_id, campaign_duration, planned_products] ): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a reach_plan_service.GenerateReachForecastRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, reach_plan_service.GenerateReachForecastRequest ): request = reach_plan_service.GenerateReachForecastRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if campaign_duration is not None: request.campaign_duration = campaign_duration if planned_products is not None: request.planned_products = planned_products # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.generate_reach_forecast ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response __all__ = ("ReachPlanServiceClient",)
#!/usr/bin/env python __docformat__ = 'reStructuredText' import argparse import numpy as np from scipy.constants import c, m_e, physical_constants from astropy import units as u def line_freq(Z, R_X, n, dn): """ Uses the Rydberg formula to get the frequency of a transition to quantum number n for a given atom. :param Z: Charge of the atom. :type Z: int :param R_X: :type R_X: float :param n: Principal quantum number of the transition. :math:`n+\\Delta n\\rightarrow n`. :type n: int :param dn: Difference between the principal quantum number of the initial state \ and the final state. :math:`\\Delta n=n_{f}-n_{i}`. :type dn: int :returns: The frequency of the transition in MHz. :rtype: float """ return (Z**2)*R_X*c*((1./(n**2))-(1./((n + dn)**2))) def set_specie(specie): """ Sets atomic constants based on the atomic specie. :param specie: Atomic specie. :type specie: string :returns: Array with the atomic mass in a.m.u., ionization potential, abundance relative to HI, :math:`V_{X}-V_{H}` and the electric charge. :Example: >>> set_specie('CI') [12.0, 11.4, 0.0003, 149.5, 1.0] """ # data for species (table 1 RG92) # [atomic.mass, ion.potential, abundance, V_X-V_H, Z] if 'HI' in specie: X = [1.0078,13.6,1.0,0.0,1.0] name = 'HI' if 'HeI' in specie: X = [4.0026,24.6,0.1,122.1,1.0] name = 'HeI' if 'CI' in specie: #X = [12.0000,11.4,3.e-4,149.5,6.0] X = [12.0000,11.4,3.e-4,149.5,1.0] name = 'CI' if 'NI' in specie: X = [14.0067,1,1,1,1.0] name = 'NI' if 'SI' in specie: #X = [37.9721,10.3,2.e-5,158.0,16.0] X = [37.9721,10.3,2.e-5,158.0,1.0] name = 'SI' # isotopes if 'CI13' in specie: X = [13.00335,-1.0,-1.0,-1.0,1.0] name = 'CI13' if 'CI14' in specie: X = [14.003241,-1.0,-1.0,-1.0,1.0] name = 'CI14' return X def set_trans(dn): """ Sets a name depending on the difference between atomic levels. :param dn: Separation between :math:`n_{i}` and :math:`n_{f}`, :math:`\\Delta n=n_{i}-n_{f}`. :type dn: int :returns: alpha, beta, gamma, delta or epsilon depending on :math:`\\Delta n`. :rtype: string :Example: >>> set_trans(5) 'epsilon' """ if dn == 1: name = 'alpha' if dn == 2: name = 'beta' if dn == 3: name = 'gamma' if dn == 4: name = 'delta' if dn == 5: name = 'epsilon' if dn == 6: name = 'zeta' if dn == 7: name = 'eta' return name def set_dn(name): """ Sets the value of Delta n depending on the transition name. :param name: Name of the transition. :type name: string :returns: :math:`\\Delta n` for the given transition. :rtype: int :Example: >>> set_dn('CIalpha') 1 >>> set_dn('CIdelta') 4 """ if 'alpha' in name: dn = 1 elif 'beta' in name: dn = 2 elif 'gamma' in name: dn = 3 elif 'delta' in name: dn = 4 elif 'epsilon' in name: dn = 5 elif 'zeta' in name: dn = 6 elif 'eta' in name: dn = 7 return dn def make_line_list(line, n_min=1, n_max=1500, unitless=True): """ Creates a list of frequencies for the corresponding line. The frequencies are in MHz. :param line: Line to compute the frequencies for. :type line: string :param n_min: Minimum n number to include in the list. :type n_min: int :param n_max: Maximum n number to include in the list. :type n_max: int :param unitless: If True the list will have no units. If not the list will be of astropy.units.Quantity_ objects. :type unitless: bool :returns: 3 lists with the line name, principal quantum number and frequency of the transitions. :rtype: list .. _astropy.units.Quantity: http://docs.astropy.org/en/stable/api/astropy.units.Quantity.html#astropy.units.Quantity """ n = np.arange(n_min, n_max) # Define the electron mass in atomic mass units m_e_amu = m_e/physical_constants['atomic mass constant'][0] # set the specie X = set_specie(line) dn = set_dn(line) trans = set_trans(dn) M_X = X[0] R_X = 10.97373/(1.0 + (m_e_amu/M_X)) Z = X[4] freq = line_freq(Z, R_X, n, dn) if not unitless: freq = freq*u.MHz return line, n, freq, trans def main(): """ Main body of the program. Useful for calling as a script. """ parser = argparse.ArgumentParser() parser.add_argument('-i', '--n_min', type=int, dest='n_min', default=1, help="Minimum n number") parser.add_argument('-n', '--n_max', type=int, dest='n_max', default=10000, help="Maximum n number") parser.add_argument('-l', '--line', dest='line', default='CI', type=str, help="Line name. E.g., CIalpha, HeIbeta, HIalpha, CI13alpha, CI14gamma or SIepsilon") args = parser.parse_args() n_min = args.n_min n_max = args.n_max line = args.line line, n, freq, trans = make_line_list(line, n_min, n_max) specie = line[:line.index(trans)] # Write the line list to a file out = 'RRL_{0}{1}.txt'.format(specie, trans) with open(out, 'w') as outf: outf.write('#SPECIES-NAME, TRANSITION-TYPE, N-LEVEL, FREQUENCY-[MHZ]\n') for i, ni in enumerate(n): outf.write('{0} {1} {2} {3}\n'.format(specie, trans, ni, freq[i])) if __name__ == '__main__': main()
""" Basic Linear Phase Digital Filter Design Helper Copyright (c) March 2017, Mark Wickert 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. """ import numpy as np import scipy.signal as signal import matplotlib.pyplot as plt from logging import getLogger log = getLogger(__name__) def firwin_lpf(n_taps, fc, fs = 1.0): """ Design a windowed FIR lowpass filter in terms of passband critical frequencies f1 < f2 in Hz relative to sampling rate fs in Hz. The number of taps must be provided. Mark Wickert October 2016 """ return signal.firwin(n_taps, 2 * fc / fs) def firwin_bpf(n_taps, f1, f2, fs = 1.0, pass_zero=False): """ Design a windowed FIR bandpass filter in terms of passband critical frequencies f1 < f2 in Hz relative to sampling rate fs in Hz. The number of taps must be provided. Mark Wickert October 2016 """ return signal.firwin(n_taps, 2 * (f1, f2) / fs, pass_zero=pass_zero) def firwin_kaiser_lpf(f_pass, f_stop, d_stop, fs = 1.0, n_bump=0, status = True): """ Design an FIR lowpass filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_pass Hz, f_stop Hz, and the desired stopband attenuation d_stop in dB, all relative to a sampling rate of fs Hz. Note: the passband ripple cannot be set independent of the stopband attenuation. Mark Wickert October 2016 """ wc = 2*np.pi*(f_pass + f_stop)/2/fs delta_w = 2*np.pi*(f_stop - f_pass)/fs # Find the filter order M = np.ceil((d_stop - 8)/(2.285*delta_w)) # Adjust filter order up or down as needed M += n_bump N_taps = M + 1 # Obtain the Kaiser window beta = signal.kaiser_beta(d_stop) w_k = signal.kaiser(N_taps,beta) n = np.arange(N_taps) b_k = wc/np.pi*np.sinc(wc/np.pi*(n-M/2)) * w_k b_k /= np.sum(b_k) if status: log.info('Kaiser Win filter taps = %d.' % N_taps) return b_k def firwin_kaiser_hpf(f_stop, f_pass, d_stop, fs = 1.0, n_bump=0, status = True): """ Design an FIR highpass filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_pass Hz, f_stop Hz, and the desired stopband attenuation d_stop in dB, all relative to a sampling rate of fs Hz. Note: the passband ripple cannot be set independent of the stopband attenuation. Mark Wickert October 2016 """ # Transform HPF critical frequencies to lowpass equivalent f_pass_eq = fs/2. - f_pass f_stop_eq = fs/2. - f_stop # Design LPF equivalent wc = 2*np.pi*(f_pass_eq + f_stop_eq)/2/fs delta_w = 2*np.pi*(f_stop_eq - f_pass_eq)/fs # Find the filter order M = np.ceil((d_stop - 8)/(2.285*delta_w)) # Adjust filter order up or down as needed M += n_bump N_taps = M + 1 # Obtain the Kaiser window beta = signal.kaiser_beta(d_stop) w_k = signal.kaiser(N_taps,beta) n = np.arange(N_taps) b_k = wc/np.pi*np.sinc(wc/np.pi*(n-M/2)) * w_k b_k /= np.sum(b_k) # Transform LPF equivalent to HPF n = np.arange(len(b_k)) b_k *= (-1)**n if status: log.info('Kaiser Win filter taps = %d.' % N_taps) return b_k def firwin_kaiser_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_stop, fs = 1.0, n_bump=0, status = True): """ Design an FIR bandpass filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the desired stopband attenuation d_stop in dB for both stopbands, all relative to a sampling rate of fs Hz. Note: the passband ripple cannot be set independent of the stopband attenuation. Mark Wickert October 2016 """ # Design BPF starting from simple LPF equivalent # The upper and lower stopbands are assumed to have # the same attenuation level. The LPF equivalent critical # frequencies: f_pass = (f_pass2 - f_pass1)/2 f_stop = (f_stop2 - f_stop1)/2 # Continue to design equivalent LPF wc = 2*np.pi*(f_pass + f_stop)/2/fs delta_w = 2*np.pi*(f_stop - f_pass)/fs # Find the filter order M = np.ceil((d_stop - 8)/(2.285*delta_w)) # Adjust filter order up or down as needed M += n_bump N_taps = M + 1 # Obtain the Kaiser window beta = signal.kaiser_beta(d_stop) w_k = signal.kaiser(N_taps,beta) n = np.arange(N_taps) b_k = wc/np.pi*np.sinc(wc/np.pi*(n-M/2)) * w_k b_k /= np.sum(b_k) # Transform LPF to BPF f0 = (f_pass2 + f_pass1)/2 w0 = 2*np.pi*f0/fs n = np.arange(len(b_k)) b_k_bp = 2*b_k*np.cos(w0*(n-M/2)) if status: log.info('Kaiser Win filter taps = %d.' % N_taps) return b_k_bp def firwin_kaiser_bsf(f_stop1, f_pass1, f_pass2, f_stop2, d_stop, fs = 1.0, n_bump=0, status = True): """ Design an FIR bandstop filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the desired stopband attenuation d_stop in dB for both stopbands, all relative to a sampling rate of fs Hz. Note: The passband ripple cannot be set independent of the stopband attenuation. Note: The filter order is forced to be even (odd number of taps) so there is a center tap that can be used to form 1 - H_BPF. Mark Wickert October 2016 """ # First design a BPF starting from simple LPF equivalent # The upper and lower stopbands are assumed to have # the same attenuation level. The LPF equivalent critical # frequencies: f_pass = (f_pass2 - f_pass1)/2 f_stop = (f_stop2 - f_stop1)/2 # Continue to design equivalent LPF wc = 2*np.pi*(f_pass + f_stop)/2/fs delta_w = 2*np.pi*(f_stop - f_pass)/fs # Find the filter order M = np.ceil((d_stop - 8)/(2.285*delta_w)) # Adjust filter order up or down as needed M += n_bump # Make filter order even (odd number of taps) if ((M+1)/2.0-int((M+1)/2.0)) == 0: M += 1 N_taps = M + 1 # Obtain the Kaiser window beta = signal.kaiser_beta(d_stop) w_k = signal.kaiser(N_taps,beta) n = np.arange(N_taps) b_k = wc/np.pi*np.sinc(wc/np.pi*(n-M/2)) * w_k b_k /= np.sum(b_k) # Transform LPF to BPF f0 = (f_pass2 + f_pass1)/2 w0 = 2*np.pi*f0/fs n = np.arange(len(b_k)) b_k_bs = 2*b_k*np.cos(w0*(n-M/2)) # Transform BPF to BSF via 1 - BPF for odd N_taps b_k_bs = -b_k_bs b_k_bs[int(M/2)] += 1 if status: log.info('Kaiser Win filter taps = %d.' % N_taps) return b_k_bs def lowpass_order(f_pass, f_stop, dpass_dB, dstop_dB, fsamp = 1): """ Optimal FIR (equal ripple) Lowpass Order Determination Text reference: Ifeachor, Digital Signal Processing a Practical Approach, second edition, Prentice Hall, 2002. Journal paper reference: Herriman et al., Practical Design Rules for Optimum Finite Imulse Response Digitl Filters, Bell Syst. Tech. J., vol 52, pp. 769-799, July-Aug., 1973.IEEE, 1973. """ dpass = 1 - 10**(-dpass_dB/20) dstop = 10**(-dstop_dB/20) Df = (f_stop - f_pass)/fsamp a1 = 5.309e-3 a2 = 7.114e-2 a3 = -4.761e-1 a4 = -2.66e-3 a5 = -5.941e-1 a6 = -4.278e-1 Dinf = np.log10(dstop)*(a1*np.log10(dpass)**2 + a2*np.log10(dpass) + a3) \ + (a4*np.log10(dpass)**2 + a5*np.log10(dpass) + a6) f = 11.01217 + 0.51244*(np.log10(dpass) - np.log10(dstop)) N = Dinf/Df - f*Df + 1 ff = 2*np.array([0, f_pass, f_stop, fsamp/2])/fsamp aa = np.array([1, 1, 0, 0]) wts = np.array([1.0, dpass/dstop]) return int(N), ff, aa, wts def bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2, dpass_dB, dstop_dB, fsamp = 1): """ Optimal FIR (equal ripple) Bandpass Order Determination Text reference: Ifeachor, Digital Signal Processing a Practical Approach, second edition, Prentice Hall, 2002. Journal paper reference: F. Mintzer & B. Liu, Practical Design Rules for Optimum FIR Bandpass Digital Filters, IEEE Transactions on Acoustics and Speech, pp. 204-206, April,1979. """ dpass = 1 - 10**(-dpass_dB/20) dstop = 10**(-dstop_dB/20) Df1 = (f_pass1 - f_stop1)/fsamp Df2 = (f_stop2 - f_pass2)/fsamp b1 = 0.01201 b2 = 0.09664 b3 = -0.51325 b4 = 0.00203 b5 = -0.5705 b6 = -0.44314 Df = min(Df1, Df2) Cinf = np.log10(dstop)*(b1*np.log10(dpass)**2 + b2*np.log10(dpass) + b3) \ + (b4*np.log10(dpass)**2 + b5*np.log10(dpass) + b6) g = -14.6*np.log10(dpass/dstop) - 16.9 N = Cinf/Df + g*Df + 1 ff = 2*np.array([0, f_stop1, f_pass1, f_pass2, f_stop2, fsamp/2])/fsamp aa = np.array([0, 0, 1, 1, 0, 0]) wts = np.array([dpass/dstop, 1, dpass/dstop]) return int(N), ff, aa, wts def bandstop_order(f_stop1, f_pass1, f_pass2, f_stop2, dpass_dB, dstop_dB, fsamp = 1): """ Optimal FIR (equal ripple) Bandstop Order Determination Text reference: Ifeachor, Digital Signal Processing a Practical Approach, second edition, Prentice Hall, 2002. Journal paper reference: F. Mintzer & B. Liu, Practical Design Rules for Optimum FIR Bandpass Digital Filters, IEEE Transactions on Acoustics and Speech, pp. 204-206, April,1979. """ dpass = 1 - 10**(-dpass_dB/20) dstop = 10**(-dstop_dB/20) Df1 = (f_pass1 - f_stop1)/fsamp Df2 = (f_stop2 - f_pass2)/fsamp b1 = 0.01201 b2 = 0.09664 b3 = -0.51325 b4 = 0.00203 b5 = -0.5705 b6 = -0.44314 Df = min(Df1, Df2) Cinf = np.log10(dstop)*(b1*np.log10(dpass)**2 + b2*np.log10(dpass) + b3) \ + (b4*np.log10(dpass)**2 + b5*np.log10(dpass) + b6) g = -14.6*np.log10(dpass/dstop) - 16.9 N = Cinf/Df + g*Df + 1 ff = 2*np.array([0, f_stop1, f_pass1, f_pass2, f_stop2, fsamp/2])/fsamp aa = np.array([1, 1, 0, 0, 1, 1]) wts = np.array([2, dpass/dstop, 2]) return int(N), ff, aa, wts def fir_remez_lpf(f_pass, f_stop, d_pass, d_stop, fs = 1.0, n_bump=5, status = True): """ Design an FIR lowpass filter using remez with order determination. The filter order is determined based on f_pass Hz, fstop Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016, updated October 2018 """ n, ff, aa, wts = lowpass_order(f_pass, f_stop, d_pass, d_stop, fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop N_taps = n N_taps += n_bump b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2) if status: log.info('Remez filter taps = %d.' % N_taps) return b def fir_remez_hpf(f_stop, f_pass, d_pass, d_stop, fs = 1.0, n_bump=5, status = True): """ Design an FIR highpass filter using remez with order determination. The filter order is determined based on f_pass Hz, fstop Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016, updated October 2018 """ # Transform HPF critical frequencies to lowpass equivalent f_pass_eq = fs/2. - f_pass f_stop_eq = fs/2. - f_stop # Design LPF equivalent n, ff, aa, wts = lowpass_order(f_pass_eq, f_stop_eq, d_pass, d_stop, fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop N_taps = n N_taps += n_bump b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2) # Transform LPF equivalent to HPF n = np.arange(len(b)) b *= (-1)**n if status: log.info('Remez filter taps = %d.' % N_taps) return b def fir_remez_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop, fs = 1.0, n_bump=5, status = True): """ Design an FIR bandpass filter using remez with order determination. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016, updated October 2018 """ n, ff, aa, wts = bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop, fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop N_taps = n N_taps += n_bump b = signal.remez(N_taps, ff, aa[0::2], wts,Hz=2) if status: log.info('Remez filter taps = %d.' % N_taps) return b def fir_remez_bsf(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop, fs = 1.0, n_bump=5, status = True): """ Design an FIR bandstop filter using remez with order determination. The filter order is determined based on f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the desired passband ripple d_pass dB and stopband attenuation d_stop dB all relative to a sampling rate of fs Hz. Mark Wickert October 2016, updated October 2018 """ n, ff, aa, wts = bandstop_order(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop, fsamp=fs) # Bump up the order by N_bump to bring down the final d_pass & d_stop # Initially make sure the number of taps is even so N_bump needs to be odd if np.mod(n,2) != 0: n += 1 N_taps = n N_taps += n_bump b = signal.remez(N_taps, ff, aa[0::2], wts, Hz=2, maxiter = 25, grid_density = 16) if status: log.info('N_bump must be odd to maintain odd filter length') log.info('Remez filter taps = %d.' % N_taps) return b def freqz_resp_list(b, a=np.array([1]), mode = 'dB', fs=1.0, n_pts = 1024, fsize=(6, 4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying the filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freqz_resp(b,a=[1],mode = 'dB',Npts = 1024,fsize=(6,4)) b = ndarray of numerator coefficients a = ndarray of denominator coefficents mode = display mode: 'dB' magnitude, 'phase' in radians, or 'groupdelay_s' in samples and 'groupdelay_t' in sec, all versus frequency in Hz Npts = number of points to plot; default is 1024 fsize = figure size; defult is (6,4) inches Mark Wickert, January 2015 """ if type(b) == list: # We have a list of filters N_filt = len(b) f = np.arange(0, n_pts) / (2.0 * n_pts) for n in range(N_filt): w,H = signal.freqz(b[n],a[n],2*np.pi*f) if n == 0: plt.figure(figsize=fsize) if mode.lower() == 'db': plt.plot(f*fs,20*np.log10(np.abs(H))) if n == N_filt-1: plt.xlabel('Frequency (Hz)') plt.ylabel('Gain (dB)') plt.title('Frequency Response - Magnitude') elif mode.lower() == 'phase': plt.plot(f*fs,np.angle(H)) if n == N_filt-1: plt.xlabel('Frequency (Hz)') plt.ylabel('Phase (rad)') plt.title('Frequency Response - Phase') elif (mode.lower() == 'groupdelay_s') or (mode.lower() == 'groupdelay_t'): """ Notes ----- Since this calculation involves finding the derivative of the phase response, care must be taken at phase wrapping points and when the phase jumps by +/-pi, which occurs when the amplitude response changes sign. Since the amplitude response is zero when the sign changes, the jumps do not alter the group delay results. """ theta = np.unwrap(np.angle(H)) # Since theta for an FIR filter is likely to have many pi phase # jumps too, we unwrap a second time 2*theta and divide by 2 theta2 = np.unwrap(2*theta)/2. theta_dif = np.diff(theta2) f_diff = np.diff(f) Tg = -np.diff(theta2)/np.diff(w) # For gain almost zero set groupdelay = 0 idx = np.nonzero(np.ravel(20*np.log10(H[:-1]) < -400))[0] Tg[idx] = np.zeros(len(idx)) max_Tg = np.max(Tg) #print(max_Tg) if mode.lower() == 'groupdelay_t': max_Tg /= fs plt.plot(f[:-1]*fs,Tg/fs) plt.ylim([0,1.2*max_Tg]) else: plt.plot(f[:-1]*fs,Tg) plt.ylim([0,1.2*max_Tg]) if n == N_filt-1: plt.xlabel('Frequency (Hz)') if mode.lower() == 'groupdelay_t': plt.ylabel('Group Delay (s)') else: plt.ylabel('Group Delay (samples)') plt.title('Frequency Response - Group Delay') else: s1 = 'Error, mode must be "dB", "phase, ' s2 = '"groupdelay_s", or "groupdelay_t"' log.info(s1 + s2)
# =========================================================================== # Using TIDIGITS dataset to predict gender (Boy, Girl, Woman, Man) # =========================================================================== # Saved WAV file format: # 0) [train|test] # 1) [m|w|b|g] (alias for man, women, boy, girl) # 2) [age] # 3) [dialectID] # 4) [speakerID] # 5) [production] # 6) [digit_sequence] # => "train_g_08_17_as_a_4291815" # =========================================================================== from __future__ import print_function, division, absolute_import import os import shutil from collections import defaultdict import numpy as np from odin import fuel as F, backend as K, visual as V from odin.utils import (cache_disk, ctext, unique_labels, Progbar, minibatch, get_exppath, get_formatted_datetime) from odin.stats import train_valid_test_split, sampling_iter _support_label = { 'other': 0, 'gender': 1, 'age': 2, 'dialect': 3, 'speaker': 4, 'production': 5, 'digit': 6, } # =========================================================================== # Const for path and features configuration # =========================================================================== PATH_EXP = get_exppath(tag='TIDIGITS', override=False) # ====== acoustic feature extraction ====== # PATH_ACOUSTIC = os.path.join(PATH_EXP, 'TIDIGITS_feat') class FeatureConfigs(object): padding = False sr = 8000 window = 'hamm' n_fft = 512 n_mels = 40 n_ceps = 40 fmin = 100 fmax = 4000 frame_length = 0.025 step_length = 0.010 dtype = 'float16' def get_exp_path(system_name, args, override=False): """ Return: exp_dir, model_path, log_path """ exp_dir = get_exppath(tag='TIDIGITS_%s_%s_%s' % (system_name, args.task, args.feat)) if 'nmix' in args: exp_dir += '_%d' % args.nmix if 'tdim' in args: exp_dir += '_%d' % args.tdim # ====== check override ====== # if bool(override) and os.path.exists(exp_dir): shutil.rmtree(exp_dir) if not os.path.exists(exp_dir): os.mkdir(exp_dir) # ====== basic paths ====== # model_path = os.path.join(exp_dir, 'model.ai') log_path = os.path.join(exp_dir, 'log_%s.txt' % get_formatted_datetime(only_number=True)) print("Exp dir:", ctext(exp_dir, 'cyan')) print("Model path:", ctext(model_path, 'cyan')) print("Log path:", ctext(log_path, 'cyan')) return exp_dir, model_path, log_path # =========================================================================== # For DNN # =========================================================================== def prepare_data(feat, label, utt_length=0.4, for_ivec=False): """ Returns (i-vector) ------------------ ds[feat] train_files y_train test_files y_test labels Returns (x-vector) ------------------ train : Feeder feeder for training data for iterating over pair of (X, y) valid : Feeder feeder for validating data for iterating over pair of (X, y) X_test_name : list of file names file names are append with '.%d' for cut segment ID X_test_true : list of integer label of each sample X_test_data : array list of test data same length as X_test_name labels : list of string list of labels for classification task Example ------- (train, valid, X_test_name, X_test_true, X_test_data, labels) = prepare_data_dnn(feat=FEAT, label='gender') """ label = str(label).lower() assert label in _support_label, "No support for label: %s" % label assert 0 < utt_length <= 1. # ====== load dataset ====== # if not os.path.exists(PATH_ACOUSTIC): raise RuntimeError("Cannot find extracted acoustic features at path: '%s'," "run the code speech_features_extraction.py!" % PATH_ACOUSTIC) ds = F.Dataset(PATH_ACOUSTIC, read_only=True) assert feat in ds, "Cannot find feature with name: %s" % feat indices = list(ds['indices'].items()) K.get_rng().shuffle(indices) # ====== helper ====== # def is_train(x): return x.split('_')[0] == 'train' def extract_label(x): return x.split('_')[_support_label[label]] print("Task:", ctext(label, 'cyan')) fn_label, labels = unique_labels([i[0] for i in indices], key_func=extract_label, return_labels=True) print("Labels:", ctext(labels, 'cyan')) # ====== training and test data ====== # train_files = [] # (name, (start, end)) ... test_files = [] for name, (start, end) in indices: if is_train(name): train_files.append((name, (start, end))) else: test_files.append((name, (start, end))) # name for each dataset, useful for later print("#Train:", ctext(len(train_files), 'cyan')) print("#Test:", ctext(len(test_files), 'cyan')) # ====== for i-vectors ====== # y_train = np.array([fn_label(i[0]) for i in train_files]) y_test = np.array([fn_label(i[0]) for i in test_files]) if bool(for_ivec): return ds[feat], train_files, y_train, test_files, y_test, labels # ====== length ====== # length = [(end - start) for _, (start, end) in indices] max_length = max(length) frame_length = int(max_length * utt_length) step_length = frame_length print("Max length :", ctext(max_length, 'yellow')) print("Frame length:", ctext(frame_length, 'yellow')) print("Step length :", ctext(step_length, 'yellow')) # ====== split dataset ====== # # split by speaker ID train_files, valid_files = train_valid_test_split( x=train_files, train=0.8, cluster_func=None, idfunc=lambda x: x[0].split('_')[4], # splited by speaker inc_test=False) print("#File train:", ctext(len(train_files), 'cyan')) print("#File valid:", ctext(len(valid_files), 'cyan')) print("#File test :", ctext(len(test_files), 'cyan')) recipes = [ F.recipes.Sequencing(frame_length=frame_length, step_length=step_length, end='pad', pad_mode='post', pad_value=0), F.recipes.Name2Label(converter_func=fn_label), F.recipes.LabelOneHot(nb_classes=len(labels), data_idx=-1) ] feeder_train = F.Feeder(F.IndexedData(ds[feat], indices=train_files), ncpu=6, batch_mode='batch') feeder_valid = F.Feeder(F.IndexedData(ds[feat], indices=valid_files), ncpu=4, batch_mode='batch') feeder_test = F.Feeder(F.IndexedData(ds[feat], indices=test_files), ncpu=4, batch_mode='file') feeder_train.set_recipes(recipes) feeder_valid.set_recipes(recipes) feeder_test.set_recipes(recipes) print(feeder_train) # ====== process X_test, y_test in advance for faster evaluation ====== # @cache_disk def _extract_test_data(feat, label, utt_length): prog = Progbar(target=len(feeder_test), print_summary=True, name="Preprocessing test set") X_test = defaultdict(list) for name, idx, X, y in feeder_test: # validate everything as expected assert fn_label(name) == np.argmax(y), name # label is right # save to list X_test[name].append((idx, X)) prog.add(X.shape[0]) # ====== create 1 array for data and dictionary for indices ====== # X_test_name = [] X_test_data = [] for name, X in X_test.items(): X = np.concatenate([x[1] for x in sorted(X, key=lambda i: i[0])], axis=0).astype('float16') X_test_name += [name + '.%d' % i for i in range(len(X))] X_test_data.append(X) X_test_name = np.array(X_test_name) X_test_data = np.concatenate(X_test_data, axis=0) return X_test_name, X_test_data # convert everything back to float32 X_test_name, X_test_data = _extract_test_data(feat, label, utt_length) X_test_true = np.array([fn_label(i.split('.')[0]) for i in X_test_name]) return feeder_train, feeder_valid, \ X_test_name, X_test_true, X_test_data, labels def make_dnn_prediction(functions, X, batch_size=256, title=''): return_list = True if not isinstance(functions, (tuple, list)): functions = [functions] return_list = False n_functions = len(functions) results = [[] for i in range(n_functions)] # ====== prepare progress bar ====== # n_samples = len(X) prog = Progbar(target=n_samples, print_summary=True, name="Making prediction: %s" % str(title)) # ====== for feeder ====== # if isinstance(X, F.Feeder): y_true = [] for x, y in X.set_batch(batch_size=batch_size): for res, fn in zip(results, functions): res.append(fn(x)) prog.add(x.shape[0]) y_true.append(np.argmax(y, axis=-1) if y.ndim == 2 else y) results = [np.concatenate(res, axis=0) for res in results] y_true = np.concatenate(y_true, axis=0) if return_list: return results, y_true return results[0], y_true # ====== for numpy array ====== # else: for start, end in minibatch(batch_size=batch_size, n=n_samples): y = X[start:end] for res, fn in zip(results, functions): res.append(fn(y)) prog.add(end - start) results = [np.concatenate(res, axis=0) for res in results] if return_list: return results return results[0] # =========================================================================== # visualization # =========================================================================== def visualize_latent_space(X_org, X_latent, name, labels, title): """ X_org : [n_samples, n_timesteps, n_features] X_latent : [n_samples, n_timesteps, n_latents] """ assert X_org.shape[0] == X_latent.shape[0] == len(name) == len(labels) assert not np.any(np.isnan(X_org)) assert not np.any(np.isnan(X_latent)) X_org = X_org.astype('float32') X_latent = X_latent.astype('float32') # ====== evaluation of the latent space ====== # n_channels = 1 if X_latent.ndim == 3 else int(np.prod(X_latent.shape[3:])) n_samples = X_org.shape[0] # 1 for original, 1 for mean channel, then the rest n_row = 1 + 1 + n_channels n_col = 3 V.plot_figure(nrow=n_row + 1, ncol=16) # only select 3 random sample for i, idx in enumerate( sampling_iter(it=range(n_samples), k= n_col, seed=1234)): x = X_org[idx] # latent tensor can be 3D or 4D z = X_latent[idx] if z.ndim > 3: z = np.reshape(z, newshape=(z.shape[0], z.shape[1], -1)) elif z.ndim == 2: z = np.reshape(z, newshape=(z.shape[0], z.shape[1], 1)) elif z.ndim == 3: pass else: raise ValueError("No support for z value: %s" % str(z.shape)) # plot original acoustic ax = V.plot_spectrogram(x.T, ax=(n_row, n_col, i + 1), title='Org') if i == 0: ax.set_title("[%s]'%s-%s'" % (str(title), str(name[idx]), str(labels[idx])), fontsize=8) else: ax.set_title("'%s-%s'" % (str(name[idx]), str(labels[idx])), fontsize=8) # plot the mean V.plot_spectrogram(np.mean(z, axis=-1).T, ax=(n_row, n_col, i + 4), title='Zmean') # plot first 25 channels if n_channels > 1: for j in range(min(8, n_channels)): V.plot_spectrogram(z[:, :, j].T, ax=(n_row, n_col, j * 3 + 7 + i), title='Z%d' % j)
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Legacy script to plot distribution of certain classes onto chromosomes. Adapted from the script used in the Tang et al. PNAS 2010 paper, sigma figure. """ import sys import logging from math import ceil from itertools import groupby import numpy as np from jcvi.formats.base import DictFile from jcvi.formats.bed import Bed from jcvi.graphics.glyph import RoundRect from jcvi.graphics.base import plt, Rectangle, Polygon, CirclePolygon, savefig from jcvi.graphics.glyph import BaseGlyph, plot_cap from jcvi.apps.base import OptionParser class Chromosome (BaseGlyph): def __init__(self, ax, x, y1, y2, width=.015, ec="k", patch=None, patchcolor='lightgrey', lw=1, fc="k", zorder=2): """ Chromosome with positions given in (x, y1) => (x, y2) The chromosome can also be patched, e.g. to show scaffold composition in alternating shades. Use a list of starting locations to segment. """ y1, y2 = sorted((y1, y2)) super(Chromosome, self).__init__(ax) pts, r = self.get_pts(x, y1, y2, width) self.append(Polygon(pts, fill=False, lw=lw, ec=ec, zorder=zorder)) if patch: rr = r * .9 # Shrink a bit for the patches for i in xrange(0, len(patch), 2): if i + 1 > len(patch) - 1: continue p1, p2 = patch[i], patch[i + 1] self.append(Rectangle((x - rr, p1), 2 * rr, p2 - p1, lw=0, fc=patchcolor)) self.add_patches() def get_pts(self, x, y1, y2, width): w = width / 2 r = width / (3 ** .5) pts = [] pts += plot_cap((x, y1 + r), np.radians(range(210, 330)), r) pts += [[x + w, y1 + r / 2], [x + w, y2 - r / 2]] pts += plot_cap((x, y2 - r), np.radians(range(30, 150)), r) pts += [[x - w, y2 - r / 2], [x - w, y1 + r / 2]] return pts, r class HorizontalChromosome (BaseGlyph): def __init__(self, ax, x1, x2, y, height=.015, ec="k", patch=None, patchcolor='lightgrey', lw=1, fc=None, zorder=2, roundrect=False): """ Horizontal version of the Chromosome glyph above. """ x1, x2 = sorted((x1, x2)) super(HorizontalChromosome, self).__init__(ax) pts, r = self.get_pts(x1, x2, y, height) if roundrect: RoundRect(ax, (x1, y - height * .5), x2 - x1, height, fill=False, lw=lw, ec=ec, zorder=zorder + 1) else: self.append(Polygon(pts, fill=False, lw=lw, ec=ec, zorder=zorder)) if fc: pts, r = self.get_pts(x1, x2, y, height / 2) if roundrect: RoundRect(ax, (x1, y - height / 4), x2 - x1, height / 2, fc=fc, lw=0, zorder=zorder) else: self.append(Polygon(pts, fc=fc, lw=0, zorder=zorder)) if patch: rr = r * .9 # Shrink a bit for the patches for i in xrange(0, len(patch), 2): if i + 1 > len(patch) - 1: continue p1, p2 = patch[i], patch[i + 1] self.append(Rectangle((p1, y - rr), p2 - p1, 2 * rr, lw=0, fc=patchcolor)) self.add_patches() def get_pts(self, x1, x2, y, height): h = height / 2 r = height / (3 ** .5) if x2 - x1 < 2 * height: # rectangle for small chromosomes return [[x1, y + h], [x1, y - h], [x2, y - h], [x2, y + h]], r pts = [] pts += plot_cap((x1 + r, y), np.radians(range(120, 240)), r) pts += [[x1 + r / 2, y - h], [x2 - r / 2, y - h]] pts += plot_cap((x2 - r, y), np.radians(range(-60, 60)), r) pts += [[x2 - r / 2, y + h], [x1 + r / 2, y + h]] return pts, r class ChromosomeWithCentromere (object): def __init__(self, ax, x, y1, y2, y3, width=.015, fc="k", fill=False, zorder=2): """ Chromosome with centromeres at y2 position """ pts = [] r = width * .5 pts += plot_cap((x, y1 - r), np.radians(range(180)), r) pts += [[x - r, y1 - r], [x - r, y2 + r]] pts += plot_cap((x, y2 + r), np.radians(range(180, 360)), r) pts += [[x + r, y2 + r], [x + r, y1 - r]] ax.add_patch(Polygon(pts, fc=fc, fill=fill, zorder=zorder)) pts = [] pts += plot_cap((x, y2 - r), np.radians(range(180)), r) pts += [[x - r, y2 - r], [x - r, y3 + r]] pts += plot_cap((x, y3 + r), np.radians(range(180, 360)), r) pts += [[x + r, y3 + r], [x + r, y2 - r]] ax.add_patch(Polygon(pts, fc=fc, fill=fill, zorder=zorder)) ax.add_patch(CirclePolygon((x, y2), radius=r * .5, fc="k", ec="k", zorder=zorder)) class ChromosomeMap (object): """ Line plots along the chromosome. """ def __init__(self, fig, root, xstart, xend, ystart, yend, pad, ymin, ymax, bins, title, subtitle, patchstart=None): width, height = xend - xstart, yend - ystart y = ystart - pad HorizontalChromosome(root, xstart, xend, y, patch=patchstart, height=.03) # Gauge lsg = "lightslategrey" root.plot([xstart - pad, xstart - pad], [ystart, ystart + height], lw=2, color=lsg) root.plot([xend + pad, xend + pad], [ystart, ystart + height], lw=2, color=lsg) root.text((xstart + xend) / 2, ystart + height + 2 * pad, title, ha="center", va="center", color=lsg) iv = (ymax - ymin) / bins iv_height = height / bins val = ymin yy = ystart while val <= ymax: root.text(xstart - 2 * pad, yy, str(val), ha="right", va="center", size=10) val += iv yy += iv_height root.text((xstart + xend) / 2, y - .05, subtitle, ha="center", va="center", color=lsg) self.axes = fig.add_axes([xstart, ystart, width, height]) class GeneticMap (BaseGlyph): def __init__(self, ax, x, y1, y2, markers, unit="cM", tip=.008, fc="k", flip=False): # tip = length of the ticks y1, y2 = sorted((y1, y2)) ax.plot([x, x], [y1, y2], '-', color=fc, lw=2) max_marker_name, max_chr_len = max(markers, key=lambda x: x[-1]) r = y2 - y1 ratio = r / max_chr_len marker_pos = {} for marker_name, cm in markers: yy = (y1 + ratio * cm) if flip else (y2 - ratio * cm) ax.plot((x - tip, x + tip), (yy, yy), "-", color=fc) marker_pos[marker_name] = yy self.marker_pos = marker_pos t = tip / 2 end_cm_labels = ((y2 + t, max_chr_len, "bottom"), (y1 - t, 0, "top")) if flip \ else ((y2 + t, 0, "bottom"), (y1 - t, max_chr_len, "top")) for yy, cm, va in end_cm_labels: label = "{0} {1}".format(int(cm), unit) ax.text(x, yy, label, color="gray", va=va, ha="center") class Gauge (BaseGlyph): def __init__(self, ax, x, y1, y2, max_chr_len, step=1e6, tip=.008, extra=.006, fc="b"): # tip = length of the ticks # extra = offset for the unit label ax.plot([x, x], [y1, y2], '-', color=fc, lw=2) r = y2 - y1 yy = y2 gauge = int(ceil(max_chr_len / step)) ratio = r / max_chr_len yinterval = 2 * ratio * step for g in xrange(0, gauge, 2): if g % 10: ax.plot((x, x + tip), (yy, yy), "-", color=fc) else: ax.plot((x - tip, x + tip), (yy, yy), '-', color=fc, lw=2) ax.text(x + tip + extra, yy, g, color="gray", va="center") yy -= yinterval ax.text(x, yy - .03, "Mb", color="gray", va="center") def canvas2px(coord, dmn, dpi): """ Convert matplotlib canvas coordinate to pixels """ return int(round(coord * dmn * dpi)) def write_ImageMapLine(tlx, tly, brx, bry, w, h, dpi, chr, segment_start, segment_end): """ Write out an image map area line with the coordinates passed to this function <area shape="rect" coords="tlx,tly,brx,bry" href="#chr7" title="chr7:100001..500001"> """ tlx, brx = [canvas2px(x, w, dpi) for x in (tlx, brx)] tly, bry = [canvas2px(y, h, dpi) for y in (tly, bry)] chr, bac_list = chr.split(':') return '<area shape="rect" coords="' + \ ",".join(str(x) for x in (tlx, tly, brx, bry)) \ + '" href="#' + chr + '"' \ + ' title="' + chr + ':' + str(segment_start) + '..' + str(segment_end) + '"' \ + ' />' def main(): """ %prog bedfile id_mappings Takes a bedfile that contains the coordinates of features to plot on the chromosomes, and `id_mappings` file that map the ids to certain class. Each class will get assigned a unique color. `id_mappings` file is optional (if omitted, will not paint the chromosome features, except the centromere). """ p = OptionParser(main.__doc__) p.add_option("--title", default="Medicago truncatula v3.5", help="title of the image [default: `%default`]") p.add_option("--gauge", default=False, action="store_true", help="draw a gauge with size label [default: %default]") p.add_option("--imagemap", default=False, action="store_true", help="generate an HTML image map associated with the image [default: %default]") p.add_option("--winsize", default=50000, type="int", help="if drawing an imagemap, specify the window size (bases) of each map element " "[default: %default bp]") p.add_option("--empty", help="Write legend for unpainted region") opts, args, iopts = p.set_image_options(figsize="6x6", dpi=300) if len(args) not in (1, 2): sys.exit(p.print_help()) bedfile = args[0] mappingfile = None if len(args) == 2: mappingfile = args[1] winsize = opts.winsize imagemap = opts.imagemap w, h = iopts.w, iopts.h dpi = iopts.dpi prefix = bedfile.rsplit(".", 1)[0] figname = prefix + "." + opts.format if imagemap: imgmapfile = prefix + '.map' mapfh = open(imgmapfile, "w") print >> mapfh, '<map id="' + prefix + '">' if mappingfile: mappings = DictFile(mappingfile, delimiter="\t") classes = sorted(set(mappings.values())) logging.debug("A total of {0} classes found: {1}".format(len(classes), ','.join(classes))) else: mappings = {} classes = [] logging.debug("No classes registered (no id_mappings given).") mycolors = "rgbymc" class_colors = dict(zip(classes, mycolors)) bed = Bed(bedfile) chr_lens = {} centromeres = {} for b, blines in groupby(bed, key=(lambda x: x.seqid)): blines = list(blines) maxlen = max(x.end for x in blines) chr_lens[b] = maxlen for b in bed: accn = b.accn if accn == "centromere": centromeres[b.seqid] = b.start if accn in mappings: b.accn = mappings[accn] else: b.accn = '-' chr_number = len(chr_lens) if centromeres: assert chr_number == len(centromeres) fig = plt.figure(1, (w, h)) root = fig.add_axes([0, 0, 1, 1]) r = .7 # width and height of the whole chromosome set xstart, ystart = .15, .85 xinterval = r / chr_number xwidth = xinterval * .5 # chromosome width max_chr_len = max(chr_lens.values()) ratio = r / max_chr_len # canvas / base # first the chromosomes for a, (chr, clen) in enumerate(sorted(chr_lens.items())): xx = xstart + a * xinterval + .5 * xwidth root.text(xx, ystart + .01, chr, ha="center") if centromeres: yy = ystart - centromeres[chr] * ratio ChromosomeWithCentromere(root, xx, ystart, yy, ystart - clen * ratio, width=xwidth) else: Chromosome(root, xx, ystart, ystart - clen * ratio, width=xwidth) chr_idxs = dict((a, i) for i, a in enumerate(sorted(chr_lens.keys()))) alpha = .75 # color the regions for chr in sorted(chr_lens.keys()): segment_size, excess = 0, 0 bac_list = [] for b in bed.sub_bed(chr): clen = chr_lens[chr] idx = chr_idxs[chr] klass = b.accn start = b.start end = b.end xx = xstart + idx * xinterval yystart = ystart - end * ratio yyend = ystart - start * ratio root.add_patch(Rectangle((xx, yystart), xwidth, yyend - yystart, fc=class_colors.get(klass, "w"), lw=0, alpha=alpha)) if imagemap: """ `segment` : size of current BAC being investigated + `excess` `excess` : left-over bases from the previous BAC, as a result of iterating over `winsize` regions of `segment` """ if excess == 0: segment_start = start segment = (end - start + 1) + excess while True: if segment < winsize: bac_list.append(b.accn) excess = segment break segment_end = segment_start + winsize - 1 tlx, tly, brx, bry = xx, (1 - ystart) + segment_start * ratio, \ xx + xwidth, (1 - ystart) + segment_end * ratio print >> mapfh, '\t' + write_ImageMapLine(tlx, tly, brx, bry, \ w, h, dpi, chr+":"+",".join(bac_list), segment_start, segment_end) segment_start += winsize segment -= winsize bac_list = [] if imagemap and excess > 0: bac_list.append(b.accn) segment_end = end tlx, tly, brx, bry = xx, (1 - ystart) + segment_start * ratio, \ xx + xwidth, (1 - ystart) + segment_end * ratio print >> mapfh, '\t' + write_ImageMapLine(tlx, tly, brx, bry, \ w, h, dpi, chr+":"+",".join(bac_list), segment_start, segment_end) if imagemap: print >> mapfh, '</map>' mapfh.close() logging.debug("Image map written to `{0}`".format(mapfh.name)) if opts.gauge: xstart, ystart = .9, .85 Gauge(root, xstart, ystart - r, ystart, max_chr_len) # class legends, four in a row xstart = .1 xinterval = .2 xwidth = .04 yy = .08 for klass, cc in sorted(class_colors.items()): if klass == '-': continue root.add_patch(Rectangle((xstart, yy), xwidth, xwidth, fc=cc, lw=0, alpha=alpha)) root.text(xstart + xwidth + .01, yy, klass, fontsize=10) xstart += xinterval empty = opts.empty if empty: root.add_patch(Rectangle((xstart, yy), xwidth, xwidth, fill=False, lw=1)) root.text(xstart + xwidth + .01, yy, empty, fontsize=10) root.text(.5, .95, opts.title, fontstyle="italic", ha="center", va="center") root.set_xlim(0, 1) root.set_ylim(0, 1) root.set_axis_off() savefig(figname, dpi=dpi, iopts=iopts) if __name__ == '__main__': main()
# Copyright 2019 The TensorFlow Authors, The Hugging Face Team. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions and classes related to optimization (weight updates).""" import re from typing import Callable, List, Optional, Union import tensorflow as tf class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule): """ Applies a warmup schedule on a given learning rate decay schedule. Args: initial_learning_rate (`float`): The initial learning rate for the schedule after the warmup (so this will be the learning rate at the end of the warmup). decay_schedule_fn (`Callable`): The schedule function to apply after the warmup for the rest of training. warmup_steps (`int`): The number of steps for the warmup part of training. power (`float`, *optional*, defaults to 1): The power to use for the polynomial warmup (defaults is a linear warmup). name (`str`, *optional*): Optional name prefix for the returned tensors during the schedule. """ def __init__( self, initial_learning_rate: float, decay_schedule_fn: Callable, warmup_steps: int, power: float = 1.0, name: str = None, ): super().__init__() self.initial_learning_rate = initial_learning_rate self.warmup_steps = warmup_steps self.power = power self.decay_schedule_fn = decay_schedule_fn self.name = name def __call__(self, step): with tf.name_scope(self.name or "WarmUp") as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. global_step_float = tf.cast(step, tf.float32) warmup_steps_float = tf.cast(self.warmup_steps, tf.float32) warmup_percent_done = global_step_float / warmup_steps_float warmup_learning_rate = self.initial_learning_rate * tf.math.pow(warmup_percent_done, self.power) return tf.cond( global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: self.decay_schedule_fn(step - self.warmup_steps), name=name, ) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name, } def create_optimizer( init_lr: float, num_train_steps: int, num_warmup_steps: int, min_lr_ratio: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-8, weight_decay_rate: float = 0.0, power: float = 1.0, include_in_weight_decay: Optional[List[str]] = None, ): """ Creates an optimizer with a learning rate schedule using a warmup phase followed by a linear decay. Args: init_lr (`float`): The desired learning rate at the end of the warmup phase. num_train_steps (`int`): The total number of training steps. num_warmup_steps (`int`): The number of warmup steps. min_lr_ratio (`float`, *optional*, defaults to 0): The final learning rate at the end of the linear decay will be `init_lr * min_lr_ratio`. adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 to use in Adam. adam_beta2 (`float`, *optional*, defaults to 0.999): The beta2 to use in Adam. adam_epsilon (`float`, *optional*, defaults to 1e-8): The epsilon to use in Adam. weight_decay_rate (`float`, *optional*, defaults to 0): The weight decay to use. power (`float`, *optional*, defaults to 1.0): The power to use for PolynomialDecay. include_in_weight_decay (`List[str]`, *optional*): List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is applied to all parameters except bias and layer norm parameters. """ # Implements linear decay of the learning rate. lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=init_lr, decay_steps=num_train_steps - num_warmup_steps, end_learning_rate=init_lr * min_lr_ratio, power=power, ) if num_warmup_steps: lr_schedule = WarmUp( initial_learning_rate=init_lr, decay_schedule_fn=lr_schedule, warmup_steps=num_warmup_steps, ) if weight_decay_rate > 0.0: optimizer = AdamWeightDecay( learning_rate=lr_schedule, weight_decay_rate=weight_decay_rate, beta_1=adam_beta1, beta_2=adam_beta2, epsilon=adam_epsilon, exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"], include_in_weight_decay=include_in_weight_decay, ) else: optimizer = tf.keras.optimizers.Adam( learning_rate=lr_schedule, beta_1=adam_beta1, beta_2=adam_beta2, epsilon=adam_epsilon ) # We return the optimizer and the LR scheduler in order to better track the # evolution of the LR independently of the optimizer. return optimizer, lr_schedule class AdamWeightDecay(tf.keras.optimizers.Adam): """ Adam enables L2 weight decay and clip_by_global_norm on gradients. Just adding the square of the weights to the loss function is *not* the correct way of using L2 regularization/weight decay with Adam, since that will interact with the m and v parameters in strange ways as shown in [Decoupled Weight Decay Regularization](https://arxiv.org/abs/1711.05101). Instead we want ot decay the weights in a manner that doesn't interact with the m/v parameters. This is equivalent to adding the square of the weights to the loss with plain (non-momentum) SGD. Args: learning_rate (`Union[float, tf.keras.optimizers.schedules.LearningRateSchedule]`, *optional*, defaults to 1e-3): The learning rate to use or a schedule. beta_1 (`float`, *optional*, defaults to 0.9): The beta1 parameter in Adam, which is the exponential decay rate for the 1st momentum estimates. beta_2 (`float`, *optional*, defaults to 0.999): The beta2 parameter in Adam, which is the exponential decay rate for the 2nd momentum estimates. epsilon (`float`, *optional*, defaults to 1e-7): The epsilon parameter in Adam, which is a small constant for numerical stability. amsgrad (`bool`, *optional*, default to `False`): Whether to apply AMSGrad variant of this algorithm or not, see [On the Convergence of Adam and Beyond](https://arxiv.org/abs/1904.09237). weight_decay_rate (`float`, *optional*, defaults to 0): The weight decay to apply. include_in_weight_decay (`List[str]`, *optional*): List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is applied to all parameters by default (unless they are in `exclude_from_weight_decay`). exclude_from_weight_decay (`List[str]`, *optional*): List of the parameter names (or re patterns) to exclude from applying weight decay to. If a `include_in_weight_decay` is passed, the names in it will supersede this list. name (`str`, *optional*, defaults to 'AdamWeightDecay'): Optional name for the operations created when applying gradients. kwargs: Keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use `learning_rate` instead. """ def __init__( self, learning_rate: Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001, beta_1: float = 0.9, beta_2: float = 0.999, epsilon: float = 1e-7, amsgrad: bool = False, weight_decay_rate: float = 0.0, include_in_weight_decay: Optional[List[str]] = None, exclude_from_weight_decay: Optional[List[str]] = None, name: str = "AdamWeightDecay", **kwargs ): super().__init__(learning_rate, beta_1, beta_2, epsilon, amsgrad, name, **kwargs) self.weight_decay_rate = weight_decay_rate self._include_in_weight_decay = include_in_weight_decay self._exclude_from_weight_decay = exclude_from_weight_decay @classmethod def from_config(cls, config): """Creates an optimizer from its config with WarmUp custom object.""" custom_objects = {"WarmUp": WarmUp} return super(AdamWeightDecay, cls).from_config(config, custom_objects=custom_objects) def _prepare_local(self, var_device, var_dtype, apply_state): super(AdamWeightDecay, self)._prepare_local(var_device, var_dtype, apply_state) apply_state[(var_device, var_dtype)]["weight_decay_rate"] = tf.constant( self.weight_decay_rate, name="adam_weight_decay_rate" ) def _decay_weights_op(self, var, learning_rate, apply_state): do_decay = self._do_use_weight_decay(var.name) if do_decay: return var.assign_sub( learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"], use_locking=self._use_locking, ) return tf.no_op() def apply_gradients(self, grads_and_vars, name=None, **kwargs): grads, tvars = list(zip(*grads_and_vars)) return super(AdamWeightDecay, self).apply_gradients(zip(grads, tvars), name=name, **kwargs) def _get_lr(self, var_device, var_dtype, apply_state): """Retrieves the learning rate with the given state.""" if apply_state is None: return self._decayed_lr_t[var_dtype], {} apply_state = apply_state or {} coefficients = apply_state.get((var_device, var_dtype)) if coefficients is None: coefficients = self._fallback_apply_state(var_device, var_dtype) apply_state[(var_device, var_dtype)] = coefficients return coefficients["lr_t"], dict(apply_state=apply_state) def _resource_apply_dense(self, grad, var, apply_state=None): lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state) decay = self._decay_weights_op(var, lr_t, apply_state) with tf.control_dependencies([decay]): return super(AdamWeightDecay, self)._resource_apply_dense(grad, var, **kwargs) def _resource_apply_sparse(self, grad, var, indices, apply_state=None): lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state) decay = self._decay_weights_op(var, lr_t, apply_state) with tf.control_dependencies([decay]): return super(AdamWeightDecay, self)._resource_apply_sparse(grad, var, indices, **kwargs) def get_config(self): config = super().get_config() config.update({"weight_decay_rate": self.weight_decay_rate}) return config def _do_use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if self.weight_decay_rate == 0: return False if self._include_in_weight_decay: for r in self._include_in_weight_decay: if re.search(r, param_name) is not None: return True if self._exclude_from_weight_decay: for r in self._exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True # Extracted from https://github.com/OpenNMT/OpenNMT-tf/blob/master/opennmt/optimizers/utils.py class GradientAccumulator(object): """ Gradient accumulation utility. When used with a distribution strategy, the accumulator should be called in a replica context. Gradients will be accumulated locally on each replica and without synchronization. Users should then call `.gradients`, scale the gradients if required, and pass the result to `apply_gradients`. """ # We use the ON_READ synchronization policy so that no synchronization is # performed on assignment. To get the value, we call .value() which returns the # value on the current replica without synchronization. def __init__(self): """Initializes the accumulator.""" self._gradients = [] self._accum_steps = None @property def step(self): """Number of accumulated steps.""" if self._accum_steps is None: self._accum_steps = tf.Variable( tf.constant(0, dtype=tf.int64), trainable=False, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, ) return self._accum_steps.value() @property def gradients(self): """The accumulated gradients on the current replica.""" if not self._gradients: raise ValueError("The accumulator should be called first to initialize the gradients") return list(gradient.value() if gradient is not None else gradient for gradient in self._gradients) def __call__(self, gradients): """Accumulates `gradients` on the current replica.""" if not self._gradients: _ = self.step # Create the step variable. self._gradients.extend( [ tf.Variable( tf.zeros_like(gradient), trainable=False, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, ) if gradient is not None else gradient for gradient in gradients ] ) if len(gradients) != len(self._gradients): raise ValueError(f"Expected {len(self._gradients)} gradients, but got {len(gradients)}") for accum_gradient, gradient in zip(self._gradients, gradients): if accum_gradient is not None and gradient is not None: accum_gradient.assign_add(gradient) self._accum_steps.assign_add(1) def reset(self): """Resets the accumulated gradients on the current replica.""" if not self._gradients: return self._accum_steps.assign(0) for gradient in self._gradients: if gradient is not None: gradient.assign(tf.zeros_like(gradient))
import tensorflow as tf import numpy as np import pickle import sys """ gives back self.pred, self. """ class vggnet(object): def __init__(self, isLoad, isTrain): self._get_variables(isLoad) self._init_weight_masks(isLoad) # self.conv_network() def loss(logits, labels): """for constructing the graph""" labels = tf.cast(labels, tf.int64) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logtis, labels, name = 'cross_entropy_batchwise') cross_entropy_mean = tf.reduce_mean(cross_entropy, name = 'cross_entropy') """ puts cross entropy as a loss into collection potentially, there can be L1 and L2 losses added to this "losses" term in collections """ tf.add_to_collection('losses', cross_entropy_mean) def error_rates(self,topk = 1): """ Args: self.pred: shape [B,C]. self.labels: shape [B]. topk(int): topk Returns: a float32 vector of length N with 0/1 values. 1 means incorrect prediction. """ return tf.cast(tf.logical_not(tf.nn.in_top_k(self.pred, self.labels, topk)), tf.float32) def conv_network(self, images, keep_prob): self.keep_prob = keep_prob imgs = images conv1_1 = self.conv_layer(imgs, 'conv1_1', padding = 'SAME', prune = True) conv1_2 = self.conv_layer(conv1_1, 'conv1_2', padding = 'SAME', prune = True) pool1 = self.maxpool(conv1_2, 'pool1', 2, 2, padding = 'SAME') conv2_1 = self.conv_layer(pool1, 'conv2_1', padding = 'SAME', prune = True) conv2_2 = self.conv_layer(conv2_1, 'conv2_2', padding = 'SAME', prune = True) pool2 = self.maxpool(conv2_2, 'pool2', 2, 2, padding = 'SAME') conv3_1 = self.conv_layer(pool2, 'conv3_1', padding = 'SAME', prune = True) conv3_2 = self.conv_layer(conv3_1, 'conv3_2', padding = 'SAME', prune = True) conv3_3 = self.conv_layer(conv3_2, 'conv3_3', padding = 'SAME', prune = True) pool3 = self.maxpool(conv3_3, 'pool3', 2, 2, padding = 'SAME') conv4_1 = self.conv_layer(pool3, 'conv4_1', padding = 'SAME', prune = True) conv4_2 = self.conv_layer(conv4_1, 'conv4_2', padding = 'SAME', prune = True) conv4_3 = self.conv_layer(conv4_2, 'conv4_3', padding = 'SAME', prune = True) pool4 = self.maxpool(conv4_3, 'pool4', 2, 2, padding = 'SAME') conv5_1 = self.conv_layer(pool4, 'conv5_1', padding = 'SAME', prune = True) conv5_2 = self.conv_layer(conv5_1, 'conv5_2', padding = 'SAME', prune = True) conv5_3 = self.conv_layer(conv5_2, 'conv5_3', padding = 'SAME', prune = True) pool5 = self.maxpool(conv5_3, 'pool5', 2, 2, padding = 'SAME') shape = int(np.prod(pool5.get_shape()[1:])) flattened = tf.reshape(pool5, [-1, shape]) fc6 = self.fc_layer(flattened, 'fc6', prune = True) fc6_drop = self.dropout_layer(fc6) # norm6 = self.batch_norm(fc6, 'norm6', train_phase = self.isTrain) fc7 = self.fc_layer(fc6_drop, 'fc7', prune = True) fc7_drop = self.dropout_layer(fc7) # norm7 = self.batch_norm(fc7, 'norm7', train_phase = self.isTrain) fc8 = self.fc_layer(fc7_drop, 'fc8', prune = True, apply_relu = False) self.pred = fc8 return self.pred def maxpool(self, x, name, filter_size, stride, padding = 'SAME'): return tf.nn.max_pool(x, ksize = [1, filter_size, filter_size, 1], strides = [1, stride, stride, 1], padding = padding, name = name) def lrn(self, x, name, depth_radius = 2, bias = 1.0, alpha = 2e-5, beta = 0.75): """ local response normalization ref: https://www.tensorflow.org/api_docs/python/tf/nn/local_response_normalization """ return tf.nn.lrn(x, depth_radius = depth_radius, bias = bias, alpha = alpha, beta = beta, name = name) def batch_norm(self, x, name, train_phase, data_format = 'NHWC', epsilon = 1e-3): """ TODO: this batch norm has an error refs: 1. https://github.com/ppwwyyxx/tensorpack/blob/a3674b47bfbf0c8b04aaa85d428b109fea0128ca/tensorpack/models/batch_norm.py 2. https://gist.github.com/tomokishii/0ce3bdac1588b5cca9fa5fbdf6e1c412 """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims in [2,4] if ndims == 2: data_format = 'NHWC' if data_format == 'NCHW': n_out = shape[1] else: n_out = shape[-1] # channel assert n_out is not None, "Input to BatchNorm cannot have unknown channels!" with tf.variable_scope(name): beta = tf.Variable(tf.constant(0.0, shape = [n_out]), name = 'beta', trainable = True) gamma = tf.Variable(tf.constant(1.0, shape = [n_out]), name = 'gamma', trainable = True) axis = list(range(len(x.get_shape())-1)) batch_mean, batch_var = tf.nn.moments(x, axis, name = 'moments') ema = tf.train.ExponentialMovingAverage(decay = 0.5) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(train_phase, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, epsilon) return normed def dropout_layer(self, x): return tf.nn.dropout(x, self.keep_prob) def fc_layer(self, x, name, prune = False, apply_relu = True): with tf.variable_scope(name, reuse = True): with tf.device('/cpu:0'): w = tf.get_variable('w') b = tf.get_variable('b') if prune: w = w * self.weights_masks[name] ret = tf.nn.xw_plus_b(x,w,b) if apply_relu: ret = tf.nn.relu(ret) return ret def conv_layer(self, x, name, padding = 'SAME', stride = 1, split = 1, data_format = 'NHWC', prune = False): channel_axis = 3 if data_format == 'NHWC' else 1 with tf.variable_scope(name, reuse = True): with tf.device('/cpu:0'): w = tf.get_variable('w') b = tf.get_variable('b') if prune: w = w * self.weights_masks[name] if split == 1: conv = tf.nn.conv2d(x, w, [1, stride, stride, 1], padding, data_format=data_format) # conv = tf.nn.conv2d(x, w, stride, padding) else: inputs = tf.split(x, split, channel_axis) kernels = tf.split(w, split, 3) # outputs = [tf.nn.conv2d(i, k, stride, padding) outputs = [tf.nn.conv2d(i, k, [1, stride, stride, 1], padding, data_format=data_format) for i, k in zip(inputs, kernels)] conv = tf.concat(outputs, channel_axis) # using Relu ret = tf.nn.relu(tf.nn.bias_add(conv, b, data_format=data_format), name='output') return ret def _get_variables(self, isload, weights_path = 'vgg_vars'): """ Network architecture definition """ self.keys = ['conv1_1', 'conv1_2', 'conv2_1', 'conv2_2', 'conv3_1', 'conv3_2', 'conv3_3', 'conv4_1', 'conv4_2', 'conv4_3', 'conv5_1', 'conv5_2', 'conv5_3', 'fc6', 'fc7', 'fc8' ] kernel_shapes = [ [3, 3, 3, 64], [3, 3, 64, 64], [3, 3, 64, 128], [3, 3, 128, 128], [3, 3, 128, 256], [3, 3, 256, 256], [3, 3, 256, 256], [3, 3, 256, 512], [3, 3, 512, 512], [3, 3, 512, 512], [3, 3, 512, 512], [3, 3, 512, 512], [3, 3, 512, 512], [7*7*512, 4096], [4096, 4096], [4096, 1001] ] biase_shape = [ [64], [64], [128], [128], [256], [256], [256], [512], [512], [512], [512], [512], [512], [4096], [4096], [1001] ] self.weight_shapes = kernel_shapes self.biase_shapes = biase_shape if isload: with open(weights_path+'.pkl', 'rb') as f: weights, biases = pickle.load(f) for i, key in enumerate(self.keys): w_key = key + '/w' b_key = key + '/b' self._init_layerwise_variables(w_shape = kernel_shapes[i], b_shape = biase_shape[i], name = key, w_init = weights[w_key], b_init = biases[b_key]) else: for i,key in enumerate(self.keys): self._init_layerwise_variables(w_shape = kernel_shapes[i], b_shape = biase_shape[i], name = key) def _init_layerwise_variables(self, w_shape, b_shape, name, w_init = None, b_init = None): with tf.variable_scope(name): with tf.device('/cpu:0'): if w_init is None: w_init = tf.contrib.layers.variance_scaling_initializer() w = tf.get_variable('w', w_shape, initializer = w_init) else: # w_init = tf.constant(w_init, dtype=tf.float32) w_init = tf.constant_initializer(w_init, dtype=tf.float32) w = tf.get_variable('w', w_shape, initializer = w_init) # w = tf.get_variable(w_init, name = 'w', dtype = tf.float32) # w = tf.Variable(w_init, name = 'w', dtype = tf.float32) if b_init is None: b_init = tf.constant_initializer() b = tf.get_variable('b', b_shape, initializer = b_init) else: # b_init = tf.constant(b_init, dtype=tf.float32) b_init = tf.constant_initializer(b_init, dtype=tf.float32) b = tf.get_variable('b', b_shape, initializer = b_init) # b = tf.get_variable(b_init, name = 'b', dtype = tf.float32) # b = tf.Variable(b_init, name = 'b', dtype = tf.float32) def _init_weight_masks(self, is_load): names = self.keys # if is_load: # with open(weights_path+'mask.npy', 'rb') as f: # self.weights_masks, self.biases_masks= pickle.load(f) # else: self.weights_masks = {} self.biases_masks = {} for i, key in enumerate(names): self.weights_masks[key] = np.ones(self.weight_shapes[i]) self.biases_masks[key] = np.ones(self.biase_shapes[i]) def _apply_a_mask(self, mask, var): return (var * mask) def save_model(sess, weights_path = 'vgg_vars'): w_save = {} b_save = {} keys = ['conv1_1', 'conv1_2', 'conv2_1', 'conv2_2', 'conv3_1', 'conv3_2', 'conv3_3', 'conv4_1', 'conv4_2', 'conv4_3', 'conv5_1', 'conv5_2', 'conv5_3', 'fc6', 'fc7', 'fc8' ] for key in keys: with tf.variable_scope(key, reuse = True): with tf.device('/cpu:0'): w = tf.get_variable('w') b = tf.get_variable('b') w_save[key] = w.eval(session = sess) b_save[key] = b.eval(session = sess) with open(weights_path, 'wb') as f: pickle.dump([w_save, b_save], f) print('model saved')
from sklearn.feature_extraction.text import CountVectorizer from sklearn.pipeline import FeatureUnion from eli5.base import ( DocWeightedSpans, WeightedSpans, FeatureWeights, FeatureWeight as FW) from eli5.formatters import FormattedFeatureName from eli5.sklearn.text import get_weighted_spans hl_in_text = FormattedFeatureName('Highlighted in text (sum)') def test_weighted_spans_word(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='word') vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[FW('see', 2), FW('lemon', 4), FW('bias', 8)], neg=[FW('tree', -6)], neg_remaining=10 )) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('see', [(2, 5)], 2), ('lemon', [(17, 22)], 4), ('tree', [(23, 27)], -6)], preserve_density=False, )], other=FeatureWeights( pos=[FW('bias', 8), FW(hl_in_text, 0)], neg=[], neg_remaining=10, )) def test_weighted_spans_word_bigrams(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='word', ngram_range=(1, 2)) vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[FW('see', 2), FW('leaning lemon', 5), FW('lemon tree', 8)], neg=[FW('tree', -6)])) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('see', [(2, 5)], 2), ('tree', [(23, 27)], -6), ('leaning lemon', [(9, 16), (17, 22)], 5), ('lemon tree', [(17, 22), (23, 27)], 8)], preserve_density=False, )], other=FeatureWeights( pos=[FW(hl_in_text, 9)], neg=[], )) def test_weighted_spans_word_stopwords(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='word', stop_words='english') vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[FW('see', 2), FW('lemon', 5), FW('bias', 8)], neg=[FW('tree', -6)])) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('lemon', [(17, 22)], 5), ('tree', [(23, 27)], -6)], preserve_density=False, )], other=FeatureWeights( pos=[FW('bias', 8), FW('see', 2)], neg=[FW(hl_in_text, -1)], )) def test_weighted_spans_char(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='char', ngram_range=(3, 4)) vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[FW('see', 2), FW('a le', 5), FW('on ', 8)], neg=[FW('lem', -6)])) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('see', [(2, 5)], 2), ('lem', [(17, 20)], -6), ('on ', [(20, 23)], 8), ('a le', [(7, 11)], 5)], preserve_density=True, )], other=FeatureWeights( pos=[FW(hl_in_text, 9)], neg=[], )) def test_no_weighted_spans(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='char', ngram_range=(3, 4)) vec.fit([doc]) w_spans = get_weighted_spans(doc, vec, FeatureWeights(pos=[], neg=[])) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[], preserve_density=True, )], other=FeatureWeights(pos=[], neg=[])) def test_unsupported(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer=lambda x: x) vec.fit([doc]) w_spans = get_weighted_spans(doc, vec, FeatureWeights(pos=[], neg=[])) assert w_spans is None def test_weighted_spans_char_wb(): doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='char_wb', ngram_range=(3, 4)) vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[FW('see', 2), FW('a le', 5), FW('on ', 8)], neg=[FW('lem', -6), FW(' lem', -4)])) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('see', [(2, 5)], 2), ('lem', [(17, 20)], -6), ('on ', [(20, 23)], 8), (' lem', [(16, 20)], -4)], preserve_density=True, )], other=FeatureWeights( pos=[FW('a le', 5), FW(hl_in_text, 0)], neg=[], )) def test_unhashed_features_other(): """ Check that when there are several candidates, they do not appear in "other" if at least one is found. If none are found, they should appear in "other" together. """ doc = 'I see: a leaning lemon tree' vec = CountVectorizer(analyzer='char', ngram_range=(3, 3)) vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[ FW([{'name': 'foo', 'sign': 1}, {'name': 'see', 'sign': -1}], 2), FW([{'name': 'zoo', 'sign': 1}, {'name': 'bar', 'sign': 1}], 3), ], neg=[ FW([{'name': 'ree', 'sign': 1}, {'name': 'tre', 'sign': 1}], -4), ], )) assert w_spans == WeightedSpans( [DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('see', [(2, 5)], 2), ('tre', [(23, 26)], -4), ('ree', [(24, 27)], -4), ], preserve_density=True, )], other=FeatureWeights( pos=[ FW([{'name': 'zoo', 'sign': 1}, {'name': 'bar', 'sign': 1}], 3), ], neg=[FW(hl_in_text, -2)], )) def test_weighted_spans_feature_union(): doc = {'text': 'I see: a leaning lemon tree', 'url': 'http://example.com'} vec = FeatureUnion([ ('text', CountVectorizer(analyzer='word', preprocessor=lambda x: x['text'].lower())), ('url', CountVectorizer(analyzer='char', ngram_range=(4, 4), preprocessor=lambda x: x['url'])), ]) vec.fit([doc]) w_spans = get_weighted_spans( doc, vec, FeatureWeights( pos=[FW('text__see', 2), FW('text__lemon', 4), FW('bias', 8), FW('url__ampl', 10), FW('url__mple', 7), ], neg=[FW('text__tree', -6), FW('url__exam', -10), ], neg_remaining=10 )) assert w_spans == WeightedSpans( [ DocWeightedSpans( document='i see: a leaning lemon tree', spans=[ ('see', [(2, 5)], 2), ('lemon', [(17, 22)], 4), ('tree', [(23, 27)], -6)], preserve_density=False, vec_name='text', ), DocWeightedSpans( document='http://example.com', spans=[ ('exam', [(7, 11)], -10), ('ampl', [(9, 13)], 10), ('mple', [(10, 14)], 7)], preserve_density=True, vec_name='url', ), ], other=FeatureWeights( pos=[FW('bias', 8), FW(FormattedFeatureName('url: Highlighted in text (sum)'), 7), FW(FormattedFeatureName('text: Highlighted in text (sum)'), 0), ], neg=[], neg_remaining=10, )) def test_feature_union_unsupported(): doc = 'I see: a leaning lemon tree' vec = FeatureUnion([('vec', CountVectorizer(analyzer=lambda x: x))]) vec.fit([doc]) w_spans = get_weighted_spans(doc, vec, FeatureWeights(pos=[], neg=[])) assert w_spans is None
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import unittest import numpy as np from op_test import OpTest, convert_float_to_uint16 import paddle import paddle.fluid as fluid from paddle.fluid import Program, program_guard import paddle.fluid.core as core paddle.enable_static() class TestTransposeOp(OpTest): def setUp(self): self.init_op_type() self.initTestCase() self.inputs = {'X': np.random.random(self.shape).astype("float64")} self.attrs = { 'axis': list(self.axis), 'use_mkldnn': self.use_mkldnn, } self.outputs = { 'XShape': np.random.random(self.shape).astype("float64"), 'Out': self.inputs['X'].transpose(self.axis) } def init_op_type(self): self.op_type = "transpose2" self.use_mkldnn = False def test_check_output(self): self.check_output(no_check_set=['XShape']) def test_check_grad(self): self.check_grad(['X'], 'Out') def initTestCase(self): self.shape = (3, 40) self.axis = (1, 0) class TestCase0(TestTransposeOp): def initTestCase(self): self.shape = (100, ) self.axis = (0, ) class TestCase1(TestTransposeOp): def initTestCase(self): self.shape = (3, 4, 10) self.axis = (0, 2, 1) class TestCase2(TestTransposeOp): def initTestCase(self): self.shape = (2, 3, 4, 5) self.axis = (0, 2, 3, 1) class TestCase3(TestTransposeOp): def initTestCase(self): self.shape = (2, 3, 4, 5, 6) self.axis = (4, 2, 3, 1, 0) class TestCase4(TestTransposeOp): def initTestCase(self): self.shape = (2, 3, 4, 5, 6, 1) self.axis = (4, 2, 3, 1, 0, 5) class TestCase5(TestTransposeOp): def initTestCase(self): self.shape = (2, 16, 96) self.axis = (0, 2, 1) class TestCase6(TestTransposeOp): def initTestCase(self): self.shape = (2, 10, 12, 16) self.axis = (3, 1, 2, 0) class TestCase7(TestTransposeOp): def initTestCase(self): self.shape = (2, 10, 2, 16) self.axis = (0, 1, 3, 2) class TestCase8(TestTransposeOp): def initTestCase(self): self.shape = (2, 3, 2, 3, 2, 4, 3, 3) self.axis = (0, 1, 3, 2, 4, 5, 6, 7) class TestCase9(TestTransposeOp): def initTestCase(self): self.shape = (2, 3, 2, 3, 2, 4, 3, 3) self.axis = (6, 1, 3, 5, 0, 2, 4, 7) class TestTransposeBF16Op(OpTest): def setUp(self): self.init_op_type() self.initTestCase() self.dtype = np.uint16 x = np.random.random(self.shape).astype("float32") self.inputs = {'X': convert_float_to_uint16(x)} self.attrs = { 'axis': list(self.axis), 'use_mkldnn': self.use_mkldnn, } self.outputs = { 'XShape': convert_float_to_uint16( np.random.random(self.shape).astype("float32")), 'Out': self.inputs['X'].transpose(self.axis) } def init_op_type(self): self.op_type = "transpose2" self.use_mkldnn = False def test_check_output(self): self.check_output(no_check_set=['XShape']) def test_check_grad(self): pass def initTestCase(self): self.shape = (3, 2) self.axis = (1, 0) class TestTransposeOpBool(TestTransposeOp): def test_check_grad(self): pass class TestTransposeOpBool1D(TestTransposeOpBool): def initTestCase(self): self.shape = (100, ) self.axis = (0, ) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool2D(TestTransposeOpBool): def initTestCase(self): self.shape = (3, 40) self.axis = (1, 0) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool3D(TestTransposeOpBool): def initTestCase(self): self.shape = (3, 4, 10) self.axis = (0, 2, 1) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool4D(TestTransposeOpBool): def initTestCase(self): self.shape = (2, 3, 4, 5) self.axis = (0, 2, 3, 1) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool5D(TestTransposeOpBool): def initTestCase(self): self.shape = (2, 3, 4, 5, 6) self.axis = (4, 2, 3, 1, 0) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool6D(TestTransposeOpBool): def initTestCase(self): self.shape = (2, 3, 4, 5, 6, 1) self.axis = (4, 2, 3, 1, 0, 5) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool7D(TestTransposeOpBool): def initTestCase(self): self.shape = (2, 3, 2, 3, 2, 4, 3) self.axis = (0, 1, 3, 2, 4, 5, 6) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpBool8D(TestTransposeOpBool): def initTestCase(self): self.shape = (2, 3, 2, 3, 2, 4, 3, 3) self.axis = (6, 1, 3, 5, 0, 2, 4, 7) self.inputs = {'X': np.random.random(self.shape).astype("bool")} self.outputs = { 'XShape': np.random.random(self.shape).astype("bool"), 'Out': self.inputs['X'].transpose(self.axis) } class TestTransposeOpError(unittest.TestCase): def test_errors(self): paddle.enable_static() with program_guard(Program(), Program()): x = fluid.layers.data(name='x', shape=[10, 5, 3], dtype='float64') def test_x_Variable_check(): # the Input(x)'s type must be Variable fluid.layers.transpose("not_variable", perm=[1, 0, 2]) self.assertRaises(TypeError, test_x_Variable_check) def test_x_dtype_check(): # the Input(x)'s dtype must be one of [bool, float16, float32, float64, int32, int64] x1 = fluid.layers.data( name='x1', shape=[10, 5, 3], dtype='int8') fluid.layers.transpose(x1, perm=[1, 0, 2]) self.assertRaises(TypeError, test_x_dtype_check) def test_perm_list_check(): # Input(perm)'s type must be list fluid.layers.transpose(x, perm="[1, 0, 2]") self.assertRaises(TypeError, test_perm_list_check) def test_perm_length_and_x_dim_check(): # Input(perm) is the permutation of dimensions of Input(input) # its length should be equal to dimensions of Input(input) fluid.layers.transpose(x, perm=[1, 0, 2, 3, 4]) self.assertRaises(ValueError, test_perm_length_and_x_dim_check) def test_each_elem_value_check(): # Each element in Input(perm) should be less than Input(x)'s dimension fluid.layers.transpose(x, perm=[3, 5, 7]) self.assertRaises(ValueError, test_each_elem_value_check) class TestTransposeApi(unittest.TestCase): def test_static_out(self): paddle.enable_static() with paddle.static.program_guard(paddle.static.Program()): x = paddle.static.data(name='x', shape=[2, 3, 4], dtype='float32') x_trans1 = paddle.transpose(x, perm=[1, 0, 2]) x_trans2 = paddle.transpose(x, perm=(2, 1, 0)) place = paddle.CPUPlace() exe = paddle.static.Executor(place) x_np = np.random.random([2, 3, 4]).astype("float32") result1, result2 = exe.run(feed={"x": x_np}, fetch_list=[x_trans1, x_trans2]) expected_result1 = np.transpose(x_np, [1, 0, 2]) expected_result2 = np.transpose(x_np, (2, 1, 0)) np.testing.assert_array_equal(result1, expected_result1) np.testing.assert_array_equal(result2, expected_result2) def test_dygraph_out(self): # This is an old test before 2.0 API so we need to disable static # to trigger dygraph paddle.disable_static() x = paddle.randn([2, 3, 4]) x_trans1 = paddle.transpose(x, perm=[1, 0, 2]) x_trans2 = paddle.transpose(x, perm=(2, 1, 0)) x_np = x.numpy() expected_result1 = np.transpose(x_np, [1, 0, 2]) expected_result2 = np.transpose(x_np, (2, 1, 0)) np.testing.assert_array_equal(x_trans1.numpy(), expected_result1) np.testing.assert_array_equal(x_trans2.numpy(), expected_result2) # This is an old test before 2.0 API so we enable static again after # dygraph test paddle.enable_static() class TestTAPI(unittest.TestCase): def test_out(self): with fluid.program_guard(fluid.Program()): data = fluid.data(shape=[10], dtype="float64", name="data") data_t = paddle.t(data) place = fluid.CPUPlace() exe = fluid.Executor(place) data_np = np.random.random([10]).astype("float64") result, = exe.run(feed={"data": data_np}, fetch_list=[data_t]) expected_result = np.transpose(data_np) self.assertEqual((result == expected_result).all(), True) with fluid.program_guard(fluid.Program()): data = fluid.data(shape=[10, 5], dtype="float64", name="data") data_t = paddle.t(data) place = fluid.CPUPlace() exe = fluid.Executor(place) data_np = np.random.random([10, 5]).astype("float64") result, = exe.run(feed={"data": data_np}, fetch_list=[data_t]) expected_result = np.transpose(data_np) self.assertEqual((result == expected_result).all(), True) with fluid.program_guard(fluid.Program()): data = fluid.data(shape=[1, 5], dtype="float64", name="data") data_t = paddle.t(data) place = fluid.CPUPlace() exe = fluid.Executor(place) data_np = np.random.random([1, 5]).astype("float64") result, = exe.run(feed={"data": data_np}, fetch_list=[data_t]) expected_result = np.transpose(data_np) self.assertEqual((result == expected_result).all(), True) with fluid.dygraph.guard(): np_x = np.random.random([10]).astype("float64") data = fluid.dygraph.to_variable(np_x) z = paddle.t(data) np_z = z.numpy() z_expected = np.array(np.transpose(np_x)) self.assertEqual((np_z == z_expected).all(), True) with fluid.dygraph.guard(): np_x = np.random.random([10, 5]).astype("float64") data = fluid.dygraph.to_variable(np_x) z = paddle.t(data) np_z = z.numpy() z_expected = np.array(np.transpose(np_x)) self.assertEqual((np_z == z_expected).all(), True) with fluid.dygraph.guard(): np_x = np.random.random([1, 5]).astype("float64") data = fluid.dygraph.to_variable(np_x) z = paddle.t(data) np_z = z.numpy() z_expected = np.array(np.transpose(np_x)) self.assertEqual((np_z == z_expected).all(), True) def test_errors(self): with fluid.program_guard(fluid.Program()): x = fluid.data(name='x', shape=[10, 5, 3], dtype='float64') def test_x_dimension_check(): paddle.t(x) self.assertRaises(ValueError, test_x_dimension_check) class TestMoveAxis(unittest.TestCase): def test_moveaxis1(self): x_np = np.random.randn(2, 3, 4, 5, 7) expected = np.moveaxis(x_np, [0, 4, 3, 2], [1, 3, 2, 0]) paddle.enable_static() with paddle.static.program_guard(fluid.Program()): x = paddle.static.data("x", shape=[2, 3, 4, 5, 7], dtype='float64') out = paddle.moveaxis(x, [0, 4, 3, 2], [1, 3, 2, 0]) exe = paddle.static.Executor() out_np = exe.run(feed={"x": x_np}, fetch_list=[out])[0] self.assertEqual(np.array_equal(out_np, expected), True) paddle.disable_static() x = paddle.to_tensor(x_np) out = paddle.moveaxis(x, [0, 4, 3, 2], [1, 3, 2, 0]) self.assertEqual(out.shape, [4, 2, 5, 7, 3]) self.assertEqual(np.array_equal(out.numpy(), expected), True) paddle.enable_static() def test_moveaxis2(self): x_np = np.random.randn(2, 3, 5) expected = np.moveaxis(x_np, -2, -1) paddle.enable_static() with paddle.static.program_guard(fluid.Program()): x = paddle.static.data("x", shape=[2, 3, 5], dtype='float64') out = x.moveaxis(-2, -1) exe = paddle.static.Executor() out_np = exe.run(feed={"x": x_np}, fetch_list=[out])[0] self.assertEqual(np.array_equal(out_np, expected), True) paddle.disable_static() x = paddle.to_tensor(x_np) out = x.moveaxis(-2, -1) self.assertEqual(out.shape, [2, 5, 3]) self.assertEqual(np.array_equal(out.numpy(), expected), True) paddle.enable_static() def test_moveaxis3(self): paddle.disable_static() x = paddle.to_tensor( [[1 + 1j, -1 - 1j], [1 + 1j, -1 - 1j], [1 + 1j, -1 - 1j]]) out = x.moveaxis(0, 1) self.assertEqual(out.shape, [2, 3]) paddle.enable_static() def test_error(self): x = paddle.randn([2, 3, 4, 5]) # src must have the same number with dst with self.assertRaises(AssertionError): paddle.moveaxis(x, [1, 0], [2]) # each element of src must be unique with self.assertRaises(ValueError): paddle.moveaxis(x, [1, 1], [0, 2]) # each element of dst must be unique with self.assertRaises(ValueError): paddle.moveaxis(x, [0, 1], [2, 2]) # each element of src must be integer with self.assertRaises(AssertionError): paddle.moveaxis(x, [0.5], [1]) # each element of dst must be integer with self.assertRaises(AssertionError): paddle.moveaxis(x, [0], [1.5]) # each element of src must be in the range of [-4, 3) with self.assertRaises(AssertionError): paddle.moveaxis(x, [-10, 1], [2, 3]) # each element of dst must be in the range of [-4, 3) with self.assertRaises(AssertionError): paddle.moveaxis(x, [2, 1], [10, 3]) if __name__ == '__main__': paddle.enable_static() unittest.main()
import os import sys import jinja2 import re import json import traceback from dpath import util as dpath_util from jinja2.exceptions import UndefinedError, FilterArgumentError, TemplateSyntaxError from jsonschema import validate, ValidationError, draft4_format_checker from json.decoder import JSONDecodeError from e2j2.exceptions import E2j2Exception from e2j2.constants import CONFIG_SCHEMAS, TAGS, NESTED_TAGS, MARKER_SETS from e2j2.tags import ( base64_tag, consul_tag, file_tag, json_tag, jsonfile_tag, list_tag, vault_tag, dns_tag, escape_tag, ) from e2j2.display import write, get_colors try: from jinja2_ansible_filters import AnsibleCoreFiltersExtension j2_extensions = [AnsibleCoreFiltersExtension] except ImportError: j2_extensions = [] def recursive_iter(obj, keys=()): if isinstance(obj, dict): for k, v in obj.items(): yield from recursive_iter(v, keys + (k,)) elif any(isinstance(obj, t) for t in (list, tuple)): for idx, item in enumerate(obj): yield from recursive_iter(item, keys + (idx,)) else: yield keys, obj def find(searchlist, j2file_ext, recurse=False): if recurse: return [ os.path.realpath(os.path.join(dirpath, j2file)) for searchlist_item in searchlist for dirpath, dirnames, files in os.walk(searchlist_item, followlinks=True) for j2file in files if j2file.endswith(j2file_ext) ] else: return [ os.path.realpath(os.path.join(searchlist_item, j2file)) for searchlist_item in searchlist for j2file in os.listdir(searchlist_item) if j2file.endswith(j2file_ext) ] def get_vars(config, whitelist, blacklist): env_list = [entry for entry in whitelist if entry not in blacklist] env_vars = os.environ return resolv_vars(config, env_list, env_vars) def resolv_vars(config, var_list, env_vars): colors = get_colors() varcontext = {} for var in var_list: var_value = env_vars[var] defined_tag = "".join( [tag for tag in TAGS if ":" in var_value and var_value.startswith(tag)] ) try: if not defined_tag: varcontext[var] = var_value else: tag_config, tag_value = parse_tag(config, defined_tag, var_value) varcontext[var] = tag_value if ( "flatten" in tag_config and tag_config["flatten"] and isinstance(tag_value, dict) ): for key, value in tag_value.items(): varcontext[key] = value except E2j2Exception as e: write( f"{colors.yellow}** WARNING: parsing {var} failed with error: {str(e)} **{colors.reset}\n" ) return varcontext def parse_tag(config, tag, value): tag_config = {} value = re.sub(r"^{}".format(tag), "", value).strip() if tag in CONFIG_SCHEMAS: envvars = os.environ config_var = tag.upper()[:-1] + "_CONFIG" token_var = tag.upper()[:-1] + "_TOKEN" # FIXME be more specific on raising error (config or data) try: tag_config = json.loads(envvars.get(config_var, "{}")) pattern = re.compile(r"config=(.+)") match = pattern.match(value) markers = detect_markers(config, value) value_with_config = ( match.group(1).split(markers["config_end"] + ":") if pattern.match(value) else None ) if value_with_config and len(value_with_config) > 1: config_str, value = value_with_config config_str = config_str.lstrip(markers["config_start"]) tag_config.update(json.loads("{%s}" % config_str)) elif value_with_config: raise E2j2Exception( "invalid config markers used, please place the config between the markers '%s' and '%s'" % (markers["config_start"], markers["config_end"]) ) if token_var in envvars: tag_config["token"] = ( tag_config["token"] if "token" in tag_config else envvars[token_var] ) if "token" in tag_config and tag_config["token"].startswith("file:"): token_value = re.sub(r"^file:", "", tag_config["token"]) tag_config["token"] = file_tag.parse(token_value).strip() except JSONDecodeError: raise E2j2Exception("decoding JSON failed") try: validate( instance=tag_config, schema=CONFIG_SCHEMAS[tag], format_checker=draft4_format_checker, ) except ValidationError: if config["stacktrace"]: write(traceback.format_exc()) raise E2j2Exception("config validation failed") if tag == "json:": tag_value = json_tag.parse(value) elif tag == "jsonfile:": tag_value = jsonfile_tag.parse(value) elif tag == "base64:": tag_value = base64_tag.parse(value) elif tag == "consul:": tag_value = consul_tag.parse(tag_config, value) elif tag == "list:": tag_value = list_tag.parse(value) elif tag == "file:": tag_value = file_tag.parse(value) elif tag == "vault:": tag_value = vault_tag.parse(tag_config, value) elif tag == "dns:": tag_value = dns_tag.parse(tag_config, value) elif tag == "escape:": tag_value = escape_tag.parse(value) else: return None, "** ERROR: tag: %s not implemented **" % tag if config["nested_tags"] and tag in NESTED_TAGS: try: for keys, item in recursive_iter(tag_value): if isinstance(item, str): dpath_util.set( tag_value, list(keys), resolv_vars(config, ["item"], {"item": item})["item"], ) except Exception: raise E2j2Exception("failed to resolve nested tag") return tag_config, tag_value def render(config, j2file, j2vars): path, filename = os.path.split(j2file) j2 = jinja2.Environment( loader=jinja2.FileSystemLoader([path or "./", "/"]), undefined=jinja2.StrictUndefined, keep_trailing_newline=True, extensions=j2_extensions, ) try: with open(j2file, "r") as file: content = file.read() markers = detect_markers(config, content) j2.block_start_string = markers["block_start"] j2.block_end_string = markers["block_end"] j2.variable_start_string = markers["variable_start"] j2.variable_end_string = markers["variable_end"] j2.comment_start_string = markers["comment_start"] j2.comment_end_string = markers["comment_end"] first_pass = j2.from_string(content).render(j2vars) if config["twopass"]: # second pass markers = detect_markers(config, first_pass) j2.block_start_string = markers["block_start"] j2.block_end_string = markers["block_end"] j2.variable_start_string = markers["variable_start"] j2.variable_end_string = markers["variable_end"] j2.comment_start_string = markers["comment_start"] j2.comment_end_string = markers["comment_end"] return j2.from_string(first_pass).render(j2vars) else: return first_pass except (UndefinedError, FilterArgumentError, TemplateSyntaxError) as err: exc_type, exc_value, exc_tb = sys.exc_info() stacktrace = traceback.format_exception(exc_type, exc_value, exc_tb) match = re.search(r"\sline\s(\d+)", stacktrace[-2]) content = "failed with error: {}".format(err) content += " at line: {}".format(match.group(1)) if match else "" raise E2j2Exception(content) except FileNotFoundError: raise E2j2Exception("Template %s not found" % filename) except Exception as err: raise E2j2Exception(str(err)) def detect_markers(config, content): marker_set = MARKER_SETS[config["marker_set"]] if config["autodetect_marker_set"]: config_marker = True if "config=" in content else False for key, value in MARKER_SETS.items(): if config_marker: if "config=" + MARKER_SETS[key]["config_start"] in content: marker_set = MARKER_SETS[key] else: if ( MARKER_SETS[key]["variable_start"] in content and MARKER_SETS[key]["variable_end"] in content ): marker_set = MARKER_SETS[key] markers = { "block_start": config["block_start"] if config["block_start"] else marker_set["block_start"], "block_end": config["block_end"] if config["block_end"] else marker_set["block_end"], "variable_start": config["variable_start"] if config["variable_start"] else marker_set["variable_start"], "variable_end": config["variable_end"] if config["variable_end"] else marker_set["variable_end"], "comment_start": config["comment_start"] if config["comment_start"] else marker_set["comment_start"], "comment_end": config["comment_end"] if config["comment_end"] else marker_set["comment_end"], "config_start": config["config_start"] if config["config_start"] else marker_set["config_start"], "config_end": config["config_end"] if config["config_end"] else marker_set["config_end"], } return markers
# Copyright 2014 CERN # # 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. # """Identity v3 federation mapping action implementations""" import json import logging from osc_lib.command import command from osc_lib import exceptions from osc_lib import utils from openstackclient.i18n import _ LOG = logging.getLogger(__name__) class _RulesReader(object): _description = _("Helper class capable of reading rules from files") def _read_rules(self, path): """Read and parse rules from path Expect the file to contain a valid JSON structure. :param path: path to the file :return: loaded and valid dictionary with rules :raises exception.CommandError: In case the file cannot be accessed or the content is not a valid JSON. Example of the content of the file: [ { "local": [ { "group": { "id": "85a868" } } ], "remote": [ { "type": "orgPersonType", "any_one_of": [ "Employee" ] }, { "type": "sn", "any_one_of": [ "Young" ] } ] } ] """ blob = utils.read_blob_file_contents(path) try: rules = json.loads(blob) except ValueError as e: msg = _("An error occurred when reading rules from file " "%(path)s: %(error)s") % {"path": path, "error": e} raise exceptions.CommandError(msg) else: return rules class CreateMapping(command.ShowOne, _RulesReader): _description = _("Create new mapping") def get_parser(self, prog_name): parser = super(CreateMapping, self).get_parser(prog_name) parser.add_argument( 'mapping', metavar='<name>', help=_('New mapping name (must be unique)'), ) parser.add_argument( '--rules', metavar='<filename>', required=True, help=_('Filename that contains a set of mapping rules (required)'), ) return parser def take_action(self, parsed_args): identity_client = self.app.client_manager.identity rules = self._read_rules(parsed_args.rules) mapping = identity_client.federation.mappings.create( mapping_id=parsed_args.mapping, rules=rules) mapping._info.pop('links', None) return zip(*sorted(mapping._info.items())) class DeleteMapping(command.Command): _description = _("Delete mapping(s)") def get_parser(self, prog_name): parser = super(DeleteMapping, self).get_parser(prog_name) parser.add_argument( 'mapping', metavar='<mapping>', nargs='+', help=_('Mapping(s) to delete'), ) return parser def take_action(self, parsed_args): identity_client = self.app.client_manager.identity result = 0 for i in parsed_args.mapping: try: identity_client.federation.mappings.delete(i) except Exception as e: result += 1 LOG.error(_("Failed to delete mapping with name or " "ID '%(mapping)s': %(e)s"), {'mapping': i, 'e': e}) if result > 0: total = len(parsed_args.mapping) msg = (_("%(result)s of %(total)s mappings failed " "to delete.") % {'result': result, 'total': total}) raise exceptions.CommandError(msg) class ListMapping(command.Lister): _description = _("List mappings") def take_action(self, parsed_args): # NOTE(marek-denis): Since rules can be long and tedious I have decided # to only list ids of the mappings. If somebody wants to check the # rules, (s)he should show specific ones. identity_client = self.app.client_manager.identity data = identity_client.federation.mappings.list() columns = ('ID',) items = [utils.get_item_properties(s, columns) for s in data] return (columns, items) class SetMapping(command.Command, _RulesReader): _description = _("Set mapping properties") def get_parser(self, prog_name): parser = super(SetMapping, self).get_parser(prog_name) parser.add_argument( 'mapping', metavar='<name>', help=_('Mapping to modify'), ) parser.add_argument( '--rules', metavar='<filename>', help=_('Filename that contains a new set of mapping rules'), ) return parser def take_action(self, parsed_args): identity_client = self.app.client_manager.identity rules = self._read_rules(parsed_args.rules) mapping = identity_client.federation.mappings.update( mapping=parsed_args.mapping, rules=rules) mapping._info.pop('links', None) class ShowMapping(command.ShowOne): _description = _("Display mapping details") def get_parser(self, prog_name): parser = super(ShowMapping, self).get_parser(prog_name) parser.add_argument( 'mapping', metavar='<mapping>', help=_('Mapping to display'), ) return parser def take_action(self, parsed_args): identity_client = self.app.client_manager.identity mapping = identity_client.federation.mappings.get(parsed_args.mapping) mapping._info.pop('links', None) return zip(*sorted(mapping._info.items()))
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys import time import systrace_agent class FtraceAgentIo(object): @staticmethod def writeFile(path, data): with open(path, 'w') as f: f.write(data) @staticmethod def readFile(path): with open(path, 'r') as f: return f.read() @staticmethod def haveWritePermissions(path): return os.access(path, os.W_OK) FT_DIR = "/sys/kernel/debug/tracing/" FT_CLOCK = FT_DIR + "trace_clock" FT_BUFFER_SIZE = FT_DIR + "buffer_size_kb" FT_TRACER = FT_DIR + "current_tracer" FT_PRINT_TGID = FT_DIR + "options/print-tgid" FT_TRACE_ON = FT_DIR + "tracing_on" FT_TRACE = FT_DIR + "trace" FT_TRACE_MARKER = FT_DIR + "trace_marker" FT_OVERWRITE = FT_DIR + "options/overwrite" all_categories = { "sched": { "desc": "CPU Scheduling", "req": ["sched/sched_switch/", "sched/sched_wakeup/"] }, "freq": { "desc": "CPU Frequency", "req": ["power/cpu_frequency/", "power/clock_set_rate/"] }, "irq": { "desc": "CPU IRQS and IPIS", "req": ["irq/"], "opt": ["ipi/"] }, "workq": { "desc": "Kernel workqueues", "req": ["workqueue/"] }, "memreclaim": { "desc": "Kernel Memory Reclaim", "req": ["vmscan/mm_vmscan_direct_reclaim_begin/", "vmscan/mm_vmscan_direct_reclaim_end/", "vmscan/mm_vmscan_kswapd_wake/", "vmscan/mm_vmscan_kswapd_sleep/"] }, "idle": { "desc": "CPU Idle", "req": ["power/cpu_idle/"] }, "regulators": { "desc": "Voltage and Current Regulators", "req": ["regulator/"] }, "disk": { "desc": "Disk I/O", "req": ["block/block_rq_issue/", "block/block_rq_complete/"], "opt": ["f2fs/f2fs_sync_file_enter/", "f2fs/f2fs_sync_file_exit/", "f2fs/f2fs_write_begin/", "f2fs/f2fs_write_end/", "ext4/ext4_da_write_begin/", "ext4/ext4_da_write_end/", "ext4/ext4_sync_file_enter/", "ext4/ext4_sync_file_exit/"] } } def try_create_agent(options, categories): if options.target != 'linux': return False return FtraceAgent(options, categories, FtraceAgentIo) class FtraceAgent(systrace_agent.SystraceAgent): def __init__(self, options, categories, fio=FtraceAgentIo): """Initialize a systrace agent. Args: options: The command-line options. categories: The trace categories to capture. """ super(FtraceAgent, self).__init__(options, categories) if not self._categories: self._categories = ["sched"] self._fio = fio self._categories = [x for x in self._categories if self._is_category_available(x)] self._expect_trace = False def _get_trace_buffer_size(self): buffer_size = 4096 if ((self._options.trace_buf_size is not None) and (self._options.trace_buf_size > 0)): buffer_size = self._options.trace_buf_size return buffer_size def _get_trace_time(self): wait_time = 5 if ((self._options.trace_time is not None) and (self._options.trace_time > 0)): wait_time = self._options.trace_time return wait_time def start(self): """Start tracing. """ if self._options.list_categories or len(self._categories) == 0: self._expect_trace = False else: self._expect_trace = True self._fio.writeFile(FT_BUFFER_SIZE, str(self._get_trace_buffer_size())) self._fio.writeFile(FT_CLOCK, 'global') self._fio.writeFile(FT_TRACER, 'nop') self._fio.writeFile(FT_OVERWRITE, "0") # TODO: riandrews to push necessary patches for TGID option to upstream # linux kernel # self._fio.writeFile(FT_PRINT_TGID, '1') for category in self._categories: self._category_enable(category) self._fio.writeFile(FT_TRACE, '') print "starting tracing." sys.stdout.flush() self._fio.writeFile(FT_TRACE_ON, '1') def collect_result(self): """Collect the result of tracing. This function will block while collecting the result. For sync mode, it reads the data, e.g., from stdout, until it finishes. For async mode, it blocks until the agent is stopped and the data is ready. """ if self._options.list_categories or len(self._categories) == 0: self._print_avail_categories() else: try: time.sleep(self._get_trace_time()) except KeyboardInterrupt: pass self._fio.writeFile(FT_TRACE_ON, '0') for category in self._categories: self._category_disable(category) if self._options.fix_threads: print "WARN: thread name fixing is not yet supported." if self._options.fix_tgids: print "WARN: tgid fixing is not yet supported." if self._options.fix_circular: print "WARN: circular buffer fixups are not yet supported." def expect_trace(self): """Check if the agent is returning a trace or not. This will be determined in collect_result(). Returns: Whether the agent is expecting a trace or not. """ return self._expect_trace def get_trace_data(self): """Get the trace data. Returns: The trace data. """ d = self._fio.readFile(FT_TRACE) self._fio.writeFile(FT_BUFFER_SIZE, "1") return d def get_class_name(self): return 'trace-data' def _is_category_available(self, category): if category not in all_categories: return False events_dir = FT_DIR + "events/" req_events = all_categories[category]["req"] for event in req_events: event_full_path = events_dir + event + "enable" if not self._fio.haveWritePermissions(event_full_path): return False return True def _avail_categories(self): ret = [] for event in all_categories: if self._is_category_available(event): ret.append(event) return ret def _print_avail_categories(self): avail = self._avail_categories() if len(avail): print "tracing options:" for category in self._avail_categories(): desc = all_categories[category]["desc"] print "{0: <16}".format(category), ": ", desc else: print "No tracing categories available - perhaps you need root?" def _category_enable_paths(self, category): events_dir = FT_DIR + "events/" req_events = all_categories[category]["req"] for event in req_events: event_full_path = events_dir + event + "enable" yield event_full_path if "opt" in all_categories[category]: opt_events = all_categories[category]["opt"] for event in opt_events: event_full_path = events_dir + event + "enable" if self._fio.haveWritePermissions(event_full_path): yield event_full_path def _category_enable(self, category): for path in self._category_enable_paths(category): self._fio.writeFile(path, "1") def _category_disable(self, category): for path in self._category_enable_paths(category): self._fio.writeFile(path, "0")
#! /usr/bin/env python """Test the arraymodule. Roger E. Masse """ import unittest from test import test_support from weakref import proxy import array, cStringIO from cPickle import loads, dumps, HIGHEST_PROTOCOL class ArraySubclass(array.array): pass class ArraySubclassWithKwargs(array.array): def __init__(self, typecode, newarg=None): array.array.__init__(typecode) tests = [] # list to accumulate all tests typecodes = "cubBhHiIlLfd" class BadConstructorTest(unittest.TestCase): def test_constructor(self): self.assertRaises(TypeError, array.array) self.assertRaises(TypeError, array.array, spam=42) self.assertRaises(TypeError, array.array, 'xx') self.assertRaises(ValueError, array.array, 'x') tests.append(BadConstructorTest) class BaseTest(unittest.TestCase): # Required class attributes (provided by subclasses # typecode: the typecode to test # example: an initializer usable in the constructor for this type # smallerexample: the same length as example, but smaller # biggerexample: the same length as example, but bigger # outside: An entry that is not in example # minitemsize: the minimum guaranteed itemsize def assertEntryEqual(self, entry1, entry2): self.assertEqual(entry1, entry2) def badtypecode(self): # Return a typecode that is different from our own return typecodes[(typecodes.index(self.typecode)+1) % len(typecodes)] def test_constructor(self): a = array.array(self.typecode) self.assertEqual(a.typecode, self.typecode) self.assertTrue(a.itemsize>=self.minitemsize) self.assertRaises(TypeError, array.array, self.typecode, None) def test_len(self): a = array.array(self.typecode) a.append(self.example[0]) self.assertEqual(len(a), 1) a = array.array(self.typecode, self.example) self.assertEqual(len(a), len(self.example)) def test_buffer_info(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.buffer_info, 42) bi = a.buffer_info() self.assertIsInstance(bi, tuple) self.assertEqual(len(bi), 2) self.assertIsInstance(bi[0], (int, long)) self.assertIsInstance(bi[1], int) self.assertEqual(bi[1], len(a)) def test_byteswap(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.byteswap, 42) if a.itemsize in (1, 2, 4, 8): b = array.array(self.typecode, self.example) b.byteswap() if a.itemsize==1: self.assertEqual(a, b) else: self.assertNotEqual(a, b) b.byteswap() self.assertEqual(a, b) def test_copy(self): import copy a = array.array(self.typecode, self.example) b = copy.copy(a) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) def test_deepcopy(self): import copy a = array.array(self.typecode, self.example) b = copy.deepcopy(a) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) def test_pickle(self): for protocol in range(HIGHEST_PROTOCOL + 1): a = array.array(self.typecode, self.example) b = loads(dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) a = ArraySubclass(self.typecode, self.example) a.x = 10 b = loads(dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) self.assertEqual(a.x, b.x) self.assertEqual(type(a), type(b)) def test_pickle_for_empty_array(self): for protocol in range(HIGHEST_PROTOCOL + 1): a = array.array(self.typecode) b = loads(dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) a = ArraySubclass(self.typecode) a.x = 10 b = loads(dumps(a, protocol)) self.assertNotEqual(id(a), id(b)) self.assertEqual(a, b) self.assertEqual(a.x, b.x) self.assertEqual(type(a), type(b)) def test_insert(self): a = array.array(self.typecode, self.example) a.insert(0, self.example[0]) self.assertEqual(len(a), 1+len(self.example)) self.assertEqual(a[0], a[1]) self.assertRaises(TypeError, a.insert) self.assertRaises(TypeError, a.insert, None) self.assertRaises(TypeError, a.insert, 0, None) a = array.array(self.typecode, self.example) a.insert(-1, self.example[0]) self.assertEqual( a, array.array( self.typecode, self.example[:-1] + self.example[:1] + self.example[-1:] ) ) a = array.array(self.typecode, self.example) a.insert(-1000, self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example) ) a = array.array(self.typecode, self.example) a.insert(1000, self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example + self.example[:1]) ) def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) self.assertRaises(TypeError, a.tofile, cStringIO.StringIO()) test_support.unlink(test_support.TESTFN) f = open(test_support.TESTFN, 'wb') try: a.tofile(f) f.close() b = array.array(self.typecode) f = open(test_support.TESTFN, 'rb') self.assertRaises(TypeError, b.fromfile) self.assertRaises( TypeError, b.fromfile, cStringIO.StringIO(), len(self.example) ) b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) b.fromfile(f, len(self.example)) self.assertEqual(a, b) self.assertRaises(EOFError, b.fromfile, f, 1) f.close() finally: if not f.closed: f.close() test_support.unlink(test_support.TESTFN) def test_filewrite(self): a = array.array(self.typecode, 2*self.example) f = open(test_support.TESTFN, 'wb') try: f.write(a) f.close() b = array.array(self.typecode) f = open(test_support.TESTFN, 'rb') b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) b.fromfile(f, len(self.example)) self.assertEqual(a, b) f.close() finally: if not f.closed: f.close() test_support.unlink(test_support.TESTFN) def test_tofromlist(self): a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tolist, 42) self.assertRaises(TypeError, b.fromlist) self.assertRaises(TypeError, b.fromlist, 42) self.assertRaises(TypeError, b.fromlist, [None]) b.fromlist(a.tolist()) self.assertEqual(a, b) def test_tofromstring(self): a = array.array(self.typecode, 2*self.example) b = array.array(self.typecode) self.assertRaises(TypeError, a.tostring, 42) self.assertRaises(TypeError, b.fromstring) self.assertRaises(TypeError, b.fromstring, 42) b.fromstring(a.tostring()) self.assertEqual(a, b) if a.itemsize>1: self.assertRaises(ValueError, b.fromstring, "x") def test_repr(self): a = array.array(self.typecode, 2*self.example) self.assertEqual(a, eval(repr(a), {"array": array.array})) a = array.array(self.typecode) self.assertEqual(repr(a), "array('%s')" % self.typecode) def test_str(self): a = array.array(self.typecode, 2*self.example) str(a) def test_cmp(self): a = array.array(self.typecode, self.example) self.assertTrue((a == 42) is False) self.assertTrue((a != 42) is True) self.assertTrue((a == a) is True) self.assertTrue((a != a) is False) self.assertTrue((a < a) is False) self.assertTrue((a <= a) is True) self.assertTrue((a > a) is False) self.assertTrue((a >= a) is True) al = array.array(self.typecode, self.smallerexample) ab = array.array(self.typecode, self.biggerexample) self.assertTrue((a == 2*a) is False) self.assertTrue((a != 2*a) is True) self.assertTrue((a < 2*a) is True) self.assertTrue((a <= 2*a) is True) self.assertTrue((a > 2*a) is False) self.assertTrue((a >= 2*a) is False) self.assertTrue((a == al) is False) self.assertTrue((a != al) is True) self.assertTrue((a < al) is False) self.assertTrue((a <= al) is False) self.assertTrue((a > al) is True) self.assertTrue((a >= al) is True) self.assertTrue((a == ab) is False) self.assertTrue((a != ab) is True) self.assertTrue((a < ab) is True) self.assertTrue((a <= ab) is True) self.assertTrue((a > ab) is False) self.assertTrue((a >= ab) is False) def test_add(self): a = array.array(self.typecode, self.example) \ + array.array(self.typecode, self.example[::-1]) self.assertEqual( a, array.array(self.typecode, self.example + self.example[::-1]) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__add__, b) self.assertRaises(TypeError, a.__add__, "bad") def test_iadd(self): a = array.array(self.typecode, self.example[::-1]) b = a a += array.array(self.typecode, 2*self.example) self.assertTrue(a is b) self.assertEqual( a, array.array(self.typecode, self.example[::-1]+2*self.example) ) a = array.array(self.typecode, self.example) a += a self.assertEqual( a, array.array(self.typecode, self.example + self.example) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__add__, b) self.assertRaises(TypeError, a.__iadd__, "bad") def test_mul(self): a = 5*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a = array.array(self.typecode, self.example)*5 self.assertEqual( a, array.array(self.typecode, self.example*5) ) a = 0*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode) ) a = (-1)*array.array(self.typecode, self.example) self.assertEqual( a, array.array(self.typecode) ) self.assertRaises(TypeError, a.__mul__, "bad") def test_imul(self): a = array.array(self.typecode, self.example) b = a a *= 5 self.assertTrue(a is b) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a *= 0 self.assertTrue(a is b) self.assertEqual(a, array.array(self.typecode)) a *= 1000 self.assertTrue(a is b) self.assertEqual(a, array.array(self.typecode)) a *= -1 self.assertTrue(a is b) self.assertEqual(a, array.array(self.typecode)) a = array.array(self.typecode, self.example) a *= -1 self.assertEqual(a, array.array(self.typecode)) self.assertRaises(TypeError, a.__imul__, "bad") def test_getitem(self): a = array.array(self.typecode, self.example) self.assertEntryEqual(a[0], self.example[0]) self.assertEntryEqual(a[0L], self.example[0]) self.assertEntryEqual(a[-1], self.example[-1]) self.assertEntryEqual(a[-1L], self.example[-1]) self.assertEntryEqual(a[len(self.example)-1], self.example[-1]) self.assertEntryEqual(a[-len(self.example)], self.example[0]) self.assertRaises(TypeError, a.__getitem__) self.assertRaises(IndexError, a.__getitem__, len(self.example)) self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1) def test_setitem(self): a = array.array(self.typecode, self.example) a[0] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[0L] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-1L] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[len(self.example)-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) a[-len(self.example)] = a[-1] self.assertEntryEqual(a[0], a[-1]) self.assertRaises(TypeError, a.__setitem__) self.assertRaises(TypeError, a.__setitem__, None) self.assertRaises(TypeError, a.__setitem__, 0, None) self.assertRaises( IndexError, a.__setitem__, len(self.example), self.example[0] ) self.assertRaises( IndexError, a.__setitem__, -len(self.example)-1, self.example[0] ) def test_delitem(self): a = array.array(self.typecode, self.example) del a[0] self.assertEqual( a, array.array(self.typecode, self.example[1:]) ) a = array.array(self.typecode, self.example) del a[-1] self.assertEqual( a, array.array(self.typecode, self.example[:-1]) ) a = array.array(self.typecode, self.example) del a[len(self.example)-1] self.assertEqual( a, array.array(self.typecode, self.example[:-1]) ) a = array.array(self.typecode, self.example) del a[-len(self.example)] self.assertEqual( a, array.array(self.typecode, self.example[1:]) ) self.assertRaises(TypeError, a.__delitem__) self.assertRaises(TypeError, a.__delitem__, None) self.assertRaises(IndexError, a.__delitem__, len(self.example)) self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1) def test_getslice(self): a = array.array(self.typecode, self.example) self.assertEqual(a[:], a) self.assertEqual( a[1:], array.array(self.typecode, self.example[1:]) ) self.assertEqual( a[:1], array.array(self.typecode, self.example[:1]) ) self.assertEqual( a[:-1], array.array(self.typecode, self.example[:-1]) ) self.assertEqual( a[-1:], array.array(self.typecode, self.example[-1:]) ) self.assertEqual( a[-1:-1], array.array(self.typecode) ) self.assertEqual( a[2:1], array.array(self.typecode) ) self.assertEqual( a[1000:], array.array(self.typecode) ) self.assertEqual(a[-1000:], a) self.assertEqual(a[:1000], a) self.assertEqual( a[:-1000], array.array(self.typecode) ) self.assertEqual(a[-1000:1000], a) self.assertEqual( a[2000:1000], array.array(self.typecode) ) def test_extended_getslice(self): # Test extended slicing by comparing with list slicing # (Assumes list conversion works correctly, too) a = array.array(self.typecode, self.example) indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100) for start in indices: for stop in indices: # Everything except the initial 0 (invalid step) for step in indices[1:]: self.assertEqual(list(a[start:stop:step]), list(a)[start:stop:step]) def test_setslice(self): a = array.array(self.typecode, self.example) a[:1] = a self.assertEqual( a, array.array(self.typecode, self.example + self.example[1:]) ) a = array.array(self.typecode, self.example) a[:-1] = a self.assertEqual( a, array.array(self.typecode, self.example + self.example[-1:]) ) a = array.array(self.typecode, self.example) a[-1:] = a self.assertEqual( a, array.array(self.typecode, self.example[:-1] + self.example) ) a = array.array(self.typecode, self.example) a[1:] = a self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example) ) a = array.array(self.typecode, self.example) a[1:-1] = a self.assertEqual( a, array.array( self.typecode, self.example[:1] + self.example + self.example[-1:] ) ) a = array.array(self.typecode, self.example) a[1000:] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) a[-1000:] = a self.assertEqual( a, array.array(self.typecode, self.example) ) a = array.array(self.typecode, self.example) a[:1000] = a self.assertEqual( a, array.array(self.typecode, self.example) ) a = array.array(self.typecode, self.example) a[:-1000] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) a[1:0] = a self.assertEqual( a, array.array(self.typecode, self.example[:1] + self.example + self.example[1:]) ) a = array.array(self.typecode, self.example) a[2000:1000] = a self.assertEqual( a, array.array(self.typecode, 2*self.example) ) a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.__setslice__, 0, 0, None) self.assertRaises(TypeError, a.__setitem__, slice(0, 0), None) self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.__setslice__, 0, 0, b) self.assertRaises(TypeError, a.__setitem__, slice(0, 0), b) self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b) def test_extended_set_del_slice(self): indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100) for start in indices: for stop in indices: # Everything except the initial 0 (invalid step) for step in indices[1:]: a = array.array(self.typecode, self.example) L = list(a) # Make sure we have a slice of exactly the right length, # but with (hopefully) different data. data = L[start:stop:step] data.reverse() L[start:stop:step] = data a[start:stop:step] = array.array(self.typecode, data) self.assertEquals(a, array.array(self.typecode, L)) del L[start:stop:step] del a[start:stop:step] self.assertEquals(a, array.array(self.typecode, L)) def test_index(self): example = 2*self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.index) for x in example: self.assertEqual(a.index(x), example.index(x)) self.assertRaises(ValueError, a.index, None) self.assertRaises(ValueError, a.index, self.outside) def test_count(self): example = 2*self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.count) for x in example: self.assertEqual(a.count(x), example.count(x)) self.assertEqual(a.count(self.outside), 0) self.assertEqual(a.count(None), 0) def test_remove(self): for x in self.example: example = 2*self.example a = array.array(self.typecode, example) pos = example.index(x) example2 = example[:pos] + example[pos+1:] a.remove(x) self.assertEqual(a, array.array(self.typecode, example2)) a = array.array(self.typecode, self.example) self.assertRaises(ValueError, a.remove, self.outside) self.assertRaises(ValueError, a.remove, None) def test_pop(self): a = array.array(self.typecode) self.assertRaises(IndexError, a.pop) a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.pop, 42, 42) self.assertRaises(TypeError, a.pop, None) self.assertRaises(IndexError, a.pop, len(a)) self.assertRaises(IndexError, a.pop, -len(a)-1) self.assertEntryEqual(a.pop(0), self.example[0]) self.assertEqual( a, array.array(self.typecode, self.example[1:]+self.example) ) self.assertEntryEqual(a.pop(1), self.example[2]) self.assertEqual( a, array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example) ) self.assertEntryEqual(a.pop(0), self.example[1]) self.assertEntryEqual(a.pop(), self.example[-1]) self.assertEqual( a, array.array(self.typecode, self.example[3:]+self.example[:-1]) ) def test_reverse(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.reverse, 42) a.reverse() self.assertEqual( a, array.array(self.typecode, self.example[::-1]) ) def test_extend(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.extend) a.extend(array.array(self.typecode, self.example[::-1])) self.assertEqual( a, array.array(self.typecode, self.example+self.example[::-1]) ) a = array.array(self.typecode, self.example) a.extend(a) self.assertEqual( a, array.array(self.typecode, self.example+self.example) ) b = array.array(self.badtypecode()) self.assertRaises(TypeError, a.extend, b) a = array.array(self.typecode, self.example) a.extend(self.example[::-1]) self.assertEqual( a, array.array(self.typecode, self.example+self.example[::-1]) ) def test_constructor_with_iterable_argument(self): a = array.array(self.typecode, iter(self.example)) b = array.array(self.typecode, self.example) self.assertEqual(a, b) # non-iterable argument self.assertRaises(TypeError, array.array, self.typecode, 10) # pass through errors raised in __iter__ class A: def __iter__(self): raise UnicodeError self.assertRaises(UnicodeError, array.array, self.typecode, A()) # pass through errors raised in next() def B(): raise UnicodeError yield None self.assertRaises(UnicodeError, array.array, self.typecode, B()) def test_coveritertraverse(self): try: import gc except ImportError: return a = array.array(self.typecode) l = [iter(a)] l.append(l) gc.collect() def test_buffer(self): a = array.array(self.typecode, self.example) with test_support.check_py3k_warnings(): b = buffer(a) self.assertEqual(b[0], a.tostring()[0]) def test_weakref(self): s = array.array(self.typecode, self.example) p = proxy(s) self.assertEqual(p.tostring(), s.tostring()) s = None self.assertRaises(ReferenceError, len, p) def test_bug_782369(self): import sys if hasattr(sys, "getrefcount"): for i in range(10): b = array.array('B', range(64)) rc = sys.getrefcount(10) for i in range(10): b = array.array('B', range(64)) self.assertEqual(rc, sys.getrefcount(10)) def test_subclass_with_kwargs(self): # SF bug #1486663 -- this used to erroneously raise a TypeError ArraySubclassWithKwargs('b', newarg=1) class StringTest(BaseTest): def test_setitem(self): super(StringTest, self).test_setitem() a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2]) class CharacterTest(StringTest): typecode = 'c' example = '\x01azAZ\x00\xfe' smallerexample = '\x01azAY\x00\xfe' biggerexample = '\x01azAZ\x00\xff' outside = '\x33' minitemsize = 1 def test_subbclassing(self): class EditableString(array.array): def __new__(cls, s, *args, **kwargs): return array.array.__new__(cls, 'c', s) def __init__(self, s, color='blue'): self.color = color def strip(self): self[:] = array.array('c', self.tostring().strip()) def __repr__(self): return 'EditableString(%r)' % self.tostring() s = EditableString("\ttest\r\n") s.strip() self.assertEqual(s.tostring(), "test") self.assertEqual(s.color, "blue") s.color = "red" self.assertEqual(s.color, "red") self.assertEqual(s.__dict__.keys(), ["color"]) def test_nounicode(self): a = array.array(self.typecode, self.example) self.assertRaises(ValueError, a.fromunicode, unicode('')) self.assertRaises(ValueError, a.tounicode) tests.append(CharacterTest) if test_support.have_unicode: class UnicodeTest(StringTest): typecode = 'u' example = unicode(r'\x01\u263a\x00\ufeff', 'unicode-escape') smallerexample = unicode(r'\x01\u263a\x00\ufefe', 'unicode-escape') biggerexample = unicode(r'\x01\u263a\x01\ufeff', 'unicode-escape') outside = unicode('\x33') minitemsize = 2 def test_unicode(self): self.assertRaises(TypeError, array.array, 'b', unicode('foo', 'ascii')) a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape')) a.fromunicode(unicode(' ', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape')) s = a.tounicode() self.assertEqual( s, unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape') ) s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape') a = array.array('u', s) self.assertEqual( repr(a), r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')""" ) self.assertRaises(TypeError, a.fromunicode) tests.append(UnicodeTest) class NumberTest(BaseTest): def test_extslice(self): a = array.array(self.typecode, range(5)) self.assertEqual(a[::], a) self.assertEqual(a[::2], array.array(self.typecode, [0,2,4])) self.assertEqual(a[1::2], array.array(self.typecode, [1,3])) self.assertEqual(a[::-1], array.array(self.typecode, [4,3,2,1,0])) self.assertEqual(a[::-2], array.array(self.typecode, [4,2,0])) self.assertEqual(a[3::-2], array.array(self.typecode, [3,1])) self.assertEqual(a[-100:100:], a) self.assertEqual(a[100:-100:-1], a[::-1]) self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4])) self.assertEqual(a[1000:2000:2], array.array(self.typecode, [])) self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, [])) def test_delslice(self): a = array.array(self.typecode, range(5)) del a[::2] self.assertEqual(a, array.array(self.typecode, [1,3])) a = array.array(self.typecode, range(5)) del a[1::2] self.assertEqual(a, array.array(self.typecode, [0,2,4])) a = array.array(self.typecode, range(5)) del a[1::-2] self.assertEqual(a, array.array(self.typecode, [0,2,3,4])) a = array.array(self.typecode, range(10)) del a[::1000] self.assertEqual(a, array.array(self.typecode, [1,2,3,4,5,6,7,8,9])) # test issue7788 a = array.array(self.typecode, range(10)) del a[9::1<<333] def test_assignment(self): a = array.array(self.typecode, range(10)) a[::2] = array.array(self.typecode, [42]*5) self.assertEqual(a, array.array(self.typecode, [42, 1, 42, 3, 42, 5, 42, 7, 42, 9])) a = array.array(self.typecode, range(10)) a[::-4] = array.array(self.typecode, [10]*3) self.assertEqual(a, array.array(self.typecode, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])) a = array.array(self.typecode, range(4)) a[::-1] = a self.assertEqual(a, array.array(self.typecode, [3, 2, 1, 0])) a = array.array(self.typecode, range(10)) b = a[:] c = a[:] ins = array.array(self.typecode, range(2)) a[2:3] = ins b[slice(2,3)] = ins c[2:3:] = ins def test_iterationcontains(self): a = array.array(self.typecode, range(10)) self.assertEqual(list(a), range(10)) b = array.array(self.typecode, [20]) self.assertEqual(a[-1] in a, True) self.assertEqual(b[0] not in a, True) def check_overflow(self, lower, upper): # method to be used by subclasses # should not overflow assigning lower limit a = array.array(self.typecode, [lower]) a[0] = lower # should overflow assigning less than lower limit self.assertRaises(OverflowError, array.array, self.typecode, [lower-1]) self.assertRaises(OverflowError, a.__setitem__, 0, lower-1) # should not overflow assigning upper limit a = array.array(self.typecode, [upper]) a[0] = upper # should overflow assigning more than upper limit self.assertRaises(OverflowError, array.array, self.typecode, [upper+1]) self.assertRaises(OverflowError, a.__setitem__, 0, upper+1) def test_subclassing(self): typecode = self.typecode class ExaggeratingArray(array.array): __slots__ = ['offset'] def __new__(cls, typecode, data, offset): return array.array.__new__(cls, typecode, data) def __init__(self, typecode, data, offset): self.offset = offset def __getitem__(self, i): return array.array.__getitem__(self, i) + self.offset a = ExaggeratingArray(self.typecode, [3, 6, 7, 11], 4) self.assertEntryEqual(a[0], 7) self.assertRaises(AttributeError, setattr, a, "color", "blue") class SignedNumberTest(NumberTest): example = [-1, 0, 1, 42, 0x7f] smallerexample = [-1, 0, 1, 42, 0x7e] biggerexample = [-1, 0, 1, 43, 0x7f] outside = 23 def test_overflow(self): a = array.array(self.typecode) lower = -1 * long(pow(2, a.itemsize * 8 - 1)) upper = long(pow(2, a.itemsize * 8 - 1)) - 1L self.check_overflow(lower, upper) class UnsignedNumberTest(NumberTest): example = [0, 1, 17, 23, 42, 0xff] smallerexample = [0, 1, 17, 23, 42, 0xfe] biggerexample = [0, 1, 17, 23, 43, 0xff] outside = 0xaa def test_overflow(self): a = array.array(self.typecode) lower = 0 upper = long(pow(2, a.itemsize * 8)) - 1L self.check_overflow(lower, upper) class ByteTest(SignedNumberTest): typecode = 'b' minitemsize = 1 tests.append(ByteTest) class UnsignedByteTest(UnsignedNumberTest): typecode = 'B' minitemsize = 1 tests.append(UnsignedByteTest) class ShortTest(SignedNumberTest): typecode = 'h' minitemsize = 2 tests.append(ShortTest) class UnsignedShortTest(UnsignedNumberTest): typecode = 'H' minitemsize = 2 tests.append(UnsignedShortTest) class IntTest(SignedNumberTest): typecode = 'i' minitemsize = 2 tests.append(IntTest) class UnsignedIntTest(UnsignedNumberTest): typecode = 'I' minitemsize = 2 tests.append(UnsignedIntTest) class LongTest(SignedNumberTest): typecode = 'l' minitemsize = 4 tests.append(LongTest) class UnsignedLongTest(UnsignedNumberTest): typecode = 'L' minitemsize = 4 tests.append(UnsignedLongTest) class FPTest(NumberTest): example = [-42.0, 0, 42, 1e5, -1e10] smallerexample = [-42.0, 0, 42, 1e5, -2e10] biggerexample = [-42.0, 0, 42, 1e5, 1e10] outside = 23 def assertEntryEqual(self, entry1, entry2): self.assertAlmostEqual(entry1, entry2) def test_byteswap(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.byteswap, 42) if a.itemsize in (1, 2, 4, 8): b = array.array(self.typecode, self.example) b.byteswap() if a.itemsize==1: self.assertEqual(a, b) else: # On alphas treating the byte swapped bit patters as # floats/doubles results in floating point exceptions # => compare the 8bit string values instead self.assertNotEqual(a.tostring(), b.tostring()) b.byteswap() self.assertEqual(a, b) class FloatTest(FPTest): typecode = 'f' minitemsize = 4 tests.append(FloatTest) class DoubleTest(FPTest): typecode = 'd' minitemsize = 8 def test_alloc_overflow(self): from sys import maxsize a = array.array('d', [-1]*65536) try: a *= maxsize//65536 + 1 except MemoryError: pass else: self.fail("Array of size > maxsize created - MemoryError expected") b = array.array('d', [ 2.71828183, 3.14159265, -1]) try: b * (maxsize//3 + 1) except MemoryError: pass else: self.fail("Array of size > maxsize created - MemoryError expected") tests.append(DoubleTest) def test_main(verbose=None): import sys test_support.run_unittest(*tests) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*tests) gc.collect() counts[i] = sys.gettotalrefcount() print counts if __name__ == "__main__": test_main(verbose=True)
from textwrap import dedent import unittest from peru import parser from peru.parser import parse_string, ParserError from peru.module import Module from peru.rule import Rule class ParserTest(unittest.TestCase): def test_parse_empty_file(self): scope, imports = parse_string('') self.assertDictEqual(scope.modules, {}) self.assertDictEqual(scope.rules, {}) self.assertEqual(imports, {}) def test_parse_rule(self): input = dedent("""\ rule foo: export: out/ """) scope, imports = parse_string(input) self.assertIn("foo", scope.rules) rule = scope.rules["foo"] self.assertIsInstance(rule, Rule) self.assertEqual(rule.name, "foo") self.assertEqual(rule.export, "out/") def test_parse_module(self): input = dedent("""\ sometype module foo: url: http://www.example.com/ rev: abcdefg """) scope, imports = parse_string(input) self.assertIn("foo", scope.modules) module = scope.modules["foo"] self.assertIsInstance(module, Module) self.assertEqual(module.name, "foo") self.assertEqual(module.type, "sometype") self.assertDictEqual(module.plugin_fields, {"url": "http://www.example.com/", "rev": "abcdefg"}) def test_parse_module_default_rule(self): input = dedent("""\ git module bar: export: bar """) scope, imports = parse_string(input) self.assertIn("bar", scope.modules) module = scope.modules["bar"] self.assertIsInstance(module, Module) self.assertIsInstance(module.default_rule, Rule) self.assertEqual(module.default_rule.export, "bar") def test_parse_toplevel_imports(self): input = dedent("""\ imports: foo: bar/ """) scope, imports = parse_string(input) self.assertDictEqual(scope.modules, {}) self.assertDictEqual(scope.rules, {}) self.assertEqual(imports, {'foo': ('bar/',)}) def test_parse_multimap_imports(self): input = dedent('''\ imports: foo: - bar/ ''') scope, imports = parse_string(input) self.assertDictEqual(scope.modules, {}) self.assertDictEqual(scope.rules, {}) self.assertEqual(imports, {'foo': ('bar/',)}) def test_parse_empty_imports(self): input = dedent('''\ imports: ''') scope, imports = parse_string(input) self.assertDictEqual(scope.modules, {}) self.assertDictEqual(scope.rules, {}) self.assertEqual(imports, {}) def test_parse_wrong_type_imports_throw(self): with self.assertRaises(ParserError): parse_string('imports: 5') def test_bad_toplevel_field_throw(self): with self.assertRaises(ParserError): parse_string("foo: bar") def test_bad_rule_field_throw(self): with self.assertRaises(ParserError): parse_string(dedent("""\ rule foo: bad_field: junk """)) def test_bad_rule_name_throw(self): with self.assertRaises(ParserError): parse_string("rule foo bar:") def test_bad_module_name_throw(self): with self.assertRaises(ParserError): parse_string("git module abc def:") with self.assertRaises(ParserError): parse_string("git module:") def test_duplicate_names_throw(self): # Modules and rules should not conflict. ok_input = dedent(''' rule foo: git module foo: ''') parse_string(ok_input) # But duplicate modules should fail. (Duplicate rules are a not # currently possible, because their YAML keys would be exact # duplicates.) bad_input = dedent(''' git module foo: hg module foo: ''') with self.assertRaises(ParserError): parse_string(bad_input) def test_non_string_module_field_name(self): input = dedent('''\ git module foo: 12345: bar ''') try: parse_string(input) except ParserError as e: assert '12345' in e.message else: assert False, 'expected ParserError' def test_non_string_module_field_value(self): input = dedent('''\ git module foo: bar: 4567 ''') try: parse_string(input) except ParserError as e: assert '4567' in e.message else: assert False, 'expected ParserError' def test_build_field_deprecated_message(self): input = dedent('''\ rule foo: build: shell command ''') try: parse_string(input) except ParserError as e: assert 'The "build" field is no longer supported.' in e.message else: assert False, 'expected ParserError' def test_name_prefix(self): input = dedent('''\ git module foo: url: fun stuff rule bar: export: more stuff ''') scope, imports = parse_string(input, name_prefix='x') # Lookup keys should be unaffected, but the names that modules and # rules give for themselves should have the prefix. assert scope.modules['foo'].name == 'xfoo' assert scope.rules['bar'].name == 'xbar' def test_forgotten_colon(self): # There are many different permutations of this error, and this only # tests the one mentioned in # https://github.com/keybase/client/issues/242. # TODO: A more general data validation library might help the parser do # a better job of checking these things. See # https://github.com/buildinspace/peru/issues/40. input = dedent('''\ rule test: pick bla ''') with self.assertRaises(ParserError): parse_string(input) def test_duplicate_key_heuristic(self): yaml = dedent('''\ a: a: 1 b: 1 b: a: 1 b: 1 a: 1 a : whitespace before colon a: stuff ''') duplicates = parser._get_duplicate_keys_approximate(yaml) self.assertEqual( [ ('a', 5, 7), ('a', 1, 8), ('a', 8, 9), ], duplicates)
""" Compute Engine definitions for the Pipeline API. """ from abc import ( ABCMeta, abstractmethod, ) from uuid import uuid4 from six import ( iteritems, with_metaclass, ) from six.moves import zip_longest from numpy import array from pandas import ( DataFrame, date_range, MultiIndex, ) from zipline.lib.adjusted_array import ensure_ndarray from zipline.errors import NoFurtherDataError from zipline.utils.numpy_utils import repeat_first_axis, repeat_last_axis from zipline.utils.pandas_utils import explode from .term import AssetExists class PipelineEngine(with_metaclass(ABCMeta)): @abstractmethod def run_pipeline(self, pipeline, start_date, end_date): """ Compute values for `pipeline` between `start_date` and `end_date`. Returns a DataFrame with a MultiIndex of (date, asset) pairs Parameters ---------- pipeline : zipline.pipeline.Pipeline The pipeline to run. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Timestamp End date of the computed matrix. Returns ------- result : pd.DataFrame A frame of computed results. The columns `result` correspond wil be the computed results of `pipeline.columns`, which should be a dictionary mapping strings to instances of `zipline.pipeline.term.Term`. For each date between `start_date` and `end_date`, `result` will contain a row for each asset that passed `pipeline.screen`. A screen of None indicates that a row should be returned for each asset that existed each day. """ raise NotImplementedError("run_pipeline") class NoOpPipelineEngine(PipelineEngine): """ A PipelineEngine that doesn't do anything. """ def run_pipeline(self, pipeline, start_date, end_date): return DataFrame( index=MultiIndex.from_product( [date_range(start=start_date, end=end_date, freq='D'), ()], ), columns=sorted(pipeline.columns.keys()), ) class SimplePipelineEngine(object): """ PipelineEngine class that computes each term independently. Parameters ---------- loader : PipelineLoader A loader to use to retrieve raw data for atomic terms. calendar : DatetimeIndex Array of dates to consider as trading days when computing a range between a fixed start and end. asset_finder : zipline.assets.AssetFinder An AssetFinder instance. We depend on the AssetFinder to determine which assets are in the top-level universe at any point in time. """ __slots__ = [ '_loader', '_calendar', '_finder', '_root_mask_term', '__weakref__', ] def __init__(self, loader, calendar, asset_finder): self._loader = loader self._calendar = calendar self._finder = asset_finder self._root_mask_term = AssetExists() def run_pipeline(self, pipeline, start_date, end_date): """ Compute a pipeline. Parameters ---------- pipeline : zipline.pipeline.Pipeline The pipeline to run. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Timestamp End date of the computed matrix. The algorithm implemented here can be broken down into the following stages: 0. Build a dependency graph of all terms in `terms`. Topologically sort the graph to determine an order in which we can compute the terms. 1. Ask our AssetFinder for a "lifetimes matrix", which should contain, for each date between start_date and end_date, a boolean value for each known asset indicating whether the asset existed on that date. 2. Compute each term in the dependency order determined in (0), caching the results in a a dictionary to that they can be fed into future terms. 3. For each date, determine the number of assets passing **all** filters. The sum, N, of all these values is the total number of rows in our output frame, so we pre-allocate an output array of length N for each factor in `terms`. 4. Fill in the arrays allocated in (3) by copying computed values from our output cache into the corresponding rows. 5. Stick the values computed in (4) into a DataFrame and return it. Step 0 is performed by `zipline.pipeline.graph.TermGraph`. Step 1 is performed in `self._compute_root_mask`. Step 2 is performed in `self.compute_chunk`. Steps 3, 4, and 5 are performed in self._format_factor_matrix. See Also -------- PipelineEngine.run_pipeline """ if end_date <= start_date: raise ValueError( "start_date must be before end_date \n" "start_date=%s, end_date=%s" % (start_date, end_date) ) screen_name = uuid4().hex graph = pipeline.to_graph(screen_name, self._root_mask_term) extra_rows = graph.extra_rows[self._root_mask_term] root_mask = self._compute_root_mask(start_date, end_date, extra_rows) dates, assets, root_mask_values = explode(root_mask) outputs = self.compute_chunk( graph, dates, assets, initial_workspace={self._root_mask_term: root_mask_values}, ) out_dates = dates[extra_rows:] screen_values = outputs.pop(screen_name) return self._to_narrow(outputs, screen_values, out_dates, assets) def _compute_root_mask(self, start_date, end_date, extra_rows): """ Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- start_date : pd.Timestamp Base start date for the matrix. end_date : pd.Timestamp End date for the matrix. extra_rows : int Number of extra rows to compute before `start_date`. Extra rows are needed by terms like moving averages that require a trailing window of data. Returns ------- lifetimes : pd.DataFrame Frame of dtype `bool` containing dates from `extra_rows` days before `start_date`, continuing through to `end_date`. The returned frame contains as columns all assets in our AssetFinder that existed for at least one day between `start_date` and `end_date`. """ calendar = self._calendar finder = self._finder start_idx, end_idx = self._calendar.slice_locs(start_date, end_date) if start_idx < extra_rows: raise NoFurtherDataError( msg="Insufficient data to compute Pipeline mask: " "start date was %s, " "earliest known date was %s, " "and %d extra rows were requested." % ( start_date, calendar[0], extra_rows, ), ) # Build lifetimes matrix reaching back to `extra_rows` days before # `start_date.` lifetimes = finder.lifetimes( calendar[start_idx - extra_rows:end_idx], include_start_date=False ) assert lifetimes.index[extra_rows] == start_date assert lifetimes.index[-1] == end_date if not lifetimes.columns.unique: columns = lifetimes.columns duplicated = columns[columns.duplicated()].unique() raise AssertionError("Duplicated sids: %d" % duplicated) # Filter out columns that didn't exist between the requested start and # end dates. existed = lifetimes.iloc[extra_rows:].any() return lifetimes.loc[:, existed] def _mask_and_dates_for_term(self, term, workspace, graph, dates): """ Load mask and mask row labels for term. """ mask = term.mask offset = graph.extra_rows[mask] - graph.extra_rows[term] return workspace[mask][offset:], dates[offset:] def _inputs_for_term(self, term, workspace, graph): """ Compute inputs for the given term. This is mostly complicated by the fact that for each input we store as many rows as will be necessary to serve **any** computation requiring that input. """ offsets = graph.offset if term.windowed: # If term is windowed, then all input data should be instances of # AdjustedArray. return [ workspace[input_].traverse( window_length=term.window_length, offset=offsets[term, input_] ) for input_ in term.inputs ] # If term is not windowed, input_data may be an AdjustedArray or # np.ndarray. Coerce the former to the latter. out = [] for input_ in term.inputs: input_data = ensure_ndarray(workspace[input_]) offset = offsets[term, input_] # OPTIMIZATION: Don't make a copy by doing input_data[0:] if # offset is zero. if offset: input_data = input_data[offset:] out.append(input_data) return out def compute_chunk(self, graph, dates, assets, initial_workspace): """ Compute the Pipeline terms in the graph for the requested start and end dates. Parameters ---------- graph : zipline.pipeline.graph.TermGraph dates : pd.DatetimeIndex Row labels for our root mask. assets : pd.Int64Index Column labels for our root mask. initial_workspace : dict Map from term -> output. Must contain at least entry for `self._root_mask_term` whose shape is `(len(dates), len(assets))`, but may contain additional pre-computed terms for testing or optimization purposes. Returns ------- results : dict Dictionary mapping requested results to outputs. """ self._validate_compute_chunk_params(dates, assets, initial_workspace) loader = self._loader # Copy the supplied initial workspace so we don't mutate it in place. workspace = initial_workspace.copy() for term in graph.ordered(): # `term` may have been supplied in `initial_workspace`, and in the # future we may pre-compute atomic terms coming from the same # dataset. In either case, we will already have an entry for this # term, which we shouldn't re-compute. if term in workspace: continue # Asset labels are always the same, but date labels vary by how # many extra rows are needed. mask, mask_dates = self._mask_and_dates_for_term( term, workspace, graph, dates ) if term.atomic: # FUTURE OPTIMIZATION: Scan the resolution order for terms in # the same dataset and load them here as well. to_load = [term] loaded = loader.load_adjusted_array( to_load, mask_dates, assets, mask, ) assert len(to_load) == len(loaded) for loaded_term, adj_array in zip_longest(to_load, loaded): workspace[loaded_term] = adj_array else: workspace[term] = term._compute( self._inputs_for_term(term, workspace, graph), mask_dates, assets, mask, ) assert(workspace[term].shape == mask.shape) out = {} graph_extra_rows = graph.extra_rows for name, term in iteritems(graph.outputs): # Truncate off extra rows from outputs. out[name] = workspace[term][graph_extra_rows[term]:] return out def _to_narrow(self, data, mask, dates, assets): """ Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- data : dict[str -> ndarray[ndim=2]] Dict mapping column names to computed results. mask : ndarray[bool, ndim=2] Mask array of values to keep. dates : ndarray[datetime64, ndim=1] Row index for arrays `data` and `mask` assets : ndarray[int64, ndim=2] Column index for arrays `data` and `mask` Returns ------- results : pd.DataFrame The indices of `results` are as follows: index : two-tiered MultiIndex of (date, asset). Contains an entry for each (date, asset) pair corresponding to a `True` value in `mask`. columns : Index of str One column per entry in `data`. If mask[date, asset] is True, then result.loc[(date, asset), colname] will contain the value of data[colname][date, asset]. """ resolved_assets = array(self._finder.retrieve_all(assets)) dates_kept = repeat_last_axis(dates.values, len(assets))[mask] assets_kept = repeat_first_axis(resolved_assets, len(dates))[mask] return DataFrame( data={name: arr[mask] for name, arr in iteritems(data)}, index=MultiIndex.from_arrays([dates_kept, assets_kept]), ).tz_localize('UTC', level=0) def _validate_compute_chunk_params(self, dates, assets, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed. """ root = self._root_mask_term clsname = type(self).__name__ # Writing this out explicitly so this errors in testing if we change # the name without updating this line. compute_chunk_name = self.compute_chunk.__name__ if root not in initial_workspace: raise AssertionError( "root_mask values not supplied to {cls}.{method}".format( cls=clsname, method=compute_chunk_name, ) ) shape = initial_workspace[root].shape implied_shape = len(dates), len(assets) if shape != implied_shape: raise AssertionError( "root_mask shape is {shape}, but received dates/assets " "imply that shape should be {implied}".format( shape=shape, implied=implied_shape, ) )
from cStringIO import StringIO import fudge import logging import socket from .. import run from teuthology.exceptions import (CommandCrashedError, CommandFailedError, ConnectionLostError) from .util import assert_raises class TestRun(object): @fudge.with_fakes def test_run_log_simple(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo 'bar baz'") in_ = fudge.Fake('ChannelFile(stdin)') out = fudge.Fake('ChannelFile(stdout)') err = fudge.Fake('ChannelFile(stderr)') cmd.returns((in_, out, err)) in_.expects('close').with_args() in_chan = fudge.Fake('channel') in_chan.expects('shutdown_write').with_args() in_.has_attr(channel=in_chan) out.expects('xreadlines').with_args().returns(['foo', 'bar']) err.expects('xreadlines').with_args().returns(['bad']) logger = fudge.Fake('logger') log_host = fudge.Fake('log_host') logger.expects('getChild').with_args('HOST').returns(log_host) log_err = fudge.Fake('log_err') log_host.expects('getChild').with_args('stderr').returns(log_err) log_err.expects('log').with_args(logging.INFO, 'bad') log_out = fudge.Fake('log_out') log_host.expects('getChild').with_args('stdout').returns(log_out) log_out.expects('log').with_args(logging.INFO, 'foo') log_out.expects('log').with_args(logging.INFO, 'bar') channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo', 'bar baz'], ) assert r.exitstatus == 0 @fudge.with_fakes def test_run_capture_stdout(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo 'bar baz'") in_ = fudge.Fake('ChannelFile(stdin)') out = fudge.Fake('ChannelFile(stdout)') err = fudge.Fake('ChannelFile(stderr)') cmd.returns((in_, out, err)) in_.expects('close').with_args() in_chan = fudge.Fake('channel') in_chan.expects('shutdown_write').with_args() in_.has_attr(channel=in_chan) out.remember_order() out.expects('read').with_args().returns('foo\nb') out.expects('read').with_args().returns('ar\n') out.expects('read').with_args().returns('') err.expects('xreadlines').with_args().returns(['bad']) logger = fudge.Fake('logger') log_host = fudge.Fake('log_host') logger.expects('getChild').with_args('HOST').returns(log_host) log_err = fudge.Fake('log_err') log_host.expects('getChild').with_args('stderr').returns(log_err) log_err.expects('log').with_args(logging.INFO, 'bad') channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(0) out_f = StringIO() r = run.run( client=ssh, logger=logger, args=['foo', 'bar baz'], stdout=out_f, ) assert r.exitstatus == 0 assert r.stdout is out_f assert r.stdout.getvalue() == 'foo\nbar\n' @fudge.with_fakes def test_run_status_bad(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(42) e = assert_raises( CommandFailedError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert e.exitstatus == 42 assert str(e) == "Command failed on HOST with status 42: 'foo'" @fudge.with_fakes def test_run_status_bad_nocheck(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(42) r = run.run( client=ssh, logger=logger, args=['foo'], check_status=False, ) assert r.exitstatus == 42 @fudge.with_fakes def test_run_status_crash(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) transport.expects('is_active').with_args().returns(True) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(-1) e = assert_raises( CommandCrashedError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert str(e) == "Command crashed: 'foo'" @fudge.with_fakes def test_run_status_crash_nocheck(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(-1) r = run.run( client=ssh, logger=logger, args=['foo'], check_status=False, ) assert r.exitstatus is None @fudge.with_fakes def test_run_status_lost(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(-1) transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) transport.expects('is_active').with_args().returns(False) e = assert_raises( ConnectionLostError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert str(e) == "SSH connection to HOST was lost: 'foo'" @fudge.with_fakes def test_run_status_lost_socket(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') out = fudge.Fake('ChannelFile').is_a_stub() logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().raises(socket.error) e = assert_raises( ConnectionLostError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert str(e) == "SSH connection was lost: 'foo'" @fudge.with_fakes def test_run_status_lost_nocheck(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(-1) r = run.run( client=ssh, logger=logger, args=['foo'], check_status=False, ) assert r.exitstatus is None @fudge.with_fakes def test_run_nowait(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(42) r = run.run( client=ssh, logger=logger, args=['foo'], wait=False, ) assert r.command == 'foo' e = assert_raises( CommandFailedError, r.wait, ) assert r.returncode == 42 assert str(e) == "Command failed on HOST with status 42: 'foo'" @fudge.with_fakes def test_run_stdin_pipe(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('exit_status_ready').with_args().returns(False) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo'], stdin=run.PIPE, wait=False, ) r.stdin.write('bar') assert r.command == 'foo' assert r.poll() is None got = r.wait() assert isinstance(r.returncode, int) assert got == 0 @fudge.with_fakes def test_run_stdout_pipe(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('read').with_args().returns('one') out.expects('read').with_args().returns('two') out.expects('read').with_args().returns('') err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('exit_status_ready').with_args().returns(False) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo'], stdout=run.PIPE, wait=False, ) assert r.exitstatus is None assert r.command == 'foo' assert r.poll() is None assert r.stdout.read() == 'one' assert r.stdout.read() == 'two' assert r.stdout.read() == '' got = r.wait() assert isinstance(r.exitstatus, int) assert got == 0 @fudge.with_fakes def test_run_stderr_pipe(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('read').with_args().returns('one') err.expects('read').with_args().returns('two') err.expects('read').with_args().returns('') logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('exit_status_ready').with_args().returns(False) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo'], stderr=run.PIPE, wait=False, ) assert r.exitstatus is None assert r.command == 'foo' assert r.poll() is None assert r.stderr.read() == 'one' assert r.stderr.read() == 'two' assert r.stderr.read() == '' got = r.wait() assert isinstance(r.exitstatus, int) assert got == 0 def test_quote_simple(self): got = run.quote(['a b', ' c', 'd e ']) assert got == "'a b' ' c' 'd e '" def test_quote_and_quote(self): got = run.quote(['echo', 'this && is embedded', '&&', 'that was standalone']) assert got == "echo 'this && is embedded' '&&' 'that was standalone'" def test_quote_and_raw(self): got = run.quote(['true', run.Raw('&&'), 'echo', 'yay']) assert got == "true && echo yay"
# -*- coding: utf-8 -*- """Windows UserAssist information collector.""" import codecs import logging from winregrc import data_format from winregrc import errors from winregrc import interface class UserAssistEntry(object): """UserAssist entry. Attributes: guid (str): GUID. name (str): name. value_name (str): name of the Windows Registry value. """ def __init__(self, guid=None, name=None, value_name=None): """Initializes an UserAssist entry. Args: guid (Optional[str]): GUID. name (Optional[str]): name. value_name (Optional[str]): name of the Windows Registry value. """ super(UserAssistEntry, self).__init__() self.guid = guid self.name = name self.value_name = value_name class UserAssistDataParser(data_format.BinaryDataFormat): """UserAssist data parser.""" _DEFINITION_FILE = 'userassist.yaml' # pylint: disable=missing-type-doc def _DebugPrintEntry(self, format_version, user_assist_entry): """Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist entry. """ value_string = '0x{0:08x}'.format(user_assist_entry.unknown1) self._DebugPrintValue('Unknown1', value_string) self._DebugPrintDecimalValue( 'Number of executions', user_assist_entry.number_of_executions) if format_version == 5: self._DebugPrintDecimalValue( 'Application focus count', user_assist_entry.application_focus_count) self._DebugPrintDecimalValue( 'Application focus duration', user_assist_entry.application_focus_duration) value_string = '{0:.2f}'.format(user_assist_entry.unknown2) self._DebugPrintValue('Unknown2', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown3) self._DebugPrintValue('Unknown3', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown4) self._DebugPrintValue('Unknown4', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown5) self._DebugPrintValue('Unknown5', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown6) self._DebugPrintValue('Unknown6', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown7) self._DebugPrintValue('Unknown7', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown8) self._DebugPrintValue('Unknown8', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown9) self._DebugPrintValue('Unknown9', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown10) self._DebugPrintValue('Unknown10', value_string) value_string = '{0:.2f}'.format(user_assist_entry.unknown11) self._DebugPrintValue('Unknown11', value_string) value_string = '0x{0:08x}'.format(user_assist_entry.unknown12) self._DebugPrintValue('Unknown12', value_string) self._DebugPrintFiletimeValue( 'Last execution time', user_assist_entry.last_execution_time) if format_version == 5: value_string = '0x{0:08x}'.format(user_assist_entry.unknown13) self._DebugPrintValue('Unknown13', value_string) self._DebugPrintText('\n') # pylint: disable=missing-return-type-doc def ParseEntry(self, format_version, entry_data): """Parses an UserAssist entry. Args: format_version (int): format version. entry_data (bytes): entry data. Returns: user_assist_entry_v3|user_assist_entry_v5: UserAssist entry. Raises: ParseError: if the value data could not be parsed. """ if format_version == 3: data_type_map = self._GetDataTypeMap('user_assist_entry_v3') elif format_version == 5: data_type_map = self._GetDataTypeMap('user_assist_entry_v5') entry_data_size = data_type_map.GetByteSize() if entry_data_size != len(entry_data): raise errors.ParseError(( 'Version: {0:d} size mismatch (calculated: {1:d}, ' 'stored: {2:d}).').format( format_version, entry_data_size, len(entry_data))) try: user_assist_entry = self._ReadStructureFromByteStream( entry_data, 0, data_type_map, 'UserAssist entry') except (ValueError, errors.ParseError) as exception: raise errors.ParseError( 'Unable to parse UserAssist entry value with error: {0!s}'.format( exception)) if self._debug: self._DebugPrintEntry(format_version, user_assist_entry) return user_assist_entry class UserAssistCollector(interface.WindowsRegistryKeyCollector): """Windows UserAssist information collector. Returns: user_assist_entries (list[UserAssistEntry]): UserAssist entries. """ _USER_ASSIST_KEY = ( 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\' 'Explorer\\UserAssist') def __init__(self, debug=False, output_writer=None): """Initializes a Windows UserAssist information collector. Args: debug (Optional[bool]): True if debug information should be printed. output_writer (Optional[OutputWriter]): output writer. """ super(UserAssistCollector, self).__init__(debug=debug) self._output_writer = output_writer self._parser = UserAssistDataParser( debug=debug, output_writer=output_writer) self.user_assist_entries = [] def _CollectUserAssistFromKey(self, guid_subkey): """Collects the UserAssist information from a GUID sub key. Args: guid_subkey (dfwinreg.WinRegistryKey): UserAssist GUID Registry key. """ version_value = guid_subkey.GetValueByName('Version') if not version_value: logging.warning('Missing Version value in sub key: {0:s}'.format( guid_subkey.name)) return format_version = version_value.GetDataAsObject() if self._debug: self._output_writer.WriteValue('GUID', guid_subkey.name) self._output_writer.WriteIntegerValueAsDecimal( 'Format version', format_version) self._output_writer.WriteText('\n') count_subkey = guid_subkey.GetSubkeyByName('Count') for value in count_subkey.GetValues(): if self._debug: self._output_writer.WriteValue('Original name', value.name) try: # Note that Python 2 codecs.decode() does not support keyword arguments # such as encodings='rot-13'. value_name = codecs.decode(value.name, 'rot-13') except UnicodeEncodeError: characters = [] for character in value.name: if ord(character) < 128: try: character = codecs.decode(character, 'rot-13') characters.append(character) except UnicodeEncodeError: characters.append(character) else: characters.append(character) value_name = ''.join(characters) if self._debug: self._output_writer.WriteValue('Converted name', value_name) self._output_writer.WriteDebugData('Value data:', value.data) if value_name != 'UEME_CTLSESSION': user_assist_entry = self._parser.ParseEntry(format_version, value.data) user_assist_entry = UserAssistEntry( guid=guid_subkey.name, name=value_name, value_name=value.name) self.user_assist_entries.append(user_assist_entry) def Collect(self, registry): # pylint: disable=arguments-differ """Collects the UserAssist information. Args: registry (dfwinreg.WinRegistry): Windows Registry. Returns: bool: True if the UserAssist key was found, False if not. """ user_assist_key = registry.GetKeyByPath(self._USER_ASSIST_KEY) if not user_assist_key: return False for guid_subkey in user_assist_key.GetSubkeys(): self._CollectUserAssistFromKey(guid_subkey) return True
import glob import pandas as pd import numpy as np pd.set_option('display.max_columns', 50) # print all rows import os os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/correct_phylo_files") cw154 = glob.glob("binary_position_RRBS_cw154*") trito = glob.glob("binary_position_RRBS_trito_pool*") print(len(cw154)) print(len(trito)) totalfiles = cw154 + trito print(len(totalfiles)) df_list = [] for file in totalfiles: df = pd.read_csv(file) df = df.drop("Unnamed: 0", axis=1) df_list.append(df) print(len(df_list)) total_matrix = pd.concat([df.set_index("position") for df in df_list], axis=1).reset_index().astype(object) indexed_matrix = total_matrix ## keep a copy for index of genomic coordinates total_matrix = total_matrix.drop("index", axis=1) drop_columns = total_matrix ## keep copy in order to create 0/1/? matrix such that each character is a column len(drop_columns.columns) len(total_matrix.columns) cell_samples = ['RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACAACC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACCGCG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACGTGG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACTCAC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.AGGATG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ATAGCG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ATCGAC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CAAGAG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CATGAC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CCTTCG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CGGTAG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CTCAGC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GACACG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GCATTC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GCTGCC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GGCATC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GTGAGG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.TAGCGG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.TATCTC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.TCTCTG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACAACC', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACCGCG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACGTGG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACTCAC', 'RRBS_cw154_Tris_protease_CTCTCTAC.AGGATG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ATAGCG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ATCGAC', 'RRBS_cw154_Tris_protease_CTCTCTAC.CATGAC', 'RRBS_cw154_Tris_protease_CTCTCTAC.CCTTCG', 'RRBS_cw154_Tris_protease_CTCTCTAC.CGGTAG', 'RRBS_cw154_Tris_protease_CTCTCTAC.CTATTG', 'RRBS_cw154_Tris_protease_CTCTCTAC.CTCAGC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GACACG', 'RRBS_cw154_Tris_protease_CTCTCTAC.GCATTC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GCTGCC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GGCATC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GTGAGG', 'RRBS_cw154_Tris_protease_CTCTCTAC.GTTGAG', 'RRBS_cw154_Tris_protease_CTCTCTAC.TAGCGG', 'RRBS_cw154_Tris_protease_CTCTCTAC.TATCTC', 'RRBS_cw154_Tris_protease_CTCTCTAC.TCTCTG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACAACC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACCGCG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACGTGG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACTCAC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.AGGATG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ATAGCG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ATCGAC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CATGAC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CCTTCG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CGGTAG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CTATTG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CTCAGC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GACACG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GCATTC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GCTGCC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GGCATC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GTGAGG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GTTGAG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.TAGCGG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.TATCTC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.TCTCTG', 'RRBS_trito_pool_1_TAAGGCGA.ACAACC', 'RRBS_trito_pool_1_TAAGGCGA.ACGTGG', 'RRBS_trito_pool_1_TAAGGCGA.ACTCAC', 'RRBS_trito_pool_1_TAAGGCGA.ATAGCG', 'RRBS_trito_pool_1_TAAGGCGA.ATCGAC', 'RRBS_trito_pool_1_TAAGGCGA.CAAGAG', 'RRBS_trito_pool_1_TAAGGCGA.CATGAC', 'RRBS_trito_pool_1_TAAGGCGA.CCTTCG', 'RRBS_trito_pool_1_TAAGGCGA.CGGTAG', 'RRBS_trito_pool_1_TAAGGCGA.CTATTG', 'RRBS_trito_pool_1_TAAGGCGA.GACACG', 'RRBS_trito_pool_1_TAAGGCGA.GCATTC', 'RRBS_trito_pool_1_TAAGGCGA.GCTGCC', 'RRBS_trito_pool_1_TAAGGCGA.GGCATC', 'RRBS_trito_pool_1_TAAGGCGA.GTGAGG', 'RRBS_trito_pool_1_TAAGGCGA.GTTGAG', 'RRBS_trito_pool_1_TAAGGCGA.TAGCGG', 'RRBS_trito_pool_1_TAAGGCGA.TATCTC', 'RRBS_trito_pool_1_TAAGGCGA.TCTCTG', 'RRBS_trito_pool_1_TAAGGCGA.TGACAG', 'RRBS_trito_pool_1_TAAGGCGA.TGCTGC', 'RRBS_trito_pool_2_CGTACTAG.ACAACC', 'RRBS_trito_pool_2_CGTACTAG.ACGTGG', 'RRBS_trito_pool_2_CGTACTAG.ACTCAC', 'RRBS_trito_pool_2_CGTACTAG.AGGATG', 'RRBS_trito_pool_2_CGTACTAG.ATAGCG', 'RRBS_trito_pool_2_CGTACTAG.ATCGAC', 'RRBS_trito_pool_2_CGTACTAG.CAAGAG', 'RRBS_trito_pool_2_CGTACTAG.CATGAC', 'RRBS_trito_pool_2_CGTACTAG.CCTTCG', 'RRBS_trito_pool_2_CGTACTAG.CGGTAG', 'RRBS_trito_pool_2_CGTACTAG.CTATTG', 'RRBS_trito_pool_2_CGTACTAG.GACACG', 'RRBS_trito_pool_2_CGTACTAG.GCATTC', 'RRBS_trito_pool_2_CGTACTAG.GCTGCC', 'RRBS_trito_pool_2_CGTACTAG.GGCATC', 'RRBS_trito_pool_2_CGTACTAG.GTGAGG', 'RRBS_trito_pool_2_CGTACTAG.GTTGAG', 'RRBS_trito_pool_2_CGTACTAG.TAGCGG', 'RRBS_trito_pool_2_CGTACTAG.TATCTC', 'RRBS_trito_pool_2_CGTACTAG.TCTCTG', 'RRBS_trito_pool_2_CGTACTAG.TGACAG'] total_matrix.columns = cell_samples print(total_matrix.shape) ## >>> print(total_matrix.shape) ## (6336559, 104) drop_columns = drop_columns.applymap(lambda x: int(x) if pd.notnull(x) else str("?")) drop_columns = drop_columns.astype(str).apply(''.join) drop_columns = drop_columns.reset_index() total_matrix = total_matrix.applymap(lambda x: int(x) if pd.notnull(x) else str("?")) total_matrix = total_matrix.astype(str).apply(''.join) os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/CLL_tests") tott = pd.Series(total_matrix.index.astype(str).str.cat(total_matrix.astype(str),' ')) tott_drop_columns = pd.Series(drop_columns.index.astype(str).str.cat(total_matrix.astype(str),' ')) ## [104 rows x 6336566 columns] print(tott.shape) print(tott_drop_columns.shape) df_tott_column_position = tott_drop_columns.apply(lambda x: pd.Series(list(x))) ## [104 rows x 6336566 columns] ## extra NaN's here df_tott_column_position_T = df_tott_column_position.T ## create transpose, and shift on columns [I don't think there is a pandas-efficient way to shift row elements left/right systematically] for i in range(10): ## 0 to 9 df_tott_column_position_T[i]= df_tott_column_position_T[i].shift(2) for i in range(90): j = i + 10 ## 10 to 99 df_tott_column_position_T[j]= df_tott_column_position_T[j].shift(1) df_tott_column_position = df_tott_column_position_T.T df_tott_column_position.drop( df_tott_column_position.columns[[i for i in range(7)]], axis=1, inplace=True) ## drop first 6 columns ### rename columns indexed_matrixT = indexed_matrix.T df_tott_column_position.columns = indexed_matrixT.ix[0] integers_to_sort = df_tott_column_position.columns.to_series().str.extract("([a-z-A-Z]+)(\d*)_(\d+)", expand=True) # use str.extract to get integers to sort integers_to_sort[1] = integers_to_sort[1].str.zfill(2) integers_to_sort[2] = integers_to_sort[2].str.zfill(10) integers_to_sort["new_coordinates"] = integers_to_sort.apply(lambda x: "{}{}_{}".format(x[0],x[1],x[2]), axis=1) df_tott_column_position.columns = integers_to_sort["new_coordinates"] df_tott_column_position.columns.name = None df_tott_column_position = df_tott_column_position.sort_index(axis=1) df_tott_column_position = df_tott_column_position.T df_tott_column_position = df_tott_column_position.astype(str).apply(''.join) new = pd.Series(cell_samples) + " " + df_tott_column_position new.to_csv("total_CLL_all_sorted.phy", header=None, index=None)
# -*- coding: utf-8 -*- """ Sahana Eden Setup Model @copyright: 2015-2016 (c) Sahana Software Foundation @license: MIT 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. """ __all__ = ("S3DeployModel", "setup_create_yaml_file", "setup_create_playbook", "setup_get_templates", "setup_get_prepop_options", "setup_log", "setup_rheader", "setup_management_exists", "setup_UpgradeMethod", "setup_refresh", "setup_getupgrades", "setup_host_validator", "setup_upgrade_status", ) from ..s3 import * from gluon import * import os import socket import shutil import time try: import ansible.playbook import ansible.inventory from ansible import callbacks except ImportError: current.log.warning("ansible module needed for Setup") try: import yaml except ImportError: current.log.warning("PyYAML module needed for Setup") TIME_FORMAT = "%b %d %Y %H:%M:%S" MSG_FORMAT = "%(now)s - %(category)s - %(data)s\n\n" class S3DeployModel(S3Model): names = ("setup_deployment", "setup_server", "setup_instance", "setup_host", "setup_packages", "setup_upgrade" ) def model(self): T = current.T s3 = current.response.s3 define_table = self.define_table configure = self.configure add_components = self.add_components set_method = self.set_method tablename = "setup_deployment" define_table(tablename, Field("name", label = T("Name"), required = True, ), Field("distro", label = T("Linux Distribution"), required = True, requires = IS_IN_SET( [ ("wheezy", "Debian Wheezy"), ("precise", "Ubuntu 14.04 LTS Precise"), ]) ), Field("remote_user", label = T("Remote User"), required = True, ), Field("secret_key", label = T("AWS Secret Key"), required = True, ), Field("access_key", label = T("AWS Access Key"), required = True, ), Field("private_key", "upload", custom_retrieve = retrieve_file, custom_store = store_file, label = T("Private Key"), length = current.MAX_FILENAME_LENGTH, required = True, ), Field("webserver_type", "integer", label = T("Web Server"), required = True, requires = IS_IN_SET({1:"apache", 2:"cherokee"}), ), Field("db_type", "integer", label = T("Database"), required = True, requires = IS_IN_SET({1:"mysql", 2: "postgresql"}), ), Field("db_password", "password", label = T("Database Password"), required = True, readable = False, ), Field("repo_url", # @ToDo: Add more advanced options default = "https://github.com/flavour/eden", label = T("Eden Repo git URL"), ), # @ToDo: Allow Multiple Field("template", label = T("Template"), required = True, requires = IS_IN_SET(setup_get_templates(), zero=None), ), Field("refresh_lock", "integer", default = 0, readable = False, writable = False, ), Field("last_refreshed", "datetime", readable = False, writable = False, ), *s3_meta_fields() ) # CRUD Strings s3.crud_strings[tablename] = Storage( label_create_button = T("Add Deployment"), label_list_button = T("View Deployments"), label_delete_button = T("Delete Deployment"), msg_record_created = T("Deployment Created"), msg_record_modified = T("Deployment updated"), msg_record_deleted = T("Deployment deleted"), msg_list_empty = T("No Deployment Saved yet"), subtitle_create = T("Add Deployment"), title_create = T("Add Deployment"), title_list = T("View Deployments"), title_update = T("Edit Deployment"), ) configure(tablename, editable = False, deletable = False, insertable = True, listadd = True ) tablename = "setup_server" define_table(tablename, Field("deployment_id", "reference setup_deployment"), Field("role", "integer", requires = IS_IN_SET({1: "all", 2: "db", 3: "webserver", 4: "eden", }), ), Field("host_ip", required = True, ), Field("hostname", label = "Hostname", required = True, ), ) configure(tablename, onvalidation = server_validation ) tablename = "setup_instance" define_table(tablename, Field("deployment_id", "reference setup_deployment"), Field("type", "integer", requires = IS_IN_SET({1: "prod", 2: "test", 3: "demo", 4: "dev"}) ), Field("url", requires = IS_URL(), ), Field("prepop_options", label = "Prepop Options", required = True, requires = IS_IN_SET([], multiple=True), ), Field("scheduler_id", "reference scheduler_task", readable = False, writable = False, ), ) configure(tablename, deletable = False, editable = False, onaccept = instance_onaccept, ) add_components("setup_deployment", setup_instance = "deployment_id", setup_server = "deployment_id", ) tablename = "setup_packages" define_table(tablename, Field("name", label = T("Package Name"), ), Field("cv", label = T("Current Version"), ), Field("av", label = T("Available Version"), ), Field("type", label = T("Type of Package"), requires = IS_IN_SET(["os", "pip", "git"]), ), Field("deployment", "reference setup_deployment", ), ) tablename = "setup_upgrade" define_table(tablename, Field("deployment", "reference setup_deployment" ), Field("scheduler", "reference scheduler_task" ), ) set_method("setup", "deploy", method = "upgrade", action = setup_UpgradeMethod, ) return {} # ------------------------------------------------------------------------- def defaults(self): """ Safe defaults for model-global names in case module is disabled """ return {} # ----------------------------------------------------------------------------- def server_validation(form): ip = form.vars.host_ip table = current.s3db.setup_server db = current.db rows = db(table.host_ip == ip).select() if rows: form.errors["host_ip"] = "Server already in use" # ----------------------------------------------------------------------------- def instance_onaccept(form): db = current.db s3db = current.s3db form_vars = form.vars # Get deployment id itable = s3db.setup_instance instance = db(itable.id == form_vars.id).select(itable.deployment_id, limitby = (0, 1) ).first() deployment_id = instance.deployment_id stable = s3db.setup_server query = (stable.deployment_id == deployment_id) rows = db(query).select(stable.role, stable.host_ip, stable.hostname, orderby = stable.role ) hosts = [] for row in rows: hosts.append((row.role, row.host_ip)) if row.role == 1 or row.role == 4: hostname = row.hostname dtable = s3db.setup_deployment deployment = db(dtable.id == deployment_id).select(dtable.db_password, dtable.webserver_type, dtable.db_type, dtable.distro, dtable.template, dtable.private_key, dtable.remote_user, limitby=(0, 1) ).first() prepop_options = str(",".join(form_vars.prepop_options)) instance_type = int(form_vars.type) if instance_type == 2: demo_type = "na" elif instance_type == 1 or instance_type == 3: # find dtype sctable = s3db.scheduler_task query = (itable.deployment_id == deployment_id) & \ (sctable.status == "COMPLETED") existing_instances = db(query).select(itable.type, join = sctable.on(itable.scheduler_id == sctable.id) ) if existing_instances: demo_type = "afterprod" else: demo_type = "beforeprod" webservers = ("apache", "cherokee") dbs = ("mysql", "postgresql") prepop = ("prod", "test", "demo") scheduler_id = setup_create_yaml_file(hosts, deployment.db_password, webservers[deployment.webserver_type - 1], dbs[deployment.db_type - 1], prepop[instance_type - 1], prepop_options, deployment.distro, False, hostname, deployment.template, form_vars.url, deployment.private_key, deployment.remote_user, demo_type, ) # add scheduler fk in current record record = db(itable.id == form_vars.id).select().first() record.update_record(scheduler_id=scheduler_id) # ----------------------------------------------------------------------------- def setup_create_yaml_file(hosts, password, web_server, database_type, prepop, prepop_options, distro, local=False, hostname=None, template="default", sitename=None, private_key=None, remote_user=None, demo_type=None): roles_path = "../private/playbook/roles/" if len(hosts) == 1: deployment = [ { "hosts": hosts[0][1], "sudo": True, "remote_user": remote_user, "vars": { "password": password, "template": template, "web_server": web_server, "type": prepop, "distro": distro, "prepop_options": prepop_options, "sitename": sitename, "hostname": hostname, "dtype": demo_type, "eden_ip": hosts[0][1], "db_ip": hosts[0][1], "db_type": database_type }, "roles": [ "%s%s" % (roles_path, database_type), "%scommon" % roles_path, "%suwsgi" % roles_path, "%sconfigure" % roles_path, "%s%s" % (roles_path, web_server), ] } ] else: deployment = [ { "hosts": hosts[0][1], "sudo": True, "remote_user": remote_user, "vars": { "distro": distro, "dtype": demo_type, "password": password, "type": prepop }, "roles": [ "%s%s" % (roles_path, database_type), ] }, { "hosts": hosts[2][1], "sudo": True, "remote_user": remote_user, "vars": { "dtype": demo_type, "db_ip": hosts[0][1], "db_type": database_type, "hostname": hostname, "password": password, "prepop_options": prepop_options, "sitename": sitename, "template": template, "type": prepop, "web_server": web_server, }, "roles": [ "%scommon" % roles_path, "%suwsgi" % roles_path, "%sconfigure" % roles_path, ] }, { "hosts": hosts[1][1], "sudo": True, "remote_user": remote_user, "vars": { "eden_ip": hosts[2][1], "type": prepop }, "roles": [ "%s%s" % (roles_path, web_server), ] } ] if demo_type == "afterprod": only_tags = ["demo"] elif prepop == "test": only_tags = ["test",] else: only_tags = ["all"] directory = os.path.join(current.request.folder, "yaml") name = "deployment_%d" % int(time.time()) file_path = os.path.join(directory, "%s.yml" % name) if not os.path.isdir(directory): os.mkdir(directory) with open(file_path, "w") as yaml_file: yaml_file.write(yaml.dump(deployment, default_flow_style=False)) row = current.s3task.schedule_task( name, vars = { "playbook": file_path, "private_key": os.path.join(current.request.folder, "uploads", private_key), "host": [host[1] for host in hosts], "only_tags": only_tags, }, function_name = "deploy", repeats = 1, timeout = 3600, sync_output = 300 ) return row # ----------------------------------------------------------------------------- def setup_create_playbook(playbook, hosts, private_key, only_tags): inventory = ansible.inventory.Inventory(hosts) #playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() # runner_cb = callbacks.PlaybookRunnerCallbacks( # stats, verbose=utils.VERBOSITY) head, tail = os.path.split(playbook) deployment_name = tail.rsplit(".")[0] cb = CallbackModule(deployment_name) pb = ansible.playbook.PlayBook( playbook = playbook, inventory = inventory, callbacks = cb, runner_callbacks = cb, stats = stats, private_key_file = private_key, only_tags = only_tags ) return pb # ----------------------------------------------------------------------------- def setup_get_prepop_options(template): module_name = "applications.eden_deployment.modules.templates.%s.config" % template __import__(module_name) config = sys.modules[module_name] prepopulate_options = config.settings.base.get("prepopulate_options") if isinstance(prepopulate_options, dict): if "mandatory" in prepopulate_options: del prepopulate_options["mandatory"] return prepopulate_options.keys() else: return ["mandatory"] # ----------------------------------------------------------------------------- def setup_log(filename, category, data): if type(data) == dict: if 'verbose_override' in data: # avoid logging extraneous data from facts data = 'omitted' else: data = data.copy() invocation = data.pop('invocation', None) data = json.dumps(data) if invocation is not None: data = json.dumps(invocation) + " => %s " % data path = os.path.join(current.request.folder, "yaml", "%s.log" % filename) now = time.strftime(TIME_FORMAT, time.localtime()) fd = open(path, "a") fd.write(MSG_FORMAT % dict(now=now, category=category, data=data)) fd.close() # ----------------------------------------------------------------------------- def setup_get_templates(): path = os.path.join(current.request.folder, "modules", "templates") templates = set(os.path.basename(folder) for folder, subfolders, files in os.walk(path) \ for file_ in files if file_ == "config.py" ) return templates # ----------------------------------------------------------------------------- def store_file(file, filename=None, path=None): path = os.path.join(current.request.folder, "uploads") if not os.path.exists(path): os.makedirs(path) pathfilename = os.path.join(path, filename) dest_file = open(pathfilename, 'wb') try: shutil.copyfileobj(file, dest_file) finally: dest_file.close() os.chmod(pathfilename, 0600) return filename # ----------------------------------------------------------------------------- def retrieve_file(filename, path=None): path = os.path.join(current.request.folder, "uploads") return (filename, open(os.path.join(path, filename), 'rb')) # ----------------------------------------------------------------------------- class CallbackModule(object): """ logs playbook results, per deployment in eden/yaml """ def __init__(self, filename): self.filename = filename def on_any(self, *args, **kwargs): pass def on_failed(self, host, res, ignore_errors=False): setup_log(self.filename, 'FAILED', res) def on_ok(self, host, res): setup_log(self.filename, 'OK', res) def on_error(self, host, msg): setup_log(self.filename, 'ERROR', msg) def on_skipped(self, host, item=None): setup_log(self.filename, 'SKIPPED', '...') def on_unreachable(self, host, res): setup_log(self.filename, 'UNREACHABLE', res) def on_no_hosts(self): pass def on_async_poll(self, host, res, jid, clock): setup_log(self.filename, 'DEBUG', host, res, jid, clock) def on_async_ok(self, host, res, jid): setup_log(self.filename, 'DEBUG', host, res, jid) def on_async_failed(self, host, res, jid): setup_log(self.filename, 'ASYNC_FAILED', res) def on_start(self): setup_log(self.filename, 'DEBUG', 'on_start') def on_notify(self, host, handler): setup_log(self.filename, 'DEBUG', host) def on_no_hosts_matched(self): setup_log(self.filename, 'DEBUG', 'no_hosts_matched') def on_no_hosts_remaining(self): setup_log(self.filename, 'DEBUG', 'no_hosts_remaining') def on_task_start(self, name, is_conditional): setup_log(self.filename, 'DEBUG', 'Starting %s' % name) def on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None): pass def on_setup(self): setup_log(self.filename, 'DEBUG', 'on_setup') def on_import_for_host(self, host, imported_file): setup_log(self.filename, 'IMPORTED', imported_file) def on_not_import_for_host(self, host, missing_file): setup_log(self.filename, 'NOTIMPORTED', missing_file) def on_play_start(self, pattern): setup_log(self.filename, 'play_start', pattern) def on_stats(self, stats): setup_log(self.filename, 'DEBUG', stats) # ----------------------------------------------------------------------------- def setup_rheader(r, tabs=[]): """ Resource component page header """ if r.representation == "html": T = current.T tabs = [(T("Deployment Details"), None), (T("Servers"), "server"), (T("Instances"), "instance"), ] rheader_tabs = s3_rheader_tabs(r, tabs) rheader = DIV(rheader_tabs) return rheader # ----------------------------------------------------------------------------- def setup_management_exists(_type, _id, deployment_id): """ Returns true/false depending on whether a management task exists for an instance """ db = current.db ttable = current.s3db.scheduler_task args = '["%s", "%s", "%s"]' % (_type, _id, deployment_id) query = ((ttable.function_name == "setup_management") & \ (ttable.args == args) & \ (ttable.status.belongs(["RUNNING", "QUEUED", "ASSIGNED"]))) exists = db(query).select(ttable.id, limitby = (0, 1)).first() if exists: return True return False # ----------------------------------------------------------------------------- class setup_UpgradeMethod(S3Method): def apply_method(self, r, **attr): s3db = current.s3db db = current.db T = current.T response = current.response record = r.record dtable = s3db.setup_deploy stable = s3db.scheduler_task query = (dtable.host == record.host) & \ (stable.status == "COMPLETED") machines = db(query).select( dtable.id.with_alias("deployment"), dtable.type.with_alias("type"), join = [ stable.on(dtable.scheduler_id == stable.id) ], distinct = True ) machine_ids = [machine.deployment for machine in machines] validate = s3db.setup_host_validator(machine_ids) if r.http == "GET": if record.last_refreshed is None: redirect(URL(c="setup", f="refresh", args=record.id)) # Data table resource = s3db.resource("setup_packages") totalrows = resource.count() list_fields = ["id", "name", "cv", "av", ] package_filter = (s3db.setup_packages.deployment == record.id) & \ (s3db.setup_packages.cv != s3db.setup_packages.av) resource.add_filter(package_filter) data = resource.select(list_fields, limit = totalrows, ) dt = S3DataTable(data["rfields"], data["rows"]) dt_id = "datatable" if validate is not None: dt_bulk_actions = None appname = current.request.application current.response.s3.scripts.append("/%s/static/scripts/S3/s3.setup.js" % appname) else: dt_bulk_actions = [(T("Upgrade"), "upgrade")] items = dt.html(totalrows, totalrows, dt_pagination = "false", dt_bulk_actions = dt_bulk_actions, ) output = dict(items=items) response.view = "list.html" elif r.http == "POST": if validate is not None: current.session.error = validate redirect(URL(c="setup", f="%s_deploy" % record.type, args=[record.id, "upgrade"])) post_vars = r.post_vars ptable = s3db.setup_packages selected = post_vars.selected if selected: selected = selected.split(",") else: selected = [] # query = ptable.id.belongs(selected) # packages = db(query).select() query = FS("id").belongs(selected) presource = s3db.resource("setup_packages", filter=query) packages = presource.select(["name", "type"], as_rows=True) system_packages = [] pip_packages = [] git_packages = [] for package in packages: if package.type == "os": system_packages.append(package.name) elif package.type == "pip": pip_packages.append(package.name) elif package.type == "git": if package.name == "web2py": git_packages.append({name: package.name, chdir: "/home/%s" % record.type}) directory = os.path.join(current.request.folder, "yaml") name = "upgrade_%d" % int(time.time()) file_path = os.path.join(directory, "%s.yml" % name) roles_path = "../private/playbook/roles/" upgrade = [ { "hosts": record.host, "sudo": True, "vars": { "system_packages": system_packages, "pip_packages": pip_packages, "git_packages": git_packages, }, "roles": [ "%supgrades" % roles_path, ] } ] if record.type == "remote": upgrade[0]["remote_user"] = record.remote_user else: upgrade[0]["connection"] = "local" if not os.path.isdir(directory): os.mkdir(directory) with open(file_path, "w") as yaml_file: yaml_file.write(yaml.dump(upgrade, default_flow_style=False)) if record.private_key: private_key = os.path.join(current.request.folder, "uploads", record.private_key) else: private_key = None only_tags = ['all'] row = current.s3task.schedule_task( name, vars = { "playbook": file_path, "private_key": private_key, "host": [record.host], "only_tags": only_tags, }, function_name = "deploy", repeats = 1, timeout = 3600, sync_output = 300 ) # Add record to setup_upgrade utable = s3db.setup_upgrade utable.insert(deployment=record.id, scheduler=row.id) current.session.flash = T("Upgrade Queued. Please wait while it is completed") redirect(URL(c="setup", f="%s_deploy" % record.type, args=[record.id, "upgrade"])) return output # ----------------------------------------------------------------------------- def setup_refresh(id): T = current.T db = current.db s3db = current.s3db dtable = s3db.setup_deploy query = (dtable.id == id) record = db(query).select(dtable.id, dtable.host, dtable.type, dtable.prepop, dtable.remote_user, dtable.private_key, ).first() if not record: return {"success": False, "msg": T("Record Not Found"), "f": "index", "args": None } # Get machines with the same host as record ptable = s3db.setup_packages stable = s3db.scheduler_task utable = s3db.setup_upgrade query = (dtable.host == record.host) & \ (stable.status == "COMPLETED") machines = db(query).select( dtable.id.with_alias("deployment"), dtable.type.with_alias("type"), join = [ stable.on(dtable.scheduler_id == stable.id) ], distinct = True ) # Check if machines have a refresh running machine_ids = [machine.deployment for machine in machines] validate = s3db.setup_host_validator(machine_ids) if validate is not None: return {"success": False, "msg": validate, "f": str("%s_deploy" % record.type), "args": [record.id, "read"] } # set the refresh lock for machine in machines: db(dtable.id == machine.deployment).update(refresh_lock=1) # find new packages if record.type == "local": response = s3db.setup_getupgrades(record.host, record.prepop) else: response = s3db.setup_getupgrades(record.host, record.prepop, record.remote_user, record.private_key, ) if response["dark"]: return {"success": False, "msg": T("Error contacting the server"), "f": str("%s_deploy" % record.type), "args": [record.id, "upgrade"] } # Call ansible runner # get a list of current packages packages = db(ptable.deployment == record.id).select(ptable.name) old_set = set() for package in packages: old_set.add(package.name) new_set = set() fetched_packages = response["contacted"][record.host]["packages"] for package in fetched_packages: new_set.add(package["name"]) new_packages = new_set.difference(old_set) upgrade_packages = new_set.intersection(old_set) uptodate_packages = old_set.difference(new_set) for package in fetched_packages: if package["name"] in new_packages: for machine in machines: if package["name"] == "web2py" and machine.deployment != record.id: continue ptable.insert(name = package["name"], cv = package["cv"], av = package["av"], type = package["type"], deployment = machine.deployment, ) elif package["name"] in upgrade_packages: for machine in machines: if package["name"] == "web2py" and machine.deployment != record.id: continue query = (ptable.name == package["name"]) & \ (ptable.deployment == machine.deployment) db(query).update(av=package["av"]) for package in uptodate_packages: for machine in machines: if package == "web2py" and machine.deployment != record.id: continue query = (ptable.name == package) & \ (ptable.deployment == machine.deployment) row = db(query).select().first() row.av = row.cv row.update_record() # release the refresh lock for machine in machines: db(dtable.id == machine.deployment).update(refresh_lock=0) # update last refreshed import datetime record.update_record(last_refreshed=datetime.datetime.now()) return {"success": True, "msg": T("Refreshed Packages"), "f": str("%s_deploy" % record.type), "args": [record.id, "upgrade"] } # ----------------------------------------------------------------------------- def setup_host_validator(machine_ids): """ Helper Function that checks whether it's safe to allow upgrade/deployments/refresh packages on given instances """ s3db = current.s3db db = current.db T = current.T dtable = s3db.setup_deploy ptable = s3db.setup_packages stable = s3db.scheduler_task utable = s3db.setup_upgrade if len(machine_ids) > 1: query = (dtable.id.belongs(machine_ids)) & \ (dtable.refresh_lock != 0) else: query = (dtable.id == machine_ids[0]) & \ (dtable.refresh_lock != 0) rows = db(query).select(dtable.id) if rows: return T("A refresh is in progress. Please wait for it to finish") # or an upgrade in process if len(machine_ids) > 1: query = (utable.deployment.belongs(machine_ids)) & \ ((stable.status != "COMPLETED") & (stable.status != "FAILED")) else: query = (utable.deployment == machine_ids[0]) & \ ((stable.status != "COMPLETED") & (stable.status != "FAILED")) rows = db(query).select(utable.deployment, join=stable.on(utable.scheduler == stable.id) ) if rows: return T("An upgrade is in progress. Please wait for it to finish") # or even a deployment in process if len(machine_ids) > 1: query = (dtable.id.belongs(machine_ids)) & \ ((stable.status != "COMPLETED") & (stable.status != "FAILED")) else: query = (dtable.id == machine_ids[0]) & \ ((stable.status != "COMPLETED") & (stable.status != "FAILED")) rows = db(query).select(dtable.id, join = stable.on(utable.scheduler == stable.id) ) if rows: return T("A deployment is in progress. Please wait for it to finish") # ----------------------------------------------------------------------------- def setup_getupgrades(host, web2py_path, remote_user=None, private_key=None): import ansible.runner module_path = os.path.join(current.request.folder, "private", "playbook", "library") if private_key: private_key = os.path.join(current.request.folder, "uploads", private_key) inventory = ansible.inventory.Inventory([host]) if private_key and remote_user: runner = ansible.runner.Runner(module_name = "upgrade", module_path = module_path, module_args = "web2py_path=/home/%s" % web2py_path, remote_user = remote_user, private_key_file = private_key, pattern = host, inventory = inventory, sudo = True, ) else: runner = ansible.runner.Runner(module_name = "upgrade", module_path = module_path, module_args = "web2py_path=/home/%s" % web2py_path, pattern = host, inventory = inventory, sudo = True, ) response = runner.run() return response def setup_upgrade_status(_id): s3db = current.s3db db = current.db T = current.T utable = s3db.setup_upgrade stable = s3db.scheduler_task query = (utable.deployment == _id) row = db(query).select(stable.status, join = utable.on(stable.id == utable.scheduler) ).last() if row.status == "COMPLETED": return T("Upgrade Completed! Refreshing the page in 5 seconds")
# flake8: noqa from tests import WikkedTest, format_link, format_include class ResolverTest(WikkedTest): def testPageInclude(self): wiki = self._getWikiFromStructure({ '/foo.txt': "A test page.\n{{include: trans-desc}}\n", '/trans-desc.txt': "BLAH\n" }) foo = wiki.getPage('/foo') self.assertEqual({'include': ['trans-desc']}, foo.getLocalMeta()) self.assertEqual( "A test page.\n%s" % format_include('trans-desc'), foo.getFormattedText()) self.assertEqual("A test page.\nBLAH", foo.text) def testPageIncludeWithMeta(self): wiki = self._getWikiFromStructure({ 'foo.txt': "A test page.\n{{include: trans-desc}}\n", 'trans-desc.txt': "BLAH: [[Somewhere]]\n{{bar: 42}}\n{{__secret: love}}\n{{+given: hope}}" }) foo = wiki.getPage('/foo') self.assertEqual([], foo.getLocalLinks()) self.assertEqual({'include': ['trans-desc']}, foo.getLocalMeta()) self.assertEqual( "A test page.\n%s" % format_include('trans-desc'), foo.getFormattedText()) self.assertEqual( "A test page.\nBLAH: %s\n\n" % format_link('Somewhere', '/Somewhere', True), foo.text) self.assertEqual(['/Somewhere'], foo.links) self.assertEqual({'bar': ['42'], 'given': ['hope'], 'include': ['trans-desc']}, foo.getMeta()) def testPageIncludeWithNamedTemplating(self): wiki = self._getWikiFromStructure({ 'foo.txt': "A test page.\n{{include: greeting|name=Dave|what=drink}}\n", 'greeting.txt': "Hello {{name}}, would you like a {{what}}?" }) foo = wiki.getPage('/foo') self.assertEqual( "A test page.\n%s" % format_include( 'greeting', '<div class="wiki-param" data-name="name">Dave</div><div class="wiki-param" data-name="what">drink</div>'), foo.getFormattedText()) self.assertEqual("A test page.\nHello Dave, would you like a drink?", foo.text) def testPageIncludeWithNumberedTemplating(self): wiki = self._getWikiFromStructure({ 'foo.txt': "A test page.\n{{include: greeting|Dave|Roger|Tom}}\n", 'greeting.txt': "Hello {{__args[0]}}, {{__args[1]}} and {{__args[2]}}." }) foo = wiki.getPage('/foo') self.assertEqual( "A test page.\n%s" % format_include( 'greeting', '<div class="wiki-param" data-name="">Dave</div><div class="wiki-param" data-name="">Roger</div><div class="wiki-param" data-name="">Tom</div>'), foo.getFormattedText()) self.assertEqual("A test page.\nHello Dave, Roger and Tom.", foo.text) def testIncludeWithPageReferenceTemplating(self): wiki =self._getWikiFromStructure({ 'selfref.txt': "Here is {{read_url(__page.url, __page.title)}}!", 'foo.txt': "Hello here.\n{{include: selfref}}\n" }) foo = wiki.getPage('/foo') self.assertEqual( 'Hello here.\nHere is <a class="wiki-link" data-wiki-url="/foo" href="/read/foo">foo</a>!', foo.text ) def testGivenOnlyInclude(self): wiki = self._getWikiFromStructure({ 'Base.txt': "The base page.\n{{include: Template 1}}", 'Template 1.txt': "TEMPLATE!\n{{+include: Template 2}}", 'Template 2.txt': "MORE TEMPLATE!" }) tpl1 = wiki.getPage('/Template 1') self.assertEqual( "TEMPLATE!\n%s" % format_include('Template 2', mod='+'), tpl1.getFormattedText()) self.assertEqual("TEMPLATE!\n", tpl1.text) base = wiki.getPage('/Base') self.assertEqual("The base page.\nTEMPLATE!\nMORE TEMPLATE!", base.text) def testDoublePageIncludeWithMeta(self): wiki = self._getWikiFromStructure({ 'Base.txt': "The base page.\n{{include: Template 1}}", 'Other.txt': "The other page.\n{{include: Template 2}}", 'Template 1.txt': "{{foo: bar}}\n{{+category: blah}}\n{{+include: Template 2}}\n{{__secret1: ssh}}", 'Template 2.txt': "{{+category: yolo}}", 'Query 1.txt': "{{query: category=yolo}}", 'Query 2.txt': "{{query: category=blah}}" }) base = wiki.getPage('/Base') self.assertEqual({ 'foo': ['bar'], 'category': ['blah', 'yolo'], 'include': ['Template 1', 'Template 2'] }, base.getMeta()) other = wiki.getPage('/Other') self.assertEqual({ 'category': ['yolo'], 'include': ['Template 2'] }, other.getMeta()) tpl1 = wiki.getPage('/Template 1') self.assertEqual({ 'foo': ['bar'], '+category': ['blah', 'yolo'], '+include': ['Template 2'], '__secret1': ['ssh'] }, tpl1.getMeta()) self.assertEqual( "\n\n\n", #"\n\n%s\n\n" % format_include('/Template 2'), tpl1.text) q1 = wiki.getPage('/Query 1') self.assertEqual( "\n* %s\n* %s\n\n" % (format_link('Base', '/Base'), format_link('Other', '/Other')), q1.text) q2 = wiki.getPage('/Query 2') self.assertEqual( "\n* %s\n\n" % format_link('Base', '/Base'), q2.text) def testLink1(self): wiki = self._getWikiFromStructure({ 'Source.txt': "A link: [[Other]]", 'Other.txt': "" }) source = wiki.getPage('/Source') self.assertEqual("A link: %s" % format_link('Other', '/Other'), source.text) def testLink2(self): wiki = self._getWikiFromStructure({ 'Folder/Source.txt': "A link: [[Other]]", 'Folder/Other.txt': "" }) source = wiki.getPage('/Folder/Source') self.assertEqual("A link: %s" % format_link('Other', '/Folder/Other'), source.text) def testLink3(self): wiki = self._getWikiFromStructure({ 'Source.txt': "[[Folder/Other]]", 'Folder/Other.txt': "" }) source = wiki.getPage('/Source') self.assertEqual(format_link('Other', '/Folder/Other'), source.text) def testLink4(self): wiki = self._getWikiFromStructure({ 'Folder/Source.txt': "[[More/Other]]", 'Folder/More/Other.txt': "" }) source = wiki.getPage('/Folder/Source') self.assertEqual(format_link('Other', '/Folder/More/Other'), source.text) def testRelativeLink1(self): wiki = self._getWikiFromStructure({ 'Source.txt': "[[./Other]]", 'Source/Other.txt': "" }) source = wiki.getPage('/Source') self.assertEqual(format_link('Other', '/Source/Other'), source.text) def testRelativeLink2(self): wiki = self._getWikiFromStructure({ 'Folder/Source.txt': "[[./Other]]", 'Folder/Source/Other.txt': "" }) source = wiki.getPage('/Folder/Source') self.assertEqual(format_link('Other', '/Folder/Source/Other'), source.text) def testRelativeLink3(self): wiki = self._getWikiFromStructure({ 'Folder/Source.txt': "[[../Other]]", 'Other.txt': "" }) source = wiki.getPage('/Folder/Source') self.assertEqual(format_link('Other', '/Other'), source.text) def testRelativeLink4(self): wiki = self._getWikiFromStructure({ 'Folder/More/Source.txt': "[[../Other]]", 'Folder/Other.txt': "" }) source = wiki.getPage('/Folder/More/Source') self.assertEqual(format_link('Other', '/Folder/Other'), source.text) def testEndpointLink1(self): wiki = self._getWikiFromStructure({ 'Source.txt': "[[blah:Other]]", '_meta/blah/Other.txt': "" }) source = wiki.getPage('/Source') self.assertEqual(format_link('Other', '/Other', endpoint='blah'), source.text) def testEndpointLink2(self): wiki = self._getWikiFromStructure({ 'Folder/Source.txt': "[[blah:/Other]]", '_meta/blah/Other.txt': "" }) source = wiki.getPage('/Folder/Source') self.assertEqual(format_link('Other', '/Other', endpoint='blah'), source.text) def testEndpointLink3(self): wiki = self._getWikiFromStructure({ 'Source.txt': "[[blah:/Folder/Other]]", '_meta/blah/Folder/Other.txt': "" }) source = wiki.getPage('/Source') self.assertEqual(format_link('Other', '/Folder/Other', endpoint='blah'), source.text) def testEndpointLink4(self): wiki = self._getWikiFromStructure({ 'Folder/Source.txt': "[[blah:Other]]", '_meta/blah/Folder/Other.txt': "" }) source = wiki.getPage('/Folder/Source') self.assertEqual(format_link('Other', '/Folder/Other', endpoint='blah'), source.text) def testEndpointLink5(self): wiki = self._getWikiFromStructure({ '_meta/foo/Folder/Source.txt': "[[blah:Other]]", '_meta/blah/Folder/Other.txt': "" }) source = wiki.getPage('foo:/Folder/Source') self.assertEqual(format_link('Other', '/Folder/Other', endpoint='blah'), source.text) def testEndpointLink6(self): wiki = self._getWikiFromStructure({ '_meta/blah/Folder/Source.txt': "[[Other]]", '_meta/blah/Folder/Other.txt': "" }) source = wiki.getPage('blah:/Folder/Source') self.assertEqual(format_link('Other', '/Folder/Other', endpoint='blah'), source.text) def testEndpointLink7(self): wiki = self._getWikiFromStructure({ '_meta/blah/Source.txt': "[[Folder/Other]]", '_meta/blah/Folder/Other.txt': "" }) source = wiki.getPage('blah:/Source') self.assertEqual(format_link('Other', '/Folder/Other', endpoint='blah'), source.text) def testEndpointLink8(self): wiki = self._getWikiFromStructure({ '_meta/blah/Source.txt': "[[:/Other]]", 'Other.txt': "" }) source = wiki.getPage('blah:/Source') self.assertEqual(format_link('Other', '/Other'), source.text) def testEndpointLink9(self): wiki = self._getWikiFromStructure({ '_meta/blah/Folder/Source.txt': "[[:Other]]", 'Folder/Other.txt': "" }) source = wiki.getPage('blah:/Folder/Source') self.assertEqual(format_link('Other', '/Folder/Other'), source.text)
#!/usr/bin/env python3 import glob import json import optparse import os import os.path import stat import re import shutil import subprocess import sys import tarfile import urllib.error import urllib.parse import urllib.request DEFAULT_RELEASE = None DEFAULT_CHANNEL = "release" KNOWN_CHANNELS = ["release", "rc", "eap"] DEFAULT_PREFIX = "/opt" DEFAULT_TMPDIR = "/tmp" APP_PREFIX = os.path.expanduser('~/.local/share/applications') DESKTOP_PREFIX = os.path.expanduser('~/Desktop') class Tool: """Defines a single IntelliJ tool""" def __init__(self, name, code, binname, aliases=None): self.name = name self.code = code self.binname = binname self.aliases = aliases if aliases else [] self.aliases.append(self.code) tools = [ Tool("CLion", "CL", "clion"), Tool("IntelliJ-Ultimate", "IIU", "idea", ["ideaU"]), Tool("IntelliJ-Community", "IIC", "idea", ["ideaC"]), Tool("PyCharm-Professional", "PCP", "pycharm", ["pycharmP"]), Tool("PyCharm-Community", "PCC", "pycharm", ["pycharmC"]), Tool("WebStorm", "WS", "webstorm"), Tool("DataGrip", "DG", "datagrip"), Tool("PhpStorm", "PS", "PhpStorm", ["php", "phps"]), Tool("Rider", "RD", "rider"), Tool("GoLand", "GO", "goland") ] toolMap = {} for t in tools: toolMap[t.name.lower()] = t for alias in t.aliases: toolMap[alias.lower()] = t def error(msg): print("ERROR: {0}".format(msg)) sys.exit(1) def usage(msg): global parser print("ERROR: {0}".format(msg)) parser.print_help() sys.exit(1) def mkdirs(path): if not os.path.exists(path): os.makedirs(path) def shell(cmd, stderr=None): print("Running: {0}".format(cmd)) return subprocess.check_output(cmd, shell=True, universal_newlines=True, stderr=stderr) def platforms(data): return "Available platforms:\n {0}".format("\n ".join(data["downloads"].keys())) class MyParser(optparse.OptionParser): def format_epilog(self, formatter): res = "Available products: " for t in tools: res += "\n {0:25s} aliases: {1}".format(t.name, " ".join(t.aliases)) res += "\n" return res def get_tool_data(tool): global channel, release code = tool.code print("Determining the version for {0} from channel {1}".format(code, channel)) releases_link = "http://data.services.jetbrains.com/products/releases?code={0}&latest={2}&type={1}".format( code, channel, "true" if release is None else "false") f = urllib.request.urlopen(releases_link) resp = json.load(f) if release is None: return resp[code][0] else: # Find the release for rel in resp[code]: build = rel["build"] version = rel["version"] majorVersion = rel["majorVersion"] year = majorVersion.split(".")[0] if release in (build, version, majorVersion, year): return rel error("Can not find release {0} for tool {1} in channel {2}".format(release, code, channel)) def do_download(download): global tool, tmpdir link = download["link"] fname = link.split('/')[-1] size = download["size"] print("Found {product} version {version}, file: {fname} ({size}) bytes".format( product=tool.name, version=version, fname=fname, size=size)) # TODO: make it work with https link = link.replace("https", "http") mkdirs(tmpdir) fname = os.path.join(tmpdir, fname) ready = False if os.path.isfile(fname): fsize = os.path.getsize(fname) # TODO: add checksum check if fsize != size: print("File exists, but the size differs ({0} vs {1}), downloading again".format(fsize, size)) else: print("File exists and size matches, skipping downloading") ready = True if not ready: print("Downloading from {0} to {1}".format(link, fname)) urllib.request.urlretrieve(link, fname, reporthook=progress) progress(1, size, size) print("\nDone!") return fname def do_install_linux(fname): # Determine the name of the output directory print("Opening file: {}".format(fname)) tar = tarfile.open(fname) first = tar.next() dirname = first.name while True: if os.path.dirname(dirname) == "": dirname = os.path.basename(dirname) break dirname = os.path.dirname(dirname) mkdirs(prefix) fulldir = os.path.join(prefix, dirname) do_extract = True if os.path.exists(fulldir): print("Target directory {0} already exists".format(fulldir)) if options.force: print("Deleting {0}".format(fulldir)) shutil.rmtree(fulldir) else: print("Not installing the tool. Use --force to delete old installation") do_extract = False if do_extract: print("Extracting into {0}".format(fulldir)) tar.extractall(prefix) if options.link: linkname = os.path.join(prefix, dirname.split('-')[0]) if os.path.exists(linkname): print("Deleting old link {0}".format(linkname)) os.remove(linkname) print("Linking {0} to {1}".format(dirname, linkname)) os.symlink(dirname, linkname) fulldir = linkname desktop_entry = """ [Desktop Entry] Name={name} Exec={binname} StartupNotify=true Terminal=false Type=Application Categories=Development;IDE; Icon={icon}""".format( name=tool.name, binname=os.path.join(fulldir, "bin", tool.binname + ".sh").replace(" ", "\\ "), icon=os.path.join(fulldir, "bin", tool.binname + ".png")) if options.app: mkdirs(APP_PREFIX) app_path = os.path.join(APP_PREFIX, tool.name + ".desktop") print("Creating {0}".format(app_path)) with open(app_path, "w") as f: f.write(desktop_entry) if options.desktop: mkdirs(DESKTOP_PREFIX) app_path = os.path.join(DESKTOP_PREFIX, tool.name + ".desktop") print("Creating {0}".format(app_path)) with open(app_path, "w") as f: f.write(desktop_entry) # Add +x st = os.stat(app_path) os.chmod(app_path, st.st_mode | stat.S_IEXEC) def do_install_macosx(fname): print("Mounting {}".format(fname)) out = shell("hdiutil attach -readonly '{0}'".format(fname, sys.stdout)) mnt = re.split(r" [ ]+", out.splitlines()[-1])[2].strip() print("Mounted as {}".format(mnt)) fullapps = glob.glob(os.path.join(mnt, "*.app")) if len(fullapps) != 1: error("Expect exactly 1 .app in the mounted directory") fullapp = fullapps[0] app = os.path.split(fullapp)[-1] app_install_path = os.path.join("/Applications", app) if os.path.exists(app_install_path): old_path = app_install_path + ".old" if os.path.exists(old_path): print("WARNING: deleting {0}".format(old_path)) shell("rm -rf '{0}'".format(old_path)) print("WARNING:\n {0}\nexists, renaming to\n {1}".format(app_install_path, old_path)) os.rename(app_install_path, old_path) print("Copying to {0}".format(app_install_path)) shell("cp -R '{0}' '{1}'".format(fullapp, app_install_path)) if os.path.exists(app_install_path): "Application installed in {0}".format(app_install_path) else: error("Unexpected error when installing the app") shell("hdiutil detach '{0}'".format(mnt)) def progress(a, b, c): """Function that prints download progress""" sofar = a * b if a % 100 == 1: sys.stdout.write("\r{0} / {1} bytes loaded ({2:05.2f}%)".format(sofar, c, 100.0 * sofar / c)) sys.stdout.flush() parser = MyParser(usage='Usage: %prog [options] <product> <platform>', description="Install various JetBrains tools") parser.add_option("-f", "--force", help="Force download and installation, even if the file exists", action="store_true") parser.add_option("-i", "--install", help="Install after downloading", action="store_true") parser.add_option("-l", "--link", help="Create a softlink with base product name", action="store_true") parser.add_option("-p", "--prefix", help="Directory to install the tool (default={0})".format(DEFAULT_PREFIX)) parser.add_option("-t", "--tmpdir", help="Temporary directory for downloaded files(default={0})".format(DEFAULT_TMPDIR)) parser.add_option("-c", "--channel", help="Channell to use(default={0}, accepted values: {1})".format( DEFAULT_CHANNEL, ", ".join(KNOWN_CHANNELS))) parser.add_option("-a", "--app", help="Add application to ~/.local/share/applications", action="store_true") parser.add_option("-d", "--desktop", help="Add application to ~/Desktop", action="store_true") parser.add_option("-r", "--release", help="""Determine the exact tool release. Can be one of: year (e.g. "2019"), major version (e.g. "2019.3"), minor version ("2019.3.4"), or build number (e.g. "193.6911.18"). (default,empty=latest)""") (options, args) = parser.parse_args() prefix = options.prefix if options.prefix else DEFAULT_PREFIX tmpdir = options.tmpdir if options.tmpdir else DEFAULT_TMPDIR channel = options.channel if options.channel else DEFAULT_CHANNEL if channel not in KNOWN_CHANNELS: usage("Unknown channel: {0}, accepted values: {1}".format(channel, ", ".join(KNOWN_CHANNELS))) release = options.release or DEFAULT_RELEASE if release == "latest" or release == "": release = None if len(args) > 2: usage("Too many arguments.") if len(args) == 0: usage("Need to provide a product.") product = args[0] tool = toolMap.get(product.lower()) if not tool: usage("Unknown product: {0}".format(product)) print("Downloading {0}".format(tool.name)) tool_data = get_tool_data(tool) if len(args) == 1: print("No platform provided.") print(platforms(tool_data)) sys.exit(1) platform = args[1] download_data = tool_data["downloads"].get(platform) if not download_data: print("Unknown platform: {0}".format(platform)) print(platforms(tool_data)) sys.exit(1) version = tool_data["version"] downloaded_fname = do_download(download_data) if options.install: if sys.platform in ("linux", "linux2"): do_install_linux(downloaded_fname) elif sys.platform == "darwin": do_install_macosx(downloaded_fname) else: ("Unsupported platform for installation: {}".format(sys.platform))
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import copy import json import numpy import logging import networkx from os import path, pardir from collections import namedtuple logger = logging.getLogger(__name__) THIS_DIR = path.dirname(path.abspath(__file__)) def load_default_probs(): json_path = path.join(THIS_DIR, pardir, 'resources', 'default_belief_probs.json') with open(json_path, 'r') as f: prior_probs = json.load(f) return prior_probs class BeliefScorer(object): """Base class for a belief engine scorer, which computes the prior probability of a statement given its type and evidence. To use with the belief engine, make a subclass with methods implemented. """ def score_statement(self, st, extra_evidence=None): """Computes the prior belief probability for an INDRA Statement. The Statement is assumed to be de-duplicated. In other words, the Statement is assumed to have a list of Evidence objects that supports it. The prior probability of the Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- st : indra.statements.Statement An INDRA Statements whose belief scores are to be calculated. extra_evidence : list[indra.statements.Evidence] A list of Evidences that are supporting the Statement (that aren't already included in the Statement's own evidence list. Returns ------- belief_score : float The computed prior probability for the statement """ raise NotImplementedError('Need to subclass BeliefScorer and ' 'implement methods.') def check_prior_probs(self, statements): """Make sure the scorer has all the information needed to compute belief scores of each statement in the provided list, and raises an exception otherwise. Parameters ---------- statements : list<indra.statements.Statement> List of statements to check """ raise NotImplementedError('Need to subclass BeliefScorer and ' 'implement methods.') class SimpleScorer(BeliefScorer): """Computes the prior probability of a statement given its type and evidence. Parameters ---------- prior_probs : dict[dict] A dictionary of prior probabilities used to override/extend the default ones. There are two types of prior probabilities: rand and syst corresponding to random error and systematic error rate for each knowledge source. The prior_probs dictionary has the general structure {'rand': {'s1': pr1, ..., 'sn': prn}, 'syst': {'s1': ps1, ..., 'sn': psn}} where 's1' ... 'sn' are names of input sources and pr1 ... prn and ps1 ... psn are error probabilities. Examples: {'rand': {'some_source': 0.1}} sets the random error rate for some_source to 0.1; {'rand': {''}} subtype_probs : dict[dict] A dictionary of random error probabilities for knowledge sources. When a subtype random error probability is not specified, will just use the overall type prior in prior_probs. If None, will only use the priors for each rule. """ def __init__(self, prior_probs=None, subtype_probs=None): self.prior_probs = load_default_probs() self.subtype_probs = {} self.update_probs(prior_probs, subtype_probs) def update_probs(self, prior_probs=None, subtype_probs=None): if prior_probs: for key in ('rand', 'syst'): self.prior_probs[key].update(prior_probs.get(key, {})) for err_type, source_dict in self.prior_probs.items(): logger.debug("Prior probabilities for %s errors: %s" % (err_type, source_dict)) self.subtype_probs = subtype_probs def score_evidence_list(self, evidences): """Return belief score given a list of supporting evidences.""" def _score(evidences): if not evidences: return 0 # Collect all unique sources sources = [ev.source_api for ev in evidences] uniq_sources = numpy.unique(sources) # Calculate the systematic error factors given unique sources syst_factors = {s: self.prior_probs['syst'][s] for s in uniq_sources} # Calculate the radom error factors for each source rand_factors = {k: [] for k in uniq_sources} for ev in evidences: rand_factors[ev.source_api].append( evidence_random_noise_prior( ev, self.prior_probs['rand'], self.subtype_probs)) # The probability of incorrectness is the product of the # source-specific probabilities neg_prob_prior = 1 for s in uniq_sources: neg_prob_prior *= (syst_factors[s] + numpy.prod(rand_factors[s])) # Finally, the probability of correctness is one minus incorrect prob_prior = 1 - neg_prob_prior return prob_prior pos_evidence = [ev for ev in evidences if not ev.epistemics.get('negated')] neg_evidence = [ev for ev in evidences if ev.epistemics.get('negated')] pp = _score(pos_evidence) np = _score(neg_evidence) # The basic assumption is that the positive and negative evidence # can't simultaneously be correct. # There are two cases to consider. (1) If the positive evidence is # incorrect then there is no Statement and the belief should be 0, # irrespective of the negative evidence. # (2) If the positive evidence is correct and the negative evidence # is incorrect. # This amounts to the following formula: # 0 * (1-pp) + 1 * (pp * (1-np)) which we simplify below score = pp * (1 - np) return score def score_statement(self, st, extra_evidence=None): """Computes the prior belief probability for an INDRA Statement. The Statement is assumed to be de-duplicated. In other words, the Statement is assumed to have a list of Evidence objects that supports it. The prior probability of the Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- st : indra.statements.Statement An INDRA Statements whose belief scores are to be calculated. extra_evidence : list[indra.statements.Evidence] A list of Evidences that are supporting the Statement (that aren't already included in the Statement's own evidence list. Returns ------- belief_score : float The computed prior probability for the statement """ if extra_evidence is None: extra_evidence = [] all_evidence = st.evidence + extra_evidence return self.score_evidence_list(all_evidence) def check_prior_probs(self, statements): """Throw Exception if BeliefEngine parameter is missing. Make sure the scorer has all the information needed to compute belief scores of each statement in the provided list, and raises an exception otherwise. Parameters ---------- statements : list[indra.statements.Statement] List of statements to check """ sources = set() for stmt in statements: sources |= set([ev.source_api for ev in stmt.evidence]) for err_type in ('rand', 'syst'): for source in sources: if source not in self.prior_probs[err_type]: msg = 'BeliefEngine missing probability parameter' + \ ' for source: %s' % source raise Exception(msg) class BayesianScorer(SimpleScorer): """This is a belief scorer which assumes a Beta prior and a set of prior counts of correct and incorrect instances for a given source. It exposes and interface to take additional counts and update its probability parameters which can then be used to calculate beliefs on a set of Statements. Parameters ---------- prior_counts : dict A dictionary of counts of the form [pos, neg] for each source. subtype_counts : dict A dictionary of counts of the form [pos, neg] for each subtype within a source. """ def __init__(self, prior_counts, subtype_counts): self.prior_probs = load_default_probs() self.subtype_probs = {} self.prior_counts = copy.deepcopy(prior_counts) if prior_counts else {} self.subtype_counts = copy.deepcopy(subtype_counts) if subtype_counts \ else {} # Set the probability estimates based on the counts self.update_probs() def update_probs(self): """Update the internal probability values given the counts.""" # We deal with the prior probsfirst # This is a fixed assumed value for systematic error syst_error = 0.05 prior_probs = {'syst': {}, 'rand': {}} for source, (p, n) in self.prior_counts.items(): # Skip if there are no actual counts if n + p == 0: continue prior_probs['syst'][source] = syst_error prior_probs['rand'][source] = \ 1 - min((float(p) / (n + p), 1-syst_error)) - syst_error # Next we deal with subtype probs based on counts subtype_probs = {} for source, entry in self.subtype_counts.items(): for rule, (p, n) in entry.items(): # Skip if there are no actual counts if n + p == 0: continue if source not in subtype_probs: subtype_probs[source] = {} subtype_probs[source][rule] = \ 1 - min((float(p) / (n + p), 1-syst_error)) - syst_error # Finally we propagate this into the full probability # data structures of the parent class super(BayesianScorer, self).update_probs(prior_probs, subtype_probs) def update_counts(self, prior_counts, subtype_counts): """Update the internal counts based on given new counts. Parameters ---------- prior_counts : dict A dictionary of counts of the form [pos, neg] for each source. subtype_counts : dict A dictionary of counts of the form [pos, neg] for each subtype within a source. """ for source, (pos, neg) in prior_counts.items(): if source not in self.prior_counts: self.prior_counts[source] = [0, 0] self.prior_counts[source][0] += pos self.prior_counts[source][1] += neg for source, subtype_dict in subtype_counts.items(): if source not in self.subtype_counts: self.subtype_counts[source] = {} for subtype, (pos, neg) in subtype_dict.items(): if subtype not in self.subtype_counts[source]: self.subtype_counts[source][subtype] = [0, 0] self.subtype_counts[source][subtype][0] += pos self.subtype_counts[source][subtype][1] += neg self.update_probs() default_scorer = SimpleScorer() class BeliefEngine(object): """Assigns beliefs to INDRA Statements based on supporting evidence. Attributes ---------- scorer : BeliefScorer A BeliefScorer object that computes the prior probability of a statement given its its statment type and evidence. Must implement the `score_statement` method which takes Statements and computes the belief score of a statement, and the `check_prior_probs` method which takes a list of INDRA Statements and verifies that the scorer has all the information it needs to score every statement in the list, and raises an exception if not. """ def __init__(self, scorer=None, matches_fun=None): if scorer is None: scorer = default_scorer assert(isinstance(scorer, BeliefScorer)) self.scorer = scorer self.matches_fun = matches_fun if matches_fun else \ lambda stmt: stmt.matches_key() def set_prior_probs(self, statements): """Sets the prior belief probabilities for a list of INDRA Statements. The Statements are assumed to be de-duplicated. In other words, each Statement in the list passed to this function is assumed to have a list of Evidence objects that support it. The prior probability of each Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements whose belief scores are to be calculated. Each Statement object's belief attribute is updated by this function. """ self.scorer.check_prior_probs(statements) for st in statements: st.belief = self.scorer.score_statement(st) def set_hierarchy_probs(self, statements): """Sets hierarchical belief probabilities for INDRA Statements. The Statements are assumed to be in a hierarchical relation graph with the supports and supported_by attribute of each Statement object having been set. The hierarchical belief probability of each Statement is calculated based on its prior probability and the probabilities propagated from Statements supporting it in the hierarchy graph. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements whose belief scores are to be calculated. Each Statement object's belief attribute is updated by this function. """ def build_hierarchy_graph(stmts): """Return a DiGraph based on matches keys and Statement supports""" logger.debug('Building hierarchy graph') g = networkx.DiGraph() for st1 in stmts: g.add_node(self.matches_fun(st1), stmt=st1) for st2 in st1.supported_by: g.add_node(self.matches_fun(st2), stmt=st2) g.add_edge(self.matches_fun(st2), self.matches_fun(st1)) logger.debug('Finished building hierarchy graph') return g def get_ranked_stmts(g): """Return a topological sort of statement matches keys from a graph. """ logger.debug('Getting ranked statements') node_ranks = networkx.algorithms.dag.topological_sort(g) node_ranks = reversed(list(node_ranks)) stmts = [g.nodes[n]['stmt'] for n in node_ranks] return stmts def assert_no_cycle(g): """If the graph has cycles, throws AssertionError.""" logger.debug('Looking for cycles in belief graph') try: cyc = networkx.algorithms.cycles.find_cycle(g) except networkx.exception.NetworkXNoCycle: return msg = 'Cycle found in hierarchy graph: %s' % cyc assert False, msg g = build_hierarchy_graph(statements) assert_no_cycle(g) ranked_stmts = get_ranked_stmts(g) logger.debug('Start belief propagation over ranked statements') for st in ranked_stmts: bps = _get_belief_package(st, self.matches_fun) supporting_evidences = [] # NOTE: the last belief package in the list is this statement's own for bp in bps[:-1]: # Iterate over all the parent evidences and add only # non-negated ones for ev in bp.evidences: if not ev.epistemics.get('negated'): supporting_evidences.append(ev) # Now add the Statement's own evidence # Now score all the evidences belief = self.scorer.score_statement(st, supporting_evidences) st.belief = belief logger.debug('Finished belief propagation over ranked statements') def set_linked_probs(self, linked_statements): """Sets the belief probabilities for a list of linked INDRA Statements. The list of LinkedStatement objects is assumed to come from the MechanismLinker. The belief probability of the inferred Statement is assigned the joint probability of its source Statements. Parameters ---------- linked_statements : list[indra.mechlinker.LinkedStatement] A list of INDRA LinkedStatements whose belief scores are to be calculated. The belief attribute of the inferred Statement in the LinkedStatement object is updated by this function. """ for st in linked_statements: source_probs = [s.belief for s in st.source_stmts] st.inferred_stmt.belief = numpy.prod(source_probs) BeliefPackage = namedtuple('BeliefPackage', 'statement_key evidences') def _get_belief_package(stmt, matches_fun): """Return the belief packages of a given statement recursively.""" # This list will contain the belief packages for the given statement belief_packages = [] # Iterate over all the support parents for st in stmt.supports: # Recursively get all the belief packages of the parent parent_packages = _get_belief_package(st, matches_fun) package_stmt_keys = [pkg.statement_key for pkg in belief_packages] for package in parent_packages: # Only add this belief package if it hasn't already been added if package.statement_key not in package_stmt_keys: belief_packages.append(package) # Now make the Statement's own belief package and append it to the list belief_package = BeliefPackage(matches_fun(stmt), stmt.evidence) belief_packages.append(belief_package) return belief_packages def sample_statements(stmts, seed=None): """Return statements sampled according to belief. Statements are sampled independently according to their belief scores. For instance, a Staement with a belief score of 0.7 will end up in the returned Statement list with probability 0.7. Parameters ---------- stmts : list[indra.statements.Statement] A list of INDRA Statements to sample. seed : Optional[int] A seed for the random number generator used for sampling. Returns ------- new_stmts : list[indra.statements.Statement] A list of INDRA Statements that were chosen by random sampling according to their respective belief scores. """ if seed: numpy.random.seed(seed) new_stmts = [] r = numpy.random.rand(len(stmts)) for i, stmt in enumerate(stmts): if r[i] < stmt.belief: new_stmts.append(stmt) return new_stmts def evidence_random_noise_prior(evidence, type_probs, subtype_probs): """Determines the random-noise prior probability for this evidence. If the evidence corresponds to a subtype, and that subtype has a curated prior noise probability, use that. Otherwise, gives the random-noise prior for the overall rule type. """ (stype, subtype) = tag_evidence_subtype(evidence) # Get the subtype, if available # Return the subtype random noise prior, if available if subtype_probs is not None: if stype in subtype_probs: if subtype in subtype_probs[stype]: return subtype_probs[stype][subtype] # Fallback to just returning the overall evidence type random noise prior return type_probs[stype] def tag_evidence_subtype(evidence): """Returns the type and subtype of an evidence object as a string, typically the extraction rule or database from which the statement was generated. For biopax, this is just the database name. Parameters ---------- statement: indra.statements.Evidence The statement which we wish to subtype Returns ------- types: tuple A tuple with (type, subtype), both strings Returns (type, None) if the type of statement is not yet handled in this function. """ source_api = evidence.source_api annotations = evidence.annotations if source_api == 'biopax': subtype = annotations.get('source_sub_id') elif source_api in ('reach', 'eidos'): if 'found_by' in annotations: from indra.sources.reach.processor import determine_reach_subtype if source_api == 'reach': subtype = determine_reach_subtype(annotations['found_by']) elif source_api == 'eidos': subtype = annotations['found_by'] else: subtype = None else: logger.debug('Could not find found_by attribute in reach ' 'statement annoations') subtype = None elif source_api == 'geneways': subtype = annotations['actiontype'] else: subtype = None return (source_api, subtype)
# 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 image ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import colorsys import math import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.compiler.tests.xla_test import XLATestCase from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_image_ops from tensorflow.python.ops import image_ops from tensorflow.python.platform import test class RGBToHSVTest(XLATestCase): def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in self.float_types: inp = np.random.rand(*shape).astype(nptype) # Convert to HSV and back, as a batch and individually with self.test_session() as sess: batch0 = array_ops.placeholder(nptype, shape=shape) with self.test_scope(): batch1 = image_ops.rgb_to_hsv(batch0) batch2 = image_ops.hsv_to_rgb(batch1) split0 = array_ops.unstack(batch0) with self.test_scope(): split1 = list(map(image_ops.rgb_to_hsv, split0)) split2 = list(map(image_ops.hsv_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = sess.run([batch1, batch2, join1, join2], { batch0: inp }) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1) self.assertAllClose(batch2, join2) self.assertAllClose(batch2, inp) def testRGBToHSVRoundTrip(self): data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] for nptype in self.float_types: rgb_np = np.array(data, dtype=nptype).reshape([2, 2, 3]) / 255. with self.test_session(): placeholder = array_ops.placeholder(nptype) with self.test_scope(): hsv = image_ops.rgb_to_hsv(placeholder) rgb = image_ops.hsv_to_rgb(hsv) rgb_tf = rgb.eval(feed_dict={placeholder: rgb_np}) self.assertAllClose(rgb_tf, rgb_np) def testRGBToHSVNumpy(self): """Tests the RGB to HSV conversion matches a reference implementation.""" for nptype in self.float_types: rgb_flat = np.random.random(64 * 3).reshape((64, 3)).astype(nptype) rgb_np = rgb_flat.reshape(4, 4, 4, 3) hsv_np = np.array([colorsys.rgb_to_hsv(r, g, b) for r, g, b in rgb_flat]) hsv_np = hsv_np.reshape(4, 4, 4, 3) with self.test_session(): placeholder = array_ops.placeholder(nptype) with self.test_scope(): hsv_op = image_ops.rgb_to_hsv(placeholder) hsv_tf = hsv_op.eval(feed_dict={placeholder: rgb_np}) self.assertAllClose(hsv_tf, hsv_np) class AdjustContrastTest(XLATestCase): def _testContrast(self, x_np, y_np, contrast_factor): with self.test_session(): x = array_ops.placeholder(x_np.dtype, shape=x_np.shape) flt_x = image_ops.convert_image_dtype(x, dtypes.float32) with self.test_scope(): y = image_ops.adjust_contrast(flt_x, contrast_factor) y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) y_tf = y.eval({x: x_np}) self.assertAllClose(y_tf, y_np, 1e-6) def testFloatContrast(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float32).reshape(x_shape) / 255. y_data = [ -45.25, -90.75, -92.5, 62.75, 169.25, 333.5, 28.75, -84.75, 349.5, 134.75, 409.25, -116.5 ] y_np = np.array(y_data, dtype=np.float32).reshape(x_shape) / 255. self._testContrast(x_np, y_np, contrast_factor=2.0) def testBatchContrast(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 0, 81, 200, 255, 10, 0, 255, 116, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=2.0) def _adjustContrastNp(self, x_np, contrast_factor): mean = np.mean(x_np, (1, 2), keepdims=True) y_np = mean + contrast_factor * (x_np - mean) return y_np def _adjustContrastTf(self, x_np, contrast_factor): with self.test_session(): x = array_ops.placeholder(np.float32) with self.test_scope(): y = image_ops.adjust_contrast(x, contrast_factor) y_tf = y.eval({x: x_np}) return y_tf def testRandomContrast(self): x_shapes = [ [1, 2, 2, 3], [2, 1, 2, 3], [1, 2, 2, 3], [2, 5, 5, 3], [2, 1, 1, 3], ] for x_shape in x_shapes: x_np = np.random.rand(*x_shape) * 255. contrast_factor = np.random.rand() * 2.0 + 0.1 y_np = self._adjustContrastNp(x_np, contrast_factor) y_tf = self._adjustContrastTf(x_np, contrast_factor) self.assertAllClose(y_tf, y_np, rtol=1e-5, atol=1e-5) class AdjustHueTest(XLATestCase): def testAdjustNegativeHue(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = -0.25 y_data = [0, 13, 1, 54, 226, 59, 8, 234, 150, 255, 39, 1] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.test_session(): x = array_ops.placeholder(x_np.dtype, shape=x_shape) flt_x = image_ops.convert_image_dtype(x, dtypes.float32) with self.test_scope(): y = gen_image_ops.adjust_hue(flt_x, delta) y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) y_tf = y.eval({x: x_np}) self.assertAllEqual(y_tf, y_np) def testAdjustPositiveHue(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = 0.25 y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.test_session(): x = array_ops.placeholder(x_np.dtype, shape=x_shape) flt_x = image_ops.convert_image_dtype(x, dtypes.float32) with self.test_scope(): y = gen_image_ops.adjust_hue(flt_x, delta) y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) y_tf = y.eval({x: x_np}) self.assertAllEqual(y_tf, y_np) def testBatchAdjustHue(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = 0.25 y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.test_session(): x = array_ops.placeholder(x_np.dtype, shape=x_shape) flt_x = image_ops.convert_image_dtype(x, dtypes.float32) with self.test_scope(): y = gen_image_ops.adjust_hue(flt_x, delta) y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) y_tf = y.eval({x: x_np}) self.assertAllEqual(y_tf, y_np) def _adjustHueNp(self, x_np, delta_h): self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) channel_count = x_v.shape[0] for i in xrange(channel_count): r = x_v[i][0] g = x_v[i][1] b = x_v[i][2] h, s, v = colorsys.rgb_to_hsv(r, g, b) h += delta_h h = math.fmod(h + 10.0, 1.0) r, g, b = colorsys.hsv_to_rgb(h, s, v) y_v[i][0] = r y_v[i][1] = g y_v[i][2] = b return y_v.reshape(x_np.shape) def _adjustHueTf(self, x_np, delta_h): with self.test_session(): x = array_ops.placeholder(dtypes.float32) with self.test_scope(): y = gen_image_ops.adjust_hue(x, delta_h) y_tf = y.eval({x: x_np}) return y_tf def testAdjustRandomHue(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ "all_random", "rg_same", "rb_same", "gb_same", "rgb_same", ] for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. delta_h = np.random.rand() * 2.0 - 1.0 if test_style == "all_random": pass elif test_style == "rg_same": x_np[..., 1] = x_np[..., 0] elif test_style == "rb_same": x_np[..., 2] = x_np[..., 0] elif test_style == "gb_same": x_np[..., 2] = x_np[..., 1] elif test_style == "rgb_same": x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError("Invalid test style: %s" % (test_style)) y_np = self._adjustHueNp(x_np, delta_h) y_tf = self._adjustHueTf(x_np, delta_h) self.assertAllClose(y_tf, y_np, rtol=2e-5, atol=1e-4) def testInvalidShapes(self): fused = False if not fused: # The tests are known to pass with the fused adjust_hue. We will enable # them when the fused implementation is the default. return x_np = np.random.rand(2, 3) * 255. delta_h = np.random.rand() * 2.0 - 1.0 fused = False with self.assertRaisesRegexp(ValueError, "Shape must be at least rank 3"): self._adjustHueTf(x_np, delta_h) x_np = np.random.rand(4, 2, 4) * 255. delta_h = np.random.rand() * 2.0 - 1.0 with self.assertRaisesOpError("input must have 3 channels"): self._adjustHueTf(x_np, delta_h) class AdjustSaturationTest(XLATestCase): def _adjust_saturation(self, image, saturation_factor): image = ops.convert_to_tensor(image, name="image") orig_dtype = image.dtype flt_image = image_ops.convert_image_dtype(image, dtypes.float32) with self.test_scope(): saturation_adjusted_image = gen_image_ops.adjust_saturation( flt_image, saturation_factor) return image_ops.convert_image_dtype(saturation_adjusted_image, orig_dtype) def testHalfSaturation(self): x_shape = [2, 2, 3] x_rgb_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_rgb_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 0.5 y_rgb_data = [6, 9, 13, 140, 180, 226, 135, 121, 234, 172, 255, 128] y_np = np.array(y_rgb_data, dtype=np.uint8).reshape(x_shape) with self.test_session(): x = array_ops.placeholder(x_np.dtype, shape=x_shape) y = self._adjust_saturation(x, saturation_factor) y_tf = y.eval({x: x_np}) self.assertAllEqual(y_tf, y_np) def testTwiceSaturation(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 2.0 y_data = [0, 5, 13, 0, 106, 226, 30, 0, 234, 89, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.test_session(): x = array_ops.placeholder(x_np.dtype, shape=x_shape) y = self._adjust_saturation(x, saturation_factor) y_tf = y.eval({x: x_np}) self.assertAllEqual(y_tf, y_np) def _adjustSaturationNp(self, x_np, scale): self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) channel_count = x_v.shape[0] for i in xrange(channel_count): r = x_v[i][0] g = x_v[i][1] b = x_v[i][2] h, s, v = colorsys.rgb_to_hsv(r, g, b) s *= scale s = min(1.0, max(0.0, s)) r, g, b = colorsys.hsv_to_rgb(h, s, v) y_v[i][0] = r y_v[i][1] = g y_v[i][2] = b return y_v.reshape(x_np.shape) def testAdjustRandomSaturation(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ "all_random", "rg_same", "rb_same", "gb_same", "rgb_same", ] with self.test_session(): for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. scale = np.random.rand() if test_style == "all_random": pass elif test_style == "rg_same": x_np[..., 1] = x_np[..., 0] elif test_style == "rb_same": x_np[..., 2] = x_np[..., 0] elif test_style == "gb_same": x_np[..., 2] = x_np[..., 1] elif test_style == "rgb_same": x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError("Invalid test style: %s" % (test_style)) y_baseline = self._adjustSaturationNp(x_np, scale) x = array_ops.placeholder(dtypes.float32, shape=x_shape) with self.test_scope(): y_fused = self._adjust_saturation(x, scale).eval(feed_dict={ x: x_np }) self.assertAllClose(y_fused, y_baseline, rtol=2e-5, atol=1e-5) class ResizeBilinearTest(XLATestCase): def _assertForwardOpMatchesExpected(self, image_np, target_shape, expected=None): if expected is None: self.fail("expected must be specified") with self.test_session() as sess, self.test_scope(): image = array_ops.placeholder(image_np.dtype) resized = gen_image_ops.resize_bilinear( image, target_shape, align_corners=True) out = sess.run(resized, {image: image_np[np.newaxis, :, :, np.newaxis]}) self.assertAllClose(expected[np.newaxis, :, :, np.newaxis], out) def _assertBackwardOpMatchesExpected(self, grads_np, input_shape=None, dtype=None, expected=None): if input_shape is None: self.fail("input_shape must be specified") if expected is None: self.fail("expected must be specified") with self.test_session() as sess, self.test_scope(): dtype = dtype or np.float32 grads = array_ops.placeholder(np.float32) resized = gen_image_ops._resize_bilinear_grad( grads, np.zeros([1, input_shape[0], input_shape[1], 1], dtype=dtype), align_corners=True) out = sess.run(resized, {grads: grads_np[np.newaxis, :, :, np.newaxis]}) self.assertAllClose(expected[np.newaxis, :, :, np.newaxis], out) def testAlignCorners1x2To3x2(self): for dtype in self.float_types: self._assertForwardOpMatchesExpected( np.array([[1, 2]], dtype=dtype), [3, 3], expected=np.array( [[1, 1.5, 2], [1, 1.5, 2], [1, 1.5, 2]], dtype=np.float32)) def testAlignCorners1x2To3x2Grad(self): for dtype in self.float_types: self._assertBackwardOpMatchesExpected( np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32), input_shape=[1, 2], dtype=dtype, expected=np.array([[9, 12]], dtype=np.float32)) def testAlignCorners2x2To1x1(self): for dtype in self.float_types: self._assertForwardOpMatchesExpected( np.array([[1, 2], [3, 4]], dtype=dtype), [1, 1], expected=np.array([[1]], dtype=np.float32)) def testAlignCorners2x2To1x1Grad(self): for dtype in self.float_types: self._assertBackwardOpMatchesExpected( np.array([[7]], dtype=np.float32), input_shape=[2, 2], dtype=dtype, expected=np.array([[7, 0], [0, 0]], dtype=np.float32)) def testAlignCorners2x2To3x3(self): for dtype in self.float_types: self._assertForwardOpMatchesExpected( np.array([[1, 2], [3, 4]], dtype=dtype), [3, 3], expected=np.array( [[1, 1.5, 2], [2, 2.5, 3], [3, 3.5, 4]], dtype=np.float32)) def testAlignCorners2x2To3x3Grad(self): self._assertBackwardOpMatchesExpected( np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), input_shape=[2, 2], expected=np.array([[5.25, 8.25], [14.25, 17.25]], dtype=np.float32)) def testAlignCorners3x3To2x2(self): for dtype in self.float_types: self._assertForwardOpMatchesExpected( np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=dtype), [2, 2], expected=np.array([[1, 3], [7, 9]], dtype=np.float32)) def testAlignCorners3x3To2x2Grad(self): for dtype in self.float_types: self._assertBackwardOpMatchesExpected( np.array([[7, 13], [22, 4]], dtype=np.float32), input_shape=[3, 3], dtype=dtype, expected=np.array( [[7, 0, 13], [0, 0, 0], [22, 0, 4]], dtype=np.float32)) def testAlignCorners4x4To3x3(self): for dtype in self.float_types: self._assertForwardOpMatchesExpected( np.array( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], dtype=dtype), [3, 3], expected=np.array( [[1, 2.5, 4], [7, 8.5, 10], [13, 14.5, 16]], dtype=np.float32)) def testAlignCorners4x4To3x3Grad(self): for dtype in self.float_types: self._assertBackwardOpMatchesExpected( np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), input_shape=[4, 4], dtype=dtype, expected=np.array( [[1, 1, 1, 3], [2, 1.25, 1.25, 3], [2, 1.25, 1.25, 3], [7, 4, 4, 9]], dtype=np.float32)) if __name__ == "__main__": test.main()
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, 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 collections import namedtuple def Enum(*values, **kwargs): names = kwargs.get('names') if names: return namedtuple('Enum', names)(*values) return namedtuple('Enum', values)(*values) RELEASE_STATES = Enum( 'available', 'unavailable', ) RELEASE_OS = Enum( 'Ubuntu', 'CentOS', names=( 'ubuntu', 'centos' ) ) CLUSTER_MODES = Enum( 'multinode', 'ha_full', 'ha_compact' ) CLUSTER_STATUSES = Enum( 'new', 'deployment', 'stopped', 'operational', 'error', 'remove', 'update', 'update_error' ) NETWORKS = Enum( # Node networks 'fuelweb_admin', 'storage', # internal in terms of fuel 'management', 'public', # private in terms of fuel 'fixed', 'private' ) NOVA_NET_MANAGERS = Enum( 'FlatDHCPManager', 'VlanManager' ) CLUSTER_GROUPING = Enum( 'roles', 'hardware', 'both' ) CLUSTER_NET_PROVIDERS = Enum( 'nova_network', 'neutron' ) NEUTRON_L23_PROVIDERS = Enum( 'ovs', 'nsx' ) NEUTRON_SEGMENT_TYPES = Enum( 'vlan', 'gre' ) NODE_STATUSES = Enum( 'ready', 'discover', 'provisioning', 'provisioned', 'deploying', 'error', 'removing', ) NODE_ERRORS = Enum( 'deploy', 'provision', 'deletion' ) NODE_GROUPS = Enum( 'default' ) NETWORK_INTERFACE_TYPES = Enum( 'ether', 'bond' ) NETWORK_VIP_TYPES = Enum( 'haproxy', 'vrouter', ) BOND_MODES = Enum( # same for both OVS and linux 'active-backup', # OVS modes 'balance-slb', 'lacp-balance-tcp', # linux modes 'balance-rr', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb', names=( 'active_backup', 'balance_slb', 'lacp_balance_tcp', 'balance_rr', 'balance_xor', 'broadcast', 'l_802_3ad', 'balance_tlb', 'balance_alb', ) ) BOND_PROPERTIES = Enum( 'mode', 'xmit_hash_policy', 'lacp_rate', # not for orchestrator input 'type__' ) BOND_XMIT_HASH_POLICY = Enum( 'layer2', 'layer2+3', 'layer3+4', 'encap2+3', 'encap3+4', names=( 'layer2', 'layer2_3', 'layer3_4', 'encap2_3', 'encap3_4', ) ) BOND_LACP_RATES = Enum( 'slow', 'fast' ) BOND_TYPES = Enum( 'ovs', 'linux' ) TASK_STATUSES = Enum( 'ready', 'running', 'error' ) TASK_NAMES = Enum( 'super', # Cluster changes # For deployment supertask, it contains # two subtasks deployment and provision 'deploy', 'deployment', 'provision', 'stop_deployment', 'reset_environment', 'update', 'node_deletion', 'cluster_deletion', 'check_before_deployment', # network 'check_networks', 'verify_networks', 'check_dhcp', 'verify_network_connectivity', 'multicast_verification', 'check_repo_availability', 'check_repo_availability_with_setup', # dump 'dump', 'capacity_log', # statistics 'create_stats_user', 'remove_stats_user' ) NOTIFICATION_STATUSES = Enum( 'read', 'unread' ) NOTIFICATION_TOPICS = Enum( 'discover', 'done', 'error', 'warning', 'release', ) CLUSTER_CHANGES = Enum( 'networks', 'attributes', 'disks', 'interfaces', 'vmware_attributes' ) PROVISION_METHODS = Enum( 'cobbler', 'image' ) STAGES = Enum( 'pre_deployment', 'deploy', 'post_deployment' ) ACTION_TYPES = Enum( 'http_request', 'nailgun_task' ) LOG_CHUNK_SEND_STATUS = Enum( 'ok', 'error' ) LOG_RECORD_SEND_STATUS = Enum( 'added', 'existed', 'failed', 'updated', 'skipped' ) NOVA_SERVICE_TYPE = Enum( 'compute', ) OPENSTACK_IMAGES_SETTINGS = Enum( "OS-EXT-IMG-SIZE:size", "byte", names=( "size_attr_name", "size_unit" ) ) DEPLOY_STRATEGY = Enum( 'parallel', 'one_by_one' ) ORCHESTRATOR_TASK_TYPES = Enum( 'puppet', 'shell', 'sync', 'upload_file', 'group', 'stage', 'skipped', 'reboot', 'copy_files', ) INTERNAL_TASKS = (ORCHESTRATOR_TASK_TYPES.group, ORCHESTRATOR_TASK_TYPES.stage, ORCHESTRATOR_TASK_TYPES.skipped) ROLE_NAME_MAX_SIZE = 64 ALL_ROLES = '*' MASTER_ROLE = 'master' # version of Fuel when we added granular deploy support FUEL_GRANULAR_DEPLOY = '6.1' # version of Fuel when we added remote repos FUEL_REMOTE_REPOS = '6.1' # version of Fuel when external mongo was added FUEL_EXTERNAL_MONGO = '6.1' # version of Fuel when Nova is not supported anymore. Neutron is left only. FUEL_NEUTRON_ONLY = '7.0' OSWL_RESOURCE_TYPES = Enum( 'vm', 'tenant', 'volume', 'security_group', 'keystone_user', 'flavor', 'cluster_stats', 'image', )
"""Notifications for Android TV notification service.""" import logging from notifications_android_tv import Notifications import requests from requests.auth import HTTPBasicAuth, HTTPDigestAuth import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA, BaseNotificationService, ) from homeassistant.const import ATTR_ICON, CONF_HOST, CONF_TIMEOUT from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from .const import ( ATTR_COLOR, ATTR_DURATION, ATTR_FILE, ATTR_FILE_AUTH, ATTR_FILE_AUTH_DIGEST, ATTR_FILE_PASSWORD, ATTR_FILE_PATH, ATTR_FILE_URL, ATTR_FILE_USERNAME, ATTR_FONTSIZE, ATTR_INTERRUPT, ATTR_POSITION, ATTR_TRANSPARENCY, CONF_COLOR, CONF_DURATION, CONF_FONTSIZE, CONF_INTERRUPT, CONF_POSITION, CONF_TRANSPARENCY, DEFAULT_TIMEOUT, ) _LOGGER = logging.getLogger(__name__) # Deprecated in Home Assistant 2021.8 PLATFORM_SCHEMA = cv.deprecated( vol.All( PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_DURATION): vol.Coerce(int), vol.Optional(CONF_FONTSIZE): vol.In(Notifications.FONTSIZES.keys()), vol.Optional(CONF_POSITION): vol.In(Notifications.POSITIONS.keys()), vol.Optional(CONF_TRANSPARENCY): vol.In( Notifications.TRANSPARENCIES.keys() ), vol.Optional(CONF_COLOR): vol.In(Notifications.BKG_COLORS.keys()), vol.Optional(CONF_TIMEOUT): vol.Coerce(int), vol.Optional(CONF_INTERRUPT): cv.boolean, } ), ) ) async def async_get_service(hass: HomeAssistant, config, discovery_info=None): """Get the NFAndroidTV notification service.""" if discovery_info is not None: notify = await hass.async_add_executor_job( Notifications, discovery_info[CONF_HOST] ) return NFAndroidTVNotificationService( notify, hass.config.is_allowed_path, ) notify = await hass.async_add_executor_job(Notifications, config.get(CONF_HOST)) return NFAndroidTVNotificationService( notify, hass.config.is_allowed_path, ) class NFAndroidTVNotificationService(BaseNotificationService): """Notification service for Notifications for Android TV.""" def __init__( self, notify: Notifications, is_allowed_path, ): """Initialize the service.""" self.notify = notify self.is_allowed_path = is_allowed_path def send_message(self, message="", **kwargs): """Send a message to a Android TV device.""" data = kwargs.get(ATTR_DATA) title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) duration = None fontsize = None position = None transparency = None bkgcolor = None interrupt = None icon = None image_file = None if data: if ATTR_DURATION in data: try: duration = int(data.get(ATTR_DURATION)) except ValueError: _LOGGER.warning( "Invalid duration-value: %s", str(data.get(ATTR_DURATION)) ) if ATTR_FONTSIZE in data: if data.get(ATTR_FONTSIZE) in Notifications.FONTSIZES: fontsize = data.get(ATTR_FONTSIZE) else: _LOGGER.warning( "Invalid fontsize-value: %s", str(data.get(ATTR_FONTSIZE)) ) if ATTR_POSITION in data: if data.get(ATTR_POSITION) in Notifications.POSITIONS: position = data.get(ATTR_POSITION) else: _LOGGER.warning( "Invalid position-value: %s", str(data.get(ATTR_POSITION)) ) if ATTR_TRANSPARENCY in data: if data.get(ATTR_TRANSPARENCY) in Notifications.TRANSPARENCIES: transparency = data.get(ATTR_TRANSPARENCY) else: _LOGGER.warning( "Invalid transparency-value: %s", str(data.get(ATTR_TRANSPARENCY)), ) if ATTR_COLOR in data: if data.get(ATTR_COLOR) in Notifications.BKG_COLORS: bkgcolor = data.get(ATTR_COLOR) else: _LOGGER.warning( "Invalid color-value: %s", str(data.get(ATTR_COLOR)) ) if ATTR_INTERRUPT in data: try: interrupt = cv.boolean(data.get(ATTR_INTERRUPT)) except vol.Invalid: _LOGGER.warning( "Invalid interrupt-value: %s", str(data.get(ATTR_INTERRUPT)) ) filedata = data.get(ATTR_FILE) if data else None if filedata is not None: if ATTR_ICON in filedata: icon = self.load_file( url=filedata.get(ATTR_ICON), local_path=filedata.get(ATTR_FILE_PATH), username=filedata.get(ATTR_FILE_USERNAME), password=filedata.get(ATTR_FILE_PASSWORD), auth=filedata.get(ATTR_FILE_AUTH), ) image_file = self.load_file( url=filedata.get(ATTR_FILE_URL), local_path=filedata.get(ATTR_FILE_PATH), username=filedata.get(ATTR_FILE_USERNAME), password=filedata.get(ATTR_FILE_PASSWORD), auth=filedata.get(ATTR_FILE_AUTH), ) self.notify.send( message, title=title, duration=duration, fontsize=fontsize, position=position, bkgcolor=bkgcolor, transparency=transparency, interrupt=interrupt, icon=icon, image_file=image_file, ) def load_file( self, url=None, local_path=None, username=None, password=None, auth=None ): """Load image/document/etc from a local path or URL.""" try: if url is not None: # Check whether authentication parameters are provided if username is not None and password is not None: # Use digest or basic authentication if ATTR_FILE_AUTH_DIGEST == auth: auth_ = HTTPDigestAuth(username, password) else: auth_ = HTTPBasicAuth(username, password) # Load file from URL with authentication req = requests.get(url, auth=auth_, timeout=DEFAULT_TIMEOUT) else: # Load file from URL without authentication req = requests.get(url, timeout=DEFAULT_TIMEOUT) return req.content if local_path is not None: # Check whether path is whitelisted in configuration.yaml if self.is_allowed_path(local_path): return open(local_path, "rb") _LOGGER.warning("'%s' is not secure to load data from!", local_path) else: _LOGGER.warning("Neither URL nor local path found in params!") except OSError as error: _LOGGER.error("Can't load from url or local path: %s", error) return None
# Functions/classes for WCSAxes related to APE14 WCSes import numpy as np from astropy.coordinates import SkyCoord, ICRS, BaseCoordinateFrame from astropy import units as u from astropy.wcs import WCS from astropy.wcs.wcsapi import SlicedLowLevelWCS from .frame import RectangularFrame, EllipticalFrame from .transforms import CurvedTransform __all__ = ['transform_coord_meta_from_wcs', 'WCSWorld2PixelTransform', 'WCSPixel2WorldTransform'] IDENTITY = WCS(naxis=2) IDENTITY.wcs.ctype = ["X", "Y"] IDENTITY.wcs.crval = [0., 0.] IDENTITY.wcs.crpix = [1., 1.] IDENTITY.wcs.cdelt = [1., 1.] def transform_coord_meta_from_wcs(wcs, frame_class, aslice=None): is_fits_wcs = isinstance(wcs, WCS) coord_meta = {} coord_meta['name'] = [] coord_meta['type'] = [] coord_meta['wrap'] = [] coord_meta['unit'] = [] coord_meta['format_unit'] = [] invert_xy = False if aslice is not None: wcs_slice = list(aslice) wcs_slice[wcs_slice.index("x")] = slice(None) wcs_slice[wcs_slice.index("y")] = slice(None) wcs = SlicedLowLevelWCS(wcs, wcs_slice[::-1]) invert_xy = aslice.index('x') > aslice.index('y') transform = WCSPixel2WorldTransform(wcs, invert_xy=invert_xy) for idx in range(wcs.world_n_dim): axis_type = wcs.world_axis_physical_types[idx] axis_unit = u.Unit(wcs.world_axis_units[idx]) coord_wrap = None format_unit = axis_unit coord_type = 'scalar' if axis_type is not None: axis_type_split = axis_type.split('.') if "pos.helioprojective.lon" in axis_type: coord_wrap = 180. format_unit = u.arcsec coord_type = "longitude" elif "pos.helioprojective.lat" in axis_type: format_unit = u.arcsec coord_type = "latitude" elif "pos" in axis_type_split: if "lon" in axis_type_split: coord_type = "longitude" elif "lat" in axis_type_split: coord_type = "latitude" elif "ra" in axis_type_split: coord_type = "longitude" format_unit = u.hourangle elif "dec" in axis_type_split: coord_type = "latitude" elif "alt" in axis_type_split: coord_type = "longitude" elif "az" in axis_type_split: coord_type = "latitude" elif "long" in axis_type_split: coord_type = "longitude" coord_meta['type'].append(coord_type) coord_meta['wrap'].append(coord_wrap) coord_meta['format_unit'].append(format_unit) coord_meta['unit'].append(axis_unit) # For FITS-WCS, for backward-compatibility, we need to make sure that we # provide aliases based on CTYPE for the name. if is_fits_wcs: if isinstance(wcs, WCS): alias = wcs.wcs.ctype[idx][:4].replace('-', '').lower() elif isinstance(wcs, SlicedLowLevelWCS): alias = wcs._wcs.wcs.ctype[wcs._world_keep[idx]][:4].replace('-', '').lower() name = (axis_type, alias) if axis_type else alias else: name = axis_type or '' coord_meta['name'].append(name) coord_meta['default_axislabel_position'] = [''] * wcs.world_n_dim coord_meta['default_ticklabel_position'] = [''] * wcs.world_n_dim coord_meta['default_ticks_position'] = [''] * wcs.world_n_dim m = wcs.axis_correlation_matrix.copy() if invert_xy: m = m[:, ::-1] if frame_class is RectangularFrame: for i, spine_name in enumerate('bltr'): pos = np.nonzero(m[:, i % 2])[0] if len(pos) > 0: coord_meta['default_axislabel_position'][pos[0]] = spine_name coord_meta['default_ticklabel_position'][pos[0]] = spine_name coord_meta['default_ticks_position'][pos[0]] = spine_name m[pos[0], :] = 0 # In the special and common case where the frame is rectangular and # we are dealing with 2-d WCS, we show all ticks on all axes for # backward-compatibility. if len(coord_meta['type']) == 2: coord_meta['default_ticks_position'] = ['bltr'] * wcs.world_n_dim elif frame_class is EllipticalFrame: if 'longitude' in coord_meta['type']: lon_idx = coord_meta['type'].index('longitude') coord_meta['default_axislabel_position'][lon_idx] = 'h' coord_meta['default_ticklabel_position'][lon_idx] = 'h' coord_meta['default_ticks_position'][lon_idx] = 'h' if 'latitude' in coord_meta['type']: lat_idx = coord_meta['type'].index('latitude') coord_meta['default_axislabel_position'][lat_idx] = 'c' coord_meta['default_ticklabel_position'][lat_idx] = 'c' coord_meta['default_ticks_position'][lat_idx] = 'c' else: for i in range(wcs.world_n_dim): coord_meta['default_axislabel_position'][i] = frame_class.spine_names coord_meta['default_ticklabel_position'][i] = frame_class.spine_names coord_meta['default_ticks_position'][i] = frame_class.spine_names return transform, coord_meta def wcsapi_to_celestial_frame(wcs): for cls, args, kwargs in wcs.world_axis_object_classes.values(): if issubclass(cls, SkyCoord): return kwargs.get('frame', ICRS()) elif issubclass(cls, BaseCoordinateFrame): return cls(**kwargs) class WCSWorld2PixelTransform(CurvedTransform): """ WCS transformation from world to pixel coordinates """ has_inverse = True frame_in = None def __init__(self, wcs, invert_xy=False): super().__init__() if wcs.pixel_n_dim != 2: raise ValueError('Only pixel_n_dim==2 is supported') self.wcs = wcs self.invert_xy = invert_xy self.frame_in = wcsapi_to_celestial_frame(wcs) def __eq__(self, other): return (isinstance(other, type(self)) and self.wcs is other.wcs and self.invert_xy == other.invert_xy) @property def input_dims(self): return self.wcs.world_n_dim def transform(self, world): # Convert to a list of arrays world = list(world.T) if len(world) != self.wcs.world_n_dim: raise ValueError(f"Expected {self.wcs.world_n_dim} world coordinates, got {len(world)} ") if len(world[0]) == 0: pixel = np.zeros((0, 2)) else: pixel = self.wcs.world_to_pixel_values(*world) if self.invert_xy: pixel = pixel[::-1] pixel = np.array(pixel).T return pixel transform_non_affine = transform def inverted(self): """ Return the inverse of the transform """ return WCSPixel2WorldTransform(self.wcs, invert_xy=self.invert_xy) class WCSPixel2WorldTransform(CurvedTransform): """ WCS transformation from pixel to world coordinates """ has_inverse = True def __init__(self, wcs, invert_xy=False): super().__init__() if wcs.pixel_n_dim != 2: raise ValueError('Only pixel_n_dim==2 is supported') self.wcs = wcs self.invert_xy = invert_xy self.frame_out = wcsapi_to_celestial_frame(wcs) def __eq__(self, other): return (isinstance(other, type(self)) and self.wcs is other.wcs and self.invert_xy == other.invert_xy) @property def output_dims(self): return self.wcs.world_n_dim def transform(self, pixel): # Convert to a list of arrays pixel = list(pixel.T) if len(pixel) != self.wcs.pixel_n_dim: raise ValueError(f"Expected {self.wcs.pixel_n_dim} world coordinates, got {len(pixel)} ") if self.invert_xy: pixel = pixel[::-1] if len(pixel[0]) == 0: world = np.zeros((0, self.wcs.world_n_dim)) else: world = self.wcs.pixel_to_world_values(*pixel) # At the moment, one has to manually check that the transformation # round-trips, otherwise it should be considered invalid. pixel_check = self.wcs.world_to_pixel_values(*world) with np.errstate(invalid='ignore'): invalid = np.zeros(len(pixel[0]), dtype=bool) for ipix in range(len(pixel)): invalid |= np.abs(pixel_check[ipix] - pixel[ipix]) > 1. for iwrl in range(len(world)): world[iwrl][invalid] = np.nan world = np.array(world).T return world transform_non_affine = transform def inverted(self): """ Return the inverse of the transform """ return WCSWorld2PixelTransform(self.wcs, invert_xy=self.invert_xy)