input
stringlengths
2.65k
237k
output
stringclasses
1 value
= self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='str', auth_settings=auth_settings, callback=params.get('callback')) return response def connect_head_namespaced_pod_proxy_2(self, namespace, name, path2, **kwargs): """ connect HEAD requests to proxy of Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.connect_head_namespaced_pod_proxy_2(namespace, name, path2, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str name: name of the Pod (required) :param str path2: path to the resource (required) :param str path: Path is the URL path to use for the current proxy request to pod. :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'name', 'path2', 'path'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method connect_head_namespaced_pod_proxy_2" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_pod_proxy_2`") # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `connect_head_namespaced_pod_proxy_2`") # verify the required parameter 'path2' is set if ('path2' not in params) or (params['path2'] is None): raise ValueError("Missing the required parameter `path2` when calling `connect_head_namespaced_pod_proxy_2`") resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json') method = 'HEAD' path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] if 'name' in params: path_params['name'] = params['name'] if 'path2' in params: path_params['path'] = params['path2'] query_params = {} if 'path' in params: query_params['path'] = params['path'] header_params = {} form_params = {} files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = [] response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='str', auth_settings=auth_settings, callback=params.get('callback')) return response def connect_put_namespaced_pod_proxy_3(self, namespace, name, path2, **kwargs): """ connect PUT requests to proxy of Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.connect_put_namespaced_pod_proxy_3(namespace, name, path2, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str name: name of the Pod (required) :param str path2: path to the resource (required) :param str path: Path is the URL path to use for the current proxy request to pod. :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'name', 'path2', 'path'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method connect_put_namespaced_pod_proxy_3" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_pod_proxy_3`") # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `connect_put_namespaced_pod_proxy_3`") # verify the required parameter 'path2' is set if ('path2' not in params) or (params['path2'] is None): raise ValueError("Missing the required parameter `path2` when calling `connect_put_namespaced_pod_proxy_3`") resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json') method = 'PUT' path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] if 'name' in params: path_params['name'] = params['name'] if 'path2' in params: path_params['path'] = params['path2'] query_params = {} if 'path' in params: query_params['path'] = params['path'] header_params = {} form_params = {} files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = [] response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='str', auth_settings=auth_settings, callback=params.get('callback')) return response def connect_post_namespaced_pod_proxy_4(self, namespace, name, path2, **kwargs): """ connect POST requests to proxy of Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.connect_post_namespaced_pod_proxy_4(namespace, name, path2, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str name: name of the Pod (required) :param str path2: path to the resource (required) :param str path: Path is the URL path to use for the current proxy request to pod. :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'name', 'path2', 'path'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method connect_post_namespaced_pod_proxy_4" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_proxy_4`") # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_proxy_4`") # verify the required parameter 'path2' is set if ('path2' not in params) or (params['path2'] is None): raise ValueError("Missing the required parameter `path2` when calling `connect_post_namespaced_pod_proxy_4`") resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json') method = 'POST' path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] if 'name' in params: path_params['name'] = params['name'] if 'path2' in params: path_params['path'] = params['path2'] query_params = {} if 'path' in params: query_params['path'] = params['path'] header_params = {} form_params = {} files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = [] response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='str', auth_settings=auth_settings, callback=params.get('callback')) return response def connect_delete_namespaced_pod_proxy_5(self, namespace, name, path2, **kwargs): """ connect DELETE requests to proxy of Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.connect_delete_namespaced_pod_proxy_5(namespace, name, path2, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str name: name of the Pod (required) :param str path2: path to the resource (required) :param str path: Path is the URL path to use for the current proxy request to pod. :return: str If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'name', 'path2', 'path'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method connect_delete_namespaced_pod_proxy_5" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_pod_proxy_5`") # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_pod_proxy_5`") # verify the required parameter 'path2' is set if ('path2' not in params) or (params['path2'] is None): raise ValueError("Missing the required parameter `path2` when calling `connect_delete_namespaced_pod_proxy_5`") resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json') method
# IMPORT CYTHON VERSION from EC_GAME import momentum_angle_free, momentum_trigonometry # IMPORT C VERSION from ECC import momentum_angle_free_c, momentum_trigonometry_c import pygame from pygame.math import Vector2 if __name__ == '__main__': import timeit v1 = Vector2(0.707, 0.707) x1 = Vector2(0.0, 0.0) v2 = Vector2(-0.707, -0.707) x2 = Vector2(1.4142, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y invert = False vec1, vec2 = momentum_angle_free(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nANGLE FREE - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) v1 = Vector2(-0.707, 0.707) x1 = Vector2(1.4142, 0.0) v2 = Vector2(0.707, -0.707) x2 = Vector2(0, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y vec1, vec2 = momentum_angle_free(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nANGLE FREE - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) v1 = Vector2(-0.707, -0.707) x1 = Vector2(1.4142, 1.4142) v2 = Vector2(0.707, 0.707) x2 = Vector2(0, 0) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y vec1, vec2 = momentum_angle_free(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nANGLE FREE - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) v1 = Vector2(0.707, -0.707) x1 = Vector2(0, 1.4142) v2 = Vector2(-0.707, 0.707) x2 = Vector2(1.4142, 0) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y vec1, vec2 = momentum_angle_free(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nANGLE FREE - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) print("\nANGLE FREE :", timeit.timeit("momentum_angle_free(v1x, v1y, v2x, " "v2y, m1, m2, x1x, x1y, x2x, x2y)", "from __main__ import momentum_angle_free, " "v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y", number=1000000)) # ------------------------------------------------------------------------------------------------------------- v1 = Vector2(0.707, 0.707) x1 = Vector2(0.0, 0.0) v2 = Vector2(-0.707, -0.707) x2 = Vector2(1.4142, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y invert = False vec1, vec2 = momentum_trigonometry(x1x, x1y, x2x, x2y, v1x, v1y, v2x, v2y, m1, m2, invert) print("\nTRIGO - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nTRIGO - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) v1 = Vector2(-0.707, 0.707) x1 = Vector2(1.4142, 0.0) v2 = Vector2(0.707, -0.707) x2 = Vector2(0, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y vec1, vec2 = momentum_trigonometry(x1x, x1y, x2x, x2y, v1x, v1y, v2x, v2y, m1, m2, invert) print("\nTRIGO - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nTRIGO - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) v1 = Vector2(-0.707, -0.707) x1 = Vector2(1.4142, 1.4142) v2 = Vector2(0.707, 0.707) x2 = Vector2(0, 0) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y vec1, vec2 = momentum_trigonometry(x1x, x1y, x2x, x2y, v1x, v1y, v2x, v2y, m1, m2, invert) print("\nTRIGO - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nTRIGO - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) v1 = Vector2(0.707, -0.707) x1 = Vector2(0, 1.4142) v2 = Vector2(-0.707, 0.707) x2 = Vector2(1.4142, 0) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y vec1, vec2 = momentum_trigonometry(x1x, x1y, x2x, x2y, v1x, v1y, v2x, v2y, m1, m2, invert) print("\nTRIGO - object1 vector : (x:%s y:%s) ", (vec1['x'], vec1['y'])) print("\nTRIGO - object2 vector : (x:%s y:%s) ", (vec2['x'], vec2['y'])) print("\nTRIGONOMETRY:", timeit.timeit("momentum_trigonometry(x1x, x1y, x2x, x2y, v1x, v1y, v2x, v2y, m1, m2)", "from __main__ import momentum_trigonometry, v1x, v1y, v2x, v2y, m1, m2," " x1x, x1y, x2x, x2y", number=1000000)) # ------------------------------------------------------------------------------------------------------------- v1 = Vector2(0.707, 0.707) x1 = Vector2(0.0, 0.0) v2 = Vector2(-0.707, -0.707) x2 = Vector2(1.4142, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y invert = False pyobject = momentum_angle_free_c(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE C - object1 vector : (x:%s y:%s) ", (pyobject['v12']['x'], pyobject['v12']['y'])) print("\nANGLE FREE C - object2 vector : (x:%s y:%s) ", (pyobject['v21']['x'], pyobject['v21']['y'])) v1 = Vector2(-0.707, 0.707) x1 = Vector2(1.4142, 0.0) v2 = Vector2(0.707, -0.707) x2 = Vector2(0, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y pyobject = momentum_angle_free_c(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE C - object1 vector : (x:%s y:%s) ", (pyobject['v12']['x'], pyobject['v12']['y'])) print("\nANGLE FREE C - object2 vector : (x:%s y:%s) ", (pyobject['v21']['x'], pyobject['v21']['y'])) v1 = Vector2(-0.707, -0.707) x1 = Vector2(1.4142, 1.4142) v2 = Vector2(0.707, 0.707) x2 = Vector2(0, 0) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y pyobject = momentum_angle_free_c(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE C - object1 vector : (x:%s y:%s) ", (pyobject['v12']['x'], pyobject['v12']['y'])) print("\nANGLE FREE C - object2 vector : (x:%s y:%s) ", (pyobject['v21']['x'], pyobject['v21']['y'])) v1 = Vector2(0.707, -0.707) x1 = Vector2(0, 1.4142) v2 = Vector2(-0.707, 0.707) x2 = Vector2(1.4142, 0) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y pyobject = momentum_angle_free_c(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y, invert) print("\nANGLE FREE C - object1 vector : (x:%s y:%s) ", (pyobject['v12']['x'], pyobject['v12']['y'])) print("\nANGLE FREE C - object2 vector : (x:%s y:%s) ", (pyobject['v21']['x'], pyobject['v21']['y'])) print("\nANGLE FREE C : ", timeit.timeit("momentum_angle_free_c(v1x, v1y, v2x, v2y, m1, m2, x1x, x1y, x2x, x2y)", "from __main__ import momentum_angle_free_c, v1x, v1y, v2x, v2y," " m1, m2, x1x, x1y, x2x, x2y", number=1000000)) # ---------------------------------------------------------------------------------------------------------------- v1 = Vector2(0.707, 0.707) x1 = Vector2(0.0, 0.0) v2 = Vector2(-0.707, -0.707) x2 = Vector2(1.4142, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y invert = False pyobject = momentum_trigonometry_c(v1x, v1y, m1, x1x, x1y, v2x, v2y, m2, x2x, x2y, invert) print("\nTRIGONOMETRY C - object1 vector : (x:%s y:%s) ", (pyobject['v12']['x'], pyobject['v12']['y'])) print("\nTRIGONOMETRY C - object2 vector : (x:%s y:%s) ", (pyobject['v21']['x'], pyobject['v21']['y'])) v1 = Vector2(-0.707, 0.707) x1 = Vector2(1.4142, 0.0) v2 = Vector2(0.707, -0.707) x2 = Vector2(0, 1.4142) m1 = 1.0 m2 = 1.0 x1x = x1.x x1y = x1.y x2x = x2.x x2y = x2.y v1x = v1.x v1y = v1.y v2x = v2.x v2y = v2.y pyobject = momentum_trigonometry_c(v1x, v1y, m1, x1x, x1y, v2x, v2y, m2, x2x, x2y, invert) print("\nTRIGONOMETRY C - object1 vector : (x:%s y:%s) ", (pyobject['v12']['x'], pyobject['v12']['y'])) print("\nTRIGONOMETRY C - object2 vector : (x:%s y:%s) ", (pyobject['v21']['x'], pyobject['v21']['y'])) v1 = Vector2(-0.707, -0.707) x1 = Vector2(1.4142, 1.4142)
"""Eco Heat Recovery Ventilation Fan Control (e.g. Blauberg VENTO Expert A50-1 W)""" from __future__ import annotations import asyncio from email.policy import default import logging import ipaddress import time from datetime import timedelta import voluptuous as vol from homeassistant.components.fan import ( ATTR_PERCENTAGE, ENTITY_ID_FORMAT, PLATFORM_SCHEMA, FanEntity, FanEntityFeature, ) from homeassistant.const import ( CONF_DEVICE_ID, CONF_ENTITY_ID, CONF_IP_ADDRESS, CONF_NAME, CONF_PASSWORD, CONF_PORT, ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.event import async_track_state_change_event from .const import ( MY_DOMAIN, CONF_DEFAULT_DEVICE_ID, CONF_DEFAULT_NAME, CONF_DEFAULT_PASSWORD, CONF_DEFAULT_PORT, ATTR_AIRFLOW, ATTR_AIRFLOW_MODES, ATTR_FILTER_REPLACEMENT_STATUS, ATTR_FILTER_TIMER_COUNTDOWN, ATTR_HUMIDITY, ATTR_HUMIDITY_SENSOR_STATUS, ATTR_HUMIDITY_SENSOR_TRESHOLD, ATTR_MACHINE_HOURS, PRESET_MODE_ON, SERVICE_CLEAR_FILTER_REMINDER, SERVICE_SET_AIRFLOW, SERVICE_HUMIDITY_SENSOR_TURN_ON, SERVICE_HUMIDITY_SENSOR_TURN_OFF, SERVICE_SET_HUMIDITY_SENSOR_TRESHOLD_PERCENTAGE, ) LOG = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=CONF_DEFAULT_NAME): cv.string, vol.Optional(CONF_DEVICE_ID, default=CONF_DEFAULT_DEVICE_ID): cv.string, vol.Required(CONF_IP_ADDRESS): vol.All(ipaddress.ip_address, cv.string), vol.Optional(CONF_PORT, default=CONF_DEFAULT_PORT): cv.port, vol.Optional(CONF_PASSWORD, default=CONF_DEFAULT_PASSWORD): cv.string, } ) # pylint: disable=unused-argument async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Initialize the EcoVent fans from config.""" name = config.get(CONF_NAME) device_id = config.get(CONF_DEVICE_ID) device_ip_address = config.get(CONF_IP_ADDRESS) device_port = config.get(CONF_PORT) device_pass = config.get(CONF_PASSWORD) fan = EcoVentFan( hass, config, device_ip_address, device_pass, device_id, name, device_port ) async_add_entities([fan], update_before_add=True) # expose service call APIs # component = EntityComponent(LOG, MY_DOMAIN, hass) component = entity_platform.async_get_current_platform() component.async_register_entity_service( SERVICE_SET_AIRFLOW, {vol.Required(ATTR_AIRFLOW): cv.string}, "async_set_airflow", ) component.async_register_entity_service( SERVICE_HUMIDITY_SENSOR_TURN_ON, {}, "async_humidity_sensor_turn_on", ) component.async_register_entity_service( SERVICE_HUMIDITY_SENSOR_TURN_OFF, {}, "async_humidity_sensor_turn_off", ) component.async_register_entity_service( SERVICE_SET_HUMIDITY_SENSOR_TRESHOLD_PERCENTAGE, { vol.Required(ATTR_PERCENTAGE): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ) }, "async_set_humidity_sensor_treshold_percentage", ) component.async_register_entity_service( SERVICE_CLEAR_FILTER_REMINDER, {}, "async_clear_filter_reminder" ) return True """Library to handle communication with Wifi ecofan from TwinFresh / Blauberg""" import socket import sys import time import math from typing import Any class EcoVentFan(FanEntity): """Class to communicate with the ecofan""" HEADER = f"FDFD" func = { "read": "01", "write": "02", "write_return": "03", "inc": "04", "dec": "05", "resp": "06", } states = {0: "off", 1: "on", 2: "togle"} speeds = { 0: "standby", 1: "low", 2: "medium", 3: "high", 0xFF: "manual", } timer_modes = {0: "off", 1: "night", 2: "party"} statuses = {0: "off", 1: "on"} airflows = {0: "ventilation", 1: "heat_recovery", 2: "air_supply"} alarms = {0: "no", 1: "alarm", 2: "warning"} days_of_week = { 0: "all days", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday", 8: "Mon-Fri", 9: "Sat-Sun", } filters = {0: "filter replacement not required", 1: "replace filter"} unit_types = { 0x0300: "Vento Expert A50-1/A85-1/A100-1 W V.2", 0x0400: "Vento Expert Duo A30-1 W V.2", 0x0500: "Vento Expert A30 W V.2", } wifi_operation_modes = {1: "client", 2: "ap"} wifi_enc_types = {48: "Open", 50: "wpa-psk", 51: "wpa2_psk", 52: "wpa_wpa2_psk"} wifi_dhcps = {0: "STATIC", 1: "DHCP", 2: "Invert"} params = { 0x0001: ["state", states], 0x0002: ["speed", speeds], 0x0006: ["boost_status", statuses], 0x0007: ["timer_mode", timer_modes], 0x000B: ["timer_counter", None], 0x000F: ["humidity_sensor_state", states], 0x0014: ["relay_sensor_state", states], 0x0016: ["analogV_sensor_state", states], 0x0019: ["humidity_treshold", None], 0x0024: ["battery_voltage", None], 0x0025: ["humidity", None], 0x002D: ["analogV", None], 0x0032: ["relay_status", statuses], 0x0044: ["man_speed", None], 0x004A: ["fan1_speed", None], 0x004B: ["fan2_speed", None], 0x0064: ["filter_timer_countdown", None], 0x0066: ["boost_time", None], 0x006F: ["rtc_time", None], 0x0070: ["rtc_date", None], 0x0072: ["weekly_schedule_state", states], 0x0077: ["weekly_schedule_setup", None], 0x007C: ["device_search", None], 0x007D: ["device_password", None], 0x007E: ["machine_hours", None], 0x0083: ["alarm_status", alarms], 0x0085: ["cloud_server_state", states], 0x0086: ["firmware", None], 0x0088: ["filter_replacement_status", statuses], 0x0094: ["wifi_operation_mode", wifi_operation_modes], 0x0095: ["wifi_name", None], 0x0096: ["wifi_pasword", None], 0x0099: ["wifi_enc_type", wifi_enc_types], 0x009A: ["wifi_freq_chnnel", None], 0x009B: ["wifi_dhcp", wifi_dhcps], 0x009C: ["wifi_assigned_ip", None], 0x009D: ["wifi_assigned_netmask", None], 0x009E: ["wifi_main_gateway", None], 0x00A3: ["curent_wifi_ip", None], 0x00B7: ["airflow", airflows], 0x00B8: ["analogV_treshold", None], 0x00B9: ["unit_type", unit_types], 0x0302: ["night_mode_timer", None], 0x0303: ["party_mode_timer", None], 0x0304: ["humidity_status", statuses], 0x0305: ["analogV_status", statuses], } write_only_params = { 0x0065: ["filter_timer_reset", None], 0x0077: ["weekly_schedule_setup", None], 0x0080: ["reset_alarms", None], 0x0087: ["factory_reset", None], 0x00A0: ["wifi_apply_and_quit", None], 0x00A2: ["wifi_discard_and_quit", None], } # ========================== HA implementation ========================== def __init__( self, hass, conf, host, password="<PASSWORD>", fan_id="DEFAULT_DEVICEID", name="ecofanv2", port=4000, ): self.hass = hass self._name = name self._host = host self._port = port self._type = "02" self._id = fan_id self._pwd_size = 0 self._password = password # HA attribute self._attr_preset_modes = [PRESET_MODE_ON] if fan_id == "DEFAULT_DEVICEID": self.get_param("device_search") self._id = self.device_search # Set HA unique_id self._attr_unique_id = self._id self.update() LOG.info(f"Created EcoVent fan controller '{self._host}'") async def async_added_to_hass(self) -> None: """Once entity has been added to HASS, subscribe to state changes.""" await super().async_added_to_hass() # setup listeners to track changes async_track_state_change_event( self.hass, [ self.state, self.speed, self.humidity, self.airflow, self.filter_replacement_status, ], self._state_changed, ) @callback def _state_changed(self, event): """Whenever state, speed, humidity or airflow change state, the fan speed needs to be updated""" entity = event.data.get("entity_id") to_state = event.data["new_state"].state ## sometimes there is no from_state old_state = event.data.get("old_state") from_state = old_state.state if old_state else None if not from_state or to_state != from_state: LOG.info( f"{entity} changed from {from_state} to {to_state}, updating '{self._name}'" ) self.schedule_update_ha_state() # pylint: disable=arguments-differ async def async_turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs, ) -> None: """Turn on the fan.""" if self.state == "off": if percentage is not None: if percentage < 2: percentage = 33 # Set to LOW await self.async_set_percentage(percentage) if preset_mode is None: await self.async_set_preset_mode(PRESET_MODE_ON) # Set to defalut else: await self.async_set_preset_mode(preset_mode) self.turn_on_ventilation() def turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs, ) -> None: """Turn on the fan.""" self.async_turn_on(percentage, preset_mode, **kwargs) async def async_turn_off(self): """Turn the entity off.""" if self.state == "on": self.turn_off_ventilation() # override orignial entity method def turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" self.async_turn_off() def set_preset_mode(self, preset_mode: str) -> None: LOG.info(f"Set async_set_preset_mode to: {preset_mode}") self._attr_preset_mode = preset_mode if preset_mode == PRESET_MODE_ON: self.turn_on_ventilation() else: self.turn_off() async def async_set_percentage(self, percentage: int) -> None: LOG.info(f"async_set_percentage: {percentage}") """Set the speed of the fan, as a percentage.""" if percentage < 2: await self.async_turn_off() else: self.set_man_speed_percent(percentage) self.turn_on_ventilation() async def async_set_airflow(self, airflow: str): """Set the airflow of the fan.""" self._airflow = airflow self.set_airflow(await self.get_airflow_number_by_name(airflow)) async def get_airflow_number_by_name(self, airflow: str): return list(self.airflows.values()).index(airflow) async def async_humidity_sensor_turn_on(self): request = "000F" value = "01" if self.humidity_sensor_state == "off": self.do_func(self.func["write_return"], request, value) async def async_humidity_sensor_turn_off(self): request = "000F" value = "00" if self.humidity_sensor_state == "on": self.do_func(self.func["write_return"], request, value) async def async_set_humidity_sensor_treshold_percentage(self, percentage: int): if percentage >= 40 and percentage <= 80: request = "0019" value = hex(percentage).replace("0x", "").zfill(2) self.do_func(self.func["write_return"], request, value) # DO WE NEED IT? self.humidity_treshold = percentage async def async_clear_filter_reminder(self): # !!!! NOT TESTED YET !!!!! if self.filter_replacement_status == "on": request = "0065" self.do_func(self.func["write"], request) async def async_set_direction(self, direction: str): """Set the direction of the fan.""" raise NotImplementedError(f"Use {SERVICE_SET_AIRFLOW} service.") async def async_oscillate(self, oscillating: bool): """Oscillate the fan.""" raise NotImplementedError(f"The fan does not support oscillations.") @property def extra_state_attributes(self): """Return optional state attributes.""" data: dict[str, float | str | None] = self.state_attributes data[ATTR_AIRFLOW_MODES] = self.airflows data["device_id"] = self.id data[ATTR_AIRFLOW] = self.airflow data[ATTR_HUMIDITY] = self.humidity data[ATTR_HUMIDITY_SENSOR_STATUS] = self.humidity_status data[ATTR_HUMIDITY_SENSOR_TRESHOLD] = self.humidity_treshold # data["night_mode_timer"] = self.night_mode_timer data[ATTR_FILTER_REPLACEMENT_STATUS] = self.filter_replacement_status data[ATTR_FILTER_TIMER_COUNTDOWN] = self.filter_timer_countdown data[ATTR_MACHINE_HOURS] = self.machine_hours return data @property def supported_features(self) -> int: return FanEntityFeature.SET_SPEED | FanEntityFeature.PRESET_MODE # ========================== HA implementation ========================== def connect(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.settimeout(4) self.socket.connect((self._host, self._port)) return self.socket def str2hex(self, str_msg): return "".join("{:02x}".format(ord(c)) for c in str_msg) def hex2str(self, hex_msg): return "".join( chr(int("0x" + hex_msg[i : (i + 2)], 16)) for i in range(0, len(hex_msg), 2) ) def hexstr2tuple(self, hex_msg): return [int(hex_msg[i : (i + 2)], 16) for i in range(0, len(hex_msg), 2)] def chksum(self, hex_msg): checksum = hex(sum(self.hexstr2tuple(hex_msg))).replace("0x", "").zfill(4) byte_array = bytearray.fromhex(checksum) chksum = hex(byte_array[1]).replace("0x", "").zfill(2) + hex( byte_array[0] ).replace("0x", "").zfill(2) return f"{chksum}" def get_size(self, str): return hex(len(str)).replace("0x", "").zfill(2) def get_header(self): id_size = self.get_size(self._id) pwd_size = self.get_size(self._password) id = self.str2hex(self._id) password = self.str2hex(self._password) str = f"{self._type}{id_size}{id}{pwd_size}{password}" return str def get_params_index(self, value): for i in self.params: if self.params[i][0] == value: return i def get_write_only_params_index(self, value): for i in self.write_only_params: if self.write_only_params[i][0] == value: return i def get_params_values(self, idx, value): index = self.get_params_index(idx) if index != None: if self.params[index][1] != None: for i in self.params[index][1]: if self.params[index][1][i] == value: return [index, i] return [index, None] else: return [None, None] def send(self, data): self.socket = self.connect() payload = self.get_header() + data payload = self.HEADER + payload + self.chksum(payload) return self.socket.sendall(bytes.fromhex(payload)) def receive(self): try: response = self.socket.recv(4096) return response except socket.timeout: return None def do_func(self, func, param, value=""): out = "" parameter = "" for i in range(0, len(param), 4): n_out = "" out = param[i :
fmt % (n, self.Atoms.type[n], self.Atoms.label[n], self.Atoms.u[n], self.Atoms.v[n], self.Atoms.w[n], self.Atoms.occupancy[n], self.Atoms.uiso[n]) # Insert string in text box self.text.insert(tk.END, str) def fun_magnets(self): """"ReOpen window with magnetic moments""" # Close window self.root.destroy() AtomsGui(self.xtl, self.symmetric_only, not self.magnetic_moments) def fun_update(self): "Update atomic properties, close window" # Get string from text box str = self.text.get('1.0', tk.END) # Analyse string """ values = np.genfromtxt(str) n = values[:,0] type = values[:,1] label = values[:,2] u = values[:,3] v = values[:,4] w = values[:,5] occ = values[:,6] uiso = values[:,7] """ lines = str.splitlines() n = [] type = [] label = [] u = [] v = [] w = [] occ = [] uiso = [] mx = [] my = [] mz = [] for ln in lines: items = ln.split() if len(items) < 8: continue n += [int(items[0])] type += [items[1]] label += [items[2]] u += [float(items[3])] v += [float(items[4])] w += [float(items[5])] occ += [float(items[6])] uiso += [float(items[7])] if self.magnetic_moments: mx += [float(items[8])] my += [float(items[9])] mz += [float(items[10])] self.Atoms.type = type self.Atoms.label = label self.Atoms.u = np.array(u) self.Atoms.v = np.array(v) self.Atoms.w = np.array(w) self.Atoms.occupancy = np.array(occ) self.Atoms.uiso = np.array(uiso) if self.magnetic_moments: self.Atoms.mx = np.array(mx) self.Atoms.my = np.array(my) self.Atoms.mz = np.array(mz) else: self.Atoms.mx = np.zeros(len(u)) self.Atoms.my = np.zeros(len(u)) self.Atoms.mz = np.zeros(len(u)) if self.symmetric_only: # Apply symmetry if updating basic structure parameters self.xtl.generate_structure() # Close window self.root.destroy() class SymmetryGui: """ View and edit the symmetry operations """ def __init__(self, xtl): """"Initialise""" self.xtl = xtl self.Symmetry = xtl.Symmetry # Create Tk inter instance self.root = tk.Tk() self.root.wm_title(xtl.name + ' Symmetry Operations') # self.root.minsize(width=640, height=480) self.root.maxsize(width=self.root.winfo_screenwidth(), height=self.root.winfo_screenheight()) self.root.tk_setPalette( background=bkg, foreground=txtcol, activeBackground=opt_active, activeForeground=txtcol) frm1 = tk.Frame(self.root) frm1.pack(side=tk.TOP) # Spacegroup entry var = tk.Label(frm1, text='Spacegroup: ', font=TTF) var.pack(side=tk.LEFT) self.spacegroup = tk.StringVar(frm1, 'P1') self.spacegroup_number = tk.StringVar(frm1, '1') var = tk.Entry(frm1, textvariable=self.spacegroup_number, font=TF, width=4, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_spacegroup) var.bind('<KP_Enter>', self.fun_spacegroup) var = tk.Label(frm1, textvariable=self.spacegroup, width=14) var.pack(side=tk.LEFT, padx=5) # Spacegroup Buttons var = tk.Button(frm1, text='Choose\nSpacegroup', command=self.fun_ch_spacegroup, height=2, font=BF, bg=btn, activebackground=btn_active) var.pack(side=tk.LEFT, padx=5, pady=5) var = tk.Button(frm1, text='Choose\nSubgroup', command=self.fun_ch_subgroup, height=2, font=BF, bg=btn, activebackground=btn_active) var.pack(side=tk.LEFT, padx=5, pady=5) var = tk.Button(frm1, text='Choose Magnetic\nSpacegroup', command=self.fun_ch_maggroup, height=2, font=BF, bg=btn, activebackground=btn_active) var.pack(side=tk.LEFT, padx=5, pady=5) frame = tk.Frame(self.root) frame.pack(side=tk.TOP) # ---Labels--- label_frame = tk.Frame(frame, relief=tk.GROOVE) label_frame.pack(side=tk.TOP, fill=tk.X) var = tk.Label(label_frame, text='n', font=SF, justify=tk.CENTER, width=4, height=2, relief=tk.RIDGE) var.pack(side=tk.LEFT, pady=1) var = tk.Label(label_frame, text='Symmetry Operations', font=SF, justify=tk.CENTER, width=25, height=2, relief=tk.RIDGE) var.pack(side=tk.LEFT, pady=1) var = tk.Label(label_frame, text='Magnetic Operations', font=SF, justify=tk.CENTER, width=25, height=2, relief=tk.RIDGE) var.pack(side=tk.LEFT, pady=1) # ---Edit Boxes--- box_frame = tk.Frame(frame) box_frame.pack(side=tk.TOP, fill=tk.BOTH) # Vertical Scrollbar self.scany = tk.Scrollbar(box_frame, command=self.fun_scroll) self.scany.pack(side=tk.RIGHT, fill=tk.Y) # Box 1: n self.text_1 = tk.Text(box_frame, width=4, height=10, font=SF, bg=ety) self.text_1.pack(side=tk.LEFT, pady=1, padx=1) # Box 1: Symmetry operations self.text_2 = tk.Text(box_frame, width=28, height=10, font=SF, bg=ety) self.text_2.pack(side=tk.LEFT, pady=1) # Box 1: Magnetic operations self.text_3 = tk.Text(box_frame, width=28, height=10, font=SF, bg=ety) self.text_3.pack(side=tk.LEFT, pady=1) # Mouse Wheel scroll: self.text_1.bind("<MouseWheel>", self.fun_mousewheel) self.text_2.bind("<MouseWheel>", self.fun_mousewheel) self.text_3.bind("<MouseWheel>", self.fun_mousewheel) self.text_1.config(yscrollcommand=self.fun_move) self.text_2.config(yscrollcommand=self.fun_move) self.text_3.config(yscrollcommand=self.fun_move) # scany.config(command=self.text1.yview) frm1 = tk.Frame(self.root) frm1.pack(side=tk.TOP) # Button var = tk.Button(frm1, text='Update', command=self.fun_update, height=2, font=BF, bg=btn, activebackground=btn_active) var.pack(side=tk.LEFT) # uvw entry var = tk.Label(frm1, text='(u v w)=') var.pack(side=tk.LEFT) self.uvw = tk.StringVar(frm1, '0.5 0 0') var = tk.Entry(frm1, textvariable=self.uvw, font=TF, width=12, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_symuvw) var.bind('<KP_Enter>', self.fun_symuvw) var = tk.Button(frm1, text='Symmetric\nPositions', font=BF, bg=btn, activebackground=btn_active, command=self.fun_symuvw) var.pack(side=tk.LEFT) # hkl entry var = tk.Label(frm1, text='(h k l)=') var.pack(side=tk.LEFT) self.hkl = tk.StringVar(frm1, '1 0 0') var = tk.Entry(frm1, textvariable=self.hkl, font=TF, width=12, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_symhkl) var.bind('<KP_Enter>', self.fun_symhkl) var = tk.Button(frm1, text='Symmetric\nReflections', font=BF, bg=btn, activebackground=btn_active, command=self.fun_symhkl) var.pack(side=tk.LEFT) self.fun_set() def update(self): """Update crystal""" # Get string from text box sym = self.text_2.get('1.0', tk.END) # symmetry operations mag = self.text_3.get('1.0', tk.END) # magnetic operations # remove 'm' mag = mag.replace('m', '') # Analyse string sym_lines = sym.splitlines() mag_lines = mag.splitlines() if len(sym_lines) != len(mag_lines): print('Warning: The number of symmetry and magnetic operations are not the same!') sym_ops = [] mag_ops = [] for sym, mag in zip(sym_lines, mag_lines): if len(sym.strip()) == 0: continue if len(mag.strip()) == 0: mag = fc.symmetry_ops2magnetic([sym.strip()])[0] sym_ops += [sym.strip()] mag_ops += [mag.strip()] self.Symmetry.symmetry_operations = sym_ops self.Symmetry.symmetry_operations_magnetic = mag_ops self.Symmetry.generate_matrices() def fun_move(self, *args): """Move within text frame""" self.scany.set(*args) self.text_1.yview('moveto', args[0]) self.text_2.yview('moveto', args[0]) self.text_3.yview('moveto', args[0]) def fun_scroll(self, *args): """Move scrollbar""" self.text_1.yview(*args) self.text_2.yview(*args) self.text_3.yview(*args) def fun_mousewheel(self, event): """Move scollbar""" self.text_1.yview("scroll", event.delta, "units") self.text_2.yview("scroll", event.delta, "units") self.text_3.yview("scroll", event.delta, "units") # this prevents default bindings from firing, which # would end up scrolling the widget twice return "break" def fun_set(self): """Generate the text box""" # Clear boxes self.text_1.delete('1.0', tk.END) self.text_2.delete('1.0', tk.END) self.text_3.delete('1.0', tk.END) # Build string Nops = len(self.Symmetry.symmetry_operations) symstr = '' magstr = '' for n in range(Nops): self.text_1.insert(tk.END, '%3.0f\n' % n) sym = self.Symmetry.symmetry_operations[n].strip('\"\'') mag = self.Symmetry.symmetry_operations_magnetic[n] symstr += '%25s\n' % (sym) magstr += '%25s\n' % (mag) # Insert string in text box self.text_2.insert(tk.END, symstr) self.text_3.insert(tk.END, magstr) # Update spacegroup name + number self.spacegroup.set(self.Symmetry.spacegroup) self.spacegroup_number.set(self.Symmetry.spacegroup_number) def fun_spacegroup(self, event=None): """Load spacegroup symmetry""" sgn = int(self.spacegroup_number.get()) self.Symmetry.load_spacegroup(sgn) self.fun_set() def fun_ch_spacegroup(self): """Button Select Spacegroup""" current = int(self.spacegroup_number.get()) sg_list = fc.spacegroup_list().split('\n') current_selection = [sg_list[current-1]] selection = SelectionBox(self.root, sg_list, current_selection, 'Select SpaceGroup', False).show() if len(selection) > 0: new_sg = int(selection[0].split()[0]) self.Symmetry.load_spacegroup(new_sg) self.fun_set() def fun_ch_subgroup(self): """Button select subgroup""" current = int(float(self.spacegroup_number.get())) # str > float > int sbg_list = fc.spacegroup_subgroups_list(current).split('\n') selection = SelectionBox(self.root, sbg_list, [], 'Select SpaceGroup Subgroup', False).show() if len(selection) > 0: new_sg = int(selection[0].split()[3]) self.Symmetry.load_spacegroup(new_sg) self.fun_set() def fun_ch_maggroup(self): """Button Select Magnetic Spacegroup""" current = int(self.spacegroup_number.get()) msg_list = fc.spacegroup_magnetic_list(current).split('\n') selection = SelectionBox(self.root, msg_list, [], 'Select Magnetic SpaceGroup', False).show() if len(selection) > 0: new_sg = selection[0].split()[3] self.Symmetry.load_magnetic_spacegroup(new_sg) self.fun_set() def fun_symuvw(self, event=None): """create symmetric uvw position""" self.update() uvw = self.uvw.get() uvw = uvw.replace(',', ' ') # remove commas uvw = uvw.replace('(', '').replace(')', '') # remove brackets uvw = uvw.replace('[', '').replace(']', '') # remove brackets uvw = np.fromstring(uvw, sep=' ') out = self.xtl.Symmetry.print_symmetric_coordinate_operations(uvw) StringViewer(out, 'Symmetric Positions') def fun_symhkl(self, event=None): """create symmetric hkl reflections""" self.update() hkl = self.hkl.get() hkl = hkl.replace(',', ' ') # remove commas hkl = hkl.replace('(', '').replace(')', '') # remove brackets hkl = hkl.replace('[', '').replace(']', '') # remove brackets hkl = np.fromstring(hkl, sep=' ') out = self.xtl.Symmetry.print_symmetric_vectors(hkl) StringViewer(out, 'Symmetric Reflections') def fun_update(self): """Update button""" self.update() # Close window self.root.destroy() class SuperstructureGui: """ Generate a superstructure """ def __init__(self, xtl): """Initialise""" self.xtl = xtl # Create Tk inter instance self.root = tk.Tk() self.root.wm_title('Properties %s' % xtl.name) # self.root.minsize(width=640, height=480) self.root.maxsize(width=self.root.winfo_screenwidth(), height=self.root.winfo_screenheight()) self.root.tk_setPalette( background=bkg, foreground=txtcol, activeBackground=opt_active, activeForeground=txtcol) frame = tk.Frame(self.root) frame.pack(side=tk.LEFT, anchor=tk.N) # Variables if hasattr(xtl, 'P'): # self.P = xtl.P self.P = np.linalg.inv(xtl.P) else: self.P = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] self.a1 = tk.DoubleVar(frame, self.P[0][0]) self.a2 = tk.DoubleVar(frame, self.P[0][1]) self.a3 = tk.DoubleVar(frame, self.P[0][2]) self.b1 = tk.DoubleVar(frame, self.P[1][0]) self.b2 = tk.DoubleVar(frame, self.P[1][1]) self.b3 = tk.DoubleVar(frame, self.P[1][2]) self.c1 = tk.DoubleVar(frame, self.P[2][0]) self.c2 = tk.DoubleVar(frame, self.P[2][1]) self.c3 = tk.DoubleVar(frame, self.P[2][2]) self.parent_hkl = tk.StringVar(frame, '1 0 0') self.super_hkl = tk.StringVar(frame, '1 0 0') lp = self.xtl.Cell.lp() self.latpar1 = tk.StringVar(frame, ' a = %6.3f b = %6.3f c = %6.3f' % lp[:3]) self.latpar2 = tk.StringVar(frame, 'alpha = %6.3f beta = %6.3f gamma = %6.3f' % lp[3:]) # Supercell box box = tk.LabelFrame(frame, text='Superstructure Cell') box.pack(side=tk.TOP, padx=4) # ---Line B1--- bline = tk.Frame(box) bline.pack(side=tk.TOP, expand=tk.TRUE, pady=5) var = tk.Label(bline, text='a\' =') var.pack(side=tk.LEFT) var = tk.Entry(bline, textvariable=self.a1, font=TF, width=3, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_updatecell) var.bind('<KP_Enter>', self.fun_updatecell) var = tk.Label(bline, text='*a + ') var.pack(side=tk.LEFT) var = tk.Entry(bline, textvariable=self.a2, font=TF, width=3, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_updatecell) var.bind('<KP_Enter>', self.fun_updatecell) var = tk.Label(bline, text='*b + ') var.pack(side=tk.LEFT) var = tk.Entry(bline, textvariable=self.a3, font=TF, width=3, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_updatecell) var.bind('<KP_Enter>', self.fun_updatecell) var = tk.Label(bline, text='*c') var.pack(side=tk.LEFT) # ---Line B2--- bline = tk.Frame(box) bline.pack(side=tk.TOP, expand=tk.TRUE, pady=5) var = tk.Label(bline, text='b\' =') var.pack(side=tk.LEFT) var = tk.Entry(bline, textvariable=self.b1, font=TF, width=3, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_updatecell) var.bind('<KP_Enter>', self.fun_updatecell) var = tk.Label(bline, text='*a + ') var.pack(side=tk.LEFT) var = tk.Entry(bline, textvariable=self.b2, font=TF, width=3, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_updatecell) var.bind('<KP_Enter>', self.fun_updatecell) var = tk.Label(bline, text='*b + ') var.pack(side=tk.LEFT) var = tk.Entry(bline, textvariable=self.b3, font=TF, width=3, bg=ety, fg=ety_txt) var.pack(side=tk.LEFT) var.bind('<Return>', self.fun_updatecell) var.bind('<KP_Enter>', self.fun_updatecell) var
#!/usr/bin/env python # coding=utf-8 from distutils.spawn import find_executable from kvirt.config import Kconfig from kvirt.baseconfig import Kbaseconfig from kvirt.containerconfig import Kcontainerconfig from kvirt.config import __version__ from kvirt.defaults import TEMPLATES from prettytable import PrettyTable import argparse from kvirt import common from kvirt import nameutils import os import random import sys import yaml def start(args): """Start vm/container""" container = args.container config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) names = [common.get_lastvm(config.client)] if not args.names else args.names k = config.k if container: cont = Kcontainerconfig(config, client=args.containerclient).cont for name in names: common.pprint("Starting container %s..." % name, color='green') cont.start_container(name) else: codes = [] for name in names: common.pprint("Starting vm %s..." % name, color='green') result = k.start(name) code = common.handle_response(result, name, element='', action='started') codes.append(code) os._exit(1 if 1 in codes else 0) def stop(args): """Stop vm/container""" container = args.container config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) names = [common.get_lastvm(config.client)] if not args.names else args.names if config.extraclients: ks = config.extraclients ks.update({config.client: config.k}) else: ks = {config.client: config.k} codes = [] for cli in ks: k = ks[cli] if container: cont = Kcontainerconfig(config, client=args.containerclient).cont for name in names: common.pprint("Stopping container %s in %s..." % (name, cli), color='green') cont.stop_container(name) else: for name in names: common.pprint("Stopping vm %s in %s..." % (name, cli), color='green') result = k.stop(name) code = common.handle_response(result, name, element='', action='stopped') codes.append(code) os._exit(1 if 1 in codes else 0) def restart(args): """Restart vm/container""" container = args.container config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) names = [common.get_lastvm(config.client)] if not args.names else args.names k = config.k if container: cont = Kcontainerconfig(config, client=args.containerclient).cont for name in names: common.pprint("Restarting container %s..." % name, color='green') cont.stop_container(name) cont.start_container(name) else: codes = [] for name in names: common.pprint("Restarting vm %s..." % name, color='green') result = k.restart(name) code = common.handle_response(result, name, element='', action='restarted') codes.append(code) os._exit(1 if 1 in codes else 0) def console(args): """Vnc/Spice/Serial/Container console""" serial = args.serial container = args.container config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) name = common.get_lastvm(config.client) if not args.name else args.name k = config.k tunnel = config.tunnel if container: cont = Kcontainerconfig(config, client=args.containerclient).cont cont.console_container(name) return elif serial: k.serialconsole(name) else: k.console(name=name, tunnel=tunnel) def delete(args): """Delete vm/container""" container = args.container template = args.template snapshots = args.snapshots yes = args.yes config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) if config.extraclients: allclients = config.extraclients.copy() allclients.update({config.client: config.k}) names = args.names if not names: common.pprint("Can't delete vms on multiple hosts without specifying their names", color='red') os._exit(1) else: allclients = {config.client: config.k} names = [common.get_lastvm(config.client)] if not args.names else args.names for cli in sorted(allclients): k = allclients[cli] common.pprint("Deleting on %s" % cli, color='green') if not yes: common.confirm("Are you sure?") if container: codes = [0] cont = Kcontainerconfig(config, client=args.containerclient).cont for name in names: common.pprint("Deleting container %s" % name, color='green') cont.delete_container(name) elif template: # k = config.k codes = [] for name in names: # shortname = os.path.basename(url) # template = os.path.basename(template) result = k.delete_image(name) if result['result'] == 'success': common.pprint("%s deleted" % name, color='green') codes.append(0) else: reason = result['reason'] common.pprint("Could not delete %s because %s" % (name, reason), color='red') codes.append(1) else: codes = [] for name in names: dnsclient, domain = k.dnsinfo(name) result = k.delete(name, snapshots=snapshots) if result['result'] == 'success': common.pprint("%s deleted" % name, color='green') codes.append(0) common.set_lastvm(name, cli, delete=True) else: reason = result['reason'] common.pprint("Could not delete %s because %s" % (name, reason), color='red') codes.append(1) if dnsclient is not None and domain is not None: z = Kconfig(client=dnsclient).k z.delete_dns(name, domain) os._exit(1 if 1 in codes else 0) def download(args): """Download Template""" pool = args.pool templates = args.templates cmd = args.cmd url = args.url config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) result = config.handle_host(pool=pool, templates=templates, download=True, cmd=cmd, url=url) if result['result'] == 'success': os._exit(0) else: os._exit(1) def info(args): """Get info on vm""" output = args.output fields = args.fields.split(',') if args.fields is not None else [] values = args.values config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) names = [common.get_lastvm(config.client)] if not args.names else args.names k = config.k for name in names: data = k.info(name) if data: print(common.print_info(data, output=output, fields=fields, values=values, pretty=True)) def host(args): """Handle host""" enable = args.enable disable = args.disable sync = args.sync if enable: baseconfig = Kbaseconfig(client=args.client, debug=args.debug) result = baseconfig.enable_host(enable) elif disable: baseconfig = Kbaseconfig(client=args.client, debug=args.debug) result = baseconfig.disable_host(disable) else: config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) result = config.handle_host(sync=sync) if result['result'] == 'success': os._exit(0) else: os._exit(1) def _list(args): """List hosts, profiles, flavors, templates, isos, pools or vms""" clients = args.clients profiles = args.profiles flavors = args.flavors templates = args.templates isos = args.isos disks = args.disks pools = args.pools repos = args.repos products = args.products networks = args.networks subnets = args.subnets loadbalancers = args.loadbalancers containers = args.containers images = args.images plans = args.plans filters = args.filters short = args.short group = args.group repo = args.repo if clients: clientstable = PrettyTable(["Client", "Type", "Enabled", "Current"]) clientstable.align["Client"] = "l" baseconfig = Kbaseconfig(client=args.client, debug=args.debug) for client in sorted(baseconfig.clients): enabled = baseconfig.ini[client].get('enabled', True) _type = baseconfig.ini[client].get('type', 'kvm') if client == baseconfig.client: clientstable.add_row([client, _type, enabled, 'X']) else: clientstable.add_row([client, _type, enabled, '']) print(clientstable) return if repos: baseconfig = Kbaseconfig(client=args.client, debug=args.debug) repos = PrettyTable(["Repo", "Url"]) repos.align["Repo"] = "l" reposinfo = baseconfig.list_repos() for repo in sorted(reposinfo): url = reposinfo[repo] repos.add_row([repo, url]) print(repos) return elif products: baseconfig = Kbaseconfig(client=args.client, debug=args.debug) products = PrettyTable(["Repo", "Group", "Product", "Description", "Numvms", "Memory"]) products.align["Repo"] = "l" productsinfo = baseconfig.list_products(group=group, repo=repo) for product in sorted(productsinfo, key=lambda x: (x['repo'], x['group'], x['name'])): name = product['name'] repo = product['repo'] description = product.get('description', 'N/A') numvms = product.get('numvms', 'N/A') memory = product.get('memory', 'N/A') group = product.get('group', 'N/A') products.add_row([repo, group, name, description, numvms, memory]) print(products) return config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace) if config.client != 'all': k = config.k if pools: pools = k.list_pools() if short: poolstable = PrettyTable(["Pool"]) for pool in sorted(pools): poolstable.add_row([pool]) else: poolstable = PrettyTable(["Pool", "Path"]) for pool in sorted(pools): poolpath = k.get_pool_path(pool) poolstable.add_row([pool, poolpath]) poolstable.align["Pool"] = "l" print(poolstable) return if networks: networks = k.list_networks() common.pprint("Listing Networks...", color='green') if short: networkstable = PrettyTable(["Network"]) for network in sorted(networks): networkstable.add_row([network]) else: networkstable = PrettyTable(["Network", "Type", "Cidr", "Dhcp", "Domain", "Mode"]) for network in sorted(networks): networktype = networks[network]['type'] cidr = networks[network]['cidr'] dhcp = networks[network]['dhcp'] mode = networks[network]['mode'] if 'domain' in networks[network]: domain = networks[network]['domain'] else: domain = 'N/A' networkstable.add_row([network, networktype, cidr, dhcp, domain, mode]) networkstable.align["Network"] = "l" print(networkstable) return if subnets: subnets = k.list_subnets() common.pprint("Listing Subnets...", color='green') if short: subnetstable = PrettyTable(["Subnets"]) for subnet in sorted(subnets): subnetstable.add_row([subnet]) else: subnetstable = PrettyTable(["Subnet", "Az", "Cidr", "Network"]) for subnet in sorted(subnets): cidr = subnets[subnet]['cidr'] az = subnets[subnet]['az'] if 'network' in subnets[subnet]: network = subnets[subnet]['network'] else: network = 'N/A' subnetstable.add_row([subnet, az, cidr, network]) subnetstable.align["Network"] = "l" print(subnetstable) return elif profiles: if containers: profiles = config.list_containerprofiles() if short: profilestable = PrettyTable(["Profile"]) for profile in sorted(profiles): profilename = profile[0] profilestable.add_row([profilename]) else: profilestable = PrettyTable(["Profile", "Image", "Nets", "Ports", "Volumes", "Cmd"]) for profile in sorted(profiles): profilestable.add_row(profile) profilestable.align["Profile"] = "l" print(profilestable) else: profiles = config.list_profiles() if short: profilestable = PrettyTable(["Profile"]) for profile in sorted(profiles): profilename = profile[0] profilestable.add_row([profilename]) else: profilestable = PrettyTable(["Profile", "Flavor", "Pool", "Disks", "Template", "Nets", "Cloudinit", "Nested", "Reservedns", "Reservehost"]) for profile in sorted(profiles): profilestable.add_row(profile) profilestable.align["Profile"] = "l" print(profilestable) return elif flavors: flavors = k.flavors() if short: flavorstable = PrettyTable(["Flavor"]) for flavor in sorted(flavors): flavorname = profile[0] flavorstable.add_row([flavorname]) else: flavorstable = PrettyTable(["Flavor", "Numcpus", "Memory"]) for flavor in sorted(flavors): flavorstable.add_row(flavor) flavorstable.align["Flavor"] = "l" print(flavorstable) return elif loadbalancers: loadbalancers = config.list_loadbalancer() if short: loadbalancerstable = PrettyTable(["Loadbalancer"]) for lb in sorted(loadbalancers): flavorstable.add_row([lb]) else: loadbalancerstable = PrettyTable(["LoadBalancer", "IPAddress", "IPProtocol", "Ports", "Target"]) for lb in sorted(loadbalancers): loadbalancerstable.add_row(lb) loadbalancerstable.align["Loadbalancer"] = "l" print(loadbalancerstable) return elif templates: templatestable = PrettyTable(["Template"]) templatestable.align["Template"] = "l" for template in k.volumes(): templatestable.add_row([template]) print(templatestable) elif isos: isostable = PrettyTable(["Iso"]) isostable.align["Iso"] = "l" for iso in k.volumes(iso=True): isostable.add_row([iso]) print(isostable) elif disks: common.pprint("Listing disks...", color='green') diskstable = PrettyTable(["Name", "Pool", "Path"]) diskstable.align["Name"] = "l" disks = k.list_disks() for disk in sorted(disks): path = disks[disk]['path'] pool = disks[disk]['pool'] diskstable.add_row([disk, pool, path]) print(diskstable) elif containers: cont = Kcontainerconfig(config, client=args.containerclient).cont common.pprint("Listing containers...", color='green') containers = PrettyTable(["Name", "Status", "Image", "Plan", "Command", "Ports", "Deploy"]) for container in cont.list_containers(): if filters: status = container[1] if status == filters: containers.add_row(container) else: containers.add_row(container) print(containers) elif images: cont = Kcontainerconfig(config, client=args.containerclient).cont common.pprint("Listing images...", color='green')
# -*- coding: utf-8 -*- """ This tutorial will introduce the basic concepts and workflow of mpcpy. By the end, we will train a simple model based on emulated data, and use the model to optimize the control signal of the system. All required data files for this tutorial are located in doc/userGuide/tutorial. The model is a simple RC model of zone thermal response to ambient temperature and a singal heat input. It is written in Modelica: .. code-block:: modelica model RC "A simple RC network for example purposes" Modelica.Blocks.Interfaces.RealInput weaTDryBul(unit="K") "Ambient temperature"; Modelica.Blocks.Interfaces.RealInput Qflow(unit="W") "Heat input"; Modelica.Blocks.Interfaces.RealOutput Tzone(unit="K") "Zone temperature"; Modelica.Thermal.HeatTransfer.Components.HeatCapacitor heatCapacitor(C=1e5) "Thermal capacitance of zone"; Modelica.Thermal.HeatTransfer.Components.ThermalResistor thermalResistor(R=0.01) "Thermal resistance of zone"; Modelica.Thermal.HeatTransfer.Sources.PrescribedTemperature preTemp; Modelica.Thermal.HeatTransfer.Sensors.TemperatureSensor senTemp; Modelica.Thermal.HeatTransfer.Sources.PrescribedHeatFlow preHeat; equation connect(senTemp.T, Tzone) connect(preHeat.Q_flow, Qflow) connect(heatCapacitor.port, senTemp.port) connect(heatCapacitor.port, preHeat.port) connect(preTemp.port, thermalResistor.port_a) connect(thermalResistor.port_b, heatCapacitor.port) connect(preTemp.T, weaTDryBul) end RC; Variables and Units ------------------- First, lets get familiar with variables and units, the basic building blocks of MPCPy. >>> from mpcpy import variables >>> from mpcpy import units Static variables contain data that is not a timeseries: >>> setpoint = variables.Static('setpoint', 20, units.degC) >>> print(setpoint) # doctest: +NORMALIZE_WHITESPACE Name: setpoint Variability: Static Quantity: Temperature Display Unit: degC The unit assigned to the variable is the display unit. However, each display unit quantity has a base unit that is used to store the data in memory. This makes it easy to convert between units when necessary. For example, the degC display unit has a quantity temperature, which has base unit in Kelvin. >>> # Get the data in display units >>> setpoint.display_data() 20.0 >>> # Get the data in base units >>> setpoint.get_base_data() 293.15 >>> # Convert the display unit to degF >>> setpoint.set_display_unit(units.degF) >>> setpoint.display_data() # doctest: +NORMALIZE_WHITESPACE 68.0 Timeseries variables contain data in the form of a ``pandas`` Series with a datetime index: >>> # Create pandas Series object >>> import pandas as pd >>> data = [0, 5, 10, 15, 20] >>> index = pd.date_range(start='1/1/2017', periods=len(data), freq='H') >>> ts = pd.Series(data=data, index=index, name='power_data') Now we can do the same thing with the timeseries variable as we did with the static variable: >>> # Create mpcpy variable >>> power_data = variables.Timeseries('power_data', ts, units.Btuh) >>> print(power_data) # doctest: +NORMALIZE_WHITESPACE Name: power_data Variability: Timeseries Quantity: Power Display Unit: Btuh >>> # Get the data in display units >>> power_data.display_data() 2017-01-01 00:00:00+00:00 0.0 2017-01-01 01:00:00+00:00 5.0 2017-01-01 02:00:00+00:00 10.0 2017-01-01 03:00:00+00:00 15.0 2017-01-01 04:00:00+00:00 20.0 Freq: H, Name: power_data, dtype: float64 >>> # Get the data in base units >>> power_data.get_base_data() 2017-01-01 00:00:00+00:00 0.000000 2017-01-01 01:00:00+00:00 1.465355 2017-01-01 02:00:00+00:00 2.930711 2017-01-01 03:00:00+00:00 4.396066 2017-01-01 04:00:00+00:00 5.861421 Freq: H, Name: power_data, dtype: float64 >>> # Convert the display unit to kW >>> power_data.set_display_unit(units.kW) >>> power_data.display_data() 2017-01-01 00:00:00+00:00 0.000000 2017-01-01 01:00:00+00:00 0.001465 2017-01-01 02:00:00+00:00 0.002931 2017-01-01 03:00:00+00:00 0.004396 2017-01-01 04:00:00+00:00 0.005861 Freq: H, Name: power_data, dtype: float64 There is additional functionality with the units that may be useful, such as setting new data and getting the units. Consult the documentation on these classes for more information. Collect model weather and control signal data --------------------------------------------- Now, we would like to collect the weather data and control signal inputs for our model. We do this using exodata objects: >>> from mpcpy import exodata Let's take our weather data from an EPW file. We instantiate the weather exodata object by supplying the path to the EPW file: >>> weather = exodata.WeatherFromEPW('USA_IL_Chicago-OHare.Intl.AP.725300_TMY3.epw') Note that using the weather exodata object assumes that weather inputs to our model are named a certain way. Consult the documentation on the weather exodata class for more information. In this case, the ambient dry bulb temperature input in our model is named weaTDryBul. Let's take our control input signal from a CSV file. The CSV file looks like: :: Time,Qflow_csv 01/01/17 12:00 AM,3000 01/01/17 01:00 AM,3000 01/01/17 02:00 AM,3000 ... 01/02/17 10:00 PM,3000 01/02/17 11:00 PM,3000 01/03/17 12:00 AM,3000 We instantiate the control exodata object by supplying the path to the CSV file as well as a map of the names of the columns to the input of our model. We also assume that the data in the CSV file is given in the local time of the weather file, and so we supply this optional parameter, tz_name, upon instantiation as well. If no time zone is supplied, it is assumed to be UTC. >>> variable_map = {'Qflow_csv' : ('Qflow', units.W)} >>> control = exodata.ControlFromCSV('ControlSignal.csv', ... variable_map, ... tz_name = weather.tz_name) Now we are ready to collect the exogenous data from our data sources for a given time period. >>> start_time = '1/1/2017' >>> final_time = '1/3/2017' >>> weather.collect_data(start_time, final_time) # doctest: +ELLIPSIS -etc- >>> control.collect_data(start_time, final_time) Use the ``display_data()`` and ``get_base_data()`` functions for the weather and control objects to get the data in the form of a pandas dataframe. Note that the data is given in UTC time. >>> control.display_data() # doctest: +ELLIPSIS Qflow Time 2017-01-01 06:00:00+00:00 3000.0 2017-01-01 07:00:00+00:00 3000.0 2017-01-01 08:00:00+00:00 3000.0 -etc- Simulate as Emulated System --------------------------- The model has parameters for the resistance and capacitance set in the modelica code. For the purposes of this tutorial, we will assume that the model with these parameter values represents the actual system. We now wish to collect measurements from this 'actual system.' For this, we use the systems module of mpcpy. >>> from mpcpy import systems First, we instantiate our system model by supplying a measurement dictionary, information about where the model resides, and information about model exodata. The measurement dictionary holds information about and data from the variables being measured. We start with defining the variables we are interested in measuring and their sample rate. In this case, we have two, the output of the model, called 'Tzone' and the control input called 'Qflow'. Note that 'heatCapacitor.T' would also be valid instead of 'Tzone'. >>> measurements = {'Tzone' : {}, 'Qflow' : {}} >>> measurements['Tzone']['Sample'] = variables.Static('sample_rate_Tzone', ... 3600, ... units.s) >>> measurements['Qflow']['Sample'] = variables.Static('sample_rate_Qflow', ... 3600, ... units.s) The model information is given by a tuple containing the path to the Modelica (.mo) file, the path of the model within the .mo file, and a list of paths of any required libraries other than the Modelica Standard. For this example, there are no additional libraries. >>> moinfo = ('Tutorial.mo', 'Tutorial.RC', {}) Ultimately, the modelica model is compiled into an FMU. If the emulation model is already an FMU, than an fmupath can be specified instead of the modelica information tuple. For more information, see the documentation on the systmems class. We can now instantiate the system emulation object with our measurement dictionary, model information, collected exogenous data, and time zone: >>> emulation = systems.EmulationFromFMU(measurements, ... moinfo = moinfo, ... weather_data = weather.data, ... control_data = control.data, ... tz_name = weather.tz_name) Finally, we can collect the measurements from our emulation over a specified time period and display the results as a pandas dataframe. The ``collect_measurements()`` function updates the measurement dictionary with timeseries data in the ``'Measured'`` field for each variable. >>> # Collect the data >>> emulation.collect_measurements('1/1/2017', '1/2/2017') # doctest: +ELLIPSIS -etc- >>> # Display the results >>> emulation.display_measurements('Measured').applymap('{:.2f}'.format) # doctest: +ELLIPSIS Qflow Tzone Time 2017-01-01 06:00:00+00:00 3000.00 293.15 2017-01-01 07:00:00+00:00 3000.00 291.01 2017-01-01 08:00:00+00:00 3000.00 291.32 -etc- Estimate Parameters ------------------- Now assume that we do not know the parameters of the model. Or, that we have measurements from a real or emulated system, and would like to estimate parameters of our model to fit the measurements. For this, we use the models module from mpcpy. >>> from mpcpy import models In this case, we have a Modelica model with two parameters that we would like to train based on the measured data from our system; the resistance and capacitance. We first need to collect some information about our parameters and do so using a parameters exodata object. The parameter information is stored in a CSV file that looks like: :: Name,Free,Value,Minimum,Maximum,Covariance,Unit heatCapacitor.C,True,40000,1.00E+04,1.00E+06,1000,J/K thermalResistor.R,True,0.002,0.001,0.1,0.0001,K/W The name is the name of the parameter in the model. The Free field indicates if the parameter is free to be changed during the estimation method or not. The Value is the current value of the parameter. If the parameter is to be estimated, this would be an initial guess. If the parameter's Free field is set to False, then the value is set to the parameter upon simulation. The Minimum and Maximum fields set the minimum and maximum value allowed by the parameter during estimation. The Covariance field sets the covariance of the parameter, and is only used for unscented kalman filtering. Finally, the Unit field specifies the unit of the parameter using the name string of MPCPy unit classes. >>> parameters = exodata.ParameterFromCSV('Parameters.csv') >>> parameters.collect_data() >>> parameters.display_data()
<filename>bayes_opt/sequentialBO/bayesian_optimization.py # -*- coding: utf-8 -*- """ Created on Tue Mar 29 11:49:58 2016 """ import numpy as np #from sklearn.gaussian_process import GaussianProcess from bayes_opt.sequentialBO.bayesian_optimization_base import BO_Sequential_Base from scipy.optimize import minimize from bayes_opt.acquisition_functions import AcquisitionFunction, unique_rows from bayes_opt.gaussian_process import GaussianProcess from bayes_opt.acquisition_maximization import acq_max,acq_max_with_name import time #import nlopt #@author: Vu #====================================================================================================== #====================================================================================================== #====================================================================================================== #====================================================================================================== counter = 0 class BayesOpt(BO_Sequential_Base): def __init__(self, gp_params, func_params, acq_params, verbose=1): """ Input parameters ---------- gp_params: GP parameters gp_params.theta: to compute the kernel gp_params.delta: to compute the kernel func_params: function to optimize func_params.init bound: initial bounds for parameters func_params.bounds: bounds on parameters func_params.func: a function to be optimized acq_params: acquisition function, acq_params.acq_func['name']=['ei','ucb','poi','lei'] ,acq['kappa'] for ucb, acq['k'] for lei acq_params.opt_toolbox: optimization toolbox 'nlopt','direct','scipy' Returns ------- dim: dimension bounds: bounds on original scale scalebounds: bounds on normalized scale of 0-1 time_opt: will record the time spent on optimization gp: Gaussian Process object """ # Find number of parameters super(BayesOpt, self).__init__(gp_params, func_params, acq_params, verbose) """ bounds=func_params['function'].bounds self.dim = len(bounds) # Create an array with parameters bounds if isinstance(bounds,dict): # Get the name of the parameters self.keys = list(bounds.keys()) self.bounds = [] for key in list(bounds.keys()): self.bounds.append(bounds[key]) self.bounds = np.asarray(self.bounds) else: self.bounds=np.asarray(bounds) #print(self.bounds) # create a scalebounds 0-1 scalebounds=np.array([np.zeros(self.dim), np.ones(self.dim)]) self.scalebounds=scalebounds.T self.max_min_gap=self.bounds[:,1]-self.bounds[:,0] # Some function to be optimized self.f = func_params['function'].func # optimization toolbox if 'opt_toolbox' not in acq_params: self.opt_toolbox='scipy' else: self.opt_toolbox=acq_params['opt_toolbox'] # acquisition function type self.acq=acq_params['acq_func'] self.acq['scalebounds']=self.scalebounds if 'debug' not in self.acq: self.acq['debug']=0 if 'stopping' not in acq_params: self.stopping_criteria=0 else: self.stopping_criteria=acq_params['stopping'] if 'optimize_gp' not in acq_params: self.optimize_gp=0 else: self.optimize_gp=acq_params['optimize_gp'] if 'marginalize_gp' not in acq_params: self.marginalize_gp=0 else: self.marginalize_gp=acq_params['marginalize_gp'] # store X in original scale self.X_original= None # store X in 0-1 scale self.X = None # store y=f(x) # (y - mean)/(max-min) self.Y = None # y original scale self.Y_original = None # performance evaluation at the maximum mean GP (for information theoretic) self.Y_original_maxGP = None self.X_original_maxGP = None # value of the acquisition function at the selected point self.alpha_Xt=None self.Tau_Xt=None self.time_opt=0 self.k_Neighbor=2 # Lipschitz constant self.L=0 self.gp_params=gp_params # Gaussian Process class self.gp=GaussianProcess(gp_params) # acquisition function self.acq_func = None # stop condition self.stop_flag=0 self.logmarginal=0 # xt_suggestion, caching for Consensus self.xstars=[] self.xstar_accumulate=[] # theta vector for marginalization GP self.theta_vector =[] # PVRS before and after self.PVRS_before_after=[] self.accummulate_PVRS_before_after=[] # store ystars #self.ystars=np.empty((0,100), float) self.ystars=[] """ # will be later used for visualization def posterior(self, Xnew): self.gp.fit(self.X, self.Y) mu, sigma2 = self.gp.predict(Xnew, eval_MSE=True) return mu, np.sqrt(sigma2) def init(self, gp_params, n_init_points=3,seed=1): """ Input parameters ---------- gp_params: Gaussian Process structure n_init_points: # init points """ super(BayesOpt, self).init(gp_params, n_init_points,seed) def init_with_data(self, init_X,init_Y): """ Input parameters ---------- gp_params: Gaussian Process structure x,y: # init data observations (in original scale) """ super(BayesOpt, self).init_with_data(init_X,init_Y) def estimate_L(self,bounds): ''' Estimate the Lipschitz constant of f by taking maximizing the norm of the expectation of the gradient of *f*. ''' def df(x,model,x0): mean_derivative=gp_model.predictive_gradient(self.X,self.Y,x) temp=mean_derivative*mean_derivative if len(temp.shape)<=1: res = np.sqrt( temp) else: res = np.sqrt(np.sum(temp,axis=1)) # simply take the norm of the expectation of the gradient return -res gp_model=self.gp dim = len(bounds) num_data=1000*dim samples = np.zeros(shape=(num_data,dim)) for k in range(0,dim): samples[:,k] = np.random.uniform(low=bounds[k][0],high=bounds[k][1],size=num_data) #samples = np.vstack([samples,gp_model.X]) pred_samples = df(samples,gp_model,0) x0 = samples[np.argmin(pred_samples)] res = minimize(df,x0, method='L-BFGS-B',bounds=bounds, args = (gp_model,x0), options = {'maxiter': 100}) try: minusL = res.fun[0][0] except: if len(res.fun.shape)==1: minusL = res.fun[0] else: minusL = res.fun L=-minusL if L<1e-6: L=0.0001 ## to avoid problems in cases in which the model is flat. return L def maximize_with_lengthscale_derived_by_fstar(self,gp_params): """ Main optimization method. Input parameters ---------- gp_params: parameter for Gaussian Process Returns ------- x: recommented point for evaluation """ if self.stop_flag==1: return if self.acq['name']=='random': x_max = [np.random.uniform(x[0], x[1], size=1) for x in self.bounds] x_max=np.asarray(x_max) x_max=x_max.T self.X_original=np.vstack((self.X_original, x_max)) # evaluate Y using original X #self.Y = np.append(self.Y, self.f(temp_X_new_original)) self.Y_original = np.append(self.Y_original, self.f(x_max)) # update Y after change Y_original self.Y=(self.Y_original-np.mean(self.Y_original))/np.std(self.Y_original) self.time_opt=np.hstack((self.time_opt,0)) return # init a new Gaussian Process self.gp=GaussianProcess(gp_params) if self.gp.KK_x_x_inv ==[]: # Find unique rows of X to avoid GP from breaking ur = unique_rows(self.X) self.gp.fit(self.X[ur], self.Y[ur]) acq=self.acq # optimize GP parameters after 10 iterations if len(self.Y)%(3*self.dim)==0: fstar_scaled=(self.acq['fstar']-np.mean(self.Y_original))/np.std(self.Y_original) newlengthscale = self.gp.optimize_lengthscale_SE_fstar(self.gp_params['lengthscale'],self.gp_params['noise_delta'],fstar_scaled) self.gp_params['lengthscale']=newlengthscale print("estimated lengthscale =",newlengthscale) # init a new Gaussian Process after optimizing hyper-parameter self.gp=GaussianProcess(gp_params) # Find unique rows of X to avoid GP from breaking ur = unique_rows(self.X) self.gp.fit(self.X[ur], self.Y[ur]) if self.acq['name']=='mes': self.maximize_mes(gp_params) return if self.acq['name']=='pvrs': self.maximize_pvrs(gp_params) return if self.acq['name']=='e3i': self.maximize_e3i(gp_params) return if self.acq['name']=='ei_kov' or self.acq['name']=='poi_kov' or self.acq['name']=='ei_fstar': self.acq['fstar_scaled']=(self.acq['fstar']-np.mean(self.Y_original))/np.std(self.Y_original) # Set acquisition function start_opt=time.time() y_max = self.Y.max() if 'xstars' not in globals(): xstars=[] self.xstars=xstars self.acq['xstars']=xstars self.acq_func = AcquisitionFunction(self.acq) if acq['name']=="ei_mu": #find the maximum in the predictive mean x_mu_max,y_max=acq_max_with_name(gp=self.gp,scalebounds=self.scalebounds,acq_name='mu',IsReturnY=True) x_max = acq_max(ac=self.acq_func.acq_kind,gp=self.gp,bounds=self.scalebounds,opt_toolbox=self.opt_toolbox,seeds=self.xstars) val_acq=self.acq_func.acq_kind(x_max,self.gp) if self.stopping_criteria!=0 and val_acq<self.stopping_criteria: val_acq=self.acq_func.acq_kind(x_max,self.gp) self.stop_flag=1 #print "Stopping Criteria is violated. Stopping Criteria is {:.15f}".format(self.stopping_criteria) self.alpha_Xt= np.append(self.alpha_Xt,val_acq) mean,var=self.gp.predict(x_max, eval_MSE=True) var.flags['WRITEABLE']=True var[var<1e-20]=0 #self.Tau_Xt= np.append(self.Tau_Xt,val_acq/var) # record the optimization time finished_opt=time.time() elapse_opt=finished_opt-start_opt self.time_opt=np.hstack((self.time_opt,elapse_opt)) # store X self.X = np.vstack((self.X, x_max.reshape((1, -1)))) # compute X in original scale temp_X_new_original=x_max*self.max_min_gap+self.bounds[:,0] self.X_original=np.vstack((self.X_original, temp_X_new_original)) # evaluate Y using original X #self.Y = np.append(self.Y, self.f(temp_X_new_original)) self.Y_original = np.append(self.Y_original, self.f(temp_X_new_original)) # update Y after change Y_original self.Y=(self.Y_original-np.mean(self.Y_original))/np.std(self.Y_original) if self.gp.flagIncremental==1: self.gp.fit_incremental(x_max,self.Y[-1]) def maximize(self): """ Main optimization method. Input parameters ---------- gp_params: parameter for Gaussian Process Returns ------- x: recommented point for evaluation """ if self.stop_flag==1: return if self.acq['name']=='random': super(BayesOpt, self).generate_random_point() return # init a new Gaussian Process self.gp=GaussianProcess(self.gp_params) if self.gp.KK_x_x_inv ==[]: # Find unique rows of X to avoid GP from breaking ur = unique_rows(self.X) self.gp.fit(self.X[ur], self.Y[ur]) acq=self.acq # optimize GP parameters after 10 iterations if len(self.Y)%(2*self.dim)==0: self.gp,self.gp_params=super(BayesOpt, self).optimize_gp_hyperparameter() if self.acq['name']=='mes': self.maximize_mes() return if self.acq['name']=='pvrs': self.maximize_pvrs() return if self.acq['name']=='e3i': self.maximize_e3i() return if self.acq['name']=='ei_kov' or self.acq['name']=='poi_kov' or self.acq['name']=='ei_fstar': self.acq['fstar_scaled']=(self.acq['fstar']-np.mean(self.Y_original))/np.std(self.Y_original) # Set acquisition function start_opt=time.time() #y_max = self.Y.max() if 'xstars' not in globals(): xstars=[] self.xstars=xstars self.acq['xstars']=xstars self.acq_func = AcquisitionFunction(self.acq) if acq['name']=="ei_mu": #find the maximum in the predictive mean x_mu_max,y_max=acq_max_with_name(gp=self.gp,scalebounds=self.scalebounds,acq_name='mu',IsReturnY=True) x_max = acq_max(ac=self.acq_func.acq_kind,gp=self.gp,bounds=self.scalebounds,opt_toolbox=self.opt_toolbox,seeds=self.xstars) val_acq=self.acq_func.acq_kind(x_max,self.gp) if self.stopping_criteria!=0 and val_acq<self.stopping_criteria: #val_acq=self.acq_func.acq_kind(x_max,self.gp) self.stop_flag=1 #print "Stopping Criteria is violated. Stopping Criteria is {:.15f}".format(self.stopping_criteria) self.alpha_Xt= np.append(self.alpha_Xt,val_acq) mean,var=self.gp.predict(x_max, eval_MSE=True) var.flags['WRITEABLE']=True var[var<1e-20]=0 #self.Tau_Xt= np.append(self.Tau_Xt,val_acq/var) # record the optimization time finished_opt=time.time() elapse_opt=finished_opt-start_opt self.time_opt=np.hstack((self.time_opt,elapse_opt)) super(BayesOpt, self).augment_the_new_data(x_max) def maximize_mes(self): """ Main optimization method. Input parameters ---------- gp_params: parameter for Gaussian Process Returns ------- x: recommented point for evaluation """ if self.stop_flag==1: return # Set acquisition function start_opt=time.time() y_max = self.Y.max() # run the acquisition function for the first time to get xstar self.xstars=[] # finding the xt of UCB y_max=np.max(self.Y) #numXtar=10*self.dim numXtar=30 y_stars=[] temp=[] # finding the xt of Thompson Sampling for ii in range(numXtar): xt_TS,y_xt_TS=acq_max_with_name(gp=self.gp,scalebounds=self.scalebounds, acq_name="thompson",IsReturnY=True) #if y_xt_TS>=y_max: y_stars.append(y_xt_TS) temp.append(xt_TS) # check if f* > y^max and ignore xt_TS otherwise if y_xt_TS>=y_max: self.xstars.append(xt_TS) if self.xstars==[]: #print 'xt_suggestion is empty' # again perform TS and take all of them self.xstars=temp self.acq['xstars']=self.xstars self.acq['ystars']=y_stars self.acq_func = AcquisitionFunction(self.acq) x_max = acq_max(ac=self.acq_func.acq_kind,gp=self.gp,bounds=self.scalebounds,opt_toolbox=self.opt_toolbox,seeds=self.xstars) #xstars_array=np.asarray(self.acq_func.object.xstars) val_acq=self.acq_func.acq_kind(x_max,self.gp) if self.stopping_criteria!=0 and val_acq<self.stopping_criteria: val_acq=self.acq_func.acq_kind(x_max,self.gp) self.stop_flag=1 print("Stopping Criteria is violated. Stopping Criteria is {:.15f}".format(self.stopping_criteria)) # record the optimization time finished_opt=time.time() elapse_opt=finished_opt-start_opt self.time_opt=np.hstack((self.time_opt,elapse_opt)) super(BayesOpt, self).augment_the_new_data(x_max) # convert ystar to original scale y_stars=[val*np.std(self.Y_original)+np.mean(self.Y_original) for idx,val in enumerate(y_stars)] self.ystars.append(np.ravel(y_stars)) def maximize_e3i(self): """ Main optimization method. Input parameters ---------- gp_params: parameter for Gaussian Process Returns ------- x: recommented point for evaluation """ if self.stop_flag==1: return # Set acquisition function start_opt=time.time() y_max = self.Y.max() # run the acquisition function for the first time to get xstar self.xstars=[] # finding the xt of UCB y_max=np.max(self.Y) numXtar=50*self.dim #numXtar=20 y_stars=[] temp=[] # finding the xt of Thompson Sampling for ii in
import re import sqlite3 import time ######################################################################### # Base class for generating a catebot response. This is intended to be a parent to classes that # implement each type of response with overrides specific to them. The classes that are expected to be # overridden are: # # getResponse(self, requests) # getContextLink(self, key, httpLocation) # getOverflowComment(self, keys) # linkCrossReferences(self, response) # parsedRequests(self, requests, includeRanges = True) # # The initializer is called with a dictionary, a base URL for links, and a Configuration object. # # NOTE: The base class is implemented with the methods that are expected to be overriden. In addition to serving # as an example of how the overrides should be written, they also implement the behavior expected when quoting # the CCC. # ######################################################################### class Response: # Set up the Catechism and initialize variables def __init__(self, dictionary, baseURL, configuration): self._dictionary = dictionary self._baseURL = baseURL self._configuration = configuration # Just returns the current character limit for the reddit comment. Makes it easy to find/change in the future. # NOTE: reddit's character limit is 10,000 characters by default. def getCharLimit(self): return 9500 # Simply returns the comment footer found at the bottom of every comment posted by the bot. def getCommentFooter(self): return ('\n***\nCatebot ' + self._configuration.version + ' links: [Source Code](https://github.com/konohitowa/catebot)' + ' | [Feedback](https://github.com/konohitowa/catebot/issues)' + ' | [Contact Dev](http://www.reddit.com/message/compose/?to=kono_hito_wa)' + ' | [FAQ](https://github.com/konohitowa/catebot/blob/master/docs/CateBot%20Info.md#faq)' + ' | [Changelog](https://github.com/konohitowa/catebot/blob/master/docs/CHANGELOG.md)') def getOverflowHeader(self, singular, plural, number): noun = singular if number > 1: noun = plural return 'The contents of the ' + noun + ' you quoted exceed the character limit ([' + str(self.getCharLimit()) + '](https://github.com/konohitowa/catebot/blob/master/docs/CateBot%20Info.md#wait-ive-counted-the-characters-and-i-didnt-hit-the-limit) characters). Instead, here are links to the ' + noun + '...\n\n' def parsedRequests(self, requests, includeRanges = True): validRequests = list() for request in requests: request = re.sub(r"\s+","",request) if ',' in request: sublist = request.split(',') else: sublist = [ request ] for subrequest in sublist: if '-' in subrequest: startingRequest = subrequest.partition('-')[0] if includeRanges: endingRequest = subrequest.partition('-')[2] if int(startingRequest) < int(endingRequest)+1: for key in range(int(startingRequest), int(endingRequest)+1): if str(key) in self._dictionary: validRequests.append(str(key)) else: validRequests.append(startingRequest) elif subrequest in self._dictionary: validRequests.append(subrequest) return validRequests # Constructs reddit comment response for Catechism requests. def getResponse(self, requests): validRequests = self.parsedRequests(requests) if len(validRequests) > 0: comment = '' for request in validRequests: content,location = self._dictionary[request] comment += ('[**CCC ' + request + '**](' + self.getContextLink(request, location) + ') ' + content) + '\n\n' comment = self.linkCrossReferences(comment) if len(comment) > self.getCharLimit(): comment = self.getOverflowComment(validRequests) comment += self.getCommentFooter() return True,comment else: return False,"" # Takes the request key and http location as parameters. The function then constructs # the appropriate context link. This link appears on each paragraph number. def getContextLink(self, request, location): return 'http://www.scborromeo.org/ccc/para/' + request + '.htm' # Constructs and returns an overflow comment whenever the comment exceeds the character limit set by # getCharLimit(). Instead of posting the contents of the request(s) in the comment, it links to webpages # that contain the contents of the request(s). def getOverflowComment(self, requests): numberOfRequests = 0 comment = '' for request in requests: content,location = self._dictionary[request] numberOfRequests += 1 comment += ('([' + request + '](' + self.getContextLink(request,location) + '))\n') if len(comment) > self.getCharLimit(): comment += "\n\nAnd even when condensing the paragraphs to links, you still exceeded the quota..." break return self.getOverflowHeader('paragraph','paragraphs',numberOfRequests) + comment def linkCrossReferences(self, comment): xrefBlocks = reversed(list(re.finditer(r'\([\d\,\s\-]+\)$(?m)',comment))) for xrefBlock in xrefBlocks: xrefs = reversed(list(re.finditer(r'\d+',xrefBlock.group(0)))) for xref in xrefs: paragraph = xref.group(0) content,location = self._dictionary[paragraph] start = xrefBlock.start()+xref.start() end = xrefBlock.start()+xref.end() comment = comment[:start]+"["+paragraph+"]("+self.getContextLink(paragraph, location)+")"+comment[end:] return comment ######################################################################### # # Constructs reddit comment response for Balitmore Catechism requests of # the form [bccd 1], [bccd 1-5], [bccd 1-5,9-10], and the same forms with # a BCCD book #, such as [bccd #1 1-5, 10-12]. The default book is #2. # ######################################################################### class BaltimoreResponse(Response): def parsedRequests(self, requests, includeRanges = True): validRequests = list() for taggedRequest in requests: bookNumber = '2' bookRequest, request = taggedRequest bookRequest = re.sub(r"\s+","",bookRequest) request = re.sub(r"\s+","",request) bookMatch = re.match(r'#(\d+)', bookRequest) if bookMatch: bookNumber = bookMatch.group(1) if int(bookNumber) < 1 or int(bookNumber) > 4: bookNumber = '2' if ',' in request: sublist = request.split(',') else: sublist = [ request ] for subrequest in sublist: if '-' in subrequest: startingRequest = subrequest.partition('-')[0] if includeRanges: endingRequest = subrequest.partition('-')[2] if int(startingRequest) < int(endingRequest)+1: for key in range(int(startingRequest), int(endingRequest)+1): if str(key) in self._dictionary[bookNumber]: validRequests.append({'Book': bookNumber, 'Request': str(key)}) elif startingRequest in self._dictionary[bookNumber]: validRequests.append({'Book': bookNumber, 'Request': startingRequest}) elif subrequest in self._dictionary[bookNumber]: validRequests.append({'Book': bookNumber, 'Request': subrequest}) return validRequests def getResponse(self, requests): validRequests = self.parsedRequests(requests) if len(validRequests) > 0: comment = '' for request in validRequests: bookNumber = request['Book'] requestNumber = request['Request'] qa = self._dictionary[bookNumber][requestNumber] comment += ('[**BCCD #' + bookNumber + " Q." + requestNumber + '**](' + self.getContextLink(bookNumber, requestNumber, qa['Q']) + ') ' + qa['Q'] + '\n\nA. ' + qa['A']) + '\n\n' comment = self.linkCrossReferences(comment) if len(comment) > self.getCharLimit(): comment = self.getOverflowComment(validRequests) comment += self.getCommentFooter() return True,comment else: return False,"" # This needs to be updated when an actual linkable source is available #q.2_who_is_god.3F #self._baseURL def getContextLink(self, bookNumber, questionNumber, questionText): modifiedQuestionText = re.sub(r'\s','_',questionText).lower() modifiedQuestionText = re.sub(r',','.2C',modifiedQuestionText) modifiedQuestionText = re.sub(r'\?','.3F',modifiedQuestionText) partitionText = "" if int(bookNumber) == 4: partitionText = "_" if int(questionNumber) < 211: partitionText += "1" else: partitionText += "2" return 'https://www.reddit.com/r/Catebot/wiki/bccd_' + bookNumber + partitionText + '#wiki_q.' + questionNumber + '_' + modifiedQuestionText def getOverflowComment(self, requests): numberOfRequests = 0 comment = '' for request in requests: numberOfRequests += 1 bookNumber = request['Book'] requestNumber = request['Request'] qa = self._dictionary[bookNumber][requestNumber] comment += ('([' + requestNumber + '](' + self.getContextLink(bookNumber, requestNumber, qa['Q']) + '))\n') if len(comment) > self.getCharLimit(): comment += "\n\nAnd even when condensing the requested questions to links, you still exceeded the quota..." break return self.getOverflowHeader('question','questions',numberOfRequests) + comment # This needs to be filled out for the {} references in #3 def linkCrossReferences(self,comment): return comment xrefBlocks = reversed(list(re.finditer(r'cann*\.\s+\d+$(?m)',comment))) for xrefBlock in xrefBlocks: xrefs = reversed(list(re.finditer(r'\d+',xrefBlock.group(0)))) for xref in xrefs: paragraph = xref.group(0) content,location = self._Catechism[paragraph] contextLink = self.__getCanonContextLink(paragraph, location) start = xrefBlock.start()+xref.start() end = xrefBlock.start()+xref.end() comment = comment[:start]+"["+paragraph+"]("+contextLink+")"+comment[end:] return comment ######################################################################### # # Constructs reddit comment response for Canon requests of form [can 12], # [can 12s1], [can 12-14], [can 12,15-17]. # ######################################################################### class CanonResponse(Response): def parsedRequests(self, requests, includeRanges = True): validRequests = list() for request in requests: request = re.sub(r"\s+","",request) if ',' in request: sublist = request.split(',') else: sublist = [ request ] for subrequest in sublist: if '-' in subrequest: startingRequest = subrequest.partition('-')[0].partition('s')[0] if includeRanges: endingRequest = subrequest.partition('-')[2].partition('s')[0] if int(startingRequest) < int(endingRequest)+1: for key in range(int(startingRequest), int(endingRequest)+1): if str(key) in self._dictionary: validRequests.append(str(key)) elif startingRequest in self._dictionary: validRequests.append(startingRequest) else: key = subrequest.partition('s')[0] if key in self._dictionary: validRequests.append(subrequest) return validRequests def getResponse(self, requests): validRequests = self.parsedRequests(requests) if len(validRequests) > 0: comment = '' for request in validRequests: key = request.partition('s')[0] section = request.partition('s')[2] isSectioned,content,location = self._dictionary[key] contextLink = self.getContextLink("", location) if section and isSectioned: try: comment += ('[**Can. ' + key + '**](' + contextLink + ') ' + u"\u00A7" + section + " " + content[section]) + '\n\n' except KeyError: comment += '[**Can. ' + key + '**](' + contextLink + ') ' + u"\u00A7" + section + " doesn't exist\n\n" elif not section and isSectioned: comment += '[**Can. ' + key + '**](' + contextLink + ') ' for sect in sorted(content.keys(),key=int): comment += u"\u00A7"+sect+" "+content[sect]+"\n\n" else: comment += '[**Can. ' + key + '**](' + contextLink + ') ' + content comment = self.linkCrossReferences(comment) if len(comment) > self.getCharLimit(): comment = self.getOverflowComment(validRequests) comment += self.getCommentFooter() return True,comment else: return False,"" def getContextLink(self, dummy, location): return self._baseURL + location def getOverflowComment(self, requests): numberOfRequests = 0 comment = '' for request in requests: isSectioned,content,location = self._dictionary[request] numberOfRequests += 1 comment += ('([' + request + '](' + self.getContextLink("",location) + '))\n') if len(comment) > self.getCharLimit(): comment += "\n\nAnd even when condensing the laws to links, you still exceeded the quota..." break return self.getOverflowHeader('law','laws',numberOfRequests) + comment # HERE def linkCrossReferences(self,comment): return comment xrefBlocks = reversed(list(re.finditer(r'cann*\.\s+\d+$(?m)',comment))) for xrefBlock in xrefBlocks: xrefs = reversed(list(re.finditer(r'\d+',xrefBlock.group(0)))) for xref in xrefs: paragraph = xref.group(0) content,location = self._Catechism[paragraph]
n_ * WC("b", S(1))) ** p_ * (c_ + x_ ** n_ * WC("d", S(1))) ** WC("q", S(1)) * (e_ + x_ ** n_ * WC("f", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons52, cons13, cons139, ) rule999 = ReplacementRule(pattern999, replacement999) pattern1000 = Pattern( Integral( (a_ + x_ ** n_ * WC("b", S(1))) ** WC("p", S(1)) * (c_ + x_ ** n_ * WC("d", S(1))) ** WC("q", S(1)) * (e_ + x_ ** n_ * WC("f", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons5, cons397, cons405, cons633, ) rule1000 = ReplacementRule(pattern1000, replacement1000) pattern1001 = Pattern( Integral( (e_ + x_ ** S(4) * WC("f", S(1))) / ( (a_ + x_ ** S(4) * WC("b", S(1))) ** (S(3) / 4) * (c_ + x_ ** S(4) * WC("d", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons155, ) rule1001 = ReplacementRule(pattern1001, replacement1001) pattern1002 = Pattern( Integral( (a_ + x_ ** n_ * WC("b", S(1))) ** p_ * (e_ + x_ ** n_ * WC("f", S(1))) / (c_ + x_ ** n_ * WC("d", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons5, cons4, cons634, ) rule1002 = ReplacementRule(pattern1002, replacement1002) pattern1003 = Pattern( Integral( (a_ + x_ ** n_ * WC("b", S(1))) ** WC("p", S(1)) * (c_ + x_ ** n_ * WC("d", S(1))) ** WC("q", S(1)) * (e_ + x_ ** n_ * WC("f", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons5, cons52, cons635, ) rule1003 = ReplacementRule(pattern1003, replacement1003) pattern1004 = Pattern( Integral( S(1) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * (c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons155, ) rule1004 = ReplacementRule(pattern1004, replacement1004) pattern1005 = Pattern( Integral( S(1) / ( x_ ** S(2) * (c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons8, cons29, cons50, cons127, cons178, ) rule1005 = ReplacementRule(pattern1005, replacement1005) pattern1006 = Pattern( Integral( sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons636, cons637, cons638, ) rule1006 = ReplacementRule(pattern1006, replacement1006) pattern1007 = Pattern( Integral( sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons639, ) rule1007 = ReplacementRule(pattern1007, replacement1007) pattern1008 = Pattern( Integral( S(1) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons575, cons640, cons638, ) rule1008 = ReplacementRule(pattern1008, replacement1008) pattern1009 = Pattern( Integral( S(1) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons583, cons179, cons180, cons641, ) rule1009 = ReplacementRule(pattern1009, replacement1009) pattern1010 = Pattern( Integral( S(1) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons119, ) rule1010 = ReplacementRule(pattern1010, replacement1010) pattern1011 = Pattern( Integral( sqrt(c_ + x_ ** S(2) * WC("d", S(1))) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons575, ) rule1011 = ReplacementRule(pattern1011, replacement1011) pattern1012 = Pattern( Integral( sqrt(c_ + x_ ** S(2) * WC("d", S(1))) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons583, ) rule1012 = ReplacementRule(pattern1012, replacement1012) pattern1013 = Pattern( Integral( sqrt(e_ + x_ ** S(2) * WC("f", S(1))) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * (c_ + x_ ** S(2) * WC("d", S(1))) ** (S(3) / 2) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons575, cons640, ) rule1013 = ReplacementRule(pattern1013, replacement1013) pattern1014 = Pattern( Integral( (e_ + x_ ** S(2) * WC("f", S(1))) ** (S(3) / 2) / ( (a_ + x_ ** S(2) * WC("b", S(1))) * (c_ + x_ ** S(2) * WC("d", S(1))) ** (S(3) / 2) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons575, cons640, ) rule1014 = ReplacementRule(pattern1014, replacement1014) pattern1015 = Pattern( Integral( (c_ + x_ ** S(2) * WC("d", S(1))) ** (S(3) / 2) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons575, cons640, ) rule1015 = ReplacementRule(pattern1015, replacement1015) pattern1016 = Pattern( Integral( (c_ + x_ ** S(2) * WC("d", S(1))) ** q_ * (e_ + x_ ** S(2) * WC("f", S(1))) ** r_ / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons642, cons398, cons643, ) rule1016 = ReplacementRule(pattern1016, replacement1016) pattern1017 = Pattern( Integral( (c_ + x_ ** S(2) * WC("d", S(1))) ** q_ * (e_ + x_ ** S(2) * WC("f", S(1))) ** r_ / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons54, cons397, cons578, ) rule1017 = ReplacementRule(pattern1017, replacement1017) pattern1018 = Pattern( Integral( (c_ + x_ ** S(2) * WC("d", S(1))) ** q_ * (e_ + x_ ** S(2) * WC("f", S(1))) ** r_ / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons54, cons397, cons398, ) rule1018 = ReplacementRule(pattern1018, replacement1018) pattern1019 = Pattern( Integral( (c_ + x_ ** S(2) * WC("d", S(1))) ** q_ * (e_ + x_ ** S(2) * WC("f", S(1))) ** r_ / (a_ + x_ ** S(2) * WC("b", S(1))), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons54, cons397, cons644, ) rule1019 = ReplacementRule(pattern1019, replacement1019) pattern1020 = Pattern( Integral( sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) / (a_ + x_ ** S(2) * WC("b", S(1))) ** S(2), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons155, ) rule1020 = ReplacementRule(pattern1020, replacement1020) pattern1021 = Pattern( Integral( S(1) / ( (a_ + x_ ** S(2) * WC("b", S(1))) ** S(2) * sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons155, ) rule1021 = ReplacementRule(pattern1021, replacement1021) pattern1022 = Pattern( Integral( (a_ + x_ ** n_ * WC("b", S(1))) ** p_ * (c_ + x_ ** n_ * WC("d", S(1))) ** q_ * (e_ + x_ ** n_ * WC("f", S(1))) ** r_, x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons54, cons65, cons397, cons405, ) rule1022 = ReplacementRule(pattern1022, replacement1022) pattern1023 = Pattern( Integral( (a_ + x_ ** n_ * WC("b", S(1))) ** p_ * (c_ + x_ ** n_ * WC("d", S(1))) ** q_ * (e_ + x_ ** n_ * WC("f", S(1))) ** r_, x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons4, cons52, cons65, cons397, cons644, ) rule1023 = ReplacementRule(pattern1023, replacement1023) pattern1024 = Pattern( Integral( S(1) / ( sqrt(a_ + x_ ** S(2) * WC("b", S(1))) * sqrt(c_ + x_ ** S(2) * WC("d", S(1))) * sqrt(e_ + x_ ** S(2) * WC("f", S(1))) ), x_, ), cons2, cons3, cons8, cons29, cons50, cons127, cons155, ) rule1024 = ReplacementRule(pattern1024, replacement1024) pattern1025 = Pattern( Integral(
# # This file is part of the GROMACS molecular simulation package. # # Copyright (c) 2019, by the GROMACS development team, led by # <NAME>, <NAME>, <NAME>, and <NAME>, # and including many others, as listed in the AUTHORS file in the # top-level source directory and at http://www.gromacs.org. # # GROMACS 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. # # GROMACS 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 GROMACS; if not, see # http://www.gnu.org/licenses, or write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # If you want to redistribute modifications to GROMACS, please # consider that scientific software is very special. Version # control is crucial - bugs must be traceable. We will be happy to # consider code for inclusion in the official distribution, but # derived work must not be called official GROMACS. Details are found # in the README & COPYING files - if they are missing, get the # official version at http://www.gromacs.org. # # To help us fund GROMACS development, we humbly ask that you cite # the research papers on the package. Check out http://www.gromacs.org. """Define gmxapi-compliant Operations Provide decorators and base classes to generate and validate gmxapi Operations. Nodes in a work graph are created as instances of Operations. An Operation factory accepts well-defined inputs as key word arguments. The object returned by such a factory is a handle to the node in the work graph. It's ``output`` attribute is a collection of the Operation's results. function_wrapper(...) produces a wrapper that converts a function to an Operation factory. The Operation is defined when the wrapper is called. The Operation is instantiated when the factory is called. The function is executed when the Operation instance is run. The framework ensures that an Operation instance is executed no more than once. """ __all__ = ['computed_result', 'append_list', 'concatenate_lists', 'function_wrapper', 'make_constant', ] import collections import functools import inspect import weakref from contextlib import contextmanager from gmxapi import exceptions class ImmediateResult(object): """Data handle for a simple result. Instances of this class can be used to provide a gmxapi compatible data handle for trivial operations. Operation and result are stateless and can be evaluated in any Context. Used internally to implement the computed_result factory. The interface for this class will evolve as the gmxapi data model evolves. Generally, code providing gmxapi data sources should use one of the factories or decorators provided in the gmxapi.operation module rather than instantiating from this class directly. """ def __init__(self, implementation=None, input=None): """Wrap a callable for a simple data source that does not need Future behavior. Provides a gmxapi compatible interface for data sources. Arguments: implementation : Python callable that consumes ``input`` and returns data input : object compatible with the call signature of ``implementation`` ``input`` must have an ``args`` attribute and a ``kwargs`` attribute to be used as implementation(*input.args, **input.kwargs) Callers should not assume when or how often ``implementation`` could be called. Only suitable for function objects without side effects. """ assert callable(implementation) assert hasattr(input, 'args') assert hasattr(input, 'kwargs') # Retain input information for introspection. self.__input = input self.__cached_value = implementation(*input.args, **input.kwargs) # TODO: (FR4) need a utility to resolve the base type of a value # that may be a proxy object. self._dtype = type(self.__cached_value) @property def dtype(self): """The data type of the return value for the wrapped function.""" return self._dtype def result(self): """Return value of the wrapped function.""" return self.__cached_value def computed_result(function): """Decorate a function to get a helper that produces an object with Result behavior. When called, the new function produces an ImmediateResult object. The new function has the same signature as the original function, but can accept gmxapi data proxies, assuming the provided proxy objects represent types compatible with the original signature. Calls to `result()` return the value that `function` would return when executed in the local context with the inputs fully resolved. The API does not specify when input data dependencies will be resolved or when the wrapped function will be executed. That is, ``@computed_result`` functions may force immediate resolution of data dependencies and/or may be called more than once to satisfy dependent operation inputs. """ @functools.wraps(function) def new_function(*args, **kwargs): # The signature of the new function will accept abstractions # of whatever types it originally accepted. This wrapper must # * Create a mapping to the original call signature from `input` # * Add handling for typed abstractions in wrapper function. # * Process arguments to the wrapper function into `input` sig = inspect.signature(function) # Note: Introspection could fail. # TODO: Figure out what to do with exceptions where this introspection # and rebinding won't work. # ref: https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object # TODO: (FR3+) create a serializable data structure for inputs discovered # from function introspection. # TODO: (FR4) handle typed abstractions in input arguments input_list = [] for arg in args: if hasattr(arg, 'result'): input_list.append(arg.result()) else: input_list.append(arg) input_dict = {} for name, value in kwargs.items(): if hasattr(value, 'result'): input_dict[name] = value.result() else: input_dict[name] = value input_pack = sig.bind(*input_list, **input_dict) result_object = ImmediateResult(function, input_pack) return result_object return new_function @computed_result def append_list(a: list = (), b: list = ()): """Operation that consumes two lists and produces a concatenated single list.""" # TODO: (FR4) Returned list should be an NDArray. if isinstance(a, (str, bytes)) or isinstance(b, (str, bytes)): raise exceptions.ValueError('Input must be a pair of lists.') try: list_a = list(a) except TypeError: list_a = list([a]) try: list_b = list(b) except TypeError: list_b = list([b]) return list_a + list_b def concatenate_lists(sublists: list = ()): """Combine data sources into a single list. A trivial data flow restructuring operation """ if isinstance(sublists, (str, bytes)): raise exceptions.ValueError('Input must be a list of lists.') if len(sublists) == 0: return [] else: return append_list(sublists[0], concatenate_lists(sublists[1:])) @computed_result def make_constant(value): """Provide a predetermined value at run time. This is a trivial operation that provides a (typed) value, primarily for internally use to manage gmxapi data flow. Accepts a value of any type. The object returned has a definite type and provides same interface as other gmxapi outputs. Additional constraints or guarantees on data type may appear in future versions. """ # TODO: (FR4+) Manage type compatibility with gmxapi data interfaces. return type(value)(value) # In the longer term, Contexts could provide metaclasses that allow transformation or dispatching # of the basic aspects of the operation protocols between Contexts or from a result handle into a # new context, based on some attribute or behavior in the result handle. # TODO: For outputs, distinguish between "results" and "events". # Both are published to the resource manager in the same way, but the relationship # with subscribers is potentially different. def function_wrapper(output=None): """Generate a decorator for wrapped functions with signature manipulation. New function accepts the same arguments, with additional arguments required by the API. The new function returns an object with an `output` attribute containing the named outputs. Example: @function_wrapper(output={'spam': str, 'foo': str}) def myfunc(parameter: str = None, output=None): output.spam = parameter output.foo = parameter + ' ' + parameter operation1 = myfunc(parameter='spam spam') assert operation1.output.spam.result() == 'spam spam' assert operation1.output.foo.result() == 'spam spam spam spam' """ # TODO: more flexibility to capture return value by default? # If 'output' is provided to the wrapper, a data structure will be passed to # the wrapped functions with the named attributes so that the function can easily # publish multiple named results. Otherwise, the `output` of the generated operation # will just capture the return value of the wrapped function. # For now, this behavior is obtained with @computed_result # TODO: (FR5+) gmxapi operations need to allow a
<reponame>bmgee/votedperceptron # Copyright 2015 <NAME>. 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. # ============================================================================== """ Multiclass Classifier. A multiclass classifier based on multiple binary classifiers. """ from itertools import combinations import numpy as np from multiprocess import Pool class MulticlassClassifier(object): """ Multiclass Classifier constructed from binary classifiers. Parameters ---------- strategy : str Strategy to use to transform multiclass classification problem to multiple binary classification problems. Valid choices are: OVA: One-vs-All OVO: One-vs-One If there are N possible_labels then OVA will require building N binary classifiers (one for every possible label) and OVO will require building (N choose 2) (i.e. N*(N-1)/2) binary classifiers (one for every possible pair of labels). possible_labels : tuple Tuple of the possible classification labels. BinaryClassifier : class Class to build the binary classifiers. Class should implement the following methods: train(data : ndarray, labels : ndarray, *) predict(input_vector : ndarray, *) -- See Notes. bc_args : tuple Positional arguments to BinaryClassifier.__init__ bc_kwargs : dict Keyword arguments to BinaryClassifier.__init__ Attributes ---------- strategy : str Same as parameter of same name. possible_labels : tuple Same as parameter of same name. Raises ------ NotImplementedError If strategy not in ('OVA', 'OVO') Notes ----- The predict method of the underlying Binary Classifiers should be set to return a real-valued confidence score for its decision, rather than just a class label. """ def __init__(self, strategy, possible_labels, BinaryClassifier, bc_args, bc_kwargs): self.strategy = strategy self.possible_labels = possible_labels # self.binary_classifiers is a dictionary of the underlying binary classifiers keyed # by a 2-tuple of the label(s) they are used to classify. # In the OVA case the keys are (x, None) since the binary classifiers are used # to predict whether an input vector is of classification label x or not. # In the OVO case the keys are (x, y) since the binary classifiers are used to # predict whether an input vector is of classification label x or label y with # positive scores indicating label x and negative scores indicating label y. if self.strategy == 'OVA': self.binary_classifiers = {(x, None): BinaryClassifier(*bc_args, **bc_kwargs) for x in self.possible_labels} elif self.strategy == 'OVO': self.binary_classifiers = {(x, y): BinaryClassifier(*bc_args, **bc_kwargs) for x, y in combinations(self.possible_labels, 2)} else: raise NotImplementedError(self.strategy) def train(self, data, labels, other_bc_train_args, other_bc_train_kwargs, process_count): """ Train the Multiclass Classifier. (i.e. by training the underlying binary classifiers). Parameters ---------- data : ndarray An ndarray where each row is a training case consisting of the state of visible units. labels : ndarray An ndarray where each element is the label/classification of a training case in data for binary classification. Valid label values are -1 and 1. other_bc_train_args : tuple Positional arguments to BinaryClassifier.train not including data and labels. other_bc_train_kwargs : dict Keyword arguments to BinaryClassifier.train not including data and labels. process_count : int The number of worker processes to use when training the binary classifiers. Notes ----- The elements in data must correspond in sequence to the elements in labels. """ def strategized_data_and_labels(strategy, label_1, label_2, data, labels): """ Generate data and labels appropriate for the given strategy and binary classifier defined by label_1 and label_2. Parameters ---------- strategy : str Strategy to use to transform multiclass classification problem to multiple binary classification problems. Valid choices are: OVA: One-vs-All OVO: One-vs-One If there are N possible_labels then OVA will require building N binary classifiers (one for every possible label) and OVO will require building (N choose 2) (i.e. N*(N-1)/2) binary classifiers (one for every possible pair of labels). label_1, label_2 : str The key of the binary classifier to be trained. data : ndarray An ndarray where each row is a training case consisting of the state of visible units. labels : ndarray An ndarray where each element is the label/classification of a training case in data for binary classification. Valid label values are -1 and 1. Returns ------- tuple 2 element tuple where first element is strategized_data and the second element is strategized_labels. Raises ------ NotImplementedError If strategy not in ('OVA', 'OVO') """ if strategy == 'OVA': # strategized_labels entries are 1 if label_1, -1 otherwise. strategized_labels = np.where(np.in1d(labels, label_1), np.ones(labels.shape, np.int8), -np.ones(labels.shape, np.int8)) strategized_data = data elif strategy == 'OVO': # strategized labels and data only containing entries # corresponding to label_1 and label_2 and strategized_labels # entries being 1 if label_1, -1 if label_2. strategized_condition = np.in1d(labels, (label_1, label_2)) strategized_prelabels = labels[strategized_condition] strategized_labels = np.where(np.in1d(strategized_prelabels, label_1), np.ones(strategized_prelabels.shape, np.int8), -np.ones(strategized_prelabels.shape, np.int8)) strategized_data = data[strategized_condition] else: raise NotImplementedError(strategy) return (strategized_data, strategized_labels) def managed_binary_classifier_train(binary_classifier, strategized_data, strategized_labels, other_bc_args, other_bc_kwargs): """ Train a specific binary classifier. Parameters ---------- binary_classifier : binary classifier The binary classifier to train. strategized_data, strategized_labels : ndarray data and labels relevant for the training of the binary classifier. other_bc_train_args : tuple Positional arguments to BinaryClassifier.train not including data and labels. other_bc_train_kwargs : dict Keyword arguments to BinaryClassifier.train not including data and labels. Returns ------- binary classifier The trained binary classifier. """ binary_classifier.train(strategized_data, strategized_labels, *other_bc_args, **other_bc_kwargs) return binary_classifier def error_callback(exc): """ Callback used by pool.apply_async when an error occurs. Parameters ---------- exc : Exception Exception thrown by the process pool.apply_async was running in. """ print(exc.__cause__) if process_count is not None and process_count > 1: trained_bc_results = {} with Pool(processes=process_count) as pool: # Use the process pool to initiate training of the # binary classifiers. for (label_1, label_2), binary_classifier in self.binary_classifiers.items(): (strategized_data, strategized_labels) = ( strategized_data_and_labels(self.strategy, label_1, label_2, data, labels) ) trained_bc_results[(label_1, label_2)] = ( pool.apply_async(func=managed_binary_classifier_train, args=(binary_classifier, strategized_data, strategized_labels, other_bc_train_args, other_bc_train_kwargs), error_callback=error_callback) ) # Retrieve the trained binary classifiers back from the process pool and # replace the untrained instances in self.binary_classifiers with # their trained counterparts. for (label_1, label_2) in self.binary_classifiers.keys(): self.binary_classifiers[(label_1, label_2)] = ( trained_bc_results[(label_1, label_2)].get() ) else: # Train each binary classifier. for (label_1, label_2), binary_classifier in self.binary_classifiers.items(): (strategized_data, strategized_labels) = ( strategized_data_and_labels(self.strategy, label_1, label_2, data, labels) ) binary_classifier.train(strategized_data, strategized_labels, *other_bc_train_args, **other_bc_train_kwargs) def predict(self, input_vector, other_bc_predict_args, other_bc_predict_kwargs): """ Output predicted label of multiclass classifier and given input vector. Based on output of underlying binary classifiers for given input vector. Parameters ---------- input_vector : ndarray A given state of visible units. other_bc_predict_args : tuple Positional arguments to BinaryClassifier.predict not including input_vector. other_bc_predict_kwargs : dict Keyword arguments to BinaryClassifier.predict not including input_vector. Returns ------- str The label the multiclass classifer predicts for the given input_vector. """ bc_scores = {(label_1, label_2): binary_classifier.predict(input_vector, *other_bc_predict_args, **other_bc_predict_kwargs) for (label_1, label_2), binary_classifier in self.binary_classifiers.items()} if self.strategy in ('OVA', 'OVO'): # Compute a confidence score for each label and set the predicted label to be # the one with the highest score. # For OVA it will just be the score output by the single corresponding binary classifier # for the label (i.e. the binary classifier keyed by (label, None)). # For OVO it will be the sum of appropriate scores output by all the binary # classifiers classifying that label # (i.e. binary classifiers with the label in any position in the key tuple). # For OVO what we mean by appropriate scores is if the label is in the second position # of the key tuple then we take the negative of the score output by the binary # classifier since positive scores predict the label in the first position of the # key tuple and negative scores indicates predict the label in the second position # of the key tuple. # The following dictionary comprehension works for both cases. label_scores = {label: sum(score if label
== 205 and satelliteSeries == 331: return 'Synth. Sat. brightness temperature cloudy' if discipline == 3 and parameterCategory == 1 and parameterNumber == 17 and instrumentType == 205 and satelliteSeries == 331 and satelliteNumber == 52: return 'Synth. Sat. radiance cloudy' if discipline == 3 and parameterCategory == 1 and parameterNumber == 16 and satelliteNumber == 52 and instrumentType == 205 and satelliteSeries == 331: return 'Synth. Sat. radiance cloudy' if discipline == 3 and parameterCategory == 1 and parameterNumber == 15 and instrumentType == 205 and satelliteSeries == 331 and satelliteNumber == 52: return 'Synth. Sat. brightness temperature clear sky' if discipline == 3 and parameterCategory == 1 and parameterNumber == 14 and satelliteNumber == 52 and instrumentType == 205 and satelliteSeries == 331: return 'Synth. Sat. brightness temperature cloudy' if discipline == 0 and parameterCategory == 2 and parameterNumber == 196 and typeOfGeneratingProcess == 200 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference IA-AN of kinetic energy' if discipline == 0 and parameterCategory == 2 and parameterNumber == 196 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 199: return 'Monthly Mean of RMS of difference FG-AN of kinetic energy' if discipline == 0 and parameterCategory == 2 and parameterNumber == 8 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 200: return 'Monthly Mean of RMS of difference IA-AN of vert.velocity (pressure)' if discipline == 0 and parameterCategory == 2 and parameterNumber == 8 and typeOfGeneratingProcess == 199 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference FG-AN of vert.velocity (pressure)' if discipline == 0 and parameterCategory == 0 and parameterNumber == 0 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 200: return 'Monthly Mean of RMS of difference IA-AN of temperature' if discipline == 0 and parameterCategory == 0 and parameterNumber == 0 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 199: return 'Monthly Mean of RMS of difference FG-AN of temperature' if discipline == 0 and parameterCategory == 1 and parameterNumber == 1 and typeOfGeneratingProcess == 200 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference IA-AN of relative humidity' if discipline == 0 and parameterCategory == 1 and parameterNumber == 1 and typeOfGeneratingProcess == 199 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference FG-AN of relative humidity' if discipline == 0 and parameterCategory == 3 and parameterNumber == 4 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 200: return 'Monthly Mean of RMS of difference IA-AN of geopotential' if discipline == 0 and parameterCategory == 3 and parameterNumber == 4 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 199: return 'Monthly Mean of RMS of difference FG-AN of geopotential' if discipline == 0 and parameterCategory == 2 and parameterNumber == 3 and typeOfGeneratingProcess == 200 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference IA-AN of v-component of wind' if discipline == 0 and parameterCategory == 2 and parameterNumber == 3 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 199: return 'Monthly Mean of RMS of difference FG-AN of v-component of wind' if discipline == 0 and parameterCategory == 2 and parameterNumber == 2 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 200: return 'Monthly Mean of RMS of difference IA-AN of u-component of wind' if discipline == 0 and parameterCategory == 2 and parameterNumber == 2 and typeOfGeneratingProcess == 199 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference FG-AN of u-component of wind' if discipline == 0 and parameterCategory == 3 and parameterNumber == 1 and typeOfGeneratingProcess == 200 and typeOfStatisticalProcessing == 5: return 'Monthly Mean of RMS of difference IA-AN of pressure reduced to MSL' if discipline == 0 and parameterCategory == 3 and parameterNumber == 1 and typeOfStatisticalProcessing == 5 and typeOfGeneratingProcess == 199: return 'Monthly Mean of RMS of difference FG-AN of pressure reduced to MSL' if discipline == 0 and parameterCategory == 6 and parameterNumber == 199 and typeOfFirstFixedSurface == 1: return 'modified cloud cover for media' if discipline == 0 and parameterCategory == 6 and parameterNumber == 198 and typeOfFirstFixedSurface == 1: return 'modified cloud depth for media' if discipline == 0 and parameterCategory == 19 and parameterNumber == 7: return 'Icing Grade (1=LGT,2=MOD,3=SEV)' if discipline == 0 and parameterCategory == 6 and parameterNumber == 13 and typeOfFirstFixedSurface == 1: return 'Ceiling' if discipline == 0 and parameterCategory == 0 and parameterNumber == 3: return 'Aequivalentpotentielle Temperatur' if discipline == 0 and parameterCategory == 7 and parameterNumber == 3 and typeOfFirstFixedSurface == 1: return 'KO index' if discipline == 0 and parameterCategory == 3 and parameterNumber == 0 and typeOfFirstFixedSurface == 107 and scaleFactorOfFirstFixedSurface == -2: return 'Druck einer isentropen Flaeche' if discipline == 0 and parameterCategory == 2 and parameterNumber == 14 and typeOfFirstFixedSurface == 107: return 'Isentrope potentielle Vorticity' if discipline == 0 and parameterCategory == 19 and parameterNumber == 25 and typeOfFirstFixedSurface == 1: return 'weather interpretation (WMO)' if discipline == 0 and parameterCategory == 6 and parameterNumber == 26 and typeOfFirstFixedSurface == 1: return 'Konv.-U-Grenze-nn Hoehe der Konvektionsuntergrenze ueber nn' if discipline == 0 and parameterCategory == 2 and parameterNumber == 10: return 'absolute vorticity advection' if discipline == 0 and parameterCategory == 7 and parameterNumber == 8 and typeOfFirstFixedSurface == 105 and scaleFactorOfFirstFixedSurface == 0: return 'storm relative helicity' if discipline == 0 and parameterCategory == 2 and parameterNumber == 1 and typeOfFirstFixedSurface == 105: return 'wind shear' if discipline == 0 and parameterCategory == 4 and parameterNumber == 51: return 'UV_Index_Maximum_W UV_Index clouded (W), daily maximum' if discipline == 0 and parameterCategory == 3 and parameterNumber == 23 and typeOfFirstFixedSurface == 1: return 'Gravity wave dissipation (vertical integral)' if discipline == 0 and parameterCategory == 3 and parameterNumber == 23 and typeOfFirstFixedSurface == 1 and typeOfStatisticalProcessing == 0: return 'Gravity wave dissipation (vertical integral)' if discipline == 0 and parameterCategory == 3 and parameterNumber == 194 and typeOfFirstFixedSurface == 1: return 'v-momentum flux due to SSO-effects' if discipline == 0 and parameterCategory == 3 and parameterNumber == 194 and typeOfStatisticalProcessing == 0 and typeOfFirstFixedSurface == 1: return 'v-momentum flux due to SSO-effects' if discipline == 0 and parameterCategory == 3 and parameterNumber == 193 and typeOfFirstFixedSurface == 1: return 'u-momentum flux due to SSO-effects' if discipline == 0 and parameterCategory == 3 and parameterNumber == 193 and typeOfFirstFixedSurface == 1 and typeOfStatisticalProcessing == 0: return 'u-momentum flux due to SSO-effects' if discipline == 0 and parameterCategory == 18 and parameterNumber == 227: return 'Ba140 - wet deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 226: return 'Ba140 - dry deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 225: return 'Air concentration of Barium 40' if discipline == 0 and parameterCategory == 18 and parameterNumber == 224: return 'I131o - wet deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 223: return 'I131o - dry deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 222: return 'I131o - concentration' if discipline == 0 and parameterCategory == 18 and parameterNumber == 221: return 'I131g - wet deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 220: return 'Xe133 - wet deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 219: return 'I131g - concentration' if discipline == 0 and parameterCategory == 18 and parameterNumber == 218: return 'Xe133 - wet deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 217: return 'Xe133 - dry deposition' if discipline == 0 and parameterCategory == 18 and parameterNumber == 216: return 'Air concentration of Xenon 133 (Xe133 - concentration)' if discipline == 0 and parameterCategory == 18 and parameterNumber == 215: return 'TRACER - wet deposition' if discipline ==
node_identifier, stdout, stderr, exit_status)) def assign_node_roles(self): logger.debug("Assigning roles to nodes") common_path = os.path.join(os.path.expanduser( self.settings.cloud_repo_dir + '/src'), 'common') sys.path.append(common_path) from thread_helper import ThreadWithExHandling # noqa roles_to_nodes = {} roles_to_nodes["controller"] = self.settings.controller_nodes roles_to_nodes["compute"] = self.settings.compute_nodes roles_to_nodes["storage"] = self.settings.ceph_nodes threads = [] for role in roles_to_nodes.keys(): index = 0 for node in roles_to_nodes[role]: thread = ThreadWithExHandling(logger, target=self.assign_role, args=(node, role, index)) threads.append(thread) thread.start() index += 1 for thread in threads: thread.join() failed_threads = 0 for thread in threads: if thread.ex is not None: failed_threads += 1 if failed_threads == 0: logger.info("Successfully assigned roles to all nodes") else: logger.info("assign_role failed on {} out of {} nodes".format( failed_threads, len(threads))) sys.exit(1) def update_sshd_conf(self): # Update sshd_config to allow for more than 10 ssh sessions # Required for assign_role to run threaded if stamp has > 10 nodes non_sah_nodes = (self.settings.controller_nodes + self.settings.compute_nodes + self.settings.ceph_nodes) # Allow for the number of nodes + a few extra sessions maxSessions = len(non_sah_nodes) + 10 setts = ['MaxStartups', 'MaxSessions'] for each in setts: re = self.run("sudo grep " + each + " /etc/ssh/sshd_config")[0].rstrip() if re != each + " " + str(maxSessions): self.run_as_root('sed -i -e "\$a' + each + ' ' + str(maxSessions) + '" /etc/ssh/sshd_config') self.run_as_root("systemctl restart sshd") def revert_sshd_conf(self): # Revert sshd_config to its default cmds = [ "sed -i '/MaxStartups/d' /etc/ssh/sshd_config", "sed -i '/MaxSessions/d' /etc/ssh/sshd_config", "systemctl restart sshd" ] for cmd in cmds: self.run_as_root(cmd) def setup_templates(self): # Re-upload the yaml files in case we're trying to leave the undercloud # intact but want to redeploy with a different config. self.setup_networking() self.setup_dell_storage() self.setup_manila() self.setup_environment() self.setup_sanity_ini() def clamp_min_pgs(self, num_pgs): if num_pgs < 1: return 0 pg_options = [8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] option_index = 0 finding_pg_value = True while finding_pg_value: if num_pgs >= pg_options[option_index]: num_pgs = pg_options[option_index] finding_pg_value = False else: option_index += 1 return num_pgs def calc_pgs(self, num_osds, num_heavy_pools, num_other_pools): if num_osds == 0: return 0, 0 replication_factor = 3 max_pgs = num_osds * 200 / replication_factor total_pgs = max_pgs * 0.8 total_heavy_pgs = total_pgs / 2 heavy_pgs = total_heavy_pgs / num_heavy_pools heavy_pgs = self.clamp_min_pgs(heavy_pgs) heavy_pools_pgs = num_heavy_pools * heavy_pgs remaining_pgs = total_pgs - heavy_pools_pgs other_pgs = remaining_pgs / num_other_pools other_pgs = self.clamp_min_pgs(other_pgs) return heavy_pgs, other_pgs def calc_num_osds(self, default_osds_per_node): # Pull down the auto-generated OSD config file from the director local_file = self.settings.ceph_osd_config_yaml + '.director' remote_file = os.path.join('/home', self.settings.director_install_account_user, Settings.CEPH_OSD_CONFIG_FILE) self.download_file(local_file, remote_file) # Calculate the number of OSDs across the entire cluster total_osds = 0 with open(local_file, 'r') as stream: osd_configs_yaml = yaml.load(stream) node_data_lookup_str = osd_configs_yaml["parameter_defaults"][ "NodeDataLookup"] uuid_to_osd_configs = json.loads(node_data_lookup_str) for uuid in uuid_to_osd_configs: osd_config = uuid_to_osd_configs[uuid] num_osds = len(osd_config["devices"]) total_osds = total_osds + num_osds num_storage_nodes = len(self.settings.ceph_nodes) num_unaccounted = num_storage_nodes - len(uuid_to_osd_configs) if num_unaccounted < 0: raise AssertionError("There are extraneous servers listed in {}. " "Unable to calculate the number of OSDs in " "the cluster. Remove the bad entries from " "the file or discard the current generated " "OSD configration by copying {}.orig to " "{}.".format( self.settings.ceph_osd_config_yaml, self.settings.ceph_osd_config_yaml, self.settings.ceph_osd_config_yaml)) total_osds = total_osds + (num_unaccounted * default_osds_per_node) return total_osds def setup_environment(self): logger.debug("Configuring Ceph storage settings for overcloud") # If the osd_disks were not specified then just return osd_disks = None if hasattr(self.settings.ceph_nodes[0], 'osd_disks'): # If the OSD disks are specified on the first storage node, then # use them. This is the best we can do until the OSP Director # supports more than a single, global OSD configuration. osd_disks = self.settings.ceph_nodes[0].osd_disks src_file = open(self.settings.dell_env_yaml, 'r') # Temporary local file used to stage the modified environment file tmp_fd, tmp_name = tempfile.mkstemp() tmp_file = os.fdopen(tmp_fd, 'w') # Leading whitespace for these variables is critical !!! osds_param = " CephAnsibleDisksConfig:" osd_scenario_param = " osd_scenario:" osd_scenario = "collocated" # Keep this as default, change if required osd_devices = " devices:\n" osd_dedicated_devices = " dedicated_devices:\n" ceph_pools = " CephPools:" domain_param = " CloudDomain:" rbd_backend_param = " NovaEnableRbdBackend:" glance_backend_param = " GlanceBackend:" rbd_cinder_backend_param = " CinderEnableRbdBackend:" osds_per_node = 0 if osd_disks: for osd in osd_disks: # Format is ":OSD_DRIVE" or ":OSD_DRIVE:JOURNAL_DRIVE", # so split on the ':' tokens = osd.split(':') # Make sure OSD_DRIVE begins with "/dev/" if not tokens[1].startswith("/dev/"): tokens[1] += "/dev/" if len(tokens) == 3: # This OSD specifies a separate journal drive # Set the osd-scenario to non-collocated osd_scenario = "non-collocated" osd_devices = "{} - {}\n".format( osd_devices, tokens[1]) osd_dedicated_devices = "{} - {}\n".format( osd_dedicated_devices, tokens[2]) osds_per_node += 1 elif len(tokens) == 2: # This OSD does not specify a separate journal # Add the same device as dedicated device # It is useful when there is a mix of collocated # and non-collocated devices osd_devices = "{} - {}\n".format( osd_devices, tokens[1]) osd_dedicated_devices = "{} - {}\n".format( osd_dedicated_devices, tokens[1]) osds_per_node += 1 else: logger.warning( "Bad entry in osd_disks: {}".format(osd)) total_osds = self.calc_num_osds(osds_per_node) if total_osds == 0: logger.info("Either the OSD configuration is not specified in " "the .properties file or the storage nodes have " "no available storage to dedicate to OSDs. Exiting") sys.exit(1) heavy_pgs, other_pgs = self.calc_pgs(total_osds, len(HEAVY_POOLS), len(OTHER_POOLS)) found_osds_param = False for line in src_file: if osd_disks and line.startswith(osds_param): found_osds_param = True elif found_osds_param: # Discard lines that begin with "#", "osd_scenario", # "devices:", "dedicated_devices:" or "-" because these lines # represent the original ceph.yaml file's OSD configuration. tokens = line.split() if len(tokens) > 0 and (tokens[0].startswith("#") or tokens[0].startswith("osd_scenario") or tokens[0].startswith("devices") or tokens[0].startswith("dedicated_devices") or # noqa: E501 tokens[0].startswith("-")): continue # End of original Ceph OSD configuration: now write the new one tmp_file.write("{}\n".format(osds_param)) tmp_file.write("{} {}\n".format( osd_scenario_param, osd_scenario)) tmp_file.write(osd_devices) if osd_scenario == "non-collocated": tmp_file.write(osd_dedicated_devices) # This is the line that follows the original Ceph OSD config tmp_file.write(line) found_osds_param = False elif line.startswith(domain_param): value = str(self.settings.domain).lower() tmp_file.write("{} {}\n".format(domain_param, value)) elif line.startswith(rbd_backend_param): value = str(self.settings.enable_rbd_nova_backend).lower() tmp_file.write("{} {}\n".format(rbd_backend_param, value)) elif line.startswith(glance_backend_param): value = str(self.settings.glance_backend).lower() tmp_file.write("{} {}\n".format(glance_backend_param, value)) elif line.startswith(rbd_cinder_backend_param): value = str(self.settings.enable_rbd_backend).lower() tmp_file.write("{} {}\n". format(rbd_cinder_backend_param, value)) elif line.startswith(ceph_pools): pool_str = line[len(ceph_pools):] pools = json.loads(pool_str) for pool in pools: if pool["name"] in HEAVY_POOLS: pool["pg_num"] = heavy_pgs pool["pgp_num"] = heavy_pgs else: pool["pg_num"] = other_pgs pool["pgp_num"] = other_pgs tmp_file.write("{} {}\n".format(ceph_pools, json.dumps(pools))) else: tmp_file.write(line) src_file.close() tmp_file.close() env_name = os.path.join(self.templates_dir, "dell-environment.yaml") self.upload_file(tmp_name, env_name) os.remove(tmp_name) def setup_sanity_ini(self): sanity_ini = self.sanity_dir + "/sanity.ini" self.upload_file(self.settings.sanity_ini, sanity_ini) # Update the remote sanity ini file with the given settings cmds = [ 'sed -i "s|floating_ip_network=.*|floating_ip_network=' + self.settings.floating_ip_network + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|floating_ip_network_start_ip=.*|' + 'floating_ip_network_start_ip=' + self.settings.floating_ip_network_start_ip + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|floating_ip_network_end_ip=.*|' + 'floating_ip_network_end_ip=' + self.settings.floating_ip_network_end_ip + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|floating_ip_network_gateway=.*|' 'floating_ip_network_gateway=' + self.settings.floating_ip_network_gateway + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|floating_ip_network_vlan=.*|floating_ip_network_vlan=' + self.settings.floating_ip_network_vlan + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|numa_enabled=.*|numa_enabled=' + str(self.settings.numa_enable) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|hugepages_enabled=.*|hugepages_enabled=' + str(self.settings.hpg_enable) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|ovs_dpdk_enabled=.*|ovs_dpdk_enabled=' + str(self.settings.enable_ovs_dpdk) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sriov_enabled=.*|sriov_enabled=' + str(self.settings.enable_sriov) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|smart_nic_enabled=.*|smart_nic_enabled=' + str(self.settings.enable_smart_nic) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|dvr_enabled=.*|dvr_enabled=' + str(self.settings.dvr_enable) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_tenant_network=.*|sanity_tenant_network=' + self.settings.sanity_tenant_network + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_user_password=.*|sanity_user_password=' + self.settings.sanity_user_password + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_user_email=.*|sanity_user_email=' + self.settings.sanity_user_email + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_key_name=.*|sanity_key_name=' + self.settings.sanity_key_name + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_number_instances=.*|sanity_number_instances=' + str(self.settings.sanity_number_instances) + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|vlan_aware_sanity=.*|vlan_aware_sanity=' + self.settings.vlan_aware_sanity + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_image_url=.*|sanity_image_url=' + self.settings.sanity_image_url + '|" pilot/deployment-validation/sanity.ini', 'sed -i "s|sanity_vlantest_network=.*|sanity_vlantest_network=' + self.settings.sanity_vlantest_network + '|" pilot/deployment-validation/sanity.ini' ] for cmd in cmds: self.run(cmd) def setup_dell_storage(self): # Clean the local docker registry if len(self.run_tty("sudo docker images -a -q")[0]) > 1: self.run_tty("sudo docker rmi $(sudo docker images -a -q) --force") # Re - Upload the yaml files in case we're trying to # leave the undercloud intact but want to redeploy with # a different config dell_storage_yaml = self.templates_dir + "/dell-cinder-backends.yaml" self.upload_file(self.settings.dell_storage_yaml, dell_storage_yaml) # Backup before modifying self.run_tty("cp " + dell_storage_yaml + " " + dell_storage_yaml + ".bak") self.setup_dellsc(dell_storage_yaml) # Dell Sc file dellsc_cinder_yaml = self.templates_dir + "/dellsc-cinder-config.yaml" self.upload_file(self.settings.dellsc_cinder_yaml, dellsc_cinder_yaml) self.run_tty("cp " + dellsc_cinder_yaml + " " + dellsc_cinder_yaml + ".bak") self.setup_dellsc(dellsc_cinder_yaml) # Unity is
1), (7, 15, 1, 2): (-1, 1), (7, 15, 1, 3): (-1, 1), (7, 15, 1, 4): (-1, 0), (7, 15, 1, 5): (-1, -1), (7, 15, 2, -5): (1, 1), (7, 15, 2, -4): (1, 1), (7, 15, 2, -3): (1, 1), (7, 15, 2, -2): (1, 1), (7, 15, 2, -1): (1, 1), (7, 15, 2, 0): (-1, 1), (7, 15, 2, 1): (-1, 1), (7, 15, 2, 2): (-1, 1), (7, 15, 2, 3): (-1, 1), (7, 15, 2, 4): (-1, 0), (7, 15, 2, 5): (-1, -1), (7, 15, 3, -5): (0, 1), (7, 15, 3, -4): (0, 1), (7, 15, 3, -3): (0, 1), (7, 15, 3, -2): (0, 1), (7, 15, 3, -1): (0, 1), (7, 15, 3, 0): (0, 1), (7, 15, 3, 1): (0, 1), (7, 15, 3, 2): (0, 1), (7, 15, 3, 3): (-1, 1), (7, 15, 3, 4): (-1, 1), (7, 15, 3, 5): (-1, 1), (7, 15, 4, -5): (0, 1), (7, 15, 4, -4): (0, 1), (7, 15, 4, -3): (0, 1), (7, 15, 4, -2): (0, 1), (7, 15, 4, -1): (0, 1), (7, 15, 4, 0): (0, 1), (7, 15, 4, 1): (0, 1), (7, 15, 4, 2): (0, 1), (7, 15, 4, 3): (0, 0), (7, 15, 4, 4): (0, 1), (7, 15, 4, 5): (0, 1), (7, 15, 5, -5): (0, 1), (7, 15, 5, -4): (0, 1), (7, 15, 5, -3): (0, 1), (7, 15, 5, -2): (0, 1), (7, 15, 5, -1): (0, 1), (7, 15, 5, 0): (0, 1), (7, 15, 5, 1): (0, 1), (7, 15, 5, 2): (0, 1), (7, 15, 5, 3): (0, 0), (7, 15, 5, 4): (0, 1), (7, 15, 5, 5): (0, 1), (7, 16, -5, -5): (0, 1), (7, 16, -5, -4): (0, 1), (7, 16, -5, -3): (0, 1), (7, 16, -5, -2): (0, 1), (7, 16, -5, -1): (0, 1), (7, 16, -5, 0): (0, 1), (7, 16, -5, 1): (0, 1), (7, 16, -5, 2): (0, 0), (7, 16, -5, 3): (0, 1), (7, 16, -5, 4): (0, 1), (7, 16, -5, 5): (0, 1), (7, 16, -4, -5): (0, 1), (7, 16, -4, -4): (0, 1), (7, 16, -4, -3): (0, 1), (7, 16, -4, -2): (0, 1), (7, 16, -4, -1): (0, 1), (7, 16, -4, 0): (0, 1), (7, 16, -4, 1): (0, 1), (7, 16, -4, 2): (0, 0), (7, 16, -4, 3): (0, 1), (7, 16, -4, 4): (0, 1), (7, 16, -4, 5): (0, 1), (7, 16, -3, -5): (0, 1), (7, 16, -3, -4): (0, 1), (7, 16, -3, -3): (0, 1), (7, 16, -3, -2): (0, 1), (7, 16, -3, -1): (0, 1), (7, 16, -3, 0): (0, 1), (7, 16, -3, 1): (0, 1), (7, 16, -3, 2): (0, 0), (7, 16, -3, 3): (0, 1), (7, 16, -3, 4): (0, 1), (7, 16, -3, 5): (0, 1), (7, 16, -2, -5): (0, 1), (7, 16, -2, -4): (0, 1), (7, 16, -2, -3): (0, 1), (7, 16, -2, -2): (0, 1), (7, 16, -2, -1): (0, 1), (7, 16, -2, 0): (1, 1), (7, 16, -2, 1): (1, 1), (7, 16, -2, 2): (1, 1), (7, 16, -2, 3): (1, 1), (7, 16, -2, 4): (1, 1), (7, 16, -2, 5): (1, 0), (7, 16, -1, -5): (-1, 1), (7, 16, -1, -4): (-1, 1), (7, 16, -1, -3): (-1, 1), (7, 16, -1, -2): (-1, 1), (7, 16, -1, -1): (1, 1), (7, 16, -1, 0): (1, 1), (7, 16, -1, 1): (1, 1), (7, 16, -1, 2): (1, 1), (7, 16, -1, 3): (1, 1), (7, 16, -1, 4): (1, 1), (7, 16, -1, 5): (1, 0), (7, 16, 0, -5): (-1, 1), (7, 16, 0, -4): (-1, 1), (7, 16, 0, -3): (-1, 1), (7, 16, 0, -2): (-1, 1), (7, 16, 0, -1): (1, 1), (7, 16, 0, 0): (1, 1), (7, 16, 0, 1): (0, 1), (7, 16, 0, 2): (0, 1), (7, 16, 0, 3): (0, 1), (7, 16, 0, 4): (0, 1), (7, 16, 0, 5): (0, 1), (7, 16, 1, -5): (1, 1), (7, 16, 1, -4): (1, 1), (7, 16, 1, -3): (1, 1), (7, 16, 1, -2): (1, 1), (7, 16, 1, -1): (0, 1), (7, 16, 1, 0): (0, 1), (7, 16, 1, 1): (-1, 1), (7, 16, 1, 2): (-1, 1), (7, 16, 1, 3): (-1, 1), (7, 16, 1, 4): (-1, 1), (7, 16, 1, 5): (-1, 1), (7, 16, 2, -5): (1, 1), (7, 16, 2, -4): (1, 1), (7, 16, 2, -3): (1, 1), (7, 16, 2, -2): (1, 1), (7, 16, 2, -1): (1, 1), (7, 16, 2, 0): (-1, 1), (7, 16, 2, 1): (-1, 1), (7, 16, 2, 2): (-1, 1), (7, 16, 2, 3): (-1, 1), (7, 16, 2, 4): (0, 1), (7, 16, 2, 5): (0, 1), (7, 16, 3, -5): (0, 1), (7, 16, 3, -4): (0, 1), (7, 16, 3, -3): (0, 1), (7, 16, 3, -2): (0, 1), (7, 16, 3, -1): (0, 1), (7, 16, 3, 0): (0, 1), (7, 16, 3, 1): (0, 1), (7, 16, 3, 2): (-1, 1), (7, 16, 3, 3): (-1, 1), (7, 16, 3, 4): (-1, 1), (7, 16, 3, 5): (-1, 1), (7, 16, 4, -5): (0, 1), (7, 16, 4, -4): (0, 1), (7, 16, 4, -3): (0, 1), (7, 16, 4, -2): (0, 1), (7, 16, 4, -1): (0, 1), (7, 16, 4, 0): (0, 1), (7, 16, 4, 1): (0, 1), (7, 16, 4, 2): (0, 0), (7, 16, 4, 3): (0, 1), (7, 16, 4, 4): (0, 1), (7, 16, 4, 5): (0, 1), (7, 16, 5, -5): (0, 1), (7, 16, 5, -4): (0, 1), (7, 16, 5, -3): (0, 1), (7, 16, 5, -2): (0, 1), (7, 16, 5, -1): (0, 1), (7, 16, 5, 0): (0, 1), (7, 16, 5, 1): (0, 1), (7, 16, 5, 2): (0, 0), (7, 16, 5, 3): (0, 1), (7, 16, 5, 4): (0, 1), (7, 16, 5, 5): (0, 1), (7, 17, -5, -5): (0, 1), (7, 17, -5, -4): (0, 1), (7, 17, -5, -3): (0, 1), (7, 17, -5, -2): (0, 1), (7, 17, -5, -1): (0, 1), (7, 17, -5, 0): (0, 1), (7, 17, -5, 1): (0, 0), (7, 17, -5, 2): (0, 1), (7, 17, -5, 3): (0, 1), (7, 17, -5, 4): (0, 1), (7, 17, -5, 5): (0, 1), (7, 17, -4, -5): (0, 1), (7, 17, -4, -4): (0, 1), (7, 17, -4, -3): (0, 1), (7, 17, -4, -2): (0, 1), (7, 17, -4, -1): (0, 1), (7, 17, -4, 0): (0, 1), (7, 17, -4, 1): (0, 0), (7, 17, -4, 2): (0, 1), (7, 17, -4, 3): (0, 1), (7, 17, -4, 4): (0, 1), (7, 17, -4, 5): (0, 1), (7, 17, -3, -5): (0, 1), (7, 17, -3, -4): (0, 1), (7, 17, -3, -3): (0, 1), (7, 17, -3, -2): (0, 1), (7, 17, -3, -1): (0, 1), (7, 17, -3, 0): (0, 1), (7, 17, -3, 1): (0, 0), (7, 17, -3, 2): (0, 1), (7, 17, -3, 3): (0, 1), (7, 17, -3, 4): (0, 1), (7, 17, -3, 5): (0, 1), (7, 17, -2, -5): (0, 1), (7, 17, -2, -4): (0, 1), (7, 17, -2, -3): (0, 1), (7, 17, -2, -2): (0, 1), (7, 17, -2, -1): (0, 1), (7, 17, -2, 0): (0, 1), (7, 17, -2, 1): (1, 1), (7, 17, -2, 2): (1, 1), (7, 17, -2, 3): (1, 1), (7, 17, -2, 4): (1, 1), (7, 17, -2, 5): (1, 0), (7,
# Copyright 2019 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 # # https://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. # Lint as: python2, python3 """Quasi Monte Carlo support: Halton sequence.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow as tf from tf_quant_finance.math.random_ops import stateless __all__ = [ 'sample', ] # The maximum dimension we support. This is limited by the number of primes # in the _PRIMES array. _MAX_DIMENSION = 1000 # The maximum sequence index we support, depending on data type. _MAX_INDEX_BY_DTYPE = {tf.float32: 2**24 - 1, tf.float64: 2**53 - 1} # The number of coefficients we use to represent each Halton number when # expressed in the (prime) base for an event dimension. In theory this should be # infinite, but in practice it is useful to cap this based on data type. _NUM_COEFFS_BY_DTYPE = {tf.float32: 24, tf.float64: 54} # Parameters that can be reused with subsequent calls to halton.sample(). HaltonParams = collections.namedtuple( 'HaltonParams', [ 'perms', # Uniform iid sample from the space of permutations as # returned by _get_permutations() below. A tensor of shape # [_MAX_SIZES_BY_AXES[dtype], sum(_PRIMES)] and dtype # tf.float32 or tf.float64. 'zero_correction', # A scaled uniform random tensor of shape # [dim] and dtype tf.float32 or tf.float64. Used to # appropriately adjust the randomization described # in Owen (2017), see below for further details. ]) def sample(dim, num_results=None, sequence_indices=None, randomized=True, randomization_params=None, seed=None, validate_args=False, dtype=None, name=None): r"""Returns a sample from the `dim` dimensional Halton sequence. Warning: The sequence elements take values only between 0 and 1. Care must be taken to appropriately transform the domain of a function if it differs from the unit cube before evaluating integrals using Halton samples. It is also important to remember that quasi-random numbers without randomization are not a replacement for pseudo-random numbers in every context. Quasi random numbers are completely deterministic and typically have significant negative autocorrelation unless randomization is used. Computes the members of the low discrepancy Halton sequence in dimension `dim`. The `dim`-dimensional sequence takes values in the unit hypercube in `dim` dimensions. Currently, only dimensions up to 1000 are supported. The prime base for the k-th axes is the k-th prime starting from 2. For example, if `dim` = 3, then the bases will be [2, 3, 5] respectively and the first element of the non-randomized sequence will be: [0.5, 0.333, 0.2]. For a more complete description of the Halton sequences see [here](https://en.wikipedia.org/wiki/Halton_sequence). For low discrepancy sequences and their applications see [here](https://en.wikipedia.org/wiki/Low-discrepancy_sequence). If `randomized` is true, this function produces a scrambled version of the Halton sequence introduced by [Owen (2017)][1]. For the advantages of randomization of low discrepancy sequences see [here]( https://en.wikipedia.org/wiki/Quasi-Monte_Carlo_method#Randomization_of_quasi-Monte_Carlo). The number of samples produced is controlled by the `num_results` and `sequence_indices` parameters. The user must supply either `num_results` or `sequence_indices` but not both. The former is the number of samples to produce starting from the first element. If `sequence_indices` is given instead, the specified elements of the sequence are generated. For example, sequence_indices=tf.range(10) is equivalent to specifying n=10. #### Examples ```python import tensorflow as tf import tensorflow_probability as tfp # Produce the first 1000 members of the Halton sequence in 3 dimensions. num_results = 1000 dim = 3 sample, params = qmc.halton.sample( dim, num_results=num_results, seed=127) # Evaluate the integral of x_1 * x_2^2 * x_3^3 over the three dimensional # hypercube. powers = tf.range(1.0, limit=dim + 1) integral = tf.reduce_mean(tf.reduce_prod(sample ** powers, axis=-1)) true_value = 1.0 / tf.reduce_prod(powers + 1.0) with tf.Session() as session: values = session.run((integral, true_value)) # Produces a relative absolute error of 1.7%. print ("Estimated: %f, True Value: %f" % values) # Now skip the first 1000 samples and recompute the integral with the next # thousand samples. The sequence_indices argument can be used to do this. sequence_indices = tf.range(start=1000, limit=1000 + num_results, dtype=tf.int32) sample_leaped, _ = qmc.halton.sample( dim, sequence_indices=sequence_indices, randomization_params=params) integral_leaped = tf.reduce_mean(tf.reduce_prod(sample_leaped ** powers, axis=-1)) with tf.Session() as session: values = session.run((integral_leaped, true_value)) # Now produces a relative absolute error of 0.05%. print ("Leaped Estimated: %f, True Value: %f" % values) ``` Args: dim: Positive Python `int` representing each sample's `event_size.` Must not be greater than 1000. num_results: (Optional) Positive scalar `Tensor` of dtype int32. The number of samples to generate. Either this parameter or sequence_indices must be specified but not both. If this parameter is None, then the behaviour is determined by the `sequence_indices`. Default value: `None`. sequence_indices: (Optional) `Tensor` of dtype int32 and rank 1. The elements of the sequence to compute specified by their position in the sequence. The entries index into the Halton sequence starting with 0 and hence, must be whole numbers. For example, sequence_indices=[0, 5, 6] will produce the first, sixth and seventh elements of the sequence. If this parameter is None, then the `num_results` parameter must be specified which gives the number of desired samples starting from the first sample. Default value: `None`. randomized: (Optional) bool indicating whether to produce a randomized Halton sequence. If True, applies the randomization described in [Owen (2017)][1]. If True, either seed or randomization_params must be specified. This is because the randomization uses stateless random number generation which requires an explicitly specified seed. Default value: `True`. randomization_params: (Optional) Instance of `HaltonParams` that fully describes the randomization behavior. If provided and randomized is True, seed will be ignored and these will be used instead of computing them from scratch. If randomized is False, this parameter has no effect. Default value: `None`. In this case with randomized = True, the necessary randomization parameters will be computed from scratch. seed: (Optional) Python integer to seed the random number generator. Must be specified if `randomized` is True and randomization_params is not specified. Ignored if randomized is False or randomization_params is specified. Default value: `None`. validate_args: If True, checks that maximum index is not exceeded. Default value: `False`. dtype: Optional `dtype`. The dtype of the output `Tensor` (either `float32` or `float64`). Default value: `None` which maps to the `float32`. name: (Optional) Python `str` describing ops managed by this function. If not supplied the name of this function is used. Default value: "halton_sample". Returns: halton_elements: Elements of the Halton sequence. `Tensor` of supplied dtype and `shape` `[num_results, dim]` if `num_results` was specified or shape `[s, dim]` where s is the size of `sequence_indices` if `sequence_indices` were specified. randomization_params: None if randomized is False. If randomized is True and randomization_params was supplied as an argument, returns that. Otherwise returns the computed randomization_params, an instance of `HaltonParams` that fully describes the randomization behavior. Raises: ValueError: if both `sequence_indices` and `num_results` were specified or if dimension `dim` is less than 1 or greater than 1000. ValueError: if `randomization` is True but `seed` is not specified. InvalidArgumentError: if `validate_args` is True and the maximum supported sequence index is exceeded. #### References [1]: <NAME>. A randomized Halton algorithm in R. _arXiv preprint arXiv:1706.02808_, 2017. https://arxiv.org/abs/1706.02808 """ if dim < 1 or dim > _MAX_DIMENSION: raise ValueError('Dimension must be between 1 and {}. Supplied {}'.format( _MAX_DIMENSION, dim)) if (num_results is None) == (sequence_indices is None): raise ValueError('Either `num_results` or `sequence_indices` must be' ' specified but not both.') dtype = dtype or tf.float32 if not dtype.is_floating: raise ValueError('dtype must be of `float`-type') with tf.compat.v1.name_scope( name, 'halton_sample', values=[num_results, sequence_indices]): # Here and in the following, the shape layout is as follows: # [sample dimension, event dimension, coefficient dimension]. # The coefficient dimension is an intermediate axes which will hold the # weights of the starting integer when
# -*- coding: utf-8 -*- from __future__ import division import numpy as np from .constants import SSO from .conversions import t_from_CT, CT_from_t from ..utilities import match_args_return __all__ = ['brineSA_CT', 'brineSA_t', 'CT_freezing', 't_freezing'] # Constants: c = (0.017947064327968736, -6.076099099929818, 4.883198653547851, -11.88081601230542, 13.34658511480257, -8.722761043208607, 2.082038908808201, -7.389420998107497, -2.110913185058476, 0.2295491578006229, -0.9891538123307282, -0.08987150128406496, 0.3831132432071728, 1.054318231187074, 1.065556599652796, -0.7997496801694032, 0.3850133554097069, -2.078616693017569, 0.8756340772729538, -2.079022768390933, 1.596435439942262, 0.1338002171109174, 1.242891021876471) T = (0.002519, -5.946302841607319, 4.136051661346983, -1.115150523403847e1, 1.476878746184548e1, -1.088873263630961e1, 2.961018839640730, -7.433320943962606, -1.561578562479883, 4.073774363480365e-2, 1.158414435887717e-2, -4.122639292422863e-1, -1.123186915628260e-1, 5.715012685553502e-1, 2.021682115652684e-1, 4.140574258089767e-2, -6.034228641903586e-1, -1.205825928146808e-2, -2.812172968619369e-1, 1.877244474023750e-2, -1.204395563789007e-1, 2.349147739749606e-1, 2.748444541144219e-3) # Adjust for the effects of dissolved air. Note that # a = 0.502500117621 / 35.16504 a, b = 0.014289763856964, 0.057000649899720 P = (2.570124672768757e-1, -1.917742353032266e+1, -1.413382858617969e-2, -5.427484830917552e-1, -4.126621135193472e-4, -4.176407833276121e-7, 4.688217641883641e-5, -3.039808885885726e-8, -4.990118091261456e-11, -9.733920711119464e-9, -7.723324202726337e-12, 7.121854166249257e-16, 1.256474634100811e-12, 2.105103897918125e-15, 8.663811778227171e-19) @match_args_return def brineSA_CT(CT, p, saturation_fraction=1): """ Calculates the Absolute Salinity of seawater at the freezing temperature. That is, the output is the Absolute Salinity of seawater, with the fraction saturation_fraction of dissolved air, that is in equilibrium with ice at Conservative Temperature CT and pressure p. If the input values are such that there is no positive value of Absolute Salinity for which seawater is frozen, the output, brineSA_CT, is put equal to -99. Parameters ---------- CT : array_like Conservative Temperature [:math:`^\circ` C (ITS-90)] p : array_like sea pressure [dbar] saturation_fraction : fraction between 0, 1. The saturation fraction of dissolved air in seawater. Default is 0 or completely saturated. Returns ------- brine_SA_CT : array_like Absolute Salinity of seawater when it freezes [ g/kg ] Examples -------- TODO References ---------- .. [1] IOC, SCOR and IAPSO, 2010: The international thermodynamic equation of seawater - 2010: Calculation and use of thermodynamic properties. Intergovernmental Oceanographic Commission, Manuals and Guides No. 56, UNESCO (English), 196 pp. See sections 3.33. """ CT, p, saturation_fraction = np.broadcast_arrays(CT, p, saturation_fraction, subok=True) if np.logical_or(saturation_fraction < 0, saturation_fraction > 1).any(): raise ValueError('Saturation_fraction MUST be between zero and one.') p_r = p * 1e-4 # Form the first estimate of brine_SA_CT from a polynomial in CT and p_r. SA = -(CT + 9 * p_r) / 0.06 # A rough estimate to get the saturated CT. SA = np.maximum(SA, 0) CTsat = (CT - (1 - saturation_fraction) * 1e-3 * (2.4 - a * SA) * (1 + b * (1 - SA / SSO))) SA = (P[0] + p * (P[2] + P[4] * CTsat + p * (P[5] + CTsat * (P[7] + P[9] * CTsat) + p * (P[8] + CTsat * (P[10] + P[12] * CTsat) + p * (P[11] + P[13] * CTsat + P[14] * p)))) + CTsat * (P[1] + CTsat * (P[3] + P[6] * p))) CT_freezing_zero_SA = (c[0] + p_r * (c[7] + p_r * (c[8] + c[9] * p_r)) - saturation_fraction * 2.4e-3 * (1 + b)) # Find CT > CT_freezing_zero_SA. If this is the case, the input values # represent seawater that is not frozen (at any positive SA). Itw = (CT > CT_freezing_zero_SA) # tw stands for "too warm" SA[Itw] = np.ma.masked # Find -SA_cut_off < SA < SA_cut_off, replace the above estimate of SA # with one based on (CT_freezing_zero_SA - CT). SA_cut_off = 2.5 # This is the band of SA within +- 2.5 g/kg of SA = 0, # which we treat differently in calculating the initial # values of both SA and dCT_dSA. Ico = (np.abs(SA) < SA_cut_off) Icoa = np.logical_and(SA < 0, SA >= -SA_cut_off) SA[Icoa] = 0 # Find SA < -SA_cut_off, set them to NaN. SA[SA < -SA_cut_off] = np.ma.masked # Form the first estimate of dCT_dSA, the derivative of CT with respect # to SA at fixed p. SA_r = 0.01 * SA x = np.sqrt(SA_r) dCT_dSA_part = (2 * c[1] + x * (3 * c[2] + x * (4 * c[3] + x * (5 * c[4] + x * (6 * c[5] + 7 * c[6] * x)))) + p_r * (2 * c[10] + p_r * (2 * c[12] + p_r * (2 * c[15] + 4 * c[21] * x * x)) + x * x * (4 * c[13] + 4 * c[17] * p_r + 6 * c[19] * x * x) + x * (3 * c[11] + 3 * p_r * (c[14] + c[18] * p_r) + x * x * (5 * c[16] + 5 * c[20] * p_r + 7 * c[22] * x * x)))) dCT_dSA = 0.5 * 0.01 * dCT_dSA_part - saturation_fraction * 1e-3 * (-a * (1 + b * (1 - SA / SSO)) - b * (2.4 - a * SA) / SSO) # Now replace the estimate of SA with the one based on # (CT_freezing_zero_SA - CT) when (np.abs(SA) < SA_cut_off). SA[Ico] = (CT[Ico] - CT_freezing_zero_SA[Ico]) / dCT_dSA[Ico] # Begin the modified Newton-Raphson method to solve the root of # CT_freezing = CT for SA. Number_of_Iterations = 2 for I_iter in range(0, Number_of_Iterations): # CT_freezing temperature function evaluation (the forward function # evaluation), the same as CT_freezing(SA, p, saturation_fraction). SA_r = 0.01 * SA x = np.sqrt(SA_r) SA_old = SA CT_freeze = (c[0] + SA_r * (c[1] + x * (c[2] + x * (c[3] + x * (c[4] + x * (c[5] + c[6] * x))))) + p_r * (c[7] + p_r * (c[8] + c[9] * p_r)) + SA_r * p_r * (c[10] + p_r * (c[12] + p_r * (c[15] + c[21] * SA_r)) + SA_r * (c[13] + c[17] * p_r + c[19] * SA_r) + x * (c[11] + p_r * (c[14] + c[18] * p_r) + SA_r * (c[16] + c[20] * p_r + c[22] * SA_r))) - saturation_fraction * 1e-3 * (2.4 - a * SA) * (1 + b * (1 - SA / SSO))) SA = SA_old - (CT_freeze - CT) / dCT_dSA # Half-way point of the modified Newton-Raphson solution method. SA_r = 0.5 * 0.01 * (SA + SA_old) # The mean value of SA and SA_old. x = np.sqrt(SA_r) dCT_dSA_part = 2 * c[1] + x * (3 * c[2] + x * (4 * c[3] + x * (5 * c[4] + x * (6 * c[5] + 7 * c[6] * x)))) + p_r * (2 * c[10] + p_r * (2 * c[12] + p_r * (2 * c[15] + 4 * c[21] * x * x)) + x * x * (4 * c[13] + 4 * c[17] * p_r + 6 * c[19] * x * x) + x * (3 * c[11] + 3 * p_r * (c[14] + c[18] * p_r) + x * x * (5 * c[16] + 5 * c[20] * p_r + 7 * c[22] * x * x))) dCT_dSA = (0.5 * 0.01 * dCT_dSA_part - saturation_fraction * 1e-3 * (-a * (1 + b * (1 - SA / SSO)) - b * (2.4 - a * SA) / SSO)) SA = SA_old - (CT_freeze - CT) / dCT_dSA # The following lines of code, if implemented, calculates the error of # this function in terms of Conservative Temperature, CT_error. With # Number_of_Iterations = 1, the maximum error in CT is 2x10^-7 C. With # Number_of_Iterations = 2, the maximum error in CT is 7x10^-15 C, which is # the machine precision of the computer. Number_of_Iterations = 2 is what # we recommend. # # SA_r = 0.01 * SA # x = np.sqrt(SA_r) # CT_freeze = c[0] + SA_r * (c[1] + x * (c[2] + x * (c[3] + x * (c[4] + x * # (c[5] + c[6] * x))))) + p_r * (c[7] + p_r * (c[8] + c[9] * # p_r)) + SA_r * p_r * (c[10] + p_r * (c[12] + p_r * (c[15] + # c[21] * SA_r)) + SA_r
# Copyright 2020 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """Learning rate schedule.""" import math from ..common import dtype as mstype from ..ops import operations as P from .cell import Cell from .._checkparam import Validator as validator class LearningRateSchedule(Cell): """Basic class of learning rate schedule.""" def __init__(self): super(LearningRateSchedule, self).__init__() def construct(self, global_step): """ Defines the computation to get the current learning rate. This method must be overridden by all subclasses. Note: The output must be a Tensor of scalar. Inputs: - **global_step** (Tensor) - The current step number. Inputs: Tensor. Learning rate at current step with shape :math:`()`. """ raise NotImplementedError def _check_inputs(learning_rate, decay_rate, decay_steps, is_stair, cls_name): validator.check_positive_int(decay_steps, 'decay_steps', cls_name) validator.check_positive_float(learning_rate, 'learning_rate', cls_name) validator.check_is_float(learning_rate, 'learning_rate', cls_name) validator.check_positive_float(decay_rate, 'decay_rate', cls_name) validator.check_is_float(decay_rate, 'decay_rate', cls_name) validator.check_value_type('is_stair', is_stair, [bool], cls_name) class ExponentialDecayLR(LearningRateSchedule): r""" Calculates learning rate based on exponential decay function. For the i-th step, the formula of computing decayed_learning_rate[i] is: .. math:: decayed\_learning\_rate[i] = learning\_rate * decay\_rate^{p} Where : .. math:: p = \frac{current\_step}{decay\_steps} If `is_stair` is True, the formula is : .. math:: p = floor(\frac{current\_step}{decay\_steps}) Args: learning_rate (float): The initial value of learning rate. decay_rate (float): The decay rate. decay_steps (int): A value used to calculate decayed learning rate. is_stair (bool): If true, learning rate is decayed once every `decay_steps` time. Default: False. Inputs: - **global_step** (Tensor) - The current step number. Outputs: Tensor. The learning rate value for the current step with shape :math:`()`. Raises: TypeError: If `learning_rate` or `decay_rate` is not a float. TypeError: If `decay_steps` is not an int or `is_stair` is not a bool. ValueError: If `decay_steps` is less than 1. ValueError: If `learning_rate` or `decay_rate` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> learning_rate = 0.1 >>> decay_rate = 0.9 >>> decay_steps = 4 >>> global_step = Tensor(2, mstype.int32) >>> exponential_decay_lr = nn.ExponentialDecayLR(learning_rate, decay_rate, decay_steps) >>> result = exponential_decay_lr(global_step) >>> print(result) 0.09486833 """ def __init__(self, learning_rate, decay_rate, decay_steps, is_stair=False): super(ExponentialDecayLR, self).__init__() _check_inputs(learning_rate, decay_rate, decay_steps, is_stair, self.cls_name) self.learning_rate = learning_rate self.decay_rate = decay_rate self.decay_steps = decay_steps self.is_stair = is_stair self.pow = P.Pow() self.cast = P.Cast() def construct(self, global_step): p = self.cast(global_step, mstype.float32) / self.decay_steps if self.is_stair: p = P.Floor()(p) return self.learning_rate * self.pow(self.decay_rate, p) class NaturalExpDecayLR(LearningRateSchedule): r""" Calculates learning rate base on natural exponential decay function. For the i-th step, the formula of computing decayed_learning_rate[i] is: .. math:: decayed\_learning\_rate[i] = learning\_rate * e^{-decay\_rate * p} Where : .. math:: p = \frac{current\_step}{decay\_steps} If `is_stair` is True, the formula is : .. math:: p = floor(\frac{current\_step}{decay\_steps}) Args: learning_rate (float): The initial value of learning rate. decay_rate (float): The decay rate. decay_steps (int): A value used to calculate decayed learning rate. is_stair (bool): If true, learning rate is decayed once every `decay_steps` time. Default: False. Inputs: - **global_step** (Tensor) - The current step number. Outputs: Tensor. The learning rate value for the current step with shape :math:`()`. Raises: TypeError: If `learning_rate` or `decay_rate` is not a float. TypeError: If `decay_steps` is not an int or `is_stair` is not a bool. ValueError: If `decay_steps` is less than 1. ValueError: If `learning_rate` or `decay_rate` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> learning_rate = 0.1 >>> decay_rate = 0.9 >>> decay_steps = 4 >>> global_step = Tensor(2, mstype.int32) >>> natural_exp_decay_lr = nn.NaturalExpDecayLR(learning_rate, decay_rate, decay_steps, True) >>> result = natural_exp_decay_lr(global_step) >>> print(result) 0.1 """ def __init__(self, learning_rate, decay_rate, decay_steps, is_stair=False): super(NaturalExpDecayLR, self).__init__() _check_inputs(learning_rate, decay_rate, decay_steps, is_stair, self.cls_name) self.learning_rate = learning_rate self.decay_rate = decay_rate self.decay_steps = decay_steps self.is_stair = is_stair self.math_e = math.e self.pow = P.Pow() self.cast = P.Cast() def construct(self, global_step): p = self.cast(global_step, mstype.float32) if self.is_stair: p = P.FloorDiv()(p, self.decay_steps) * self.decay_steps return self.learning_rate * self.pow(self.math_e, -self.decay_rate * p) class InverseDecayLR(LearningRateSchedule): r""" Calculates learning rate base on inverse-time decay function. For the i-th step, the formula of computing decayed_learning_rate[i] is: .. math:: decayed\_learning\_rate[i] = learning\_rate / (1 + decay\_rate * p) Where : .. math:: p = \frac{current\_step}{decay\_steps} If `is_stair` is True, The formula is : .. math:: p = floor(\frac{current\_step}{decay\_steps}) Args: learning_rate (float): The initial value of learning rate. decay_rate (float): The decay rate. decay_steps (int): A value used to calculate decayed learning rate. is_stair (bool): If true, learning rate decay once every `decay_steps` times. Default: False. Inputs: - **global_step** (Tensor) - The current step number. Outputs: Tensor. The learning rate value for the current step with shape :math:`()`. Raises: TypeError: If `learning_rate` or `decay_rate` is not a float. TypeError: If `decay_steps` is not an int or `is_stair` is not a bool. ValueError: If `decay_steps` is less than 1. ValueError: If `learning_rate` or `decay_rate` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> learning_rate = 0.1 >>> decay_rate = 0.9 >>> decay_steps = 4 >>> global_step = Tensor(2, mstype.int32) >>> inverse_decay_lr = nn.InverseDecayLR(learning_rate, decay_rate, decay_steps, True) >>> result = inverse_decay_lr(global_step) >>> print(result) 0.1 """ def __init__(self, learning_rate, decay_rate, decay_steps, is_stair=False): super(InverseDecayLR, self).__init__() _check_inputs(learning_rate, decay_rate, decay_steps, is_stair, self.cls_name) self.learning_rate = learning_rate self.decay_rate = decay_rate self.decay_steps = decay_steps self.is_stair = is_stair self.cast = P.Cast() def construct(self, global_step): p = self.cast(global_step, mstype.float32) / self.decay_steps if self.is_stair: p = P.Floor()(p) return self.learning_rate / (1 + self.decay_rate * p) class CosineDecayLR(LearningRateSchedule): r""" Calculates learning rate based on cosine decay function. For the i-th step, the formula of computing decayed_learning_rate[i] is: .. math:: decayed\_learning\_rate[i] = min\_learning\_rate + 0.5 * (max\_learning\_rate - min\_learning\_rate) * (1 + cos(\frac{current\_step}{decay\_steps}\pi)) Args: min_lr (float): The minimum value of learning rate. max_lr (float): The maximum value of learning rate. decay_steps (int): A value used to calculate decayed learning rate. Inputs: - **global_step** (Tensor) - The current step number. Outputs: Tensor. The learning rate value for the current step with shape :math:`()`. Raises: TypeError: If `min_lr` or `max_lr` is not a float. TypeError: If `decay_steps` is not an int. ValueError: If `min_lr` is less than 0 or `decay_steps` is less than 1. ValueError: If `max_lr` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> min_lr = 0.01 >>> max_lr = 0.1 >>> decay_steps = 4 >>> global_steps = Tensor(2, mstype.int32) >>> cosine_decay_lr = nn.CosineDecayLR(min_lr, max_lr, decay_steps) >>> result = cosine_decay_lr(global_steps) >>> print(result) 0.055 """ def __init__(self, min_lr, max_lr, decay_steps): super(CosineDecayLR, self).__init__() if not isinstance(min_lr, float): raise TypeError("The min_lr must be float.") validator.check_non_negative_float(min_lr, "min_lr", self.cls_name) validator.check_positive_float(max_lr, 'max_lr', self.cls_name) validator.check_is_float(max_lr, 'max_lr', self.cls_name) validator.check_positive_int(decay_steps, "decay_steps", self.cls_name) if min_lr >= max_lr: raise ValueError('The `max_lr` should be greater than the `min_lr`.') self.min_lr = min_lr self.max_lr = max_lr self.decay_steps = decay_steps self.math_pi = math.pi self.delta = 0.5 * (max_lr - min_lr) self.cos = P.Cos() self.min = P.Minimum() self.cast = P.Cast() def construct(self, global_step): p = self.cast(self.min(global_step, self.decay_steps), mstype.float32) return self.min_lr + self.delta * (1.0 + self.cos(self.math_pi * p / self.decay_steps)) class PolynomialDecayLR(LearningRateSchedule): r""" Calculates learning rate base on polynomial decay function. For the i-th step, the formula of computing decayed_learning_rate[i] is: .. math:: decayed\_learning\_rate[i] = (learning\_rate - end\_learning\_rate) * (1 - tmp\_step / tmp\_decay\_steps)^{power} + end\_learning\_rate Where : .. math:: tmp\_step=min(current\_step, decay\_steps) If `update_decay_steps` is true, update the value of `tmp_decay_step` every `decay_steps`. The formula is : .. math:: tmp\_decay\_steps = decay\_steps * ceil(current\_step / decay\_steps) Args: learning_rate (float): The initial value of learning rate. end_learning_rate (float): The end value of learning rate. decay_steps (int): A value used to calculate decayed learning rate. power (float): A value used to calculate decayed learning rate. This parameter must be greater than 0. update_decay_steps (bool): If true, learning
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as AddressProvider class Provider(AddressProvider): street_prefixes = ('Av', 'Avenida', 'R.', 'Rua', 'Travessa', 'Largo') city_formats = ('{{city_name}}',) street_name_formats = ( '{{street_prefix}} {{last_name}}', '{{street_prefix}} {{first_name}} {{last_name}}', '{{street_prefix}} de {{last_name}}', ) street_address_formats = ( '{{street_name}}, {{building_number}}', ) address_formats = ( "{{street_address}}\n{{postcode}} {{city}}", ) building_number_formats = ('S/N', '%', '%#', '%#', '%#', '%##') postcode_formats = ('####-###',) cities = ( 'Abrantes', 'Agualva-Cacém', 'Albufeira', 'Alcobaça', 'Alcácer do Sal', 'Almada', 'Almeirim', 'Alverca do Ribatejo', 'Amadora', 'Amarante', 'Amora', 'Anadia', 'Angra do Heroísmo', 'Aveiro', 'Barcelos', 'Barreiro', 'Beja', 'Braga', 'Bragança', 'Caldas da Rainha', 'Caniço', 'Cantanhede', 'Cartaxo', 'Castelo Branco', 'Chaves', 'Coimbra', 'Costa da Caparica', 'Covilhã', 'Câmara de Lobos', 'Elvas', 'Entroncamento', 'Ermesinde', 'Esmoriz', 'Espinho', 'Esposende', 'Estarreja', 'Estremoz', 'Fafe', 'Faro', 'Felgueiras', 'Figueira da Foz', 'Fiães', 'Freamunde', 'Funchal', 'Fundão', 'Fátima', 'Gafanha da Nazaré', 'Gandra', 'Gondomar', 'Gouveia', 'Guarda', 'Guimarães', 'Horta', 'Lagoa', 'Lagos', 'Lamego', 'Leiria', 'Lisboa', 'Lixa', 'Loulé', 'Loures', 'Lourosa', 'Macedo de Cavaleiros', 'Maia', 'Mangualde', 'Marco de Canaveses', 'Marinha Grande', 'Matosinhos', 'Mealhada', 'Miranda do Douro', 'Mirandela', 'Montemor-o-Novo', 'Montijo', 'Moura', 'Mêda', 'Odivelas', 'Olhão', 'Oliveira de Azeméis', 'Oliveira do Bairro', 'Oliveira do Hospital', 'Ourém', 'Ovar', 'Paredes', 'Paços de Ferreira', 'Penafiel', 'Peniche', 'Peso da Régua', 'Pinhel', 'Pombal', 'Ponta Delgada', 'Ponte de Sor', 'Portalegre', 'Portimão', 'Porto', 'Porto Santo', 'Praia da Vitória', 'Póvoa de Santa Iria', 'Póvoa de Varzim', 'Quarteira', 'Queluz', 'Rebordosa', 'Reguengos de Monsaraz', 'Ribeira Grande', 'Rio Maior', 'Rio Tinto', 'Sabugal', 'Sacavém', 'Santa Comba Dão', 'Santa Cruz', 'Santa Maria da Feira', 'Santana', 'Santarém', 'Santiago do Cacém', 'Santo Tirso', 'Seia', 'Seixal', 'Serpa', 'Setúbal', 'Silves', 'Sines', 'Sintra', 'São João da Madeira', 'São Mamede de Infesta', 'São Salvador de Lordelo', 'Tarouca', 'Tavira', 'Tomar', 'Tondela', 'Torres Novas', 'Torres Vedras', 'Trancoso', 'Trofa', 'Valbom', 'Vale de Cambra', 'Valongo', 'Valpaços', 'Vendas Novas', 'Viana do Castelo', 'Vila Franca de Xira', 'Vila Nova de Famalicão', 'Vila Nova de Foz Côa', 'Vila Nova de Gaia', 'Vila Nova de Santo André', 'Vila Real', 'Vila Real de Santo António', 'Vila do Conde', 'Viseu', 'Vizela', 'Évora', 'Ílhavo', ) countries = ( 'Afeganistão', 'África do Sul', 'Akrotiri', 'Albânia', 'Alemanha', 'Andorra', 'Angola', 'Anguila', 'Antárctida', 'Antígua e Barbuda', 'Antilhas Neerlandesas', 'Arábia Saudita', 'Arctic Ocean', 'Argélia', 'Argentina', 'Arménia', 'Aruba', 'Ashmore and Cartier Islands', 'Atlantic Ocean', 'Austrália', 'Áustria', 'Azerbaijão', 'Baamas', 'Bangladeche', 'Barbados', 'Barém', 'Bélgica', 'Belize', 'Benim', 'Bermudas', 'Bielorrússia', 'Birmânia', 'Bolívia', 'Bósnia e Herzegovina', 'Botsuana', 'Brasil', 'Brunei', 'Bulgária', 'Burquina Faso', 'Burúndi', 'Butão', 'Cabo Verde', 'Camarões', 'Camboja', 'Canadá', 'Catar', 'Cazaquistão', 'Chade', 'Chile', 'China', 'Chipre', 'Clipperton Island', 'Colômbia', 'Comores', 'Congo-Brazzaville', 'Congo-Kinshasa', 'Coral Sea Islands', 'Coreia do Norte', 'Coreia do Sul', 'Costa do Marfim', 'Costa Rica', 'Croácia', 'Cuba', 'Dhekelia', 'Dinamarca', 'Domínica', 'Egipto', 'Emiratos Árabes Unidos', 'Equador', 'Eritreia', 'Eslováquia', 'Eslovénia', 'Espanha', 'Estados Unidos', 'Estónia', 'Etiópia', 'Faroé', 'Fiji', 'Filipinas', 'Finlândia', 'França', 'Gabão', 'Gâmbia', 'Gana', 'Gaza Strip', 'Geórgia', 'Geórgia do Sul e Sandwich do Sul', 'Gibraltar', 'Granada', 'Grécia', 'Gronelândia', 'Guame', 'Guatemala', 'Guernsey', 'Guiana', 'Guiné', 'Guiné Equatorial', 'Guiné-Bissau', 'Haiti', 'Honduras', 'Hong Kong', 'Hungria', 'Iémen', 'Ilha Bouvet', 'Ilha do Natal', 'Ilha Norfolk', 'Ilhas Caimão', 'Ilhas Cook', 'Ilhas dos Cocos', 'Ilhas Falkland', 'Ilhas Heard e McDonald', 'Ilhas Marshall', 'Ilhas Salomão', 'Ilhas Turcas e Caicos', 'Ilhas Virgens Americanas', 'Ilhas Virgens Britânicas', 'Índia', 'Indian Ocean', 'Indonésia', 'Irão', 'Iraque', 'Irlanda', 'Islândia', 'Israel', 'Itália', 'Jamaica', 'Jan Mayen', 'Japão', 'Jersey', 'Jibuti', 'Jordânia', 'Kuwait', 'Laos', 'Lesoto', 'Letónia', 'Líbano', 'Libéria', 'Líbia', 'Listenstaine', 'Lituânia', 'Luxemburgo', 'Macau', 'Macedónia', 'Madagáscar', 'Malásia', 'Malávi', 'Maldivas', 'Mali', 'Malta', 'Man, Isle of', 'Marianas do Norte', 'Marrocos', 'Maurícia', 'Mauritânia', 'Mayotte', 'México', 'Micronésia', 'Moçambique', 'Moldávia', 'Mónaco', 'Mongólia', 'Monserrate', 'Montenegro', 'Mundo', 'Namíbia', 'Nauru', 'Navassa Island', 'Nepal', 'Nicarágua', 'Níger', 'Nigéria', 'Niue', 'Noruega', 'Nova Caledónia', 'Nova Zelândia', 'Omã', 'Pacific Ocean', 'Países Baixos', 'Palau', 'Panamá', 'Papua-Nova Guiné', 'Paquistão', 'Paracel Islands', 'Paraguai', 'Peru', 'Pitcairn', 'Polinésia Francesa', 'Polónia', 'Porto Rico', 'Portugal', 'Quénia', 'Quirguizistão', 'Quiribáti', 'Reino Unido', 'República Centro-Africana', 'República Checa', 'República Dominicana', 'Roménia', 'Ruanda', 'Rússia', 'Salvador', 'Samoa', 'Samoa Americana', 'Santa Helena', 'Santa Lúcia', 'São Cristóvão e Neves', 'São Marinho', 'São Pedro e Miquelon', 'São Tomé e Príncipe', 'São Vicente e Granadinas', 'Sara Ocidental', 'Seicheles', 'Senegal', 'Serra Leoa', 'Sérvia', 'Singapura', 'Síria', 'Somália', 'Southern Ocean', 'Spratly Islands', 'Sri Lanca', 'Suazilândia', 'Sudão', 'Suécia', 'Suíça', 'Suriname', 'Svalbard e Jan Mayen', 'Tailândia', 'Taiwan', 'Tajiquistão', 'Tanzânia', 'Território Britânico do Oceano Índico', 'Territórios Austrais Franceses', 'Timor Leste', 'Togo', 'Tokelau', 'Tonga', 'Trindade e Tobago', 'Tunísia', 'Turquemenistão', 'Turquia', 'Tuvalu', 'Ucrânia', 'Uganda', 'União Europeia', 'Uruguai', 'Usbequistão', 'Vanuatu', 'Vaticano', 'Venezuela', 'Vietname', 'Wake Island', 'Wallis e Futuna', 'West Bank', 'Zâmbia', 'Zimbabué', ) # From https://pt.wikipedia.org/wiki/Distritos_de_Portugal distritos = ( 'Aveiro', 'Beja', 'Braga', 'Bragança', 'Castelo Branco', 'Coimbra', 'Évora', 'Faro', 'Guarda', 'Leiria', 'Lisboa', 'Portalegre', 'Porto', 'Santarém', 'Setúbal', 'Viana do Castelo', 'Vila Real', 'Viseu', ) # From https://pt.wikipedia.org/wiki/Lista_de_concelhos_por_NUTS,_distritos_e_ilhas concelhos = ( "Águeda", "<NAME>", "Alandroal", "Albergaria-a-Velha", "Albufeira", "Alcácer do Sal", "Alcanena", "Alcobaça", "Alcochete", "Alcoutim", "Alenquer", "Alfândega da Fé", "Alijó", "Aljezur", "Aljustrel", "Almada", "Almeida", "Almeirim", "Almodôvar", "Alpiarça", "Alter do Chão", "Alvaiázere", "Alvito", "Amadora", "Amarante", "Amares", "Anadia", "Angra do Heroísmo", "Ansião", "Arcos de Valdevez", "Arganil", "Armamar", "Arouca", "Arraiolos", "Arronches", "Arruda dos Vinhos", "Aveiro", "Avis", "Azambuja", "Baião", "Barcelos", "Barrancos", "Barreiro", "Batalha", "Beja", "Belmonte", "Benavente", "Bombarral", "Borba", "Boticas", "Braga", "Bragança", "Cabeceiras de Basto", "Cadaval", "Caldas da Rainha", "Calheta (R.A.A.)", "Calheta (R.A.M.)", "Câmara de Lobos", "Caminha", "Campo Maior", "Cantanhede", "Carrazeda de Ansiães", "Carregal do Sal", "Cartaxo", "Cascais", "Castanheira de Pêra", "Castelo Branco", "Castelo de Paiva", "Castelo de Vide", "<NAME>", "<NAME>", "Castro Verde", "Celorico da Beira", "Celorico de Basto", "Chamusca", "Chaves", "Cinfães", "Coimbra", "Condeixa-a-Nova", "Constância", "Coruche", "Corvo", "Covilhã", "Crato", "Cuba", "Elvas", "Entroncamento", "Espinho", "Esposende", "Estarreja", "Estremoz", "Évora", "Fafe", "Faro", "Felgueiras", "Ferreira do Alentejo", "Ferreira do Zêzere", "Figueira da Foz", "Figueira de Castelo Rodrigo", "Figueiró dos Vinhos", "Fornos de Algodres", "Freixo de Espada à Cinta", "Fronteira", "Funchal", "Fundão", "Gavião", "Góis", "Golegã", "Gondomar", "Gouveia", "Grândola", "Guarda", "Guimarães", "Horta", "Idanha-a-Nova", "Ílhavo", "Lagoa", "Lagoa (R.A.A)", "Lagos", "Lajes das Flores", "Lajes do Pico", "Lamego", "Leiria", "Lisboa", "Loulé", "Loures", "Lourinhã", "Lousã", "Lousada", "Mação", "Mac<NAME> Cavaleiros", "Machico", "Madalena", "Mafra", "Maia", "Mangualde", "Manteigas", "Marco de Canaveses", "Marinha Grande", "Marvão", "Matosinhos", "Mealhada", "Meda", "Melgaço", "Mértola", "Mesão Frio", "Mira", "Mir<NAME>", "Miranda do Douro", "Mirandela", "Mogadouro", "Moimenta da Beira", "Moita", "Monção", "Monchique", "Mondim de Basto", "Monforte", "Montalegre", "Montemor-o-Novo", "Montemor-o-Velho", "Montijo", "Mora", "Mortágua", "Moura", "Mourão", "Murça", "Murtosa", "Nazaré", "Nelas", "Nisa", "Nordeste", "Óbidos", "Odemira", "Odivelas", "Oeiras", "Oleiros", "Olhão", "Oliveira de Azeméis", "Oliveira de Frades", "Oliveira do Bairro", "Oliveira do Hospital", "Ourém", "Ourique", "Ovar", "Paços de Ferreira", "Palmela", "Pampilhosa da Serra", "Paredes", "Paredes de Coura", "<NAME>", "Penacova", "Penafiel", "Penalva do Castelo", "Penamacor", "Penedono", "Penela", "Peniche", "Peso da Régua", "Pinhel", "Pombal", "Ponta Delgada", "Ponta do Sol", "Ponte da Barca", "Ponte de Lima", "Ponte de Sor", "Portalegre", "Portel", "Portimão", "Porto", "Porto de Mós", "Porto Moniz", "Porto Santo", "Povoação", "Póvoa de Lanhoso", "<NAME>", "Proença-a-Nova", "Redondo", "<NAME>", "Resende", "Ribeira Brava", "Ribeira de Pena", "Ribeira Grande", "<NAME>", "Sabrosa", "Sabugal", "Salvaterra de Magos", "Santa Comba Dão", "Santa Cruz", "Santa Cruz da Graciosa", "Santa Cruz das Flores", "Santa Maria da Feira", "Santa Marta de Penaguião", "Santana", "Santarém", "Santiago do Cacém", "Santo Tirso", "São Brás de Alportel", "São João da Madeira", "São João da Pesqueira", "São Pedro do Sul", "São Roque do Pico", "São Vicente", "Sardoal", "Sátão", "Seia", "Seixal", "Sernancelhe", "Serpa", "Sertã", "Sesimbra", "Setúbal", "Sever do Vouga", "Silves", "Sines", "Sintra", "Sobral de Monte Agraço", "Soure", "Sousel", "Tábua", "Tabuaço", "Tarouca", "Tavira", "Terras de Bouro", "Tomar", "Tondela", "Torre de Moncorvo", "Torres Novas", "Torres Vedras", "Trancoso", "Trofa", "Vagos", "Vale de Cambra", "Valença", "Valongo", "Valpaços", "Velas", "Vendas Novas", "V<NAME> Alentejo", "V<NAME>", "Vidigueira", "Vieira do Minho", "Vila da Praia da Vitória", "Vila de Rei", "Vila do Bispo", "Vila do Conde", "Vila do Porto", "Vila Flor", "Vila Franca de Xira", "Vila Franca do Campo", "Vila Nova da Barquinha", "Vila Nova de Cerveira", "Vila Nova de Famalicão", "Vila Nova de Foz Côa", "Vila Nova de Gaia", "Vila Nova de Paiva", "Vila Nova de Poiares", "Vila Pouca de Aguiar", "Vila Real", "Vila Real de Santo António", "Vila Velha de Ródão", "Vila Verde", "Vila Viçosa", "Vimioso", "Vinhais", "Viseu", "Vizela", "Vouzela", ) # From https://pt.wikipedia.org/wiki/Lista_de_freguesias_de_Portugal freguesias = [ "Abrantes", "Águeda", "<NAME>", "Alandroal", "Albergaria-a-Velha", "Albufeira", "Alcácer do Sal", "Alcanena", "Alcobaça", "Alcochete", "Alcoutim", "Alenquer", "Alfândega da Fé", "Alijó", "Aljezur", "Aljustrel", "Almada", "Almeida", "Almeirim", "Almodôvar", "Alpiarça", "Alter do Chão", "Alvaiázere", "Alvito", "Amadora", "Amarante",
import sys import unittest import importlib import asn1tools sys.path.append('tests/files') sys.path.append('tests/files/3gpp') sys.path.append('tests/files/cen') sys.path.append('tests/files/etsi') sys.path.append('tests/files/ieee') sys.path.append('tests/files/ietf') sys.path.append('tests/files/oma') class Asn1ToolsParseTest(unittest.TestCase): maxDiff = None def parse_and_verify(self, module, path='.'): asn_path = 'tests/files/' + path + '/' + module + '.asn' actual = asn1tools.parse_files(asn_path) # from pprint import pformat # # py_path = 'tests/files/' + path + '/' + module + '.py' # # with open(py_path, 'w') as fout: # fout.write('EXPECTED = ' + pformat(actual)) module = importlib.import_module(module) self.assertEqual(actual, module.EXPECTED) def test_parse_foo(self): self.parse_and_verify('foo') def test_parse_bar(self): self.parse_and_verify('bar') def test_parse_all_types(self): self.parse_and_verify('all_types') def test_parse_extensibility_implied(self): self.parse_and_verify('extensibility_implied') def test_parse_all_types_automatic_tags(self): self.parse_and_verify('all_types_automatic_tags') def test_parse_module_tags_explicit(self): self.parse_and_verify('module_tags_explicit') def test_parse_module_tags_implicit(self): self.parse_and_verify('module_tags_implicit') def test_parse_module_tags_automatic(self): self.parse_and_verify('module_tags_automatic') def test_parse_information_object(self): self.parse_and_verify('information_object') def test_parse_x683(self): self.parse_and_verify('x683') def test_parse_x680(self): self.parse_and_verify('x680') def test_parse_x691_a1(self): self.parse_and_verify('x691_a1') def test_parse_x691_a2(self): self.parse_and_verify('x691_a2') def test_parse_x691_a3(self): self.parse_and_verify('x691_a3') def test_parse_x691_a4(self): self.parse_and_verify('x691_a4') def test_parse_zforce(self): self.parse_and_verify('zforce') def test_parse_rrc_8_6_0(self): self.parse_and_verify('rrc_8_6_0', '3gpp') def test_parse_rrc_14_4_0(self): self.parse_and_verify('rrc_14_4_0', '3gpp') def test_parse_s1ap_14_4_0(self): self.parse_and_verify('s1ap_14_4_0', '3gpp') def test_parse_lpp_14_3_0(self): self.parse_and_verify('lpp_14_3_0', '3gpp') def test_parse_rfc1155(self): self.parse_and_verify('rfc1155', 'ietf') def test_parse_rfc1157(self): self.parse_and_verify('rfc1157', 'ietf') def test_parse_rfc2986(self): self.parse_and_verify('rfc2986', 'ietf') def test_parse_rfc3161(self): self.parse_and_verify('rfc3161', 'ietf') def test_parse_rfc3279(self): self.parse_and_verify('rfc3279', 'ietf') def test_parse_rfc3281(self): self.parse_and_verify('rfc3281', 'ietf') def test_parse_rfc3447(self): self.parse_and_verify('rfc3447', 'ietf') def test_parse_rfc3852(self): self.parse_and_verify('rfc3852', 'ietf') def test_parse_rfc4210(self): self.parse_and_verify('rfc4210', 'ietf') def test_parse_rfc4211(self): self.parse_and_verify('rfc4211', 'ietf') def test_parse_rfc4511(self): self.parse_and_verify('rfc4511', 'ietf') def test_parse_rfc5084(self): self.parse_and_verify('rfc5084', 'ietf') def test_parse_rfc5280(self): self.parse_and_verify('rfc5280', 'ietf') def test_parse_rfc5280_modified(self): self.parse_and_verify('rfc5280_modified', 'ietf') def test_parse_etsi_cam_pdu_descriptions_1_3_2(self): self.parse_and_verify('cam_pdu_descriptions_1_3_2', 'etsi') def test_parse_etsi_its_container_1_2_1(self): self.parse_and_verify('its_container_1_2_1', 'etsi') def test_parse_etsi_mapem_2_1_1(self): self.parse_and_verify('mapem_2_1_1', 'etsi') def test_parse_cen_dsrc(self): self.parse_and_verify('dsrc', 'cen') def test_parse_ieee_1609_2(self): self.parse_and_verify('ieee1609_2', 'ieee') def test_parse_oma_ulp(self): self.parse_and_verify('ulp', 'oma') def test_parse_enumerated(self): self.parse_and_verify('enumerated') def test_parse_comments(self): self.parse_and_verify('comments') def test_parse_constraints_extensions(self): self.parse_and_verify('constraints_extensions') def test_parse_time_types(self): self.parse_and_verify('time_types') def test_parse_named_numbers(self): self.parse_and_verify('named_numbers') def test_parse_import_imported(self): self.parse_and_verify('import_imported') def test_parse_parameterization(self): self.parse_and_verify('parameterization') def test_parse_imports_global_module_reference(self): actual = asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'IMPORTS ' 'a FROM B ' 'c, d FROM E global-module-reference ' 'f, g FROM H {iso(1)}; ' 'END') expected = { 'A': { 'extensibility-implied': False, 'imports': { 'B': ['a'], 'E': ['c', 'd'], 'H': ['f', 'g'] }, 'object-classes': {}, 'object-sets': {}, 'types': {}, 'values': {} } } self.assertEqual(actual, expected) def test_parse_imports_single_value_reference(self): """Test that a value reference, in this test 'c', is not parsed as an assignmed identifier, but an imported value from 'D'. """ actual = asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'IMPORTS ' 'A FROM B ' 'c FROM D; ' 'END') expected = { 'A': { 'extensibility-implied': False, 'imports': { 'B': ['A'], 'D': ['c'] }, 'object-classes': {}, 'object-sets': {}, 'types': {}, 'values': {} } } self.assertEqual(actual, expected) def test_parse_empty_imports(self): actual = asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'IMPORTS ; ' 'END') expected = { 'A': { 'extensibility-implied': False, 'imports': {}, 'object-classes': {}, 'object-sets': {}, 'types': {}, 'values': {} } } self.assertEqual(actual, expected) def test_parse_keyword_in_type_name(self): actual = asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'ENDa ::= INTEGER ' 'END') expected = { 'A': { 'extensibility-implied': False, 'imports': {}, 'object-classes': {}, 'object-sets': {}, 'types': {'ENDa': {'type': 'INTEGER'}}, 'values': {} } } self.assertEqual(actual, expected) def test_parse_error_empty_string(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('') self.assertEqual(str(cm.exception), "Invalid ASN.1 syntax at line 1, column 1: '>!<': " "Expected modulereference.") def test_parse_error_begin_missing(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= END') self.assertEqual(str(cm.exception), "Invalid ASN.1 syntax at line 1, column 19: " "'A DEFINITIONS ::= >!<END': Expected BEGIN.") def test_parse_error_end_missing(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN') self.assertEqual(str(cm.exception), "Invalid ASN.1 syntax at line 1, column 24: " "'A DEFINITIONS ::= BEGIN>!<': Expected END.") def test_parse_error_type_assignment_missing_assignment(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN A END') self.assertEqual(str(cm.exception), "Invalid ASN.1 syntax at line 1, column 27: " "'A DEFINITIONS ::= BEGIN A >!<END': " "Expected ::=.") def test_parse_error_value_assignment_missing_assignment(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN a INTEGER END') self.assertEqual(str(cm.exception), "Invalid ASN.1 syntax at line 1, column 35: " "'A DEFINITIONS ::= BEGIN a INTEGER >!<END': " "Expected ::=.") def test_parse_error_sequence_missing_type(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN' ' A ::= SEQUENCE { a } ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 45: 'A DEFINITIONS ::= BEGIN " " A ::= SEQUENCE { a >!<} END': Expected Type.") def test_parse_error_sequence_missing_member_name(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN' ' A ::= SEQUENCE { A } ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 43: 'A DEFINITIONS ::= " "BEGIN A ::= SEQUENCE { >!<A } END': Expected \"}\".") def test_parse_error_definitive_identifier(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A {} DEFINITIONS ::= BEGIN ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 4: 'A {>!<} DEFINITIONS " "::= BEGIN END': Expected {{identifier Suppress:(\"(\") - " "definitiveNumberForm - Suppress:(\")\")} | identifier | " "definitiveNumberForm}.") def test_parse_error_missing_union_member_beginning(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= INTEGER (| SIZE (1))' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 40: 'A DEFINITIONS ::= BEGIN " "B ::= INTEGER (>!<| SIZE (1))END': Expected one or more constraints.") def test_parse_error_missing_union_member_middle(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= INTEGER (SIZE (1) | | (0))' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 49: \'A DEFINITIONS " "::= BEGIN B ::= INTEGER (SIZE (1) >!<| | (0))END\': Expected \")\".") def test_parse_error_missing_union_member_end(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= INTEGER (SIZE (1) |)' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 49: \'A DEFINITIONS " "::= BEGIN B ::= INTEGER (SIZE (1) >!<|)END\': Expected \")\".") def test_parse_error_size_constraint_missing_parentheses(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= INTEGER (SIZE 1)' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 45: \'A DEFINITIONS ::= " "BEGIN B ::= INTEGER (SIZE >!<1)END\': Expected \"(\".") def test_parse_error_size_constraint_missing_size(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= INTEGER (SIZE ())' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 46: 'A DEFINITIONS ::= " "BEGIN B ::= INTEGER (SIZE (>!<))END': Expected one or more " "constraints.") def test_parse_error_tag_class_number_missing(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= [] INTEGER ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 32: 'A DEFINITIONS " "::= BEGIN B ::= [>!<] INTEGER END': Expected ClassNumber.") def test_parse_error_missing_type(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'B ::= ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 31: 'A DEFINITIONS ::= BEGIN " "B ::= >!<END': Expected Type.") def test_parse_error_end_missing_with_comments(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS -- g -- \n' '-- hhhh\n' '::= BEGIN ') self.assertEqual(str(cm.exception), "Invalid ASN.1 syntax at line 3, column 11: " "'::= BEGIN >!<': Expected END.") def test_parse_error_late_extension_additions(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'Foo ::= SEQUENCE { ' 'a BOOLEAN, ' '..., ' '..., ' '[[ ' 'c BOOLEAN ' ']] ' '} ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 63: \'A DEFINITIONS ::= " "BEGIN Foo ::= SEQUENCE { a BOOLEAN, ..., ...>!<, [[ c BOOLEAN ]] " "} END\': Expected \"}\".") def test_parse_error_too_many_extension_markers(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= BEGIN ' 'Foo ::= SEQUENCE { ' 'a BOOLEAN, ' '..., ' '[[ ' 'b BOOLEAN ' ']], ' '[[ ' 'c BOOLEAN ' ']], ' '..., ' 'd BOOLEAN, ' '... ' '} ' 'END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 1, column 108: \'A DEFINITIONS ::= " "BEGIN Foo ::= SEQUENCE { a BOOLEAN, ..., [[ b BOOLEAN ]], [[ c " "BOOLEAN ]], ..., d BOOLEAN>!<, ... } END\': Expected \"}\".") def test_parse_error_missing_single_line_comment_end(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= \n' 'BEGIN -- END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 2, column 7: 'BEGIN >!<-- END': " "Missing newline or -- for single line comment.") def test_parse_error_missing_multi_line_comment_end(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= \n' 'BEGIN /* END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 2, column 7: 'BEGIN >!</* END': " "Missing */ for multi line comment.") def test_parse_error_multi_line_comment_overlapping(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.parse_string('A DEFINITIONS ::= \n' 'BEGIN /*/ END') self.assertEqual( str(cm.exception), "Invalid ASN.1 syntax at line 2, column 7: 'BEGIN >!</*/ END': " "Missing */ for multi line comment.") def test_parse_x680_duplicated_enum_number_a_c_0(self): with self.assertRaises(asn1tools.ParseError) as cm: asn1tools.compile_string('A DEFINITIONS ::= BEGIN ' 'E ::= ENUMERATED { a, b, ..., c(0) }
import math import os import sys import numpy as np import torch import torch.nn.functional as F from scipy.sparse import csr_matrix, diags, identity from scipy.sparse import hstack as sparse_hstack from scipy import interpolate from torch import nn from torch.nn.modules.loss import _WeightedLoss from torch.utils.data import DataLoader, Dataset from torchinfo import summary import gc try: from utils_ft import * except: from libs.utils_ft import * import matplotlib.pyplot as plt class BurgersDataset(Dataset): def __init__(self, subsample: int, n_grid_fine=2**13, viscosity: float = 0.1, n_krylov: int = 2, smoother=None, uniform: bool = True, train_data=True, train_portion=0.9, valid_portion=0.1, super_resolution: int = 1, data_path=None, online_features=False, return_edge=False, renormalization=False, return_distance_features=True, return_mass_features=False, return_downsample_grid: bool = True, random_sampling=False, random_state=1127802, debug=False): r''' PyTorch dataset overhauled for Burger's data from Li et al 2020 https://github.com/zongyi-li/fourier_neural_operator FNO1d network size n_hidden = 64, 16 modes: 549569 Benchmark: error \approx 1e-2 after 100 epochs after subsampling to 512 subsampling = 2**3 #subsampling rate h = 2**13 // sub #total grid size divided by the subsampling rate Periodic BC Uniform: - node: f sampled at uniform grid - pos: uniform grid, pos encoding - targets: [targets, targets derivative] ''' self.data_path = data_path if subsample > 1: assert subsample % 2 == 0 self.subsample = subsample self.super_resolution = super_resolution self.supsample = subsample//super_resolution self.n_grid_fine = n_grid_fine # finest resolution self.n_grid = n_grid_fine // subsample self.h = 1/n_grid_fine self.uniform = uniform self.return_downsample_grid = return_downsample_grid self.train_data = train_data self.train_portion = train_portion self.valid_portion = valid_portion self.n_krylov = n_krylov self.viscosity = viscosity self.smoother = smoother self.random_sampling = random_sampling self.random_state = random_state self.online_features = online_features self.edge_features = None # failsafe self.mass_features = None self.return_edge = return_edge # whether to do Kipf-Weiling renormalization A += I self.renormalization = renormalization self.return_mass_features = return_mass_features self.return_distance_features = return_distance_features self.debug = debug self._set_seed() self._initialize() def __len__(self): return self.n_samples def _initialize(self): data = 'train' if self.train_data else 'valid' with timer(f"Loading {self.data_path.split('/')[-1]} for {data}."): data = loadmat(self.data_path) x_data = data['a'] y_data = data['u'] del data gc.collect() train_len, valid_len = self.train_test_split(len(x_data)) if self.train_data: x_data, y_data = x_data[:train_len], y_data[:train_len] else: x_data, y_data = x_data[-valid_len:], y_data[-valid_len:] self.n_samples = len(x_data) get_data = self.get_uniform_data if self.uniform else self.get_nonuniform_data grid, grid_fine, nodes, targets = get_data(x_data, y_data) if not self.online_features and self.return_edge: edge_features = [] mass_features = [] for i in tqdm(range(self.n_samples)): edge, mass = self.get_edge(grid) edge_features.append(edge) mass_features.append(mass) self.edge_features = np.asarray(edge_features, dtype=np.float32) self.mass_features = np.asarray(mass_features, dtype=np.float32) self.node_features = nodes[..., None] if nodes.ndim == 2 else nodes # self.pos = np.c_[grid[...,None], grid[...,None]] #(N, S, 2) self.n_features = self.node_features.shape[-1] self.pos = grid[..., None] if self.uniform else grid self.pos_fine = grid_fine[..., None] self.target = targets[..., None] if targets.ndim == 2 else targets def _set_seed(self): s = self.random_state os.environ['PYTHONHASHSEED'] = str(s) np.random.seed(s) torch.manual_seed(s) def get_uniform_data(self, x_data, y_data): targets = y_data targets_diff = self.central_diff(targets, self.h) if self.super_resolution >= 2: nodes = x_data[:, ::self.supsample] targets = targets[:, ::self.supsample] targets_diff = targets_diff[:, ::self.supsample] else: nodes = x_data[:, ::self.subsample] targets = targets[:, ::self.subsample] targets_diff = targets_diff[:, ::self.subsample] targets = np.stack([targets, targets_diff], axis=2) grid = np.linspace(0, 1, self.n_grid) # subsampled # grids = np.asarray([grid for _ in range(self.n_samples)]) grid_fine = np.linspace(0, 1, self.n_grid_fine//self.supsample) return grid, grid_fine, nodes, targets @staticmethod def central_diff(x, h): # x: (batch, seq_len, feats) # x: (seq_len, feats) # x: (seq_len, ) # padding is one before feeding to this function # TODO: change the pad to u (u padded with the other end b/c periodicity) if x.ndim == 1: pad_0, pad_1 = x[-2], x[1] # pad periodic x = np.c_[pad_0, x, pad_1] # left center right x_diff = (x[2:] - x[:-2])/2 elif x.ndim == 2: pad_0, pad_1 = x[:, -2], x[:, 1] x = np.c_[pad_0, x, pad_1] x_diff = (x[:, 2:] - x[:, :-2])/2 # pad = np.zeros(x_diff.shape[0]) # return np.c_[pad, x_diff/h, pad] return x_diff/h @staticmethod def laplacian_1d(x, h): # standard [1, -2, 1] stencil x_lap = (x[1:-1] - x[:-2]) - (x[2:] - x[1:-1]) # return np.r_[0, x_lap/h**2, 0] return x_lap/h**2 def train_test_split(self, len_data): # TODO: change this to random split if self.train_portion <= 1: train_len = int(self.train_portion*len_data) elif 1 < self.train_portion <= len_data: train_len = self.train_portion else: train_len = int(0.8*len_data) if self.valid_portion <= 1: valid_len = int(self.valid_portion*len_data) elif 1 < self.valid_portion <= len_data: valid_len = self.valid_portion else: valid_len = int(0.1*len_data) try: assert train_len <= len_data - valid_len, \ f"train len {train_len} be non-overlapping with test len {valid_len}" except AssertionError as err: print(err) return train_len, valid_len def get_nonuniform_data(self, x_data, y_data): ''' generate non-uniform data for each sample same number of points, but uniformly random chosen out: - x_data assimilated by u first. deprecated ''' targets_u = y_data x0, xn = 0, 1 n_nodes = self.n_grid h = self.h grid_u = np.linspace(x0, xn, n_nodes) grids_u = np.asarray([grid_u for _ in range(self.n_samples)]) pad_0, pad_n = y_data[:, 0], y_data[:, -1] targets_u_diff = self.central_diff(np.c_[pad_0, y_data, pad_n], h) grids, nodes, targets, targets_diff = [], [], [], [] # mesh, function, [solution, solution uniform], derivative for i in tqdm(range(self.n_samples)): node_fine = x_data[i] # all 8192 function value f _node_fine = np.r_[0, node_fine, 0] # padding node_fine_diff = self.central_diff(_node_fine, h) node_fine_lap = self.laplacian_1d(_node_fine, h) sampling_density = np.sqrt( node_fine_diff**2 + self.viscosity*node_fine_lap**2) # sampling_density = np.sqrt(node_fine_lap**2) sampling_density = sampling_density[1:-1] sampling_density /= sampling_density.sum() grid, ix, ix_fine = self.get_grid(sampling_density) grids.append(grid) node = x_data[i, ix] # coarse grid target, target_diff = y_data[i, ix_fine], targets_u_diff[i, ix_fine] nodes.append(node) targets.append(target) targets_diff.append(target_diff) if self.super_resolution >= 2: nodes_u = x_data[:, ::self.supsample] targets_u = y_data[:, ::self.supsample] targets_u_diff = targets_u_diff[:, ::self.supsample] else: nodes_u = x_data[:, ::self.subsample] targets_u = y_data[:, ::self.subsample] targets_u_diff = targets_u_diff[:, ::self.subsample] grids = np.asarray(grids) nodes = np.asarray(nodes) targets = np.asarray(targets) targets_diff = np.asarray(targets_diff) ''' target[...,0] = target_u: u on uniform grid target[...,1] = targets_u_diff: Du on uniform grid target[...,2] = target: u target[...,3] = targets_diff: Du last dim is for reference target[...,4] = nodes_u: f on uniform grid ''' targets = np.stack( [targets_u, targets_u_diff, targets, targets_diff, nodes_u], axis=2) return grids, grids_u, nodes, targets def get_grid(self, sampling_density): x0, xn = 0, 1 sampling_density = None if self.random_sampling else sampling_density ix_fine = np.sort(np.random.choice(range(1, self.n_grid_fine-1), size=self.super_resolution*self.n_grid-2, replace=False, p=sampling_density)) ix_fine = np.r_[0, ix_fine, self.n_grid_fine-1] ix = ix_fine[::self.super_resolution] grid = self.h*ix[1:-1] grid = np.r_[x0, grid, xn] ix = np.r_[0, ix[1:-1], self.n_grid_fine-1] return grid, ix, ix_fine def get_edge(self, grid): ''' generate edge features ''' # mass lumping weight = np.asarray([self.n_grid for _ in range( self.n_grid)]) if self.renormalization else None edge = get_laplacian_1d(grid, normalize=True, weight=weight, smoother=self.smoother).toarray().astype(np.float32) if self.n_krylov > 1: dim = edge.shape # (S, S) dim += (self.n_krylov, ) # (S, S, N_krylov) edges = np.zeros(dim) edges[..., 0] = edge for i in range(1, self.n_krylov): edges[..., i] = edge.dot(edges[..., i-1]) else: edges = edge[..., None] distance = get_distance_matrix(grid, graph=False) mass = get_mass_1d(grid, normalize=False).toarray().astype(np.float32) if self.return_mass_features and self.return_distance_features: mass = mass[..., None] edges = np.concatenate([edges, distance, mass], axis=2) elif self.return_distance_features: edges = np.concatenate([edges, distance], axis=2) return edges, mass def __getitem__(self, index): ''' Outputs: - pos: coords - x: rhs - target: solution ''' pos_dim = 1 if self.uniform else 2 if self.uniform: pos = self.pos[:, :pos_dim] else: pos = self.pos[index, :, :pos_dim] grid = pos[..., 0] if self.online_features: edge = get_laplacian_1d( grid, normalize=True).toarray().astype(np.float32) if self.n_krylov > 1: dim = edge.shape dim += (self.n_krylov, ) edges = np.zeros(dim) edges[..., 0] = edge for i in range(1, self.n_krylov): edges[..., i] = edge.dot(edges[..., i-1]) else: edges = edge[..., np.newaxis] distance = get_distance_matrix(grid, graph=False) mass = get_mass_1d( grid, normalize=False).toarray().astype(np.float32) if self.return_distance_features: edges = np.concatenate([edges, distance], axis=2) edge_features = torch.from_numpy(edges) mass = torch.from_numpy(mass) elif not self.online_features and self.return_edge: edge_features = torch.from_numpy(self.edge_features[index]) mass = torch.from_numpy(self.mass_features[index]) else: edge_features = torch.tensor([1.0]) mass = torch.tensor([1.0]) if self.return_downsample_grid: self.pos_fine = grid[..., None] pos_fine = torch.from_numpy(self.pos_fine) pos = torch.from_numpy(grid[..., None]) node_features = torch.from_numpy(self.node_features[index]) target = torch.from_numpy(self.target[index]) return dict(node=node_features.float(), pos=pos.float(), grid=pos_fine.float(), edge=edge_features.float(), mass=mass.float(), target=target.float(),) class UnitGaussianNormalizer: def __init__(self, eps=1e-5): super(UnitGaussianNormalizer, self).__init__() ''' modified from utils3.py in https://github.com/zongyi-li/fourier_neural_operator Changes: - .to() has a return to polymorph the torch behavior - naming convention changed to sklearn scalers ''' self.eps = eps def fit_transform(self, x): self.mean = x.mean(0) self.std = x.std(0) return (x - self.mean) / (self.std + self.eps) def transform(self, x): return (x - self.mean) / (self.std +
<reponame>cydenix/OpenGLCffi<gh_stars>0 DEF = ''' typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; typedef signed char khronos_int8_t; typedef unsigned char khronos_uint8_t; typedef signed short int khronos_int16_t; typedef unsigned short int khronos_uint16_t; typedef signed long int khronos_intptr_t; typedef unsigned long int khronos_uintptr_t; typedef signed long int khronos_ssize_t; typedef unsigned long int khronos_usize_t; typedef float khronos_float_t; typedef khronos_uint64_t khronos_utime_nanoseconds_t; typedef khronos_int64_t khronos_stime_nanoseconds_t; typedef khronos_int8_t GLbyte; typedef khronos_uint8_t GLubyte; typedef khronos_float_t GLfloat; typedef khronos_float_t GLclampf; typedef khronos_int32_t GLfixed; typedef khronos_int64_t GLint64; typedef khronos_uint64_t GLuint64; typedef khronos_int64_t GLint64EXT; typedef khronos_uint64_t GLuint64EXT; typedef khronos_intptr_t GLintptr; typedef khronos_ssize_t GLsizeiptr; typedef unsigned int GLenum; typedef unsigned char GLboolean; typedef unsigned int GLbitfield; typedef void GLvoid; typedef short GLshort; typedef int GLint; typedef int GLclampx; typedef unsigned short GLushort; typedef unsigned int GLuint; typedef int GLsizei; typedef double GLdouble; typedef double GLclampd; typedef void *GLeglImageOES; typedef char GLchar; typedef char GLcharARB; typedef unsigned short GLhalfARB; typedef unsigned short GLhalf; typedef ptrdiff_t GLintptrARB; typedef ptrdiff_t GLsizeiptrARB; typedef struct __GLsync *GLsync; struct _cl_context; struct _cl_event; typedef void (GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); typedef unsigned short GLhalfNV; typedef GLintptr GLvdpauSurfaceNV; typedef unsigned int GLhandleARB; void glStencilMaskSeparate(GLenum face, GLuint mask); void glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); void glTextureStorage3DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); void glGetProgramPipelineivEXT(GLuint pipeline, GLenum pname, GLint *params); void glPathGlyphsNV(GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); void glEndPerfMonitorAMD(GLuint monitor); void glCoverStrokePathInstancedNV(GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); void glUniform2ui64NV(GLint location, GLuint64EXT x, GLuint64EXT y); void glColorMaskiEXT(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); GLboolean glIsBuffer(GLuint buffer); void glGetMultisamplefv(GLenum pname, GLuint index, GLfloat *val); void glProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); void glProgramUniform4fEXT(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); void glCoverStrokePathNV(GLuint path, GLenum coverMode); void glDebugMessageControl(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); void glProgramUniform4iEXT(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); void glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); void glGetInternalformatSampleivNV(GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); void glProgramUniform2fEXT(GLuint program, GLint location, GLfloat v0, GLfloat v1); void glProgramUniform3f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); void glObjectPtrLabelKHR(const void *ptr, GLsizei length, const GLchar *label); void glFramebufferTextureLayerDownsampleIMG(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale); void glResumeTransformFeedback(); void glPathCommandsNV(GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); void glInsertEventMarkerEXT(GLsizei length, const GLchar *marker); void glCopyImageSubDataEXT(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); void glDepthRangeArrayfvNV(GLuint first, GLsizei count, const GLfloat *v); void glProgramUniformMatrix3x4fvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLenum glGetGraphicsResetStatus(); void glVertexAttrib1fv(GLuint index, const GLfloat *v); GLboolean glIsEnabled(GLenum cap); void glStencilOp(GLenum fail, GLenum zfail, GLenum zpass); void glProgramUniform2i64vNV(GLuint program, GLint location, GLsizei count, const GLint64EXT *value); void glGenFramebuffers(GLsizei n, GLuint *framebuffers); void glClearTexSubImageEXT(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); void glGetAttachedShaders(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); void glDeleteVertexArrays(GLsizei n, const GLuint *arrays); void glGetPathColorGenfvNV(GLenum color, GLenum pname, GLfloat *value); void glGetPointerv(GLenum pname, void **params); void glGetUniformfv(GLuint program, GLint location, GLfloat *params); void glGetUniformuiv(GLuint program, GLint location, GLuint *params); void glProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); void glSelectPerfMonitorCountersAMD(GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint *params); void glProgramPathFragmentInputGenNV(GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); GLsync glFenceSync(GLenum condition, GLbitfield flags); GLboolean glUnmapBufferOES(GLenum target); void glGetQueryObjecti64vEXT(GLuint id, GLenum pname, GLint64 *params); void glProgramUniform4uiEXT(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); void glValidateProgramPipeline(GLuint pipeline); void glStencilStrokePathInstancedNV(GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); void glProgramUniform2i64NV(GLuint program, GLint location, GLint64EXT x, GLint64EXT y); void glGenSamplers(GLsizei count, GLuint *samplers); void glStencilThenCoverStrokePathNV(GLuint path, GLint reference, GLuint mask, GLenum coverMode); void glGetTexParameterIuiv(GLenum target, GLenum pname, GLuint *params); GLboolean glIsSync(GLsync sync); void glGetObjectPtrLabel(const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); void glMatrixLoadTranspose3x3fNV(GLenum matrixMode, const GLfloat *m); void glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); void glProgramUniformMatrix2x4fvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); void glDrawElementsBaseVertexEXT(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); void glPathParameterivNV(GLuint path, GLenum pname, const GLint *value); void glUniform4uiv(GLint location, GLsizei count, const GLuint *value); void glGetIntegeri_vEXT(GLenum target, GLuint index, GLint *data); void glPathStencilFuncNV(GLenum func, GLint ref, GLuint mask); void glTextureViewOES(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); void glInvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); void glGetQueryObjectivEXT(GLuint id, GLenum pname, GLint *params); void glDeleteSync(GLsync sync); GLboolean glIsImageHandleResidentNV(GLuint64 handle); void glUniform3iv(GLint location, GLsizei count, const GLint *value); void glUseProgram(GLuint program); void glGetProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); void glProgramUniformMatrix3x2fvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); void glBindFragDataLocationEXT(GLuint program, GLuint color, const GLchar *name); void glGetBooleanv(GLenum pname, GLboolean *data); void glDeleteShader(GLuint shader); void glEnableiOES(GLenum target, GLuint index); void glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); void glTexParameterf(GLenum target, GLenum pname, GLfloat param); void glVertexAttribBinding(GLuint attribindex, GLuint bindingindex); void glTexParameteri(GLenum target, GLenum pname, GLint param); void glGetShaderSource(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); void glFramebufferSampleLocationsfvNV(GLenum target, GLuint start, GLsizei count, const GLfloat *v); void glGetNextPerfQueryIdINTEL(GLuint queryId, GLuint *nextQueryId); void glGetPathCoordsNV(GLuint path, GLfloat *coords); void glGenProgramPipelines(GLsizei n, GLuint *pipelines); void glVertexAttrib3fv(GLuint index, const GLfloat *v); void glLinkProgram(GLuint program); void glGetObjectLabel(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); const GLubyte * glGetString(GLenum name); void glGetPathParameterfvNV(GLuint path, GLenum pname, GLfloat *value); void glExtGetShadersQCOM(GLuint *shaders, GLint maxShaders, GLint *numShaders); void glEndQuery(GLenum target); GLboolean glIsQueryEXT(GLuint id); void glFramebufferParameteri(GLenum target, GLenum pname, GLint param); void glDeleteTextures(GLsizei n, const GLuint *textures); void glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); void glSamplerParameteri(GLuint sampler, GLenum pname, GLint param); void glViewportArrayvNV(GLuint first, GLsizei count, const GLfloat *v); void glGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); void glUniform1i(GLint location, GLint v0); void glCullFace(GLenum mode); void glProgramUniform4i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); void glProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GLboolean glPointAlongPathNV(GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); void glAttachShader(GLuint program, GLuint shader); void glDisableiEXT(GLenum target, GLuint index); void glGetBufferParameteriv(GLenum target, GLenum pname, GLint *params); void glTexParameterIuiv(GLenum target, GLenum pname, const GLuint *params); void glGetQueryObjectuivEXT(GLuint id, GLenum pname, GLuint *params); void glDeletePathsNV(GLuint path, GLsizei range); void glGetnUniformfvKHR(GLuint program, GLint location, GLsizei bufSize, GLfloat *params); void glProgramUniform1iEXT(GLuint program, GLint location, GLint v0); void glTexBufferRangeOES(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); GLboolean glIsTransformFeedback(GLuint id); void glGetObjectLabelEXT(GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); void glUniformHandleui64vNV(GLint location, GLsizei count, const GLuint64 *value); GLboolean glIsProgramPipeline(GLuint pipeline); void glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); void glGetnUniformfv(GLuint program, GLint location, GLsizei bufSize, GLfloat *params); void glFramebufferPixelLocalStorageSizeEXT(GLuint target, GLsizei size); void glStencilFunc(GLenum func, GLint ref, GLuint mask); void glUniformMatrix4x2fvNV(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); void glGetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint *params); void glDispatchComputeIndirect(GLintptr indirect); void glGetShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); void glVertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w); void glRenderbufferStorageMultisampleNV(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); void glUniformHandleui64NV(GLint location, GLuint64 value); void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha); void glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image); void glCompressedTexSubImage3DOES(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); void glBlitFramebufferNV(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); void glBeginPerfQueryINTEL(GLuint queryHandle); void glProgramUniform1uivEXT(GLuint program, GLint location, GLsizei count, const GLuint *value); void glDeleteBuffers(GLsizei n, const GLuint *buffers); void glBindProgramPipeline(GLuint pipeline); void glScissor(GLint x, GLint y, GLsizei width, GLsizei height); void glGetSamplerParameterIuivEXT(GLuint sampler, GLenum pname, GLuint *params); void glProgramUniform4i64NV(GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); void glProgramUniform4uivEXT(GLuint program, GLint location, GLsizei count, const GLuint *value); const GLubyte * glGetStringi(GLenum name, GLuint index); void glGetTexParameterIivOES(GLenum target, GLenum pname, GLint *params); void glUniform2fv(GLint location,
the inner product between two vectors with the (False, 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=(False, 'maintain')) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_false_true(self): """Test the inner product between two vectors with the (False, True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=(False, True)) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_maintain_false(self): """Test the inner product between two vectors with the ('maintain', False) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=('maintain', False)) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_maintain_maintain(self): """Test the inner product between two vectors with the ('maintain', 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=('maintain', 'maintain')) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_maintain_true(self): """Test the inner product between two vectors with the ('maintain', True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=('maintain', True)) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_true_false(self): """Test the inner product between two vectors with the (True, False) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=(True, False)) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_true_maintain(self): """Test the inner product between two vectors with the (True, 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=(True, 'maintain')) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_vector_true_true(self): """Test the inner product between two vectors with the (True, True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) result = self.uniform_matrix.inner_product(self.vec1, self.vec2, normalized=(True, True)) self.assertAlmostEqual(expected_result, result, places=5) def test_inner_product_vector_corpus_default(self): """Test the inner product between a vector and a corpus with the default normalization.""" expected_result = 0.0 expected_result += 2 * 1.0 * 1 # government * s_{ij} * government expected_result += 2 * 0.5 * 1 # government * s_{ij} * holiday expected_result += 1 * 0.5 * 1 # denied * s_{ij} * government expected_result += 1 * 0.5 * 1 # denied * s_{ij} * holiday expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_false_maintain(self): """Test the inner product between a vector and a corpus with the (False, 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=(False, 'maintain')) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_false_true(self): """Test the inner product between a vector and a corpus with the (False, True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=(False, True)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_maintain_false(self): """Test the inner product between a vector and a corpus with the ('maintain', False) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=('maintain', False)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_maintain_maintain(self): """Test the inner product between a vector and a corpus with the ('maintain', 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=('maintain', 'maintain')) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_maintain_true(self): """Test the inner product between a vector and a corpus with the ('maintain', True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=('maintain', True)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_true_false(self): """Test the inner product between a vector and a corpus with the (True, False) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=(True, False)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_true_maintain(self): """Test the inner product between a vector and a corpus with the (True, 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=(True, 'maintain')) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_vector_corpus_true_true(self): """Test the inner product between a vector and a corpus with the (True, True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((1, 2), expected_result) result = self.uniform_matrix.inner_product(self.vec1, [self.vec2] * 2, normalized=(True, True)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_default(self): """Test the inner product between a corpus and a vector with the default normalization.""" expected_result = 0.0 expected_result += 2 * 1.0 * 1 # government * s_{ij} * government expected_result += 2 * 0.5 * 1 # government * s_{ij} * holiday expected_result += 1 * 0.5 * 1 # denied * s_{ij} * government expected_result += 1 * 0.5 * 1 # denied * s_{ij} * holiday expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_false_maintain(self): """Test the inner product between a corpus and a vector with the (False, 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=(False, 'maintain')) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_false_true(self): """Test the inner product between a corpus and a vector with the (False, True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=(False, True)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_maintain_false(self): """Test the inner product between a corpus and a vector with the ('maintain', False) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=('maintain', False)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_maintain_maintain(self): """Test the inner product between a corpus and a vector with the ('maintain', 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=('maintain', 'maintain')) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_maintain_true(self): """Test the inner product between a corpus and a vector with the ('maintain', True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=('maintain', True)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_true_false(self): """Test the inner product between a corpus and a vector with the (True, False) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=(True, False)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_true_maintain(self): """Test the inner product between a corpus and a vector with the (True, 'maintain') normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result *= math.sqrt(self.identity_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=(True, 'maintain')) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_vector_true_true(self): """Test the inner product between a corpus and a vector with the (True, True) normalization.""" expected_result = self.uniform_matrix.inner_product(self.vec1, self.vec2) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec1, self.vec1)) expected_result /= math.sqrt(self.uniform_matrix.inner_product(self.vec2, self.vec2)) expected_result = numpy.full((3, 1), expected_result) result = self.uniform_matrix.inner_product([self.vec1] * 3, self.vec2, normalized=(True, True)) self.assertTrue(isinstance(result, numpy.ndarray)) self.assertTrue(numpy.allclose(expected_result, result)) def test_inner_product_corpus_corpus_default(self): """Test the inner product between two corpora with the default normalization.""" expected_result = 0.0 expected_result += 2 * 1.0 * 1 # government * s_{ij} * government expected_result += 2 * 0.5 * 1 # government * s_{ij} * holiday expected_result += 1 * 0.5 * 1 # denied * s_{ij} * government expected_result += 1 * 0.5 * 1 # denied * s_{ij} * holiday expected_result = numpy.full((3,
import sys, os import params #This sets the path in our computer to where the eyetracker stuff is located #sys.path.append('/Users/Preetpal/desktop/ubc_4/experimenter_platform/modules') #sys.path.append('E\\Users\\admin\\Desktop\\experimenter_platform\\modules') sys.path.append(os.path.join(sys.path[0],'Modules')) sys.path.append(os.path.join(sys.path[0],'tobii_binder')) import os import datetime import time import tobii_research as tr import csv import numpy as np from tornado import gen import emdat_utils import ast import subprocess from application.backend.eye_tracker_class import * class TobiiControllerNewSdk: """ The singleton class used to communicate with Tobii eye tracker API: it initializes the eye tracker, stores the raw gaze data, so the detection components can compute the features they are responsible for, and it stores the EMDAT features computed over the whole execution of the platform. """ def __init__(self): """Initializes TobiiController instances keyword arguments None """ print("constructing eyetracker object") self.gazeData = [] self.eventData = [] self.datafile = None #Preetpal's code for fixation self.x = [] self.y = [] self.time = [] self.validity = [] self.pupilsize = [] self.pupilvelocity = [] self.head_distance = [] self.EndFixations = [] self.mouse_clicks = [] self.keyboard_clicks = [] #This contains the websocket to send data to be displayed on front end self.runOnlineFix = True # initialize communications self.aoi_ids = {} self.dpt_id = 0 # for computing pupil velocity self.last_pupil_left = -1 self.last_pupil_right = -1 self.LastTimestamp = -1 self.init_emdat_global_features() # Instantiate an eye tracker class corresponding to the EYETRACKER_TYPE determined inside the params.py file self.eye_tracker = globals()[EyeTrackerNames[params.EYETRACKER_TYPE].value]() print("constructed eyetracker object") ############################################################################ # activation methods ############################################################################ def activate(self): self.eye_tracker.activate(self) def startTracking(self): """Starts the collection of gaze data arguments None keyword arguments None returns None -- resets both self.gazeData and self.eventData, then sets TobiiTracker.on_gazedata as an event callback for self.eyetracker.events.OnGazeDataReceived and calls self.eyetracker.StartTracking() """ print("starting tracker") self.gazeData = [] self.eventData = [] #Preetpal's Code to initialize/empty arrays to be used in fixation algorithm self.x = [] self.y = [] self.time = [] self.validity = [] self.pupilsize = [] self.pupilvelocity = [] self.head_distance = [] self.mouse_clicks = [] self.keyboard_clicks = [] print("=================== SLEEPING =========================") time.sleep(1) print("=================== WOKE UP =========================") self.eye_tracker.start_tracking(self) def stopTracking(self): """Stops the collection of gaze data arguments None keyword arguments None returns None -- calls self.eyetracker.StopTracking(), then unsets TobiiTracker.on_gazedata as an event callback for self.eyetracker.events.OnGazeDataReceived, and calls TobiiTracker.flushData before resetting both self.gazeData and self.eventData """ self.eye_tracker.stop_tracking(self) #self.flushData() self.gazeData = [] self.EndFixations = [] #Preetpals code #Empty the arrays needed for fixation algorithm #May need to also empty the websocket set self.x = [] self.y = [] self.time = [] self.validity = [] self.pupilsize = [] self.pupilvelocity = [] self.head_distance = [] self.mouse_clicks = [] self.keyboard_clicks = [] self.aoi_ids = {} self.dpt_id = 0 def logFixations(self, user_id, task_id): """Log the recorded fixations for the current user and task arguments user_id ID of current user_id task_id ID of current task keyword arguments None returns None """ with open(str(params.LOG_PREFIX) + "_user_" + str(user_id) + "_task_"+str(task_id) + "_raw_fixations.csv", "wb") as f: f.write( "x,y,duration,start_time\n" ) # header for fix in self.EndFixations: f.write( ",".join([str(x) for x in fix])+"\n" ) def on_gazedata(self, gaze): """Adds new data point to the raw data arrays. If x, y coordinate data is not available, stores the coordinates for this datapoint as (-1280, -1024). Any other feature, if not available, is stored as -1. arguments error -- some Tobii error message, isn't used in function gaze -- Tobii gaze data struct keyword arguments None returns None -- appends gaze to self.gazeData list """ #Don't need raw gaze so this code is commented out #self.gazeData.append(gaze) #Below code is just print statements that are commented out ''' print gaze.keys() print 'Timestamp: ', gaze["device_time_stamp"] print 'LeftGazePoint2D: ', gaze["left_gaze_point_on_display_area"] print 'RightGazePoint2D: ', gaze["right_gaze_point_on_display_area"] print 'LeftEyePosition3D: ', gaze["left_gaze_point_in_user_coordinate_system"] print 'RightEyePosition3D', gaze["right_gaze_point_in_user_coordinate_system"] print 'LeftPupil: ', gaze["left_pupil_diameter"] print 'RightPupil: ', gaze["right_pupil_diameter"] print gaze["left_gaze_point_validity"] print gaze["right_gaze_point_validity"] ''' #Below code checks to see if the gaze data is valid. If it is valid then #we average the left and right. Else we use the valid eye. We are multiplying #by SCREEN_SIZE_X and SCREEN_SIZE_Y because those are the dimensions of the monitor and since #the gaze values returned are between 0 and 1 if ((gaze["left_gaze_point_on_display_area"][0] >= 0) & (gaze["right_gaze_point_on_display_area"][0] >= 0)): self.x.append(((gaze["left_gaze_point_on_display_area"][0] + gaze["right_gaze_point_on_display_area"][0])/2) * params.SCREEN_SIZE_X) self.y.append(((gaze["left_gaze_point_on_display_area"][1] + gaze["right_gaze_point_on_display_area"][1])/2) * params.SCREEN_SIZE_Y) elif (gaze["left_gaze_point_on_display_area"][0] >= 0): self.x.append(gaze["left_gaze_point_on_display_area"][0] * params.SCREEN_SIZE_X) self.y.append(gaze["left_gaze_point_on_display_area"][1] * params.SCREEN_SIZE_Y) elif (gaze["right_gaze_point_on_display_area"][0] >= 0): self.x.append(gaze["right_gaze_point_on_display_area"][0] * params.SCREEN_SIZE_X) self.y.append(gaze["right_gaze_point_on_display_area"][1] * params.SCREEN_SIZE_Y) else: self.x.append(-1 * params.SCREEN_SIZE_X) self.y.append(-1 * params.SCREEN_SIZE_Y) #print(gaze.RightGazePoint2D.x * params.SCREEN_SIZE_X, gaze.RightGazePoint2D.y * params.SCREEN_SIZE_Y) # print("%f" % (time.time() * 1000.0)) if (params.USE_EMDAT): for aoi, polygon in self.AOIs.iteritems(): if utils.point_inside_polygon((self.x[-1], self.y[-1]), polygon): self.aoi_ids[aoi].append(self.dpt_id) # Pupil size features self.pupilsize.append(self.get_pupil_size(gaze["left_pupil_diameter"], gaze["right_pupil_diameter"])) if (self.last_pupil_right != -1): self.pupilvelocity.append(self.get_pupil_velocity(self.last_pupil_left, self.last_pupil_right, gaze["left_pupil_diameter"], gaze["right_pupil_diameter"], gaze["device_time_stamp"] - self.LastTimestamp)) else: self.pupilvelocity.append(-1) self.time.append(gaze["device_time_stamp"]) self.head_distance.append(self.get_distance(gaze["left_gaze_point_in_user_coordinate_system"][2], gaze["right_gaze_point_in_user_coordinate_system"][2])) self.validity.append(gaze["left_gaze_point_validity"] == 1 or gaze["right_gaze_point_validity"] == 1) # for pupil velocity self.last_pupil_left = gaze["left_pupil_diameter"] self.last_pupil_right = gaze["right_pupil_diameter"] self.LastTimestamp = gaze["device_time_stamp"] self.dpt_id += 1 def on_gazedata_4c(self, x, y, time_stamp): """Adds new data point to the raw data arrays. If x, y coordinate data is not available, stores the coordinates for this datapoint as (-1280, -1024). Any other feature, if not available, is stored as -1. arguments error -- some Tobii error message, isn't used in function gaze -- Tobii gaze data struct keyword arguments None returns None -- appends gaze to self.gazeData list """ #Don't need raw gaze so this code is commented out #self.gazeData.append(gaze) # print(gaze.RightGazePoint2D.x * 1280, gaze.RightGazePoint2D.y * 1024) # print("%f" % (time.time() * 1000.0)) self.x.append(x) self.y.append(y) if (params.USE_EMDAT): for aoi, polygon in self.AOIs.iteritems(): if utils.point_inside_polygon((self.x[-1], self.y[-1]), polygon): print("point inside ", aoi) self.aoi_ids[aoi].append(self.dpt_id) self.time.append(time_stamp) self.validity.append(True) self.LastTimestamp = time_stamp self.dpt_id += 1 def on_gazedata_simulation(self, x, y, time_stamp): """Adds new data point to the raw data arrays. If x, y coordinate data is not available, stores the coordinates for this datapoint as (-1280, -1024). Any other feature, if not available, is stored as -1. arguments error -- some Tobii error message, isn't used in function gaze -- Tobii gaze data struct keyword arguments None returns None -- appends gaze to self.gazeData list """ #Don't need raw gaze so this code is commented out #self.gazeData.append(gaze) # print(gaze.RightGazePoint2D.x * 1280, gaze.RightGazePoint2D.y * 1024) # print("%f" % (time.time() * 1000.0)) self.x.append(x) self.y.append(y) if (params.USE_EMDAT): for aoi, polygon in self.AOIs.iteritems(): if utils.point_inside_polygon((self.x[-1], self.y[-1]), polygon): print("point inside ", aoi) self.aoi_ids[aoi].append(self.dpt_id) self.time.append(time_stamp) self.validity.append(True) self.LastTimestamp = time_stamp self.dpt_id += 1 def add_fixation(self, x, y, duration, start_time): ''' Called by FixationDetector when a new fixation is detected. Adds a new fixation to data array to be used for EMDAT features calculation. Args: x - coordinate of fixation on the screen y - coordinate of fixation on the screen duration - duration of fixation in microseconds ''' self.EndFixations.append((x, y, duration, start_time)) def add_mouse_key_click(self, mouse_click): ''' Called by MouseKeyboardEventDetector when a new mouse click is detected. Adds a new mouse click to data array to be used for EMDAT features calculation. Args: mouse_click - BasicMouseEvent object ''' self.mouse_clicks.append(mouse_click) def add_keyboard_click(self, keyboard_click): ''' Called by MouseKeyboardEventDetector when a new keyboard click is detected. Adds a new keyboard click to data array to be used for EMDAT features calculation. Args: keyboard_click - KeyboardEvent object ''' self.keyboard_clicks.append(keyboard_click) def get_pupil_size(self, pupilleft, pupilright): ''' Used for extracting pupilsize in on_gazedata(). If recordings for both eyes are available, return their average, else return value for a recorded eye (if any) Args: pupilleft - recording of pupil size on left eye pupilright - recording of pupil size on right eye Returns: pupil size to generate pupil features with. ''' if pupilleft == 0 and pupilright == 0: return -1 if pupilleft == 0: return pupilright if pupilright == 0: return pupilleft return (pupilleft + pupilright) / 2.0 def get_pupil_velocity(self, last_pupilleft, last_pupilright, pupilleft, pupilright, time): ''' Used for extracting pupilvelocity in on_gazedata(). If pupilsizes for both eyes are available, return the average of their difference, else return value for a recorded eye (if any) Args: last_pupilleft - pupilsize for left eye from previous gaze object last_pupilright - pupilsize for right eye from previous gaze object pupilleft - pupilsize for left eye from current gaze object pupilright - pupilsize for left eye from current gaze
header, footer def generate_struct_union_definition(self, entry, code): code.mark_pos(entry.pos) type = entry.type scope = type.scope if scope: kind = type.kind packed = type.is_struct and type.packed if packed: kind = "%s %s" % (type.kind, "__Pyx_PACKED") code.globalstate.use_utility_code(packed_struct_utility_code) header, footer = \ self.sue_header_footer(type, kind, type.cname) if packed: code.putln("#if defined(__SUNPRO_C)") code.putln(" #pragma pack(1)") code.putln("#elif !defined(__GNUC__)") code.putln(" #pragma pack(push, 1)") code.putln("#endif") code.putln(header) var_entries = scope.var_entries if not var_entries: error(entry.pos, "Empty struct or union definition not allowed outside a 'cdef extern from' block") for attr in var_entries: code.putln( "%s;" % attr.type.declaration_code(attr.cname)) code.putln(footer) if packed: code.putln("#if defined(__SUNPRO_C)") code.putln(" #pragma pack()") code.putln("#elif !defined(__GNUC__)") code.putln(" #pragma pack(pop)") code.putln("#endif") def generate_cpp_class_definition(self, entry, code): code.mark_pos(entry.pos) type = entry.type scope = type.scope if scope: if type.templates: code.putln("template <class %s>" % ", class ".join( [T.empty_declaration_code() for T in type.templates])) # Just let everything be public. code.put("struct %s" % type.cname) if type.base_classes: base_class_decl = ", public ".join( [base_class.empty_declaration_code() for base_class in type.base_classes]) code.put(" : public %s" % base_class_decl) code.putln(" {") py_attrs = [e for e in scope.entries.values() if e.type.is_pyobject and not e.is_inherited] has_virtual_methods = False constructor = None destructor = None for attr in scope.var_entries: if attr.type.is_cfunction and attr.type.is_static_method: code.put("static ") elif attr.name == "<init>": constructor = attr elif attr.name == "<del>": destructor = attr elif attr.type.is_cfunction: code.put("virtual ") has_virtual_methods = True code.putln("%s;" % attr.type.declaration_code(attr.cname)) is_implementing = 'init_module' in code.globalstate.parts if constructor or py_attrs: if constructor: arg_decls = [] arg_names = [] for arg in constructor.type.original_args[ :len(constructor.type.args)-constructor.type.optional_arg_count]: arg_decls.append(arg.declaration_code()) arg_names.append(arg.cname) if constructor.type.optional_arg_count: arg_decls.append(constructor.type.op_arg_struct.declaration_code(Naming.optional_args_cname)) arg_names.append(Naming.optional_args_cname) if not arg_decls: arg_decls = ["void"] else: arg_decls = ["void"] arg_names = [] if is_implementing: code.putln("%s(%s) {" % (type.cname, ", ".join(arg_decls))) if py_attrs: code.put_ensure_gil() for attr in py_attrs: code.put_init_var_to_py_none(attr, nanny=False); if constructor: code.putln("%s(%s);" % (constructor.cname, ", ".join(arg_names))) if py_attrs: code.put_release_ensured_gil() code.putln("}") else: code.putln("%s(%s);" % (type.cname, ", ".join(arg_decls))) if destructor or py_attrs or has_virtual_methods: if has_virtual_methods: code.put("virtual ") if is_implementing: code.putln("~%s() {" % type.cname) if py_attrs: code.put_ensure_gil() if destructor: code.putln("%s();" % destructor.cname) if py_attrs: for attr in py_attrs: code.put_var_xdecref(attr, nanny=False); code.put_release_ensured_gil() code.putln("}") else: code.putln("~%s();" % type.cname) if py_attrs: # Also need copy constructor and assignment operators. if is_implementing: code.putln("%s(const %s& __Pyx_other) {" % (type.cname, type.cname)) code.put_ensure_gil() for attr in scope.var_entries: if not attr.type.is_cfunction: code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname)) code.put_var_incref(attr, nanny=False) code.put_release_ensured_gil() code.putln("}") code.putln("%s& operator=(const %s& __Pyx_other) {" % (type.cname, type.cname)) code.putln("if (this != &__Pyx_other) {") code.put_ensure_gil() for attr in scope.var_entries: if not attr.type.is_cfunction: code.put_var_xdecref(attr, nanny=False); code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname)) code.put_var_incref(attr, nanny=False) code.put_release_ensured_gil() code.putln("}") code.putln("return *this;") code.putln("}") else: code.putln("%s(const %s& __Pyx_other);" % (type.cname, type.cname)) code.putln("%s& operator=(const %s& __Pyx_other);" % (type.cname, type.cname)) code.putln("};") def generate_enum_definition(self, entry, code): code.mark_pos(entry.pos) type = entry.type name = entry.cname or entry.name or "" header, footer = self.sue_header_footer(type, "enum", name) code.putln(header) enum_values = entry.enum_values if not enum_values: error(entry.pos, "Empty enum definition not allowed outside a 'cdef extern from' block") else: last_entry = enum_values[-1] # this does not really generate code, just builds the result value for value_entry in enum_values: if value_entry.value_node is not None: value_entry.value_node.generate_evaluation_code(code) for value_entry in enum_values: if value_entry.value_node is None: value_code = value_entry.cname else: value_code = ("%s = %s" % ( value_entry.cname, value_entry.value_node.result())) if value_entry is not last_entry: value_code += "," code.putln(value_code) code.putln(footer) if entry.type.typedef_flag: # Not pre-declared. code.putln("typedef enum %s %s;" % (name, name)) def generate_typeobj_predeclaration(self, entry, code): code.putln("") name = entry.type.typeobj_cname if name: if entry.visibility == 'extern' and not entry.in_cinclude: code.putln("%s %s %s;" % ( Naming.extern_c_macro, PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"), name)) elif entry.visibility == 'public': code.putln("%s %s %s;" % ( Naming.extern_c_macro, PyrexTypes.public_decl("PyTypeObject", "DL_EXPORT"), name)) # ??? Do we really need the rest of this? ??? #else: # code.putln("static PyTypeObject %s;" % name) def generate_exttype_vtable_struct(self, entry, code): if not entry.used: return code.mark_pos(entry.pos) # Generate struct declaration for an extension type's vtable. type = entry.type scope = type.scope self.specialize_fused_types(scope) if type.vtabstruct_cname: code.putln("") code.putln("struct %s {" % type.vtabstruct_cname) if type.base_type and type.base_type.vtabstruct_cname: code.putln("struct %s %s;" % ( type.base_type.vtabstruct_cname, Naming.obj_base_cname)) for method_entry in scope.cfunc_entries: if not method_entry.is_inherited: code.putln("%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.cname)) code.putln("};") def generate_exttype_vtabptr_declaration(self, entry, code): if not entry.used: return code.mark_pos(entry.pos) # Generate declaration of pointer to an extension type's vtable. type = entry.type if type.vtabptr_cname: code.putln("static struct %s *%s;" % ( type.vtabstruct_cname, type.vtabptr_cname)) def generate_exttype_final_methods_declaration(self, entry, code): if not entry.used: return code.mark_pos(entry.pos) # Generate final methods prototypes type = entry.type for method_entry in entry.type.scope.cfunc_entries: if not method_entry.is_inherited and method_entry.final_func_cname: declaration = method_entry.type.declaration_code( method_entry.final_func_cname) modifiers = code.build_function_modifiers(method_entry.func_modifiers) code.putln("static %s%s;" % (modifiers, declaration)) def generate_objstruct_predeclaration(self, type, code): if not type.scope: return code.putln(self.sue_predeclaration(type, "struct", type.objstruct_cname)) def generate_objstruct_definition(self, type, code): code.mark_pos(type.pos) # Generate object struct definition for an # extension type. if not type.scope: return # Forward declared but never defined header, footer = \ self.sue_header_footer(type, "struct", type.objstruct_cname) code.putln(header) base_type = type.base_type if base_type: basestruct_cname = base_type.objstruct_cname if basestruct_cname == "PyTypeObject": # User-defined subclasses of type are heap allocated. basestruct_cname = "PyHeapTypeObject" code.putln( "%s%s %s;" % ( ("struct ", "")[base_type.typedef_flag], basestruct_cname, Naming.obj_base_cname)) else: code.putln( "PyObject_HEAD") if type.vtabslot_cname and not (type.base_type and type.base_type.vtabslot_cname): code.putln( "struct %s *%s;" % ( type.vtabstruct_cname, type.vtabslot_cname)) for attr in type.scope.var_entries: if attr.is_declared_generic: attr_type = py_object_type else: attr_type = attr.type code.putln( "%s;" % attr_type.declaration_code(attr.cname)) code.putln(footer) if type.objtypedef_cname is not None: # Only for exposing public typedef name. code.putln("typedef struct %s %s;" % (type.objstruct_cname, type.objtypedef_cname)) def generate_c_class_declarations(self, env, code, definition): for entry in env.c_class_entries: if definition or entry.defined_in_pxd: code.putln("static PyTypeObject *%s = 0;" % ( entry.type.typeptr_cname)) def generate_cvariable_declarations(self, env, code, definition): if env.is_cython_builtin: return for entry in env.var_entries: if (entry.in_cinclude or entry.in_closure or (entry.visibility == 'private' and not (entry.defined_in_pxd or entry.used))): continue storage_class = None dll_linkage = None init = None if entry.visibility == 'extern': storage_class = Naming.extern_c_macro dll_linkage = "DL_IMPORT" elif entry.visibility == 'public': storage_class = Naming.extern_c_macro if definition: dll_linkage = "DL_EXPORT" else: dll_linkage = "DL_IMPORT" elif entry.visibility == 'private': storage_class = "static" dll_linkage = None if entry.init is not None: init = entry.type.literal_code(entry.init) type = entry.type cname = entry.cname if entry.defined_in_pxd and not definition: storage_class = "static" dll_linkage = None type = CPtrType(type) cname = env.mangle(Naming.varptr_prefix, entry.name) init = 0 if storage_class: code.put("%s " % storage_class) code.put(type.declaration_code( cname, dll_linkage=dll_linkage)) if init is not None: code.put_safe(" = %s" % init) code.putln(";") if entry.cname != cname: code.putln("#define %s (*%s)" % (entry.cname, cname)) def generate_cfunction_declarations(self, env, code, definition): for entry in env.cfunc_entries: if entry.used or (entry.visibility == 'public' or entry.api): generate_cfunction_declaration(entry, env, code, definition) def generate_variable_definitions(self, env, code): for entry in env.var_entries: if not entry.in_cinclude and entry.visibility == "public": code.put(entry.type.declaration_code(entry.cname)) if entry.init is not None: init = entry.type.literal_code(entry.init) code.put_safe(" = %s" % init) code.putln(";") def generate_typeobj_definitions(self, env, code): full_module_name = env.qualified_name for entry in env.c_class_entries: #print "generate_typeobj_definitions:", entry.name #print "...visibility =", entry.visibility if entry.visibility != 'extern': type = entry.type scope = type.scope if scope: # could be None if there was an error self.generate_exttype_vtable(scope, code) self.generate_new_function(scope, code, entry) self.generate_dealloc_function(scope, code) if scope.needs_gc(): self.generate_traverse_function(scope, code, entry) if scope.needs_tp_clear(): self.generate_clear_function(scope, code, entry) if scope.defines_any_special(["__getitem__"]): self.generate_getitem_int_function(scope, code) if scope.defines_any_special(["__setitem__", "__delitem__"]): self.generate_ass_subscript_function(scope, code) if scope.defines_any_special(["__getslice__", "__setslice__", "__delslice__"]): warning(self.pos, "__getslice__, __setslice__, and __delslice__ are not supported by Python 3, " "use __getitem__, __setitem__, and __delitem__ instead", 1) code.putln("#if PY_MAJOR_VERSION >= 3") code.putln("#error __getslice__, __setslice__, and __delslice__ not supported in Python 3.") code.putln("#endif") if scope.defines_any_special(["__setslice__", "__delslice__"]): self.generate_ass_slice_function(scope, code) if scope.defines_any_special(["__getattr__", "__getattribute__"]): self.generate_getattro_function(scope, code) if scope.defines_any_special(["__setattr__", "__delattr__"]): self.generate_setattro_function(scope, code) if scope.defines_any_special(["__get__"]): self.generate_descr_get_function(scope, code) if scope.defines_any_special(["__set__", "__delete__"]): self.generate_descr_set_function(scope, code) if not scope.is_closure_class_scope and scope.defines_any(["__dict__"]): self.generate_dict_getter_function(scope, code) if scope.defines_any_special(TypeSlots.richcmp_special_methods): self.generate_richcmp_function(scope, code) self.generate_property_accessors(scope, code) self.generate_method_table(scope, code) self.generate_getset_table(scope, code) self.generate_typeobj_definition(full_module_name, entry, code) def generate_exttype_vtable(self, scope, code): # Generate the definition of an extension type's vtable. type = scope.parent_type if type.vtable_cname: code.putln("static struct %s %s;" % ( type.vtabstruct_cname, type.vtable_cname)) def generate_self_cast(self, scope, code): type = scope.parent_type code.putln( "%s = (%s)o;" % ( type.declaration_code("p"), type.empty_declaration_code())) def generate_new_function(self, scope, code, cclass_entry): tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__') slot_func = scope.mangle_internal("tp_new") type = scope.parent_type base_type = type.base_type have_entries, (py_attrs, py_buffers, memoryview_slices) = \ scope.get_refcounted_entries() is_final_type = scope.parent_type.is_final_type if scope.is_internal: # internal classes (should) never need None inits, normal zeroing will do py_attrs = [] cpp_class_attrs = [entry for
<reponame>cholve/stratum<filename>stratum/portage/build_defs.bzl # Copyright 2018 Google LLC # Copyright 2018-present Open Networking Foundation # SPDX-License-Identifier: Apache-2.0 """A portable build system for Stratum P4 switch stack. To use this, load() this file in a BUILD file, specifying the symbols needed. The public symbols are the macros: decorate(path) sc_cc_lib Declare a portable Library. sc_proto_lib Declare a portable .proto Library. sc_cc_bin Declare a portable Binary. sc_package Declare a portable tarball package. and the variables/lists: ALL_ARCHES All known arches. EMBEDDED_ARCHES All embedded arches. EMBEDDED_PPC Name of PowerPC arch - "ppc". EMBEDDED_X86 Name of "x86" arch. HOST_ARCH Name of default "host" arch. HOST_ARCHES All host arches. STRATUM_INTERNAL For declaring Stratum internal visibility. The macros are like cc_library(), proto_library(), and cc_binary(), but with different options and some restrictions. The key difference: you can supply lists of architectures for which they should be compiled - defaults to all if left unstated. Internally, libraries and binaries are generated for every listed architecture. The names are decorated to keep them different and allow all to be generated and addressed independently. This aspect of the system is suboptimal - something along the lines of augmenting context with a user defined configuration fragment would be a much cleaner solution. Currently supported architectures: ppc x86 """ load("//tools/build_defs/label:def.bzl", "parse_label") load( "//devtools/build_cleaner/skylark:build_defs.bzl", "register_extension_info", ) load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") # Generic path & label helpers. ============================================ def _normpath(path): """Normalize a path. Normalizes a path by removing unnecessary path-up segments and its corresponding directories. Providing own implementation because import os is not allowed in build defs. For example ../../dir/to/deeply/nested/path/../../../other/path will become ../../dir/to/other/path Args: path: A valid absolute or relative path to normalize. Returns: A path equivalent to the input path with minimal use of path-up segments. Invalid input paths will stay invalid. """ sep = "/" level = 0 result = [] for d in path.split(sep): if d in ("", "."): if result: continue elif d == "..": if level > 0: result.pop() level += -1 continue else: level += 1 result.append(d) return sep.join(result) # Adds a suffix to a label, expanding implicit targets if needed. def decorate(label, suffix): if label.endswith(":"): # .../bar: -> .../bar label = label[:-1] if ":" in label: # .../bar:bat -> .../bar:bat_suffix return "%s_%s" % (label, suffix) elif label.startswith("//"): # //foo/bar -> //foo/bar:bar_suffix return "%s:%s_%s" % (label, label.split("/")[-1], suffix) else: # bar -> bar_suffix return "%s_%s" % (label, suffix) # Creates a relative filename from a label, replacing "//" and ":". def _make_filename(label): if label.startswith("//"): # //foo/bar:bat/baz -> google3_foo/bar/bat/baz return label.replace("//", "google3/").replace(":", "/") elif label.startswith(":"): # :bat/baz -> bat/baz return label[1:] else: # bat/baz -> bat/baz return label # Adds dquotes around a string. def dquote(s): return '"' + s + '"' # Adds squotes around a string. def squote(s): return "'" + s + "'" # Emulate Python 2.5+ str(startswith([prefix ...]) def starts_with(s, prefix_list): for prefix in prefix_list: if s.startswith(prefix): return prefix return None def sc_platform_select(host = None, ppc = None, x86 = None, default = None): """Public macro to alter blaze rules based on the platform architecture. Generates a blaze select(...) statement that can be used in most contexts to alter a blaze rule based on the target platform architecture. If no selection is provided for a given platform, {default} is used instead. A specific value or default must be provided for every target platform. Args: host: The value to use for host builds. ppc: The value to use for ppc builds. x86: The value to use for x86 builds. default: The value to use for any of {host,ppc,x86} that isn't specified. Returns: The requested selector. """ if default == None and (host == None or ppc == None or x86 == None): fail("Missing a select value for at least one platform in " + "sc_platform_select. Please add.") config_label_prefix = "//stratum:stratum_" return select({ "//conditions:default": (host or default), config_label_prefix + "ppc": (ppc or default), config_label_prefix + "x86": (x86 or default), }) # Generates an sc_platform_select based on a textual list of arches. def sc_platform_filter(value, default, arches): return sc_platform_select( host = value if "host" in arches else default, ppc = value if "ppc" in arches else default, x86 = value if "x86" in arches else default, ) def sc_platform_alias( name, host = None, ppc = None, x86 = None, default = None, visibility = None): """Public macro to create an alias that changes based on target arch. Generates a blaze alias that will select the appropriate target. If no selection is provided for a given platform and no default is set, a dummy default target is used instead. Args: name: The name of the alias target. host: The result of the alias for host builds. ppc: The result of the alias for ppc builds. x86: The result of the alias for x86 builds. default: The result of the alias for any of {host,ppc,x86} that isn't specified. visibility: The visibility of the alias target. """ native.alias( name = name, actual = sc_platform_select( default = default or "//stratum/portage:dummy", host = host, ppc = ppc, x86 = x86, ), visibility = visibility, ) # Embedded build definitions. ============================================== EMBEDDED_PPC = "ppc" EMBEDDED_X86 = "x86" EMBEDDED_ARCHES = [ EMBEDDED_PPC, EMBEDDED_X86, ] HOST_ARCH = "host" HOST_ARCHES = [HOST_ARCH] ALL_ARCHES = EMBEDDED_ARCHES + HOST_ARCHES # Identify Stratum platform arch for .pb.h shims and other portability hacks. _ARCH_DEFINES = sc_platform_select( default = ["STRATUM_ARCH_HOST"], ppc = ["STRATUM_ARCH_PPC"], x86 = ["STRATUM_ARCH_X86"], ) STRATUM_INTERNAL = [ "//stratum:__subpackages__", ] # # Build options for all embedded architectures # # Set _TRACE_SRCS to show sources in embedded sc_cc_lib compile steps. # This is more general than it may seem: genrule doesn't have hdrs or deps # attributes, so all embedded dependencies appear as a `src'. # TODO(unknown): if useful again then inject from cmdline else kill feature. _TRACE_SRCS = False # Used for all gcc invocations. _EMBEDDED_FLAGS = [ "-O0", # Don't use this for program-sizing build #-- "-Os", # Use this for program-sizing build "-g", # Don't use this for program-sizing build "-Wall", "-Werror", # Warn lots, and force fixing warnings. "-no-canonical-prefixes", # Don't mangle paths and confuse blaze. "-fno-builtin-malloc", # We'll use tcmalloc "-fno-builtin-calloc", "-fno-builtin-realloc", "-fno-builtin-free", "-D__STDC_FORMAT_MACROS=1", # TODO(unknown): Figure out how we can use $(CC_FLAGS) instead of this. "-D__GOOGLE_STL_LEGACY_COMPATIBILITY", ] # Used for C and C++ compiler invocations. _EMBEDDED_CFLAGS = [ "-I$(GENDIR)", ] # Used for C++ compiler invocations. _EMBEDDED_CXXFLAGS = [ "-std=gnu++11", # Allow C++11 features _and_ GNU extensions. ] # Used for linking binaries. _EMBEDDED_LDFLAGS = [ # "-static", # Use this for program-sizing build # "-Wl,--gc-sections,--no-wchar-size-warning", # Use this for program-sizing build ] # PPC ====================================================================== _PPC_GRTE = "//unsupported_toolchains/crosstoolng_powerpc32_8540/sysroot" # X86 ====================================================================== _X86_GRTE = "//grte/v4_x86/release/usr/grte/v4" # Portability definitions =================================================== def sc_cc_test( name, size = None, srcs = None, deps = None, data = None, defines = None, copts = None, linkopts = None, visibility = None): """Creates a cc_test rule that interacts safely with Stratum builds. Generates a cc_test rule that doesn't break the build when an embedded arch is selected. During embedded builds this target will generate a dummy binary and will not attempt to build any dependencies. Args: name: Analogous to cc_test name argument. size: Analogous to cc_test size argument. srcs: Analogous to cc_test srcs argument. deps: Analogous to cc_test deps argument. data: Analogous to cc_test data argument. defines: Analogous to cc_test defines argument. copts: Analogous to cc_test copts argument. linkopts: Analogous to cc_test linkopts argument. visibility: Analogous to cc_test visibility argument. """ cc_test( name = name, size = size or "small", srcs = sc_platform_select(host = srcs or [], default = []), deps = sc_platform_select( host = deps or [], default = ["//stratum/portage:dummy_with_main"], ), data = data or [], defines = defines, copts = copts, linkopts = linkopts, visibility = visibility, ) register_extension_info( extension_name = "sc_cc_test", label_regex_for_dep = "{extension_name}", ) def sc_cc_lib( name, deps = None, srcs = None, hdrs = None, arches = None, copts = None, defines = None, includes = None, include_prefix = None, strip_include_prefix = None, data = None, testonly = None, textual_hdrs = None, visibility = None, xdeps = None): """Creates rules for the given portable library and arches. Args: name: Analogous to cc_library name argument. deps: Analogous to cc_library deps argument. srcs: Analogous to cc_library srcs argument. hdrs: Analogous to cc_library hdrs argument. arches: List of architectures to generate this
<filename>bazel/go/dependencies.bzl load("@bazel_gazelle//:deps.bzl", "go_repository", "git_repository") GO_DEPENDENCIES = { "overlaps": { # github.com/stretchr/testify:v1.2.2 -> v1.1.0 # k8s.io:v1.10.8 -> <PASSWORD> (>v1.0.0, <v1.1.0) "github.com/davecgh/go-spew": { "name": "com_github_davecgh_go_spew", "commit": "<PASSWORD>", "importpath": "github.com/davecgh/go-spew", }, # used by us directly and k8s # commit from k8s.io:v1.10.8 "github.com/ghodss/yaml": { "name": "com_github_ghodss_yaml", "commit": "73d445a93680fa1a78ae23a5839bad48f32ba1ee", "importpath": "github.com/ghodss/yaml", }, # github.com/envoyproxy/go-control-plane:v0.2 -> 342cbe0a04158f6dcb03ca0079991a51a4248c02 # k8s.io:v1.10.8 -> c0656edd0d9eab7c66d1eb0c568f9039345796f7 "github.com/gogo/protobuf": { "name": "com_github_gogo_protobuf", "commit": "342cbe0a04158f6dcb03ca0079991a51a4248c02", "importpath": "github.com/gogo/protobuf", "build_file_proto_mode": "disable", }, # TODO: also included/overwritten by rules_go. should have a policy for this one # github.com/envoyproxy/go-control-plane:v0.2 -> ab9f9a6dab164b7d1246e0e688b0ab7b94d8553e # k8s.io:v1.9.3 -> 1643683e1b54a9e88ad26d98f81400c8c9d9f4f9 #"github.com/golang/protobuf": { # "name": "com_github_golang_protobuf", # "commit": "<PASSWORD>", # "importpath": "github.com/golang/protobuf", #}, # depended upon by both k8s.io and gin # commit from k8s.io:v1.10.8 "github.com/json-iterator/go": { "name": "com_github_json_iterator_go", "commit": "f2b4162afba35581b6d4a50d3b8f34e33c144682", "importpath": "github.com/json-iterator/go", }, # github.com/envoyproxy/go-control-plane:v0.2 -> c155da19408a8799da419ed3eeb0cb5db0ad5dbc # github.com/docker/docker:1a57535aa277e0f2a3c1922c736551148c5b4351 -> v1.0.3 "github.com/sirupsen/logrus": { "name": "com_github_sirupsen_logrus", "commit": "c155da19408a8799da419ed3eeb0cb5db0ad5dbc", "importpath": "github.com/sirupsen/logrus", }, # depended upon by both k8s.io and gin # commit from k8s.io:v1.10.8 "github.com/ugorji/go": { "name": "com_github_ugorji_go", "commit": "ded73eae5db7e7a0ef6f55aace87a2873c5d2b74", "importpath": "github.com/ugorji/go", }, # github.com/mlab-lattice/lattice -> 81e90905daefcd6fd217b62423c0908922eadb30 # github.com/envoyproxy/go-control-plane:v0.2 -> 5119cf507ed5294cc409c092980c7497ee5d6fd2 "golang.org/x/crypto": { "name": "org_golang_x_crypto", "commit": "81e90905daefcd6fd217b62423c0908922eadb30", "importpath": "golang.org/x/crypto", }, # github.com/docker/docker:1a57535aa277e0f2a3c1922c736551148c5b4351 -> 5561cd9b4330353950f399814f427425c0a26fd2 # k8s.io:v1.9.3 -> ? # github.com/envoyproxy/go-control-plane:v0.2 -> 5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec "golang.org/x/net": { "name": "org_golang_x_net", "commit": "<KEY>", "importpath": "golang.org/x/net", }, # github.com/envoyproxy/go-control-plane:v0.2 -> <KEY> # k8s.io:v1.9.3 -> 95c6576299259db960f6c5b9b69ea52422860fce "golang.org/x/sys": { "name": "org_golang_x_sys", "commit": "<KEY>", "importpath": "golang.org/x/sys", }, # github.com/envoyproxy/go-control-plane:v0.2 -> e19ae1496984b1c655b8044a65c0300a3c878dd3 # k8s.io:v1.9.3 -> b19bf474d317b857955b12035d2c5acb57ce8b01 "golang.org/x/text": { "name": "org_golang_x_text", "commit": "e19ae1496984b1c655b8044a65c0300a3c878dd3", "importpath": "golang.org/x/text", }, # github.com/envoyproxy/go-control-plane:v0.2 -> a8101f21cf983e773d0c1133ebc5424792003214 # k8s.io:v1.9.3 -> 09f6ed296fc66555a25fe4ce95173148778dfa85 "google.golang.org/genproto": { "name": "org_golang_google_genproto", "commit": "a<PASSWORD>0c<PASSWORD>3ebc54<PASSWORD>9<PASSWORD>", "importpath": "google.golang.org/genproto", }, # github.com/envoyproxy/go-control-plane:v0.2 -> <PASSWORD>e<PASSWORD> # k8s.io:v1.9.3 -> 5b3c<PASSWORD>4cf6a20ebd46c8b32a0a3afcb9e "google.golang.org/grpc": { "name": "org_golang_google_grpc", "commit": "<PASSWORD>", "importpath": "google.golang.org/grpc", }, # depended upon by both k8s.io and gin # commit from k8s.io:v1.10.8 "gopkg.in/yaml.v2": { "name": "in_gopkg_yaml_v2", "commit": "670d4cfef0544295bc27a114dbac37980d83185a", "importpath": "gopkg.in/yaml.v2", }, }, "github.com/mlab-lattice/lattice": { "github.com/armon/go-radix": { "name": "com_github_armon_go_radix", "tag": "v1.0.0", "importpath": "github.com/armon/go-radix", }, "github.com/aws/aws-sdk-go": { "name": "com_github_aws_aws_sdk_go", "tag": "v1.12.35", "importpath": "github.com/aws/aws-sdk-go", }, "github.com/blang/semver": { "name": "com_github_blang_semver", "tag": "v3.5.1", "importpath": "github.com/blang/semver", }, "github.com/briandowns/spinner": { "name": "com_github_briandowns_spinner", "commit": "<PASSWORD>", "importpath": "github.com/briandowns/spinner", }, # master HEAD as of 3/6/18 "github.com/buger/goterm": { "name": "com_github_buger_goterm", "commit": "<PASSWORD>", "importpath": "github.com/buger/goterm", }, "github.com/coreos/go-iptables": { "name": "com_github_coreos_go_iptables", # repo has a file named "build" so have to force gazelle to generate a BUILD.bazel file "build_file_generation": "on", "build_file_name": "BUILD.bazel", "commit": "<PASSWORD>36e6ccb6f6e424f7d89c614164e796<PASSWORD>", "importpath": "github.com/coreos/go-iptables", }, "github.com/deckarep/golang-set": { "name": "com_github_deckarep_golang_set", "commit": "1<PASSWORD>8f51bed434f1dadf96dcd9b43aabac66795", "importpath": "github.com/deckarep/golang-set", }, "github.com/docker/docker": { "name": "com_github_docker_docker", # corresponds to docker v18.05.0-ce "commit": "1<PASSWORD>c<PASSWORD>", "importpath": "github.com/docker/docker", }, "github.com/envoyproxy/go-control-plane": { "name": "com_github_envoyproxy_go_control_plane", "tag": "v0.2", "importpath": "github.com/envoyproxy/go-control-plane", }, "github.com/fatih/color": { "name": "com_github_fatih_color", "tag": "v1.5.0", "importpath": "github.com/fatih/color", }, "github.com/gin-gonic/gin": { "name": "com_github_gin_gonic_gin", "tag": "v1.2", "importpath": "github.com/gin-gonic/gin", }, "github.com/olekukonko/tablewriter": { "name": "com_github_olekukonko_tablewriter", "commit": "be2c049b30ccd4d3fd795d6bf7dce74e42eeedaa", "importpath": "github.com/olekukonko/tablewriter", }, "github.com/satori/go.uuid": { "name": "com_github_satori_go_uuid", "commit": "5bf94b69c6b68ee1b541973bb8e1144db23a194b", "importpath": "github.com/satori/go.uuid", }, "github.com/sergi/go-diff": { "name": "com_github_sergi_go_diff", "commit": "feef008d51ad2b3778f85d387ccf91735543008d", "importpath": "github.com/sergi/go-diff", }, # also depended upon by k8s.io # jumping ahead of their requirement to include: https://github.com/spf13/cobra/pull/502 "github.com/spf13/cobra": { "name": "com_github_spf13_cobra", "commit": "<PASSWORD>", "importpath": "github.com/spf13/cobra", }, "github.com/swaggo/swag": { "name": "com_github_swaggo_swag", "tag": "v1.3.2", "importpath": "github.com/swaggo/swag", }, "github.com/swaggo/gin-swagger": { "name": "com_github_swaggo_gin_swagger", "tag": "v1.0.0", "importpath": "github.com/swaggo/gin-swagger", }, # FIXME(kevindrosendahl): remove when removing old pkg/util/cli "github.com/tfogo/tablewriter": { "name": "com_github_tfogo_tablewriter", "commit": "4776fb554dc2ca114fbce4738142a47de1ea0929", "importpath": "github.com/tfogo/tablewriter", }, "github.com/tidwall/gjson": { "name": "com_github_tidwall_gjson", "tag": "v1.0.6", "importpath": "github.com/tidwall/gjson", }, "gopkg.in/src-d/go-git.v4": { "name": "in_gopkg_src_d_go_git_v4", "commit": "f9879dd043f84936a1f8acb8a53b74332a7ae135", "importpath": "gopkg.in/src-d/go-git.v4", }, "k8s.io/api": { "name": "io_k8s_api", # https://github.com/bazelbuild/rules_go/issues/964 "build_file_proto_mode": "disable", "tag": "kubernetes-1.10.8", "importpath": "k8s.io/api", }, "k8s.io/apimachinery": { "name": "io_k8s_apimachinery", # https://github.com/bazelbuild/rules_go/issues/964 "build_file_proto_mode": "disable", "tag": "kubernetes-1.10.8", "importpath": "k8s.io/apimachinery", }, "k8s.io/client-go": { "name": "io_k8s_client_go", "tag": "kubernetes-1.10.8", "importpath": "k8s.io/client-go", }, # testing dependencies "github.com/onsi/ginkgo": { "name": "com_github_onsi_ginkgo", "tag": "v1.4.0", "importpath": "github.com/onsi/ginkgo", }, "github.com/onsi/gomega": { "name": "com_github_onsi_gomega", "tag": "v1.3.0", "importpath": "github.com/onsi/gomega", }, "github.com/stretchr/testify": { "name": "com_github_stretchr_testify", "tag": "v1.2.2", "importpath": "github.com/stretchr/testify", }, }, # commits taken from: https://github.com/aws/aws-sdk-go/blob/v1.12.35/Gopkg.lock "github.com/aws/aws-sdk-go": { "github.com/go-ini/ini": { "name": "com_github_go_ini_ini", "commit": "300e940a926eb277d3901b20bdfcc54928ad3642", "importpath": "github.com/go-ini/ini", }, "github.com/jmespath/go-jmespath": { "name": "com_github_jmespath_go_jmespath", "commit": "0b12d6b521d83fc7f755e7cfc1b1fbdd35a01a74", "importpath": "github.com/jmespath/go-jmespath", }, }, # no dependency versions listed, taken from master HEAD "github.com/deckarep/golang-set": { "github.com/golang/groupcache": { "name": "com_github_golang_groupcache", "commit": "84a468cf14b4376def5d68c722b139b881c450a4", "importpath": "github.com/golang/groupcache", }, }, # Getting the right commits is a little tricky. First go to https://github.com/docker/docker-ce and find # the corresponding release. Then go to components/engine and look at the most recent commit. # At the bottom of the commit message it should say what commit is was cherry picked from. # Go to github.com/moby/moby and go to that commit and check vendor.conf # Taken from https://github.com/docker/docker-ce/tree/v18.05.0-ce/components/engine # -> https://github.com/docker/docker-ce/commit/c1ef5d203fff0b7c86c403d614a1e81a014fae56 # -> https://github.com/moby/moby/blob/1a57535aa277e0f2a3c1922c736551148c5b4351/vendor.conf "github.com/docker/docker": { "github.com/docker/distribution": { "name": "com_github_docker_distribution", "commit": "edc3ab29cdff8694dd6feb85cfeb4b5f1b38ed9c", "importpath": "github.com/docker/distribution", }, "github.com/docker/go-connections": { "name": "com_github_docker_go_connections", "commit": "7beb39f0b969b075d1325fecb092faf27fd357b6", "importpath": "github.com/docker/go-connections", }, "github.com/docker/go-units": { "name": "com_github_docker_go_units", "commit": "9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1", "importpath": "github.com/docker/go-units", }, "github.com/opencontainers/runc": { "name": "com_github_opencontainers_runc", "commit": "4fc53a81fb7c994640722ac585fa9ca548971871", "importpath": "github.com/opencontainers/runc", }, "github.com/pkg/errors": { "name": "com_github_pkg_errors", "commit": "839d9e913e063e28dfd0e6c7b7512793e0a48be9", "importpath": "github.com/pkg/errors", }, "github.com/opencontainers/go-digest": { "name": "com_github_opencontainers_go_digest", "tag": "v1.0.0-rc1", "importpath": "github.com/opencontainers/go-digest", }, "github.com/Nvveen/Gotty": { "name": "com_github_Nvveen_Gotty", "commit": "a8b993ba6abdb0e0c12b0125c603323a71c7790c", "importpath": "github.com/Nvveen/Gotty", # looks like github.com/Nvveen/Gotty is what is being included: # https://github.com/moby/moby/blob/6e7715d65ba892a47d355e16bf9ad87fb537a2d0/pkg/jsonmessage/jsonmessage.go#L11 # but that it is being aliased in vendor.conf: # https://github.com/moby/moby/blob/6e7715d65ba892a47d355e16bf9ad87fb537a2d0/vendor.conf#L142 "vcs": "git", "remote": "https://github.com/ijc25/Gotty", }, "github.com/docker/libtrust": { "name": "com_github_docker_libtrust", "commit": "9cbd2a1374f46905c68a4eb3694a130610adc62a", "importpath": "github.com/docker/libtrust", }, }, # commits taken from: https://github.com/envoyproxy/go-control-plane/blob/v0.2/glide.lock "github.com/envoyproxy/go-control-plane": { "github.com/envoyproxy/data-plane-api": { "name": "com_github_envoyproxy_data_plane_api", "commit": "22d98ce77228bde6984dfee38a285f501e748343", "importpath": "github.com/envoyproxy/data-plane-api", }, "github.com/gogo/googleapis": { "name": "com_github_gogo_googleapis", "commit": "0cd9801be74a10d5ac39d69626eac8255ffcd502", "importpath": "github.com/gogo/googleapis", "build_file_proto_mode": "disable", }, "github.com/lyft/protoc-gen-validate": { "name": "com_github_lyft_protoc_gen_validate", "commit": "2463485ae0c04eea7977c7f521549229f659e39a", "importpath": "github.com/lyft/protoc-gen-validate", "build_file_proto_mode": "disable", }, "istio.io/gogo-genproto": { "name": "io_istio_gogo_genproto", "commit": "dd2b5b6a8f1400838165245e704a011a30154a44", "importpath": "istio.io/gogo-genproto", }, }, # commits taken from: https://github.com/gin-gonic/gin/blob/v1.2/vendor/vendor.json "github.com/fatih/color": { "github.com/mattn/go-colorable": { "name": "com_github_mattn_go_colorable", "commit": "5411d3eea5978e6cdc258b30de592b60df6aba96", "importpath": "github.com/mattn/go-colorable", }, }, # commits from https://github.com/gin-gonic/gin/blob/d459835d2b077e44f7c9b453505ee29881d5d12d/vendor/vendor.json "github.com/gin-gonic/gin": { # also depended upon by github.com/fatih/color "github.com/gin-contrib/sse": { "name": "com_github_gin_contrib_sse", "commit": "22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae", "importpath": "github.com/gin-contrib/sse", }, "github.com/mattn/go-isatty": { "name": "com_github_mattn_go_isatty", "commit": "5<PASSWORD>", "importpath": "github.com/mattn/go-isatty", }, "gopkg.in/go-playground/validator.v8": { "name": "in_gopkg_go_playground_validator_v8", "commit": "<PASSWORD>6<PASSWORD>05e2<PASSWORD>", "importpath": "gopkg.in/go-playground/validator.v8", }, }, # no dependency versions listed, taken from master HEAD "github.com/olekukonko/tablewriter": { "github.com/mattn/go-runewidth": { "name": "com_github_mattn_go_runewidth", "commit": "9<PASSWORD>1d9f7767e3d6f422ea06661bc2c7a19e8a5d", "importpath": "github.com/mattn/go-runewidth", }, }, "github.com/spf13/cobra": { "github.com/spf13/pflag": { "name": "com_github_spf13_pflag", "commit": "<PASSWORD>0bdda4d8fc772cdfea", "importpath": "github.com/spf13/pflag", }, }, "github.com/tidwall/gjson": { "github.com/tidwall/match": { "name": "com_github_tidwall_match", "commit": "1731857f09b1f38450e2c12409748407822dc6be", "importpath": "github.com/tidwall/match", }, }, # could not find a list of dependency versions, so mostly took master HEAD "gopkg.in/src-d/go-git.v4": { "github.com/jbenet/go-context": { "name": "com_github_jbenet_go_context", "commit": "d14ea06fba99483203c19d92cfcd13ebe73135f4", "importpath": "github.com/jbenet/go-context", }, "github.com/mitchellh/go-homedir": { "name": "com_github_mitchellh_go_homedir", "commit": "b8bc1bf767474819792c23f32d8286a45736f1c6", "importpath": "github.com/mitchellh/go-homedir", }, "github.com/src-d/gcfg": { "name": "com_github_src_d_gcfg", "commit": "f187355171c936ac84a82793659ebb4936bc1c23", "importpath": "github.com/src-d/gcfg", }, "github.com/xanzy/ssh-agent": { "name": "com_github_xanzy_ssh_agent", "commit": "ba9c9e33906f58169366275e3450db66139a31a9", "importpath": "github.com/xanzy/ssh-agent", }, "gopkg.in/src-d/go-billy.v3": { "name": "in_gopkg_src_d_go_billy_v3", "commit": "c329b7bc7b9d24905d2bc1b85bfa29f7ae266314", "importpath": "gopkg.in/src-d/go-billy.v3", }, "gopkg.in/warnings.v0": { "name": "in_gopkg_warnings_v0", "commit": "ec4a0fea49c7b46c2aeb0b51<PASSWORD>9<PASSWORD>b", "importpath": "gopkg.in/warnings.v0", }, }, # commits taken from https://github.com/kubernetes/kubernetes/blob/v1.10.8/Godeps/Godeps.json "k8s.io": { "github.com/emicklei/go-restful": { "name": "com_github_emicklei_go_restful", "commit": "ff4f55a206334ef123e4f79bbf348980da81ca46", "importpath": "github.com/emicklei/go-restful", }, "github.com/emicklei/go-restful-swagger12": { "name": "com_github_emicklei_go_restful_swagger12", "commit": "dcef7f55730566d41eae5db10e7d6981829720f6", "importpath": "github.com/emicklei/go-restful-swagger12", }, "github.com/go-openapi/jsonpointer": { "name": "com_github_go_openapi_jsonpointer", "commit": "46af16f9f7b149af66e5d1bd010e3574dc06de98", "importpath": "github.com/go-openapi/jsonpointer", }, "github.com/go-openapi/jsonreference": { "name": "com_github_go_openapi_jsonreference", "commit": "13c6e3589ad90f49bd3e3bbe2c2cb3d7a4142272", "importpath": "github.com/go-openapi/jsonreference", }, "github.com/go-openapi/spec": { "name": "com_github_go_openapi_spec", "commit": "1de3e0542de65ad8d75452a595886fdd0befb363", "importpath": "github.com/go-openapi/spec", }, "github.com/go-openapi/swag": { "name": "com_github_go_openapi_swag", "commit": "f3f9494671f93fcff853e3c6e9e948b3eb71e590", "importpath": "github.com/go-openapi/swag", }, "github.com/google/btree": { "name": "com_github_google_btree", "commit": "7d79101e329e5a3adf994758c578dab82b90c017", "importpath": "github.com/google/btree", }, "github.com/google/gofuzz": { "name": "com_github_google_gofuzz", "commit": "44d81051d367757e1c7c6a5a86423ece9afcf63c", "importpath": "github.com/google/gofuzz", }, "github.com/googleapis/gnostic": { "name": "com_github_googleapis_gnostic", # https://github.com/bazelbuild/rules_go/issues/964 "build_file_proto_mode": "disable", "commit": "0c5108395e2debce0d731cf0287ddf7242066aba", "importpath": "github.com/googleapis/gnostic", }, "github.com/gregjones/httpcache": { "name": "com_github_gregjones_httpcache", "commit": "787624de3eb7bd915c329cba748687a3b22666a6", "importpath": "github.com/gregjones/httpcache", }, "github.com/hashicorp/golang-lru": { "name": "com_github_hashicorp_golang_lru", "commit": "a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4", "importpath": "github.com/hashicorp/golang-lru", }, "github.com/howeyc/gopass": { "name": "com_github_howeyc_gopass", "commit": "bf9dde6d0d2c004a008c27aaee91170c786f6db8", "importpath": "github.com/howeyc/gopass", }, "github.com/imdario/mergo": { "name": "com_github_imdario_mergo", "commit": "6633656539c1639d9d78127b7d47c622b5d7b6dc", "importpath": "github.com/imdario/mergo", }, "github.com/mailru/easyjson": { "name": "com_github_mailru_easyjson", "commit": "2f5df55504ebc322e4d52d34df6a1f5b503bf26d", "importpath": "github.com/mailru/easyjson", }, "github.com/modern-go/reflect2": { "name": "com_github_modern_go_reflect2", "commit": "05fbef0ca5da472bbf96c9322b84a53edc03c9fd", "importpath": "github.com/modern-go/reflect2", }, "github.com/modern-go/concurrent": { "name": "com_github_modern_go_concurrent", "commit": "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94", "importpath": "github.com/modern-go/concurrent", }, "github.com/pborman/uuid": { "name": "com_github_pborman_uuid", "commit": "ca53cad383cad2479bbba7f7a1a05797ec1386e4", "importpath": "github.com/pborman/uuid", }, "github.com/peterbourgon/diskv": { "name": "com_github_peterbourgon_diskv", "commit": "5f041e8faa004a95c88a202771f4cc3e991971e6", "importpath": "github.com/peterbourgon/diskv", }, "github.com/PuerkitoBio/purell": { "name": "com_github_puerkitobio_purell", "commit": "8a290539e2e8629dbc4e6bad948158f790ec31f4", "importpath": "github.com/PuerkitoBio/purell", }, "github.com/PuerkitoBio/urlesc": { "name": "com_github_puerkitobio_urlesc", "commit": "5bd2802263f21d8788851d5305584c82a5c75d7e", "importpath": "github.com/PuerkitoBio/urlesc", }, "golang.org/x/time": { "name": "org_golang_x_time", "commit": "f51c12702a4d776e4c1fa9b0fabab841babae631", "importpath": "golang.org/x/time", }, "golang.org/x/tools": { "name": "org_golang_x_tools", "commit": "<PASSWORD>", "importpath": "golang.org/x/tools", }, "gopkg.in/inf.v0": { "name": "in_gopkg_inf_v0", "commit": "<PASSWORD>", "importpath": "gopkg.in/inf.v0", }, "k8s.io/apiserver": { "name": "io_k8s_apiserver", "tag": "kubernetes-1.10.8", "importpath": "k8s.io/apiserver", }, "k8s.io/kube-openapi": { "name": "io_k8s_kube_openapi", "commit": "39cb288412c48cb533ba4be5d6c28620b9a0c1b4", "importpath": "k8s.io/kube-openapi", }, }, "github.com/stretchr/testify": { "github.com/pmezard/go-difflib": { "name": "com_github_pmezard_go_difflib", "commit": "v1.0.0", "importpath": "github.com/pmezard/go-difflib", }, "github.com/stretchr/objx": { "name": "com_github_stretchr_objx", "commit":
[0.1, -1]] * 16 self.turn_right_incoming = False # self.middle = False return self.buffer.pop() # if self.turning_right: # if yellow_b_r < 0.01 and ((pos_slope_avg is not None and pos_slope_avg >= 0.65) \ # or neg_slope_avg is not None): # # If we turn right, eventually the bot will find a high enuf slope on the right side # # or we see the negative slopes! # self.turn_right_incoming = self.turning_right = False # self.turn_right_prep = -1 # # self.middle = False # if yellow_b_s < 0.1 and abs(yellow_b_r - yellow_b_l) < 0.01: # self.buffer = [[0.1, -1]] * 20 # return self.buffer.pop() # if self.alt: # self.alt = False # # return [self.stop_speed(0.35), -1] # return [0.35, -1] # else: # self.alt = True # return [0.1, 0] # if white_b_r > 0.01 or (yellow_b_l > 0.01 and yellow_b_r < 0.03): # if self.turn_right_prep < 0: # self.turn_right_prep = 3 # st = self.turn_right_prep_angles[self.turn_right_prep] # self.turn_right_prep -= 1 # return [self.stop_speed(0.44), st] # self.turning_right = True # return [0.35, -1] # if white_b_r <= 0.01: # # A bit of hack here # # Turning right is easy to 'die' so alternate btw turning and step slightly forward # if yellow_b_l > 0.015 and yellow_b_r > 0.015 \ # and max_g_b_l >= max_g_b_r: # # return [-0.35, -1] # return [0.1, -1] # # if max_g_b_r > 177: # # return [self.stop_speed(0.44), 1] # if self.alt: # self.alt = False # # return [self.stop_speed(0.35), -1] # return [0.35, -1] # else: # self.alt = True # return [0.1, 0] # if (pos_slope_avg is not None and pos_slope_avg >= 0.65) \ # or neg_slope_avg is not None: # # If we turn right, eventually the bot will find a high enuf slope on the right side # # or we see the negative slopes! # self.turn_right_incoming = False # return [self.stop_speed(0.44), 0] # Duckie the bot is in the middle of 2 lanes # Duckie is not expecting any turns # Expecting standard situations if pos_slope_avg is not None and neg_slope_avg is not None: if pos_slope_avg >= 0.65 and neg_slope_avg <= -0.6: return [self.stop_speed(0.8), steerer] if pos_slope_avg < 0.65 and neg_slope_avg <= -0.6 : # Found a right curve here # Believe Duckie will turn right in the future self.turn_right_incoming = True if neg_slope_avg > -0.6: # Found a left curve here # Believe Duckie will turn left in the future self.turn_left_incoming = True if yellow_b_l < 0.02: return [self.stop_speed(0.8), 1] if white_b_r < 0.02: return [self.stop_speed(0.8), -1] return [self.stop_speed(0.8), 0] if pos_slope_avg is not None: if pos_slope_avg < 0.5 and neg_slope_avg is None: # Found a right curve here # Believe Duckie will turn right in the future self.turn_right_incoming = True if white_b_r > 0.02: return [self.stop_speed(0.8), steerer] else: return [self.stop_speed(0.44), steerer] if neg_slope_avg is not None: if neg_slope_avg > -0.6: # Found a left curve here # Believe Duckie will turn left in the future self.turn_left_incoming = True if white_b_r > 0.02: return [self.stop_speed(0.8), steerer] else: return [self.stop_speed(0.44), steerer] return [self.stop_speed(0.44), steerer] def predict3(self, rgb_array=None, raw_obs=None): print("Status ",self.turn_left_incoming, self.turn_right_incoming, self.middle) if rgb_array is None: return [0, 0] image = np.array(rgb_array) if self.buffer != []: action = self.buffer.pop() if self.stop_sign and raw_obs is not None: self.detect_stop(raw_obs) return action # For maps with pits if self.has_pit and is_pit(rgb_array, 100, 200, 699, 399) > 0.9: self.buffer = [[0.1, 1.0]] * 62 self.middle = False return [0.1, 1.0] # For maps with stop signs if self.stop_sign and raw_obs is not None: self.detect_stop(raw_obs) lines, pos_slope_avg, neg_slope_avg = detect_lane(rgb_array=image) print("Slopes ", pos_slope_avg, neg_slope_avg) if lines is []: return [1.0, 1] if pos_slope_avg is None: psa = 0 else: psa = pos_slope_avg if neg_slope_avg is None: nsa = 0 else: nsa = neg_slope_avg steerer = abs(nsa) - psa if steerer < 0: steerer = max(steerer, -1) if steerer > 0: steerer = min(steerer, 1) # if nsa != 0 and psa != 0: # steerer = abs(nsa) - psa # else: # steerer = 0 # Bot-left yellow_b_l, white_b_l, max_g_b_l = inspect_box(image, 0, 300, 399, 599) # Bot-right yellow_b_r, white_b_r, max_g_b_r = inspect_box(image, 400, 300, 799, 599) # Bottom stripe yellow_b_s, white_b_s, max_g_b_s = inspect_box(image, 200, 500, 599, 599) print("Yellows ", yellow_b_l, yellow_b_s, yellow_b_r) print("Whites ", white_b_l, white_b_s, white_b_r) print("Max green vals ", max_g_b_l, max_g_b_s, max_g_b_r) # Big assumption of intersection: Always have either left or forward if self.passing_intersection: if white_b_l > 0.01 and white_b_r > 0.01: # approaching the sideway, have to turn left if self.remaining_steps_of_slow > 0: fwd_steps = [[0.1, 0]] * 50 buf_steps = [[0.1, 0]] * 10 self.remaining_steps_of_slow = 10 else: fwd_steps = [[0.44, 0]] * 16 buf_steps = [[0.44, 0]] * 3 self.buffer = fwd_steps + [[0.1, 1]] * 30 + buf_steps self.passing_intersection = False return self.buffer.pop() # okay, can go forward if self.remaining_steps_of_slow > 0: fwd_steps = [[0.1, 0]] * 50 self.remaining_steps_of_slow = 0 else: fwd_steps = [[0.44, 0]] * 16 self.buffer = fwd_steps self.passing_intersection = False return self.buffer.pop() # Find lanes if not self.middle: # return [-self.stop_speed(0.44), 0] # if self.intersection: # if white_b_l < 0.001: # if white_b_r < 0.001: # self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 8 # return self.buffer.pop() # if white_b_l > 0.01: # if white_b_r < 0.001: # # stuck to the left side... # self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 13 # return self.buffer.pop() if yellow_b_l > 0.02 and white_b_l < 0.0001 and white_b_r > 0.0001: # consider the middle boy if yellow_b_s > 0.001: # oof # if psa >= 1: # self.buffer = [[]] if psa > 0.25: self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 8 + [[-self.stop_speed(0.35), 0]] else: self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 10 + [[-self.stop_speed(0.35), 0]] return self.buffer.pop() # between 2 lanes alr self.middle = True if steerer > 0: return [self.stop_speed(0.44), 1] else: return [self.stop_speed(0.44), -1] elif yellow_b_l > 0.02 and white_b_l < 0.0001 and white_b_r <= 0.0001: if psa > 0.5: # between 2 lanes, a bit close to left lane # self.middle = True return [self.stop_speed(0.44), steerer] else: # slope too small if yellow_b_s < 0.1: return [0.1, 1] elif psa > 0 and psa < 0.1: # self.middle = True self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 16 return self.buffer.pop() elif psa > 0 and psa < 0.2: # self.middle = True self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 8 return self.buffer.pop() elif psa > 0: self.buffer = [[0.1, 0], [0.1, -1], [0.1, -1]] * 4 return self.buffer.pop() return [0.1, -1] # self.buffer = [[0.35, -1]] *20 + [[0.44, 0]] * 5 # return self.buffer.pop() elif yellow_b_l > 0.02 and white_b_r > 0.02 and yellow_b_r > 0.02: # definitely grass on the right return [self.stop_speed(0.44), 1] elif yellow_b_l <= 0.02: if yellow_b_r > 0.02 and white_b_r > 0.02: if white_b_l < 0.02: # prolly the grass # turn to the left to find out more return [0.1, 1] else: # kinda freakish # let's backdown return [-self.stop_speed(0.44), 0] if white_b_l > 0.02 and white_b_r > 0.02: # cheeky # in front could be the grass # but it could also be facing the edge # false edges may be detected, so let's back down a bit return [-self.stop_speed(0.44), 0] if white_b_r > 0.02: return [self.stop_speed(0.44), 1] if white_b_l > 0.02 and yellow_b_r > 0.02: # oh boy, we're reverse # let's turn around madly # welp, based on the slopes! if pos_slope_avg is not None and pos_slope_avg < 0.6: # positive slope is quite low # let's back down once for safety and turn right self.buffer = [[0.1, -1]] * 20 + [[-self.stop_speed(0.44), 0]] return [-self.stop_speed(0.44), 0] # By
= Var(within=Reals,bounds=(0,950),initialize=0) m.x597 = Var(within=Reals,bounds=(0,950),initialize=0) m.x598 = Var(within=Reals,bounds=(0,950),initialize=0) m.x599 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x600 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x601 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x602 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x603 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x604 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x605 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x606 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x607 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x608 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x609 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x610 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x611 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x612 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x613 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x614 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x615 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x616 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x617 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x618 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x619 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x620 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x621 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x622 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x623 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x624 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x625 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x626 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x627 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x628 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x629 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x630 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x631 = Var(within=Reals,bounds=(0,720),initialize=0) m.x632 = Var(within=Reals,bounds=(0,720),initialize=0) m.x633 = Var(within=Reals,bounds=(0,720),initialize=0) m.x634 = Var(within=Reals,bounds=(0,720),initialize=0) m.x635 = Var(within=Reals,bounds=(0,720),initialize=0) m.x636 = Var(within=Reals,bounds=(0,720),initialize=0) m.x637 = Var(within=Reals,bounds=(0,720),initialize=0) m.x638 = Var(within=Reals,bounds=(0,720),initialize=0) m.x639 = Var(within=Reals,bounds=(0,720),initialize=0) m.x640 = Var(within=Reals,bounds=(0,720),initialize=0) m.x641 = Var(within=Reals,bounds=(0,720),initialize=0) m.x642 = Var(within=Reals,bounds=(0,720),initialize=0) m.x643 = Var(within=Reals,bounds=(0,720),initialize=0) m.x644 = Var(within=Reals,bounds=(0,720),initialize=0) m.x645 = Var(within=Reals,bounds=(0,720),initialize=0) m.x646 = Var(within=Reals,bounds=(0,720),initialize=0) m.x647 = Var(within=Reals,bounds=(0,720),initialize=0) m.x648 = Var(within=Reals,bounds=(0,720),initialize=0) m.x649 = Var(within=Reals,bounds=(0,720),initialize=0) m.x650 = Var(within=Reals,bounds=(0,720),initialize=0) m.x651 = Var(within=Reals,bounds=(0,720),initialize=0) m.x652 = Var(within=Reals,bounds=(0,720),initialize=0) m.x653 = Var(within=Reals,bounds=(0,720),initialize=0) m.x654 = Var(within=Reals,bounds=(0,720),initialize=0) m.x655 = Var(within=Reals,bounds=(0,720),initialize=0) m.x656 = Var(within=Reals,bounds=(0,720),initialize=0) m.x657 = Var(within=Reals,bounds=(0,720),initialize=0) m.x658 = Var(within=Reals,bounds=(0,720),initialize=0) m.x659 = Var(within=Reals,bounds=(0,720),initialize=0) m.x660 = Var(within=Reals,bounds=(0,720),initialize=0) m.x661 = Var(within=Reals,bounds=(0,720),initialize=0) m.x662 = Var(within=Reals,bounds=(0,720),initialize=0) m.x663 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x664 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x665 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x666 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x667 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x668 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x669 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x670 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x671 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x672 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x673 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x674 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x675 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x676 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x677 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x678 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x679 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x680 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x681 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x682 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x683 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x684 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x685 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x686 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x687 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x688 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x689 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x690 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x691 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x692 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x693 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x694 = Var(within=Reals,bounds=(0,3000),initialize=0) m.x695 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x696 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x697 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x698 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x699 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x700 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x701 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x702 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x703 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x704 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x705 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x706 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x707 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x708 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x709 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x710 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x711 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x712 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x713 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x714 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x715 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x716 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x717 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x718 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x719 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x720 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x721 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x722 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x723 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x724 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x725 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x726 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x727 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x728 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x729 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x730 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x731 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x732 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x733 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x734 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x735 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x736 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x737 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x738 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x739 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x740 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x741 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x742 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x743 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x744 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x745 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x746 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x747 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x748 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x749 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x750 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x751 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x752 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x753 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x754 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x755 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x756 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x757 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x758 = Var(within=Reals,bounds=(0,1400),initialize=0) m.x759 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x760 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x761 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x762 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x763 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x764 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x765 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x766 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x767 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x768 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x769 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x770 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x771 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x772 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x773 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x774 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x775 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x776 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x777 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x778 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x779 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x780 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x781 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x782 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x783 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x784 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x785 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x786 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x787 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x788 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x789 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x790 = Var(within=Reals,bounds=(0,2200),initialize=0) m.x791 = Var(within=Reals,bounds=(0,800),initialize=0) m.x792 = Var(within=Reals,bounds=(0,800),initialize=0) m.x793 = Var(within=Reals,bounds=(0,800),initialize=0) m.x794 = Var(within=Reals,bounds=(0,800),initialize=0) m.x795 = Var(within=Reals,bounds=(0,800),initialize=0) m.x796 = Var(within=Reals,bounds=(0,800),initialize=0) m.x797 = Var(within=Reals,bounds=(0,800),initialize=0) m.x798 = Var(within=Reals,bounds=(0,800),initialize=0) m.x799 = Var(within=Reals,bounds=(0,800),initialize=0) m.x800 = Var(within=Reals,bounds=(0,800),initialize=0) m.x801 = Var(within=Reals,bounds=(0,800),initialize=0) m.x802 = Var(within=Reals,bounds=(0,800),initialize=0) m.x803 = Var(within=Reals,bounds=(0,800),initialize=0) m.x804 = Var(within=Reals,bounds=(0,800),initialize=0) m.x805 = Var(within=Reals,bounds=(0,800),initialize=0) m.x806 = Var(within=Reals,bounds=(0,800),initialize=0) m.x807 = Var(within=Reals,bounds=(0,800),initialize=0) m.x808 = Var(within=Reals,bounds=(0,800),initialize=0) m.x809 = Var(within=Reals,bounds=(0,800),initialize=0) m.x810 = Var(within=Reals,bounds=(0,800),initialize=0) m.x811 = Var(within=Reals,bounds=(0,800),initialize=0) m.x812 = Var(within=Reals,bounds=(0,800),initialize=0) m.x813 = Var(within=Reals,bounds=(0,800),initialize=0) m.x814 = Var(within=Reals,bounds=(0,800),initialize=0) m.x815 = Var(within=Reals,bounds=(0,800),initialize=0) m.x816 = Var(within=Reals,bounds=(0,800),initialize=0) m.x817 = Var(within=Reals,bounds=(0,800),initialize=0) m.x818 = Var(within=Reals,bounds=(0,800),initialize=0) m.x819 = Var(within=Reals,bounds=(0,800),initialize=0) m.x820 = Var(within=Reals,bounds=(0,800),initialize=0) m.x821 = Var(within=Reals,bounds=(0,800),initialize=0) m.x822 = Var(within=Reals,bounds=(0,800),initialize=0) m.x823 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x824 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x825 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x826 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x827 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x828 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x829 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x830 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x831 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x832 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x833 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x834 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x835 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x836 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x837 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x838 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x839 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x840 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x841 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x842 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x843 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x844 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x845 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x846 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x847 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x848 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x849 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x850 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x851 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x852 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x853 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x854 = Var(within=Reals,bounds=(0,1800),initialize=0) m.x855 = Var(within=Reals,bounds=(0,1),initialize=0) m.x856 = Var(within=Reals,bounds=(0,1),initialize=0) m.x857 = Var(within=Reals,bounds=(0,1),initialize=0) m.x858 = Var(within=Reals,bounds=(0,1),initialize=0) m.x859 = Var(within=Reals,bounds=(0,1),initialize=0) m.x860 = Var(within=Reals,bounds=(0,1),initialize=0) m.x861 = Var(within=Reals,bounds=(0,1),initialize=0) m.x862 = Var(within=Reals,bounds=(0,1),initialize=0) m.x863 = Var(within=Reals,bounds=(0,1),initialize=0) m.x864 = Var(within=Reals,bounds=(0,1),initialize=0) m.x865 = Var(within=Reals,bounds=(0,1),initialize=0) m.x866 = Var(within=Reals,bounds=(0,1),initialize=0) m.x867 = Var(within=Reals,bounds=(0,1),initialize=0) m.x868 = Var(within=Reals,bounds=(0,1),initialize=0) m.x869 = Var(within=Reals,bounds=(0,1),initialize=0) m.x870 = Var(within=Reals,bounds=(0,1),initialize=0) m.x871 = Var(within=Reals,bounds=(0,1),initialize=0) m.x872 = Var(within=Reals,bounds=(0,1),initialize=0) m.x873 = Var(within=Reals,bounds=(0,1),initialize=0) m.x874 = Var(within=Reals,bounds=(0,1),initialize=0) m.x875 = Var(within=Reals,bounds=(0,1),initialize=0) m.x876 = Var(within=Reals,bounds=(0,1),initialize=0) m.x877 = Var(within=Reals,bounds=(0,1),initialize=0) m.x878 = Var(within=Reals,bounds=(0,1),initialize=0) m.x879 = Var(within=Reals,bounds=(0,1),initialize=0) m.x880 = Var(within=Reals,bounds=(0,1),initialize=0) m.x881 = Var(within=Reals,bounds=(0,1),initialize=0) m.x882 = Var(within=Reals,bounds=(0,1),initialize=0) m.x883 = Var(within=Reals,bounds=(0,1),initialize=0) m.x884 = Var(within=Reals,bounds=(0,1),initialize=0) m.x885 = Var(within=Reals,bounds=(0,1),initialize=0) m.x886 = Var(within=Reals,bounds=(0,1),initialize=0) m.x887 = Var(within=Reals,bounds=(0,1),initialize=0) m.x888 = Var(within=Reals,bounds=(0,1),initialize=0) m.x889 = Var(within=Reals,bounds=(0,1),initialize=0) m.x890 = Var(within=Reals,bounds=(0,1),initialize=0) m.x891 = Var(within=Reals,bounds=(0,1),initialize=0) m.x892 = Var(within=Reals,bounds=(0,1),initialize=0) m.x893 = Var(within=Reals,bounds=(0,1),initialize=0) m.x894 = Var(within=Reals,bounds=(0,1),initialize=0) m.x895 = Var(within=Reals,bounds=(0,1),initialize=0) m.x896 = Var(within=Reals,bounds=(0,1),initialize=0) m.x897 = Var(within=Reals,bounds=(0,1),initialize=0) m.x898 = Var(within=Reals,bounds=(0,1),initialize=0) m.x899 = Var(within=Reals,bounds=(0,1),initialize=0) m.x900 = Var(within=Reals,bounds=(0,1),initialize=0) m.x901 = Var(within=Reals,bounds=(0,1),initialize=0) m.x902 = Var(within=Reals,bounds=(0,1),initialize=0) m.x903 = Var(within=Reals,bounds=(0,1),initialize=0) m.x904 = Var(within=Reals,bounds=(0,1),initialize=0) m.x905 = Var(within=Reals,bounds=(0,1),initialize=0) m.x906 = Var(within=Reals,bounds=(0,1),initialize=0) m.x907 = Var(within=Reals,bounds=(0,1),initialize=0) m.x908 = Var(within=Reals,bounds=(0,1),initialize=0) m.x909 = Var(within=Reals,bounds=(0,1),initialize=0) m.x910 = Var(within=Reals,bounds=(0,1),initialize=0) m.x911 = Var(within=Reals,bounds=(0,1),initialize=0) m.x912 = Var(within=Reals,bounds=(0,1),initialize=0) m.x913 = Var(within=Reals,bounds=(0,1),initialize=0) m.x914 = Var(within=Reals,bounds=(0,1),initialize=0) m.x915 = Var(within=Reals,bounds=(0,1),initialize=0) m.x916 = Var(within=Reals,bounds=(0,1),initialize=0) m.x917 = Var(within=Reals,bounds=(0,1),initialize=0) m.x918 = Var(within=Reals,bounds=(0,1),initialize=0) m.x919 = Var(within=Reals,bounds=(0,1),initialize=0) m.x920 = Var(within=Reals,bounds=(0,1),initialize=0) m.x921 = Var(within=Reals,bounds=(0,1),initialize=0) m.x922 = Var(within=Reals,bounds=(0,1),initialize=0) m.x923 = Var(within=Reals,bounds=(0,1),initialize=0) m.x924 = Var(within=Reals,bounds=(0,1),initialize=0) m.x925 = Var(within=Reals,bounds=(0,1),initialize=0) m.x926 = Var(within=Reals,bounds=(0,1),initialize=0) m.x927 = Var(within=Reals,bounds=(0,1),initialize=0) m.x928 = Var(within=Reals,bounds=(0,1),initialize=0) m.x929 = Var(within=Reals,bounds=(0,1),initialize=0) m.x930 = Var(within=Reals,bounds=(0,1),initialize=0) m.x931 = Var(within=Reals,bounds=(0,1),initialize=0) m.x932 = Var(within=Reals,bounds=(0,1),initialize=0) m.x933 = Var(within=Reals,bounds=(0,1),initialize=0) m.x934 = Var(within=Reals,bounds=(0,1),initialize=0) m.x935 = Var(within=Reals,bounds=(0,1),initialize=0) m.x936 = Var(within=Reals,bounds=(0,1),initialize=0) m.x937 = Var(within=Reals,bounds=(0,1),initialize=0) m.x938 = Var(within=Reals,bounds=(0,1),initialize=0) m.x939 = Var(within=Reals,bounds=(0,1),initialize=0) m.x940 = Var(within=Reals,bounds=(0,1),initialize=0) m.x941 = Var(within=Reals,bounds=(0,1),initialize=0) m.x942 = Var(within=Reals,bounds=(0,1),initialize=0) m.x943 = Var(within=Reals,bounds=(0,1),initialize=0) m.x944 = Var(within=Reals,bounds=(0,1),initialize=0) m.x945 = Var(within=Reals,bounds=(0,1),initialize=0) m.x946 = Var(within=Reals,bounds=(0,1),initialize=0) m.x947 = Var(within=Reals,bounds=(0,1),initialize=0) m.x948 = Var(within=Reals,bounds=(0,1),initialize=0) m.x949 = Var(within=Reals,bounds=(0,1),initialize=0) m.x950 = Var(within=Reals,bounds=(0,1),initialize=0) m.x951 = Var(within=Reals,bounds=(0,1),initialize=0) m.x952 = Var(within=Reals,bounds=(0,1),initialize=0) m.x953 = Var(within=Reals,bounds=(0,1),initialize=0) m.x954 = Var(within=Reals,bounds=(0,1),initialize=0) m.x955 = Var(within=Reals,bounds=(0,1),initialize=0) m.x956 = Var(within=Reals,bounds=(0,1),initialize=0) m.x957 = Var(within=Reals,bounds=(0,1),initialize=0) m.x958 = Var(within=Reals,bounds=(0,1),initialize=0) m.x959 = Var(within=Reals,bounds=(0,1),initialize=0) m.x960 = Var(within=Reals,bounds=(0,1),initialize=0) m.x961 = Var(within=Reals,bounds=(0,1),initialize=0) m.x962 = Var(within=Reals,bounds=(0,1),initialize=0) m.x963 = Var(within=Reals,bounds=(0,1),initialize=0) m.x964 = Var(within=Reals,bounds=(0,1),initialize=0) m.x965 = Var(within=Reals,bounds=(0,1),initialize=0) m.x966 = Var(within=Reals,bounds=(0,1),initialize=0) m.x967 = Var(within=Reals,bounds=(0,1),initialize=0) m.x968 = Var(within=Reals,bounds=(0,1),initialize=0) m.x969 = Var(within=Reals,bounds=(0,1),initialize=0) m.x970 = Var(within=Reals,bounds=(0,1),initialize=0) m.x971 = Var(within=Reals,bounds=(0,1),initialize=0) m.x972 = Var(within=Reals,bounds=(0,1),initialize=0) m.x973 = Var(within=Reals,bounds=(0,1),initialize=0) m.x974 = Var(within=Reals,bounds=(0,1),initialize=0) m.x975 = Var(within=Reals,bounds=(0,1),initialize=0) m.x976 = Var(within=Reals,bounds=(0,1),initialize=0) m.x977 = Var(within=Reals,bounds=(0,1),initialize=0) m.x978 = Var(within=Reals,bounds=(0,1),initialize=0) m.x979 = Var(within=Reals,bounds=(0,1),initialize=0) m.x980 = Var(within=Reals,bounds=(0,1),initialize=0) m.x981 = Var(within=Reals,bounds=(0,1),initialize=0) m.x982 = Var(within=Reals,bounds=(0,1),initialize=0) m.x983 = Var(within=Reals,bounds=(0,None),initialize=0) m.x984 = Var(within=Reals,bounds=(0,None),initialize=0) m.x985 = Var(within=Reals,bounds=(0,None),initialize=0) m.x986 = Var(within=Reals,bounds=(0,None),initialize=0) m.x987 = Var(within=Reals,bounds=(0,None),initialize=0) m.x988 = Var(within=Reals,bounds=(0,None),initialize=0) m.x989 = Var(within=Reals,bounds=(0,None),initialize=0) m.x990 = Var(within=Reals,bounds=(0,None),initialize=0) m.x991 = Var(within=Reals,bounds=(0,None),initialize=0) m.x992 = Var(within=Reals,bounds=(0,None),initialize=0) m.x993 = Var(within=Reals,bounds=(0,None),initialize=0) m.x994 = Var(within=Reals,bounds=(0,None),initialize=0) m.x995 = Var(within=Reals,bounds=(0,None),initialize=0) m.x996 = Var(within=Reals,bounds=(0,None),initialize=0) m.x997 = Var(within=Reals,bounds=(0,None),initialize=0) m.x998 = Var(within=Reals,bounds=(0,None),initialize=0) m.x999 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1000 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1001 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1002 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1003 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1004 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1005 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1006 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1007 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1008 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1009 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1010 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1011 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1012 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1013 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1014 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1015 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1016 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1017 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1018 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1019 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1020 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1021 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1022 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1023 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1024 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1025 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1026 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1027 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1028 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1029 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1030 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1031 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1032 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1033 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1034 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1035 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1036 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1037 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1038 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1039 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1040 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1041 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1042 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1043 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1044 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1045 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1046 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1047 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1048 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1049 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1050 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1051 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1052 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1053 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1054 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1055 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1056 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1057 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1058 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1059 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1060 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1061 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1062 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1063 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1064 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1065 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1066 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1067 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1068 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1069 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1070 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1071 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1072 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1073 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1074 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1075 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1076 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1077 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1078 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1079 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1080 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1081 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1082 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1083 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1084 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1085 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1086 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1087 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1088 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1089 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1090 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1091 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1092 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1093 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1094 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1095 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1096 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1097 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1098 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1099 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1100 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1101 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1102 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1103 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1104 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1105 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1106 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1107 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1108 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1109 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1110 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1111 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1112 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1113 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1114 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1115 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1116 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1117 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1118 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1119 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1120 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1121 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1122 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1123 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1124 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1125 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1126 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1127 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1128 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1129 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1130 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1131 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1132 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1133 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1134 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1135 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1136 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1137 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1138 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1139 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1140 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1141 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1142 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1143 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1144 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1145 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1146 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1147 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1148 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1149 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1150 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1151 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1152 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1153 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1154 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1155 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1156 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1157 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1158 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1159 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1160 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1161 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1162 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1163 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1164 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1165 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1166 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1167 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1168 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1169 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1170 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1171 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1172 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1173 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1174 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1175 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1176 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1177 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1178 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1179 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1180 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1181 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1182 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1183 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1184 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1185 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1186 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1187 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1188 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1189 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1190 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1191 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1192 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1193 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1194 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1195 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1196 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1197 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1198 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1199 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1200 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1201 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1202 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1203 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1204 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1205 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1206 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1207 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1208 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1209 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1210 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1211 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1212 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1213 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1214 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1215 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1216 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1217 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1218 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1219 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1220 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1221 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1222 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1223 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1224 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1225 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1226 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1227 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1228 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1229 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1230 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1231 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1232 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1233 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1234 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1235 = Var(within=Reals,bounds=(0,None),initialize=0) m.x1236
old file in " + path_to_default_files + ".")) else: print("No changes to " + latlongs_file + ".") # Given either the new lat_longs file (if new coordinates were added in this iteration of the script) or the old file, # Construct the color_ordering.tsv file based on the data dictionary. Only places with existing coordinates are added. # Countries and divisions are sorted according to the coordinates, locations are sorted by the alphabet. Regions have # a fixed ordering. def build_ordering(data, new_latlongs): ordering = read_ordering(path_to_default_files) if new_latlongs: latlongs_path = path_to_output_files else: latlongs_path = path_to_default_files latlongs = read_latlongs(latlongs_path) # Drop all empty locations data_clean = {} for region in data: data_clean[region] = {} for country in data[region]: data_clean[region][country] = {} for division in data[region][country]: data_clean[region][country][division] = [] for location in data[region][country][division]: if location != "": data_clean[region][country][division].append(location) with open(path_to_output_files + ordering_file, "w") as out: for hierarchy in ordering: if hierarchy not in ["region", "country", "division", "location"]: for l in ordering[hierarchy]: out.write(hierarchy + "\t" + l + "\n") else: for region in region_order: if hierarchy == "region": out.write("region\t" + region + "\n") else: out.write("\n# " + region + "\n") for country in sort_by_coordinates(data_clean[region], latlongs["country"]): if hierarchy == "country": out.write("country\t" + country + "\n") else: if hierarchy == "location": if sum([len(data_clean[region][country][d]) for d in data_clean[region][country]]) > 0: # only write country as a comment if there is data following it out.write("\n### " + country) if hierarchy == "division": if len(data_clean[region][country]) > 0: out.write("\n### " + country + "\n") for division in sort_by_coordinates(data_clean[region][country], latlongs["division"]): if hierarchy == "division": out.write("division\t" + division + "\n") continue if len(data_clean[region][country][division]) > 0: # only write division as a comment if there is data following it out.write("\n# " + division + "\n") for location in sorted(data_clean[region][country][division]): out.write("location\t" + location + "\n") if hierarchy == "location" or hierarchy == "division": out.write("\n################\n") out.write("\n################\n\n\n") new_ordering = read_ordering(path_to_output_files) if not new_ordering == ordering: print(bold("Attention: " + ordering_file + " was altered! Remember to replace the old file in " + path_to_default_files + ".")) else: print("No changes to " + ordering_file + ".") # Sort a list of divisions or countries by latitude or longitude (whichever has the larger range) def sort_by_coordinates(data, coordinates): max_lat = -90 min_lat = 90 max_long = -150 min_long = 150 for loc in data: if loc in coordinates: (lat, long) = coordinates[loc] max_lat = max(max_lat, lat) min_lat = min(min_lat, lat) max_long = max(max_long, long) min_long = min(min_long, long) index = 1 if (max_lat - min_lat) > (max_long - min_long): index = 0 loc_per_coord = {} for loc in data: if loc in coordinates: coord = coordinates[loc][index] if coordinates[loc][index] in loc_per_coord: loc_per_coord[coord].append(loc) else: loc_per_coord[coord] = [loc] sorted_locs = [] for coord in sorted(loc_per_coord): sorted_locs.extend(loc_per_coord[coord]) return sorted_locs # Collect all stored annotations in a categorized manner, sorted by topics (e.g. geography-related) and annotation type # (e.g. location, division, country...) def read_annotations(annotationsFile, gisaid): types = {"geography": ["location", "division", "country", "region", "division_exposure", "country_exposure", "region_exposure"], "special": ["sampling_strategy", "date", "host", "strain"], "paper": ["title", "paper_url"]} types_inverted = {t:section for section, type in types.items() for t in type} annotations = {"comments": [], "geography": {}, "special": {}, "paper": {}} with open(path_to_annotations + annotationsFile) as f: line = f.readline() while line: if line.startswith("#"): annotations["comments"].append(line.strip()) else: l = line.strip().split("\t") if line.endswith("\t\n"): l.append("") if gisaid: if len(l) != 4: print("Invalid annotation length (annotation deleted): " + line.strip()) line = f.readline() continue else: id = l[0] + "\t" + l[1] type = l[2] content = l[3] else: if len(l) != 3: print("Invalid annotation: " + line.strip()) line = f.readline() continue else: id = l[0] type = l[1] content = l[2] if type not in types_inverted: print("Invalid annotation type (annotation deleted): " + line.strip()) else: section = types_inverted[type] if id not in annotations[section]: annotations[section][id] = {} if type in annotations[section][id]: print("Duplicate annotation (first annotation deleted): " + line.strip() + " vs. " + type + "\t" + annotations[section][id][type]) annotations[section][id][type] = content line = f.readline() return annotations # Given applied geoLocationRules and manualAnnotationRules, search the metadata for all affected strains def create_annotations(metadata_filename, applied_rules_geoLocation, applied_rules_manual, gisaid): geoLocationAnnotations = {} manualAnnotations = {} with open(path_to_metadata + metadata_filename) as f: header = f.readline().split("\t") country_i = header.index("country") region_i = header.index("region") division_i = header.index("division") location_i = header.index("location") strain_i = header.index("strain") gisaid_epi_isl_i = header.index("gisaid_epi_isl") genbank_accession_i = header.index("genbank_accession") host_i = header.index("host") line = f.readline() while line: l = line.split("\t") country = l[country_i] region = l[region_i] division = l[division_i] location = l[location_i] host = l[host_i] strain = l[strain_i] if gisaid: id = strain + "\t" + l[gisaid_epi_isl_i] else: id = l[genbank_accession_i] if (region, country, division, location) in applied_rules_geoLocation: geoLocationAnnotations[id] = (region, country, division, location), applied_rules_geoLocation[(region, country, division, location)] if (region, country, division, location) in applied_rules_manual: manualAnnotations[id] = (region, country, division, location), applied_rules_manual[(region, country, division, location)] line = f.readline() return geoLocationAnnotations, manualAnnotations # Compare old annotations with new alterations to the data and flag & adjust conflicts # (Since annotations overwrite geoLocationRules in the ncov-ingest pipeline, there is a need to find all annotations # that conflict with new rules and adjust the annotation accordingly) # For geoLocationRules, only test whether there are conflicting annotations that need adjustment. # For manualAnnotationRules, also produce new annotations. def find_conflicting_annotations(annotations, geoLocationAnnotations, manualAnnotations): for id in annotations["geography"]: for ruleSet in [geoLocationAnnotations, manualAnnotations]: if id in ruleSet: (region2, country2, division2, location2) = ruleSet[id][1] annotations_correct = {"region": region2, "country": country2, "division": division2, "location": location2} for type in annotations_correct: if type in annotations["geography"][id]: name0 = annotations["geography"][id][type] comment = "" if "#" in name0: (name0, comment) = name0.split(" #") if name0 != annotations_correct[type]: print("Conflicting annotation: " + id + "\t" + bold(type + " " + name0) + " will be replaced with " + bold(annotations_correct[type])) annotations["geography"][id][type] = annotations_correct[type] if comment != "": annotations["geography"][id][type] += " #" + comment for id in manualAnnotations: (region, country, division, location) = manualAnnotations[id][0] (region2, country2, division2, location2) = manualAnnotations[id][1] annotations_correct = {"region": (region, region2), "country": (country, country2), "division": (division, division2), "location": (location, location2)} for type in annotations_correct: if annotations_correct[type][0] != annotations_correct[type][1]: if id not in annotations["geography"]: annotations["geography"][id] = {} if type not in annotations["geography"][id]: annotations["geography"][id][type] = annotations_correct[type][1] + " # previously " + annotations_correct[type][0] return annotations clade_dates = { "19A": "2019-12-01", "19B": "2019-12-01", "20A": "2020-01-20", "20A.EU2": "2020-02-15", "20B": "2020-02-14", "20C": "2020-02-25", "20D": "2020-03-12", "20E (EU1)": "2020-05-27", "20F": "2020-05-24", "20G": "2020-06-11", "20H (Beta, V2)": "2020-08-10", "20I (Alpha, V1)": "2020-09-20", "20J (Gamma, V3)": "2020-10-29", "21A (Delta)": "2020-10-30", "21B (Kappa)": "2020-10-30", "21C (Epsilon)": "2020-08-03", "21D (Eta)": "2020-11-21", "21E (Theta)": "2021-01-10", "21F (Iota)": "2020-11-20", "21G (Lambda)": "2021-01-05", "21H": "2021-01-05", } # Check for special cases where annotations need to be introduced, e.g. special characters in strain names, or adjustment to "Mink" # Also check for sampling dates that are too early for the assigned clade and auto-add to exclude def special_metadata_checks(metadata_filename, annotations, gisaid): special_annotations = {} unknown_clades = [] with open(path_to_metadata + metadata_filename) as f: header = f.readline().strip().split("\t") strain_i = header.index("strain") gisaid_epi_isl_i = header.index("gisaid_epi_isl") genbank_accession_i = header.index("genbank_accession") host_i = header.index("host") clade_i = header.index("Nextstrain_clade") date_i = header.index("date") clock_deviation_i = header.index("clock_deviation") line = f.readline() while line: l = line.strip().split("\t") host = l[host_i] strain = l[strain_i] if gisaid: id = strain + "\t" + l[gisaid_epi_isl_i] else: id = l[genbank_accession_i] # Check for special cases where annotations need to be introduced, e.g. special characters in strain names, or adjustment to "Mink" if host == "Neovison vison" or host == "Mustela lutreola": print("Adjust host " + host + " to Mink") if id not in special_annotations: special_annotations[id] = {} special_annotations[id]["host"] = "Mink # previously " + host problematic_char = ["'", "`"] for c in problematic_char: if c in strain: strain2 = strain.replace(c, "-") print("Adjust strain " + strain + " to " + strain2) if id not in special_annotations: special_annotations[id] = {} special_annotations[id]["strain"] = strain2 + " # previously " + strain line = f.readline() for id in special_annotations: if id not in annotations["special"]: annotations["special"][id] = {} for type in special_annotations[id]: if type in annotations["special"][id]: if annotations["special"][id][type] != special_annotations[id][type]: print("Conflicting annotation: " + id + "\t" + bold(type +
#!/usr/bin/python3 # Author: GMFTBY # Time: 2019.9.16 ''' Translate the test dataset with the best trained model ''' import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import argparse from tqdm import tqdm import random import ipdb import math from utils import * from data_loader import * from metric.metric import * from model.seq2seq_attention import Seq2Seq from model.seq2seq_gp import Seq2Seq_Full, Seq2Seq_Normal, Seq2Seq_Vamp from model.seq2seq_multi_head_attention import Seq2Seq_Multi_Head from model.seq2seq_transformer import Transformer from model.HRED import HRED from model.VHRED import VHRED from model.KgCVAE import KgCVAE from model.HRAN import HRAN from model.HRAN_ablation import HRAN_ablation from model.WSeq import WSeq from model.WSeq_RA import WSeq_RA from model.DSHRED import DSHRED from model.DSHRED_RA import DSHRED_RA from model.MReCoSa import MReCoSa from model.MReCoSa_RA import MReCoSa_RA try: from model.MTGCN import MTGCN from model.MTGAT import MTGAT from model.GatedGCN import GatedGCN from model.layers import * except: print(f'[!] cannot load module torch_geometric, ignore it') def translate(**kwargs): # load the vocab tgt_vocab = load_pickle(kwargs['tgt_vocab']) src_vocab = load_pickle(kwargs['src_vocab']) src_w2idx, src_idx2w = src_vocab tgt_w2idx, tgt_idx2w = tgt_vocab # load dataset if kwargs['hierarchical'] == 1: if kwargs['graph'] == 1: test_iter = get_batch_data_graph(kwargs['src_test'], kwargs['tgt_test'], kwargs['test_graph'], kwargs['src_vocab'], kwargs['tgt_vocab'], kwargs['batch_size'], kwargs['maxlen'], kwargs["tgt_maxlen"], mode='test') else: if kwargs['model'] in ['VHRED','KgCVAE']: ld = False else: ld = True test_iter = get_batch_data(kwargs['src_test'], kwargs['tgt_test'], kwargs['src_vocab'], kwargs['tgt_vocab'], kwargs['batch_size'], kwargs['maxlen'], kwargs["tgt_maxlen"], ld=ld, mode='test') else: test_iter = get_batch_data_flatten(kwargs['src_test'], kwargs['tgt_test'], kwargs['src_vocab'], kwargs['tgt_vocab'], kwargs['batch_size'], kwargs['maxlen'], kwargs['tgt_maxlen'], mode='test') # pretrained mode pretrained = None # load net if kwargs['model'] == 'HRED': net = HRED(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'VHRED': net = VHRED(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], z_hidden=kwargs['z_hidden'], pretrained=pretrained) elif kwargs['model'] == 'KgCVAE': net = KgCVAE(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], eos=tgt_w2idx['<eos>'], unk=tgt_w2idx['<unk>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], z_hidden=kwargs['z_hidden'], pretrained=pretrained) elif kwargs['model'] == 'HRAN': net = HRAN(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'HRAN-ablation': net = HRAN_ablation(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'DSHRED': net = DSHRED(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'DSHRED_RA': net = DSHRED_RA(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'WSeq': net = WSeq(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'WSeq_RA': net = WSeq_RA(kwargs['embed_size'], len(src_w2idx), len(tgt_w2idx), kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], pretrained=pretrained) elif kwargs['model'] == 'Transformer': net = Transformer(len(src_w2idx), len(tgt_w2idx), kwargs['d_model'], kwargs['nhead'], kwargs['num_encoder_layers'], kwargs['dim_feedforward'], utter_n_layer=kwargs['utter_n_layer'], dropout=kwargs['dropout'], sos=tgt_w2idx['<sos>'], pad=tgt_w2idx['<pad>'], teach_force=kwargs['teach_force'], position_embed_size=kwargs['position_embed_size']) elif kwargs['model'] == 'MReCoSa': net = MReCoSa(len(src_w2idx), 512, len(tgt_w2idx), 512, 512, teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained) elif kwargs['model'] == 'MReCoSa_RA': net = MReCoSa_RA(len(src_w2idx), 512, len(tgt_w2idx), 512, 512, teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained) elif kwargs['model'] == 'Seq2Seq': net = Seq2Seq(len(src_w2idx), kwargs['embed_size'], len(tgt_w2idx), kwargs['utter_hidden' ], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained) elif kwargs['model'] == 'Seq2Seq_Full': net = Seq2Seq_Full(len(src_w2idx), kwargs['embed_size'], len(tgt_w2idx), kwargs['utter_hidden' ], kwargs['decoder_hidden'], kwargs['latent_size'], kwargs['kernel_v'], kwargs['kernel_r'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained) elif kwargs['model'] == 'Seq2Seq_Normal': net = Seq2Seq_Normal(len(src_w2idx), kwargs['embed_size'], len(tgt_w2idx), kwargs['utter_hidden' ], kwargs['decoder_hidden'], kwargs['latent_size'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained) elif kwargs['model'] == 'Seq2Seq_Vamp': net = Seq2Seq_Vamp(len(src_w2idx), kwargs['embed_size'], len(tgt_w2idx), kwargs['utter_hidden' ], kwargs['decoder_hidden'], kwargs['latent_size'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained) elif kwargs['model'] == 'Seq2Seq_MHA': net = Seq2Seq_Multi_Head(len(src_w2idx), kwargs['embed_size'], len(tgt_w2idx), kwargs['utter_hidden' ], kwargs['decoder_hidden'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], pretrained=pretrained, nhead=kwargs['nhead']) elif kwargs['model'] == 'MTGCN': net = MTGCN(len(src_w2idx), len(tgt_w2idx), kwargs['embed_size'], kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], kwargs['position_embed_size'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], context_threshold=kwargs['context_threshold']) elif kwargs['model'] == 'MTGAT': net = MTGAT(len(src_w2idx), len(tgt_w2idx), kwargs['embed_size'], kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], kwargs['position_embed_size'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], context_threshold=kwargs['context_threshold'], heads=kwargs['gat_heads']) elif kwargs['model'] == 'GatedGCN': net = GatedGCN(len(src_w2idx), len(tgt_w2idx), kwargs['embed_size'], kwargs['utter_hidden'], kwargs['context_hidden'], kwargs['decoder_hidden'], kwargs['position_embed_size'], teach_force=kwargs['teach_force'], pad=tgt_w2idx['<pad>'], sos=tgt_w2idx['<sos>'], dropout=kwargs['dropout'], utter_n_layer=kwargs['utter_n_layer'], context_threshold=kwargs['context_threshold']) else: raise Exception(f'[!] wrong model named {kwargs["model"]}') if torch.cuda.is_available(): net.cuda() net.eval() print('Net:') print(net) print(f'[!] Parameters size: {sum(x.numel() for x in net.parameters())}') # load best model load_best_model(kwargs['dataset'], kwargs['model'], kwargs['kernel_v'], net, min_threshold=kwargs['min_threshold'], max_threshold=kwargs["max_threshold"]) # calculate the loss criterion = nn.NLLLoss(ignore_index=tgt_w2idx['<pad>']) total_loss, batch_num = 0.0, 0 # translate with open(kwargs['pred'], 'w') as f: pbar = tqdm(test_iter) for batch in pbar: if kwargs['graph'] == 1: sbatch, tbatch, gbatch, subatch, tubatch, turn_lengths = batch else: sbatch, tbatch, turn_lengths = batch batch_size = tbatch.shape[1] if kwargs['hierarchical']: turn_size = len(sbatch) src_pad, tgt_pad = src_w2idx['<pad>'], tgt_w2idx['<pad>'] src_eos, tgt_eos = src_w2idx['<eos>'], tgt_w2idx['<eos>'] # output: [maxlen, batch_size], sbatch: [turn, max_len, batch_size] if kwargs['graph'] == 1: output, _ = net.predict(sbatch, gbatch, subatch, tubatch, len(tbatch), turn_lengths, loss=True) else: output, _ = net.predict(sbatch, len(tbatch), turn_lengths, loss=True) # true working ppl by using teach_force with torch.no_grad(): if kwargs['graph'] == 1: f_l = net(sbatch, tbatch, gbatch, subatch, tubatch, turn_lengths) else: f_l = net(sbatch, tbatch, turn_lengths) if type(f_l) == tuple: f_l = f_l[0] # teach_force over # ipdb.set_trace() loss = criterion(f_l[1:].view(-1, len(tgt_w2idx)), tbatch[1:].contiguous().view(-1)) batch_num += 1 total_loss += loss.item() for i in range(batch_size): ref = list(map(int, tbatch[:, i].tolist())) tgt = list(map(int, output[:, i].tolist())) # [maxlen] if kwargs['hierarchical']: src = [sbatch[j][:, i].tolist() for j in range(turn_size)] # [turns, maxlen] else: src = list(map(int, sbatch[:, i].tolist())) # filte the <pad> ref_endx = ref.index(tgt_pad) if tgt_pad in ref else len(ref) ref_endx_ = ref.index(tgt_eos) if tgt_eos in ref else len(ref) ref_endx = min(ref_endx, ref_endx_) ref = ref[1:ref_endx] ref = ' '.join(num2seq(ref, tgt_idx2w)) ref = ref.replace('<sos>', '').strip() ref = ref.replace('< user1 >', '').strip() ref = ref.replace('< user0 >', '').strip() tgt_endx = tgt.index(tgt_pad) if tgt_pad in tgt else len(tgt) tgt_endx_ = tgt.index(tgt_eos) if tgt_eos in tgt else len(tgt) tgt_endx = min(tgt_endx, tgt_endx_) tgt = tgt[1:tgt_endx] tgt = ' '.join(num2seq(tgt, tgt_idx2w)) tgt = tgt.replace('<sos>', '').strip() tgt = tgt.replace('< user1 >', '').strip() tgt = tgt.replace('< user0 >', '').strip() if kwargs['hierarchical']: source = [] for item in src: item_endx = item.index(src_pad) if src_pad in item else len(item) item_endx_ = item.index(src_eos) if src_eos in item else len(item) item_endx = min(item_endx, item_endx_) item = item[1:item_endx] item = num2seq(item, src_idx2w) source.append(' '.join(item)) src = ' __eou__ '.join(source) else: src_endx = src.index(src_pad) if src_pad in src else len(src) src_endx_ = src.index(src_eos) if src_eos in src else len(src) sec_endx = min(src_endx, src_endx_) src = src[1:src_endx] src = ' '.join(num2seq(src, src_idx2w)) f.write(f'- src: {src}\n') f.write(f'- ref: {ref}\n') f.write(f'- tgt: {tgt}\n\n') l = round(total_loss / batch_num, 4) print(f'[!] write the translate result into {kwargs["pred"]}') if kwargs['ppl'] == 'origin': print(f'[!] loss: {l}, PPL: {round(math.exp(l), 4)}', file=open(f'./processed/{kwargs["dataset"]}/{kwargs["model"]}/{kwargs["kernel_v"]}/pertub-ppl.txt', 'a')) else: raise Exception(f'[!] make sure the mode for ppl calculating is origin or ngram, but {kwargs["ppl"]} is given.') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Translate script') parser.add_argument('--src_test', type=str, default=None, help='src test file') parser.add_argument('--tgt_test', type=str, default=None, help='tgt test file') parser.add_argument('--min_threshold', type=int, default=0, help='epoch threshold for loading best model') parser.add_argument('--max_threshold', type=int, default=20, help='epoch threshold for loading best model') parser.add_argument('--batch_size', type=int, default=16, help='batch size') parser.add_argument('--model', type=str, default='HRED', help='model to be trained') parser.add_argument('--utter_n_layer', type=int, default=1, help='layer of encoder') parser.add_argument('--utter_hidden', type=int, default=150, help='utterance encoder hidden size') parser.add_argument('--latent_size', type=int, default=256, help='latent variable size') parser.add_argument('--kernel_v', type=float, default=1.0, help='kernel param v') parser.add_argument('--kernel_r', type=float, default=0.0001, help='kernel param r') parser.add_argument('--context_hidden', type=int, default=150, help='context encoder hidden size') parser.add_argument('--decoder_hidden', type=int, default=150, help='decoder hidden size') parser.add_argument('--seed', type=int, default=30, help='random seed') parser.add_argument('--embed_size', type=int, default=200, help='embedding layer size') parser.add_argument('--dataset', type=str, default='dailydialog', help='dataset for training') parser.add_argument('--src_vocab', type=str, default=None, help='src vocabulary') parser.add_argument('--tgt_vocab', type=str, default=None, help='tgt vocabulary') parser.add_argument('--maxlen', type=int, default=50, help='the maxlen of the utterance') parser.add_argument('--pred', type=str, default=None, help='the csv file save the output') parser.add_argument('--hierarchical', type=int, default=1, help='whether hierarchical architecture') parser.add_argument('--d_model', type=int, default=512, help='d_model for transformer') parser.add_argument('--nhead', type=int, default=8, help='head number for transformer') parser.add_argument('--num_encoder_layers', type=int, default=6) parser.add_argument('--num_decoder_layers', type=int, default=6) parser.add_argument('--dim_feedforward', type=int, default=2048) parser.add_argument('--tgt_maxlen', type=int, default=50, help='target sequence maxlen') parser.add_argument('--pretrained', type=str, default=None, help='pretrained mode') parser.add_argument('--contextrnn', dest='contextrnn', action='store_true') parser.add_argument('--no-contextrnn', dest='contextrnn', action='store_false') parser.add_argument('--position_embed_size', type=int, default=30) parser.add_argument('--test_graph', type=str, default=None) parser.add_argument('--graph', type=int, default=0) parser.add_argument('--plus', type=int,
<filename>color_dict.py color_dict = [{ 0: (0, 0, 0, 0), 1: (255, 255, 255, 255), 2: (204, 204, 204, 255), 3: (160, 160, 160, 255), 4: (128, 128, 128, 255), 5: (100, 100, 100, 255), 6: (51, 51, 51, 255), 7: (0, 0, 0, 255), 8: (238, 225, 197, 255), 9: (193, 123, 183, 255), 10: (255, 212, 216, 255), 11: (150, 116, 94, 255), 12: (255, 153, 153, 255), 13: (169, 96, 60, 255), 14: (204, 55, 55, 255), 15: (233, 98, 76, 255), 16: (229, 0, 79, 255), 17: (220, 0, 0, 255), 18: (134, 48, 48, 255), 19: (68, 11, 0, 255), 20: (195, 188, 165, 255), 21: (162, 154, 135, 255), 22: (216, 187, 125, 255), 23: (157, 131, 91, 255), 24: (255, 248, 176, 255), 25: (255, 255, 102, 255), 26: (215, 203, 70, 255), 27: (141, 136, 0, 255), 28: (230, 167, 58, 255), 29: (115, 85, 15, 255), 30: (97, 65, 51, 255), 31: (243, 204, 100, 255), 32: (240, 142, 55, 255), 33: (211, 238, 233, 255), 34: (159, 238, 241, 255), 35: (121, 199, 236, 255), 36: (49, 97, 134, 255), 37: (0, 153, 255, 255), 38: (0, 80, 178, 255), 39: (148, 206, 199, 255), 40: (136, 220, 174, 255), 41: (69, 178, 174, 255), 42: (151, 220, 96, 255), 43: (140, 255, 90, 255), 44: (117, 187, 0, 255), 45: (0, 204, 34, 255), 46: (40, 130, 70, 255), 47: (10, 57, 24, 255), 48: (170, 129, 255, 255), 49: (85, 52, 194, 255), 50: (255, 255, 255, 255), 51: (0, 0, 0, 255), 52: (19, 204, 163, 255), 53: (10, 105, 146, 255), 54: (142, 106, 12, 255), 55: (51, 51, 51, 255), 56: (158, 168, 255, 255), 57: (76, 190, 255, 255), 58: (26, 214, 214, 255), 59: (46, 209, 133, 255), 60: (88, 214, 34, 255), 61: (193, 229, 46, 255), 62: (245, 235, 103, 255), 63: (241, 183, 91, 255), 64: (255, 255, 255, 255), 65: (240, 142, 55, 255), 66: (255, 192, 80, 255), 67: (160, 248, 116, 255), 68: (76, 52, 47, 255), 500: (255, 123, 26, 255), 501: (0, 0, 0, 255), 502: (64, 191, 255, 255), 503: (0, 0, 0, 255), 504: (0, 204, 34, 255), 505: (0, 0, 0, 255), 506: (255, 255, 102, 255), 507: (0, 0, 0, 255), 508: (255, 128, 128, 255), 509: (0, 0, 0, 255), 510: (255, 232, 232, 255), 511: (192, 48, 0, 255), 512: (190, 205, 255, 255), 513: (27, 43, 158, 255), 514: (225, 197, 0, 238), 515: (255, 232, 232, 255), 516: (192, 48, 0, 255), 517: (102, 210, 255, 255), 518: (255, 40, 4, 255), 519: (255, 255, 255, 255), 520: (198, 154, 65, 255), 521: (255, 255, 255, 255), 522: (196, 119, 234, 255), 523: (255, 235, 234, 255), 524: (255, 112, 146, 255), 525: (255, 255, 255, 255), 526: (71, 186, 255, 255), 527: (255, 174, 0, 255), 528: (139, 95, 0, 255), 529: (48, 214, 255, 255), 530: (61, 101, 125, 255), 531: (255, 130, 97, 255), 532: (128, 74, 59, 255), 533: (255, 200, 200, 255), 534: (174, 0, 0, 255), 535: (255, 255, 192, 255), 536: (160, 88, 0, 255), 537: (255, 192, 255, 255), 538: (64, 0, 160, 255), 539: (255, 81, 81, 255), 540: (255, 182, 25, 255), 541: (192, 91, 254, 255), 542: (0, 150, 255, 255), 543: (0, 24, 255, 255), 544: (255, 86, 110, 255), 545: (180, 0, 0, 255), 546: (96, 184, 250, 255), 547: (196, 57, 99, 255), 548: (241, 198, 0, 255), 549: (243, 243, 243, 255), 550: (0, 0, 0, 255), 551: (192, 255, 192, 255), 552: (0, 0, 0, 255), 553: (89, 144, 255, 255), 554: (0, 0, 0, 255), 555: (179, 140, 255, 255), 556: (0, 0, 0, 255), 557: (255, 166, 102, 255), 558: (0, 0, 0, 255), 559: (255, 225, 25, 255), 560: (0, 0, 0, 255), 561: (250, 137, 182, 255), 562: (0, 0, 0, 255), 563: (233, 194, 156, 255), 564: (0, 0, 0, 255), 565: (255, 255, 255, 255), 566: (71, 186, 255, 255), 567: (255, 255, 255, 255), 568: (230, 167, 58, 255), 569: (255, 255, 255, 255), 570: (0, 204, 34, 255), 571: (255, 255, 255, 255), 572: (0, 0, 0, 255), 573: (249, 232, 70, 255), 574: (0, 0, 0, 255), 575: (55, 222, 153, 255), 576: (91, 226, 255, 255), 577: (255, 194, 64, 255), 578: (255, 90, 208, 255), 579: (128, 240, 240, 255), 580: (0, 32, 32, 255), 700: (255, 255, 255, 255), 701: (100, 100, 100, 255), 702: (0, 0, 0, 255), 703: (255, 212, 216, 255), 704: (204, 55, 55, 255), 705: (233, 98, 76, 255), 706: (240, 142, 55, 255), 707: (0, 153, 255, 255), 708: (170, 129, 255, 255), 709: (85, 52, 194, 255), 710: (245, 235, 103, 255), }, { 0: (0, 0, 0, 0), 1: (76, 52, 47, 255), 2: (103, 79, 69, 255), 3: (134, 111, 96, 255), 4: (160, 138, 119, 255), 5: (182, 161, 138, 255), 6: (250, 217, 174, 255), 7: (255, 243, 231, 255), 8: (125, 82, 59, 255), 9: (125, 69, 117, 255), 10: (145, 25, 37, 255), 11: (153, 119, 96, 255), 12: (145, 58, 58, 255), 13: (135, 78, 50, 255), 14: (148, 0, 0, 255), 15: (120, 20, 5, 255), 16: (204, 0, 71, 255), 17: (220, 0, 0, 255), 18: (168, 61, 61, 255), 19: (235, 180, 169, 255), 20: (135, 101, 74, 255), 21: (163, 135, 103, 255), 22: (115, 46, 9, 255), 23: (171, 120, 82, 255), 24: (97, 92, 40, 255), 25: (145, 145, 17, 255), 26: (175, 165, 59, 255), 27: (187, 183, 72, 255), 28: (153, 97, 0, 255), 29: (189, 165, 111, 255), 30: (207, 170, 155, 255), 31: (166, 127, 22, 255), 32: (163, 76, 0, 255), 33: (70, 115, 107, 255), 34: (42, 107, 110, 255), 35: (40, 102, 130, 255), 36: (106, 141, 168, 255), 37: (0, 87, 145, 255), 38: (90, 106, 125, 255), 39: (64, 145, 136, 255), 40: (45, 133, 84, 255), 41: (41, 125, 122, 255), 42: (71, 133, 21, 255), 43: (112, 161, 27, 255), 44: (86, 117, 33, 255), 45: (25, 148, 0, 255), 46: (71, 173, 71, 255), 47: (168, 247, 134, 255), 48: (96, 71, 145, 255), 49: (125, 115, 158, 255), 50: (255, 255, 255, 255), 51: (0, 0, 0, 255), 52: (19, 204, 163, 255), 53: (10, 105, 146, 255), 54: (142, 106, 12, 255), 55: (51, 51, 51, 255), 56: (107, 117, 209, 255), 57: (41, 138, 194, 255), 58: (10, 173, 160, 255), 59: (0, 167, 131, 255), 60: (47, 156, 0, 255), 61: (120, 150, 0, 255), 62: (138, 129, 6, 255), 63: (168, 104, 0, 255), 64: (156, 97, 22, 255), 65: (255, 177, 125, 255), 66: (219, 71, 25, 255), 67: (2, 117, 24, 255), 68: (76, 52, 47, 255), 500: (204, 86, 0, 255), 501: (255, 195, 172, 0), 502: (42, 148, 202, 255), 503: (225, 237, 255, 255), 504: (82, 160, 95, 255), 505: (197, 220, 141, 0), 506: (190, 103, 0, 255), 507: (255, 213, 140, 255), 508: (195, 70, 70, 255), 509: (255, 208, 208, 255), 510: (255, 232, 232, 255), 511: (192, 48, 0, 255), 512: (190, 205, 255, 255), 513: (27, 43, 158, 255), 514: (176, 116, 0, 255), 515: (255, 232, 232, 255), 516: (192, 48, 0, 255), 517: (102, 210, 255, 255), 518: (255, 40, 4, 255), 519: (255, 255, 255, 255), 520: (198, 154, 65, 255), 521: (255, 255, 255, 255), 522: (196, 119, 234, 255), 523: (255, 235, 234, 255), 524: (255, 112, 146, 255), 525:
the `member` dictionary. :type key: str :return: Returns the value of the member. :rtype: Anything """ return self.members[key] class DeconvolutionExperiment: """A deconvolution experiment class used to keep track of everything that is required to do a full AntiSplodge experiment. :param SC: A single-cell dataset, formatted as an AnnData object. :type SC: AnnData """ def __init__(self, SC): # h5ad/AnnData formated single-cell dataset self.SC = SC self.celltypes_column = "" self.celltypes = None self.num_classes = -1 self.verbose = False def setVerbosity(self, verbose): """Sets the verbosity level of the prints of the experiment, either True or False. :param verbose: Verboisty of the prints (True or False), this is False when the experiment is inititalized. :type verbose: bool """ self.verbose = verbose def setCellTypeColumn(self, name): """Column in the `SC` dataset, that holds the cell types. This create members: `celltypes_column`, `celltypes`, `num_classes`. :param name: Name (key) of the column. :type name: str """ self.celltypes_column = name self.celltypes = np.array(np.unique(self.SC.obs[name])) self.num_classes = len(self.celltypes) def splitTrainTestValidation(self, train=0.9, rest=0.5): """Split the `SC` dataset into training, validation and test dataset, the splits are strattified on the cell types. This create members: `trainIndex`, `valIndex`, `testIndex`, `SC_train`, `SC_val`, `SC_test`. :param train: A number between 0 and 1 controlling the proportion of samples used in the training dataset, defaults to 0.9 (90%) :type train: float (0.9, optional) :param rest: A number between 0 and 1 controlling the proportion of samples used in the training dataset (the rest will be in the validation dataset), defaults to 0.5 (A 50%/50% split) :type rest: float (0.5, optional) """ # # Split into train and rest # TrainIndex, RestIndex, _, _ = train_test_split(range(0,self.SC.n_obs), self.SC.obs[self.celltypes_column], test_size=1-train, stratify=self.SC.obs[self.celltypes_column]) # # Use the rest to split into validation and test # SC_rest = self.SC[RestIndex,:] ValIndex, TestIndex, _, _ = train_test_split(range(0,SC_rest.n_obs), SC_rest.obs[self.celltypes_column], test_size=rest, stratify=SC_rest.obs[self.celltypes_column]) # Final AnnData objects self.trainIndex = TrainIndex self.valIndex = ValIndex self.testIndex = TestIndex self.SC_train = self.SC[TrainIndex,:] self.SC_val = SC_rest[ValIndex,:] self.SC_test = SC_rest[TestIndex,:] def generateTrainTestValidation(self, num_profiles, CD): """Generate training, testing, and, validation profiles. This function will call `multinomialSampler`, `getConvolutedProfilesFromDistributions`, and, `getProportionFromCountVector`, in that order, for each dataset. This create members: `X_train_counts`, `X_val_counts`, `X_test_counts`, `X_train`, `X_val`, `X_test`, `Y_train`, `Y_val`, `Y_test`, `Y_train_prop`, `Y_val_prop`, `Y_test_prop`, `num_features`. :param num_profiles: A list of lengths 3, controlling the number of profiles used for training, testing, and, validation (index 0, 1, and, 2, respectively). :type num_profiles: list of ints, length = 3 :param CD: A list of lengths 2, controlling the number of cell densities used (index 0 is the minimum number of CDs, and index 1 is the maximum number of CDs). The same CD will be used for the training, testing, and, validation dataset, respectively. :type CD: list of ints, length = 2 """ # SAMPLE PROFILES if self.verbose: print("GENERATING PROFILES") X_train_profiles = multinomialSampler(self.num_classes, num_profiles[0], CD[0], CD[1]) X_val_profiles = multinomialSampler(self.num_classes, num_profiles[1], CD[0], CD[1]) X_test_profiles = multinomialSampler(self.num_classes, num_profiles[2], CD[0], CD[1]) if self.verbose: print("GENERATING TRAIN DATASET (N={})".format(len(X_train_profiles))) X_train, Y_train, I_ = getConvolutedProfilesFromDistributions(self.SC_train, self.celltypes, self.celltypes_column, X_train_profiles, normalize_X=True) Y_train_prop = getProportionFromCountVector(X_train_profiles) if self.verbose: print("GENERATING VALIDATION DATASET (N={})".format(len(X_val_profiles))) X_val, Y_val, I_ = getConvolutedProfilesFromDistributions(self.SC_val, self.celltypes, self.celltypes_column, X_val_profiles, normalize_X=True) Y_val_prop = getProportionFromCountVector(X_val_profiles) if self.verbose: print("GENERATING TEST DATASET (N={})".format(len(X_test_profiles))) X_test, Y_test, I_ = getConvolutedProfilesFromDistributions(self.SC_test, self.celltypes, self.celltypes_column, X_test_profiles, normalize_X=True) Y_test_prop = getProportionFromCountVector(X_test_profiles) # bind counts, proportions and convoluted profiles self.X_train_counts = X_train_profiles self.X_val_counts = X_val_profiles self.X_test_counts = X_test_profiles self.X_train = X_train self.X_val = X_val self.X_test = X_test self.Y_train = Y_train self.Y_val = Y_val self.Y_test = Y_test self.Y_train_prop = Y_train_prop self.Y_val_prop = Y_val_prop self.Y_test_prop = Y_test_prop # set features to the number of elements in X_train self.num_features = X_train[0].shape[0] def setupDataLoaders(self, batch_size=1000): """Will process the profiles generated by the `generateTrainTestValidation` method into ready-to-use data loaders. This create members: `train_loader`, `val_loader`, `test_loader`. :param batch_size: The number of samples in each batch, defaults to 1000 :type batch_size: int (1000, optional) """ # batch size for data loaders self.batch_size = batch_size dataset_train = SingleCellDataset(torch.from_numpy(np.array(self.X_train)).float(), torch.from_numpy(np.array(self.Y_train_prop)).float()) train_loader = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True ) train_loader_no_shuffle = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=False ) dataset_val = SingleCellDataset(torch.from_numpy(np.array(self.X_val)).float(), torch.from_numpy(np.array(self.Y_val_prop)).float()) val_loader = DataLoader( dataset=dataset_val, batch_size=batch_size, shuffle=True ) val_loader_no_shuffle = DataLoader( dataset=dataset_val, batch_size=batch_size, shuffle=False ) dataset_test = SingleCellDataset(torch.from_numpy(np.array(self.X_test)).float(), torch.from_numpy(np.array(self.Y_test_prop)).float()) test_loader = DataLoader( dataset=dataset_test, batch_size=batch_size # we don't shuffle test data ) # bind loaders self.train_loader = train_loader self.train_loader_no_shuffle = train_loader_no_shuffle self.val_loader = val_loader self.val_loader_no_shuffle = val_loader_no_shuffle self.test_loader = test_loader def setupModel(self, cuda_id=1, dropout=0.0, fps=512, sps=256, lps=128, ops=64, lp=1, normalize_output=False): """Initialize the feed forward neural network model. We recommend about half number of nodes per part for each subsequent layer part. The first layer should be smaller than the input. Check out the member variable `num_features`. This create members: `model`, `device`. :param cuda_id: The id of the CUDA device, this can be either an int for the id or "cpu" (to use CPU device), defaults to 1 :type cuda_id: int (or "cpu") (1, optional) :param dropout: [ParamDescription], defaults to 0.33 :type dropout: float (0.33, optional) :param fps: Nodes for each layer for the first part/block, defaults to 512 :type fps: int (512, optional) :param sps: Nodes for each layer for the second part/block, defaults to 256 :type sps: int (256, optional) :param lps: Nodes for each layer for the last part/block, defaults to 128 :type lps: int (128, optional) :param ops: Number of nodes in the last hidden layer just before the output layer, defaults to 64 :type ops: int (64, optional) :param lp: Layers per part/block, defaults to 1 :type lp: int (1, optional) """ # CUDA SETTINGS device = torch.device("cuda:{}".format(cuda_id) if torch.cuda.is_available() else "cpu") if self.verbose: print("(CUDA) device is: {}".format(device)) # setup the NN model model = CelltypeDeconvolver( num_feature = self.num_features, num_class=self.num_classes, number_of_layers_per_part = lp, first_part_size = fps, second_part_size = sps, last_part_size = lps, out_part_size = ops, input_dropout = dropout, normalize_output = normalize_output ) # bind to device model.Set("device", device) model.to(device) # bind settings and models self.device = device self.model = model def setupOptimizerAndCriterion(self, learning_rate = 0.001, optimizer=None, criterion=None): """Set the optimizer and criterion, and bind it to the model. This create members: `optimizer`, `criterion`. :param learning_rate: The learning rate of the optimizer, if you supply another optimizer, remember to set it yourself, defaults to 0.001 :type learning_rate: float (0.001, optional) :param optimizer: The neural network optimizer, defaults to `None`, and will then use pytorch's `optim.Adam`. :type optimizer: Pytorch optimizer (None, optional) :param criterion: The neural network criterion, defaults to `None`, and will then use pytorch's `nn.L1Loss`. :type criterion: Pytorch criterion or loss function (None, optional) """ # define optimizer and criterion if not set if optimizer == None: optimizer = optim.Adam(self.model.parameters(), lr=learning_rate) if criterion == None: criterion = torch.nn.L1Loss() # attach members as to the model object self.model.Set("optimizer", optimizer) self.model.Set("criterion", criterion) # bind optimizers self.optimizer = optimizer self.criterion = criterion def loadCheckpoint(self, checkpoint): """Loads a checkpoint file (.pt) containing the state of a neural network onto the `model` member variable. :param checkpoint: The path to the checkpoint file :type checkpoint: str """ print("Restoring checkpoint:", checkpoint) self.model.load_state_dict(torch.load(checkpoint)) def train(experiment, patience=25, save_file=None, auto_load_model_on_finish=True, best_loss=None, validation_metric="jsd"): """Train the model found in an experiment, this will utilize the train and validation dataset. :param patience: Patience counter, the training will stop once a new better loss hasn't been seen in the last `patience` epochs, defaults to 25 :type patience: int (25, optional) :param save_file: The file to save the model parameters each time a better setting has been found. This is done each time the validation error is better (lower) than the best seen. Defaults to None, in which case a time-stamped file will be used. :type save_file: str or None (None, optional) :param auto_load_model_on_finish: If the best model settings should be loaded back onto the model when the training stops, defaults to True :type auto_load_model_on_finish: bool (True, optional) :param best_loss: A loss function to beat in order to save the model as the new best, used for warm restarts, defaults to None. :type best_loss: float or None (None,
# Copyright (c) 2013 ARM Limited # All rights reserved # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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. # # Authors: <NAME> import parse import colours from colours import unknownColour from point import Point import re import blobs from time import time as wall_time import os id_parts = "TSPLFE" all_ids = set(id_parts) no_ids = set([]) class BlobDataSelect(object): """Represents which data is displayed for Ided object""" def __init__(self): # Copy all_ids self.ids = set(all_ids) def __and__(self, rhs): """And for filtering""" ret = BlobDataSelect() ret.ids = self.ids.intersection(rhs.ids) return ret class BlobVisualData(object): """Super class for block data colouring""" def to_striped_block(self, select): """Return an array of colours to use for a striped block""" return unknownColour def get_inst(self): """Get an instruction Id (if any) from this data""" return None def get_line(self): """Get a line Id (if any) from this data""" return None def __repr__(self): return self.__class__.__name__ + '().from_string(' + \ self.__str__() + ')' def __str__(self): return '' class Id(BlobVisualData): """A line or instruction id""" def __init__(self): self.isFault = False self.threadId = 0 self.streamSeqNum = 0 self.predictionSeqNum = 0 self.lineSeqNum = 0 self.fetchSeqNum = 0 self.execSeqNum = 0 def as_list(self): return [self.threadId, self.streamSeqNum, self.predictionSeqNum, self.lineSeqNum, self.fetchSeqNum, self.execSeqNum] def __cmp__(self, right): return cmp(self.as_list(), right.as_list()) def from_string(self, string): m = re.match('^(F;)?(\d+)/(\d+)\.(\d+)/(\d+)(/(\d+)(\.(\d+))?)?', string) def seqnum_from_string(string): if string is None: return 0 else: return int(string) if m is None: print 'Invalid Id string', string else: elems = m.groups() if elems[0] is not None: self.isFault = True else: self.isFault = False self.threadId = seqnum_from_string(elems[1]) self.streamSeqNum = seqnum_from_string(elems[2]) self.predictionSeqNum = seqnum_from_string(elems[3]) self.lineSeqNum = seqnum_from_string(elems[4]) self.fetchSeqNum = seqnum_from_string(elems[6]) self.execSeqNum = seqnum_from_string(elems[8]) return self def get_inst(self): if self.fetchSeqNum != 0: return self else: return None def get_line(self): return self def __str__(self): """Returns the usual id T/S.P/L/F.E string""" return ( str(self.threadId) + '/' + str(self.streamSeqNum) + '.' + str(self.predictionSeqNum) + '/' + str(self.lineSeqNum) + '/' + str(self.fetchSeqNum) + '.' + str(self.execSeqNum)) def to_striped_block(self, select): ret = [] if self.isFault: ret.append(colours.faultColour) if 'T' in select.ids: ret.append(colours.number_to_colour(self.threadId)) if 'S' in select.ids: ret.append(colours.number_to_colour(self.streamSeqNum)) if 'P' in select.ids: ret.append(colours.number_to_colour(self.predictionSeqNum)) if 'L' in select.ids: ret.append(colours.number_to_colour(self.lineSeqNum)) if self.fetchSeqNum != 0 and 'F' in select.ids: ret.append(colours.number_to_colour(self.fetchSeqNum)) if self.execSeqNum != 0 and 'E' in select.ids: ret.append(colours.number_to_colour(self.execSeqNum)) if len(ret) == 0: ret = [colours.unknownColour] if self.isFault: ret.append(colours.faultColour) return ret class Branch(BlobVisualData): """Branch data new stream and prediction sequence numbers, a branch reason and a new PC""" def __init__(self): self.newStreamSeqNum = 0 self.newPredictionSeqNum = 0 self.newPC = 0 self.reason = "NoBranch" self.id = Id() def from_string(self, string): m = re.match('^(\w+);(\d+)\.(\d+);([0-9a-fA-Fx]+);(.*)$', string) if m is not None: self.reason, newStreamSeqNum, newPredictionSeqNum, \ newPC, id = m.groups() self.newStreamSeqNum = int(newStreamSeqNum) self.newPredictionSeqNum = int(newPredictionSeqNum) self.newPC = int(newPC, 0) self.id = special_view_decoder(Id)(id) # self.branch = special_view_decoder(Branch)(branch) else: print "Bad Branch data:", string return self def to_striped_block(self, select): return [colours.number_to_colour(self.newStreamSeqNum), colours.number_to_colour(self.newPredictionSeqNum), colours.number_to_colour(self.newPC)] class Counts(BlobVisualData): """Treat the input data as just a /-separated list of count values (or just a single value)""" def __init__(self): self.counts = [] def from_string(self, string): self.counts = map(int, re.split('/', string)) return self def to_striped_block(self, select): return map(colours.number_to_colour, self.counts) class Colour(BlobVisualData): """A fixed colour block, used for special colour decoding""" def __init__(self, colour): self.colour = colour def to_striped_block(self, select): return [self.colour] class DcacheAccess(BlobVisualData): """Data cache accesses [RW];id""" def __init__(self): self.direc = 'R' self.id = Id() def from_string(self, string): self.direc, id = re.match('^([RW]);([^;]*);.*$', string).groups() self.id.from_string(id) return self def get_inst(self): return self.id def to_striped_block(self, select): if self.direc == 'R': direc_colour = colours.readColour elif self.direc == 'R': direc_colour = colours.writeColour else: direc_colour = colours.errorColour return [direc_colour] + self.id.to_striped_block(select) class ColourPattern(object): """Super class for decoders that make 2D grids rather than just single striped blocks""" def elems(self): return [] def to_striped_block(self, select): return [[[colours.errorColour]]] def special_view_decoder(class_): """Generate a decode function that checks for special character arguments first (and generates a fixed colour) before building a BlobVisualData of the given class""" def decode(symbol): if symbol in special_state_colours: return Colour(special_state_colours[symbol]) else: return class_().from_string(symbol) return decode class TwoDColours(ColourPattern): """A 2D grid pattern decoder""" def __init__(self, blockss): self.blockss = blockss @classmethod def decoder(class_, elemClass, dataName): """Factory for making decoders for particular block types""" def decode(pairs): if dataName not in pairs: print 'TwoDColours: no event data called:', \ dataName, 'in:', pairs return class_([[Colour(colours.errorColour)]]) else: parsed = parse.list_parser(pairs[dataName]) return class_(parse.map2(special_view_decoder(elemClass), \ parsed)) return decode @classmethod def indexed_decoder(class_, elemClass, dataName, picPairs): """Factory for making decoders for particular block types but where the list elements are pairs of (index, data) and strip and stripelems counts are picked up from the pair data on the decoder's picture file. This gives a 2D layout of the values with index 0 at strip=0, elem=0 and index 1 at strip=0, elem=1""" def decode(pairs): if dataName not in pairs: print 'TwoDColours: no event data called:', \ dataName, 'in:', pairs return class_([[Colour(colours.errorColour)]]) else: strips = int(picPairs['strips']) strip_elems = int(picPairs['stripelems']) raw_iv_pairs = pairs[dataName] parsed = parse.parse_indexed_list(raw_iv_pairs) array = [[Colour(colours.emptySlotColour) for i in xrange(0, strip_elems)] for j in xrange(0, strips)] for index, value in parsed: try: array[index % strips][index / strips] = \ special_view_decoder(elemClass)(value) except: print "Element out of range strips: %d," \ " stripelems %d, index: %d" % (strips, strip_elems, index) # return class_(array) return class_(array) return decode def elems(self): """Get a flat list of all elements""" ret = [] for blocks in self.blockss: ret += blocks return ret def to_striped_block(self, select): return parse.map2(lambda d: d.to_striped_block(select), self.blockss) class FrameColours(ColourPattern): """Decode to a 2D grid which has a single occupied row from the event data and some blank rows forming a frame with the occupied row as a 'title' coloured stripe""" def __init__(self, block, numBlankSlots): self.numBlankSlots = numBlankSlots self.block = block @classmethod def decoder(class_, elemClass, numBlankSlots, dataName): """Factory for element type""" def decode(pairs): if dataName not in pairs: print 'FrameColours: no event data called:', dataName, \ 'in:', pairs return class_([Colour(colours.errorColour)]) else: parsed = parse.list_parser(pairs[dataName]) return class_(special_view_decoder(elemClass) (parsed[0][0]), numBlankSlots) return decode def elems(self): return [self.block] def to_striped_block(self, select): return ([[self.block.to_striped_block(select)]] + (self.numBlankSlots * [[[colours.backgroundColour]]])) special_state_colours = { 'U': colours.unknownColour, 'B': colours.blockedColour, '-': colours.bubbleColour, '': colours.emptySlotColour, 'E': colours.emptySlotColour, 'R': colours.reservedSlotColour, 'X': colours.errorColour, 'F': colours.faultColour, 'r': colours.readColour, 'w': colours.writeColour } special_state_names = { 'U': '(U)nknown', 'B': '(B)locked', '-': '(-)Bubble', '': '()Empty', 'E': '(E)mpty', 'R': '(R)eserved', 'X': '(X)Error', 'F': '(F)ault', 'r': '(r)ead', 'w': '(w)rite' } special_state_chars = special_state_colours.keys() # The complete set of available block data types decoder_element_classes = { 'insts': Id,
import json from flameboi.common.flameboi import Flameboi # from slack_blockkit.block_element import ButtonElement from slack_blockkit.composition_object import TextObject from slack_blockkit.layout_block import DividerBlock, SectionBlock, ActionsBlock from slack_blockkit.utils import get_blocks, get_text_block_with_image def publish_init_home(user_id: str, theBot: Flameboi): """ Publishes an initial app home view to the specified user and sets the external id as the {user_id}_home. :return: None. """ response = theBot.bot_client.views_publish( user_id=user_id, view=json.dumps( { "type": "home", "title": {"type": "plain_text", "text": "Welcome!"}, "blocks": _get_about_block(), "external_id": f"{user_id}_home", }, ), ) assert response["ok"] def choose_home_view(action: str, user: str, theBot: Flameboi): """ Updates an app home view to the specified external id. Determined by the Action identified by the button as passed by argument. :return: None. """ if action == "About": response = theBot.bot_client.views_update( view=json.dumps( { "type": "home", "title": {"type": "plain_text", "text": "Welcome!"}, "blocks": _get_about_block(), "external_id": f"{user}_home", }, ), external_id=f"{user}_home", ) assert response["ok"] elif action == "Contact": response = theBot.bot_client.views_update( view=json.dumps( { "type": "home", "title": {"type": "plain_text", "text": "Welcome!"}, "blocks": _get_contact_block(), "external_id": f"{user}_home", }, ), external_id=f"{user}_home", ) assert response["ok"] elif action == "Channels": response = theBot.bot_client.views_update( view=json.dumps( { "type": "home", "title": {"type": "plain_text", "text": "Welcome!"}, "blocks": _get_channels_block(), "external_id": f"{user}_home", }, ), external_id=f"{user}_home", ) assert response["ok"] def _get_home_buttons() -> ActionsBlock: """ Constructs a block, which contains buttons for easy navigation on flameboi home tab. :return: ActionBlock containing 4 ButtonElements. :rtype: ActionBlock """ return ActionsBlock( elements=[ { "type": "button", "text": {"type": "plain_text", "text": "About", "emoji": True,}, "action_id": "About", }, { "type": "button", "text": {"type": "plain_text", "text": "Leadership", "emoji": True,}, "action_id": "Contact", }, { "type": "button", "text": {"type": "plain_text", "text": "Channels", "emoji": True,}, "action_id": "Channels", }, { "type": "button", "text": { "type": "plain_text", "text": "CodeDevils Website", "emoji": True, }, "action_id": "Link", "url": "https://www.codedevils.org", }, ], ) def _get_about_block() -> list: """ Constructs a block, which contains information on and links to the CodeDevils website. :return: The about message block as a list. :rtype: list """ block = get_blocks( ActionsBlock( elements=[ { "type": "button", "text": {"type": "plain_text", "text": "About", "emoji": True,}, "action_id": "About", }, { "type": "button", "text": { "type": "plain_text", "text": "Leadership", "emoji": True, }, "action_id": "Contact", }, { "type": "button", "text": {"type": "plain_text", "text": "Channels", "emoji": True,}, "action_id": "Channels", }, { "type": "button", "text": { "type": "plain_text", "text": "CodeDevils Website", "emoji": True, }, "action_id": "Link", "url": "https://www.codedevils.org", }, ], ), DividerBlock(), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "Welcome to *CodeDevils*! I'm Flameboi, and I'll help you get settled. " "\n\n*A little about us:*" ), ), ), DividerBlock(), get_text_block_with_image( text=( "\n\n*Rules:*" "\n\n\t- All of <https://eoss.asu.edu/dos/srr/codeofconduct|" "ASU's Code of Conduct> applies!" "\n\t- Be nice!" "\n\t- Be professional!" "\n\t- Be postin' in the correct channels!\n" ), image_url=( "https://cdn0.iconfinder.com/data/icons/media-flat-2/58/012_-_Settings-512.png" ), alt_text="Rules", ), DividerBlock(), get_text_block_with_image( text=( "\n\n*Good Info:*" "\n\nGeneral Body Meetings (GBMs) are open to all members and are held every other Monday, " "at 6pm AZ time (except during summer) via Slack video conference in #meetings." "\n\nPertinent news and reminders are posted in #announcements, be sure to check!" "\n\nAdd the <https://calendar.google.com/calendar/b/2?cid=Y29kZWRldm" "lscy5pbmZvQGdtYWlsLmNvbQ|calendar> to your own so you don't miss anything!" "\n\nWe’ve recently reorganized the Slack, cutting down a lot of bloat. " "New members have been automatically added to each channel, but if " "you’re a veteran member you may have to join the channels manually.\n" ), image_url=( "https://cdn0.iconfinder.com/data/icons/media-flat-2/58/001_-_play-512.png" ), alt_text="Info", ), DividerBlock(), get_text_block_with_image( text=( "\n\n*Get Involved:*" "\n\nYou’re a part of CodeDevils, take advantage of it!\n" "\n\nCodeDevils is a real club, with real memberships and perks. If you haven’t already, " "<https://asu.campuslabs.com/engage/organization/codedevils|register> on SunDevil Sync. This helps us with " "accurate headcounting, which can be used to justify funding from ASU for fun things.\n" "\n\nCheck out various channels with the button above!\n" "\n\nCheckout the CodeDevils \n" ), image_url=( "https://cdn0.iconfinder.com/data/icons/media-flat-2/58/007_-_Record-512.png" ), alt_text="Get Involved", ), DividerBlock(), get_text_block_with_image( text=("\n<https://github.com/ASU-CodeDevils|GitHub>\n"), image_url=( "https://cdn3.iconfinder.com/data/icons/social-media-2169/24/social_media_social_media_logo_github_2-512.png" ), alt_text="Twitter", ), DividerBlock(), get_text_block_with_image( text=("\n<https://twitter.com/code_devils|Twitter>\n"), image_url=( "https://cdn3.iconfinder.com/data/icons/social-media-2169/24/social_media_social_media_logo_twitter-512.png" ), alt_text="Twitter", ), DividerBlock(), get_text_block_with_image( text=("\n<https://www.instagram.com/code.devils/|Instagram>\n"), image_url=( "https://cdn3.iconfinder.com/data/icons/social-media-2169/24/social_media_social_media_logo_instagram-512.png" ), alt_text="Instagram", ), DividerBlock(), get_text_block_with_image( text=("\n<https://www.facebook.com/codedevils.asu|Facebook>\n"), image_url=( "https://cdn3.iconfinder.com/data/icons/social-media-2169/24/social_media_social_media_logo_facebook-512.png" ), alt_text="Facebook", ), ) return block def _get_contact_block() -> list: """ Constructs an contacts block, which contains information on the leadership of CodeDevils website. :return: The contacts message block as a list. :rtype: list """ block = get_blocks( ActionsBlock( elements=[ { "type": "button", "text": {"type": "plain_text", "text": "About", "emoji": True,}, "action_id": "About", }, { "type": "button", "text": { "type": "plain_text", "text": "Leadership", "emoji": True, }, "action_id": "Contact", }, { "type": "button", "text": {"type": "plain_text", "text": "Channels", "emoji": True,}, "action_id": "Channels", }, { "type": "button", "text": { "type": "plain_text", "text": "CodeDevils Website", "emoji": True, }, "action_id": "Link", "url": "https://www.codedevils.org", }, ], ), DividerBlock(), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "Welcome to *CodeDevils*! I'm Flameboi, and I'll help you get settled. " "\n\n*Our Leadership:*" ), ), ), DividerBlock(), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "If you have questions or concerns, send an email to <EMAIL> or reach out " "to any CodeDevils leadership on Slack or email:" ), ), ), DividerBlock(), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "\nPresident:" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @dswelbor" ), ), ), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "\nVice President:" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @jwdouble" ), ), ), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "\nTreasurer:" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @pbrannan " ), ), ), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "\nSecretary:" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @jnaylor3" ), ), ), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "\nWebmasters:" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @vperuzzi" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @jcreyno5" "\n\t<NAME>\n\t\tEmail: <EMAIL>\n\t\tSlack: @jlabrec" ), ), ), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "\nStaff Advisor (ASU Professor):" "\n\t<NAME> \n\t\tEmail: <EMAIL>\n\t\tSlack:@racuna1" ), ), ), ) return block def _get_channels_block() -> list: """ Constructs an onboarding block, which contains information on different channels and a link to the CodeDevils website. :return: The onboarding message block as a list. :rtype: list """ hacker_rank_current_url = "https://www.hackerrank.com/codedevils-spring-challenge" block = get_blocks( ActionsBlock( elements=[ { "type": "button", "text": {"type": "plain_text", "text": "About", "emoji": True,}, "action_id": "About", }, { "type": "button", "text": { "type": "plain_text", "text": "Leadership", "emoji": True, }, "action_id": "Contact", }, { "type": "button", "text": {"type": "plain_text", "text": "Channels", "emoji": True,}, "action_id": "Channels", }, { "type": "button", "text": { "type": "plain_text", "text": "CodeDevils Website", "emoji": True, }, "action_id": "Link", "url": "https://www.codedevils.org", }, ], ), DividerBlock(), SectionBlock( text=TextObject( btype=TextObject.BTYPE_MARKDOWN, text=( "Welcome to *CodeDevils*! I'm Flameboi, and I'll help you get settled. " "\n\n*Some of the channels to explore:*" ), ), ), DividerBlock(), get_text_block_with_image( text=( "*<#C2N5P84BD>*\nPost literally anything that you want! College is too boring to " "be serious all the time, so brighten someone's day up with a random thought" " or funny meme." ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_Messages-512.png" ), alt_text="Hangout", ), get_text_block_with_image( text=( "*<#CMGU8033K>*\n Take a minute to introduce yourself here. Tells us about yourself," " what you're looking to get out of your time at ASU, the program you're in, or something" " that interests you outside of your academic life!" ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_Books-512.png" ), alt_text="Intro", ), get_text_block_with_image( text=( "*<#C3UQCFHS5>*\nLearn about exciting new job opportunities and internships" " from other members, and gain insight on how to succeed during interviews." ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_Stock-512.png" ), alt_text="Careers", ), get_text_block_with_image( text=( "*<#C46E4B24Q>*\nTake part in our " f"<{hacker_rank_current_url}|HackerRank> challenges to improve your skills and compete to win " "CodeDevil's swag! We hold a new contest each term, jump in and get yourself a CodeDevils Tee!" ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_Settings-512.png" ), alt_text="Coding Challenges", ), get_text_block_with_image( text=( "*<#C311NUV6C>* and *<#C0111TQ05ML>*\nEver think about programming something" " real and usable with a team? Need help with something you're working on? These channels to join" " a project, discuss a problem, or even get something started." ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_Store-512.png" ), alt_text="Projects and Debugging", ), get_text_block_with_image( text=( "*<#C010TCLHME2>*\nTake some time away from studying and play some games with your fellow " " CodeDevils! Here you can find some people to team up with or team up against!" ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_iTunes-512.png" ), alt_text="Games", ), get_text_block_with_image( text=( "*<#CT06NE2AV>*\nTake part in CodeDevils club meetings. We hold/post" " Virtual Study Halls (usually 12-5pm AZ on Saturdays), club meetings, etc here." " These are usually zoom based." ), image_url=( "https://cdn0.iconfinder.com/data/icons/apple-apps/100/Apple_Whatsapp-512.png" ), alt_text="Meetings", ), get_text_block_with_image( text=( "*<#C30L07P18>*\nImportant announcements relating to the CodeDevils Club or " "ASU student body can be found here. Posts can include things such as virtual "
frag. This is due to isomeric substitution e.g.: two # different Me groups off a core. These are still valid matches but could be removed # by ensuring that the original smiles is also different # finally get the attachment point info back from the numeric id's fattach_str_R = self.refattach_dict[ self.double_pairs_dict[ctxm_id][molid_fragid_uid_R][0]] cattach_str_R = self.refattach_dict[ self.double_pairs_dict[ctxm_id][molid_fragid_uid_R][1]] fattach_str_L = self.refattach_dict[query_dict[ctxm_id][molid_fragid_uid_L][0]] cattach_str_L = self.refattach_dict[query_dict[ctxm_id][molid_fragid_uid_L][1]] yield molid_L, molid_R, ctx, frag_L, frag_R, fattach_str_L, cattach_str_L, \ fattach_str_R, cattach_str_R def iterator_double_pairs_dict(self, use_comparison_dict=False): """Method to iterate over Double Cut Dictionary structure and yield pairs""" for molid_L, molid_R, ctx, frag_L, frag_R, fattach_str_L, cattach_str_L, fattach_str_R, cattach_str_R \ in self.__subiterator_double_pairs_dict(use_comparison_dict): for count_ in range(2): # yield the pair twice, first raw data, second with flipped numbering if count_ == 0: # print molid_L, molid_R, ctx, frag_L, frag_R, fattach_str_L, cattach_str_L, fattach_str_R, # cattach_str_R yield molid_L, molid_R, ctx, frag_L, frag_R, fattach_str_L, cattach_str_L, fattach_str_R, \ cattach_str_R else: ctx = ctx.replace("[1", "[9") ctx = ctx.replace("[2", "[1") ctx = ctx.replace("[9", "[2") if '[12' not in frag_L: frag_L = frag_L.replace("[1", "[9") frag_L = frag_L.replace("[2", "[1") frag_L = frag_L.replace("[9", "[2") if '[12' not in frag_R: frag_R = frag_R.replace("[1", "[9") frag_R = frag_R.replace("[2", "[1") frag_R = frag_R.replace("[9", "[2") # regex to flip the numbers in the attachment points fattach_str_L = re.sub("\[(\d)(.*)\|(\d)(.*)", r"[\3\2|\1\4", fattach_str_L) cattach_str_L = re.sub("\[(\d)(.*)\|(\d)(.*)", r"[\3\2|\1\4", cattach_str_L) fattach_str_R = re.sub("\[(\d)(.*)\|(\d)(.*)", r"[\3\2|\1\4", fattach_str_R) cattach_str_R = re.sub("\[(\d)(.*)\|(\d)(.*)", r"[\3\2|\1\4", cattach_str_R) # print "-F-> ", molid_L, molid_R, ctx, frag_L, frag_R, fattach_str_L, cattach_str_L, # fattach_str_R, cattach_str_R yield molid_L, molid_R, ctx, frag_L, frag_R, fattach_str_L, cattach_str_L, fattach_str_R, \ cattach_str_R def _inspector_double_pairs_dict(self): """Method is simply used in validation work, it's not algorithmically useful. The code will confirm that dicer is canonicalising the double cut context fragments correctly. Incorrect canonicalisation will result in a double cut being represented in two different ways and stored independently, with different fragments against each case. Pairs will be missed as you only find mmp's for each of the different representations and not between the two representations. Correct canonicalisation will ensure this does not happen. The code below is searching for cases where two different canonicalised forms are stored with different fragments. The code should not return any results, thus proving that canonicalisation is done correctly. Example validation test code would be: def test_inspector_double_cut_pairs(self): self.test_mmp_object.build_from_dicer("twomillionsmi.smi", 'DOUBLE', 'NONE') self.test_mmp_object.inspector_double_pairs_dict() Ran on with 2.1M smi and no results were returned (no print to cmd line) unit test switched back to smiple input file """ # regex to find contexts that have a fragmentation point label of '1' regex_context1 = re.compile(r'\[1\w{1,3}\]') counter = 0 for ctxm_id in self.double_pairs_dict: counter += 1 # if (counter % 1000) == 0: # print "Iteration: ", counter # first deconvolute the context ids so we can get back the smiles ctx1_id, ctx2_id = inv_cantor(ctxm_id) ctx1_smi = self.refsmi_dict[ctx1_id] ctx2_smi = self.refsmi_dict[ctx2_id] if regex_context1.search(ctx1_smi) is not None: # got [1 so flip ctx1_smi_flipped = ctx1_smi.replace("[1", "[2") ctx2_smi_flipped = ctx2_smi.replace("[2", "[1") else: ctx1_smi_flipped = ctx1_smi.replace("[2", "[1") ctx2_smi_flipped = ctx2_smi.replace("[1", "[2") if ctx1_smi_flipped in self.refsmi_dict: ctx1_id_flipped = self.refsmi_dict[ctx1_smi_flipped] else: ctx1_id_flipped = None if ctx2_smi_flipped in self.refsmi_dict: ctx2_id_flipped = self.refsmi_dict[ctx2_smi_flipped] else: ctx2_id_flipped = None if ctx1_id_flipped is not None and ctx2_id_flipped is not None: ctxm_id_flipped = cantor(ctx1_id_flipped, ctx2_id_flipped) if ctxm_id_flipped in self.double_pairs_dict: # print "Iteration: ", counter, " had a duplicate reversed entry ctx smi" if self.double_pairs_dict[ctxm_id] != self.double_pairs_dict[ctxm_id_flipped]: # # OK, this is bad, it should not happen: print("Original:") print(("{} {}".format(ctxm_id, self.double_pairs_dict[ctxm_id]))) print("Double") print(("{} {}".format(ctxm_id_flipped, self.double_pairs_dict[ctxm_id_flipped]))) def print_to_file(self, out_fi, cut_type, inc_types_header=False): """Method to get pairs from the base data object of the class out_fi: The user specified output file cut_type: Specifies the type of fragmentation required. Allowed values are SINGLE, DOUBLE or BOTH. Currently this class does not support anything greater than double cut fragmentation Example usage: # give me a CSV named my_output.pairs of all the pairs: my_mmp_object.print_to_file('my_output.pairs', 'CSV', 'BOTH') # give me a CSV of only the DOUBLE cut pairs: my_mmp_object.print_to_file('my_output.pairs', 'CSV', 'DOUBLE') """ # check file write possible before start self.logger.info('Opening output file for write: %s' % out_fi) # check cut_type, convert to int if cut_type.upper() == 'DOUBLE': # confusing but faster later cut_type_id = 3 elif cut_type.upper() == 'BOTH': # confusing but faster later cut_type_id = 2 elif cut_type.upper() == 'SINGLE': cut_type_id = 1 else: self.logger.warn('cut_type specification is incorrect, using single cut: %s' % cut_type.upper()) cut_type_id = 1 # Now start processing the data structures to write the pairs with open(out_fi, "w") as f: # # write single header line # f.write("CUT,MOLID_L,MOLID_R,CONTEXT,FRAG_L,FRAG_R,ATTCHPT_FRAG_L," "ATTCHPT_CTX_L,ATTCHPT_FRAG_R,ATTCHPT_CTX_R\n") if inc_types_header: f.write("STRING,STRING,STRING,SMILES,SMILES,SMILES,STRING,STRING,STRING,STRING\n") # # print pairs for single if cut_type_id <= 2: # for molid_L, molid_R, ctx, frag_L, frag_R in self.iterator_single_pairs_dict(): for molid_L, molid_R, ctx, frag_L, frag_R, fa_L, ca_L, fa_R, ca_R \ in self.iterator_single_pairs_dict(): f.write('single,%d,%d,%s,%s,%s,%s,%s,%s,%s\n' % (molid_L, molid_R, ctx, frag_L, frag_R, fa_L, ca_L, fa_R, ca_R)) # # print pairs for double if cut_type_id >= 2: # for molid_L, molid_R, ctx, frag_L, frag_R in self.iterator_double_pairs_dict(): for molid_L, molid_R, ctx, frag_L, frag_R, fa_L, ca_L, fa_R, ca_R \ in self.iterator_double_pairs_dict(): f.write('double,%d,%d,%s,%s,%s,%s,%s,%s,%s\n' % (molid_L, molid_R, ctx, frag_L, frag_R, fa_L, ca_L, fa_R, ca_R)) # close the file handle f.close() self.logger.info('All done!') class _TestMMPObjectClass(unittest.TestCase): """Test class for MMPObjectClass(object) written to use pythons unittest Example usage: python mmp_objects.py coverage run mmp_objects.py coverage report mmp_objects.py """ def setUp(self): """Instantiate temp file names, test data objects that get written to temp files a silent logger object (needed to instantiate class) and the mmp object we'll test""" self.maxDiff = None self.temp_file_input_smi = tempfile.NamedTemporaryFile(delete=False, encoding='utf-8', mode='wt') self.temp_file_input_smi_1b = tempfile.NamedTemporaryFile(delete=False, encoding='utf-8', mode='wt') self.temp_file_input_smi_2 = tempfile.NamedTemporaryFile(delete=False, encoding='utf-8', mode='wt') self.temp_file_output_pairs = tempfile.NamedTemporaryFile(delete=False, encoding='utf-8', mode='wt') self.mmplogger = logging.getLogger('mmpobjectclass_testlogger') logging.disable(logging.CRITICAL) self.test_mmp_object = MMPObjectClass(self.mmplogger) # input is a set of smiles to generate pairs from # golden output data sets are the expected output from the code we'll run during the test self.test_dataset_input_smi_01 = { # basic test set # CHEMBL3105327 https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL3105327/ '3105327': 'Cc1ccc2c(ccn2c3nc(cs3)c4cc(ccc4F)C(F)(F)F)c1', # CHEMBL1526778 https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL1526778/ '1526778': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccc(C)c(C)c3', # CHEMBL1494678 https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL1494678/ '1494678': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccccc3', # test a bug converting double cut label [12 to [21 # CHEMBL472166 '472166': 'OC(CCn1ccnc1)(c2ccccc2)c3ccccc3', # CHEMBL69798 '69798': 'Cc1nccn1CCC(O)(c2ccccc2)c3ccccc3', } self.test_dataset_input_smi_01b = { # no pairs from these extras # CHEMBL367346 https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL367346/ '367346': 'Cc1sc(N)nc1c2cccc(Cl)c2', # https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL366881/ '366881': 'Cc1sc(N)nc1c2ccc(Cl)c(Cl)c2' } self.test_dataset_input_smi_02 = { # CHEMBL1477460 https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL1477460/ '1477460': 'COc1ccc(cc1)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C', # CHEMBL1441050 https://www.ebi.ac.uk/chembl/compound_report_card/CHEMBL1441050/ '1441050': 'COc1ccc(cc1OC)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C' } self.test_dataset_goldenoutput_pairs_01 = { 'CUT,MOLID_L,MOLID_R,CONTEXT,FRAG_L,FRAG_R,ATTCHPT_FRAG_L,ATTCHPT_CTX_L,ATTCHPT_FRAG_R,ATTCHPT_CTX_R': None, 'double,1526778,1494678,[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C,Cc1ccc(c2[n][2cH]s[1cH]2)cc1C,s1[2cH][n]c(c2ccccc2)[1cH]1,[2:NPL3|1:C3],[1:C2|2:C2],[2:NPL3|1:C3],[1:C2|2:C2]': None, 'double,1526778,1494678,[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C,Cc1ccc(c2[n][1cH]s[2cH]2)cc1C,s1[1cH][n]c(c2ccccc2)[2cH]1,[1:NPL3|2:C3],[2:C2|1:C2],[1:NPL3|2:C3],[2:C2|1:C2]': None, 'double,1526778,1494678,[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C,Cc1s[2cH][n]c1c1cc([1cH]cc1)C,s1[2cH][n]c(c2ccccc2)[1cH]1,[2:NPL3|1:C3],[1:CAR|2:C2],[2:NPL3|1:C3],[1:C2|2:C2]': None, 'double,1526778,1494678,[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C,Cc1s[1cH][n]c1c1cc([2cH]cc1)C,s1[1cH][n]c(c2ccccc2)[2cH]1,[1:NPL3|2:C3],[2:CAR|1:C2],[1:NPL3|2:C3],[2:C2|1:C2]': None, 'double,1526778,1494678,[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C,Cc1s[2cH][n]c1c1c[1cH]c(cc1)C,s1[2cH][n]c(c2ccccc2)[1cH]1,[2:NPL3|1:C3],[1:CAR|2:C2],[2:NPL3|1:C3],[1:C2|2:C2]': None, 'double,1526778,1494678,[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C,Cc1s[1cH][n]c1c1c[2cH]c(cc1)C,s1[1cH][n]c(c2ccccc2)[2cH]1,[1:NPL3|2:C3],[2:CAR|1:C2],[1:NPL3|2:C3],[2:C2|1:C2]': None, 'double,1494678,1526778,[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C,s1[2cH][n]c(c2ccccc2)[1cH]1,Cc1ccc(c2[n][2cH]s[1cH]2)cc1C,[2:NPL3|1:C3],[1:C2|2:C2],[2:NPL3|1:C3],[1:C2|2:C2]': None, 'double,1494678,1526778,[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C,s1[1cH][n]c(c2ccccc2)[2cH]1,Cc1ccc(c2[n][1cH]s[2cH]2)cc1C,[1:NPL3|2:C3],[2:C2|1:C2],[1:NPL3|2:C3],[2:C2|1:C2]': None, 'double,1494678,1526778,[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C,s1[2cH][n]c(c2ccccc2)[1cH]1,Cc1s[2cH][n]c1c1cc([1cH]cc1)C,[2:NPL3|1:C3],[1:C2|2:C2],[2:NPL3|1:C3],[1:CAR|2:C2]': None, 'double,1494678,1526778,[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C,s1[1cH][n]c(c2ccccc2)[2cH]1,Cc1s[1cH][n]c1c1cc([2cH]cc1)C,[1:NPL3|2:C3],[2:C2|1:C2],[1:NPL3|2:C3],[2:CAR|1:C2]': None, 'double,1494678,1526778,[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C,s1[2cH][n]c(c2ccccc2)[1cH]1,Cc1s[2cH][n]c1c1c[1cH]c(cc1)C,[2:NPL3|1:C3],[1:C2|2:C2],[2:NPL3|1:C3],[1:CAR|2:C2]': None, 'double,1494678,1526778,[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C,s1[1cH][n]c(c2ccccc2)[2cH]1,Cc1s[1cH][n]c1c1c[2cH]c(cc1)C,[1:NPL3|2:C3],[2:C2|1:C2],[1:NPL3|2:C3],[2:CAR|1:C2]': None, 'double,472166,69798,[1cH]1ccccc1.[2cH]1ccccc1,O[12CH2]CC[n]1c[n]cc1,O[12CH2]CC[n]1c([n]cc1)C,[2:CAR|1:CAR],[1:C3|2:C3],[2:CAR|1:CAR],[1:C3|2:C3]': None, 'double,472166,69798,[2cH]1ccccc1.[1cH]1ccccc1,O[12CH2]CC[n]1c[n]cc1,O[12CH2]CC[n]1c([n]cc1)C,[1:CAR|2:CAR],[2:C3|1:C3],[1:CAR|2:CAR],[2:C3|1:C3]': None, 'double,69798,472166,[1cH]1ccccc1.[2cH]1ccccc1,O[12CH2]CC[n]1c([n]cc1)C,O[12CH2]CC[n]1c[n]cc1,[2:CAR|1:CAR],[1:C3|2:C3],[2:CAR|1:CAR],[1:C3|2:C3]': None, 'double,69798,472166,[2cH]1ccccc1.[1cH]1ccccc1,O[12CH2]CC[n]1c([n]cc1)C,O[12CH2]CC[n]1c[n]cc1,[1:CAR|2:CAR],[2:C3|1:C3],[1:CAR|2:CAR],[2:C3|1:C3]': None} self.test_dataset_goldenoutput_pairs_02 = { 'CUT,MOLID_L,MOLID_R,CONTEXT,FRAG_L,FRAG_R,ATTCHPT_FRAG_L,ATTCHPT_CTX_L,ATTCHPT_FRAG_R,ATTCHPT_CTX_R': None, 'STRING,STRING,STRING,SMILES,SMILES,SMILES,STRING,STRING,STRING,STRING': None, 'single,1526778,1494678,Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1,Cc1cc[1cH]cc1C,[1cH]1ccccc1,[1:C2],[1:CAR],[1:C2],[1:CAR]': None, 'single,1494678,1526778,Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1,[1cH]1ccccc1,Cc1cc[1cH]cc1C,[1:C2],[1:CAR],[1:C2],[1:CAR]': None, 'single,472166,69798,O[1CH](c1ccccc1)c1ccccc1,[1CH3]C[n]1c[n]cc1,[1CH3]C[n]1c([n]cc1)C,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,69798,472166,O[1CH](c1ccccc1)c1ccccc1,[1CH3]C[n]1c([n]cc1)C,[1CH3]C[n]1c[n]cc1,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,472166,69798,OC([1CH3])(c1ccccc1)c1ccccc1,[1CH3][n]1c[n]cc1,[1CH3][n]1c([n]cc1)C,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,69798,472166,OC([1CH3])(c1ccccc1)c1ccccc1,[1CH3][n]1c([n]cc1)C,[1CH3][n]1c[n]cc1,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,472166,69798,OC(C[1CH3])(c1ccccc1)c1ccccc1,[1nH]1c[n]cc1,Cc1[1nH]cc[n]1,[1:C3],[1:NPL3],[1:C3],[1:NPL3]': None, 'single,69798,472166,OC(C[1CH3])(c1ccccc1)c1ccccc1,Cc1[1nH]cc[n]1,[1nH]1c[n]cc1,[1:C3],[1:NPL3],[1:C3],[1:NPL3]': None, 'single,472166,69798,OC(CC[n]1[1cH][n]cc1)(c1ccccc1)c1ccccc1,[1H],[1CH4],[1:C2],[1:H],[1:C2],[1:C3]': None, 'single,69798,472166,OC(CC[n]1[1cH][n]cc1)(c1ccccc1)c1ccccc1,[1CH4],[1H],[1:C2],[1:C3],[1:C2],[1:H]': None} self.test_dataset_goldenoutput_pairs_03 = { 'CUT,MOLID_L,MOLID_R,CONTEXT,FRAG_L,FRAG_R,ATTCHPT_FRAG_L,ATTCHPT_CTX_L,ATTCHPT_FRAG_R,ATTCHPT_CTX_R': None, 'STRING,STRING,STRING,SMILES,SMILES,SMILES,STRING,STRING,STRING,STRING': None, 'single,1526778,1494678,Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1,Cc1cc[1cH]cc1C,[1cH]1ccccc1,[1:C2],[1:CAR],[1:C2],[1:CAR]': None, 'single,1494678,1526778,Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1,[1cH]1ccccc1,Cc1cc[1cH]cc1C,[1:C2],[1:CAR],[1:C2],[1:CAR]': None, 'single,472166,69798,O[1CH](c1ccccc1)c1ccccc1,[1CH3]C[n]1c[n]cc1,[1CH3]C[n]1c([n]cc1)C,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,69798,472166,O[1CH](c1ccccc1)c1ccccc1,[1CH3]C[n]1c([n]cc1)C,[1CH3]C[n]1c[n]cc1,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,472166,69798,OC([1CH3])(c1ccccc1)c1ccccc1,[1CH3][n]1c[n]cc1,[1CH3][n]1c([n]cc1)C,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,69798,472166,OC([1CH3])(c1ccccc1)c1ccccc1,[1CH3][n]1c([n]cc1)C,[1CH3][n]1c[n]cc1,[1:C3],[1:C3],[1:C3],[1:C3]': None, 'single,472166,69798,OC(C[1CH3])(c1ccccc1)c1ccccc1,[1nH]1c[n]cc1,Cc1[1nH]cc[n]1,[1:C3],[1:NPL3],[1:C3],[1:NPL3]': None, 'single,69798,472166,OC(C[1CH3])(c1ccccc1)c1ccccc1,Cc1[1nH]cc[n]1,[1nH]1c[n]cc1,[1:C3],[1:NPL3],[1:C3],[1:NPL3]': None} self.test_dataset_goldenoutput_pairs_04 = copy.deepcopy(self.test_dataset_goldenoutput_pairs_03) self.test_dataset_goldenoutput_pairs_04['STRING,STRING,STRING,SMILES,SMILES,SMILES,STRING,STRING,STRING,STRING'] = None self.test_dataset_goldenoutput_pairs_05 = { (1477460, 1494678, 'Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n]c1c1cc[1cH]cc1'): ('[1OH]C', '[1H]'), (1477460, 1526778, 'Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1'): ('COc1cc[1cH]cc1', 'Cc1cc[1cH]cc1C'), (1477460, 1494678, 'Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1'): ('COc1cc[1cH]cc1', '[1cH]1ccccc1'), (1441050, 1526778, 'Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1'): ('COc1cc[1cH]cc1OC', 'Cc1cc[1cH]cc1C'), (1441050, 1494678, 'Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1'): ('COc1cc[1cH]cc1OC', '[1cH]1ccccc1')} self.test_dataset_goldenoutput_pairs_06 = { (1477460, 1526778, '[1CH4].Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][2cH]1'): ( '[1OH]c1cc[2cH]cc1', 'Cc1[1cH]c[2cH]cc1'), (1477460, 1526778, '[2CH4].Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1'): ( '[2OH]c1cc[1cH]cc1', 'Cc1[2cH]c[1cH]cc1'), (1441050, 1526778, '[1CH4].Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][2cH]1'): ( '[1OH]c1c(OC)cc[2cH]c1', 'Cc1[1cH]c[2cH]cc1'), (1441050, 1526778, '[2CH4].Cc1sc([n]2c(c(c(c2C)C(=O)C)C(=O)C)C)[n][1cH]1'): ( '[2OH]c1c(OC)cc[1cH]c1', 'Cc1[2cH]c[1cH]cc1'), (1477460, 1526778, '[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C'): ( 'COc1ccc(c2[n][2cH]s[1cH]2)cc1', 'Cc1s[2cH][n]c1c1c[1cH]c(cc1)C'), (1477460, 1526778, '[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C'): ( 'COc1ccc(c2[n][1cH]s[2cH]2)cc1', 'Cc1s[1cH][n]c1c1c[2cH]c(cc1)C'), (1477460, 1494678, '[1CH4].Cc1[2nH]c(c(c1C(=O)C)C(=O)C)C'): ( 'COc1ccc(c2[n][2cH]s[1cH]2)cc1', 's1[2cH][n]c(c2ccccc2)[1cH]1'), (1477460, 1494678, '[2CH4].Cc1[1nH]c(c(c1C(=O)C)C(=O)C)C'): ( 'COc1ccc(c2[n][1cH]s[2cH]2)cc1', 's1[1cH][n]c(c2ccccc2)[2cH]1')} self.test_dataset_goldenoutput_pairs_numeric = {(1526778, 1494678, 31, 30, 47): 1, (1494678, 1526778, 31, 47, 30): 1, (472166, 69798, 57, 56, 74): 1, (69798, 472166, 57, 74, 56): 1, (472166, 69798, 59, 58, 73): 1, (69798, 472166, 59, 73, 58): 1, (472166, 69798, 61, 60, 72): 1, (69798, 472166, 61, 72, 60): 1, (472166, 69798, 68, 12, 1): 1, (69798, 472166, 68, 1, 12): 1} self.test_dataset_goldenoutput_pairs_numeric_threshold03 = {(1526778, 1494678, 25, 24, 40): 1, (1494678, 1526778, 25, 40, 24): 1, (472166, 69798, 52, 51, 63): 1, (69798, 472166, 52, 63, 51): 1, (472166, 69798, 59, 8, 1): 1, (69798,
of segment fit IS2_atl03_fit[gtx]['land_ice_segments']['ground_track']['x_atc'] = Segment_X_atc[gtx] IS2_atl03_fill[gtx]['land_ice_segments']['ground_track']['x_atc'] = Segment_X_atc[gtx].fill_value IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_atc'] = {} IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_atc']['units'] = "meters" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_atc']['contentType'] = "referenceInformation" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_atc']['long_name'] = "X Along Track" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_atc']['description'] = ("The along-track " "x-coordinate of the segment, measured parallel to the RGT, measured from the ascending node of the equatorial " "crossing of a given RGT.") IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_atc']['coordinates'] = \ "../segment_id ../delta_time ../latitude ../longitude" #-- along-track Y coordinates of segment fit IS2_atl03_fit[gtx]['land_ice_segments']['ground_track']['y_atc'] = Segment_Y_atc[gtx] IS2_atl03_fill[gtx]['land_ice_segments']['ground_track']['y_atc'] = Segment_Y_atc[gtx].fill_value IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['y_atc'] = {} IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['y_atc']['units'] = "meters" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['y_atc']['contentType'] = "referenceInformation" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['y_atc']['long_name'] = "Y Along Track" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['y_atc']['description'] = ("The along-track " "y-coordinate of the segment, relative to the RGT, measured along the perpendicular to the RGT, " "positive to the right of the RGT.") IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['y_atc']['coordinates'] = \ "../segment_id ../delta_time ../latitude ../longitude" #-- along-track X coordinate spread of points used in segment fit IS2_atl03_fit[gtx]['land_ice_segments']['ground_track']['x_spread'] = Segment_X_spread[gtx] IS2_atl03_fill[gtx]['land_ice_segments']['ground_track']['x_spread'] = Segment_X_spread[gtx].fill_value IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_spread'] = {} IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_spread']['units'] = "meters" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_spread']['contentType'] = "referenceInformation" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_spread']['long_name'] = "X Along Track Spread" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_spread']['description'] = ("The spread of " "along-track x-coordinates for points used in the segment fit. Coordinates measured parallel to the " "RGT, measured from the ascending node of the equatorial crossing of a given RGT.") IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['x_spread']['coordinates'] = \ "../segment_id ../delta_time ../latitude ../longitude" #-- elevation fv = fileID[gtx]['geolocation']['ref_elev'].attrs['_FillValue'] ref_elev = np.ma.array(fileID[gtx]['geolocation']['ref_elev'][:], fill_value=fv) ref_elev.mask = ref_elev.data == ref_elev.fill_value segment_ref_elev = (ref_elev[1:] + ref_elev[0:-1])/2.0 segment_ref_elev.data[segment_ref_elev.mask] = segment_ref_elev.fill_value IS2_atl03_fit[gtx]['land_ice_segments']['ground_track']['ref_elev'] = segment_ref_elev IS2_atl03_fill[gtx]['land_ice_segments']['ground_track']['ref_elev'] = segment_ref_elev.fill_value IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_elev'] = {} IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_elev']['units'] = "radians" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_elev']['contentType'] = "referenceInformation" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_elev']['long_name'] = "Elevation" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_elev']['description'] = ("Elevation of the " "unit pointing vector for the reference photon in the local ENU frame in radians. The angle is measured " "from East-North plane and positive towards Up") IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_elev']['coordinates'] = \ "../segment_id ../delta_time ../latitude ../longitude" #-- azimuth fv = fileID[gtx]['geolocation']['ref_azimuth'].attrs['_FillValue'] ref_azimuth = np.ma.array(fileID[gtx]['geolocation']['ref_azimuth'][:], fill_value=fv) ref_azimuth.mask = ref_azimuth.data == ref_azimuth.fill_value segment_ref_azimuth = (ref_azimuth[1:] + ref_azimuth[0:-1])/2.0 segment_ref_azimuth.data[segment_ref_azimuth.mask] = segment_ref_azimuth.fill_value IS2_atl03_fit[gtx]['land_ice_segments']['ground_track']['ref_azimuth'] = segment_ref_azimuth IS2_atl03_fill[gtx]['land_ice_segments']['ground_track']['ref_azimuth'] = segment_ref_azimuth.fill_value IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_azimuth'] = {} IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_azimuth']['units'] = "radians" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_azimuth']['contentType'] = "referenceInformation" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_azimuth']['long_name'] = "Azimuth" IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_azimuth']['description'] = ("Azimuth of the " "unit pointing vector for the reference photon in the local ENU frame in radians. The angle is measured " "from North and positive towards East") IS2_atl03_attrs[gtx]['land_ice_segments']['ground_track']['ref_azimuth']['coordinates'] = \ "../segment_id ../delta_time ../latitude ../longitude" #-- parallel h5py I/O does not support compression filters at this time if (comm.rank == 0): #-- use default output file name and path if args.output: output_file=os.path.expanduser(args.output) else: fargs=(SUB,'ATL06',YY,MM,DD,HH,MN,SS,TRK,CYCL,GRAN,RL,VERS,AUX) file_format='{0}{1}_{2}{3}{4}{5}{6}{7}_{8}{9}{10}_{11}_{12}{13}.h5' output_file=os.path.join(ATL03_dir,file_format.format(*fargs)) #-- write to HDF5 file HDF5_ATL03_write(IS2_atl03_fit, IS2_atl03_attrs, COMM=comm, VERBOSE=args.verbose, INPUT=[args.ATL03,args.ATL09], FILL_VALUE=IS2_atl03_fill, CLOBBER=True, FILENAME=output_file) #-- change the permissions level to MODE os.chmod(output_file, args.mode) #-- close the input ATL03 file fileID.close() #-- PURPOSE: read ICESat-2 ATL09 HDF5 data file for specific variables def read_HDF5_ATL09(FILENAME, pfl, D, ATTRIBUTES=True, VERBOSE=False, COMM=None): #-- Open the HDF5 file for reading fileID = h5py.File(FILENAME, 'r', driver='mpio', comm=COMM) print(FILENAME) if VERBOSE and (COMM.rank == 0) else None #-- allocate python dictionaries for ICESat-2 ATL09 variables and attributes IS2_atl09_mds = {} IS2_atl09_attrs = {} #-- read profile reported for the ATLAS strong beams within the file IS2_atl09_mds[pfl] = dict(high_rate={}) #-- extract delta_time for mapping ATL09 atmospheric parameters to ATL03 delta_time = fileID[pfl]['high_rate']['delta_time'][:] #-- Calibrated Attenuated Backscatter at 25 hz high_rate_keys = ['aclr_true','bsnow_con','bsnow_dens','bsnow_h', 'bsnow_h_dens','bsnow_od','bsnow_psc','cloud_flag_asr','cloud_flag_atm', 'cloud_fold_flag','column_od_asr','column_od_asr_qf','msw_flag', 'snow_ice','solar_azimuth','solar_elevation','surf_refl_true'] #-- number of output ATL03 segments n_seg = len(D) #-- parallel indices for filling variables ii = np.arange(COMM.rank,n_seg,COMM.size) #-- extract variables of interest and map to ATL03 segments for key in high_rate_keys: val = np.copy(fileID[pfl]['high_rate'][key][:]) fint = scipy.interpolate.interp1d(delta_time, val, kind='nearest', fill_value='extrapolate') IS2_atl09_mds[pfl]['high_rate'][key] = np.zeros((n_seg),dtype=val.dtype) IS2_atl09_mds[pfl]['high_rate'][key][ii] = fint(D[ii]).astype(val.dtype) #-- Getting attributes of included variables if ATTRIBUTES: #-- Getting attributes of IS2_atl09_mds profile variables IS2_atl09_attrs[pfl] = dict(high_rate={}) #-- Global Group Attributes for att_name,att_val in fileID[pfl].attrs.items(): IS2_atl09_attrs[pfl][att_name] = att_val #-- Variable Attributes for key in high_rate_keys: IS2_atl09_attrs[pfl]['high_rate'][key] = {} for att_name,att_val in fileID[pfl]['high_rate'][key].attrs.items(): IS2_atl09_attrs[pfl]['high_rate'][key][att_name] = att_val #-- Global File Attributes if ATTRIBUTES: for att_name,att_val in fileID.attrs.items(): IS2_atl09_attrs[att_name] = att_val #-- Closing the HDF5 file fileID.close() #-- Return the datasets and variables return (IS2_atl09_mds,IS2_atl09_attrs) #-- PURPOSE: outputting the reduced and corrected ICESat-2 data to HDF5 def HDF5_ATL03_write(IS2_atl03_data, IS2_atl03_attrs, COMM=None, INPUT=None, FILENAME='', FILL_VALUE=None, CLOBBER=True, VERBOSE=False): #-- setting HDF5 clobber attribute if CLOBBER: clobber = 'w' else: clobber = 'w-' #-- open output HDF5 file fileID = h5py.File(FILENAME, clobber)#, driver='mpio', comm=COMM) print(FILENAME) if VERBOSE and (COMM.rank == 0) else None #-- create HDF5 records h5 = {} # #-- ICESat-2 spacecraft orientation at time # fileID.create_group('orbit_info') # h5['orbit_info'] = {} # for k,v in IS2_atl03_data['orbit_info'].items(): # #-- Defining the HDF5 dataset variables # val = 'orbit_info/{0}'.format(k) # h5['orbit_info'][k] = fileID.create_dataset(val, np.shape(v), data=v, # dtype=v.dtype, compression='gzip') # #-- add HDF5 variable attributes # for att_name,att_val in IS2_atl03_attrs['orbit_info'][k].items(): # h5['orbit_info'][k].attrs[att_name] = att_val #-- information ancillary to the data product #-- number of GPS seconds between the GPS epoch (1980-01-06T00:00:00Z UTC) #-- and ATLAS Standard Data Product (SDP) epoch (2018-01-01T00:00:00Z UTC) h5['ancillary_data'] = {} for k in ['atlas_sdp_gps_epoch','data_end_utc','data_start_utc','end_cycle', 'end_geoseg','end_gpssow','end_gpsweek','end_orbit','end_region', 'end_rgt','granule_end_utc','granule_start_utc','release','start_cycle', 'start_geoseg','start_gpssow','start_gpsweek','start_orbit','start_region', 'start_rgt','version']: #-- Defining the HDF5 dataset variables v = IS2_atl03_data['ancillary_data'][k] val = 'ancillary_data/{0}'.format(k) h5['ancillary_data'][k] = fileID.create_dataset(val, np.shape(v), data=v, dtype=v.dtype) #-- add HDF5 variable attributes for att_name,att_val in IS2_atl03_attrs['ancillary_data'][k].items(): h5['ancillary_data'][k].attrs[att_name] = att_val #-- land_ice_segments variable groups for each beam GROUPS=['fit_statistics','geophysical','ground_track','dem','bias_correction'] #-- write each output beam for gtx in ['gt1l','gt1r','gt2l','gt2r','gt3l','gt3r']: fileID.create_group(gtx) fileID['ancillary_data'].create_group(gtx) #-- add HDF5 group attributes for beam for att_name in ['Description','atlas_pce','atlas_beam_type', 'groundtrack_id','atmosphere_profile','atlas_spot_number', 'sc_orientation']: fileID[gtx].attrs[att_name] = IS2_atl03_attrs[gtx][att_name] #-- add transmit pulse shape and dead time parameters h5['ancillary_data'][gtx] = {} for k,v in IS2_atl03_data['ancillary_data'][gtx].items(): #-- attributes attrs = IS2_atl03_attrs['ancillary_data'][gtx][k] #-- Defining the HDF5 dataset variables val = 'ancillary_data/{0}/{1}'.format(gtx,k) h5['ancillary_data'][gtx][k] = fileID.create_dataset(val, np.shape(v), data=v, dtype=v.dtype) #-- add HDF5 variable attributes for att_name,att_val in attrs.items(): h5['ancillary_data'][gtx][k].attrs[att_name] = att_val #-- create land_ice_segments group fileID[gtx].create_group('land_ice_segments') h5[gtx] = dict(land_ice_segments={}) for att_name in ['Description','data_rate']: att_val = IS2_atl03_attrs[gtx]['land_ice_segments'][att_name] fileID[gtx]['land_ice_segments'].attrs[att_name] = att_val #-- segment_id v = IS2_atl03_data[gtx]['land_ice_segments']['segment_id'] attrs = IS2_atl03_attrs[gtx]['land_ice_segments']['segment_id'] # #-- parallel indices for filling variables # pind = np.arange(COMM.rank,len(v),COMM.size) #-- Defining the HDF5 dataset variables val = '{0}/{1}/{2}'.format(gtx,'land_ice_segments','segment_id') h5[gtx]['land_ice_segments']['segment_id'] = fileID.create_dataset(val, np.shape(v), data=v, dtype=v.dtype, compression='gzip') # with h5[gtx]['land_ice_segments']['segment_ID'].collective: # h5[gtx]['land_ice_segments']['segment_id'][pind] = v[pind] #-- make dimension h5[gtx]['land_ice_segments']['segment_id'].make_scale('segment_id') #-- add HDF5 variable attributes for att_name,att_val in attrs.items(): h5[gtx]['land_ice_segments']['segment_id'].attrs[att_name] = att_val #-- geolocation, time and height variables for k in ['latitude','longitude','delta_time','h_li','h_li_sigma', 'sigma_geo_h','atl06_quality_summary']: #-- values and attributes v = IS2_atl03_data[gtx]['land_ice_segments'][k] attrs = IS2_atl03_attrs[gtx]['land_ice_segments'][k] fillvalue = FILL_VALUE[gtx]['land_ice_segments'][k] #-- Defining the HDF5 dataset variables val = '{0}/{1}/{2}'.format(gtx,'land_ice_segments',k) h5[gtx]['land_ice_segments'][k] = fileID.create_dataset(val, np.shape(v), data=v, dtype=v.dtype, fillvalue=fillvalue, compression='gzip') # with h5[gtx]['land_ice_segments'][k].collective: # h5[gtx]['land_ice_segments'][k][pind] = v[pind] #-- attach dimensions for i,dim in enumerate(['segment_id']): h5[gtx]['land_ice_segments'][k].dims[i].attach_scale( h5[gtx]['land_ice_segments'][dim]) #-- add HDF5 variable attributes for att_name,att_val in attrs.items(): h5[gtx]['land_ice_segments'][k].attrs[att_name] = att_val #-- fit statistics, geophysical corrections, geolocation and dem for key in GROUPS: fileID[gtx]['land_ice_segments'].create_group(key) h5[gtx]['land_ice_segments'][key] = {} for att_name in ['Description','data_rate']: att_val=IS2_atl03_attrs[gtx]['land_ice_segments'][key][att_name] fileID[gtx]['land_ice_segments'][key].attrs[att_name] = att_val for k,v in IS2_atl03_data[gtx]['land_ice_segments'][key].items(): #-- attributes attrs = IS2_atl03_attrs[gtx]['land_ice_segments'][key][k] fillvalue = FILL_VALUE[gtx]['land_ice_segments'][key][k] #-- Defining the HDF5 dataset variables val = '{0}/{1}/{2}/{3}'.format(gtx,'land_ice_segments',key,k) if fillvalue: h5[gtx]['land_ice_segments'][key][k] = \ fileID.create_dataset(val, np.shape(v), data=v, dtype=v.dtype, fillvalue=fillvalue, compression='gzip') else: h5[gtx]['land_ice_segments'][key][k] = \ fileID.create_dataset(val, np.shape(v), data=v, dtype=v.dtype, compression='gzip') # with h5[gtx]['land_ice_segments'][key][k].collective: # h5[gtx]['land_ice_segments'][key][k][pind] = v[pind] #-- attach dimensions for i,dim in enumerate(['segment_id']): h5[gtx]['land_ice_segments'][key][k].dims[i].attach_scale( h5[gtx]['land_ice_segments'][dim]) #-- add HDF5 variable attributes for att_name,att_val in attrs.items(): h5[gtx]['land_ice_segments'][key][k].attrs[att_name] = att_val #-- HDF5 file title fileID.attrs['featureType'] = 'trajectory' fileID.attrs['title'] = 'ATLAS/ICESat-2 Land Ice Height' fileID.attrs['summary'] = ('Estimates of the ice-sheet mean surface height ' 'relative to the WGS-84 ellipsoid, and ancillary parameters needed to ' 'interpret and assess the quality of these height estimates.') fileID.attrs['description'] = ('Land ice surface heights for each beam, ' 'along and across-track slopes calculated for beam pairs. All ' 'parameters are calculated for the same along-track increments for ' 'each beam and repeat.') date_created = datetime.datetime.today() fileID.attrs['date_created'] = date_created.isoformat() project = 'ICESat-2 > Ice, Cloud, and land Elevation Satellite-2' fileID.attrs['project'] = project platform = 'ICESat-2 > Ice, Cloud, and land Elevation Satellite-2' fileID.attrs['project'] = platform #-- add attribute for elevation instrument and designated processing level instrument = 'ATLAS > Advanced Topographic Laser Altimeter System' fileID.attrs['instrument'] = instrument fileID.attrs['source'] = 'Spacecraft' fileID.attrs['references'] = 'https://nsidc.org/data/icesat-2' fileID.attrs['processing_level'] = '4' #-- add attributes for input ATL03 and ATL09 files fileID.attrs['input_files'] = ','.join([os.path.basename(i)
self.taiko_standard_recent(ctx, playerName) return player = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "OsuPlayer") if player == None: return await self.player_not_found(ctx) await self.taiko_standard_recent(ctx, player) return @commands.command(aliases = ["rctb"]) async def rcatch(self, ctx, *, player = None): """**INDONESIA** Cek recent game Osu!Catch. **ENGLISH** Check recent game Osu!Catch.""" LangCheck = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "Language") if LangCheck == None: await self.language_not_set(ctx) if type(player) == str: playerName = player await self.ctb_standard_recent(ctx, playerName) return player = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "OsuPlayer") if player == None: return await self.player_not_found(ctx) await self.ctb_standard_recent(ctx, player) return @commands.command() async def rmania(self, ctx, *, player = None): """**INDONESIA** Cek recent game Osu!Mania. **ENGLISH** Check recent game Osu!Mania.""" LangCheck = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "Language") if LangCheck == None: await self.language_not_set(ctx) if type(player) == str: playerName = player await self.mania_standard_recent(ctx, playerName) return player = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "OsuPlayer") if player == None: return await self.player_not_found(ctx) await self.mania_standard_recent(ctx, player) return async def player_not_found(self, ctx): LangCheck = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "Language") if LangCheck == "ID": msg = "> Kamu belum mengatur Osu!player dalam server ini.\n" msg += "> Silahkan ketik *`{}setosu [player]`*\n".format(ctx.prefix) msg += "> **Contoh**\n" msg += "> *`{}setosu kazereborn`*".format(ctx.prefix) em = discord.Embed(color = 0XFF8C00, description = msg) em.set_author(name = "Oops", icon_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Osu%21Logo_%282015%29.svg/1200px-Osu%21Logo_%282015%29.svg.png") em.set_footer(text = f"{ctx.author}", icon_url = f"{ctx.author.avatar_url}") return await ctx.send(embed = em) if LangCheck == "EN": msg = "> You have not set your Osu!player in this server.\n" msg += "> Please type *`{}setosu [player]`*\n".format(ctx.prefix) msg += "> **Example**\n" msg += "> *`{}setosu kazereborn`*".format(ctx.prefix) em = discord.Embed(color = 0XFF8C00, description = msg) em.set_author(name = "Oops", icon_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Osu%21Logo_%282015%29.svg/1200px-Osu%21Logo_%282015%29.svg.png") em.set_footer(text = f"{ctx.author}", icon_url = f"{ctx.author.avatar_url}") return await ctx.send(embed = em) async def std_statistic(self, ctx, player): LangCheck = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "Language") try: # STATISTIC PLAYER r = requests.get("https://osu.ppy.sh/api/get_user?k=526d85b33ad4b0912850229a00e17e91b612d653&m=0&u={}".format(player)) data = r.text data = json.loads(data) a = data #BEST PERFORMANCE r2 = requests.get("https://osu.ppy.sh/api/get_user_best?k=526d85b33ad4b0912850229a00e17e91b612d653&limit=1&m=0&u={}".format(str(a[0]["username"]))) data2 = r2.text data2 = json.loads(data2) b = data2 # BEATMAPS r3 = requests.get("https://osu.ppy.sh/api/get_beatmaps?k=526d85b33ad4b0912850229a00e17e91b612d653&b={}".format(str(b[0]["beatmap_id"]))) data3 = r3.text data3 = json.loads(data3) c = data3 # PEMBULATAN KABAWAH UNTUK LEVEL level = a[0]["level"] flevel = float(level) rlevel = int(flevel) # PEMBULATAN KEBAWAH UNTUK PERFORMANCE pp = a[0]["pp_raw"] fpp = float(pp) rpp = int(fpp) # PEMBULATAN KEBAWAH UNTUK AKURASI acc = a[0]["accuracy"] facc = float(acc) racc = int(facc) # PEMBULATAN UNTUK BEST PERFORMANCE bpp = b[0]["pp"] rbpp = float(bpp) rbpp = round(rbpp) # PENGAMBILAN 2 ANGKA DI BELAKANG KOMA UNTUK DIFFICULT BEATMAPS dbm = c[0]["difficultyrating"] rdbm = "{:.2f}".format(float(dbm)) # PENAMBAHAN TITIK SETIAP 3 DIGIT UNTUK SCORE tds = b[0]["score"] ttds = re.sub(r"(?<!^)(?=(\d{3})+$)", r".", "{}".format(tds)) # PENAMBAHAN TITIK SETIAP 3 DIGIT UNTUK PLAYCOUNT playCount = a[0]["playcount"] playCount = re.sub(r"(?<!^)(?=(\d{3})+$)", r".", "{}".format(playCount)) # ICON FLAG country = a[0]["country"] countryId = country.lower() print (countryId) flagimg = "https://flagpedia.net/data/flags/w702/{}.webp".format(countryId) # EMBED BOT UNTUK STATISTIC PLAYER if LangCheck == "ID": msg = "ID Player : {}\n".format(str(a[0]["user_id"])) msg += "Level : {}\n".format(str(rlevel)) msg += "Performance : {}pp\n".format(str(rpp)) msg += "Akurasi : {}%\n".format(str(racc)) msg += "Global Rank : #{}\n".format(str(a[0]["pp_rank"])) msg += "Local Rank : {}#{}\n".format(country, str(a[0]["pp_country_rank"])) msg += "Total Bermain : {}".format(playCount) em = discord.Embed(color = 0XFF8C00, description = "```\n{}\n```".format(msg)) em.set_author(name = "Osu!Standard profile {}".format(str(a[0]["username"])), icon_url = "{}".format(flagimg)) TotalRank = "<:ARank:788996704301088779> {} ".format(a[0]["count_rank_a"]) TotalRank += "<:SRank:788996986359251006> {} ".format(a[0]["count_rank_s"]) TotalRank += "<:SHRank:788997286477824022> {} ".format(a[0]["count_rank_sh"]) TotalRank += "<:SSRank:788997396470300712> {} ".format(a[0]["count_rank_ss"]) TotalRank += "<:SSHRank:788997506684026921> {}".format(a[0]["count_rank_ssh"]) em.add_field(name = "Total Rank", value = TotalRank) em.add_field(name = "Homepage Link", value = "https://osu.ppy.sh/users/{}".format(str(a[0]["user_id"])), inline = False) em.set_footer(text = f"{ctx.author}", icon_url=ctx.author.avatar_url) em.set_image(url = "http://lemmmy.pw/osusig/sig.php?colour=hexee8833&uname={}&removeavmargin&flagshadow&flagstroke&darkheader&darktriangles&opaqueavatar&rankedscore&onlineindicator=undefined&xpbar&xpbarhex".format(str(a[0]["user_id"]))) msg = await ctx.send(embed = em) if LangCheck == "EN": msg = "Player ID : {}\n".format(str(a[0]["user_id"])) msg += "Level : {}\n".format(str(rlevel)) msg += "Performance : {}pp\n".format(str(rpp)) msg += "Accuracy : {}%\n".format(str(racc)) msg += "Global Rank : #{}\n".format(str(a[0]["pp_rank"])) msg += "Local Rank : {}#{}\n".format(country, str(a[0]["pp_country_rank"])) msg += "Total Play : {}".format(playCount) em = discord.Embed(color = 0XFF8C00, description = "```\n{}\n```".format(msg)) em.set_author(name = "Osu!Standard profile {}".format(str(a[0]["username"])), icon_url = "{}".format(flagimg)) TotalRank = "<:ARank:788996704301088779> {} ".format(a[0]["count_rank_a"]) TotalRank += "<:SRank:788996986359251006> {} ".format(a[0]["count_rank_s"]) TotalRank += "<:SHRank:788997286477824022> {} ".format(a[0]["count_rank_sh"]) TotalRank += "<:SSRank:788997396470300712> {} ".format(a[0]["count_rank_ss"]) TotalRank += "<:SSHRank:788997506684026921> {}".format(a[0]["count_rank_ssh"]) em.add_field(name = "Total Rank", value = TotalRank) em.add_field(name = "Homepage Link", value = "https://osu.ppy.sh/users/{}".format(str(a[0]["user_id"])), inline = False) em.set_footer(text = f"{ctx.author}", icon_url=ctx.author.avatar_url) em.set_image(url = "http://lemmmy.pw/osusig/sig.php?colour=hexee8833&uname={}&removeavmargin&flagshadow&flagstroke&darkheader&darktriangles&opaqueavatar&rankedscore&onlineindicator=undefined&xpbar&xpbarhex".format(str(a[0]["user_id"]))) msg = await ctx.send(embed = em) except: if LangCheck == "ID": msg = "Player *`{}`* tidak ditemukan.".format(player) em = discord.Embed(color = 0XFF8C00, description = msg) em.set_footer(text = "{}".format(ctx.author), icon_url = "{}".format(ctx.author.avatar_url)) return await ctx.send(embed = em) if LangCheck == "EN": msg = "Player *`{}`* is not found.".format(player) em = discord.Embed(color = 0XFF8C00, description = msg) em.set_footer(text = "{}".format(ctx.author), icon_url = "{}".format(ctx.author.avatar_url)) return await ctx.send(embed = em) async def taiko_statistic(self, ctx, player): LangCheck = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "Language") try: # STATISTIC PLAYER r = requests.get("https://osu.ppy.sh/api/get_user?k=526d85b33ad4b0912850229a00e17e91b612d653&m=1&u={}".format(player)) data = r.text data = json.loads(data) a = data #BEST PERFORMANCE r2 = requests.get("https://osu.ppy.sh/api/get_user_best?k=526d85b33ad4b0912850229a00e17e91b612d653&limit=1&m=1&u={}".format(str(a[0]["username"]))) data2 = r2.text data2 = json.loads(data2) b = data2 # BEATMAPS r3 = requests.get("https://osu.ppy.sh/api/get_beatmaps?k=526d85b33ad4b0912850229a00e17e91b612d653&b={}".format(str(b[0]["beatmap_id"]))) data3 = r3.text data3 = json.loads(data3) c = data3 # PEMBULATAN KABAWAH UNTUK LEVEL level = a[0]["level"] flevel = float(level) rlevel = int(flevel) # PEMBULATAN KEBAWAH UNTUK PERFORMANCE pp = a[0]["pp_raw"] fpp = float(pp) rpp = int(fpp) # PEMBULATAN KEBAWAH UNTUK AKURASI acc = a[0]["accuracy"] facc = float(acc) racc = int(facc) # PEMBULATAN UNTUK BEST PERFORMANCE bpp = b[0]["pp"] rbpp = float(bpp) rbpp = round(rbpp) # PENGAMBILAN 2 ANGKA DI BELAKANG KOMA UNTUK DIFFICULT BEATMAPS dbm = c[0]["difficultyrating"] rdbm = "{:.2f}".format(float(dbm)) # PENAMBAHAN TITIK SETIAP 3 DIGIT UNTUK SCORE tds = b[0]["score"] ttds = re.sub(r"(?<!^)(?=(\d{3})+$)", r".", "{}".format(tds)) # PENAMBAHAN TITIK SETIAP 3 DIGIT UNTUK PLAYCOUNT playCount = a[0]["playcount"] playCount = re.sub(r"(?<!^)(?=(\d{3})+$)", r".", "{}".format(playCount)) # ICON FLAG country = a[0]["country"] countryId = country.lower() print (countryId) flagimg = "https://flagpedia.net/data/flags/w702/{}.webp".format(countryId) # EMBED BOT UNTUK STATISTIC PLAYER if LangCheck == "ID": msg = "ID Player : {}\n".format(str(a[0]["user_id"])) msg += "Level : {}\n".format(str(rlevel)) msg += "Performance : {}pp\n".format(str(rpp)) msg += "Akurasi : {}%\n".format(str(racc)) msg += "Global Rank : #{}\n".format(str(a[0]["pp_rank"])) msg += "Local Rank : {}#{}\n".format(country, str(a[0]["pp_country_rank"])) msg += "Total Bermain : {}".format(playCount) em = discord.Embed(color = 0XFF8C00, description = "```\n{}\n```".format(msg)) em.set_author(name = "Osu!Taiko profile {}".format(str(a[0]["username"])), icon_url = "{}".format(flagimg)) TotalRank = "<:ARank:788996704301088779> {} ".format(a[0]["count_rank_a"]) TotalRank += "<:SRank:788996986359251006> {} ".format(a[0]["count_rank_s"]) TotalRank += "<:SHRank:788997286477824022> {} ".format(a[0]["count_rank_sh"]) TotalRank += "<:SSRank:788997396470300712> {} ".format(a[0]["count_rank_ss"]) TotalRank += "<:SSHRank:788997506684026921> {}".format(a[0]["count_rank_ssh"]) em.add_field(name = "Total Rank", value = TotalRank) em.add_field(name = "Homepage Link", value = "https://osu.ppy.sh/users/{}".format(str(a[0]["user_id"])), inline = False) em.set_footer(text = f"{ctx.author}", icon_url=ctx.author.avatar_url) em.set_image(url = "http://lemmmy.pw/osusig/sig.php?colour=hexee8833&uname={}&mode=1&removeavmargin&flagshadow&flagstroke&darkheader&darktriangles&opaqueavatar&rankedscore&onlineindicator=undefined&xpbar&xpbarhex".format(str(a[0]["user_id"]))) msg = await ctx.send(embed = em) if LangCheck == "EN": msg = "ID Player : {}\n".format(str(a[0]["user_id"])) msg += "Level : {}\n".format(str(rlevel)) msg += "Performance : {}pp\n".format(str(rpp)) msg += "Accuracy : {}%\n".format(str(racc)) msg += "Global Rank : #{}\n".format(str(a[0]["pp_rank"])) msg += "Local Rank : {}#{}\n".format(country, str(a[0]["pp_country_rank"])) msg += "Total Play : {}".format(playCount) em = discord.Embed(color = 0XFF8C00, description = "```\n{}\n```".format(msg)) em.set_author(name = "Osu!Taiko profile {}".format(str(a[0]["username"])), icon_url = "{}".format(flagimg)) TotalRank = "<:ARank:788996704301088779> {} ".format(a[0]["count_rank_a"]) TotalRank += "<:SRank:788996986359251006> {} ".format(a[0]["count_rank_s"]) TotalRank += "<:SHRank:788997286477824022> {} ".format(a[0]["count_rank_sh"]) TotalRank += "<:SSRank:788997396470300712> {} ".format(a[0]["count_rank_ss"]) TotalRank += "<:SSHRank:788997506684026921> {}".format(a[0]["count_rank_ssh"]) em.add_field(name = "Total Rank", value = TotalRank) em.add_field(name = "Homepage Link", value = "https://osu.ppy.sh/users/{}".format(str(a[0]["user_id"])), inline = False) em.set_footer(text = f"{ctx.author}", icon_url=ctx.author.avatar_url) em.set_image(url = "http://lemmmy.pw/osusig/sig.php?colour=hexee8833&uname={}&mode=1&removeavmargin&flagshadow&flagstroke&darkheader&darktriangles&opaqueavatar&rankedscore&onlineindicator=undefined&xpbar&xpbarhex".format(str(a[0]["user_id"]))) msg = await ctx.send(embed = em) except: if LangCheck == "ID": msg = "Player *`{}`* tidak ditemukan".format(player) em = discord.Embed(color = 0XFF8C00, description = msg) em.set_footer(text = "{}".format(ctx.author), icon_url = "{}".format(ctx.author.avatar_url)) return await ctx.send(embed = em) if LangCheck == "EN": msg = "Player *`{}`* is not found".format(player) em = discord.Embed(color = 0XFF8C00, description = msg) em.set_footer(text = "{}".format(ctx.author), icon_url = "{}".format(ctx.author.avatar_url)) return await ctx.send(embed = em) async def ctb_statistic(self, ctx, player): LangCheck = self.settings.getUserStat(ctx.message.author, ctx.message.guild, "Language") try: # STATISTIC PLAYER r = requests.get("https://osu.ppy.sh/api/get_user?k=526d85b33ad4b0912850229a00e17e91b612d653&m=2&u={}".format(player)) data = r.text data = json.loads(data) a = data #BEST PERFORMANCE r2 = requests.get("https://osu.ppy.sh/api/get_user_best?k=526d85b33ad4b0912850229a00e17e91b612d653&limit=1&m=2&u={}".format(str(a[0]["username"]))) data2 = r2.text data2 = json.loads(data2) b = data2 # BEATMAPS r3 = requests.get("https://osu.ppy.sh/api/get_beatmaps?k=526d85b33ad4b0912850229a00e17e91b612d653&b={}".format(str(b[0]["beatmap_id"]))) data3 = r3.text data3 = json.loads(data3) c = data3 # PEMBULATAN KABAWAH UNTUK LEVEL level = a[0]["level"] flevel = float(level) rlevel = int(flevel) # PEMBULATAN KEBAWAH UNTUK PERFORMANCE pp = a[0]["pp_raw"] fpp = float(pp)
#/usr/bin/python from __future__ import print_function import argparse import torch import pickle import numpy as np import os import math import random import sys import matplotlib.pyplot as plt import seaborn as sns import scipy.io import data from sklearn.decomposition import PCA from torch import nn, optim from torch.nn import functional as F from detm import DETM from utils import nearest_neighbors, get_topic_coherence parser = argparse.ArgumentParser(description='The Embedded Topic Model') ### data and file related arguments parser.add_argument('--dataset', type=str, default='un', help='name of corpus') parser.add_argument('--data_path', type=str, default='un/', help='directory containing data') parser.add_argument('--emb_path', type=str, default='skipgram/embeddings.txt', help='directory containing embeddings') parser.add_argument('--save_path', type=str, default='./results', help='path to save results') parser.add_argument('--batch_size', type=int, default=1000, help='number of documents in a batch for training') parser.add_argument('--min_df', type=int, default=100, help='to get the right data..minimum document frequency') ### model-related arguments parser.add_argument('--num_topics', type=int, default=50, help='number of topics') parser.add_argument('--rho_size', type=int, default=300, help='dimension of rho') parser.add_argument('--emb_size', type=int, default=300, help='dimension of embeddings') parser.add_argument('--t_hidden_size', type=int, default=800, help='dimension of hidden space of q(theta)') parser.add_argument('--theta_act', type=str, default='relu', help='tanh, softplus, relu, rrelu, leakyrelu, elu, selu, glu)') parser.add_argument('--train_embeddings', type=int, default=1, help='whether to fix rho or train it') parser.add_argument('--eta_nlayers', type=int, default=3, help='number of layers for eta') parser.add_argument('--eta_hidden_size', type=int, default=200, help='number of hidden units for rnn') parser.add_argument('--delta', type=float, default=0.005, help='prior variance') ### optimization-related arguments parser.add_argument('--lr', type=float, default=0.005, help='learning rate') parser.add_argument('--lr_factor', type=float, default=4.0, help='divide learning rate by this') parser.add_argument('--epochs', type=int, default=100, help='number of epochs to train') parser.add_argument('--mode', type=str, default='train', help='train or eval model') parser.add_argument('--optimizer', type=str, default='adam', help='choice of optimizer') parser.add_argument('--seed', type=int, default=2019, help='random seed (default: 1)') parser.add_argument('--enc_drop', type=float, default=0.0, help='dropout rate on encoder') parser.add_argument('--eta_dropout', type=float, default=0.0, help='dropout rate on rnn for eta') parser.add_argument('--clip', type=float, default=0.0, help='gradient clipping') parser.add_argument('--nonmono', type=int, default=10, help='number of bad hits allowed') parser.add_argument('--wdecay', type=float, default=1.2e-6, help='some l2 regularization') parser.add_argument('--anneal_lr', type=int, default=0, help='whether to anneal the learning rate or not') parser.add_argument('--bow_norm', type=int, default=1, help='normalize the bows or not') ### evaluation, visualization, and logging-related arguments parser.add_argument('--num_words', type=int, default=20, help='number of words for topic viz') parser.add_argument('--log_interval', type=int, default=10, help='when to log training') parser.add_argument('--visualize_every', type=int, default=1, help='when to visualize results') parser.add_argument('--eval_batch_size', type=int, default=1000, help='input batch size for evaluation') parser.add_argument('--load_from', type=str, default='', help='the name of the ckpt to eval from') parser.add_argument('--tc', type=int, default=0, help='whether to compute tc or not') args = parser.parse_args() pca = PCA(n_components=2) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") ## set seed np.random.seed(args.seed) torch.backends.cudnn.deterministic = True torch.manual_seed(args.seed) ## get data # 1. vocabulary print('Getting vocabulary ...') data_file = os.path.join(args.data_path, 'min_df_{}'.format(args.min_df)) vocab, train, valid, test = data.get_data(data_file, temporal=True) vocab_size = len(vocab) args.vocab_size = vocab_size # 1. training data print('Getting training data ...') train_tokens = train['tokens'] train_counts = train['counts'] train_times = train['times'] args.num_times = len(np.unique(train_times)) args.num_docs_train = len(train_tokens) train_rnn_inp = data.get_rnn_input( train_tokens, train_counts, train_times, args.num_times, args.vocab_size, args.num_docs_train) # 2. dev set print('Getting validation data ...') valid_tokens = valid['tokens'] valid_counts = valid['counts'] valid_times = valid['times'] args.num_docs_valid = len(valid_tokens) valid_rnn_inp = data.get_rnn_input( valid_tokens, valid_counts, valid_times, args.num_times, args.vocab_size, args.num_docs_valid) # 3. test data print('Getting testing data ...') test_tokens = test['tokens'] test_counts = test['counts'] test_times = test['times'] args.num_docs_test = len(test_tokens) test_rnn_inp = data.get_rnn_input( test_tokens, test_counts, test_times, args.num_times, args.vocab_size, args.num_docs_test) test_1_tokens = test['tokens_1'] test_1_counts = test['counts_1'] test_1_times = test_times args.num_docs_test_1 = len(test_1_tokens) test_1_rnn_inp = data.get_rnn_input( test_1_tokens, test_1_counts, test_1_times, args.num_times, args.vocab_size, args.num_docs_test) test_2_tokens = test['tokens_2'] test_2_counts = test['counts_2'] test_2_times = test_times args.num_docs_test_2 = len(test_2_tokens) test_2_rnn_inp = data.get_rnn_input( test_2_tokens, test_2_counts, test_2_times, args.num_times, args.vocab_size, args.num_docs_test) ## get embeddings print('Getting embeddings ...') emb_path = args.emb_path vect_path = os.path.join(args.data_path.split('/')[0], 'embeddings.pkl') vectors = {} with open(emb_path, 'rb') as f: for l in f: line = l.decode().split() word = line[0] if word in vocab: vect = np.array(line[1:]).astype(np.float) vectors[word] = vect embeddings = np.zeros((vocab_size, args.emb_size)) words_found = 0 for i, word in enumerate(vocab): try: embeddings[i] = vectors[word] words_found += 1 except KeyError: embeddings[i] = np.random.normal(scale=0.6, size=(args.emb_size, )) embeddings = torch.from_numpy(embeddings).to(device) args.embeddings_dim = embeddings.size() print('\n') print('=*'*100) print('Training a Dynamic Embedded Topic Model on {} with the following settings: {}'.format(args.dataset.upper(), args)) print('=*'*100) ## define checkpoint if not os.path.exists(args.save_path): os.makedirs(args.save_path) if args.mode == 'eval': ckpt = args.load_from else: ckpt = os.path.join(args.save_path, 'detm_{}_K_{}_Htheta_{}_Optim_{}_Clip_{}_ThetaAct_{}_Lr_{}_Bsz_{}_RhoSize_{}_L_{}_minDF_{}_trainEmbeddings_{}'.format( args.dataset, args.num_topics, args.t_hidden_size, args.optimizer, args.clip, args.theta_act, args.lr, args.batch_size, args.rho_size, args.eta_nlayers, args.min_df, args.train_embeddings)) ## define model and optimizer if args.load_from != '': print('Loading checkpoint from {}'.format(args.load_from)) with open(args.load_from, 'rb') as f: model = torch.load(f) else: model = DETM(args, embeddings) print('\nDETM architecture: {}'.format(model)) model.to(device) if args.optimizer == 'adam': optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wdecay) elif args.optimizer == 'adagrad': optimizer = optim.Adagrad(model.parameters(), lr=args.lr, weight_decay=args.wdecay) elif args.optimizer == 'adadelta': optimizer = optim.Adadelta(model.parameters(), lr=args.lr, weight_decay=args.wdecay) elif args.optimizer == 'rmsprop': optimizer = optim.RMSprop(model.parameters(), lr=args.lr, weight_decay=args.wdecay) elif args.optimizer == 'asgd': optimizer = optim.ASGD(model.parameters(), lr=args.lr, t0=0, lambd=0., weight_decay=args.wdecay) else: print('Defaulting to vanilla SGD') optimizer = optim.SGD(model.parameters(), lr=args.lr) def train(epoch): """Train DETM on data for one epoch. """ model.train() acc_loss = 0 acc_nll = 0 acc_kl_theta_loss = 0 acc_kl_eta_loss = 0 acc_kl_alpha_loss = 0 cnt = 0 indices = torch.randperm(args.num_docs_train) indices = torch.split(indices, args.batch_size) for idx, ind in enumerate(indices): optimizer.zero_grad() model.zero_grad() data_batch, times_batch = data.get_batch( train_tokens, train_counts, ind, args.vocab_size, args.emb_size, temporal=True, times=train_times) sums = data_batch.sum(1).unsqueeze(1) if args.bow_norm: normalized_data_batch = data_batch / sums else: normalized_data_batch = data_batch loss, nll, kl_alpha, kl_eta, kl_theta = model(data_batch, normalized_data_batch, times_batch, train_rnn_inp, args.num_docs_train) loss.backward() if args.clip > 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip) optimizer.step() acc_loss += torch.sum(loss).item() acc_nll += torch.sum(nll).item() acc_kl_theta_loss += torch.sum(kl_theta).item() acc_kl_eta_loss += torch.sum(kl_eta).item() acc_kl_alpha_loss += torch.sum(kl_alpha).item() cnt += 1 if idx % args.log_interval == 0 and idx > 0: cur_loss = round(acc_loss / cnt, 2) cur_nll = round(acc_nll / cnt, 2) cur_kl_theta = round(acc_kl_theta_loss / cnt, 2) cur_kl_eta = round(acc_kl_eta_loss / cnt, 2) cur_kl_alpha = round(acc_kl_alpha_loss / cnt, 2) lr = optimizer.param_groups[0]['lr'] print('Epoch: {} .. batch: {}/{} .. LR: {} .. KL_theta: {} .. KL_eta: {} .. KL_alpha: {} .. Rec_loss: {} .. NELBO: {}'.format( epoch, idx, len(indices), lr, cur_kl_theta, cur_kl_eta, cur_kl_alpha, cur_nll, cur_loss)) cur_loss = round(acc_loss / cnt, 2) cur_nll = round(acc_nll / cnt, 2) cur_kl_theta = round(acc_kl_theta_loss / cnt, 2) cur_kl_eta = round(acc_kl_eta_loss / cnt, 2) cur_kl_alpha = round(acc_kl_alpha_loss / cnt, 2) lr = optimizer.param_groups[0]['lr'] print('*'*100) print('Epoch----->{} .. LR: {} .. KL_theta: {} .. KL_eta: {} .. KL_alpha: {} .. Rec_loss: {} .. NELBO: {}'.format( epoch, lr, cur_kl_theta, cur_kl_eta, cur_kl_alpha, cur_nll, cur_loss)) print('*'*100) def visualize(): """Visualizes topics and embeddings and word usage evolution. """ model.eval() with torch.no_grad(): alpha = model.mu_q_alpha beta = model.get_beta(alpha) print('beta: ', beta.size()) print('\n') print('#'*100) print('Visualize topics...') times = [0, 10, 40] topics_words = [] for k in range(args.num_topics): for t in times: gamma = beta[k, t, :] top_words = list(gamma.cpu().numpy().argsort()[-args.num_words+1:][::-1]) topic_words = [vocab[a] for a in top_words] topics_words.append(' '.join(topic_words)) print('Topic {} .. Time: {} ===> {}'.format(k, t, topic_words)) print('\n') print('Visualize word embeddings ...') queries = ['economic', 'assembly', 'security', 'management', 'debt', 'rights', 'africa'] try: embeddings = model.rho.weight # Vocab_size x E except: embeddings = model.rho # Vocab_size x E neighbors = [] for word in queries: print('word: {} .. neighbors: {}'.format( word, nearest_neighbors(word, embeddings, vocab, args.num_words))) print('#'*100) # print('\n') # print('Visualize word evolution ...') # topic_0 = None ### k # queries_0 = ['woman', 'gender', 'man', 'mankind', 'humankind'] ### v # topic_1 = None # queries_1 = ['africa', 'colonial', 'racist', 'democratic'] # topic_2 = None # queries_2 = ['poverty', 'sustainable', 'trade'] # topic_3 = None # queries_3 = ['soviet', 'convention', 'iran'] # topic_4 = None # climate # queries_4 = ['environment', 'impact', 'threats', 'small', 'global', 'climate'] def _eta_helper(rnn_inp): inp = model.q_eta_map(rnn_inp).unsqueeze(1) hidden = model.init_hidden() output, _ = model.q_eta(inp, hidden) output = output.squeeze() etas = torch.zeros(model.num_times, model.num_topics).to(device) inp_0 = torch.cat([output[0], torch.zeros(model.num_topics,).to(device)], dim=0) etas[0] = model.mu_q_eta(inp_0) for t in range(1, model.num_times): inp_t = torch.cat([output[t], etas[t-1]], dim=0) etas[t] = model.mu_q_eta(inp_t) return etas def get_eta(source): model.eval() with torch.no_grad(): if source == 'val': rnn_inp = valid_rnn_inp return _eta_helper(rnn_inp) else: rnn_1_inp = test_1_rnn_inp return _eta_helper(rnn_1_inp) def get_theta(eta, bows): model.eval() with torch.no_grad(): inp = torch.cat([bows, eta], dim=1) q_theta = model.q_theta(inp) mu_theta = model.mu_q_theta(q_theta) theta = F.softmax(mu_theta, dim=-1) return theta def get_completion_ppl(source): """Returns document completion perplexity. """ model.eval() with torch.no_grad(): alpha = model.mu_q_alpha if source == 'val': indices = torch.split(torch.tensor(range(args.num_docs_valid)), args.eval_batch_size) tokens = valid_tokens counts = valid_counts times = valid_times eta = get_eta('val') acc_loss = 0 cnt = 0 for idx, ind in enumerate(indices): data_batch, times_batch = data.get_batch( tokens, counts, ind, args.vocab_size, args.emb_size, temporal=True, times=times) sums = data_batch.sum(1).unsqueeze(1) if args.bow_norm: normalized_data_batch = data_batch / sums else: normalized_data_batch = data_batch eta_td = eta[times_batch.type('torch.LongTensor')] theta = get_theta(eta_td, normalized_data_batch) alpha_td = alpha[:, times_batch.type('torch.LongTensor'), :] beta = model.get_beta(alpha_td).permute(1, 0, 2) loglik = theta.unsqueeze(2) * beta loglik = loglik.sum(1) loglik = torch.log(loglik) nll = -loglik * data_batch nll = nll.sum(-1) loss = nll / sums.squeeze() loss = loss.mean().item() acc_loss += loss cnt += 1 cur_loss = acc_loss / cnt ppl_all = round(math.exp(cur_loss), 1) print('*'*100) print('{} PPL: {}'.format(source.upper(), ppl_all)) print('*'*100) return ppl_all else: indices = torch.split(torch.tensor(range(args.num_docs_test)), args.eval_batch_size) tokens_1 = test_1_tokens counts_1
#!/usr/bin/env python import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'agilent-n6700b-power-system')) sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 't2k-temperature-sensor')) sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tektronix-afg3252-function-generator')) sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'thermoscientific-rte10-circulator')) import socket # for making plots import pyqtgraph as pg # other utilities import collections import datetime, time import json import numpy as np import pandas as pd import signal import statistics import zmq # device API imports from AFG3252 import AFG3252 from N6700B import N6700B from T2KTEMPSENSOR import T2KTEMPSENSOR from NESLABRTE10 import NESLABRTE10 # PyQt imports from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import * from PyQt5.QtWidgets import * # helper function for dealing with timestamp axis # ref: https://gist.github.com/iverasp/9349dffa42aeffb32e48a0868edfa32d def timestamp(): return int(time.mktime(datetime.datetime.now().timetuple())) # helper class for dealing with timestamp axis # ref: https://gist.github.com/iverasp/9349dffa42aeffb32e48a0868edfa32d class TimeAxisItem(pg.AxisItem): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setLabel(text='Time', units=None) self.enableAutoSIPrefix(False) def attachToPlotItem(self, plotItem): """Add this axis to the given PlotItem :param plotItem: (PlotItem) """ self.setParentItem(plotItem) viewBox = plotItem.getViewBox() self.linkToView(viewBox) self._oldAxis = plotItem.axes[self.orientation]['item'] self._oldAxis.hide() plotItem.axes[self.orientation]['item'] = self pos = plotItem.axes[self.orientation]['pos'] plotItem.layout.addItem(self, *pos) self.setZValue(-1000) def tickStrings(self, values, scale, spacing): return [datetime.datetime.fromtimestamp(value).strftime("%H:%M") for value in values] class Window(QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) # get the control handles # function generator self.devFunGen = AFG3252(socket.gethostbyname('192.168.0.101')) # power unit self.devPowerUnit = N6700B('192.168.0.201') # temperature sensor ## If I open the temperature sensor as a member variable, ## temperature readings will all turn empty after the first reading. ## Don't quite know what happens here. However, opening the connection ## everytime when I want to get readings seems to be a workaround... self.devTempSen = T2KTEMPSENSOR() # widgets I want to have control *************************************** # power unit starts with pu self.puVoltageSwitch = QPushButton(text='Switch On') self.puVoltageSwitch.setCheckable(True) # self.puVoltageSwitch.clicked.connect(self.puPowerSwitch) self.puVoltageSwitch.toggled.connect(self.puPowerSwitch) self.puChCB = QComboBox() self.puChCB.addItems(['all', '1', '2', '3', '4']) self.puChCB.setCurrentIndex(3) # self.puChCB.setEnabled(False) self.puVsetEdit = QLineEdit('60') self.puVsetEdit.setValidator(QDoubleValidator(bottom=0, top=60, decimals=10)) self.puVRbEdit = QLineEdit() # function generator stars with fg self.fgChSel = QComboBox() self.fgChSel.addItems(['1', '2', 'all']) self.fgChSel.setCurrentIndex(2) self.fgOutputSwitch = QPushButton(text='Switch On') self.fgOutputSwitch.setCheckable(True) self.fgOutputSwitch.clicked.connect(self.fgToggleOutput) self.fgRecallChSel = QComboBox() self.fgRecallChSel.addItems(['0', '1', '2', '3', '4']) # recall waveform when a saved state is selected self.fgRecallChSel.activated.connect(self.fgRecallState) self.fgRecallChSel.setCurrentIndex(2) self.fgFreqEdit = QLineEdit('1') self.fgFreqEdit.setValidator(QDoubleValidator(bottom=0, decimals=10)) self.fgFreqBtn = QPushButton(text='Apply') self.fgFreqBtn.clicked.connect(self.fgApplyFreq) self.fgAmplEdit = QLineEdit('2.8') self.fgAmplEdit.setValidator(QDoubleValidator(decimals=10)) self.fgAmplBtn = QPushButton(text='Apply') self.fgAmplBtn.clicked.connect(self.fgApplyAmpl) # touch the selected state to initialize readings self.fgRecallState() # a message box self.msgBox = QTextEdit() # self.msgBox.setText('Welcome to the control application!\n') self.msgBox.append('Welcome to the control application!') self.msgBox.setReadOnly(True) # T2K temperature sensor interface self.tsTemperatureCB = QComboBox() self.tsTemperatureCB.addItems(['T0', 'T1', 'T2', 'T3', 'T4']) self.tsTemperatureCB.activated.connect(self.tsReadTemperature) self.tsTemperatureEdit = QLineEdit() self.tsView = pg.GraphicsView() self.tsLo = pg.GraphicsLayout() self.tsPlot = None # member variable place holder # below are data structure for plotting self.timerTime = 2000 self.tsPoints = 90 self.tsX = dict() self.tsY = dict() for sen in ['T0', 'T1', 'T2', 'T3', 'T4']: self.tsX[sen] = collections.deque(maxlen=self.tsPoints) self.tsY[sen] = collections.deque(maxlen=self.tsPoints) # end of widgets declaration ******************************************* # main window layout # Initialize tab screen self.tabs = QTabWidget() self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() # Add tabs self.tabs.addTab(self.tab1, 'Simple Control') self.tabs.addTab(self.tab2, 'Parameter Scan') self.tabs.addTab(self.tab3, 'Singal Channel Dark Rate Scan') self.tab1.layout = QGridLayout() self.tab1.layout.addWidget(self.createVoltageControl(), 0, 0, 1, 1) self.tab1.layout.addWidget(self.createPulserControl(), 0, 1, 1, 1) self.tab1.layout.addWidget(self.createCirculatorControl(), 0, 2, 1, 1) self.tab1.layout.addWidget(self.msgBox, 1, 0, 1, 3) self.tab1.layout.addWidget(self.createTemperatureSensor(), 0, 3, 2, 1) self.tab1.setLayout(self.tab1.layout) self.tab2.setLayout(self.createParameterScan()) self.tab3.setLayout(self.createDarkRateScan()) grid = QGridLayout() grid.addWidget(self.tabs, 0, 0) self.setLayout(grid) # end of main window layout self.setWindowTitle('MPPC Slow Control App') self.resize(1200, 300) # use a figure as this app's icon # ref: https://stackoverflow.com/questions/42602713/how-to-set-a-window-icon-with-pyqt5 scriptDir = os.path.dirname(os.path.realpath(__file__)) self.setWindowIcon(QtGui.QIcon(os.path.join(scriptDir, 'logo.png'))) #***** DAQ STATUS VARIABLE ***** # Make sure this variable is defined before any timer instantiation. self.daqReady = True # Parameter scan queue for parameter values to be gone through # whenever the DAQ status is ready self.psQueue = [] # use a timer for voltage readback # ref: https://pythonpyqt.com/qtimer/ self.timer = QTimer() self.timer.start(self.timerTime) self.timer.timeout.connect(self.puReadbackVoltage) self.puReadbackVoltage() self.timer.timeout.connect(self.tsReadTemperature) self.tsReadTemperature() self.timer.timeout.connect(self.wcReadInternalTemperature) # zmq and polling timer implementation context = zmq.Context() self.socket = context.socket(zmq.PAIR) self.socket.connect("tcp://localhost:5556") self.poller = zmq.Poller() self.poller.register(self.socket, zmq.POLLIN) self.timerPoll = QTimer() self.timerPoll.start(100) self.timerPoll.timeout.connect(self.pollMsg) # make a timer to log instrument readback data # every 10 seconds. self.logDataTimer = QTimer() self.logDataTimer.start(10000) self.logDataTimer.timeout.connect(self.tsLogReadouts) self.logDataTimer.timeout.connect(self.wcLogInternalTemperature) # also make dataframes for storing data points to be saved to disk. self.dfTempSensor = pd.DataFrame(columns=['Datetime','T0','T1','T2', 'T3','T4']) self.dfWcIntTemp = pd.DataFrame(columns=['Datetime', 'Internal Temperature']) def closeEvent(self, a0): ''' Application destructor. Turn off various hardware components on window exit. ''' ## turn off the power system # get the active channel active_ch = int(self.puChCB.currentText()) self.devPowerUnit.power_off(active_ch) ## turn off the function generator self.devFunGen.disableOutput(1) self.devFunGen.disableOutput(2) return super().closeEvent(a0) def createCirculatorControl(self): # connect to the water circulator self.devWaterCirculator = NESLABRTE10() # member widgets for the water circulator self.wcLogDataCkB = QCheckBox() self.wcSetpointEdit = QLineEdit(text=str(self.devWaterCirculator.read_setpoint())) self.wcApplySetpointBtn = QPushButton('Apply') self.wcReadbackEdit = QLineEdit(text=str(self.devWaterCirculator.read_internal_temperature())) self.wcSwitchBtn = QPushButton('Switch On') self.wcSwitchBtn.setCheckable(True) # event connection self.wcApplySetpointBtn.clicked.connect(self.wcApplySetpoint) self.wcSwitchBtn.clicked.connect(self.wcSwitch) # layout of water circulator control panel groupBox = QGroupBox('Thermo Scientific Water Circulator') grid = QGridLayout() grid.addWidget(QLabel('Setpoint: '), 0, 0, Qt.AlignRight) grid.addWidget(self.wcSetpointEdit, 0, 1) grid.addWidget(QLabel(u'\u00B0C'), 0, 2) grid.addWidget(self.wcApplySetpointBtn, 0, 3) grid.addWidget(QLabel('Readback: '), 1, 0, Qt.AlignRight) grid.addWidget(self.wcReadbackEdit, 1, 1) grid.addWidget(QLabel(u'\u00B0C'), 1, 2) grid.addWidget(self.wcSwitchBtn, 2, 3) grid.addWidget(self.wcLogDataCkB, 3, 0, Qt.AlignRight) grid.addWidget(QLabel('Log Data to File'), 3, 1, 1, 3) groupBox.setLayout(grid) return groupBox def createDarkRateScan(self): # widgets belonging to this tab self.drsFebCB = QComboBox() self.drsFebCB.addItems(['All', '0', '1']) self.drsChCB = QComboBox() self.drsChCB.addItems(['All']+[str(i) for i in range(32)]) # editors for setting threshold self.drsDac1From = QLineEdit(text='220') self.drsDac1To = QLineEdit(text='220') self.drsDac1Step = QLineEdit(text='1') ### Legacy variables below self.drsDac2From = QLineEdit(text='220') self.drsDac2To = QLineEdit(text='220') self.drsDac2Step = QLineEdit(text='1') ### Legacy variables above self.drsEditPreGain = QLineEdit(text='55') self.drsEditNEvt = QLineEdit('10000') self.drsStartBtn = QPushButton(text='Start Scan') self.drsStartBtn.clicked.connect(self.sendDrJsonMsg) # lay out widgets grid = QGridLayout() groupBox1 = QGroupBox('Channels to Scan') grid1 = QGridLayout() grid1.addWidget(QLabel('FEB'), 0, 0, Qt.AlignRight) grid1.addWidget(self.drsFebCB, 0, 1, Qt.AlignLeft) grid1.addWidget(QLabel('Channel'), 0, 2, Qt.AlignRight) grid1.addWidget(self.drsChCB, 0, 3, Qt.AlignLeft) groupBox1.setLayout(grid1) grid.addWidget(groupBox1, 0, 0, 1, 5) groupBox2 = QGroupBox('Thresholds to Scan') grid2 = QGridLayout() grid2.addWidget(QLabel('from'), 0, 1, Qt.AlignCenter) grid2.addWidget(QLabel('to'), 0, 2, Qt.AlignCenter) grid2.addWidget(QLabel('step'), 0, 3, Qt.AlignCenter) grid2.addWidget(QLabel('DAC'), 1, 0, Qt.AlignRight) grid2.addWidget(self.drsDac1From, 1, 1, Qt.AlignCenter) grid2.addWidget(self.drsDac1To, 1, 2, Qt.AlignCenter) grid2.addWidget(self.drsDac1Step, 1, 3, Qt.AlignCenter) groupBox2.setLayout(grid2) grid.addWidget(groupBox2, 1, 0, 1, 5) # grid.addWidget(QLabel('FEB2 DAC from'), 1, 2, Qt.AlignRight) # grid.addWidget(self.drsDac2From, 1, 3, Qt.AlignCenter) # grid.addWidget(QLabel('FEB2 DAC to'), 2, 2, Qt.AlignRight) # grid.addWidget(self.drsDac2To, 2, 3, Qt.AlignCenter) # grid.addWidget(QLabel('FEB2 DAC step'), 3, 2, Qt.AlignRight) # grid.addWidget(self.drsDac2Step, 3, 3, Qt.AlignCenter) groupBox3 = QGroupBox('Other Parameters') grid3 = QGridLayout() grid3.addWidget(QLabel('preamp gain'), 0, 0, Qt.AlignRight) grid3.addWidget(self.drsEditPreGain, 0, 1, Qt.AlignLeft) grid3.addWidget(QLabel('number of events'), 0, 2, Qt.AlignRight) grid3.addWidget(self.drsEditNEvt, 0, 3, Qt.AlignLeft) groupBox3.setLayout(grid3) grid.addWidget(groupBox3, 4, 0, 1, 5) grid.addWidget(self.drsStartBtn, 5, 4, Qt.AlignCenter) return grid def createParameterScan(self): # member widgets self.parKeys = ['vol', 'feb1dac', 'feb1gain', 'feb1bias', 'feb2dac', 'feb2gain', 'feb2bias', 'temp'] self.editParVal = dict() for key in self.parKeys: self.editParVal[key] = dict() self.editParVal['vol']['from'] = QLineEdit('58') self.editParVal['vol']['to'] = QLineEdit('60') self.editParVal['vol']['step'] = QLineEdit('1') self.editParVal['feb1dac']['from'] = QLineEdit('200') self.editParVal['feb1dac']['to'] = QLineEdit('200') self.editParVal['feb1dac']['step'] = QLineEdit('1') self.editParVal['feb1gain']['from'] = QLineEdit('52') self.editParVal['feb1gain']['to'] = QLineEdit('52') self.editParVal['feb1gain']['step'] = QLineEdit('1') self.editParVal['feb1bias']['from'] = QLineEdit('200') self.editParVal['feb1bias']['to'] = QLineEdit('200') self.editParVal['feb1bias']['step'] = QLineEdit('0') self.editParVal['feb2dac']['from'] = QLineEdit('230') self.editParVal['feb2dac']['to'] = QLineEdit('230') self.editParVal['feb2dac']['step'] = QLineEdit('0') self.editParVal['feb2gain']['from'] = QLineEdit('52') self.editParVal['feb2gain']['to'] = QLineEdit('52') self.editParVal['feb2gain']['step'] = QLineEdit('1') self.editParVal['feb2bias']['from'] = QLineEdit('200') self.editParVal['feb2bias']['to'] = QLineEdit('200') self.editParVal['feb2bias']['step'] = QLineEdit('0') self.editParVal['temp']['from'] = QLineEdit('18') self.editParVal['temp']['to'] = QLineEdit('22') self.editParVal['temp']['step'] = QLineEdit('1') self.editNEvt = QLineEdit('10000') self.scanBut = QPushButton(text='Start Scan') self.scanBut.clicked.connect(self.sendJsonMsg) grid = QGridLayout() grid.addWidget(QLabel('Include'), 0, 0, Qt.AlignCenter) grid.addWidget(QLabel('Parameter'), 0, 1, Qt.AlignCenter) grid.addWidget(QLabel('From'), 0, 2, 1, 2, Qt.AlignCenter) grid.addWidget(QLabel('To'), 0, 4, 1, 2, Qt.AlignCenter) grid.addWidget(QLabel('Step'), 0, 6, 1, 2, Qt.AlignCenter) grid.addWidget(QLabel('Voltage'), 1, 1) grid.addWidget(self.editParVal['vol']['from'], 1, 2) grid.addWidget(QLabel('V'), 1, 3) grid.addWidget(self.editParVal['vol']['to'], 1, 4) grid.addWidget(QLabel('V'), 1, 5) grid.addWidget(self.editParVal['vol']['step'], 1, 6) grid.addWidget(QLabel('V'), 1, 7) grid.addWidget(QLabel('FEB1 DAC'), 2, 1) grid.addWidget(self.editParVal['feb1dac']['from'], 2, 2) grid.addWidget(self.editParVal['feb1dac']['to'], 2, 4) grid.addWidget(self.editParVal['feb1dac']['step'], 2, 6) grid.addWidget(QLabel('FEB1 Gain'), 3, 1) grid.addWidget(self.editParVal['feb1gain']['from'], 3, 2) grid.addWidget(self.editParVal['feb1gain']['to'], 3, 4) grid.addWidget(self.editParVal['feb1gain']['step'], 3, 6) grid.addWidget(QLabel('FEB1 Bias'), 4, 1) grid.addWidget(self.editParVal['feb1bias']['from'], 4, 2) grid.addWidget(self.editParVal['feb1bias']['to'], 4, 4) grid.addWidget(self.editParVal['feb1bias']['step'], 4, 6) grid.addWidget(QLabel('FEB2 DAC'), 5, 1) grid.addWidget(self.editParVal['feb2dac']['from'], 5, 2) grid.addWidget(self.editParVal['feb2dac']['to'], 5, 4) grid.addWidget(self.editParVal['feb2dac']['step'], 5, 6) grid.addWidget(QLabel('FEB2 Gain'), 6, 1) grid.addWidget(self.editParVal['feb2gain']['from'], 6, 2) grid.addWidget(self.editParVal['feb2gain']['to'], 6, 4) grid.addWidget(self.editParVal['feb2gain']['step'], 6, 6) grid.addWidget(QLabel('FEB2 Bias'), 7, 1) grid.addWidget(self.editParVal['feb2bias']['from'], 7, 2) grid.addWidget(self.editParVal['feb2bias']['to'], 7, 4) grid.addWidget(self.editParVal['feb2bias']['step'], 7, 6) grid.addWidget(QLabel('Temperature'), 8, 1) grid.addWidget(self.editParVal['temp']['from'], 8, 2) grid.addWidget(QLabel(u'\u00B0C'), 8, 3) grid.addWidget(self.editParVal['temp']['to'], 8, 4) grid.addWidget(QLabel(u'\u00B0C'), 8, 5) grid.addWidget(self.editParVal['temp']['step'], 8, 6) grid.addWidget(QLabel(u'\u00B0C'), 8, 7) grid.addWidget(QLabel('number of events'), 9, 1, Qt.AlignRight) grid.addWidget(self.editNEvt, 9, 2) grid.addWidget(self.scanBut, 9, 6) # put on checkboxes self.includeParCB = dict() for i in range(len(self.parKeys)): k = self.parKeys[i] self.includeParCB[k] = QCheckBox() self.includeParCB[k].setChecked(True) grid.addWidget(self.includeParCB[k], i+1, 0, Qt.AlignCenter) #
<gh_stars>0 from configuration import PATH from Instance import Instance import utils import inspect import logging from itertools import combinations from random import sample, shuffle, random from bisect import bisect from collections import defaultdict import concurrent.futures import networkx as nx import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as ptc import copy import time import ctypes lib = ctypes.cdll.LoadLibrary('./libmain.so.1') class Solution(Instance): def __init__(self, name, ind_radius=0, ind_k=0, path=PATH): Instance.__init__(self, name, ind_radius, ind_k, path) self.sensors = nx.Graph() self.sensors.add_node(0) self.neighbors = nx.Graph() self.sensors_sorted = [[0, [0., 0.]]] self.target_coverage = defaultdict(list) @property def score(self): return len(self.sensors.nodes) - 1 @staticmethod def call_cpp(): lib.print_c(ctypes.c_double(5.5)) def copy(self): return copy.deepcopy(self) # Add or remove sensors def _reduce_target(self, i): inf_x = bisect(self._data_x[:, 1], list( np.array(self._data[i]) - np.array([self._rcapt, 0]))) sup_x = bisect(self._data_x[:, 1], list( np.array(self._data[i]) + np.array([self._rcapt, 0]))) return inf_x, sup_x def _find_neighbors(self, i, distance=1): neighbors = [] inf_x, sup_x = self._reduce_target(i) for j in range(max(inf_x - 1, 1), min(sup_x + 1, self._n)): x_j = self._data_x[j][0] if self._distance_ind(i, x_j) <= distance: neighbors.append(x_j) return neighbors def _reduce_sensors(self, i): x = bisect(np.array(self.sensors_sorted, dtype=object) [:, 1], self._data[i]) inf_x = bisect(np.array(self.sensors_sorted, dtype=object)[:, 1], list( np.array(self._data[i]) - np.array([self._rcom, 0]))) sup_x = bisect(np.array(self.sensors_sorted, dtype=object)[:, 1], list( np.array(self._data[i]) + np.array([self._rcom, 0]))) return x, inf_x, sup_x def add_sensor(self, i): if i in self.sensors.nodes: logging.warning(" {} already a sensor ...\n\t{}".format( i, inspect.getframeinfo(inspect.currentframe().f_back))) return 0 self.sensors.add_node(i) x, inf_x, sup_x = self._reduce_sensors(i) self.sensors_sorted.insert(x, [i, self._data[i]]) for j in range(max(inf_x - 1, 0), min(sup_x + 1, len(self.sensors_sorted))): x_j = self.sensors_sorted[j][0] if self._distance_ind(i, x_j) <= self._rcom and i != x_j: self.sensors.add_edge(i, x_j) # for j in self.sensors.nodes: # if self._distance_ind(i,j) < self._rcom: # self.sensors.add_edge(i,j) neighbors = list(self.neighbors.neighbors(i)) for x_j in neighbors: if i in self.target_coverage[x_j]: logging.warning(" {} already in target_coverage of {} ...\n\t{}\n{}\n{}".format( i, x_j, inspect.getframeinfo(inspect.currentframe().f_back), inspect.getframeinfo(inspect.currentframe().f_back.f_back), inspect.getframeinfo(inspect.currentframe().f_back.f_back.f_back))) continue self.target_coverage[x_j].append(i) return 1 def remove_sensor(self, i): self.sensors.remove_node(i) self.sensors_sorted.remove([i, self._data[i]]) neighbors = list(self.neighbors.neighbors(i)) for x_j in neighbors: self.target_coverage[x_j] = list(filter(lambda x: x != i, self.target_coverage[x_j])) return 1 # Check admissibility def _is_connected(self): return nx.is_connected(self.sensors) def _is_covered(self): for i in range(1, self._n): if len(self.target_coverage[i]) < self._k: return False, i return True, -1 def is_admissible(self): return self._is_connected() and self._is_covered()[0] # Optimize locally the solution def add_all(self): for i in range(1, self._n): self.sensors.add_node(i) x, inf_x, sup_x = self._reduce_sensors(i) self.sensors_sorted.insert(x, [i, self._data[i]]) for j in range(max(inf_x - 1, 0), min(sup_x + 1, len(self.sensors_sorted))): x_j = self.sensors_sorted[j][0] if self._distance_ind(i, x_j) <= self._rcom and i != x_j: self.sensors.add_edge(i, x_j) # for j in self.sensors.nodes: # if self._distance_ind(i,j) < self._rcom: # self.sensors.add_edge(i,j) neighbors = self._find_neighbors(i, distance=self._rcapt) for x_j in neighbors: self.target_coverage[x_j].append(i) self.neighbors.add_edge(i, x_j) def _to_be_removed(self, min_coverage=0, r=0): # sensor_to_be_removed_1, sensor_to_be_removed_2 = [], [] sensor_to_be_removed_1 = [] # degrees = self.sensors.degree() if min_coverage > 0: for sensor in list(self.sensors.nodes)[1:]: L1 = list(map(lambda target: len( self.target_coverage[target]), list(self.neighbors.neighbors(sensor)))) # L2 = list(map(lambda target: degrees[target], # self.target_coverage[sensor])) if min(L1) == min_coverage - r: sensor_to_be_removed_1.append(sensor) # if min(L2) == min_coverage-r: # sensor_to_be_removed_2.append(sensor) else: for sensor in list(self.sensors.nodes)[1:]: L1 = list(map(lambda target: len( self.target_coverage[target]), list(self.neighbors.neighbors(sensor)))) # L2 = list(map(lambda target: degrees[target], # self.target_coverage[sensor])) if min(L1) > min_coverage: sensor_to_be_removed_1 = [sensor] min_coverage = min(L1) elif min(L1) == min_coverage: sensor_to_be_removed_1.append(sensor) # if min(L2) > min_coverage: # sensor_to_be_removed_2 = [sensor] # min_coverage = min(L2) # elif min(L2) == min_coverage: # sensor_to_be_removed_2.append(sensor) # sensor_to_be_removed = sensor_to_be_removed_1 + sensor_to_be_removed_2 # shuffle(sensor_to_be_removed) shuffle(sensor_to_be_removed_1) return min_coverage, sensor_to_be_removed_1 def _is_removable(self, to_remove): for i in to_remove: self.remove_sensor(i) if self.is_admissible(): return True, i else: self.add_sensor(i) return False, 0 def _is_removable_through_r(self, r_max): min_coverage = 0 # min_coverage = [0,0] for r in range(r_max): min_coverage, to_remove = self._to_be_removed(min_coverage, r) admissible, removed = self._is_removable(to_remove) if admissible: return True, removed return False, 0 def optimize_locally(self, r_max=2): admissible = True L_removed = [] while admissible: admissible, removed = self._is_removable_through_r(r_max) if admissible: L_removed.append(removed) return L_removed # First neighborhood structure def _find_max_coverage(self, max_coverage, q): i_max = [] if max_coverage == 0: for i in range(1, self._n): if len(self.target_coverage[i]) == max_coverage: i_max.append(i) if len(self.target_coverage[i]) > max_coverage: i_max = [i] max_coverage = len(self.target_coverage[i]) else: for i in range(1, self._n): if len(self.target_coverage[i]) == max_coverage - q: i_max.append(i) return i_max, max_coverage def _is_switchable(self, switch): for i in range(len(switch)): try_switch = switch[i] for sensor in try_switch: if sensor == 0: print("gros probleme") self.add_sensor(sensor) if not self.is_admissible(): for sensor in try_switch: if sensor == 0: print("problem") self.remove_sensor(sensor) else: return True return False def test_one_switch_multiproc(self, single_switch): for sensor in single_switch: if sensor == 0: print("gros probleme") self.add_sensor(sensor) if not self.is_admissible(): for sensor in single_switch: if sensor == 0: print("problem") self.remove_sensor(sensor) return 0 return 1 def _is_switchable_multiproc(self, switch): with concurrent.futures.ProcessPoolExecutor(max_workers=4) as worker_pool: futures = [worker_pool.submit(self.test_one_switch_multiproc, switch[i]) for i in range(len(switch))] for future in concurrent.futures.as_completed(futures): if future.result() == 1: return True return False # pool = mp.Pool(processes=4) # results = [pool.apply_async(self.test_one_switch_multiproc, args=(switch[i],)) # for i in range(len(switch))] # for p in results: # if p.get() is True: # return True # return False def neighborhood_1(self, max_coverage=0, q=0, nb_removed=1): """ q : le q ième plus grand nombre de capteurs nb_removed : on retire p et on ajoute p-i """ i_max, max_coverage = self._find_max_coverage(max_coverage, q) for i_test in i_max: to_test = self.target_coverage[i_test][:] logging.debug( "Removing sensors {}\tTarget node is {}".format(to_test, i_test)) switch = list(combinations(self.neighbors.neighbors(i_test), len( self.target_coverage[i_test]) - nb_removed)) shuffle(switch) # if len(switch) > 5000: # switch = sample(switch,5000) for sensor in to_test: self.remove_sensor(sensor) if not self._is_switchable(switch): logging.debug( "Neighborhood 1 : Switch fail around {}".format(i_test)) for sensor in to_test: self.add_sensor(sensor) else: logging.debug("Neighborhood 1 : Switch sucess around {}" "\tNew score {}".format( i_test, self.score)) logging.debug("Neighborhood 1 : Removed 1 sensor") return 1, max_coverage return 0, max_coverage # Second neighborhood structure def add_sensor_close_to_target(self, target_index): if target_index in self.sensors.nodes or target_index == 0: index_neighbors = np.array( sorted( self._data.items(), key=lambda x: utils.distance( x[1], self._data[target_index])), dtype=object) i = 0 while i < len(index_neighbors) and (index_neighbors[i][0] in self.sensors.nodes): i += 1 if i == len(index_neighbors): logging.warning("Cannot add sensor close to {}", target_index) return -1 self.add_sensor(index_neighbors[i][0]) logging.debug("close to target : added sensor (neighbor of {}) {}".format( target_index, index_neighbors[i][0])) else: self.add_sensor(target_index) logging.debug( "close to target : added sensor {}".format(target_index)) def remove_random_sensors(self, nb_removed): random_generator = np.random.default_rng() if 0 in self.sensors.nodes: list_choices = list(self.sensors.nodes) list_choices.remove(0) to_be_removed = random_generator.choice(list_choices, size=nb_removed, replace=False, shuffle=True) else: to_be_removed = random_generator.choice(list(self.sensors.nodes), size=nb_removed, replace=False, shuffle=True) logging.debug( "Neighborhood 2 : Removing {} sensors".format(to_be_removed)) for sensor in to_be_removed: self.remove_sensor(sensor) def fix_broken_coverrage(self): nb_added = 0 is_covered, index_not_covered = self._is_covered() while not(is_covered): if index_not_covered == 0: raise ValueError(index_not_covered) self.add_sensor_close_to_target(target_index=index_not_covered) nb_added += 1 is_covered, index_not_covered = self._is_covered() return nb_added def fix_broken_connection(self): nb_added = 0 random_generator = np.random.default_rng() while not(self._is_connected()): connected_components = [list(self.sensors.subgraph( component).nodes) for component in nx.connected_components(self.sensors)] logging.debug("Neighborhood 2 : {} connected components".format( len(list(connected_components)))) neighbors00 = self._find_neighbors(0, distance=self._rcom) found_component = False for neighbor in neighbors00: if neighbor in self.sensors.nodes: component_with_00 = list(nx.node_connected_component( self.sensors, neighbor)) found_component = True break if not found_component: self.add_sensor(neighbors00[0]) component_with_00 = list(nx.node_connected_component( self.sensors, neighbors00[0])) # Choose the closest component X to the component Y containing (0,0) random_element_connected_to_00 = random_generator.choice( component_with_00) smallest_distance_to_random_element = np.inf closest_component = None for component in connected_components: if random_element_connected_to_00 in component: continue for node in component: distance_to_random_element = self._distance_ind( node, random_element_connected_to_00) if distance_to_random_element < smallest_distance_to_random_element: smallest_distance_to_random_element = distance_to_random_element closest_component = component closest_component = list(closest_component) # Choose the closest node y0 to a random x of X, in the component (0,0) random_element_component = random_generator.choice( closest_component) smallest_distance_to_component = np.inf closest_node = 0 for node in component_with_00: distance_to_component = self._distance_ind( node, random_element_component) if distance_to_component < smallest_distance_to_component: smallest_distance_to_component = distance_to_component closest_node = node # Choose the closest node to y0, in the component X smallest_distance_to_closest_node = smallest_distance_to_component closest_node_in_component = random_element_component for node in component: distance_to_closest_node = self._distance_ind( node, closest_node) if distance_to_closest_node < smallest_distance_to_closest_node: smallest_distance_to_closest_node = distance_to_closest_node closest_node_in_component = node barycenter = utils.compute_barycenter( [[closest_node, self._data[closest_node]], [closest_node_in_component, self._data[closest_node_in_component]]]) closest_target = utils.find_closest( barycenter, list(self._data.items())) self.add_sensor_close_to_target(closest_target[0]) nb_added += 1 return nb_added def neighborhood_2(self, to_remove=4): """ Remove to_remove sensors randomly selected. Then fix the coverage and connection for admissibility """ self.remove_random_sensors(to_remove) nb_added = 0 nb_added += self.fix_broken_connection() nb_added += self.fix_broken_coverrage() nb_added += self.fix_broken_connection() if not(self.is_admissible()): raise RuntimeError if to_remove - nb_added > 0: logging.debug("Neighborhood 2 : Removed {} sensors".format(to_remove - nb_added)) else: logging.debug("Neighborhood 2 : Added {} sensors".format(nb_added - to_remove))
<reponame>vclabskku/nlos<gh_stars>0 """BSD 2-Clause License Copyright (c) 2019, Allied Vision Technologies GmbH 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE SOFTWARE IS PRELIMINARY AND STILL IN TESTING AND VERIFICATION PHASE AND IS PROVIDED ON AN “AS IS” AND “AS AVAILABLE” BASIS AND IS BELIEVED TO CONTAIN DEFECTS. A PRIMARY PURPOSE OF THIS EARLY ACCESS IS TO OBTAIN FEEDBACK ON PERFORMANCE AND THE IDENTIFICATION OF DEFECT SOFTWARE, HARDWARE AND DOCUMENTATION. """ import unittest import threading import os from vimba import * from vimba.frame import * def dummy_frame_handler(cam: Camera, frame: Frame): pass class CamCameraTest(unittest.TestCase): def setUp(self): self.vimba = Vimba.get_instance() self.vimba._startup() try: self.cam = self.vimba.get_camera_by_id(self.get_test_camera_id()) except VimbaCameraError as e: self.vimba._shutdown() raise Exception('Failed to lookup Camera.') from e self.cam.set_access_mode(AccessMode.Full) def tearDown(self): self.cam.set_access_mode(AccessMode.Full) self.vimba._shutdown() def test_camera_context_manager_access_mode(self): # Expectation: Entering Context must not throw in cases where the current access mode is # within get_permitted_access_modes() permitted_modes = self.cam.get_permitted_access_modes() for mode in permitted_modes: self.cam.set_access_mode(mode) try: with self.cam: pass except BaseException: self.fail() def test_camera_context_manager_feature_discovery(self): # Expectation: Outside of context, all features must be cleared, # inside of context all features must be detected. with self.cam: self.assertNotEqual(self.cam.get_all_features(), ()) def test_camera_access_mode(self): # Expectation: set/get access mode self.cam.set_access_mode(AccessMode.None_) self.assertEqual(self.cam.get_access_mode(), AccessMode.None_) self.cam.set_access_mode(AccessMode.Full) self.assertEqual(self.cam.get_access_mode(), AccessMode.Full) self.cam.set_access_mode(AccessMode.Read) self.assertEqual(self.cam.get_access_mode(), AccessMode.Read) def test_camera_get_id(self): # Expectation: get decoded camera id self.assertTrue(self.cam.get_id()) def test_camera_get_name(self): # Expectation: get decoded camera name self.assertTrue(self.cam.get_name()) def test_camera_get_model(self): # Expectation: get decoded camera model self.assertTrue(self.cam.get_model()) def test_camera_get_serial(self): # Expectation: get decoded camera serial self.assertTrue(self.cam.get_serial()) def test_camera_get_permitted_access_modes(self): # Expectation: get currently permitted access modes expected = (AccessMode.None_, AccessMode.Full, AccessMode.Read, AccessMode.Config) for mode in self.cam.get_permitted_access_modes(): self.assertIn(mode, expected) def test_camera_get_interface_id(self): # Expectation: get interface Id this camera is connected to self.assertTrue(self.cam.get_interface_id()) def test_camera_get_features_affected(self): # Expectation: Features that affect other features shall return a set of affected feature # Features that don't affect other features shall return (). If a Feature is supplied that # is not associated with that camera, a TypeError must be raised. with self.cam: try: affect = self.cam.get_feature_by_name('Height') except VimbaFeatureError as e: raise unittest.SkipTest('Failed to lookup Feature Height') from e try: not_affect = self.cam.get_feature_by_name('AcquisitionFrameCount') except VimbaFeatureError as e: raise unittest.SkipTest('Failed to lookup Feature AcquisitionFrameCount') from e self.assertEqual(self.cam.get_features_affected_by(not_affect), ()) try: payload_size = self.cam.get_feature_by_name('PayloadSize') except VimbaFeatureError as e: raise unittest.SkipTest('Failed to lookup Feature PayloadSize') from e self.assertIn(payload_size, self.cam.get_features_affected_by(affect)) def test_camera_frame_generator_limit_set(self): # Expectation: The Frame generator fetches the given number of images. with self.cam: self.assertEqual(len([i for i in self.cam.get_frame_generator(0)]), 0) self.assertEqual(len([i for i in self.cam.get_frame_generator(1)]), 1) self.assertEqual(len([i for i in self.cam.get_frame_generator(7)]), 7) self.assertEqual(len([i for i in self.cam.get_frame_generator(11)]), 11) def test_camera_frame_generator_error(self): # Expectation: The Frame generator raises a ValueError on a # negative limit and the camera raises an ValueError # if the camera is not opened. # generator execution must throw if streaming is enabled with self.cam: # Check limits self.assertRaises(ValueError, self.cam.get_frame_generator, -1) self.assertRaises(ValueError, self.cam.get_frame_generator, 1, 0) self.assertRaises(ValueError, self.cam.get_frame_generator, 1, -1) self.cam.start_streaming(dummy_frame_handler, 5) self.assertRaises(VimbaCameraError, self.cam.get_frame) self.assertRaises(VimbaCameraError, next, self.cam.get_frame_generator(1)) # Stop Streaming: Everything should be fine. self.cam.stop_streaming() self.assertNoRaise(self.cam.get_frame) self.assertNoRaise(next, self.cam.get_frame_generator(1)) def test_camera_get_frame(self): # Expectation: Gets single Frame without any exception. Image data must be set. # If a zero or negative timeouts must lead to a ValueError. with self.cam: self.assertRaises(ValueError, self.cam.get_frame, 0) self.assertRaises(ValueError, self.cam.get_frame, -1) self.assertNoRaise(self.cam.get_frame) self.assertEqual(type(self.cam.get_frame()), Frame) def test_camera_capture_error_outside_vimba_scope(self): # Expectation: Camera access outside of Vimba scope must lead to a RuntimeError gener = None with self.cam: gener = self.cam.get_frame_generator(1) # Shutdown API self.vimba._shutdown() # Access invalid Iterator self.assertRaises(RuntimeError, next, gener) def test_camera_capture_error_outside_camera_scope(self): # Expectation: Camera access outside of Camera scope must lead to a RuntimeError gener = None with self.cam: gener = self.cam.get_frame_generator(1) self.assertRaises(RuntimeError, next, gener) def test_camera_capture_timeout(self): # Expectation: Camera access outside of Camera scope must lead to a VimbaTimeout with self.cam: self.assertRaises(VimbaTimeout, self.cam.get_frame, 1) def test_camera_is_streaming(self): # Expectation: After start_streaming() is_streaming() must return true. After stop it must # return false. If the camera context is left without stop_streaming(), leaving # the context must stop streaming. # Normal Operation self.assertEqual(self.cam.is_streaming(), False) with self.cam: self.cam.start_streaming(dummy_frame_handler) self.assertEqual(self.cam.is_streaming(), True) self.cam.stop_streaming() self.assertEqual(self.cam.is_streaming(), False) # Missing the stream stop. Close must stop streaming with self.cam: self.cam.start_streaming(dummy_frame_handler, 5) self.assertEqual(self.cam.is_streaming(), True) self.assertEqual(self.cam.is_streaming(), False) def test_camera_streaming_error_frame_count(self): # Expectation: A negative or zero frame_count must lead to an value error with self.cam: self.assertRaises(ValueError, self.cam.start_streaming, dummy_frame_handler, 0) self.assertRaises(ValueError, self.cam.start_streaming, dummy_frame_handler, -1) def test_camera_streaming(self): # Expectation: A given frame_handler must be executed for each buffered frame. class FrameHandler: def __init__(self, frame_count): self.cnt = 0 self.frame_count = frame_count self.event = threading.Event() def __call__(self, cam: Camera, frame: Frame): self.cnt += 1 if self.cnt == self.frame_count: self.event.set() timeout = 5.0 frame_count = 10 handler = FrameHandler(frame_count) with self.cam: try: self.cam.start_streaming(handler, frame_count) # Wait until the FrameHandler has been executed for each queued frame self.assertTrue(handler.event.wait(timeout)) finally: self.cam.stop_streaming() def test_camera_streaming_queue(self): # Expectation: A given frame must be reused if it is enqueued again. class FrameHandler: def __init__(self, frame_count): self.cnt = 0 self.frame_count = frame_count self.event = threading.Event() def __call__(self, cam: Camera, frame: Frame): self.cnt += 1 if self.cnt == self.frame_count: self.event.set() cam.queue_frame(frame) timeout = 5.0 frame_count = 5 frame_reuse = 2 handler = FrameHandler(frame_count * frame_reuse) with self.cam: try: self.cam.start_streaming(handler, frame_count) # Wait until the FrameHandler has been executed for each queued frame self.assertTrue(handler.event.wait(timeout)) finally: self.cam.stop_streaming() def test_camera_runtime_type_check(self): def valid_handler(cam, frame): pass def invalid_handler_1(cam): pass def invalid_handler_2(cam, frame, extra): pass self.assertRaises(TypeError, self.cam.set_access_mode, -1) with self.cam: # Expectation: raise TypeError on passing invalid parameters self.assertRaises(TypeError, self.cam.get_frame, 'hi') self.assertRaises(TypeError, self.cam.get_features_affected_by, 'No Feature') self.assertRaises(TypeError, self.cam.get_features_selected_by, 'No Feature') self.assertRaises(TypeError, self.cam.get_features_by_type, 0.0) self.assertRaises(TypeError, self.cam.get_feature_by_name, 0) self.assertRaises(TypeError, self.cam.get_frame_generator, '3') self.assertRaises(TypeError, self.cam.get_frame_generator, 0, 'foo') self.assertRaises(TypeError, self.cam.start_streaming, valid_handler, 'no int') self.assertRaises(TypeError, self.cam.start_streaming, invalid_handler_1) self.assertRaises(TypeError, self.cam.start_streaming, invalid_handler_2) self.assertRaises(TypeError, self.cam.save_settings, 0, PersistType.All) self.assertRaises(TypeError, self.cam.save_settings, 'foo.xml', 'false type') def test_camera_save_load_settings(self): # Expectation: After settings export a settings change must be reverted by loading a # Previously saved configuration. file_name = 'test_save_load_settings.xml' with self.cam: feat_height = self.cam.get_feature_by_name('Height') old_val = feat_height.get() self.cam.save_settings(file_name, PersistType.All) min_, max_ = feat_height.get_range() inc = feat_height.get_increment() feat_height.set(max_ - min_ - inc) self.cam.load_settings(file_name, PersistType.All) os.remove(file_name) self.assertEqual(old_val, feat_height.get()) def test_camera_save_settings_verify_path(self): # Expectation: Valid files end with .xml and can be either a absolute path or relative # path to the given File. Everything else is a ValueError. valid_paths = ( 'valid1.xml', os.path.join('.', 'valid2.xml'), os.path.join('Tests', 'valid3.xml'), os.path.join(os.path.dirname(os.path.abspath(__file__)), 'valid4.xml'), ) with self.cam: self.assertRaises(ValueError, self.cam.save_settings, 'inval.xm', PersistType.All) for path in valid_paths: self.assertNoRaise(self.cam.save_settings, path, PersistType.All) os.remove(path) def test_camera_load_settings_verify_path(self): # Expectation: Valid files end with .xml and must exist before before any execution. valid_paths = ( 'valid1.xml', os.path.join('.', 'valid2.xml'), os.path.join('Tests', 'valid3.xml'), os.path.join(os.path.dirname(os.path.abspath(__file__)), 'valid4.xml'), ) with self.cam: self.assertRaises(ValueError, self.cam.load_settings, 'inval.xm', PersistType.All) for path in valid_paths: self.assertRaises(ValueError, self.cam.load_settings, path, PersistType.All) for path in valid_paths: self.cam.save_settings(path, PersistType.All) self.assertNoRaise(self.cam.load_settings, path, PersistType.All) os.remove(path) def test_camera_context_manager_reentrancy(self): # Expectation: Camera Context Manager must be reentrant. Multiple calls to _open # must be prevented (would cause VimbaC - Error) with self.cam: with self.cam: with self.cam: pass def test_camera_api_context_sensitity_outside_context(self): # Expectation: Call set_access_mode withing with scope must raise a RuntimeError with self.cam: self.assertRaises(RuntimeError, self.cam.set_access_mode) def test_camera_api_context_sensitity_inside_context(self): # Expectation: Most Camera related functions are only valid then called within the given # Context. If called from Outside a runtime error must be raised. self.assertRaises(RuntimeError,
16463, 16465, 16466, 16467, 16468, 16471, 16472, 16473, 16474, 16475, 16476, 16477, 16478, 16479, 16480, 16483, 16484, 16485, 16486, 16487, 16489, 16490, 16491, 16492, 16494, 16496, 16497, 16498, 16499, 16501, 16502, 16503, 16504, 16505, 16506, 16507, 16508, 16509, 16510, 16513, 16514, 16515, 16516, 16518, 16519, 16521, 16522, 16523, 16524, 16525, 16526, 16527, 16528, 16530, 16531, 16532, 16533, 16534, 16535, 16536, 16539, 16540, 16541, 16542, 16543, 16544, 16545, 16548, 16549, 16550, 16551, 16552, 16554, 16555, 16558, 16560, 16561, 16562, 16563, 16564, 16565, 16566, 16567, 16568, 16569, 16571, 16573, 16574, 16577, 16578, 16579, 16580, 16581, 16583, 16602, 16603, 16604, 16605, 16606, 16607, 16608, 16622, 16623, 16642, 16643, 16644, 16645, 16646, 16647, 16648, 16649, 16650, 16651, 16652, 16653, 16654, 16655, 16656, 16658, 16659, 16660, 16661, 16662, 16663, 16665, 16666, 16667, 16668, 16669, 16670, 16671, 16672, 16673, 16674, 16675, 16676, 16677, 16678, 16679, 16680, 16681, 16682, 16683, 16684, 16685, 16686, 16687, 16688, 16689, 16690, 16691, 16692, 16693, 16694, 16695, 16696, 16697, 16698, 16699, 16700, 16701, 16702, 16703, 16704, 16705, 16706, 16707, 16708, 16709, 16710, 16711, 16712, 16713, 16714, 16715, 16716, 16717, 16718, 16719, 16720, 16721, 16722, 16723, 16724, 16725, 16726, 16727, 16728, 16729, 16730, 16731, 16732, 16733, 16734, 16735, 16736, 16737, 16738, 16739, 16740, 16741, 16742, 16743, 16744, 16745, 16746, 16747, 16748, 16762, 16763, 16764, 16765, 16766, 16767, 16768, 16769, 16782, 16783, 16784, 16785, 16786, 16787, 16788, 16789, 16790, 16791, 16793, 16794, 16795, 16796, 16797, 16798, 16799, 16800, 16801, 16802, 16803, 16804, 16805, 16806, 16807, 16808, 16809, 16810, 16811, 16812, 16813, 16814, 16815, 16816, 16817, 16818, 16819, 16820, 16821, 16822, 16823, 16824, 16825, 16826, 16827, 16828, 16829, 16830, 16831, 16832, 16833, 16834, 16835, 16836, 16837, 16838, 16839, 16840, 16841, 16842, 16843, 16844, 16845, 16846, 16847, 16848, 16849, 16850, 16851, 16852, 16853, 16854, 16855, 16856, 16857, 16858, 16859, 16860, 16861, 16862, 16863, 16864, 16865, 16866, 16867, 16868, 16869, 16870, 16871, 16872, 16873, 16882, 16883, 16884, 16885, 16886, 16887, 16888, 16889, 16890, 16891, 16892, 16893, 16894, 16895, 16896, 16897, 16898, 16899, 16900, 16901, 16902, 16903, 16904, 16905, 16906, 16907, 16908, 16909, 16910, 16911, 16912, 16913, 16914, 16915, 16916, 16917, 16918, 16919, 16920, 16921, 16922, 16923, 16924, 16925, 16926, 16927, 16928, 16929, 16930, 16931, 16932, 16933, 16934, 16935, 16936, 16937, 16938, 16939, 16940, 16941, 16942, 16943, 16944, 16945, 16946, 16947, 16948, 16949, 16950, 16951, 16952, 16953, 16954, 16955, 16956, 16957, 16958, 16959, 16960, 16961, 16962, 16963, 16964, 16965, 16966, 16967, 16968, 16969, 16970, 16971, 16972, 16973, 16974, 16975, 16976, 16977, 16978, 16979, 16980, 16981, 16982, 16983, 16984, 16985, 16986, 16987, 16988, 16989, 16990, 16991, 16992, 16993, 16994, 16995, 16996, 16997, 16998, 16999, 17001, 17002, 17003, 17004, 17005, 17006, 17007, 17008, 17009, 17010, 17011, 17012, 17013, 17014, 17015, 17016, 17017, 17018, 17019, 17020, 17021, 17022, 17023, 17024, 17025, 17026, 17027, 17028, 17029, 17030, 17031, 17032, 17033, 17034, 17035, 17036, 17037, 17038, 17039, 17042, 17043, 17044, 17045, 17046, 17047, 17048, 17049, 17050, 17051, 17052, 17053, 17054, 17055, 17056, 17057, 17058, 17059, 17060, 17061, 17062, 17063, 17064, 17065, 17066, 17067, 17068, 17069, 17070, 17071, 17072, 17073, 17074, 17075, 17076, 17077, 17078, 17082, 17102, 17103, 17104, 17105, 17106, 17107, 17109, 17110, 17111, 17112, 17113, 17114, 17117, 17118, 17119, 17124, 17125, 17126, 17142, 17182, 17183, 17184, 17185, 17186, 17187, 17188, 17189, 17190, 17191, 17192, 17193, 17194, 17195, 17196, 17197, 17198, 17200, 17201, 17202, 17203, 17204, 17222, 17223, 17224, 17242, 17262, 17302, 17303, 17304, 17305, 17306, 17307, 17308, 17309, 17310, 17322, 17323, 17324, 17325, 17326, 17327, 17328, 17329, 17330, 17331, 17332, 17333, 17344, 17345, 17346, 17348, 17349, 17351, 17352, 17353, 17355, 17362, 17363, 17364, 17384, 17402, 17403, 17404, 17405, 17406, 17407, 17408, 17410, 17411, 17413, 17414, 17422, 17423, 17442, 17502, 17503, 17504, 17505, 17506, 17507, 17508, 17522, 17523, 17542, 17562, 17564, 17566, 17567, 17568, 17569, 17570, 17571, 17572, 17573, 17576, 17577, 17578, 17579, 17580, 17581, 17583, 17584, 17586, 17588, 17590, 17591, 17592, 17593, 17594, 17596, 17598, 17599, 17600, 17601, 17602, 17603, 17604, 17605, 17607, 17608, 17610, 17611, 17612, 17613, 17616, 17617, 17618, 17620, 17622, 17623, 17624, 17625, 17626, 17642, 17643, 17662, 17682, 17683, 17684, 17685, 17686, 17687, 17688, 17689, 17690, 17691, 17692, 17693, 17694, 17695, 17696, 17702, 17703, 17704, 17705, 17706, 17707, 17708, 17709, 17710, 17711, 17712, 17713, 17714, 17715, 17716, 17717, 17718, 17719, 17720, 17721, 17722, 17723, 17724, 17725, 17726, 17727, 17728, 17730, 17732, 17733, 17734, 17735, 17736, 17737, 17738, 17739, 17740, 17741, 17742, 17743, 17744, 17745, 17746, 17747, 17748, 17749, 17750, 17751, 17752, 17753, 17754, 17755, 17756, 17757, 17758, 17759, 17760, 17761, 17762, 17763, 17764, 17765, 17766, 17767, 17768, 17770, 17771, 17772, 17773, 17774, 17775, 17776, 17777, 17778, 17779, 17780, 17781, 17782, 17849, 17850, 17900, 17901, 17902, 17903, 17904, 17905, 17906, 17907, 17908, 17909, 17922, 17943, 17962, 17963, 17964, 17965, 17966, 17968, 17969, 35514, 34955, 18002, 34684, 35279, 35280, 18022, 18042, 18043, 18044, 18045, 18046, 18047, 18048, 18082, 18083, 18102, 18103, 18104, 18142, 18143, 18144, 18145, 18146, 18147, 18148, 18149, 18150, 18151, 18152, 18154, 18160, 18168, 18169, 18170, 18171, 18172, 18173, 18182, 18202, 18203, 18204, 18205, 18206, 18207, 18208, 18222, 18223, 18224, 18225, 18226, 18227, 18228, 18229, 18230, 18231, 18232, 18233, 18234, 18236, 18237, 18238, 18239, 18240, 18241, 18242, 18243, 18244, 18245, 18246, 18247, 18248, 18249, 18250, 18251, 18252, 18253, 18254, 18255, 18256, 18257, 18258, 18259, 18260, 18261, 18262, 18263, 18264, 18265, 18266, 18267, 18268, 18269, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289, 18290, 18291, 18292, 18294, 18295, 18296, 18297, 18298, 18299, 18300, 18301, 18302, 18305, 18306, 18307, 18308, 18309, 18310, 18311, 18312, 18313, 18314, 18315, 18317, 18318, 18319, 18321, 18322, 18323, 18324, 18325, 18326, 18327, 18328, 18329, 18330, 18331, 18332, 18333, 18334, 18335, 18336, 18337, 18338, 18339, 18340, 18343, 18344, 18345, 18346, 18347, 18348, 18349, 18350, 18351, 18352, 18353, 18354, 18356, 18357, 18358, 18359, 18360, 18361, 18362, 18363, 18364, 18365, 18366, 18367, 18368, 18369, 18370, 18371, 18372, 18373, 18374, 18375, 18376, 18377, 18378, 18379, 18380, 18381, 18382, 18383, 18384, 18385, 18386, 18387, 18388, 18389, 18390, 18391, 18392, 18393, 18394, 18395, 18396, 18397, 18398, 18399, 18400, 18401, 18402, 18403, 18404, 18405, 18406, 18407, 18408, 18409, 18410, 18411, 18412, 18413, 18414, 18415, 18416, 18417, 18418, 18420, 18421, 18422, 18423, 18424, 18425, 18426, 18427, 18428, 18429, 18430, 18432, 18434, 18435, 18436, 18437, 18440, 18441, 18442, 18443, 18444, 18445, 18447, 18448, 18449, 18450, 18451, 18452, 18453, 18454, 18455, 18456, 18457, 18458, 18459, 18460, 18461, 18462, 18463, 18464, 18465, 18466, 18467, 18468, 18469, 18470, 18471, 18472, 18473, 18475, 18476, 18477, 18478, 18479, 18480, 18481, 18482, 18483, 18484, 18485, 18486, 18487, 18488, 18489, 18490, 18491, 18492, 18493, 18494, 18495, 18496, 18497, 18498, 18499, 18500, 18501, 18502, 18503, 18504, 18505, 18506, 18507, 18508, 18509, 18510, 18511, 18512, 18513, 18514, 18515, 18516, 18517, 18518, 18519, 18520, 18521, 18522, 18523, 18524, 18525, 18526, 18527, 18528, 18529, 18530, 18531, 18532, 18533, 18534, 18535, 18536, 18537, 18538, 18539, 18540, 18541, 18542, 18543, 18544, 18545, 18546, 18547, 18562, 18563, 18564, 18565, 18566, 18567, 18582, 18583, 18584, 18585, 18586, 18587, 18588, 18590, 18591, 18592, 18594, 18597, 18598, 18600, 18601, 18602, 18603, 18604, 18605, 18606, 18607, 18608, 18609, 18610, 18611, 18612, 18622, 18623, 18624, 18625, 18626, 18628, 18629, 18631, 18632, 18633, 18634, 18635, 18636, 18637, 18638, 18639, 18640, 18641, 18642, 18643, 18645, 18646, 18647, 18648, 18649, 18650, 18651, 18652, 18653, 18654, 18655, 18656, 18657, 18658, 18659, 18660, 18661, 18662, 18663, 18664, 18665, 18670, 18671, 18672, 18673, 18674, 18675, 18676, 18677, 18678, 18679, 18680, 18681, 18682, 18683, 18684, 18686, 18687, 18688, 18689, 18690, 18691, 18692, 18693, 18694, 18695, 18696, 18697, 18698, 18699, 18700, 18701, 18702, 18703, 18704, 18705, 18706, 18707, 18708, 18709, 18710, 18711, 18712, 18713, 18714, 18715, 18716, 18717, 18718, 18719, 18720, 18721, 18722, 18723, 18724, 18725, 18726, 18727, 18728, 18729, 18730, 18731, 18734, 18735, 18736, 18737, 18738, 18739, 18740, 18741, 18742, 18743, 18744, 18745, 18746, 18749, 18752, 18753, 18754, 18755, 18756, 18757, 18758, 18759, 18760, 18761, 18762, 18766, 18767, 18769, 18770, 18771,
StoredFieldFacet(FacetType): """Lets you sort/group using the value in an unindexed, stored field (e.g. :class:`whoosh.fields.STORED`). This is usually slower than using an indexed field. For fields where the stored value is a space-separated list of keywords, (e.g. ``"tag1 tag2 tag3"``), you can use the ``allow_overlap`` keyword argument to allow overlapped faceting on the result of calling the ``split()`` method on the field value (or calling a custom split function if one is supplied). """ def __init__(self, fieldname, allow_overlap=False, split_fn=None, maptype=None): """ :param fieldname: the name of the stored field. :param allow_overlap: if True, when grouping, allow documents to appear in multiple groups when they have multiple terms in the field. The categorizer uses ``string.split()`` or the custom ``split_fn`` to convert the stored value into a list of facet values. :param split_fn: a custom function to split a stored field value into multiple facet values when ``allow_overlap`` is True. If not supplied, the categorizer simply calls the value's ``split()`` method. """ self.fieldname = fieldname self.allow_overlap = allow_overlap self.split_fn = split_fn self.maptype = maptype def default_name(self): return self.fieldname def categorizer(self, global_searcher): return self.StoredFieldCategorizer(self.fieldname, self.allow_overlap, self.split_fn) class StoredFieldCategorizer(Categorizer): def __init__(self, fieldname, allow_overlap, split_fn): self.fieldname = fieldname self.allow_overlap = allow_overlap self.split_fn = split_fn def set_searcher(self, segment_searcher, docoffset): self.segment_searcher = segment_searcher def keys_for(self, matcher, docid): d = self.segment_searcher.stored_fields(docid) value = d.get(self.fieldname) if self.split_fn: return self.split_fn(value) else: return value.split() def key_for(self, matcher, docid): d = self.segment_searcher.stored_fields(docid) return d.get(self.fieldname) class MultiFacet(FacetType): """Sorts/facets by the combination of multiple "sub-facets". For example, to sort by the value of the "tag" field, and then (for documents where the tag is the same) by the value of the "path" field:: facet = MultiFacet(FieldFacet("tag"), FieldFacet("path") results = searcher.search(myquery, sortedby=facet) As a shortcut, you can use strings to refer to field names, and they will be assumed to be field names and turned into FieldFacet objects:: facet = MultiFacet("tag", "path") You can also use the ``add_*`` methods to add criteria to the multifacet:: facet = MultiFacet() facet.add_field("tag") facet.add_field("path", reverse=True) facet.add_query({"a-m": TermRange("name", "a", "m"), "n-z": TermRange("name", "n", "z")}) """ def __init__(self, items=None, maptype=None): self.facets = [] if items: for item in items: self._add(item) self.maptype = maptype def __repr__(self): return "%s(%r, %r)" % (self.__class__.__name__, self.facets, self.maptype) @classmethod def from_sortedby(cls, sortedby): multi = cls() if isinstance(sortedby, string_type): multi._add(sortedby) elif (isinstance(sortedby, (list, tuple)) or hasattr(sortedby, "__iter__")): for item in sortedby: multi._add(item) else: multi._add(sortedby) return multi def _add(self, item): if isinstance(item, FacetType): self.add_facet(item) elif isinstance(item, string_type): self.add_field(item) else: raise Exception("Don't know what to do with facet %r" % (item,)) def add_field(self, fieldname, reverse=False): self.facets.append(FieldFacet(fieldname, reverse=reverse)) return self def add_query(self, querydict, other=None, allow_overlap=False): self.facets.append(QueryFacet(querydict, other=other, allow_overlap=allow_overlap)) return self def add_score(self): self.facets.append(ScoreFacet()) return self def add_facet(self, facet): if not isinstance(facet, FacetType): raise TypeError("%r is not a facet object, perhaps you meant " "add_field()" % (facet,)) self.facets.append(facet) return self def categorizer(self, global_searcher): if not self.facets: raise Exception("No facets") elif len(self.facets) == 1: catter = self.facets[0].categorizer(global_searcher) else: catter = self.MultiCategorizer([facet.categorizer(global_searcher) for facet in self.facets]) return catter class MultiCategorizer(Categorizer): def __init__(self, catters): self.catters = catters @property def needs_current(self): return any(c.needs_current for c in self.catters) def set_searcher(self, segment_searcher, docoffset): for catter in self.catters: catter.set_searcher(segment_searcher, docoffset) def key_for(self, matcher, docid): return tuple(catter.key_for(matcher, docid) for catter in self.catters) def key_to_name(self, key): return tuple(catter.key_to_name(keypart) for catter, keypart in izip(self.catters, key)) class Facets(object): """Maps facet names to :class:`FacetType` objects, for creating multiple groupings of documents. For example, to group by tag, and **also** group by price range:: facets = Facets() facets.add_field("tag") facets.add_facet("price", RangeFacet("price", 0, 1000, 100)) results = searcher.search(myquery, groupedby=facets) tag_groups = results.groups("tag") price_groups = results.groups("price") (To group by the combination of multiple facets, use :class:`MultiFacet`.) """ def __init__(self, x=None): self.facets = {} if x: self.add_facets(x) @classmethod def from_groupedby(cls, groupedby): facets = cls() if isinstance(groupedby, (cls, dict)): facets.add_facets(groupedby) elif isinstance(groupedby, string_type): facets.add_field(groupedby) elif isinstance(groupedby, FacetType): facets.add_facet(groupedby.default_name(), groupedby) elif isinstance(groupedby, (list, tuple)): for item in groupedby: facets.add_facets(cls.from_groupedby(item)) else: raise Exception("Don't know what to do with groupedby=%r" % groupedby) return facets def names(self): """Returns an iterator of the facet names in this object. """ return iter(self.facets) def items(self): """Returns a list of (facetname, facetobject) tuples for the facets in this object. """ return self.facets.items() def add_field(self, fieldname, **kwargs): """Adds a :class:`FieldFacet` for the given field name (the field name is automatically used as the facet name). """ self.facets[fieldname] = FieldFacet(fieldname, **kwargs) return self def add_query(self, name, querydict, **kwargs): """Adds a :class:`QueryFacet` under the given ``name``. :param name: a name for the facet. :param querydict: a dictionary mapping keys to :class:`whoosh.query.Query` objects. """ self.facets[name] = QueryFacet(querydict, **kwargs) return self def add_facet(self, name, facet): """Adds a :class:`FacetType` object under the given ``name``. """ if not isinstance(facet, FacetType): raise Exception("%r:%r is not a facet" % (name, facet)) self.facets[name] = facet return self def add_facets(self, facets, replace=True): """Adds the contents of the given ``Facets`` or ``dict`` object to this object. """ if not isinstance(facets, (dict, Facets)): raise Exception("%r is not a Facets object or dict" % facets) for name, facet in facets.items(): if replace or name not in self.facets: self.facets[name] = facet return self # Objects for holding facet groups class FacetMap(object): """Base class for objects holding the results of grouping search results by a Facet. Use an object's ``as_dict()`` method to access the results. You can pass a subclass of this to the ``maptype`` keyword argument when creating a ``FacetType`` object to specify what information the facet should record about the group. For example:: # Record each document in each group in its sorted order myfacet = FieldFacet("size", maptype=OrderedList) # Record only the count of documents in each group myfacet = FieldFacet("size", maptype=Count) """ def add(self, groupname, docid, sortkey): """Adds a document to the facet results. :param groupname: the name of the group to add this document to. :param docid: the document number of the document to add. :param sortkey: a value representing the sort position of the document in the full results. """ raise NotImplementedError def as_dict(self): """Returns a dictionary object mapping group names to implementation-specific values. For example, the value might be a list of document numbers, or a integer representing the number of documents in the group. """ raise NotImplementedError class OrderedList(FacetMap): """Stores a list of document numbers for each group, in the same order as they appear in the search results. The ``as_dict`` method returns a dictionary mapping group names to lists of document numbers. """ def __init__(self): self.dict = defaultdict(list) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.dict) def add(self, groupname, docid, sortkey): self.dict[groupname].append((sortkey, docid)) def as_dict(self): d = {} for key, items in iteritems(self.dict): d[key] = [docnum for _, docnum in sorted(items)] return d class UnorderedList(FacetMap): """Stores a list of document numbers for each group, in arbitrary order. This is slightly faster and uses less memory than :class:`OrderedListResult` if you don't care about the ordering of the documents within groups. The ``as_dict`` method returns a dictionary mapping group names to lists of document numbers. """ def __init__(self): self.dict = defaultdict(list) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.dict) def add(self, groupname, docid, sortkey): self.dict[groupname].append(docid) def as_dict(self): return dict(self.dict) class Count(FacetMap): """Stores the number of documents in each group. The ``as_dict`` method returns a dictionary mapping group names to integers. """ def __init__(self): self.dict = defaultdict(int) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.dict) def add(self, groupname, docid, sortkey): self.dict[groupname] += 1 def as_dict(self): return dict(self.dict) class Best(FacetMap): """Stores the "best" document in each group (that is, the one with the highest sort key). The ``as_dict`` method returns a dictionary mapping group names to docnument numbers. """ def __init__(self): self.bestids = {} self.bestkeys = {} def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.bestids) def add(self, groupname, docid, sortkey): if groupname not in self.bestids or sortkey < self.bestkeys[groupname]: self.bestids[groupname] = docid self.bestkeys[groupname] = sortkey def as_dict(self): return self.bestids # Helper functions def add_sortable(writer, fieldname, facet, column=None): """Adds a per-document value column to an existing field which was created without the
for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_device_group_datasource_list" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'device_group_id' is set if ('device_group_id' not in params or params['device_group_id'] is None): raise ValueError("Missing the required parameter `device_group_id` when calling `get_device_group_datasource_list`") # noqa: E501 if 'device_group_id' in params and not re.search('\d+', params['device_group_id'] if type(params['device_group_id']) is str else str(params['device_group_id'])): # noqa: E501 raise ValueError("Invalid value for parameter `device_group_id` when calling `get_device_group_datasource_list`, must conform to the pattern `/\d+/`") # noqa: E501 collection_formats = {} path_params = {} if 'device_group_id' in params: path_params['deviceGroupId'] = params['device_group_id'] # noqa: E501 query_params = [] if 'include_disabled_data_source_without_instance' in params: query_params.append(('includeDisabledDataSourceWithoutInstance', params['include_disabled_data_source_without_instance'])) # noqa: E501 if 'fields' in params: query_params.append(('fields', params['fields'])) # noqa: E501 if 'size' in params: query_params.append(('size', params['size'])) # noqa: E501 if 'offset' in params: query_params.append(('offset', params['offset'])) # noqa: E501 if 'filter' in params: query_params.append(('filter', params['filter'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['LMv1'] # noqa: E501 return self.api_client.call_api( '/device/groups/{deviceGroupId}/datasources', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='DeviceGroupDatasourcePaginationResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_device_group_list(self, **kwargs): # noqa: E501 """get device group list # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_device_group_list(async_req=True) >>> result = thread.get() :param async_req bool :param str fields: :param int size: :param int offset: :param str filter: :return: DeviceGroupPaginationResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_device_group_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_device_group_list_with_http_info(**kwargs) # noqa: E501 return data def get_device_group_list_with_http_info(self, **kwargs): # noqa: E501 """get device group list # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_device_group_list_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param str fields: :param int size: :param int offset: :param str filter: :return: DeviceGroupPaginationResponse If the method is called asynchronously, returns the request thread. """ all_params = ['fields', 'size', 'offset', 'filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_device_group_list" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'fields' in params: query_params.append(('fields', params['fields'])) # noqa: E501 if 'size' in params: query_params.append(('size', params['size'])) # noqa: E501 if 'offset' in params: query_params.append(('offset', params['offset'])) # noqa: E501 if 'filter' in params: query_params.append(('filter', params['filter'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['LMv1'] # noqa: E501 return self.api_client.call_api( '/device/groups', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='DeviceGroupPaginationResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_device_group_property_by_name(self, gid, name, **kwargs): # noqa: E501 """get device group property by name # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_device_group_property_by_name(gid, name, async_req=True) >>> result = thread.get() :param async_req bool :param int gid: group ID (required) :param str name: (required) :param str fields: :return: EntityProperty If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_device_group_property_by_name_with_http_info(gid, name, **kwargs) # noqa: E501 else: (data) = self.get_device_group_property_by_name_with_http_info(gid, name, **kwargs) # noqa: E501 return data def get_device_group_property_by_name_with_http_info(self, gid, name, **kwargs): # noqa: E501 """get device group property by name # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_device_group_property_by_name_with_http_info(gid, name, async_req=True) >>> result = thread.get() :param async_req bool :param int gid: group ID (required) :param str name: (required) :param str fields: :return: EntityProperty If the method is called asynchronously, returns the request thread. """ all_params = ['gid', 'name', 'fields'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_device_group_property_by_name" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'gid' is set if ('gid' not in params or params['gid'] is None): raise ValueError("Missing the required parameter `gid` when calling `get_device_group_property_by_name`") # noqa: E501 # verify the required parameter 'name' is set if ('name' not in params or params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `get_device_group_property_by_name`") # noqa: E501 if 'gid' in params and not re.search('\d+', params['gid'] if type(params['gid']) is str else str(params['gid'])): # noqa: E501 raise ValueError("Invalid value for parameter `gid` when calling `get_device_group_property_by_name`, must conform to the pattern `/\d+/`") # noqa: E501 if 'name' in params and not re.search('[^\/]+', params['name'] if type(params['name']) is str else str(params['name'])): # noqa: E501 raise ValueError("Invalid value for parameter `name` when calling `get_device_group_property_by_name`, must conform to the pattern `/[^\/]+/`") # noqa: E501 collection_formats = {} path_params = {} if 'gid' in params: path_params['gid'] = params['gid'] # noqa: E501 if 'name' in params: path_params['name'] = params['name'] # noqa: E501 query_params = [] if 'fields' in params: query_params.append(('fields', params['fields'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['LMv1'] # noqa: E501 return self.api_client.call_api( '/device/groups/{gid}/properties/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='EntityProperty', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_device_group_property_list(self, gid, **kwargs): # noqa: E501 """get device group properties # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_device_group_property_list(gid, async_req=True) >>> result = thread.get() :param async_req bool :param int gid: group ID (required) :param str fields: :param int size: :param int offset: :param str filter: :return: PropertyPaginationResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_device_group_property_list_with_http_info(gid, **kwargs) # noqa: E501 else: (data) = self.get_device_group_property_list_with_http_info(gid, **kwargs) # noqa: E501 return data def get_device_group_property_list_with_http_info(self, gid, **kwargs): # noqa: E501 """get device group properties # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_device_group_property_list_with_http_info(gid, async_req=True) >>> result = thread.get() :param async_req bool :param int gid: group ID (required) :param str fields: :param int size: :param int offset: :param str filter: :return: PropertyPaginationResponse If the method is called asynchronously, returns the request thread. """ all_params = ['gid', 'fields', 'size', 'offset', 'filter'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_device_group_property_list" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'gid' is set if ('gid' not in params or params['gid'] is None): raise ValueError("Missing the required parameter `gid` when calling `get_device_group_property_list`") # noqa: E501 if 'gid' in params and not re.search('\d+', params['gid'] if type(params['gid']) is str else str(params['gid'])): # noqa: E501 raise ValueError("Invalid value for parameter `gid` when calling `get_device_group_property_list`, must conform to the pattern `/\d+/`") # noqa: E501 collection_formats = {} path_params = {} if 'gid' in params: path_params['gid'] = params['gid'] # noqa: E501 query_params = [] if 'fields' in params: query_params.append(('fields', params['fields'])) # noqa: E501 if 'size' in params: query_params.append(('size', params['size'])) # noqa: E501
save_dir=save_dir, initial_state_path=initial_state_path) self.observation_space = self.idsgame_config.game_config.get_attacker_observation_space() def get_attacker_action(self, action) -> Union[int, Union[int, int], int]: import gym_idsgame.envs.util.idsgame_util as util attacker_action, _ = action return util.interpret_attack_action(attacker_action, self.idsgame_config.game_config) def get_defender_action(self, action) -> Union[Union[int, int], int, int]: import gym_idsgame.envs.util.idsgame_util as util defend_id = self.idsgame_config.defender_agent.action(self.state) defend_node_id, defend_node_pos, defend_type = util.interpret_defense_action( defend_id, self.idsgame_config.game_config) return defend_node_id, defend_node_pos, defend_type class DefenderEnv(IdsGameEnv, ABC): """ Abstract DefenderEnv of the IdsGameEnv. Environments where the attacker is part of the environment and the environment is designed to be used by a defender-agent should inherit this class """ def __init__(self, idsgame_config: IdsGameConfig, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ if idsgame_config is None: raise ValueError("Cannot instantiate env without configuration") if idsgame_config.attacker_agent is None: raise ValueError("Cannot instantiate defender-env without an attacker agent") super().__init__(idsgame_config=idsgame_config, save_dir=save_dir, initial_state_path=initial_state_path) self.observation_space = self.idsgame_config.game_config.get_defender_observation_space() def get_defender_action(self, action) -> Union[int, Union[int, int], int]: import gym_idsgame.envs.util.idsgame_util as util _, defender_action = action return util.interpret_defense_action(defender_action, self.idsgame_config.game_config) def get_attacker_action(self, action) -> Union[Union[int, int], int, int, bool]: import gym_idsgame.envs.util.idsgame_util as util attack_id = self.idsgame_config.attacker_agent.action(self.state) attack_node_id, attack_node_pos, attack_type, reconnaissance = util.interpret_attack_action(attack_id, self.idsgame_config.game_config) return attack_node_id, attack_node_pos, attack_type, reconnaissance class AttackDefenseEnv(IdsGameEnv, ABC): """ Abstract AttackDefenseEnv of the IdsGameEnv. Environments where both the attacker and defender are external to the environment should inherit this class. """ def __init__(self, idsgame_config: IdsGameConfig, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ if idsgame_config is None: raise ValueError("Cannot instantiate env without configuration") super().__init__(idsgame_config=idsgame_config, save_dir=save_dir, initial_state_path=initial_state_path) def get_defender_action(self, action: Union[int, int]) -> Union[int, Union[int, int], int]: _, defender_action = action import gym_idsgame.envs.util.idsgame_util as util return util.interpret_defense_action(defender_action, self.idsgame_config.game_config) def get_attacker_action(self, action: Union[int, int]) -> Union[Union[int, int], int, int]: attacker_action, _ = action import gym_idsgame.envs.util.idsgame_util as util return util.interpret_attack_action(attacker_action, self.idsgame_config.game_config) # -------- Concrete envs ------------ class IdsGameCyberEnv(AttackDefenseEnv): """ [AttackDefenseEnv] 4 layer, 5 servers per layer, 10 attack-defense-values, connected layers [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 [Rewards] Sparse [Version] 5 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ if idsgame_config is None: game_config = GameConfig(num_layers=2, num_servers_per_layer=3, num_attack_types=4, max_value=3) game_config.set_initial_state(defense_val=1, attack_val=0, num_vulnerabilities_per_node=1, det_val=2, vulnerability_val=0, num_vulnerabilities_per_layer=2) game_config.network_config = NetworkConfig(game_config.num_rows, game_config.num_cols, connected_layers=True) if initial_state_path is not None: game_config.set_load_initial_state(initial_state_path) idsgame_config = IdsGameConfig(game_config=game_config) idsgame_config.render_config.caption = "idsgame-cyber-v0" super().__init__(idsgame_config=idsgame_config, save_dir=save_dir) # -------- Version 0 ------------ class IdsGameRandomDefenseV0Env(AttackerEnv): """ [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random defender [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 [Rewards] Sparse [Version] 0 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ from gym_idsgame.agents.bot_agents.random_defense_bot_agent import RandomDefenseBotAgent if idsgame_config is None: game_config = GameConfig(num_layers=1, num_servers_per_layer=1, num_attack_types=10, max_value=9) game_config.set_initial_state(defense_val=2, attack_val=0, num_vulnerabilities_per_node=1, det_val=2, vulnerability_val=0, num_vulnerabilities_per_layer=1) if initial_state_path is not None: game_config.set_load_initial_state(initial_state_path) defender_agent = RandomDefenseBotAgent(game_config) idsgame_config = IdsGameConfig(game_config=game_config, defender_agent=defender_agent) idsgame_config.render_config.caption = "idsgame-random_defense-v0" super().__init__(idsgame_config=idsgame_config, save_dir=save_dir) class IdsGameMinimalDefenseV0Env(AttackerEnv): """ [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, defender following the "defend minimal strategy" [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 [Rewards] Sparse [Version] 0 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ from gym_idsgame.agents.bot_agents.defend_minimal_value_bot_agent import DefendMinimalValueBotAgent if idsgame_config is None: game_config = GameConfig(num_layers=1, num_servers_per_layer=1, num_attack_types=10, max_value=9) game_config.set_initial_state(defense_val=2, attack_val=0, num_vulnerabilities_per_node=1, det_val=2, vulnerability_val=0, num_vulnerabilities_per_layer=1) if initial_state_path is not None: game_config.set_load_initial_state(initial_state_path) defender_agent = DefendMinimalValueBotAgent(game_config) idsgame_config = IdsGameConfig(game_config=game_config, defender_agent=defender_agent) idsgame_config.render_config.caption = "idsgame-minimal_defense-v0" super().__init__(idsgame_config=idsgame_config, save_dir=save_dir) class IdsGameRandomAttackV0Env(DefenderEnv): """ [DefenderEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random attacker [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 [Rewards] Sparse [Version] 0 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ from gym_idsgame.agents.bot_agents.random_attack_bot_agent import RandomAttackBotAgent if idsgame_config is None: game_config = GameConfig(num_layers=1, num_servers_per_layer=1, num_attack_types=10, max_value=9) game_config.set_initial_state(defense_val=2, attack_val=0, num_vulnerabilities_per_node=1, det_val=2, vulnerability_val=0, num_vulnerabilities_per_layer=1) if initial_state_path is not None: game_config.set_load_initial_state(initial_state_path) attacker_agent = RandomAttackBotAgent(game_config, self) idsgame_config = IdsGameConfig(game_config=game_config, attacker_agent=attacker_agent) idsgame_config.render_config.caption = "idsgame-random_attack-v0" super().__init__(idsgame_config=idsgame_config, save_dir=save_dir) class IdsGameMaximalAttackV0Env(DefenderEnv): """ [DefenderEnv] 1 layer, 1 server per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 [Rewards] Sparse [Version] 0 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ from gym_idsgame.agents.bot_agents.attack_maximal_value_bot_agent import AttackMaximalValueBotAgent if idsgame_config is None: game_config = GameConfig(num_layers=1, num_servers_per_layer=1, num_attack_types=10, max_value=9) game_config.set_initial_state(defense_val=2, attack_val=0, num_vulnerabilities_per_node=1, det_val=2, vulnerability_val=0, num_vulnerabilities_per_layer=1) if initial_state_path is not None: game_config.set_load_initial_state(initial_state_path) attacker_agent = AttackMaximalValueBotAgent(game_config, self) idsgame_config = IdsGameConfig(game_config=game_config, attacker_agent=attacker_agent) idsgame_config.render_config.caption = "idsgame-maximal_attack-v0" super().__init__(idsgame_config=idsgame_config, save_dir=save_dir) class IdsGameV0Env(AttackDefenseEnv): """ [AttackDefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 [Rewards] Sparse [Version] 0 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config: configuration of the environment (if not specified a default config is used) """ if idsgame_config is None: game_config = GameConfig(num_layers=1, num_servers_per_layer=1, num_attack_types=10, max_value=9) game_config.set_initial_state(defense_val=2, attack_val=0, num_vulnerabilities_per_node=1, det_val=2, vulnerability_val=0, num_vulnerabilities_per_layer=1) if initial_state_path is not None: game_config.set_load_initial_state(initial_state_path) idsgame_config = IdsGameConfig(game_config=game_config) idsgame_config.render_config.caption = "idsgame-v0" super().__init__(idsgame_config=idsgame_config, save_dir=save_dir) # -------- Version 1 ------------ class IdsGameRandomDefenseV1Env(AttackerEnv): """ [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random defender [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 [Rewards] Sparse [Version] 1 [Observations] partially observed [Environment] Deterministic [Attacker Starting Position] Start node [Reconnaissance activities] disabled [Reconnaissance bool features] No """ def __init__(self, idsgame_config: IdsGameConfig = None, save_dir: str = None, initial_state_path: str = None): """ Initialization of the environment :param save_dir: directory to save outputs of the env :param initial_state_path: path to the initial state (if none, use default) :param idsgame_config:
y, w, h) def create_radio_group(self): return _gui.GuiMenu_create_radio_group(self) def add_item(self, *args): return _gui.GuiMenu_add_item(self, *args) def add_separator(self, *args): return _gui.GuiMenu_add_separator(self, *args) def add_sub_menu(self, *args): return _gui.GuiMenu_add_sub_menu(self, *args) def add_widget(self, widget): return _gui.GuiMenu_add_widget(self, widget) def remove_all_items(self): return _gui.GuiMenu_remove_all_items(self) def disable_all_items(self): return _gui.GuiMenu_disable_all_items(self) def enable_all_items(self): return _gui.GuiMenu_enable_all_items(self) def get_item(self, item_name): return _gui.GuiMenu_get_item(self, item_name) def get_items(self): return _gui.GuiMenu_get_items(self) def on_submenu_show(self, sender, event, data): return _gui.GuiMenu_on_submenu_show(self, sender, event, data) def on_submenu_hide(self, sender, event, data): return _gui.GuiMenu_on_submenu_hide(self, sender, event, data) def on_submenu_focus_out(self, sender, event, data): return _gui.GuiMenu_on_submenu_focus_out(self, sender, event, data) def on_submenu_click(self, sender, event, data): return _gui.GuiMenu_on_submenu_click(self, sender, event, data) def on_submenu_selection_changed(self, sender, event, data): return _gui.GuiMenu_on_submenu_selection_changed(self, sender, event, data) def draw_menu(self, dc): return _gui.GuiMenu_draw_menu(self, dc) def set_buttons(self, buttons): return _gui.GuiMenu_set_buttons(self, buttons) def get_parent_item(self): return _gui.GuiMenu_get_parent_item(self) def get_parent_menu(self): return _gui.GuiMenu_get_parent_menu(self) def get_main_menu(self): return _gui.GuiMenu_get_main_menu(self) def remove_item(self, item): return _gui.GuiMenu_remove_item(self, item) def remove_sub_menu(self, menu): return _gui.GuiMenu_remove_sub_menu(self, menu) def move_item(self, item, neighbor_item, after=False): return _gui.GuiMenu_move_item(self, item, neighbor_item, after) if _newclass: set_sub_menu_show_delay = staticmethod(_gui.GuiMenu_set_sub_menu_show_delay) else: set_sub_menu_show_delay = _gui.GuiMenu_set_sub_menu_show_delay def add_filter_item(self): return _gui.GuiMenu_add_filter_item(self) def remove_filter_item(self): return _gui.GuiMenu_remove_filter_item(self) def set_enable_filter(self, value, position=0): return _gui.GuiMenu_set_enable_filter(self, value, position) if _newclass: is_visible_by_filter = staticmethod(_gui.GuiMenu_is_visible_by_filter) else: is_visible_by_filter = _gui.GuiMenu_is_visible_by_filter if _newclass: class_info = staticmethod(_gui.GuiMenu_class_info) else: class_info = _gui.GuiMenu_class_info if _newclass: ___class_destructor__ = staticmethod(_gui.GuiMenu____class_destructor__) else: ___class_destructor__ = _gui.GuiMenu____class_destructor__ def get_class_info(self): return _gui.GuiMenu_get_class_info(self) GuiMenu_swigregister = _gui.GuiMenu_swigregister GuiMenu_swigregister(GuiMenu) EVT_ID_MENU_CLICK = cvar.EVT_ID_MENU_CLICK EVT_ID_MENU_SHOW = cvar.EVT_ID_MENU_SHOW EVT_ID_MENU_HIDE = cvar.EVT_ID_MENU_HIDE EVT_ID_MENU_FOCUS_OUT = cvar.EVT_ID_MENU_FOCUS_OUT EVT_ID_MENU_SELECTION_CHANGED = cvar.EVT_ID_MENU_SELECTION_CHANGED EVT_ID_MENU_KEY_PRESSED = cvar.EVT_ID_MENU_KEY_PRESSED EVT_ID_MENU_ITEM_OVER = cvar.EVT_ID_MENU_ITEM_OVER def GuiMenu_set_sub_menu_show_delay(ms): return _gui.GuiMenu_set_sub_menu_show_delay(ms) GuiMenu_set_sub_menu_show_delay = _gui.GuiMenu_set_sub_menu_show_delay def GuiMenu_is_visible_by_filter(text, filter): return _gui.GuiMenu_is_visible_by_filter(text, filter) GuiMenu_is_visible_by_filter = _gui.GuiMenu_is_visible_by_filter def GuiMenu_class_info(): return _gui.GuiMenu_class_info() GuiMenu_class_info = _gui.GuiMenu_class_info def GuiMenu____class_destructor__(instance, is_array): return _gui.GuiMenu____class_destructor__(instance, is_array) GuiMenu____class_destructor__ = _gui.GuiMenu____class_destructor__ class GuiMenuButtonGroup(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, GuiMenuButtonGroup, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, GuiMenuButtonGroup, name) __repr__ = _swig_repr def __init__(self, parent): this = _gui.new_GuiMenuButtonGroup(parent) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _gui.delete_GuiMenuButtonGroup __del__ = lambda self: None def add_button(self, label): return _gui.GuiMenuButtonGroup_add_button(self, label) def get_button(self, label): return _gui.GuiMenuButtonGroup_get_button(self, label) def get_parent(self): return _gui.GuiMenuButtonGroup_get_parent(self) def get_buttons(self): return _gui.GuiMenuButtonGroup_get_buttons(self) GuiMenuButtonGroup_swigregister = _gui.GuiMenuButtonGroup_swigregister GuiMenuButtonGroup_swigregister(GuiMenuButtonGroup) class GuiMenuButton(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, GuiMenuButton, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, GuiMenuButton, name) __repr__ = _swig_repr def __init__(self, *args): this = _gui.new_GuiMenuButton(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def push(self): return _gui.GuiMenuButton_push(self) def get_menu(self): return _gui.GuiMenuButton_get_menu(self) def set_menu(self, menu): return _gui.GuiMenuButton_set_menu(self, menu) def release_menu(self): return _gui.GuiMenuButton_release_menu(self) def get_menu_anchor(self): return _gui.GuiMenuButton_get_menu_anchor(self) def set_menu_anchor(self, anchor): return _gui.GuiMenuButton_set_menu_anchor(self, anchor) def process_event(self, event_id): return _gui.GuiMenuButton_process_event(self, event_id) def on_menu_hide(self, sender, event, data): return _gui.GuiMenuButton_on_menu_hide(self, sender, event, data) if _newclass: class_info = staticmethod(_gui.GuiMenuButton_class_info) else: class_info = _gui.GuiMenuButton_class_info if _newclass: ___class_destructor__ = staticmethod(_gui.GuiMenuButton____class_destructor__) else: ___class_destructor__ = _gui.GuiMenuButton____class_destructor__ def get_class_info(self): return _gui.GuiMenuButton_get_class_info(self) GuiMenuButton_swigregister = _gui.GuiMenuButton_swigregister GuiMenuButton_swigregister(GuiMenuButton) def GuiMenuButton_class_info(): return _gui.GuiMenuButton_class_info() GuiMenuButton_class_info = _gui.GuiMenuButton_class_info def GuiMenuButton____class_destructor__(instance, is_array): return _gui.GuiMenuButton____class_destructor__(instance, is_array) GuiMenuButton____class_destructor__ = _gui.GuiMenuButton____class_destructor__ class GuiMenuRadioGroup(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, GuiMenuRadioGroup, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, GuiMenuRadioGroup, name) __repr__ = _swig_repr def __init__(self): this = _gui.new_GuiMenuRadioGroup() try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _gui.delete_GuiMenuRadioGroup __del__ = lambda self: None def add_item(self, item): return _gui.GuiMenuRadioGroup_add_item(self, item) def remove_item(self, item): return _gui.GuiMenuRadioGroup_remove_item(self, item) def get_items(self): return _gui.GuiMenuRadioGroup_get_items(self) GuiMenuRadioGroup_swigregister = _gui.GuiMenuRadioGroup_swigregister GuiMenuRadioGroup_swigregister(GuiMenuRadioGroup) class GuiMenuItem(base.CoreCustomData): __swig_setmethods__ = {} for _s in [base.CoreCustomData]: __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) __setattr__ = lambda self, name, value: _swig_setattr(self, GuiMenuItem, name, value) __swig_getmethods__ = {} for _s in [base.CoreCustomData]: __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) __getattr__ = lambda self, name: _swig_getattr(self, GuiMenuItem, name) __repr__ = _swig_repr def __init__(self, *args): this = _gui.new_GuiMenuItem(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _gui.delete_GuiMenuItem __del__ = lambda self: None def get_name(self): return _gui.GuiMenuItem_get_name(self) def set_name(self, name): return _gui.GuiMenuItem_set_name(self, name) def is_separator(self): return _gui.GuiMenuItem_is_separator(self) def get_menu(self): return _gui.GuiMenuItem_get_menu(self) def is_sub_menu(self): return _gui.GuiMenuItem_is_sub_menu(self) def get_action(self): return _gui.GuiMenuItem_get_action(self) def is_action(self): return _gui.GuiMenuItem_is_action(self) def is_item(self): return _gui.GuiMenuItem_is_item(self) def is_clickable_menu(self): return _gui.GuiMenuItem_is_clickable_menu(self) def is_clickable(self): return _gui.GuiMenuItem_is_clickable(self) def get_shortcut(self): return _gui.GuiMenuItem_get_shortcut(self) def set_icon(self, *args): return _gui.GuiMenuItem_set_icon(self, *args) def set_icons(self, *args): return _gui.GuiMenuItem_set_icons(self, *args) def remove_icons(self): return _gui.GuiMenuItem_remove_icons(self) def get_icon(self): return _gui.GuiMenuItem_get_icon(self) def get_icons(self): return _gui.GuiMenuItem_get_icons(self) def set_bold(self, bold): return _gui.GuiMenuItem_set_bold(self, bold) def is_bold(self): return _gui.GuiMenuItem_is_bold(self) def set_faded(self, faded): return _gui.GuiMenuItem_set_faded(self, faded) def is_faded(self): return _gui.GuiMenuItem_is_faded(self) def set_italic(self, italic): return _gui.GuiMenuItem_set_italic(self, italic) def is_italic(self): return _gui.GuiMenuItem_is_italic(self) def set_checkable(self, flag): return _gui.GuiMenuItem_set_checkable(self, flag) def get_checkable(self): return _gui.GuiMenuItem_get_checkable(self) def check(self, flag): return _gui.GuiMenuItem_check(self, flag) def is_checked(self): return _gui.GuiMenuItem_is_checked(self) def set_radio_group(self, group): return _gui.GuiMenuItem_set_radio_group(self, group) def get_radio_group(self): return _gui.GuiMenuItem_get_radio_group(self) def disable(self): return _gui.GuiMenuItem_disable(self) def enable(self): return _gui.GuiMenuItem_enable(self) def is_disabled(self): return _gui.GuiMenuItem_is_disabled(self) def is_enabled(self): return _gui.GuiMenuItem_is_enabled(self) def set_data(self, data): return _gui.GuiMenuItem_set_data(self, data) def get_data(self): return _gui.GuiMenuItem_get_data(self) def set_is_clickable_menu(self, value): return _gui.GuiMenuItem_set_is_clickable_menu(self, value) def set_is_clickable(self, value): return _gui.GuiMenuItem_set_is_clickable(self, value) def set_doc(self, doc): return _gui.GuiMenuItem_set_doc(self, doc) def get_doc(self): return _gui.GuiMenuItem_get_doc(self) if _newclass: class_info = staticmethod(_gui.GuiMenuItem_class_info) else: class_info = _gui.GuiMenuItem_class_info if _newclass: ___class_destructor__ = staticmethod(_gui.GuiMenuItem____class_destructor__) else: ___class_destructor__ = _gui.GuiMenuItem____class_destructor__ def get_class_info(self): return _gui.GuiMenuItem_get_class_info(self) GuiMenuItem_swigregister = _gui.GuiMenuItem_swigregister GuiMenuItem_swigregister(GuiMenuItem) def GuiMenuItem_class_info(): return _gui.GuiMenuItem_class_info() GuiMenuItem_class_info = _gui.GuiMenuItem_class_info def GuiMenuItem____class_destructor__(instance, is_array): return _gui.GuiMenuItem____class_destructor__(instance, is_array) GuiMenuItem____class_destructor__ = _gui.GuiMenuItem____class_destructor__ class GuiIcon(base.EventObject): __swig_setmethods__ = {} for _s in [base.EventObject]: __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) __setattr__ = lambda self, name, value: _swig_setattr(self, GuiIcon, name, value) __swig_getmethods__ = {} for _s in [base.EventObject]: __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) __getattr__ = lambda self, name: _swig_getattr(self, GuiIcon, name) __repr__ = _swig_repr def __init__(self, data): this = _gui.new_GuiIcon(data) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _gui.delete_GuiIcon __del__ = lambda self: None def get_image(self, *args): return _gui.GuiIcon_get_image(self, *args) if _newclass: class_info = staticmethod(_gui.GuiIcon_class_info) else: class_info = _gui.GuiIcon_class_info if _newclass: ___class_destructor__ = staticmethod(_gui.GuiIcon____class_destructor__) else: ___class_destructor__ = _gui.GuiIcon____class_destructor__ def get_class_info(self): return _gui.GuiIcon_get_class_info(self) GuiIcon_swigregister = _gui.GuiIcon_swigregister GuiIcon_swigregister(GuiIcon) def GuiIcon_class_info(): return _gui.GuiIcon_class_info() GuiIcon_class_info = _gui.GuiIcon_class_info def GuiIcon____class_destructor__(instance, is_array): return _gui.GuiIcon____class_destructor__(instance, is_array) GuiIcon____class_destructor__ = _gui.GuiIcon____class_destructor__ class GuiInputDialog(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, GuiInputDialog, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, GuiInputDialog, name) __repr__ = _swig_repr VALUE_TYPE_STRING = _gui.GuiInputDialog_VALUE_TYPE_STRING VALUE_TYPE_INT = _gui.GuiInputDialog_VALUE_TYPE_INT VALUE_TYPE_SCRIPT = _gui.GuiInputDialog_VALUE_TYPE_SCRIPT VALUE_TYPE_ENUM = _gui.GuiInputDialog_VALUE_TYPE_ENUM VALUE_TYPE_LIST = _gui.GuiInputDialog_VALUE_TYPE_LIST def __init__(self, *args): this = _gui.new_GuiInputDialog(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def add_widget(self, label, value, type): return _gui.GuiInputDialog_add_widget(self, label, value, type) def show_modal(self): return _gui.GuiInputDialog_show_modal(self) def get_value(self, *args): return _gui.GuiInputDialog_get_value(self, *args) def is_ok(self): return _gui.GuiInputDialog_is_ok(self) if _newclass: class_info = staticmethod(_gui.GuiInputDialog_class_info) else: class_info = _gui.GuiInputDialog_class_info if _newclass: ___class_destructor__ = staticmethod(_gui.GuiInputDialog____class_destructor__) else: ___class_destructor__ = _gui.GuiInputDialog____class_destructor__ def get_class_info(self): return _gui.GuiInputDialog_get_class_info(self) GuiInputDialog_swigregister = _gui.GuiInputDialog_swigregister GuiInputDialog_swigregister(GuiInputDialog) def GuiInputDialog_class_info(): return _gui.GuiInputDialog_class_info() GuiInputDialog_class_info = _gui.GuiInputDialog_class_info def GuiInputDialog____class_destructor__(instance, is_array): return _gui.GuiInputDialog____class_destructor__(instance, is_array) GuiInputDialog____class_destructor__ = _gui.GuiInputDialog____class_destructor__ class GuiColorDialog(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, GuiColorDialog, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, GuiColorDialog, name) __repr__ = _swig_repr RETURN_OK = _gui.GuiColorDialog_RETURN_OK RETURN_CANCEL = _gui.GuiColorDialog_RETURN_CANCEL RETURN_UNKNOWN = _gui.GuiColorDialog_RETURN_UNKNOWN MODE_HUE = _gui.GuiColorDialog_MODE_HUE MODE_SATURATION = _gui.GuiColorDialog_MODE_SATURATION MODE_BRIGHTNESS = _gui.GuiColorDialog_MODE_BRIGHTNESS MODE_RED = _gui.GuiColorDialog_MODE_RED MODE_GREEN = _gui.GuiColorDialog_MODE_GREEN MODE_BLUE = _gui.GuiColorDialog_MODE_BLUE MODE_COUNT = _gui.GuiColorDialog_MODE_COUNT if _newclass: get_mode_name = staticmethod(_gui.GuiColorDialog_get_mode_name) else: get_mode_name = _gui.GuiColorDialog_get_mode_name FORMULA_A = _gui.GuiColorDialog_FORMULA_A FORMULA_B = _gui.GuiColorDialog_FORMULA_B FORMULA_A_ADD_B = _gui.GuiColorDialog_FORMULA_A_ADD_B FORMULA_A_SUB_B = _gui.GuiColorDialog_FORMULA_A_SUB_B FORMULA_B_SUB_A = _gui.GuiColorDialog_FORMULA_B_SUB_A FORMULA_A_MUL_B = _gui.GuiColorDialog_FORMULA_A_MUL_B FORMULA_A_DIV_B = _gui.GuiColorDialog_FORMULA_A_DIV_B FORMULA_B_DIV_A = _gui.GuiColorDialog_FORMULA_B_DIV_A FORMULA_MEAN_A_B = _gui.GuiColorDialog_FORMULA_MEAN_A_B FORMULA_INV_A = _gui.GuiColorDialog_FORMULA_INV_A FORMULA_COUNT = _gui.GuiColorDialog_FORMULA_COUNT if _newclass: get_formula_name = staticmethod(_gui.GuiColorDialog_get_formula_name) else: get_formula_name = _gui.GuiColorDialog_get_formula_name def __init__(self, *args): this = _gui.new_GuiColorDialog(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def get_value(self): return _gui.GuiColorDialog_get_value(self) def show(self, *args): return _gui.GuiColorDialog_show(self, *args) def set_dialog_title(self, title): return _gui.GuiColorDialog_set_dialog_title(self, title) def draw(self, dc): return _gui.GuiColorDialog_draw(self, dc) def set_rgb_color(self, r, g, b): return _gui.GuiColorDialog_set_rgb_color(self, r, g, b) def set_current_rgb_color(self, r, g, b, a): return _gui.GuiColorDialog_set_current_rgb_color(self, r, g, b, a) def set_current_rgb_color_dragging(self, r, g, b, a): return _gui.GuiColorDialog_set_current_rgb_color_dragging(self, r, g, b, a) def set_hsv_color(self, h, s, v): return _gui.GuiColorDialog_set_hsv_color(self, h, s, v) def get_rgb_color(self): return _gui.GuiColorDialog_get_rgb_color(self) def get_hsv_color(self): return _gui.GuiColorDialog_get_hsv_color(self) def set_a_color(self, alpha): return _gui.GuiColorDialog_set_a_color(self, alpha) def get_a_color(self): return _gui.GuiColorDialog_get_a_color(self) def get_current_rgb_color(self): return _gui.GuiColorDialog_get_current_rgb_color(self) def get_current_hsv_color(self): return _gui.GuiColorDialog_get_current_hsv_color(self) def get_current_a_color(self): return _gui.GuiColorDialog_get_current_a_color(self) def get_rgba_color(self): return _gui.GuiColorDialog_get_rgba_color(self) def get_current_rgba_color(self): return _gui.GuiColorDialog_get_current_rgba_color(self) def update_color_format(self): return _gui.GuiColorDialog_update_color_format(self) def get_mode(self): return _gui.GuiColorDialog_get_mode(self) def get_formula(self): return _gui.GuiColorDialog_get_formula(self) def revert_to_previous_color(self): return _gui.GuiColorDialog_revert_to_previous_color(self) def get_custom_colors(self): return _gui.GuiColorDialog_get_custom_colors(self) def set_custom_color(self, index, color): return _gui.GuiColorDialog_set_custom_color(self, index, color) def get_color_space(self): return _gui.GuiColorDialog_get_color_space(self) def set_listener(self, l): return _gui.GuiColorDialog_set_listener(self, l) def get_listener(self): return _gui.GuiColorDialog_get_listener(self) if _newclass: class_info = staticmethod(_gui.GuiColorDialog_class_info) else: class_info = _gui.GuiColorDialog_class_info if _newclass:
bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'DocumentList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentStatus(): """ Document information, including translation status. :attr str document_id: System generated ID identifying a document being translated using one specific translation model. :attr str filename: filename from the submission (if it was missing in the multipart-form, 'noname.<ext matching content type>' is used. :attr str status: The status of the translation job associated with a submitted document. :attr str model_id: A globally unique string that identifies the underlying model that is used for translation. :attr str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be absent or an empty string. :attr str source: Translation source language code. :attr float detected_language_confidence: (optional) A score between 0 and 1 indicating the confidence of source language detection. A higher value indicates greater confidence. This is returned only when the service automatically detects the source language. :attr str target: Translation target language code. :attr datetime created: The time when the document was submitted. :attr datetime completed: (optional) The time when the translation completed. :attr int word_count: (optional) An estimate of the number of words in the source document. Returned only if `status` is `available`. :attr int character_count: (optional) The number of characters in the source document, present only if status=available. """ def __init__(self, document_id: str, filename: str, status: str, model_id: str, source: str, target: str, created: datetime, *, base_model_id: str = None, detected_language_confidence: float = None, completed: datetime = None, word_count: int = None, character_count: int = None) -> None: """ Initialize a DocumentStatus object. :param str document_id: System generated ID identifying a document being translated using one specific translation model. :param str filename: filename from the submission (if it was missing in the multipart-form, 'noname.<ext matching content type>' is used. :param str status: The status of the translation job associated with a submitted document. :param str model_id: A globally unique string that identifies the underlying model that is used for translation. :param str source: Translation source language code. :param str target: Translation target language code. :param datetime created: The time when the document was submitted. :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be absent or an empty string. :param float detected_language_confidence: (optional) A score between 0 and 1 indicating the confidence of source language detection. A higher value indicates greater confidence. This is returned only when the service automatically detects the source language. :param datetime completed: (optional) The time when the translation completed. :param int word_count: (optional) An estimate of the number of words in the source document. Returned only if `status` is `available`. :param int character_count: (optional) The number of characters in the source document, present only if status=available. """ self.document_id = document_id self.filename = filename self.status = status self.model_id = model_id self.base_model_id = base_model_id self.source = source self.detected_language_confidence = detected_language_confidence self.target = target self.created = created self.completed = completed self.word_count = word_count self.character_count = character_count @classmethod def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: raise ValueError( 'Required property \'document_id\' not present in DocumentStatus JSON' ) if 'filename' in _dict: args['filename'] = _dict.get('filename') else: raise ValueError( 'Required property \'filename\' not present in DocumentStatus JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in DocumentStatus JSON' ) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') else: raise ValueError( 'Required property \'model_id\' not present in DocumentStatus JSON' ) if 'base_model_id' in _dict: args['base_model_id'] = _dict.get('base_model_id') if 'source' in _dict: args['source'] = _dict.get('source') else: raise ValueError( 'Required property \'source\' not present in DocumentStatus JSON' ) if 'detected_language_confidence' in _dict: args['detected_language_confidence'] = _dict.get( 'detected_language_confidence') if 'target' in _dict: args['target'] = _dict.get('target') else: raise ValueError( 'Required property \'target\' not present in DocumentStatus JSON' ) if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) else: raise ValueError( 'Required property \'created\' not present in DocumentStatus JSON' ) if 'completed' in _dict: args['completed'] = string_to_datetime(_dict.get('completed')) if 'word_count' in _dict: args['word_count'] = _dict.get('word_count') if 'character_count' in _dict: args['character_count'] = _dict.get('character_count') return cls(**args) @classmethod def _from_dict(cls, _dict): """Initialize a DocumentStatus object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'base_model_id') and self.base_model_id is not None: _dict['base_model_id'] = self.base_model_id if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'detected_language_confidence' ) and self.detected_language_confidence is not None: _dict[ 'detected_language_confidence'] = self.detected_language_confidence if hasattr(self, 'target') and self.target is not None: _dict['target'] = self.target if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'completed') and self.completed is not None: _dict['completed'] = datetime_to_string(self.completed) if hasattr(self, 'word_count') and self.word_count is not None: _dict['word_count'] = self.word_count if hasattr(self, 'character_count') and self.character_count is not None: _dict['character_count'] = self.character_count return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this DocumentStatus object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class StatusEnum(str, Enum): """ The status of the translation job associated with a submitted document. """ PROCESSING = 'processing' AVAILABLE = 'available' FAILED = 'failed' class IdentifiableLanguage(): """ IdentifiableLanguage. :attr str language: The language code for an identifiable language. :attr str name: The name of the identifiable language. """ def __init__(self, language: str, name: str) -> None: """ Initialize a IdentifiableLanguage object. :param str language: The language code for an identifiable language. :param str name: The name of the identifiable language. """ self.language = language self.name = name @classmethod def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in IdentifiableLanguage JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in IdentifiableLanguage JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): """Initialize a IdentifiableLanguage object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this IdentifiableLanguage object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IdentifiableLanguage') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'IdentifiableLanguage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IdentifiableLanguages(): """ IdentifiableLanguages. :attr List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ def __init__(self, languages: List['IdentifiableLanguage']) -> None: """ Initialize a IdentifiableLanguages object. :param List[IdentifiableLanguage] languages: A list of all languages that the
import json import random import warnings from typing import Any, Callable, Dict, List, Union, Type, Optional, NoReturn from pydantic import PrivateAttr from vkwave.bots import BotEvent, BotType, EventTypeFilter, UserEvent from vkwave.bots.core import BaseFilter from vkwave.bots.core.dispatching.filters.builtin import get_payload, get_text from vkwave.bots.core.dispatching.handler.callback import BaseCallback from vkwave.bots.core.dispatching.handler.cast import caster as callback_caster from vkwave.bots.core.types.json_types import JSONEncoder from vkwave.types.bot_events import BotEventType from vkwave.types.objects import ( BaseBoolInt, MessagesMessageAttachment, MessagesMessageAttachmentType, UsersUser, ) from vkwave.types.responses import BaseOkResponse, MessagesEditResponse, MessagesSendResponse from vkwave.types.user_events import EventId try: import aiofile except ImportError: aiofile = None class SimpleUserEvent(UserEvent): def __init__(self, event: UserEvent): super().__init__(event.object, event.api_ctx) self.user_data = event.user_data def __setitem__(self, key: Any, item: Any) -> None: self.user_data[key] = item def __getitem__(self, key: Any) -> Any: return self.user_data[key] @property def text(self) -> str: return get_text(self) @property def peer_id(self) -> int: return self.object.object.peer_id @property def from_id(self) -> int: return self.object.object.message_data.from_id @property def user_id(self) -> int: return self.from_id if self.peer_id > 2e9 else self.peer_id async def get_user( self, raw_mode: bool = False, **kwargs ) -> Union["UsersUser", dict]: # getting information about the sender raw_user = ( await self.api_ctx.api_request("users.get", {"user_ids": self.user_id, **kwargs}) )["response"][0] return raw_user if raw_mode else UsersUser(**raw_user) async def answer( self, message: Optional[str] = None, domain: Optional[str] = None, lat: Optional[int] = None, long: Optional[int] = None, attachment: Optional[str] = None, reply_to: Optional[int] = None, forward_messages: Optional[List[int]] = None, forward: Optional[str] = None, sticker_id: Optional[int] = None, group_id: Optional[int] = None, keyboard: Optional[str] = None, template: Optional[str] = None, payload: Optional[str] = None, content_source: Optional[str] = None, dont_parse_links: Optional[bool] = None, disable_mentions: Optional[bool] = None, intent: Optional[str] = None, subscribe_id: Optional[int] = None, expire_ttl: Optional[int] = None, silent: Optional[bool] = None, ) -> MessagesSendResponse: return await self.api_ctx.messages.send( message=message, forward=forward, template=template, content_source=content_source, intent=intent, subscribe_id=subscribe_id, expire_ttl=expire_ttl, silent=silent, domain=domain, lat=lat, long=long, attachment=attachment, reply_to=reply_to, forward_messages=forward_messages, sticker_id=sticker_id, group_id=group_id, keyboard=keyboard, payload=payload, dont_parse_links=dont_parse_links, disable_mentions=disable_mentions, peer_id=self.object.object.peer_id, random_id=random.randint(-2147483648, 2147483647), ) async def long_answer( self, message: str, domain: Optional[str] = None, lat: Optional[int] = None, long: Optional[int] = None, attachment: Optional[str] = None, reply_to: Optional[int] = None, forward_messages: Optional[List[int]] = None, forward: Optional[str] = None, sticker_id: Optional[int] = None, group_id: Optional[int] = None, keyboard: Optional[str] = None, template: Optional[str] = None, payload: Optional[str] = None, content_source: Optional[str] = None, dont_parse_links: Optional[bool] = None, disable_mentions: Optional[bool] = None, intent: Optional[str] = None, subscribe_id: Optional[int] = None, expire_ttl: Optional[int] = None, silent: Optional[bool] = None, ) -> List[MessagesSendResponse]: """ Shortcut for sending message > 4096 lenght :return: Message IDs """ message_ids: List[MessagesSendResponse] = [] for x in range(0, len(message), 4096): message_id = await self.answer( message=message[x:x+4096], forward=forward, template=template, content_source=content_source, intent=intent, subscribe_id=subscribe_id, expire_ttl=expire_ttl, silent=silent, domain=domain, lat=lat, long=long, attachment=attachment, reply_to=reply_to, forward_messages=forward_messages, sticker_id=sticker_id, group_id=group_id, keyboard=keyboard, payload=payload, dont_parse_links=dont_parse_links, disable_mentions=disable_mentions, ) message_ids.append(message_id) return message_ids async def reply( self, message: Optional[str] = None, domain: Optional[str] = None, lat: Optional[int] = None, long: Optional[int] = None, attachment: Optional[str] = None, forward_messages: Optional[List[int]] = None, forward: Optional[str] = None, sticker_id: Optional[int] = None, group_id: Optional[int] = None, keyboard: Optional[str] = None, template: Optional[str] = None, payload: Optional[str] = None, content_source: Optional[str] = None, dont_parse_links: Optional[bool] = None, disable_mentions: Optional[bool] = None, intent: Optional[str] = None, subscribe_id: Optional[int] = None, expire_ttl: Optional[int] = None, silent: Optional[bool] = None, ) -> MessagesSendResponse: return await self.api_ctx.messages.send( message=message, forward=forward, template=template, content_source=content_source, intent=intent, subscribe_id=subscribe_id, expire_ttl=expire_ttl, silent=silent, domain=domain, lat=lat, long=long, attachment=attachment, reply_to=self.object.object.message_id, forward_messages=forward_messages, sticker_id=sticker_id, group_id=group_id, keyboard=keyboard, payload=payload, dont_parse_links=dont_parse_links, disable_mentions=disable_mentions, peer_id=self.object.object.peer_id, random_id=random.randint(-2147483648, 2147483647), ) async def edit( self, message: Optional[str] = None, return_raw_response: bool = False, lat: Optional[int] = None, long: Optional[int] = None, attachment: Optional[str] = None, keep_forward_messages: Optional[BaseBoolInt] = None, keep_snippets: Optional[BaseBoolInt] = None, group_id: Optional[int] = None, dont_parse_links: Optional[bool] = None, message_id: Optional[int] = None, conversation_message_id: Optional[int] = None, template: Optional[str] = None, keyboard: Optional[str] = None, ) -> MessagesEditResponse: return await self.api_ctx.messages.edit( message=message, peer_id=self.object.object.peer_id, return_raw_response=return_raw_response, lat=lat, long=long, attachment=attachment, keep_forward_messages=keep_forward_messages, keep_snippets=keep_snippets, group_id=group_id, dont_parse_links=dont_parse_links, message_id=message_id or self.object.object.message_id, conversation_message_id=conversation_message_id, template=template, keyboard=keyboard, ) async def set_activity( self, type: Optional[str] = None, user_id: Optional[int] = None, group_id: Optional[int] = None, ) -> MessagesSendResponse: """ type: typing — пользователь начал набирать текст, audiomessage — пользователь записывает голосовое сообщение """ return await self.api_ctx.messages.set_activity( user_id=user_id, type=type, peer_id=self.object.object.peer_id, group_id=group_id, ) def _check_event_type(event_type: str): if event_type not in ( BotEventType.MESSAGE_NEW, BotEventType.MESSAGE_EDIT, BotEventType.MESSAGE_REPLY, BotEventType.MESSAGE_TYPING_STATE, BotEventType.MESSAGE_ALLOW, ): raise RuntimeError("You cant use event.answer() with this event") class SimpleAttachment(MessagesMessageAttachment): _event: "SimpleBotEvent" = PrivateAttr() _data: Optional[bytes] = PrivateAttr() _allowed_types: List[MessagesMessageAttachmentType] = PrivateAttr() _url_types: Dict[MessagesMessageAttachmentType, Callable] = PrivateAttr() def __init__(self, attachment: MessagesMessageAttachment, event: "SimpleBotEvent"): super().__init__(**attachment.dict()) self._event = event self._data = None self._allowed_types = [ MessagesMessageAttachmentType.AUDIO_MESSAGE, MessagesMessageAttachmentType.DOC, MessagesMessageAttachmentType.AUDIO, MessagesMessageAttachmentType.PHOTO, MessagesMessageAttachmentType.GRAFFITI, ] self._url_types = { MessagesMessageAttachmentType.PHOTO: lambda _attachment: _attachment.photo.sizes[ -1 ].url, MessagesMessageAttachmentType.AUDIO_MESSAGE: lambda _attachment: _attachment.audio_message.link_ogg, MessagesMessageAttachmentType.DOC: lambda _attachment: _attachment.doc.url, MessagesMessageAttachmentType.AUDIO: lambda _attachment: _attachment.audio.url, MessagesMessageAttachmentType.GRAFFITI: lambda _attachment: _attachment.graffiti.url, } @property def url(self) -> str: return self._url_types[self.type](self) async def download(self) -> Union[NoReturn, bytes]: if self._data is not None: return self._data if self.type not in self._allowed_types: raise RuntimeError("cannot download this attachment type") url = self.url client, token = await self._event.api_ctx.api_options.get_client_and_token() data = await client.http_client.request_data(method="GET", url=url) self._data = data return data async def save(self, path: str): attach_data = self._data if attach_data is None: attach_data = await self.download() if aiofile is None: warnings.warn("aiofile is not installed, saving synchronously") with open(path, "wb") as f: f.write(attach_data) return async with aiofile.async_open(path, "wb") as afp: await afp.write(attach_data) class Attachments(list): def __init__(self, event: "SimpleBotEvent"): super().__init__( [ SimpleAttachment(attachment, event=event) for attachment in event.object.object.message.attachments ] ) class SimpleBotEvent(BotEvent): """Базовый класс события.""" def __init__(self, event: BotEvent): super().__init__(event.object, event.api_ctx) self.user_data = event.user_data self._attachments: Optional[Attachments] = None self._payload: Optional[dict] = None def __setitem__(self, key: Any, item: Any) -> None: self.user_data[key] = item def __getitem__(self, key: Any) -> Any: return self.user_data[key] @property def text(self) -> str: """Получает текст сообщения Returns: str: Текст """ return get_text(self) @property def peer_id(self) -> int: """Получает идентификатор чата Returns: int: идентификатор чата """ if self.object.type == BotEventType.MESSAGE_EVENT.value: return self.object.object.peer_id return self.object.object.message.peer_id @property def from_id(self) -> int: """Получает идентификатор отправителя Returns: int: идентификатор отправителя """ if self.object.type == BotEventType.MESSAGE_EVENT.value: return self.object.object.user_id return self.object.object.message.from_id @property def payload(self) -> Optional[dict]: """Получает payload события Returns: int: payload события """ current_payload = get_payload(self) if current_payload is None: return current_payload if self._payload is None: self._payload = ( json.loads(current_payload) if not isinstance(current_payload, dict) else current_payload ) return self._payload @property def attachments(self) -> Optional[List[SimpleAttachment]]: """Получает список вложений Returns: Optional[List[SimpleAttachment]]: список вложений """ if self.object.object.message.attachments is None: return None if self._attachments is None: self._attachments = Attachments(event=self) return self._attachments @property def user_id(self) -> int: """Шорткат для выбора from_id или peer_id Returns: int: идентификатор пользователя """ return self.from_id if self.peer_id > 2e9 else self.peer_id async def get_user(self, raw_mode: bool = False, **kwargs) -> Union["UsersUser", dict]: """Получение объекта пользователя Returns: Union["UsersUser", dict]: Объект пользователя """ raw_user = ( await self.api_ctx.api_request("users.get", {"user_ids": self.user_id, **kwargs}) )["response"][0] return raw_user if raw_mode else UsersUser(**raw_user) async def edit( self, message: Optional[str] = None, lat: Optional[int] = None, long: Optional[int] = None, attachment: Optional[str] = None, keep_forward_messages: Optional[BaseBoolInt] = None, keep_snippets: Optional[BaseBoolInt] = None, group_id: Optional[int] = None, dont_parse_links: Optional[bool] = None, disable_mentions: Optional[bool] = None, message_id: Optional[int] = None, conversation_message_id: Optional[int] = None, template: Optional[str] = None, keyboard: Optional[str] = None, ) -> MessagesEditResponse: """Шорткат для редактирования своего сообщения. Args: message (Optional[str]): Текст. lat (Optional[int]): Широта. long (Optional[int]): Долгота. attachment (Optional[str]): Вложения (строка с идентификаторами, разделёнными запятой). keep_forward_messages (Optional[BaseBoolInt]): — сохранить прикрепленные пересланные сообщения. keep_snippets (Optional[BaseBoolInt]): 1 — сохранить прикрепленные внешние ссылки (сниппеты). group_id (Optional[int]): Идентификатор группы. dont_parse_links (Optional[bool]): 1 — не создавать сниппет ссылки из сообщения. disable_mentions (Optional[bool]): 1 — отключить уведомление об упоминании в сообщении. message_id (Optional[int]): Идентификатор сообщения. conversation_message_id (Optional[int]): Идентификатор сообщения в беседе. template (Optional[str]): Шаблон. keyboard (Optional[str]): Клавиатура. Returns: MessagesEditResponse: Ответ сервера """ _check_event_type(self.object.type) return await self.api_ctx.messages.edit( peer_id=self.object.object.message.peer_id, message=message, lat=lat, long=long, attachment=attachment, keep_forward_messages=keep_forward_messages, keep_snippets=keep_snippets, group_id=group_id, dont_parse_links=dont_parse_links, disable_mentions=disable_mentions, message_id=message_id, conversation_message_id=conversation_message_id, template=template, keyboard=keyboard ) async def reply( self, message: Optional[str] = None, domain: Optional[str] = None, lat: Optional[int] = None, long: Optional[int] = None, attachment: Optional[str] = None, sticker_id: Optional[int] = None, group_id: Optional[int] = None, keyboard: Optional[str] = None, template: Optional[str] = None, payload: Optional[str] = None, content_source: Optional[str] = None, dont_parse_links: Optional[bool] = None, disable_mentions: Optional[bool] = None, intent: Optional[str] = None, subscribe_id: Optional[int]
<filename>numba/core/dataflow.py<gh_stars>0 import collections from pprint import pprint import sys import warnings from numba.core.errors import UnsupportedError from numba.core.ir import Loc class DataFlowAnalysis(object): """ Perform stack2reg This is necessary to resolve blocks that propagates stack value. This would allow the use of `and` and `or` and python2.6 jumps. """ def __init__(self, cfa): self.cfa = cfa self.bytecode = cfa.bytecode # { block offset -> BlockInfo } self.infos = {} self.edge_process = {} def run(self): for blk in self.cfa.iterliveblocks(): self.infos[blk.offset] = self.run_on_block(blk) def run_on_block(self, blk): incoming_blocks = [] info = BlockInfo(blk, blk.offset, incoming_blocks) edge_callbacks = [] for ib, pops in self.cfa.incoming_blocks(blk): # By nature of Python bytecode, there will be no incoming # variables from subsequent blocks. This is an easy way # of breaking the potential circularity of the problem. if ib.offset >= blk.offset: continue ib = self.infos[ib.offset] incoming_blocks.append(ib) if (ib.offset, blk.offset) in self.edge_process: edge_callbacks.append(self.edge_process[(ib.offset, blk.offset)]) # Compute stack offset at block entry # The stack effect of our predecessors should be known assert ib.stack_offset is not None, ib new_offset = ib.stack_offset + ib.stack_effect - pops if new_offset < 0: raise RuntimeError("computed negative stack offset for %s" % blk) if info.stack_offset is None: info.stack_offset = new_offset elif info.stack_offset != new_offset: warnings.warn("inconsistent stack offset for %s" % blk, RuntimeWarning) # Compute syntax blocks at block entry assert ib.syntax_blocks is not None, ib if info.syntax_blocks is None: info.syntax_blocks = ib.syntax_blocks[:] elif info.syntax_blocks != ib.syntax_blocks: warnings.warn("inconsistent entry syntax blocks for %s" % blk, RuntimeWarning) if info.stack_offset is None: # No incoming blocks => assume it's the entry block info.stack_offset = 0 info.syntax_blocks = [] info.stack_effect = 0 for callback in edge_callbacks: callback(info) for offset in blk: inst = self.bytecode[offset] self.dispatch(info, inst) return info def dump(self): for blk in self.infos.values(): blk.dump() def dispatch(self, info, inst): fname = "op_%s" % inst.opname.replace('+', '_') fn = getattr(self, fname, self.handle_unknown_opcode) fn(info, inst) def handle_unknown_opcode(self, info, inst): raise UnsupportedError( "Use of unknown opcode '{}'".format(inst.opname), loc=Loc(filename=self.bytecode.func_id.filename, line=inst.lineno) ) def dup_topx(self, info, inst, count): orig = [info.pop() for _ in range(count)] orig.reverse() # We need to actually create new temporaries if we want the # IR optimization pass to work correctly (see issue #580) duped = [info.make_temp() for _ in range(count)] info.append(inst, orig=orig, duped=duped) for val in orig: info.push(val) for val in duped: info.push(val) def add_syntax_block(self, info, block): """ Add an inner syntax block. """ block.stack_offset = info.stack_offset info.syntax_blocks.append(block) def pop_syntax_block(self, info): """ Pop the innermost syntax block and revert its stack effect. """ block = info.syntax_blocks.pop() assert info.stack_offset >= block.stack_offset while info.stack_offset + info.stack_effect > block.stack_offset: info.pop(discard=True) return block def op_NOP(self, info, inst): pass def op_DUP_TOPX(self, info, inst): count = inst.arg assert 1 <= count <= 5, "Invalid DUP_TOPX count" self.dup_topx(info, inst, count) def op_DUP_TOP(self, info, inst): self.dup_topx(info, inst, count=1) def op_DUP_TOP_TWO(self, info, inst): self.dup_topx(info, inst, count=2) def op_ROT_TWO(self, info, inst): first = info.pop() second = info.pop() info.push(first) info.push(second) def op_ROT_THREE(self, info, inst): first = info.pop() second = info.pop() third = info.pop() info.push(first) info.push(third) info.push(second) def op_ROT_FOUR(self, info, inst): first = info.pop() second = info.pop() third = info.pop() forth = info.pop() info.push(first) info.push(forth) info.push(third) info.push(second) def op_UNPACK_SEQUENCE(self, info, inst): count = inst.arg iterable = info.pop() stores = [info.make_temp() for _ in range(count)] tupleobj = info.make_temp() info.append(inst, iterable=iterable, stores=stores, tupleobj=tupleobj) for st in reversed(stores): info.push(st) def op_BUILD_TUPLE(self, info, inst): count = inst.arg items = list(reversed([info.pop() for _ in range(count)])) tup = info.make_temp() info.append(inst, items=items, res=tup) info.push(tup) def op_BUILD_LIST(self, info, inst): count = inst.arg items = list(reversed([info.pop() for _ in range(count)])) lst = info.make_temp() info.append(inst, items=items, res=lst) info.push(lst) def op_LIST_APPEND(self, info, inst): value = info.pop() index = inst.arg target = info.peek(index) appendvar = info.make_temp() res = info.make_temp() info.append(inst, target=target, value=value, appendvar=appendvar, res=res) def op_BUILD_MAP(self, info, inst): dct = info.make_temp() count = inst.arg items = [] # BUILD_MAP takes <count> pairs from the stack for i in range(count): v, k = info.pop(), info.pop() items.append((k, v)) info.append(inst, items=items[::-1], size=count, res=dct) info.push(dct) def op_BUILD_SET(self, info, inst): count = inst.arg # Note: related python bug http://bugs.python.org/issue26020 items = list(reversed([info.pop() for _ in range(count)])) res = info.make_temp() info.append(inst, items=items, res=res) info.push(res) def op_POP_TOP(self, info, inst): info.pop(discard=True) def op_STORE_ATTR(self, info, inst): target = info.pop() value = info.pop() info.append(inst, target=target, value=value) def op_DELETE_ATTR(self, info, inst): target = info.pop() info.append(inst, target=target) def op_STORE_FAST(self, info, inst): value = info.pop() info.append(inst, value=value) def op_STORE_MAP(self, info, inst): key = info.pop() value = info.pop() dct = info.tos info.append(inst, dct=dct, key=key, value=value) def op_STORE_DEREF(self, info, inst): value = info.pop() info.append(inst, value=value) def op_LOAD_FAST(self, info, inst): name = self.bytecode.co_varnames[inst.arg] res = info.make_temp(name) info.append(inst, res=res) info.push(res) def op_LOAD_CONST(self, info, inst): res = info.make_temp('const') info.append(inst, res=res) info.push(res) def op_LOAD_GLOBAL(self, info, inst): res = info.make_temp() info.append(inst, res=res) info.push(res) def op_LOAD_DEREF(self, info, inst): res = info.make_temp() info.append(inst, res=res) info.push(res) def op_LOAD_ATTR(self, info, inst): item = info.pop() res = info.make_temp() info.append(inst, item=item, res=res) info.push(res) def op_BINARY_SUBSCR(self, info, inst): index = info.pop() target = info.pop() res = info.make_temp() info.append(inst, index=index, target=target, res=res) info.push(res) def op_STORE_SUBSCR(self, info, inst): index = info.pop() target = info.pop() value = info.pop() info.append(inst, target=target, index=index, value=value) def op_DELETE_SUBSCR(self, info, inst): index = info.pop() target = info.pop() info.append(inst, target=target, index=index) def op_GET_ITER(self, info, inst): value = info.pop() res = info.make_temp() info.append(inst, value=value, res=res) info.push(res) def op_FOR_ITER(self, info, inst): iterator = info.tos pair = info.make_temp() indval = info.make_temp() pred = info.make_temp() info.append(inst, iterator=iterator, pair=pair, indval=indval, pred=pred) info.push(indval) # Setup for stack POP (twice) at loop exit (before processing instruction at jump target) def pop_info(info): info.pop() info.pop() self.edge_process[(info.block.offset, inst.get_jump_target())] = pop_info def op_CALL_FUNCTION(self, info, inst): narg = inst.arg args = list(reversed([info.pop() for _ in range(narg)])) func = info.pop() res = info.make_temp() info.append(inst, func=func, args=args, res=res) info.push(res) def op_CALL_FUNCTION_KW(self, info, inst): narg = inst.arg names = info.pop() # tuple of names args = list(reversed([info.pop() for _ in range(narg)])) func = info.pop() res = info.make_temp() info.append(inst, func=func, args=args, names=names, res=res) info.push(res) def op_CALL_FUNCTION_EX(self, info, inst): if inst.arg & 1: errmsg = 'CALL_FUNCTION_EX with **kwargs not supported' raise NotImplementedError(errmsg) vararg = info.pop() func = info.pop() res = info.make_temp() info.append(inst, func=func, vararg=vararg, res=res) info.push(res) def _build_tuple_unpack(self, info, inst): # Builds tuple from other tuples on the stack tuples = list(reversed([info.pop() for _ in range(inst.arg)])) temps = [info.make_temp() for _ in range(len(tuples) - 1)] info.append(inst, tuples=tuples, temps=temps) # The result is in the last temp var info.push(temps[-1]) def op_BUILD_TUPLE_UNPACK_WITH_CALL(self, info, inst): # just unpack the input tuple, call inst will be handled afterwards self._build_tuple_unpack(info, inst) def op_BUILD_TUPLE_UNPACK(self, info, inst): self._build_tuple_unpack(info, inst) def op_BUILD_CONST_KEY_MAP(self, info, inst): keys = info.pop() vals = list(reversed([info.pop() for _ in range(inst.arg)])) keytmps = [info.make_temp() for _ in range(inst.arg)] res = info.make_temp() info.append(inst, keys=keys, keytmps=keytmps, values=vals, res=res) info.push(res) def op_PRINT_ITEM(self, info, inst): warnings.warn("Python2 style print partially supported. Please use " "Python3 style print.", RuntimeWarning) item = info.pop() printvar = info.make_temp() res = info.make_temp() info.append(inst, item=item, printvar=printvar, res=res) def op_PRINT_NEWLINE(self, info, inst): printvar = info.make_temp() res = info.make_temp() info.append(inst, printvar=printvar, res=res) def _unaryop(self, info, inst): val = info.pop() res = info.make_temp() info.append(inst, value=val, res=res) info.push(res) op_UNARY_NEGATIVE = _unaryop op_UNARY_POSITIVE = _unaryop op_UNARY_NOT = _unaryop op_UNARY_INVERT = _unaryop def _binaryop(self, info, inst): rhs = info.pop() lhs = info.pop() res = info.make_temp() info.append(inst, lhs=lhs, rhs=rhs, res=res) info.push(res) op_COMPARE_OP = _binaryop op_IS_OP = _binaryop op_CONTAINS_OP = _binaryop op_INPLACE_ADD = _binaryop op_INPLACE_SUBTRACT = _binaryop op_INPLACE_MULTIPLY = _binaryop op_INPLACE_DIVIDE = _binaryop op_INPLACE_TRUE_DIVIDE = _binaryop op_INPLACE_FLOOR_DIVIDE = _binaryop op_INPLACE_MODULO = _binaryop op_INPLACE_POWER = _binaryop op_INPLACE_MATRIX_MULTIPLY = _binaryop op_INPLACE_LSHIFT = _binaryop op_INPLACE_RSHIFT = _binaryop op_INPLACE_AND = _binaryop op_INPLACE_OR = _binaryop op_INPLACE_XOR = _binaryop op_BINARY_ADD = _binaryop op_BINARY_SUBTRACT = _binaryop op_BINARY_MULTIPLY = _binaryop op_BINARY_DIVIDE = _binaryop op_BINARY_TRUE_DIVIDE = _binaryop op_BINARY_FLOOR_DIVIDE = _binaryop op_BINARY_MODULO = _binaryop op_BINARY_POWER = _binaryop op_BINARY_MATRIX_MULTIPLY = _binaryop op_BINARY_LSHIFT = _binaryop op_BINARY_RSHIFT = _binaryop op_BINARY_AND = _binaryop op_BINARY_OR = _binaryop op_BINARY_XOR = _binaryop def op_SLICE_0(self, info, inst): """ TOS = TOS[:] """ tos = info.pop() res = info.make_temp() slicevar = info.make_temp() indexvar = info.make_temp() nonevar = info.make_temp() info.append(inst, base=tos, res=res, slicevar=slicevar, indexvar=indexvar, nonevar=nonevar) info.push(res) def op_SLICE_1(self, info, inst): """
set this if you have two datasets of the same type that are used for different purposes. Such as having a second level1 dataset that was used for QA (but is not this same scene). :param inherit_geometry: Instead of re-calculating the valid bounds geometry based on the data, which can be very computationally expensive e.g. Landsat 7 striped data, use the valid data geometry from this source dataset. See :func:`add_source_path` if you have a filepath reference instead of a document. """ if not classifier: classifier = dataset.properties.get("odc:product_family") if not classifier: # TODO: This rule is a little obscure to force people to know. # We could somehow figure out the product family from the product? raise ValueError( "Source dataset doesn't have a 'odc:product_family' property (eg. 'level1', 'fc'), " "you must specify a classifier for the kind of source dataset." ) self._lineage[classifier].append(dataset.id) if auto_inherit_properties: self._inherit_properties_from(dataset) if inherit_geometry: self._inherited_geometry = dataset.geometry def note_source_datasets( self, classifier: str, *dataset_ids: Union[str, uuid.UUID], ): """ Expand the lineage with raw source dataset ids. Note: If you have direct access to the datasets, you probably want to use :func:`add_source_path` or :func:`add_source_dataset`, so that fields can be inherited from them automatically. :param classifier: How to classify the source dataset. By convention, this is usually the family of the source dataset (properties->odc:product_family). Such as "level1". A classifier is used to distinguish source datasets of the same product that are used differently. Such as a normal source level1 dataset (classifier: "level1"), and a second source level1 that was used only for QA (classifier: "qa"). :param dataset_ids: The UUIDs of the source datasets """ for dataset_id in dataset_ids: if not isinstance(dataset_id, uuid.UUID): try: dataset_id = uuid.UUID(dataset_id) except ValueError as v: # The default parse error doesn't tell you anything useful to track down which one broke. raise ValueError( f"Not a valid UUID for source {classifier!r} dataset: {dataset_id!r}" ) from v self._lineage[classifier].append(dataset_id) def _inherit_properties_from(self, source_dataset: DatasetDoc): for name in self.INHERITABLE_PROPERTIES: if name not in source_dataset.properties: continue new_value = source_dataset.properties[name] try: self.properties.normalise_and_set( name, new_value, # If already set, do nothing. allow_override=False, ) except KeyError as k: warnings.warn( f"Inheritable property {name!r} is different from current value {k.args}" ) def write_measurement( self, name: str, path: Location, overviews: Iterable[int] = images.DEFAULT_OVERVIEWS, overview_resampling: Resampling = Resampling.average, expand_valid_data: bool = True, file_id: str = None, ): """ Write a measurement by copying it from a file path. Assumes the file is gdal-readable. :param name: Identifier for the measurement eg ``'blue'``. :param path: :param overviews: Set of overview sizes to write :param overview_resampling: rasterio Resampling method to use :param expand_valid_data: Include this measurement in the valid-data geometry of the metadata. :param file_id: Optionally, how to identify this in the filename instead of using the name. (DEA has measurements called ``blue``, but their written filenames must be ``band04`` by convention.) """ with rasterio.open(path) as ds: self.write_measurement_rio( name, ds, overviews=overviews, expand_valid_data=expand_valid_data, overview_resampling=overview_resampling, file_id=file_id, ) def write_measurement_rio( self, name: str, ds: DatasetReader, overviews=images.DEFAULT_OVERVIEWS, overview_resampling=Resampling.average, expand_valid_data=True, file_id=None, ): """ Write a measurement by reading it from an open rasterio dataset :param ds: An open rasterio dataset See :func:`write_measurement` for other parameters. """ if len(ds.indexes) != 1: raise NotImplementedError( f"TODO: Multi-band images not currently implemented (have {len(ds.indexes)})" ) self._write_measurement( name, ds.read(1), images.GridSpec.from_rio(ds), self.names.measurement_file_path( self._work_path, name, "tif", file_id=file_id ), expand_valid_data=expand_valid_data, nodata=ds.nodata, overview_resampling=overview_resampling, overviews=overviews, ) def write_measurement_numpy( self, name: str, array: numpy.ndarray, grid_spec: GridSpec, nodata: Optional[Union[float, int]] = None, overviews=images.DEFAULT_OVERVIEWS, overview_resampling=Resampling.average, expand_valid_data=True, file_id: str = None, ): """ Write a measurement from a numpy array and grid spec. The most common case is to copy the grid spec from your input dataset, assuming you haven't reprojected. Example:: p.write_measurement_numpy( "blue", new_array, GridSpec.from_dataset_doc(source_dataset), nodata=-999, ) See :func:`write_measurement` for other parameters. :param array: :param grid_spec: :param nodata: """ self._write_measurement( name, array, grid_spec, self.names.measurement_file_path( self._work_path, name, "tif", file_id=file_id ), expand_valid_data=expand_valid_data, nodata=nodata, overview_resampling=overview_resampling, overviews=overviews, ) def write_measurements_odc_xarray( self, dataset: Dataset, nodata: Optional[Union[float, int]] = None, overviews=images.DEFAULT_OVERVIEWS, overview_resampling=Resampling.average, expand_valid_data=True, file_id=None, ): """ Write measurements from an ODC xarray.Dataset The main requirement is that the Dataset contains a CRS attribute and X/Y or lat/long dimensions and coordinates. These are used to create an ODC GeoBox. :param dataset: an xarray dataset (as returned by ``dc.load()`` and other methods) See :func:`write_measurement` for other parameters. """ grid_spec = images.GridSpec.from_odc_xarray(dataset) for name, dataarray in dataset.data_vars.items(): self._write_measurement( name, dataarray.data, grid_spec, self.names.measurement_file_path( self._work_path, name, "tif", file_id=file_id ), expand_valid_data=expand_valid_data, overview_resampling=overview_resampling, overviews=overviews, nodata=nodata, ) def _write_measurement( self, name: str, data: numpy.ndarray, grid: GridSpec, out_path: Path, expand_valid_data: bool, nodata: Optional[Union[float, int]], overview_resampling: Resampling, overviews: Tuple[int, ...], ): res = FileWrite.from_existing(grid.shape).write_from_ndarray( data, out_path, geobox=grid, nodata=nodata, overview_resampling=overview_resampling, overviews=overviews, ) # Ensure the file_format field is set to what we're writing. file_format = res.file_format.name if "odc:file_format" not in self.properties: self.properties["odc:file_format"] = file_format if file_format != self.properties["odc:file_format"]: raise RuntimeError( f"Inconsistent file formats between bands. " f"Was {self.properties['odc:file_format']!r}, now {file_format !r}" ) self._measurements.record_image( name, grid, out_path, data, nodata=nodata, expand_valid_data=expand_valid_data, ) # We checksum immediately as the file has *just* been written so it may still # be in os/filesystem cache. self._checksum.add_file(out_path) def note_measurement( self, name, path: Location, expand_valid_data=True, relative_to_dataset_location=False, ): """ Reference a measurement from its existing file path. (no data is copied, but Geo information is read from it.) :param name: :param path: :param expand_valid_data: :param relative_to_dataset_location: """ read_location = path if relative_to_dataset_location: read_location = documents.resolve_absolute_offset( self._dataset_location or (self._metadata_path and self._metadata_path.parent), path, ) with rasterio.open(read_location) as ds: ds: DatasetReader if ds.count != 1: raise NotImplementedError( "TODO: Only single-band files currently supported" ) self._measurements.record_image( name, images.GridSpec.from_rio(ds), path, ds.read(1) if expand_valid_data else None, nodata=ds.nodata, expand_valid_data=expand_valid_data, ) def extend_user_metadata(self, section_name: str, doc: Dict[str, Any]): """ Record extra metadata from the processing of the dataset. It can be any document suitable for yaml/json serialisation, and will be written into the sidecar "proc-info" metadata. This is typically used for recording processing parameters or environment information. :param section_name: Should be unique to your product, and identify the kind of document, eg 'brdf_ancillary' :param doc: Document """ if section_name in self._user_metadata: raise ValueError(f"metadata section {section_name} already exists") self._user_metadata[section_name] = deepcopy(doc) def note_software_version(self, name: str, url: str, version: str): """ Record the version of some software used to produce the dataset. :param name: a short human-readable name for the software. eg "datacube-core" :param url: A URL where the software is found, such as the git repository. :param version: the version string, eg. "1.0.0b1" """ for v in self._software_versions: # Uniquely identify software by the tuple (name, url) if v["name"] == name and v["url"] == url: existing_version = v["version"] if existing_version != version: raise ValueError( f"duplicate setting of software {url!r} with different value " f"({existing_version!r} != {version!r})" ) return self._software_versions.append(dict(name=name, url=url, version=version)) def done( self, validate_correctness: bool = True, sort_measurements: bool = True ) -> Tuple[uuid.UUID, Path]: """ Write the dataset and move it into place. It will be validated, metadata will be written, and if all is correct, it will be moved to the output location. The final move is done atomically, so the dataset will only exist in the output location if it is complete. :param validate_correctness: Run the eo3-validator on the resulting metadata. :param sort_measurements: Order measurements alphabetically. (instead of insert-order) :raises: :class:`IncompleteDatasetError` If any critical metadata is incomplete. :returns: The id and final path to the dataset metadata file. """ self.note_software_version( "eodatasets3", "https://github.com/GeoscienceAustralia/eo-datasets", eodatasets3.__version__, ) crs, grid_docs, measurement_docs = self._measurements.as_geo_docs() if measurement_docs and sort_measurements: measurement_docs = dict(sorted(measurement_docs.items())) if self._inherited_geometry: valid_data = self._inherited_geometry else: valid_data = self._measurements.consume_and_get_valid_data() # Avoid the messiness of different empty collection types. # (to have a non-null geometry we'd also need non-null grids and crses) if valid_data.is_empty: valid_data = None if self._is_writing_files(): # (the checksum isn't written yet -- it'll be the last file) self.add_accessory_file( "checksum:sha1", self.names.checksum_path(self._work_path) ) processing_metadata = self.names.metadata_path( self._work_path, suffix="proc-info.yaml" ) self._write_yaml( {**self._user_metadata, "software_versions": self._software_versions}, processing_metadata, allow_external_paths=True, ) self.add_accessory_file("metadata:processor", processing_metadata) dataset = DatasetDoc( id=self.dataset_id, label=self.label, product=ProductDoc( name=self.names.product_name, href=self.names.product_uri ), crs=self._crs_str(crs) if crs is not None
import struct import logging import io import time try: import queue except ImportError: import Queue as queue from ..network import CanError from .. import objectdictionary from .base import SdoBase from .constants import * from .exceptions import * logger = logging.getLogger(__name__) class SdoClient(SdoBase): """Handles communication with an SDO server.""" #: Max time in seconds to wait for response from server RESPONSE_TIMEOUT = 0.3 #: Max number of request retries before raising error MAX_RETRIES = 1 #: Seconds to wait before sending a request, for rate limiting PAUSE_BEFORE_SEND = 0.0 def __init__(self, rx_cobid, tx_cobid, od): """ :param int rx_cobid: COB-ID that the server receives on (usually 0x600 + node ID) :param int tx_cobid: COB-ID that the server responds with (usually 0x580 + node ID) :param canopen.ObjectDictionary od: Object Dictionary to use for communication """ SdoBase.__init__(self, rx_cobid, tx_cobid, od) self.responses = queue.Queue() def on_response(self, can_id, data, timestamp): self.responses.put(bytes(data)) def send_request(self, request): retries_left = self.MAX_RETRIES while True: try: if self.PAUSE_BEFORE_SEND: time.sleep(self.PAUSE_BEFORE_SEND) self.network.send_message(self.rx_cobid, request) except CanError as e: # Could be a buffer overflow. Wait some time before trying again retries_left -= 1 if not retries_left: raise logger.info(str(e)) time.sleep(0.1) else: break def read_response(self): try: response = self.responses.get( block=True, timeout=self.RESPONSE_TIMEOUT) except queue.Empty: raise SdoCommunicationError("No SDO response received") res_command, = struct.unpack_from("B", response) if res_command == RESPONSE_ABORTED: abort_code, = struct.unpack_from("<L", response, 4) raise SdoAbortedError(abort_code) return response def request_response(self, sdo_request): retries_left = self.MAX_RETRIES if not self.responses.empty(): # logger.warning("There were unexpected messages in the queue") self.responses = queue.Queue() while True: self.send_request(sdo_request) # Wait for node to respond try: return self.read_response() except SdoCommunicationError as e: retries_left -= 1 if not retries_left: self.abort(0x5040000) raise logger.warning(str(e)) def abort(self, abort_code=0x08000000): """Abort current transfer.""" request = bytearray(8) request[0] = REQUEST_ABORTED # TODO: Is it necessary to include index and subindex? struct.pack_into("<L", request, 4, abort_code) self.send_request(request) logger.error("Transfer aborted by client with code 0x{:08X}".format(abort_code)) def upload(self, index, subindex): """May be called to make a read operation without an Object Dictionary. :param int index: Index of object to read. :param int subindex: Sub-index of object to read. :return: A data object. :rtype: bytes :raises canopen.SdoCommunicationError: On unexpected response or timeout. :raises canopen.SdoAbortedError: When node responds with an error. """ fp = self.open(index, subindex, buffering=0) size = fp.size data = fp.read() if size is None: # Node did not specify how many bytes to use # Try to find out using Object Dictionary var = self.od.get_variable(index, subindex) if var is not None: # Found a matching variable in OD # If this is a data type (string, domain etc) the size is # unknown anyway so keep the data as is if var.data_type not in objectdictionary.DATA_TYPES: # Get the size in bytes for this variable size = len(var) // 8 # Truncate the data to specified size data = data[0:size] return data def download(self, index, subindex, data, force_segment=False): """May be called to make a write operation without an Object Dictionary. :param int index: Index of object to write. :param int subindex: Sub-index of object to write. :param bytes data: Data to be written. :param bool force_segment: Force use of segmented transfer regardless of data size. :raises canopen.SdoCommunicationError: On unexpected response or timeout. :raises canopen.SdoAbortedError: When node responds with an error. """ fp = self.open(index, subindex, "wb", buffering=7, size=len(data), force_segment=force_segment) fp.write(data) fp.close() def open(self, index, subindex=0, mode="rb", encoding="ascii", buffering=1024, size=None, block_transfer=False, force_segment=False, request_crc_support=True): """Open the data stream as a file like object. :param int index: Index of object to open. :param int subindex: Sub-index of object to open. :param str mode: ========= ========================================================== Character Meaning --------- ---------------------------------------------------------- 'r' open for reading (default) 'w' open for writing 'b' binary mode (default) 't' text mode ========= ========================================================== :param str encoding: The str name of the encoding used to decode or encode the file. This will only be used in text mode. :param int buffering: An optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. :param int size: Size of data to that will be transmitted. :param bool block_transfer: If block transfer should be used. :param bool force_segment: Force use of segmented download regardless of data size. :param bool request_crc_support: If crc calculation should be requested when using block transfer :returns: A file like object. """ buffer_size = buffering if buffering > 1 else io.DEFAULT_BUFFER_SIZE if "r" in mode: if block_transfer: raw_stream = BlockUploadStream(self, index, subindex, request_crc_support=request_crc_support) else: raw_stream = ReadableStream(self, index, subindex) if buffering: buffered_stream = io.BufferedReader(raw_stream, buffer_size=buffer_size) else: return raw_stream if "w" in mode: if block_transfer: raw_stream = BlockDownloadStream(self, index, subindex, size, request_crc_support=request_crc_support) else: raw_stream = WritableStream(self, index, subindex, size, force_segment) if buffering: buffered_stream = io.BufferedWriter(raw_stream, buffer_size=buffer_size) else: return raw_stream if "b" not in mode: # Text mode line_buffering = buffering == 1 return io.TextIOWrapper(buffered_stream, encoding, line_buffering=line_buffering) return buffered_stream class ReadableStream(io.RawIOBase): """File like object for reading from a variable.""" #: Total size of data or ``None`` if not specified size = None def __init__(self, sdo_client, index, subindex=0): """ :param canopen.sdo.SdoClient sdo_client: The SDO client to use for reading. :param int index: Object dictionary index to read from. :param int subindex: Object dictionary sub-index to read from. """ self._done = False self.sdo_client = sdo_client self._toggle = 0 self.pos = 0 logger.debug("Reading 0x%X:%d from node %d", index, subindex, sdo_client.rx_cobid - 0x600) request = bytearray(8) SDO_STRUCT.pack_into(request, 0, REQUEST_UPLOAD, index, subindex) response = sdo_client.request_response(request) res_command, res_index, res_subindex = SDO_STRUCT.unpack_from(response) res_data = response[4:8] if res_command & 0xE0 != RESPONSE_UPLOAD: raise SdoCommunicationError("Unexpected response 0x%02X" % res_command) # Check that the message is for us if res_index != index or res_subindex != subindex: raise SdoCommunicationError(( "Node returned a value for 0x{:X}:{:d} instead, " "maybe there is another SDO client communicating " "on the same SDO channel?").format(res_index, res_subindex)) self.exp_data = None if res_command & EXPEDITED: # Expedited upload if res_command & SIZE_SPECIFIED: self.size = 4 - ((res_command >> 2) & 0x3) self.exp_data = res_data[:self.size] else: self.exp_data = res_data self.pos += len(self.exp_data) elif res_command & SIZE_SPECIFIED: self.size, = struct.unpack("<L", res_data) logger.debug("Using segmented transfer of %d bytes", self.size) else: logger.debug("Using segmented transfer") def read(self, size=-1): """Read one segment which may be up to 7 bytes. :param int size: If size is -1, all data will be returned. Other values are ignored. :returns: 1 - 7 bytes of data or no bytes if EOF. :rtype: bytes """ if self._done: return b"" if self.exp_data is not None: self._done = True return self.exp_data if size is None or size < 0: return self.readall() command = REQUEST_SEGMENT_UPLOAD command |= self._toggle request = bytearray(8) request[0] = command response = self.sdo_client.request_response(request) res_command, = struct.unpack_from("B", response) if res_command & 0xE0 != RESPONSE_SEGMENT_UPLOAD: raise SdoCommunicationError("Unexpected response 0x%02X" % res_command) if res_command & TOGGLE_BIT != self._toggle: raise SdoCommunicationError("Toggle bit mismatch") length = 7 - ((res_command >> 1) & 0x7) if res_command & NO_MORE_DATA: self._done = True self._toggle ^= TOGGLE_BIT self.pos += length return response[1:length + 1] def readinto(self, b): """ Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. """ data = self.read(7) b[:len(data)] = data return len(data) def readable(self): return True def tell(self): return self.pos class WritableStream(io.RawIOBase): """File like object for writing to a variable.""" def __init__(self, sdo_client, index, subindex=0, size=None, force_segment=False): """ :param canopen.sdo.SdoClient sdo_client: The SDO client to use for communication. :param int index: Object dictionary index to read from. :param int subindex: Object dictionary sub-index to read from. :param int size: Size of data in number of bytes if known in advance. :param bool force_segment: Force use of segmented transfer regardless of size. """ self.sdo_client = sdo_client self.size = size self.pos = 0 self._toggle = 0 self._exp_header = None self._done = False if size is None or size > 4 or force_segment: # Initiate segmented download request = bytearray(8) command = REQUEST_DOWNLOAD if size is
_jump_box_host_fd.write(_jump_box_host_contents) _jump_box_host_fd.close() cld_attr_lst["vm_defaults"]["ssh_config_file"] = _jump_box_host_fn print "done\n" else : _msg = "The attribute \"CREATE_JUMPHOST\" in Global Object " _msg += " VM_DEFAULTS is set to \"True\", but the actual " _msg += " IP address of the jump_host VM could not be determined." _msg += " Please try to re-run the tool." cberr(_msg, True) exit(1) _all_global_objects = cld_attr_lst.keys() cld_attr_lst["client_should_refresh"] = str(0.0) _remove_from_global_objects = [ "name", "model", "user-defined", \ "dependencies", "cloud_filename", \ "cloud_name", "objectstore", \ "command_originated", "state", \ "tracking", "channel", "sorting", \ "ai_arrived", "ai_departed", \ "ai_failed", "ai_reservations", "walkthrough" ] for _object in _remove_from_global_objects : if _object in _all_global_objects : _all_global_objects.remove(_object) cld_attr_lst["all"] = ','.join(_all_global_objects) cld_attr_lst["all_vmcs_attached"] = "false" if "regression" in cld_attr_lst["space"] : cld_attr_lst["regression"] = str(cld_attr_lst["space"]["regression"]).strip().lower() else : cld_attr_lst["regression"] = "false" cld_attr_lst["description"] = _cld_conn.get_description() cld_attr_lst["username"] = cld_attr_lst["time"]["username"] cld_attr_lst["start_time"] = str(int(time())) cld_attr_lst["client_should_refresh"] = str(0) cld_attr_lst["time"]["hard_reset"] = uni_attr_lst["time"]["hard_reset"] if "hard_reset" in uni_attr_lst["time"] else False cld_attr_lst["space"]["tracefile"] = uni_attr_lst["space"]["tracefile"] if "tracefile" in uni_attr_lst["space"] else "none" # While setting up the Object Store, check for free ports for the # API, GUI, and Gmetad (Host OS performance data collection) # daemons, using their indicated ports as the base port cld_attr_lst["mon_defaults"]["collector_host_multicast_port"] = _proc_man.get_free_port(cld_attr_lst["mon_defaults"]["collector_host_multicast_port"], protocol = "tcp") cld_attr_lst["mon_defaults"]["collector_host_aggregator_port"] = _proc_man.get_free_port(cld_attr_lst["mon_defaults"]["collector_host_aggregator_port"], protocol = "tcp") cld_attr_lst["mon_defaults"]["collector_host_summarizer_port"] = _proc_man.get_free_port(cld_attr_lst["mon_defaults"]["collector_host_summarizer_port"], protocol = "tcp") os_func, ms_func, unused, unused = load_store_functions(cld_attr_lst) os_func(cld_attr_lst, "initialize", cloud_name = cld_attr_lst["name"]) ms_func(cld_attr_lst, "initialize") _status = 0 _expid = cld_attr_lst["time"]["experiment_id"] _cld_name = cld_attr_lst["name"] _msg = _smsg + "\nThe experiment identifier is " + _expid + "\n" cld_attr_lst["cloud_name"] = _cld_name except ImportError, msg : _status = 8 _msg = _fmsg + str(msg) except OSError, msg : _status = 8 _msg = _fmsg + str(msg) except AttributeError, msg : _status = 8 _msg = _fmsg + str(msg) except DataOpsException, obj : _status = 8 _msg = _fmsg + str(msg) # Chicken and the egg problem: # Can't catch this exception if the import fails # inside of the try/catch ... find another solution #except _cld_ops_class.CldOpsException, obj : # _status = str(obj.msg) # _msg = _fmsg + str(obj.msg) except StoreSetupException, obj : _status = str(obj.status) _msg = _fmsg + str(obj.msg) except ProcessManagement.ProcessManagementException, obj : _status = str(obj.status) _msg = _fmsg + str(obj.msg) except socket.gaierror, e : _status = 24 _msg = _fmsg + " vmc: " + cld_attr_lst["vmc_defaults"]["access"] + str(e) except Exception, e : _status = 23 _msg = _fmsg + str(e) finally : if _status : cberr(_msg) else : cbdebug(_msg) return self.package(_status, _msg, cld_attr_lst) @trace def start_vpnserver(self, cld_attr_lst) : ''' TBD ''' if cld_attr_lst["model"].lower() == "sim" : cbdebug("No need for a VPN server on simcloud.") return _type = cld_attr_lst["vpn"]["kind"] _vpn_server_config = cld_attr_lst["space"]["generated_configurations_dir"] _vpn_server_config += '/' + cld_attr_lst["cloud_name"] + "_server-cb-openvpn.conf" _vpn_server_address = cld_attr_lst["vpn"]["server_ip"] _vpn_server_port = cld_attr_lst["vpn"]["server_port"] try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" if not os.path.isfile(_vpn_server_config) : _proc_man = ProcessManagement() script = self.path + "/util/openvpn/make_keys.sh" _vpn_network = cld_attr_lst["vpn"]["network"] _vpn_netmask = cld_attr_lst["vpn"]["netmask"] _cmd = script + ' ' + _vpn_network + ' ' + _vpn_netmask + ' ' _cmd += cld_attr_lst["cloud_name"] + ' ' + _vpn_server_address + ' ' + _vpn_server_port cbinfo("Creating \"" + _type + "\" VPN server unified CB configuration: " + _cmd + ", please wait ...", True) _status, out, err =_proc_man.run_os_command(_cmd) if not _status : cbdebug("VPN configuration success: (" + _vpn_network + ' ' + _vpn_netmask + ")", True) else : raise Exception("VPN configuration failed: " + out + err) else : cbinfo("VPN configuration for this cloud already generated: " + _vpn_server_config, True) vpn_client_config = cld_attr_lst["space"]["generated_configurations_dir"] vpn_client_config += '/' + cld_attr_lst["cloud_name"] + "_client-cb-openvpn.conf" cld_attr_lst["vm_defaults"]["vpn_config_file"] = vpn_client_config # if cld_attr_lst["vm_defaults"]["use_vpn_ip"] and not cld_attr_lst["vpn"]["start_server"] : # _msg = " The attribute \"USE_VPN_IP\" in Global Object " # _msg += "[VM_DEFAULTS] is set to \"True\". Will set the" # _msg += "attribute \"START_SERVER\" in the Global Object " # _msg += "[VPN] also to \"True\"." # cbdebug(_msg, True) # cld_attr_lst["vpn"]["start_server"] = True if str(cld_attr_lst["vm_defaults"]["use_vpn_ip"]).lower() == "false" : _status = 0 _msg = "VPN is disabled for this cloud." return True if str(cld_attr_lst["vpn"]["start_server"]).lower() == "false" : _msg = "Bypassing the startup of a \"" + _type + "\" VPN server..." # Occasionally (on laptops) the VPN ip address of the orchestrator # has reset and is no longer the same as what is located in the # configuration file. In that case, update the runtime configuration # and notify the user. client_not_found = True try : tmp = Nethashget(cld_attr_lst["vpn"]["management_ip"]) tmp.nmap(int(cld_attr_lst["vpn"]["management_port"]), "TCP") tn = telnetlib.Telnet(cld_attr_lst["vpn"]["management_ip"], int(cld_attr_lst["vpn"]["management_port"]), 1) tn.write("log all\r\n") tn.write("exit\n") lines = [] while True : try : lines.append(tn.read_until("\n", 1)) except Exception, e : break tn.close lines.reverse() for line in lines : if line.count("route " + cld_attr_lst["vpn"]["network"]) : bip = line.split(" ")[10] client_not_found = False if bip != cld_attr_lst["vpn"]["server_bootstrap"] : cbwarn("VPN Bootstrap changed to: " + bip, True) cld_attr_lst["vpn"]["server_bootstrap"] = bip break except Exception, e: pass if client_not_found : cbdebug("Local VPN client not online. VMs may not be reachable.", True) _status = 0 else : _vpn_pid = False print "Checking for a running VPN daemon.....", _proc_man = ProcessManagement(username = "root") _base_cmd = "openvpn --config " + _vpn_server_config _cmd = _base_cmd + " --daemon" _vpn_pid = _proc_man.get_pid_from_cmdline(_cmd) if not _vpn_pid : _vpn_pid = _proc_man.start_daemon("sudo " + _cmd, \ protocol = "tcp", \ conditional = True, \ port = _vpn_server_port, \ search_keywords = _vpn_server_config) if len(_vpn_pid) : if _vpn_pid[0].count("pnf") : _x, _p, _username = _vpn_pid[0].split('-') _msg = "Unable to start VPN service. Port 1194" _msg += " is already taken by process" + _p + "." _status = 8181 raise ProcessManagement.ProcessManagementException(_status, _msg) else : _p = _vpn_pid[0] _msg = "VPN daemon was successfully started. " _msg += "The process id is " + str(_p) + ".\n" sys.stdout.write(_msg) else : _msg = "\nVPN failed to start. To discover why, please " _msg += "run:\n\n" + _base_cmd + "\n\n ... and report the bug." cberr(_msg, True) _status = 7161 raise ProcessManagement.ProcessManagementException(_status, _msg) else : _p = _vpn_pid _msg = "A VPN daemon of the kind \"" + _type + "\" " _msg += "on node " + _vpn_server_address + ", TCP " _msg += "port " + str(_vpn_server_port) + " seems to be " _msg += "running.\n" sys.stdout.write(_msg) _status = 0 except ProcessManagement.ProcessManagementException, obj : _status = str(obj.status) _fmsg = str(obj.msg) except Exception, e : _status = 23 _fmsg = str(e) finally : if _status : _msg = "Unable to start VPN server: " + _fmsg cberr(_msg) exit(_status) else : print '' cbdebug(_msg) return True @trace def clddetach(self, cld_attr_list, parameters, command, api = False) : ''' TBD ''' try : _status = 100 _fmsg = "An error has occurred, but no error message was captured" _update_frequency = 5 _max_tries = 10 _obj_type = command.split('-')[0].upper() _status, _fmsg = self.parse_cli(cld_attr_list, parameters, command) if not _status : _cld_attr_list = self.osci.get_object(cld_attr_list["name"], "CLOUD", False, cld_attr_list["name"], False) self.update_cloud_attribute(cld_attr_list["name"], "client_should_refresh", str(0)) _msg = "Waiting for all active AIDRS daemons to finish gracefully...." cbdebug(_msg, True) _curr_tries = 0 _aidrs_list = self.osci.get_object_list(cld_attr_list["name"], "AIDRS") while _aidrs_list : cbdebug("Still waiting.... ") _aidrs_list = self.osci.get_object_list(cld_attr_list["name"], "AIDRS") if _aidrs_list and _curr_tries < _max_tries : for _aidrs_uuid in _aidrs_list : _aidrs_attr_list = self.osci.get_object(cld_attr_list["name"], "AIDRS", \ False, \ _aidrs_uuid, \ False) _x_attr_list = {} _parameters = cld_attr_list["name"] + ' ' + _aidrs_attr_list["name"] + " true" self.objdetach(_x_attr_list, _parameters, "aidrs-detach") sleep(_update_frequency) _curr_tries += 1 else : break if _curr_tries >= _max_tries : _msg = "Some AIDRS (daemons) did not die after " _msg += str(_max_tries * _update_frequency) + " seconds." _msg += "Please kill them manually after the end of the " _msg += "cloud detachment process (a \"pkill -f aidrs-submit\"" _msg += " should suffice)." else : _msg = "All AIDRS (daemons and objects were removed)." cbdebug(_msg, True) sleep (_update_frequency) _curr_tries = 0 for _object_typ in [ "VMCRS", "FIRS",
3*SIZE/8, SIZE/2, SIZE/4), "RIGHT":(OFFSET+SIZE*j + SIZE, OFFSET + SIZE*i + 3*SIZE/8, SIZE/2, SIZE/4), "UP":(OFFSET+SIZE*j + 3*SIZE/8, OFFSET + SIZE*i - SIZE/2, SIZE/4, SIZE/2), "DOWN":(OFFSET+SIZE*j + 3*SIZE/8, OFFSET + SIZE*i + SIZE, SIZE/4, SIZE/2), "START":(OFFSET+SIZE*j + 3*SIZE/8, OFFSET + SIZE*i + SIZE, SIZE/4, SIZE/2)}[TOTAL_SEQ[frame]] # current move tgt = {"LEFT":(OFFSET+SIZE*j-int(SIZE/2), OFFSET + SIZE*i + int(SIZE/2)), "RIGHT":(OFFSET+SIZE*j + SIZE + int(SIZE/2), OFFSET + SIZE*i + int(SIZE/2)), "UP":(OFFSET+SIZE*j + int(SIZE/2), OFFSET + SIZE*i - int(SIZE/2)), "DOWN":(OFFSET+SIZE*j + int(SIZE/2), OFFSET + SIZE*i + SIZE + int(SIZE/2))}[TOTAL_SEQ[frame+1]] pygame.draw.circle(screen, (150, 50, 0, 100), [int(x) for x in tgt], int(SIZE/2)) # looking square pygame.draw.rect(screen, (150, 0, 0, 100), e) # current move pygame.draw.rect(screen, (0, 0, 0, 100), d) # next move eyes 1 pygame.draw.rect(screen, (0, 0, 0, 100), f) # next move eyes 2 elif SNAKE_STATES[frame][i][j] == 'T': pygame.draw.rect(screen, (0, 100, 0), (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE)) elif SNAKE_STATES[frame][i][j] == 1: pygame.draw.rect(screen, (0, 150, 0), (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE)) pygame.draw.rect(screen, (120, 120, 120), (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE), 1) # outline font = pygame.font.Font('freesansbold.ttf', 22) text = font.render("CURRENT SCORE: {}".format(SCORES[frame]), True, (200, 200, 200)) try: text2 = font.render("MOOGLES EATEN: {}".format(MOOGLES[frame]), True, (200, 200, 200)) text4 = font.render("TIME: {}/{}".format(CURR_FRAME[frame], TIME_OUT[frame]), True, (200, 200, 200)) except Exception: pass text3 = font.render("NEXT MOVE: {}".format(TOTAL_SEQ[frame+1]), True, (200, 200, 200)) r1 = text.get_rect() try: r2 = text2.get_rect() r4 = text4.get_rect() except Exception: pass r3 = text3.get_rect() r1.topleft = (OFFSET, 500) try: r2.topleft = (OFFSET, 525) r4.topleft = (OFFSET, 575) except Exception: pass r3.topleft = (OFFSET, 550) screen.blit(text, r1) try: screen.blit(text2, r2) screen.blit(text4, r4) except Exception: pass screen.blit(text3, r3) # Flip the display pygame.display.flip() sleep(delay/1000) input() def kill_screen(file_name): ''' Where were u when snek was kil I was at computer, coding algorithm When program show "Gam ovr" "No" --> Shows final frame before death ''' pygame.init() # Set up the drawing window screen = pygame.display.set_mode([100 + 40*BOARD_SIZE, 200 + 40*BOARD_SIZE]) pygame.display.set_caption('KM Snek') with open(file_name, 'rb') as f: dat = pickle.load(f) seq = dat["Sequence"] if "Sequence" in dat else None snakes = dat["Snakes"] if "Snakes" in dat else None tgts = dat["Targets"] if "Targets" in dat else None scores = dat["Scores"] if "Scores" in dat else None moogles = dat["Moogles"] if "Moogles" in dat else None frames = dat["Frames"] if "Frames" in dat else None timeout = dat["Timeout"] if "Timeout" in dat else None print("Replaying Game of Size {}".format(len(snakes))) draw_board(snakes[-1], tgts[-1], len(snakes)-1, seq[-2], seq[-1], scores[-1], moogles[-1], screen, frames[-1], timeout[-1]) input() def getDirection(axis, direction): if (axis == -1): if (direction == -1): return "LEFT" elif (direction == 1): return "RIGHT" elif(axis == 1): if (direction == -1): return "UP" elif (direction == 1): return "DOWN" # converts variables to a word direction def main(dataCollectMode=False): SNAKE_STATES = [] # full board display TGT_STATES = [] # coordinates of food if applicable TOTAL_SEQ = ['START'] # sequence of total moves, set with START as the starting position SCORES = [] MOOGLES = [] CURR_FRAME = [] TIME_OUT = [] frame = 0 # ========== EXISTING CODE ====== #ptr to board board = init_board() #ptr to axes and direction axis = c_int(0) p_axis = cast(addressof(axis),POINTER(c_int)) direction = c_int(0) p_direction = cast(addressof(direction),POINTER(c_int)) play_on = 1 # ========== /EXISTING CODE ====== seedRand(random.randint(0, 1000000)) mooglex, moogley = -1, -1 # position of target --> SET to -1, -1 as default when there is NO TARGET def target_exists(): ''' checks if target exists ''' return mooglex != -1 and moogley != -1 def locate_target(): ''' Locates target ''' for j in range(BOARD_SIZE): for i in range(BOARD_SIZE): if board[0].cell_value[j][i] != 0: # REMEMBER TO DEREFERENCE THE POINTER return (i, j) return (-1, -1) ''' Game control ''' if not dataCollectMode: pygame.init() # Set up the drawing window screen = pygame.display.set_mode([500, 600]) pygame.display.set_caption('KM Snek') while (play_on): #clear() x_coord, y_coord = board[0].snek[0].head[0].coord[x], board[0].snek[0].head[0].coord[y] # get x, y tail_x, tail_y = board[0].snek[0].tail[0].coord[x], board[0].snek[0].tail[0].coord[y] M = [[0] * BOARD_SIZE for i in range(BOARD_SIZE)] for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): if board[0].occupancy[i][j] == 1: M[i][j] = 1 if j == tail_x and i == tail_y: M[i][j] = 'T' # overwrite with tail if j == x_coord and i == y_coord: M[i][j] = 'H' # overwrite with head SNAKE_STATES.append(M) # collects snake occupancy info mooglex, moogley = locate_target() if target_exists(): TGT_STATES.append((mooglex, moogley)) else: TGT_STATES.append(None) SCORES.append(get_score()) MOOGLES.append(get_moogles_eaten()) CURR_FRAME.append(get_curr_frame()) TIME_OUT.append(get_time_out()) length = board[0].snek[0].length dead_stack = get_dead_stack() curr = board[0].snek[0].head snek = {} # squares occupied by snake, along with colour for i in range(length): c = 75 if i == length-1 else ((200-int(100*i/length)) if (200-int(100*i/length)) > 100 else 100) snek[(curr[0].coord[x], curr[0].coord[y])] = (c*dead_stack, c*(1-dead_stack), c/4*(1-dead_stack)) curr = curr[0].next play_on = gameStep(p_axis, p_direction, board) # execute next move # also determine current input move TOTAL_SEQ.append(getDirection(axis.value, direction.value)) # append to current total moves if not dataCollectMode: # print("\n\nNEXT FRAME:") # show_board(board) # Fill the background with white screen.fill((20, 20, 20)) pygame.display.set_caption('KM Snake - Frame Number {}'.format(frame+1)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): if (j, i) in snek: pygame.draw.rect(screen, snek[(j, i)], (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE)) if TGT_STATES and TGT_STATES[-1] and (j, i) == TGT_STATES[-1] and SNAKE_STATES[-1][i][j]: pygame.draw.rect(screen, (0, 150, 255), (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE)) elif TGT_STATES and TGT_STATES[-1] and (j, i) == TGT_STATES[-1]: # food pygame.draw.rect(screen, (0, 0, 255), (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE)) elif SNAKE_STATES[-1][i][j] == 'H': d = {"LEFT":(OFFSET+SIZE*j, OFFSET + SIZE*i + SIZE/8, SIZE/4, SIZE/4), "RIGHT":(OFFSET+SIZE*j + 3*SIZE/4, OFFSET + SIZE*i + 5*SIZE/8, SIZE/4, SIZE/4), "UP":(OFFSET+SIZE*j + 5*SIZE/8, OFFSET + SIZE*i , SIZE/4, SIZE/4), "DOWN":(OFFSET+SIZE*j + SIZE/8, OFFSET + SIZE*i + 3*SIZE/4, SIZE/4, SIZE/4), "START":(OFFSET+SIZE*j + SIZE/8, OFFSET + SIZE*i + 3*SIZE/4, SIZE/4, SIZE/4)}[TOTAL_SEQ[-2]] # seeker head f = {"LEFT":(OFFSET+SIZE*j, OFFSET + SIZE*i + 5*SIZE/8, SIZE/4, SIZE/4), "RIGHT":(OFFSET+SIZE*j + 3*SIZE/4, OFFSET + SIZE*i + SIZE/8, SIZE/4, SIZE/4), "UP":(OFFSET+SIZE*j + SIZE/8, OFFSET + SIZE*i , SIZE/4, SIZE/4), "DOWN":(OFFSET+SIZE*j + 5*SIZE/8, OFFSET + SIZE*i + 3*SIZE/4, SIZE/4, SIZE/4), "START":(OFFSET+SIZE*j + 5*SIZE/8, OFFSET + SIZE*i + 3*SIZE/4, SIZE/4, SIZE/4)}[TOTAL_SEQ[-2]] # seeker head e = {"LEFT":(OFFSET+SIZE*j-SIZE/2, OFFSET + SIZE*i + 3*SIZE/8, SIZE/2, SIZE/4), "RIGHT":(OFFSET+SIZE*j + SIZE, OFFSET + SIZE*i + 3*SIZE/8, SIZE/2, SIZE/4), "UP":(OFFSET+SIZE*j + 3*SIZE/8, OFFSET + SIZE*i - SIZE/2, SIZE/4, SIZE/2), "DOWN":(OFFSET+SIZE*j + 3*SIZE/8, OFFSET + SIZE*i + SIZE, SIZE/4, SIZE/2), "START":(OFFSET+SIZE*j + 3*SIZE/8, OFFSET + SIZE*i + SIZE, SIZE/4, SIZE/2)}[TOTAL_SEQ[-2]] # current move tgt = {"LEFT":(OFFSET+SIZE*j-int(SIZE/2), OFFSET + SIZE*i + int(SIZE/2)), "RIGHT":(OFFSET+SIZE*j + SIZE + int(SIZE/2), OFFSET + SIZE*i + int(SIZE/2)), "UP":(OFFSET+SIZE*j + int(SIZE/2), OFFSET + SIZE*i - int(SIZE/2)), "DOWN":(OFFSET+SIZE*j + int(SIZE/2), OFFSET + SIZE*i + SIZE + int(SIZE/2))}[TOTAL_SEQ[-1]] pygame.draw.circle(screen, (150, 50, 0, 100), [int(x) for x in tgt], int(SIZE/2)) # looking square pygame.draw.rect(screen, (150, 0, 0, 100), e) # current move pygame.draw.rect(screen, (0, 0, 0, 100), d) # next move eyes 1 pygame.draw.rect(screen, (0, 0, 0, 100), f) # next move eyes 2 pygame.draw.rect(screen, (120, 120, 120), (OFFSET + SIZE*j, OFFSET + SIZE*i, SIZE, SIZE), 1) # outline font = pygame.font.Font('freesansbold.ttf', 22) text = font.render("CURRENT SCORE: {}".format(SCORES[-1]), True, (200, 200, 200)) text2 = font.render("MOOGLES EATEN: {}".format(MOOGLES[-1]), True, (200, 200, 200)) text3 = font.render("NEXT MOVE: {}".format(TOTAL_SEQ[-1]), True, (200, 200, 200)) text4 = font.render("TIME: {}/{}".format(CURR_FRAME[-1], TIME_OUT[-1]), True, (200, 200, 200)) r1 = text.get_rect() r2 = text2.get_rect() r3 = text3.get_rect() r4 = text4.get_rect() r1.topleft = (OFFSET, 500) r2.topleft = (OFFSET, 525) r3.topleft = (OFFSET, 550) r4.topleft = (OFFSET, 575) screen.blit(text, r1) screen.blit(text2, r2) screen.blit(text3, r3) screen.blit(text4, r4) # Flip the display pygame.display.flip() frame += 1 #print("Frame {}\nScore: {}\nMoogles Eaten:{}\n".format(frame, SCORES[-1], MOOGLES[-1])) ''' if not dataCollectMode: sleep(0.5) ''' #pass by reference to clean memory score = get_score() end_game(byref(board)) return (score, {"Sequence":TOTAL_SEQ, "Targets":TGT_STATES, "Snakes":SNAKE_STATES, "Scores":SCORES, "Moogles":MOOGLES, "Frames":CURR_FRAME, "Timeout":TIME_OUT}) if __name__ == "__main__": TRIALS = 0 NAME_EXT = '' # main function --> this allows some funky scoping stuff to work random.seed() response = '' while(response.lower() not in {'collect', 'collectlog', 'replay', 'play', 'lastframe','replay200'}): response = input("Mode Selection?\n[COLLECT] - data collection mode without game logs\n[COLLECTLOG] - log moves\n[REPLAY] - load data file\n[LASTFRAME] = print last frame\n[PLAY] - play normally\n") response = response.upper() DATA_COLLECT = False LOG_GAMES = False REPLAY = False LAST_FRAME = False REPLAY200 = False COLLECT_ALL = False if response == 'COLLECT': DATA_COLLECT = True while(not response.isnumeric()): response = input("Number of Trials?\n") TRIALS = int(response) NAME_EXT = input("File Prefix Name?\n") # common file prefix elif response == 'COLLECTLOG': DATA_COLLECT = True LOG_GAMES = True while(not response.isnumeric()): response = input("Number of Trials?\n") TRIALS = int(response) NAME_EXT = input("File Prefix Name?\n") # common file prefix elif response == 'REPLAY': REPLAY = True NAME_EXT = input("File Prefix Name?\n") # common file prefix elif response == 'LASTFRAME': REPLAY = True NAME_EXT = input("File Prefix Name?\n") # common file prefix LAST_FRAME = True elif response == 'PLAY': NAME_EXT = input("File Prefix Name?\n") # common file prefix elif response == 'REPLAY200': REPLAY200 = True NAME_EXT = input("File Prefix Name?\n") # common file prefix elif response == 'COLLECTALL': COLLECTALL == 'TRUE' while(not response.isnumeric()): response = input("Number of Trials?\n") TRIALS = int(response) NAME_EXT = input("File Prefix Name?\n") # common file prefix if DATA_COLLECT: # data collection mode with open(NAME_EXT+"_output.tsv", 'a') as f: f.write("Trial Number Score Moogles Eaten Time Taken Data Location\n") for i in range(TRIALS): with open(NAME_EXT+"_output.tsv", 'a') as f: t_start = time() (score, dat) = main(dataCollectMode=True) t_end = time() print("\nTrial {}/{} Completed in {} seconds. Progress {}%".format(i+1, TRIALS, t_end-t_start, 100*(i+1)/TRIALS)) f.write(str(i) + '\t' + str(score) + '\t' + str(dat["Moogles"][-1]) + '\t' + str(t_end-t_start) + '\t' + NAME_EXT + 'data'+str(i) +'\n') if LOG_GAMES: # I'M PICKLE RICK WUBBA LUBBA DUB DUB with open('data/'+NAME_EXT +'data'+str(i)+'.dat', 'wb') as datout: pickle.dump(dat, datout) elif
# -*- coding: utf-8 -*- import os import random import string import sphinx from sphinx.errors import SphinxError from docutils import nodes from docutils.parsers.rst import directives from pkg_resources import parse_version from sphinx.roles import XRefRole from sphinxcontrib.needs.directives.need import Need, NeedDirective, \ process_need_nodes, purge_needs, add_sections, html_visit, html_depart, latex_visit, latex_depart from sphinxcontrib.needs.directives.needimport import Needimport, NeedimportDirective from sphinxcontrib.needs.directives.needtable import Needtable, NeedtableDirective, process_needtables from sphinxcontrib.needs.directives.needlist import Needlist, NeedlistDirective, process_needlist from sphinxcontrib.needs.directives.needflow import Needflow, NeedflowDirective, process_needflow from sphinxcontrib.needs.builder import NeedsBuilder from sphinxcontrib.needs.directives.needfilter import Needfilter, NeedfilterDirective, process_needfilters from sphinxcontrib.needs.environment import install_styles_static_files, install_datatables_static_files, \ install_collapse_static_files from sphinxcontrib.needs.roles.need_incoming import Need_incoming, process_need_incoming from sphinxcontrib.needs.roles.need_outgoing import Need_outgoing, process_need_outgoing from sphinxcontrib.needs.roles.need_ref import Need_ref, process_need_ref from sphinxcontrib.needs.roles.need_part import NeedPart, process_need_part from sphinxcontrib.needs.roles.need_count import NeedCount, process_need_count from sphinxcontrib.needs.utils import process_dynamic_values from sphinxcontrib.needs.functions import register_func, needs_common_functions sphinx_version = sphinx.__version__ if parse_version(sphinx_version) >= parse_version("1.6"): from sphinx.util import logging else: import logging logging.basicConfig() # Only need to do this once VERSION = '0.3.14' DEFAULT_TEMPLATE_COLLAPSE = """ .. _{{id}}: {% if hide == false -%} .. role:: needs_tag .. role:: needs_status .. role:: needs_type .. role:: needs_id .. role:: needs_title .. rst-class:: need .. rst-class:: need_{{type_name}} .. container:: need .. container:: toggle .. container:: header :needs_type:`{{type_name}}`: {% if title %}:needs_title:`{{title}}`{% endif %} :needs_id:`{{id}}` {% if status and status|upper != "NONE" and not hide_status %} | status: :needs_status:`{{status}}`{% endif %} {% if tags and not hide_tags %} | tags: :needs_tag:`{{tags|join("` :needs_tag:`")}}`{% endif %} | links incoming: :need_incoming:`{{id}}` | links outgoing: :need_outgoing:`{{id}}` {{content|indent(4) }} {% endif -%} """ DEFAULT_TEMPLATE = """ .. _{{id}}: {% if hide == false -%} .. role:: needs_tag .. role:: needs_status .. role:: needs_type .. role:: needs_id .. role:: needs_title .. rst-class:: need .. rst-class:: need_{{type_name}} .. container:: need :needs_type:`{{type_name}}`: :needs_title:`{{title}}` :needs_id:`{{id}}` {%- if status and status|upper != "NONE" and not hide_status %} | status: :needs_status:`{{status}}` {%- endif %} {%- if tags and not hide_tags %} | tags: :needs_tag:`{{tags|join("` :needs_tag:`")}}` {%- endif %} | links incoming: :need_incoming:`{{id}}` | links outgoing: :need_outgoing:`{{id}}` {{content|indent(4) }} {% endif -%} """ DEFAULT_DIAGRAM_TEMPLATE = \ """ {%- if is_need -%} <size:12>{{type_name}}</size>\\n**{{title|wordwrap(15, wrapstring='**\\\\n**')}}**\\n<size:10>{{id}}</size> {%- else -%} <size:12>{{type_name}} (part)</size>\\n**{{content|wordwrap(15, wrapstring='**\\\\n**')}}**\\n<size:10>{{id_parent}}.**{{id}}**</size> {%- endif -%} """ def setup(app): log = logging.getLogger(__name__) app.add_builder(NeedsBuilder) app.add_config_value('needs_types', [dict(directive="req", title="Requirement", prefix="R_", color="#BFD8D2", style="node"), dict(directive="spec", title="Specification", prefix="S_", color="#FEDCD2", style="node"), dict(directive="impl", title="Implementation", prefix="I_", color="#DF744A", style="node"), dict(directive="test", title="Test Case", prefix="T_", color="#DCB239", style="node"), # Kept for backwards compatibility dict(directive="need", title="Need", prefix="N_", color="#9856a5", style="node")], 'html') app.add_config_value('needs_template', DEFAULT_TEMPLATE, 'html') app.add_config_value('needs_template_collapse', DEFAULT_TEMPLATE_COLLAPSE, 'html') app.add_config_value('needs_include_needs', True, 'html') app.add_config_value('needs_need_name', "Need", 'html') app.add_config_value('needs_spec_name', "Specification", 'html') app.add_config_value('needs_id_prefix_needs', "", 'html') app.add_config_value('needs_id_prefix_specs', "", 'html') app.add_config_value('needs_id_length', 5, 'html') app.add_config_value('needs_specs_show_needlist', False, 'html') app.add_config_value('needs_id_required', False, 'html') app.add_config_value('needs_id_regex', "^[A-Z0-9_]{{{id_length},}}".format( id_length=app.config.needs_id_length), 'html') app.add_config_value('needs_show_link_type', False, 'html') app.add_config_value('needs_show_link_title', False, 'html') app.add_config_value('needs_file', "needs.json", 'html') app.add_config_value('needs_table_columns', "ID;TITLE;STATUS;TYPE;OUTGOING;TAGS", 'html') app.add_config_value('needs_table_style', "DATATABLES", 'html') app.add_config_value('needs_collapse_details', True, 'html') app.add_config_value('needs_role_need_template', u"{title} ({id})", 'html') app.add_config_value('needs_role_need_max_title_length', 30, 'html') app.add_config_value('needs_extra_options', {}, 'html') app.add_config_value('needs_title_optional', False, 'html') app.add_config_value('needs_max_title_length', -1, 'html') app.add_config_value('needs_title_from_content', False, 'html') app.add_config_value('needs_diagram_template', DEFAULT_DIAGRAM_TEMPLATE, 'html') # app.add_config_value('needs_functions', None, 'html') app.add_config_value('needs_global_options', {}, 'html') app.add_config_value('needs_hide_options', [], 'html') # If given, only the defined status are allowed. # Values needed for each status: # * name # * description # Example: [{"name": "open", "description": "open status"}, {...}, {...}] app.add_config_value('needs_statuses', False, 'html') # If given, only the defined tags are allowed. # Values needed for each tag: # * name # * description # Example: [{"name": "new", "description": "new needs"}, {...}, {...}] app.add_config_value('needs_tags', False, 'html') # Path of css file, which shall be used for need style app.add_config_value('needs_css', "modern.css", 'html') # Prefix for need_part output in tables app.add_config_value('needs_part_prefix', u'\u2192\u00a0', 'html') # List of additional links, which can be used by setting related option # Values needed for each new link: # * name (will also be the option name) # * incoming # * copy_link (copy to common links data. Default: True) # * color (used for needflow. Default: #000000) # Example: [{"name": "blocks, "incoming": "is blocked by", "copy_link": True, "color": "#ffcc00"}] app.add_config_value('needs_extra_links', [], 'html') app.add_config_value('needs_flow_show_links', False, 'html') app.add_config_value('needs_flow_link_types', ["links"], 'html') # Define nodes app.add_node(Need, html=(html_visit, html_depart), latex=(latex_visit, latex_depart)) app.add_node(Needfilter, ) app.add_node(Needimport) app.add_node(Needlist) app.add_node(Needtable) app.add_node(Needflow) app.add_node(NeedPart, html=(visitor_dummy, visitor_dummy), latex=(visitor_dummy, visitor_dummy)) ######################################################################## # DIRECTIVES ######################################################################## # Define directives # As values from conf.py are not available during setup phase, we have to import and read them by our own. # Otherwise this "app.config.needs_types" would always return the default values only. try: import imp # If sphinx gets started multiple times inside a python process, the following module gets also # loaded several times. This has a drawback, as the config from the current build gets somehow merged # with the config from the previous builds. # So if the current config does not define a parameter, which was set in build before, the "old" value is # taken. This is dangerous, because a developer may simply want to use the defaults (like the predefined types) # and therefore does not set this specific value. But instead he would get the value from a previous build. # So we generate a random module name for our configuration, so that this is loaded for the first time. # Drawback: The old modules will still exist (but are not used). # # From https://docs.python.org/2.7/library/functions.html#reload # "When a module is reloaded, its dictionary (containing the module’s global variables) is retained. # Redefinitions of names will override the old definitions, so this is generally not a problem. # If the new version of a module does not define a name that was defined by the old version, # the old definition remains" # Be sure, our current working directory is the folder, which stores the conf.py. # Inside the conf.py there may be relatives paths, which would be incorrect, if our cwd is wrong. old_cwd = os.getcwd() os.chdir(app.confdir) module_name = "needs_app_conf_" + ''.join(random.choice(string.ascii_uppercase) for _ in range(5)) config = imp.load_source(module_name, os.path.join(app.confdir, "conf.py")) os.chdir(old_cwd) # Lets switch back the cwd, otherwise other stuff may not run... types = getattr(config, "needs_types", app.config.needs_types) extra_options = getattr(config, "needs_extra_options", app.config.needs_extra_options) # Get extra links and create a dictionary of needed options. extra_links_raw = getattr(config, "needs_extra_links", app.config.needs_extra_links) extra_links = {} for extra_link in extra_links_raw: extra_links[extra_link['option']] = directives.unchanged title_optional = getattr(config, "needs_title_optional", app.config.needs_title_optional) title_from_content = getattr(config, "needs_title_from_content", app.config.needs_title_from_content) app.needs_functions = getattr(config, "needs_functions", []) except IOError: types = app.config.needs_types except Exception as e: log.error("Error during sphinxcontrib-needs setup: {0}, {1}".format( os.path.join(app.confdir, "conf.py"), e)) types = app.config.needs_types # Update NeedDirective to use customized options NeedDirective.option_spec.update(extra_options) # Update NeedDirective to use customized links NeedDirective.option_spec.update(extra_links) if title_optional or title_from_content: NeedDirective.required_arguments = 0 NeedDirective.optional_arguments = 1 for type in types: # Register requested types of needs app.add_directive(type["directive"], NeedDirective) app.add_directive("{0}_list".format(type["directive"]), NeedDirective) app.add_directive('needfilter', NeedfilterDirective) app.add_directive('needlist', NeedlistDirective) app.add_directive('needtable', NeedtableDirective) app.add_directive('needflow', NeedflowDirective) app.add_directive('needimport', NeedimportDirective) ######################################################################## # ROLES ######################################################################## # Provides :need:`ABC_123` for inline links. app.add_role('need', XRefRole(nodeclass=Need_ref, innernodeclass=nodes.emphasis, warn_dangling=True)) app.add_role('need_incoming', XRefRole(nodeclass=Need_incoming, innernodeclass=nodes.emphasis, warn_dangling=True)) app.add_role('need_outgoing', XRefRole(nodeclass=Need_outgoing, innernodeclass=nodes.emphasis, warn_dangling=True)) app.add_role('need_part', XRefRole(nodeclass=NeedPart, innernodeclass=nodes.inline, warn_dangling=True)) # Shortcut for need_inline app.add_role('np', XRefRole(nodeclass=NeedPart, innernodeclass=nodes.inline, warn_dangling=True)) app.add_role('need_count', XRefRole(nodeclass=NeedCount, innernodeclass=nodes.inline, warn_dangling=True)) ######################################################################## # EVENTS ######################################################################## # Make connections to events app.connect('env-purge-doc', purge_needs) app.connect('env-before-read-docs', prepare_env) app.connect('doctree-resolved', add_sections) app.connect('doctree-resolved', process_need_nodes) app.connect('doctree-resolved', process_dynamic_values) app.connect('doctree-resolved', process_needfilters) app.connect('doctree-resolved', process_needlist) app.connect('doctree-resolved', process_needtables) app.connect('doctree-resolved', process_needflow) app.connect('doctree-resolved', process_need_part) app.connect('doctree-resolved', process_need_ref) app.connect('doctree-resolved', process_need_incoming) app.connect('doctree-resolved', process_need_outgoing) app.connect('doctree-resolved', process_need_count) app.connect('env-updated', install_datatables_static_files) # Call this after all JS files, which perform DOM manipulation, have been called. # Otherwise newly added dom objects can not be collapsed app.connect('env-updated', install_collapse_static_files) # This should be called last, so that need-styles can override styles from used libraries app.connect('env-updated', install_styles_static_files) return {'version': VERSION} # identifies the version of our extension def visitor_dummy(*args, **kwargs): """ Dummy class for visitor methods, which does nothing. """ pass def prepare_env(app, env, docname): """ Prepares the sphinx environment to store sphinx-needs internal data. """ if not hasattr(env, 'needs_all_needs'): # Used to store all needed information about all needs in document env.needs_all_needs = {} if not hasattr(env, 'needs_all_filters'): # Used to store all needed information about all filters in document env.needs_all_filters = {} if not hasattr(env, 'needs_functions'): # Used to store all registered functions for supporting dynamic need values. env.needs_functions = {} # needs_functions = getattr(app.config, 'needs_functions', []) needs_functions = app.needs_functions if needs_functions is None: needs_functions = [] if not isinstance(needs_functions, list): raise SphinxError('Config parameter needs_functions must be a list!') # Register built-in functions for need_common_func in needs_common_functions: register_func(env, need_common_func) # Register functions configured by user for needs_func in needs_functions: register_func(env, needs_func) app.config.needs_hide_options += ['hidden'] app.config.needs_extra_options['hidden'] = directives.unchanged # The default link name. Must exist in all configurations. Therefore we set
<th>%s</th>'\ % ('protein', 'dataset', 'res type', 'resnum', 'atom', '&Delta&delta', '&Delta&delta err', 'pKa', 'pKa err', 'model') print '<tr>' for name in kys: for d in pkainfo[name]: PI = pkainfo[name][d] resnum = PI['resnum'] res = PI['res'] atom = PI['atom'] model = PI['model'] for p in PI: if not 'pK' in p: continue pka = PI[p][p] span = PI[p]['span'] if primary == True and not '1 pKa' in model: continue if pkainfo[name][d][p].has_key('pkaerror'): pkaerr = pkainfo[name][d][p]['pkaerror'] spanerr = pkainfo[name][d][p]['spanerror'] else: pkaerr = 0 spanerr=0 if not resinfo[res].has_key(atom): resinfo[res][atom]={} resinfo[res][atom]['pkas']=[] resinfo[res][atom]['pkaerrs']=[] resinfo[res][atom]['spans']=[] resinfo[res][atom]['spanerrs']=[] resinfo[res][atom]['pkas'].append(pka) resinfo[res][atom]['pkaerrs'].append(pkaerr) resinfo[res][atom]['spans'].append(span) resinfo[res][atom]['spanerrs'].append(spanerr) #print name, res, resnum, atom, span, spanerr, pka, pkaerr, model if pka != None: print '<td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%.2f</td> <td>%.2f</td> <td>%.2f</td> <td>%.2f</td> <td>%s</td>' \ % (name, d, res, resnum, atom, span, spanerr, pka, pkaerr, model) print '</tr>' print '</table>' print '<br>' #summary table for average pKas per residue print '<h2>Average pKa and &Delta&delta per atom/residue</h2><br\Delta' print '<table id="summary" width=60% align=center cellspacing="0">' print '<tr><td>Residue</td> <td>atom</td> <td>average &Delta&delta</td> <td>average &Delta&delta err</td> <td>average pKa</td> <td>av pKa error</td> <td>no. curves</td></tr>' for r in resinfo: allpkas=[] allspans=[] allpkaerrs=[] for a in resinfo[r]: numcurves = len(resinfo[r][a]['pkas']) averagepka = numpy.mean(resinfo[r][a]['pkas']) averagepkaerr = numpy.mean(resinfo[r][a]['pkaerrs']) averagespan = numpy.mean(resinfo[r][a]['spans']) averagespanerr = numpy.mean(resinfo[r][a]['spanerrs']) minpka = min(resinfo[r][a]['pkas']) maxpka = min(resinfo[r][a]['pkas']) print '<tr><td>%s</td> <td>%s</td> <td>%.2f</td> <td>%.2f</td> <td>%.1f</td> <td>%.2f</td> <td>%s</td></tr>' \ %(r, a, averagespan, averagespanerr, averagepka, averagepkaerr, numcurves) allpkas += resinfo[r][a]['pkas'] allpkaerrs += resinfo[r][a]['pkaerrs'] allspans += resinfo[r][a]['spans'] finalpkaerr = numpy.sqrt(sum(numpy.square(allpkaerrs))) print '<tr><td>%s</td> <td>%s</td> <td>%.2f</td> <td>%.2f</td> <td>%.1f</td> <td>%.1f</td> <td>%s</td></tr>' \ %(r, 'All', numpy.average(allspans), numpy.std(allspans), numpy.average(allpkas), numpy.std(allpkas), len(allpkas)) print '</table>' print '<br>' if outfile != None: sys.stdout.flush() sys.stdout = saveout fsock.close() return def combineCurves(cls, d1, d2, factor=5): """Combine 2 sets of chem shifts to get one pH titr""" ph1,ch1 = d1.getxy() ph2,ch2 = d2.getxy() def getnearest(x, v): #get index of nearest val n=100 c=0 for val in x: i = abs(val-v) if v < n: n = v i = c c=c+1 return i print ph1 print ph2 #get ref vals for both , ie. min val ref1 = min(ch1) ref2 = min(ch2) comb = [] if ph1==ph2: for v in range(len(ph1)): comb.append(sqrt(pow(ch1[v]-ref1,2)+pow((ch2[v]-ref2)/factor,2))) else: print 'not equal' #combine nearest ph vals instead for v in range(len(ph1)): #get nearest in ph2 to v1 v2 = getnearest(ph2, v) comb.append(sqrt(pow(ch1[v]-ref1,2)+pow((ch2[v2]-ref2)/factor,2))) dc = EkinDataset(xy=[ph1, comb]) return dc def makeCombined(cls, ekindata1, ekindata2, names=None): """Make combined chem shft and fit,then compare to originals""" proteins = ekindata1.keys() ekindatac = {} E1 = EkinProject(ekindata1) E2 = EkinProject(ekindata2) for prot in proteins: print if cls.protnames != None: name = cls.protnames[prot] print 'processing protein', name print '-------------------------' if names != None and name not in names: continue if not ekindata2.has_key(prot): print 'this protein is not in the 2nd ekindata' continue edata1 = ekindata1[prot]; E1 = EkinProject(data=edata1) edata2 = ekindata2[prot]; E2 = EkinProject(data=edata2) Ec = EkinProject() for d in E1.datasets: if d in cls.excluded or not d in E2.datasets: continue d1 = E1.getDataset(d) d2 = E2.getDataset(d) print name dc = cls.combineCurves(d1, d2) Ec.insertDataset(dc, d) Ec.saveProject(name[:5]+'_combined') for d in Ec.datasets: f, p = Ec.findBestModel(d, models=cls.models, strictchecking=True, alpha=0.05) Ec.saveProject(name[:5]+'_combined') ekindatac[prot] = Ec.prepare_data() return def getClosest(cls, val, pkas): #print val ,pkas c=100 ind=0 for j in pkas: d=abs(val - j) if d < c: c=d ind=pkas.index(j) return pkas[ind] def comparepKas(cls, E1, E2, d, titratable=False, errcutoff=1e2): """Compare pKas from fits in two ekin datasets returns: None if fails to find meaningful pKas from fits otherwise returns tuple of results""" reliable=True #print d try: res1 = E1.getMetaData(d)['residue'] except: #print E1.getDataset(d) return if titratable == True and not res1 in cls.titratable: return None fitdata1 = E1.getFitData(d) fitdata2 = E2.getFitData(d) if len(fitdata1)<1: return None model1 = fitdata1['model'] model2 = fitdata2['model'] #if model1 != model2: # print 'different models' #return None p1,p1val,sp1 = cls.getMainpKa(fitdata1, res=res1)#,strict=False) p2,p2val,sp2 = cls.getMainpKa(fitdata2, res=res1)#,strict=False) allpkas1,allpkvals1,allsp1 = cls.getallpKas(fitdata1,minspan=0.03) allpkas2,allpkvals2,allsp2 = cls.getallpKas(fitdata2,minspan=0.03) if p1val != None and p2val != None and len(allpkas1) > 0 and len(allpkas2) > 0: pchk = cls.getClosest(p1val, allpkvals2) try: perr1 = round(E1.getMeta(d, 'exp_errors')[p1][1],4) perr2 = round(E2.getMeta(d, 'exp_errors')[p2][1],4) except: return None #print d, p1val, p2val, perr1, perr2 #print errcutoff if perr1>errcutoff or perr2>errcutoff: return None if p2val != pchk: p2val = pchk else: if p1val != None and p2val == None: if len(allpkas2) > 0: p2val = cls.getClosest(p1val, allpkvals2) else: return None elif p2val != None and p1val == None: if len(allpkas1) > 0: p1val = cls.getClosest(p2val, allpkvals1) else: return None elif p1val==None and p2val==None: return None perr1=perr2=None reliable = False return p1val, p2val, sp1, sp2, perr1, perr2, reliable def compareAllpKas(cls, E1, E2, titratable=False, exclude=None, errcutoff=1e2): """Compare all pKas from 2 ekin projects""" relpkas1=[]; relpkas2=[] relspans1=[]; relspans2=[] otherpkas1=[]; otherpkas2=[] errs1=[] errs2=[] names=[] residues=[] for d in E1.datasets: if exclude!=None and d in exclude: continue if not d in E2.datasets: continue X = cls.comparepKas(E1, E2, d, titratable, errcutoff) if X == None: continue p1val, p2val, sp1, sp2, err1, err2, rel = X if rel == True: relpkas1.append(p1val) relpkas2.append(p2val) relspans1.append(sp1) relspans2.append(sp2) errs1.append(err1) errs2.append(err2) names.append(d) res = E1.getMetaData(d)['residue'] residues.append(res) else: otherpkas1.append(p1val) otherpkas2.append(p2val) #print names,residues #print 'reliable pkas matched:', len(relpkas1) #print 'others:', len(otherpkas1) return relpkas1, relpkas2, otherpkas1, otherpkas2, relspans1, relspans2, errs1, errs2, residues def compareNuclei(cls, DB, col1, col2, names=None, titratable=True, silent=False, path=None): """Compare corresponding datasets for proteins that have data for 2 different NMR nuclei e.g. 1H vs 15N over entire DB""" relpkas1=[] relpkas2=[] relspans1=[] relspans2=[] otherpkas1=[] otherpkas2=[] #names=[] pkasbyres1={} pkasbyres2={} for t in cls.residue_list: pkasbyres1[t]=[] pkasbyres2[t]=[] cls.getProtNames(DB) for prot in DB.getRecs(): name = cls.protnames[prot] if names != None and name not in names: continue if silent==False: print 'processing protein', name print '-------------------------' if not DB[prot].has_key(col1) or not DB[prot].has_key(col2): continue E1 = DB[prot][col1] E2 = DB[prot][col2] X = cls.compareAllpKas(E1, E2, titratable, exclude=cls.excluded) if X == None: continue rp1, rp2, op1, op2, rsp1, rsp2, errs1, errs2, resnames = X relpkas1.extend(rp1) relpkas2.extend(rp2) otherpkas1.extend(op1) otherpkas2.extend(op2) for vals in zip(resnames,rp1,rp2): r,a,b=vals #print r,a,b if r in cls.titratable: pkasbyres1[r].append(a) pkasbyres2[r].append(b) if silent==False: print 'reliable pkas matched:', len(relpkas1) print 'others:', len(otherpkas1) f=pylab.figure(figsize=(10,20)) ax1=f.add_subplot(211) ax2=f.add_subplot(212) cc = cls.doXYPlot(ax1, relpkas1, relpkas2, #names=names, title='15N vs 1H: reliable pKas', xlabel='15N (pH units)', ylabel='1H (pH units)') #print 'reliable pKas, correl coeff:', cc cc = cls.doXYPlot(ax2, otherpkas1, otherpkas2, color='r', title='15N vs 1H : other pKas', xlabel='15N (pH units)', ylabel='1H (pH units)') f.suptitle('Comparison of corresponding 1H vs 15N fitted pKas',fontsize=24) #print 'other pKas, correl coeff:', cc if path==None: path = os.getcwd() fname = 'comparenuclei.png' f.savefig(os.path.join(path,fname), dpi=100) f1=pylab.figure(figsize=(8,8)) ax=f1.add_subplot(111) i=0 leglines = [];series=[] for r in pkasbyres1.keys(): if len(pkasbyres1[r])==0: continue if i >= len(cls.shapes) or i>=len(cls.pylabcolors): i=0 cls.doXYPlot(ax, pkasbyres1[r],pkasbyres2[r], symbol=cls.shapes[i], color=cls.pylabcolors[i], markersize=40, title='1H vs 15N: reliable pKa values by residue', xlabel='15N', ylabel='1H') l = pylab.Line2D(range(10), range(10), color=cls.pylabcolors[i], alpha=0.7, marker=cls.shapes[i]) leglines.append(l) series.append(r) i+=1 leg = ax.legend(leglines, series, markerscale=2, numpoints=1,loc='lower right', prop=FontProperties(size="small")) leg.draw_frame(False) fname1 = 'comparenuclei_relbyres.png' f1.savefig(os.path.join(path,fname1), dpi=100) #pylab.show() return fname, fname1 def compareExtractedpKas(cls, DB, col, prot1, prot2): """Compare extracted pKas across similar proteins and plot correlations per res""" pkas = cls.extractpKas(DB, col) p1={};p2={};p1errs={};p2errs={} labels={} tp=['conserved','non-conserved'] for t in tp: p1[t]=[];p2[t]=[] p1errs[t]=[];p2errs[t]=[] labels[t]=[] s1=[];s2=[] pkas1 = pkas[prot1] pkas2 = pkas[prot2] for n in pkas1.keys(): if n in pkas1 and n in pkas2: res1 = pkas1[n]['res']; res2 = pkas2[n]['res'] #this part requires alignment info!! if res1 == res2:# and res1 in cls.titratable: t='conserved' else: t='non-conserved' p1[t].append(pkas1[n]['pka']); p2[t].append(pkas2[n]['pka']) p1errs[t].append(pkas1[n]['pkaerror']); p2errs[t].append(pkas2[n]['pkaerror']) #s1.append(pkas1[n]['span']); s2.append(pkas2[n]['span']); labels[t].append(n) fig1=pylab.figure() i=0; leg=[] for t in tp: print p1[t], labels[t] if len(p1[t])==0 or len(p2[t])==0: continue cls.doXYPlot(fig1, p1[t], p2[t], xerrs=p1errs[t], yerrs=p2errs[t], symbol=cls.shapes[i], color=cls.pylabcolors[i], title='compared pKas', annotate=labels[t], xlabel=prot1, ylabel=prot2) l = pylab.Line2D(range(10), range(10), color=cls.pylabcolors[i], alpha=0.8, marker=cls.shapes[i]) leg.append(l) i+=1 pylab.legend(leg,tp,numpoints=1) a=fig1.get_axes()[0] a.set_xlim(4,5.5) a.set_ylim(4,5.5) fig1.savefig('compareprotpkas.png', dpi=200) '''fig2=pylab.figure() cc = cls.doXYPlot(fig2, s1, s2, xerrs=p1errs, yerrs=p2errs, title='compared $\Delta\delta$', annotate=labels[t], xlabel=prot1, ylabel=prot2) fig2.savefig('compareprotspans.png', dpi=200)''' return def mappKas(self, DB, col, pkainfo,names=None,spansfile=None, nucleus='H',calculatespans=True): """Create mapping of pKas to nearby titratable groups, we use the dict of extracted pKas, but also requires the DB for structural info""" self.getProtNames(DB) path = os.getcwd() for prot in DB.getRecs(): name = self.protnames[prot] fname = name.replace(' ','').replace('(','').replace(')','') if names != None and name not in names: continue if not
import numpy as np import math import os from scipy.sparse import csr_matrix,csc_matrix from scipy.sparse.linalg import lsqr def read_ply_point_normal(shape_name): file = open(shape_name,'r') lines = file.readlines() start = 0 while True: line = lines[start].strip() if line == "end_header": start += 1 break line = line.split() if line[0] == "element": if line[1] == "vertex": vertex_num = int(line[2]) start += 1 if vertex_num==0: return [] vertices_normals = np.zeros([vertex_num,6], np.float32) for i in range(vertex_num): line = lines[i+start].split() vertices_normals[i,0] = float(line[0]) #X vertices_normals[i,1] = float(line[1]) #Y vertices_normals[i,2] = float(line[2]) #Z vertices_normals[i,3] = float(line[3]) #normalX vertices_normals[i,4] = float(line[4]) #normalY vertices_normals[i,5] = float(line[5]) #normalZ return vertices_normals def read_ply_triangle(shape_name): file = open(shape_name,'r') lines = file.readlines() vertices = [] triangles = [] start = 0 while True: line = lines[start].strip() if line == "end_header": start += 1 break line = line.split() if line[0] == "element": if line[1] == "vertex": vertex_num = int(line[2]) if line[1] == "face": face_num = int(line[2]) start += 1 vertices = np.zeros([vertex_num,3], np.float32) triangles = np.zeros([face_num,3], np.int32) for i in range(vertex_num): line = lines[start].split() vertices[i,0] = float(line[0]) vertices[i,1] = float(line[1]) vertices[i,2] = float(line[2]) start += 1 for i in range(face_num): line = lines[start].split() triangles[i,0] = int(line[1]) triangles[i,1] = int(line[2]) triangles[i,2] = int(line[3]) start += 1 return vertices, triangles def read_ply_edge(shape_name): file = open(shape_name,'r') lines = file.readlines() vertices = [] edges = [] start = 0 while True: line = lines[start].strip() if line == "end_header": start += 1 break line = line.split() if line[0] == "element": if line[1] == "vertex": vertex_num = int(line[2]) if line[1] == "edge": edge_num = int(line[2]) start += 1 vertices = np.zeros([vertex_num,3], np.float32) edges = np.zeros([edge_num,2], np.int32) for i in range(vertex_num): line = lines[start].split() vertices[i,0] = float(line[0]) vertices[i,1] = float(line[1]) vertices[i,2] = float(line[2]) start += 1 for i in range(edge_num): line = lines[start].split() edges[i,0] = int(line[0]) edges[i,1] = int(line[1]) start += 1 return vertices, edges def write_obj(dire, vertices, triangles, flip=False, switch=False): v = np.array(vertices, np.float32) t = np.array(triangles, np.int32) vertices = v triangles = t if flip: v2 = np.copy(v) v2[:,0] = -v[:,0] t2 = np.copy(t) t2[:,1] = t[:,2] t2[:,2] = t[:,1] vertices = v2 triangles = t2 if switch: v2 = np.copy(v) v2[:,0] = -v[:,2] v2[:,2] = v[:,0] vertices = v2 triangles = t fout = open(dire, 'w') for ii in range(len(vertices)): fout.write("v "+str(vertices[ii,0])+" "+str(vertices[ii,1])+" "+str(vertices[ii,2])+"\n") for ii in range(len(triangles)): fout.write("f "+str(triangles[ii,0]+1)+" "+str(triangles[ii,1]+1)+" "+str(triangles[ii,2]+1)+"\n") fout.close() def write_ply_triangle(dire, vertices, triangles): fout = open(dire, 'w') fout.write("ply\n") fout.write("format ascii 1.0\n") fout.write("element vertex "+str(len(vertices))+"\n") fout.write("property float x\n") fout.write("property float y\n") fout.write("property float z\n") fout.write("element face "+str(len(triangles))+"\n") fout.write("property list uchar int vertex_index\n") fout.write("end_header\n") for i in range(len(vertices)): fout.write(str(vertices[i][0])+" "+str(vertices[i][1])+" "+str(vertices[i][2])+"\n") for i in range(len(triangles)): fout.write("3 "+str(triangles[i][0])+" "+str(triangles[i][1])+" "+str(triangles[i][2])+"\n") fout.close() def write_ply_point_normal(name, vertices, normals=None): fout = open(name, 'w') fout.write("ply\n") fout.write("format ascii 1.0\n") fout.write("element vertex "+str(len(vertices))+"\n") fout.write("property float x\n") fout.write("property float y\n") fout.write("property float z\n") fout.write("property float nx\n") fout.write("property float ny\n") fout.write("property float nz\n") fout.write("end_header\n") if normals is None: for ii in range(len(vertices)): fout.write(str(vertices[ii,0])+" "+str(vertices[ii,1])+" "+str(vertices[ii,2])+" "+str(vertices[ii,3])+" "+str(vertices[ii,4])+" "+str(vertices[ii,5])+"\n") else: for ii in range(len(vertices)): fout.write(str(vertices[ii,0])+" "+str(vertices[ii,1])+" "+str(vertices[ii,2])+" "+str(normals[ii,0])+" "+str(normals[ii,1])+" "+str(normals[ii,2])+"\n") fout.close() def write_ply_edge(dire, vertices, edges): fout = open(dire, 'w') fout.write("ply\n") fout.write("format ascii 1.0\n") fout.write("element vertex "+str(len(vertices))+"\n") fout.write("property float x\n") fout.write("property float y\n") fout.write("property float z\n") fout.write("element edge "+str(len(edges))+"\n") fout.write("property int vertex1\n") fout.write("property int vertex2\n") fout.write("end_header\n") for i in range(len(vertices)): fout.write(str(vertices[i][0])+" "+str(vertices[i][1])+" "+str(vertices[i][2])+"\n") for i in range(len(edges)): fout.write(str(edges[i][0])+" "+str(edges[i][1])+"\n") fout.close() def write_ply_edgeloop(dire, vertices, loops): edge_num = 0 for i in range(len(loops)): if loops[i][-1]<0: continue edge_num += len(loops[i]) fout = open(dire, 'w') fout.write("ply\n") fout.write("format ascii 1.0\n") fout.write("element vertex "+str(len(vertices))+"\n") fout.write("property float x\n") fout.write("property float y\n") fout.write("property float z\n") fout.write("element edge "+str(edge_num)+"\n") fout.write("property int vertex1\n") fout.write("property int vertex2\n") fout.write("end_header\n") for i in range(len(vertices)): fout.write(str(vertices[i][0])+" "+str(vertices[i][1])+" "+str(vertices[i][2])+"\n") for i in range(len(loops)): if loops[i][-1]<0: continue for j in range(len(loops[i])): fout.write(str(loops[i][j])+" "+str(loops[i][(j+1)%len(loops[i])])+"\n") fout.close() def sqdist(p1,p2): return np.sum(np.square(p1-p2)) def midpoint(p1,p2): return (p1+p2)/2 def min_dist2(p1,plist2): if len(plist2)==0: return 666666.666 return np.min(np.sum(np.square(p1-plist2),axis=1)) def find_loops(vertices, edges): vertices = np.array(vertices,np.float32) edges = np.array(edges,np.int32) merge_threshold = 1e-4 #first, remove non-edge points print("merging") edge_use_flag = np.zeros([len(vertices)], np.uint8) for i in range(len(edges)): edge_use_flag[edges[i,0]]=1 edge_use_flag[edges[i,1]]=1 tmp_mapping = edge_use_flag.nonzero()[0] tmp_vertices = vertices[tmp_mapping] tmp_vertices_len = len(tmp_vertices) #second, merge same vertex loop_tv = [] inverse_mapping = [] loop_te = [] mapping = np.zeros([len(vertices)], np.int32) use_flag = np.zeros([len(vertices)], np.uint8) counter=0 for i in range(tmp_vertices_len): if i==0: mapping[tmp_mapping[i]]=counter counter += 1 use_flag[tmp_mapping[i]]=1 continue tmp_within = np.sum(np.abs(tmp_vertices[i]-tmp_vertices[:i]),axis=1)<merge_threshold max_idx = np.argmax(tmp_within) if tmp_within[max_idx]: mapping[tmp_mapping[i]]=mapping[tmp_mapping[max_idx]] else: mapping[tmp_mapping[i]]=counter counter += 1 use_flag[tmp_mapping[i]]=1 for i in range(len(vertices)): if use_flag[i]: loop_tv.append(vertices[i]) inverse_mapping.append(i) for i in range(len(edges)): e0 = mapping[edges[i,0]] e1 = mapping[edges[i,1]] if e0!=e1: loop_te.append([e0,e1]) print("merging - end") print("finding loop") #find loops loop_le = [] prev_vertex = np.full([len(loop_tv)], -1, np.int32) next_vertex = np.full([len(loop_tv)], -1, np.int32) vertex_used_flag = np.zeros([len(loop_tv)], np.uint8) for i in range(len(loop_te)): if loop_te[i][0]!=loop_te[i][1]: prev_vertex[loop_te[i][1]] = loop_te[i][0] next_vertex[loop_te[i][0]] = loop_te[i][1] while(np.min(vertex_used_flag)==0): target_v = -1 #find a start for i in range(len(loop_tv)): if vertex_used_flag[i]==0: if prev_vertex[i]<0 and next_vertex[i]<0: vertex_used_flag[i]=1 else: target_v = i break if target_v<0: break vertex_used_flag[target_v]=1 #find origin prev_v_list = [target_v] prev_v = target_v while prev_vertex[prev_v]>=0 and prev_vertex[prev_v] not in prev_v_list: prev_v = prev_vertex[prev_v] vertex_used_flag[prev_v]=1 prev_v_list.append(prev_v) #get loop next_v_list = prev_v_list[::-1] if prev_vertex[next_v_list[0]]<0: target_v = next_v_list[-1] next_v = target_v while next_vertex[next_v]>=0 and next_vertex[next_v] not in next_v_list: next_v = next_vertex[next_v] vertex_used_flag[next_v]=1 next_v_list.append(next_v) if next_vertex[next_v]<0: next_v_list.append(-1) else: if next_vertex[next_v]==next_v_list[-2]: next_v_list.append(-1) else: next_v_list = next_v_list[next_v_list.index(next_vertex[next_v]):] else: loop_le.append(next_v_list[:next_v_list.index(prev_vertex[next_v_list[0]])+1]) next_v_list = next_v_list[next_v_list.index(prev_vertex[next_v_list[0]]):] target_v = next_v_list[-1] next_v = target_v while next_vertex[next_v]>=0 and next_vertex[next_v] not in next_v_list: next_v = next_vertex[next_v] vertex_used_flag[next_v]=1 next_v_list.append(next_v) if next_vertex[next_v]<0: next_v_list.append(-1) else: if next_vertex[next_v]==next_v_list[-2]: next_v_list.append(-1) else: next_v_list = next_v_list[next_v_list.index(next_vertex[next_v]):] loop_le.append(next_v_list) print('loop -> lines', len(loop_le)) #close loops loop_fe = [] loop_le_used_flag = np.zeros([len(loop_le)], np.uint8) for i in range(len(loop_le)): if loop_le[i][-1]>=0: loop_fe.append(loop_le[i]) loop_le_used_flag[i]=1 print('loop -> closed ', len(loop_fe)) distance_threshold = 0.02 distance_threshold2 = distance_threshold*distance_threshold for i in range(len(loop_le)): if loop_le_used_flag[i]==0: tmp_used_flag = np.copy(loop_le_used_flag) tmp_used_flag[i]=1 newloop_idx = [i] newloop = loop_le[i][:-1] newloop_ordercount = len(newloop) newloop_starti = newloop[0] newloop_start = loop_tv[newloop_starti] newloop_endi = newloop[-1] newloop_end = loop_tv[newloop_endi] prev_seq_headi = newloop_starti prev_seq_head = loop_tv[prev_seq_headi] prev_endi = newloop_endi looped_flag = False while True: nearest_id = -1 nearest_dist2 = 666666.666 for j in range(len(loop_le)): if tmp_used_flag[j]==0: tmp_vi = loop_le[j][0] tmp_v = loop_tv[tmp_vi] tmp_dist2 = np.sum(np.square(newloop_end-tmp_v)) if tmp_dist2<nearest_dist2: nearest_id = j nearest_dist2 = tmp_dist2 if nearest_dist2<distance_threshold2: tmp_used_flag[nearest_id]=1 newloop_idx.append(nearest_id) newloop = newloop + loop_le[nearest_id][:-1] newloop_ordercount += len(loop_le[nearest_id])-1 newloop_endi = loop_le[nearest_id][-2] newloop_end = loop_tv[newloop_endi] prev_seq_headi = loop_le[nearest_id][0] prev_seq_head = loop_tv[prev_seq_headi] tmp_dist2 = np.sum(np.square(newloop_end-newloop_start)) if tmp_dist2<distance_threshold2: looped_flag = True break if prev_endi==newloop_endi: break prev_endi=newloop_endi if looped_flag: loop_fe.append(newloop) loop_le_used_flag = tmp_used_flag print('loop + found ', len(loop_fe)) distance_threshold = 0.04 distance_threshold2 = distance_threshold*distance_threshold for i in range(len(loop_le)): if loop_le_used_flag[i]==0: tmp_used_flag = np.copy(loop_le_used_flag) tmp_used_flag[i]=1 newloop_idx = [i] newloop = loop_le[i][:-1] newloop_ordercount = len(newloop) newloop_starti = newloop[0] newloop_start = loop_tv[newloop_starti] newloop_endi = newloop[-1] newloop_end = loop_tv[newloop_endi] prev_seq_headi = newloop_starti prev_seq_head = loop_tv[prev_seq_headi] prev_endi = newloop_endi looped_flag = False while True: nearest_id = -1 nearest_dist2 = 666666.666 for j in range(len(loop_le)): if tmp_used_flag[j]==0: tmp_vi = loop_le[j][0] tmp_v = loop_tv[tmp_vi] tmp_dist2 = np.sum(np.square(newloop_end-tmp_v)) if tmp_dist2<nearest_dist2: nearest_id = j nearest_dist2 = tmp_dist2 if nearest_dist2<distance_threshold2: tmp_used_flag[nearest_id]=1 newloop_idx.append(nearest_id) newloop = newloop + loop_le[nearest_id][:-1] newloop_ordercount += len(loop_le[nearest_id])-1 newloop_endi = loop_le[nearest_id][-2] newloop_end = loop_tv[newloop_endi] prev_seq_headi = loop_le[nearest_id][0] prev_seq_head = loop_tv[prev_seq_headi] tmp_dist2 = np.sum(np.square(newloop_end-newloop_start)) if tmp_dist2<distance_threshold2: looped_flag = True break if prev_endi==newloop_endi: break prev_endi=newloop_endi if looped_flag: loop_fe.append(newloop) loop_le_used_flag = tmp_used_flag print('loop + found ', len(loop_fe)) distance_threshold = 0.06 distance_threshold2 = distance_threshold*distance_threshold for i in range(len(loop_le)): if loop_le_used_flag[i]==0: tmp_used_flag = np.copy(loop_le_used_flag) tmp_used_flag[i]=1 newloop_idx = [i] newloop = loop_le[i][:-1] newloop_ordercount = len(newloop) newloop_starti = newloop[0] newloop_start = loop_tv[newloop_starti] newloop_endi = newloop[-1] newloop_end = loop_tv[newloop_endi] prev_seq_headi = newloop_starti prev_seq_head = loop_tv[prev_seq_headi] prev_endi = newloop_endi looped_flag = False while True: nearest_id = -1 nearest_dist2 = 666666.666 for j in range(len(loop_le)): if tmp_used_flag[j]==0: tmp_vi = loop_le[j][0] tmp_v = loop_tv[tmp_vi] tmp_dist2 = np.sum(np.square(newloop_end-tmp_v)) if tmp_dist2<nearest_dist2: nearest_id = j nearest_dist2 = tmp_dist2 if nearest_dist2<distance_threshold2: tmp_used_flag[nearest_id]=1 newloop_idx.append(nearest_id) newloop = newloop + loop_le[nearest_id][:-1] newloop_ordercount += len(loop_le[nearest_id])-1 newloop_endi = loop_le[nearest_id][-2] newloop_end = loop_tv[newloop_endi] prev_seq_headi = loop_le[nearest_id][0] prev_seq_head = loop_tv[prev_seq_headi] tmp_dist2 = np.sum(np.square(newloop_end-newloop_start)) if tmp_dist2<distance_threshold2: looped_flag = True break if prev_endi==newloop_endi: break prev_endi=newloop_endi if
(see\n' ' section Calls) can be applied:\n' '\n' ' User-defined functions\n' ' A user-defined function object is created by a function\n' ' definition (see section Function definitions). It should be\n' ' called with an argument list containing the same number of ' 'items\n' " as the function's formal parameter list.\n" '\n' ' Special attributes:\n' '\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | Attribute | Meaning ' '| |\n' ' ' '+=========================+=================================+=============+\n' ' | "__doc__" "func_doc" | The function\'s documentation ' '| Writable |\n' ' | | string, or "None" if ' '| |\n' ' | | unavailable. ' '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__name__" "func_name" | The function\'s name ' '| Writable |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__module__" | The name of the module the | ' 'Writable |\n' ' | | function was defined in, or ' '| |\n' ' | | "None" if unavailable. ' '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__defaults__" | A tuple containing default | ' 'Writable |\n' ' | "func_defaults" | argument values for those ' '| |\n' ' | | arguments that have defaults, ' '| |\n' ' | | or "None" if no arguments have ' '| |\n' ' | | a default value. ' '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__code__" "func_code" | The code object representing | ' 'Writable |\n' ' | | the compiled function body. ' '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__globals__" | A reference to the dictionary | ' 'Read-only |\n' ' | "func_globals" | that holds the function\'s ' '| |\n' ' | | global variables --- the global ' '| |\n' ' | | namespace of the module in ' '| |\n' ' | | which the function was defined. ' '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__dict__" "func_dict" | The namespace supporting | ' 'Writable |\n' ' | | arbitrary function attributes. ' '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' ' | "__closure__" | "None" or a tuple of cells that | ' 'Read-only |\n' ' | "func_closure" | contain bindings for the ' '| |\n' " | | function's free variables. " '| |\n' ' ' '+-------------------------+---------------------------------+-------------+\n' '\n' ' Most of the attributes labelled "Writable" check the type of ' 'the\n' ' assigned value.\n' '\n' ' Changed in version 2.4: "func_name" is now writable.\n' '\n' ' Changed in version 2.6: The double-underscore attributes\n' ' "__closure__", "__code__", "__defaults__", and "__globals__"\n' ' were introduced as aliases for the corresponding "func_*"\n' ' attributes for forwards compatibility with Python 3.\n' '\n' ' Function objects also support getting and setting arbitrary\n' ' attributes, which can be used, for example, to attach ' 'metadata\n' ' to functions. Regular attribute dot-notation is used to get ' 'and\n' ' set such attributes. *Note that the current implementation ' 'only\n' ' supports function attributes on user-defined functions. ' 'Function\n' ' attributes on built-in functions may be supported in the\n' ' future.*\n' '\n' " Additional information about a function's definition can be\n" ' retrieved from its code object; see the description of ' 'internal\n' ' types below.\n' '\n' ' User-defined methods\n' ' A user-defined method object combines a class, a class ' 'instance\n' ' (or "None") and any callable object (normally a user-defined\n' ' function).\n' '\n' ' Special read-only attributes: "im_self" is the class ' 'instance\n' ' object, "im_func" is the function object; "im_class" is the\n' ' class of "im_self" for bound methods or the class that asked ' 'for\n' ' the method for unbound methods; "__doc__" is the method\'s\n' ' documentation (same as "im_func.__doc__"); "__name__" is the\n' ' method name (same as "im_func.__name__"); "__module__" is ' 'the\n' ' name of the module the method was defined in, or "None" if\n' ' unavailable.\n' '\n' ' Changed in version 2.2: "im_self" used to refer to the class\n' ' that defined the method.\n' '\n' ' Changed in version 2.6: For Python 3 forward-compatibility,\n' ' "im_func" is also available as "__func__", and "im_self" as\n' ' "__self__".\n' '\n' ' Methods also support accessing (but not setting) the ' 'arbitrary\n' ' function attributes on the underlying function object.\n' '\n' ' User-defined method objects may be created when getting an\n' ' attribute of a class (perhaps via an instance of that class), ' 'if\n' ' that attribute is a user-defined function object, an unbound\n' ' user-defined method object, or a class method object. When ' 'the\n' ' attribute is a user-defined method object, a new method ' 'object\n' ' is only created if the class from which it is being retrieved ' 'is\n' ' the same as, or a derived class of, the class stored in the\n' ' original method object; otherwise, the original method object ' 'is\n' ' used as it is.\n' '\n' ' When a user-defined method object is created by retrieving a\n' ' user-defined function object from a class, its "im_self"\n' ' attribute is "None" and the method object is said to be ' 'unbound.\n' ' When one is created by retrieving a user-defined function ' 'object\n' ' from a class via one of its instances, its "im_self" ' 'attribute\n' ' is the instance, and the method object is said to be bound. ' 'In\n' ' either case, the new method\'s "im_class" attribute is the ' 'class\n' ' from which the retrieval takes place, and its "im_func"\n' ' attribute is the original function object.\n' '\n' ' When a user-defined method object is created by retrieving\n' ' another method object from a class or instance, the behaviour ' 'is\n' ' the same as for a function object, except that the "im_func"\n' ' attribute of the new instance is not the original method ' 'object\n' ' but its "im_func" attribute.\n' '\n' ' When a user-defined method object is created by retrieving a\n' ' class method object from a class or instance, its "im_self"\n' ' attribute is the class itself, and its "im_func" attribute ' 'is\n' ' the function object underlying the class method.\n' '\n' ' When an unbound user-defined method object is called, the\n' ' underlying function ("im_func") is called, with the ' 'restriction\n' ' that the first argument must be an instance of the proper ' 'class\n' ' ("im_class") or of a derived class thereof.\n' '\n' ' When a bound user-defined method object is called, the\n' ' underlying function ("im_func") is called, inserting the ' 'class\n' ' instance ("im_self") in front of the argument list. For\n' ' instance, when "C" is a class which contains a definition for ' 'a\n' ' function "f()", and "x" is an instance of "C", calling ' '"x.f(1)"\n' ' is equivalent to calling "C.f(x, 1)".\n' '\n' ' When a user-defined method object is derived from a class ' 'method\n' ' object, the "class instance" stored in "im_self" will ' 'actually\n' ' be the class itself, so that calling either "x.f(1)" or ' '"C.f(1)"\n' ' is equivalent to calling "f(C,1)" where "f" is the ' 'underlying\n' ' function.\n' '\n' ' Note that the transformation from function object to (unbound ' 'or\n' ' bound) method object happens each time the attribute is\n' ' retrieved from the class or instance. In some cases, a ' 'fruitful\n' ' optimization is to assign the attribute to a local variable ' 'and\n' ' call that local variable. Also notice that this ' 'transformation\n' ' only happens for user-defined functions; other callable ' 'objects\n' ' (and all non-callable objects) are retrieved without\n' ' transformation. It is also important to note that ' 'user-defined\n' ' functions which are attributes of a class instance are not\n' ' converted to bound methods; this *only* happens when the\n' ' function is an attribute of the class.\n' '\n' ' Generator functions\n' ' A function or method which uses the "yield" statement (see\n' ' section The yield statement) is called a
<gh_stars>0 # Copyright (C) GRyCAP - I3M - UPV # # 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. """Module with methods shared by all the classes.""" import base64 import json import os import re import shutil import subprocess import tarfile import tempfile import uuid import sys from copy import deepcopy from zipfile import ZipFile from io import BytesIO from typing import Optional, Dict, List, Generator, Union, Any from distutils import dir_util from packaging import version import yaml import scar.logger as logger import scar.http.request as request from scar.exceptions import GitHubTagNotFoundError, YamlFileNotFoundError COMMANDS = ['scar-config'] def lazy_property(func): # Skipped type hinting: https://github.com/python/mypy/issues/3157 """ A decorator that makes a property lazy-evaluated.""" attr_name = '_lazy_' + func.__name__ @property def _lazy_property(self): if not hasattr(self, attr_name): setattr(self, attr_name, func(self)) return getattr(self, attr_name) return _lazy_property class SysUtils: """Common methods for system management.""" @staticmethod def is_variable_in_environment(variable: str) -> bool: """Checks if a variable is in the system environment.""" return variable in os.environ @staticmethod def set_environment_variable(key: str, variable: Any) -> None: """Sets a system environment variable.""" if key and variable: os.environ[key] = variable @staticmethod def get_environment_variable(variable: str) -> str: """Returns the value of system environment variable or an empty string if not found.""" return os.environ.get(variable, '') @staticmethod def delete_environment_variable(variable: str) -> None: """Delete a system environment variable.""" if SysUtils.is_variable_in_environment(variable): del os.environ[variable] @staticmethod def execute_command_with_msg(command: List[str], cmd_wd: Optional[str]=None, cli_msg: str='') -> str: """Execute the specified command and return the result.""" cmd_out = subprocess.check_output(command, cwd=cmd_wd).decode('utf-8') logger.debug(cmd_out) logger.info(cli_msg) return cmd_out[:-1] @staticmethod def get_user_home_path() -> str: """Returns the path of the current user's home.""" return os.path.expanduser("~") @staticmethod def finish_scar_execution() -> None: """Finishes the program execution.""" logger.end_execution_trace() sys.exit(0) class DataTypesUtils: """Common methods for data types management.""" @staticmethod def merge_dicts(dict1: Dict, dict2: Dict) -> Dict: """Merge 'dict1' and 'dict2' dicts into 'dict1'. 'dict2' has precedence over 'dict1'.""" for key, val in dict2.items(): if val is not None: if isinstance(val, dict) and key in dict1: dict1[key] = DataTypesUtils.merge_dicts(dict1[key], val) elif isinstance(val, list) and key in dict1: dict1[key] += val else: dict1[key] = val return dict1 @staticmethod def merge_dicts_with_copy(dict1: Dict, dict2: Dict) -> Dict: """Merge 'dict1' and 'dict2' dicts into a new Dict. 'dict2' has precedence over 'dict1'.""" result = deepcopy(dict1) for key, val in dict2.items(): if val is not None: if isinstance(val, dict) and key in result: result[key] = DataTypesUtils.merge_dicts_with_copy(result[key], val) elif isinstance(val, list) and key in result: result[key] += val else: result[key] = val return result @staticmethod def divide_list_in_chunks(elements: List, chunk_size: int) -> Generator[List, None, None]: """Yield successive n-sized chunks from th elements list.""" if not elements: yield [] for i in range(0, len(elements), chunk_size): yield elements[i:i + chunk_size] @staticmethod def parse_arg_list(arg_keys: List, cmd_args: Dict) -> Dict: """Parse an argument dictionary filtering by the names specified in a list.""" result = {} for key in arg_keys: if isinstance(key, tuple): if key[0] in cmd_args and cmd_args[key[0]]: result[key[1]] = cmd_args[key[0]] else: if key in cmd_args and cmd_args[key]: result[key] = cmd_args[key] return result class FileUtils: """Common methods for file and directory management.""" @staticmethod def copy_file(source: str, dest: str) -> None: """Copy file to specified destination.""" shutil.copy(source, dest) @staticmethod def copy_dir(source: str, dest: str) -> None: """Copy directory to specified destination.""" dir_util.copy_tree(source, dest) @staticmethod def create_folder(folder_name): """Creates a system folder. Does nothing if the folder exists.""" os.makedirs(folder_name, exist_ok=True) @staticmethod def get_scar_root_path() -> str: """Returns the root path of the project.""" return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @staticmethod def join_paths(*paths: str) -> str: """Returns the strings passed joined as a system path.""" return os.path.join(*paths) @staticmethod def get_tmp_dir() -> str: """Gets the directory where the temporal folder of the system is located.""" return tempfile.gettempdir() @staticmethod def create_tmp_dir() -> tempfile.TemporaryDirectory: """Creates a directory in the temporal folder of the system. When the context is finished, the folder is automatically deleted.""" return tempfile.TemporaryDirectory() @staticmethod def create_tmp_file(**kwargs) -> tempfile.NamedTemporaryFile: """Creates a directory in the temporal folder of the system. When the context is finished, the folder is automatically deleted.""" return tempfile.NamedTemporaryFile(**kwargs) @staticmethod def get_tree_size(path: str) -> int: """Return total size of files in given path and subdirs.""" total = 0 for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): total += FileUtils.get_tree_size(entry.path) else: total += entry.stat(follow_symlinks=False).st_size return total @staticmethod def get_all_files_in_directory(dir_path: str) -> List[str]: """Returns a list with all the file paths in the specified directory and subdirectories.""" files = [] for dirname, _, filenames in os.walk(dir_path): for filename in filenames: files.append(os.path.join(dirname, filename)) return files @staticmethod def get_file_size(file_path: str) -> int: """Returns the file size in bytes""" return os.stat(file_path).st_size @staticmethod def create_file_with_content(path: str, content: Optional[Union[str, bytes]], mode: str='w') -> None: """Creates a new file with the passed content. If the content is a dictionary, first is converted to a string.""" with open(path, mode) as fwc: if isinstance(content, dict): content = json.dumps(content) fwc.write(content) @staticmethod def read_file(file_path: str, mode: str='r') -> Optional[Union[str, bytes]]: """Reads the whole specified file and returns the content.""" with open(file_path, mode) as content_file: return content_file.read() @staticmethod def delete_file(path: str) -> None: """Delete the specified file.""" if os.path.isfile(path): os.remove(path) @staticmethod def delete_folder(path: str) -> None: """Delete a folder with all its contents.""" shutil.rmtree(path) @staticmethod def create_tar_gz(files_to_archive: List[str], destination_tar_path: str) -> str: """Create a .tar.gz file with the passed list of files.""" with tarfile.open(destination_tar_path, 'w:gz') as tar: for file_path in files_to_archive: tar.add(file_path, arcname=os.path.basename(file_path)) return destination_tar_path @staticmethod def extract_tar_gz(tar_path: str, destination_path: str) -> None: """Extract the content of a .tar.gz file in the specified path.""" with tarfile.open(tar_path, 'r:gz') as tar: tar.extractall(path=destination_path) @staticmethod def unzip_folder(zip_path: str, folder_where_unzip_path: str, msg: str='') -> None: """Must use the unzip binary to preserve the file properties and the symlinks.""" zip_exe = '/usr/bin/unzip' SysUtils.execute_command_with_msg([zip_exe, zip_path], cmd_wd=folder_where_unzip_path, cli_msg=msg) @staticmethod def zip_folder(zip_path: str, folder_to_zip_path: str, msg: str='') -> None: """Must use the zip binary to preserve the file properties and the symlinks.""" zip_exe = '/usr/bin/zip' SysUtils.execute_command_with_msg([zip_exe, '-r9y', zip_path, '.'], cmd_wd=folder_to_zip_path, cli_msg=msg) @staticmethod def is_file(file_path: str): """Test whether a path is a regular file.""" return os.path.isfile(file_path) @staticmethod def load_yaml(file_path: str) -> Dict: """Returns the content of a YAML file as a Dict.""" if os.path.isfile(file_path): with open(file_path) as cfg_file: return yaml.safe_load(cfg_file) else: raise YamlFileNotFoundError(file_path=file_path) @staticmethod def write_yaml(file_path: str, content: Dict) -> None: with open(file_path, 'w') as cfg_file: yaml.safe_dump(content, cfg_file) @staticmethod def create_tmp_config_file(cfg_args): cfg_path = FileUtils.join_paths(SysUtils.get_user_home_path(), ".scar", "scar_tmp.yaml") os.environ['SCAR_TMP_CFG'] = cfg_path FileUtils.write_yaml(cfg_path, cfg_args) @staticmethod def load_tmp_config_file(): return FileUtils.load_yaml(os.environ['SCAR_TMP_CFG']) @staticmethod def get_file_name(file_path: str) -> str: return os.path.basename(file_path) @staticmethod def extract_zip_from_url(url: str, dest_path: str) -> None: with ZipFile(BytesIO(url)) as thezip: thezip.extractall(dest_path) class StrUtils: """Common methods for string management.""" @staticmethod def decode_base64(value: Union[bytes, str]) -> bytes: """Decode a Base64 encoded bytes-like object or ASCII string and return the decoded bytes""" return base64.b64decode(value) @staticmethod def encode_base64(value: bytes) -> bytes: """Encode a bytes-like object using Base64 and return the encoded bytes.""" return base64.b64encode(value) @staticmethod def base64_to_utf8_string(value: Union[bytes, str]) -> str: """Decode a Base64 encoded bytes-like object or ASCII string and return the decoded value as a string.""" return StrUtils.decode_base64(value).decode('utf-8') @staticmethod def utf8_to_base64_string(value: str) -> str: """Encode a 'utf-8' string using Base64 and return the encoded value as a string.""" return StrUtils.encode_base64(bytes(value, 'utf-8')).decode('utf-8') @staticmethod def bytes_to_base64str(value, encoding='utf-8') -> str: """Encode a 'utf-8' string using Base64 and return the encoded value as a string.""" return StrUtils.encode_base64(value).decode(encoding) @staticmethod def dict_to_base64_string(value: Dict) -> str: """Encodes a dictionary to base64 and returns a string.""" return StrUtils.utf8_to_base64_string(json.dumps(value)) @staticmethod def find_expression(string_to_search: str, rgx_pattern: str) -> Optional[str]: """Returns the first group that matches the rgx_pattern in the string_to_search.""" if string_to_search: pattern = re.compile(rgx_pattern) match = pattern.search(string_to_search) if match: return match.group() return None @staticmethod def get_random_uuid4_str() -> str: """Returns a random generated uuid4 string.""" return str(uuid.uuid4()) @staticmethod def compare_versions(ver1: str, ver2: str) -> int: """Returns value < 0 to indicate that ver1 is less than ver2. Returns value > 0 to indicate that ver1 is greater
<reponame>WeisiX/ITAS3D ### Copyright (C) 2017 NVIDIA Corporation. All rights reserved. ### Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). import time import os import numpy as np import torch from torch.autograd import Variable from collections import OrderedDict from subprocess import call import fractions def lcm(a,b): return abs(a * b)/fractions.gcd(a,b) if a and b else 0 from options.train_options import TrainOptions from data.data_loader import CreateDataLoader from models.models import create_model import util.util as util from util.visualizer import Visualizer def train(): opt = TrainOptions().parse() if opt.debug: opt.display_freq = 1 opt.print_freq = 1 opt.nThreads = 1 ### initialize dataset data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() dataset_size = len(data_loader) if opt.dataset_mode == 'pose': print('#training frames = %d' % dataset_size) else: print('#training videos = %d' % dataset_size) ### initialize models modelG, modelD, flowNet = create_model(opt) visualizer = Visualizer(opt) iter_path = os.path.join(opt.checkpoints_dir, opt.name, 'iter.txt') ### if continue training, recover previous states if opt.continue_train: try: start_epoch, epoch_iter = np.loadtxt(iter_path , delimiter=',', dtype=int) except: start_epoch, epoch_iter = 1, 0 print('Resuming from epoch %d at iteration %d' % (start_epoch, epoch_iter)) if start_epoch > opt.niter: modelG.module.update_learning_rate(start_epoch-1) modelD.module.update_learning_rate(start_epoch-1) if (opt.n_scales_spatial > 1) and (opt.niter_fix_global != 0) and (start_epoch > opt.niter_fix_global): modelG.module.update_fixed_params() if start_epoch > opt.niter_step: data_loader.dataset.update_training_batch((start_epoch-1)//opt.niter_step) modelG.module.update_training_batch((start_epoch-1)//opt.niter_step) else: start_epoch, epoch_iter = 1, 0 ### set parameters n_gpus = opt.n_gpus_gen // opt.batchSize # number of gpus used for generator for each batch tG, tD = opt.n_frames_G, opt.n_frames_D tDB = tD * opt.output_nc s_scales = opt.n_scales_spatial t_scales = opt.n_scales_temporal input_nc = 1 if opt.label_nc != 0 else opt.input_nc output_nc = opt.output_nc opt.print_freq = lcm(opt.print_freq, opt.batchSize) total_steps = (start_epoch-1) * dataset_size + epoch_iter total_steps = total_steps // opt.print_freq * opt.print_freq ### real training starts here for epoch in range(start_epoch, opt.niter + opt.niter_decay + 1): epoch_start_time = time.time() for idx, data in enumerate(dataset, start=epoch_iter): if total_steps % opt.print_freq == 0: iter_start_time = time.time() total_steps += opt.batchSize epoch_iter += opt.batchSize # whether to collect output images save_fake = total_steps % opt.display_freq == 0 _, n_frames_total, height, width = data['B'].size() # n_frames_total = n_frames_load * n_loadings + tG - 1 n_frames_total = n_frames_total // opt.output_nc n_frames_load = opt.max_frames_per_gpu * n_gpus # number of total frames loaded into GPU at a time for each batch n_frames_load = min(n_frames_load, n_frames_total - tG + 1) t_len = n_frames_load + tG - 1 # number of loaded frames plus previous frames fake_B_last = None # the last generated frame from previous training batch (which becomes input to the next batch) real_B_all, fake_B_all, flow_ref_all, conf_ref_all = None, None, None, None # all real/generated frames so far if opt.sparse_D: real_B_all, fake_B_all, flow_ref_all, conf_ref_all = [None]*t_scales, [None]*t_scales, [None]*t_scales, [None]*t_scales real_B_skipped, fake_B_skipped = [None]*t_scales, [None]*t_scales # temporally subsampled frames flow_ref_skipped, conf_ref_skipped = [None]*t_scales, [None]*t_scales # temporally subsampled flows for i in range(0, n_frames_total-t_len+1, n_frames_load): # 5D tensor: batchSize, # of frames, # of channels, height, width input_A = Variable(data['A'][:, i*input_nc:(i+t_len)*input_nc, ...]).view(-1, t_len, input_nc, height, width) input_B = Variable(data['B'][:, i*output_nc:(i+t_len)*output_nc, ...]).view(-1, t_len, output_nc, height, width) inst_A = Variable(data['inst'][:, i:i+t_len, ...]).view(-1, t_len, 1, height, width) if len(data['inst'].size()) > 2 else None ###################################### Forward Pass ########################## ####### generator fake_B, fake_B_raw, flow, weight, real_A, real_Bp, fake_B_last = modelG(input_A, input_B, inst_A, fake_B_last) if i == 0: fake_B_first = fake_B[0, 0] # the first generated image in this sequence real_B_prev, real_B = real_Bp[:, :-1], real_Bp[:, 1:] # the collection of previous and current real frames ####### discriminator ### individual frame discriminator flow_ref, conf_ref = flowNet(real_B, real_B_prev) # reference flows and confidences fake_B_prev = real_B_prev[:, 0:1] if fake_B_last is None else fake_B_last[0][:, -1:] if fake_B.size()[1] > 1: fake_B_prev = torch.cat([fake_B_prev, fake_B[:, :-1].detach()], dim=1) losses = modelD(0, reshape([real_B, fake_B, fake_B_raw, real_A, real_B_prev, fake_B_prev, flow, weight, flow_ref, conf_ref])) losses = [ torch.mean(x) if x is not None else 0 for x in losses ] loss_dict = dict(zip(modelD.module.loss_names, losses)) ### temporal discriminator loss_dict_T = [] # get skipped frames for each temporal scale if t_scales > 0: if opt.sparse_D: real_B_all, real_B_skipped = get_skipped_frames_sparse(real_B_all, real_B, t_scales, tD, n_frames_load, i) fake_B_all, fake_B_skipped = get_skipped_frames_sparse(fake_B_all, fake_B, t_scales, tD, n_frames_load, i) flow_ref_all, flow_ref_skipped = get_skipped_frames_sparse(flow_ref_all, flow_ref, t_scales, tD, n_frames_load, i, is_flow=True) conf_ref_all, conf_ref_skipped = get_skipped_frames_sparse(conf_ref_all, conf_ref, t_scales, tD, n_frames_load, i, is_flow=True) else: real_B_all, real_B_skipped = get_skipped_frames(real_B_all, real_B, t_scales, tD) fake_B_all, fake_B_skipped = get_skipped_frames(fake_B_all, fake_B, t_scales, tD) flow_ref_all, conf_ref_all, flow_ref_skipped, conf_ref_skipped = get_skipped_flows(flowNet, flow_ref_all, conf_ref_all, real_B_skipped, flow_ref, conf_ref, t_scales, tD) # run discriminator for each temporal scale for s in range(t_scales): if real_B_skipped[s] is not None: losses = modelD(s+1, [real_B_skipped[s], fake_B_skipped[s], flow_ref_skipped[s], conf_ref_skipped[s]]) losses = [ torch.mean(x) if not isinstance(x, int) else x for x in losses ] loss_dict_T.append(dict(zip(modelD.module.loss_names_T, losses))) # collect losses loss_D = (loss_dict['D_fake'] + loss_dict['D_real']) * 0.5 loss_G = loss_dict['G_GAN'] + loss_dict['G_GAN_Feat'] + loss_dict['G_VGG'] loss_G += loss_dict['G_Warp'] + loss_dict['F_Flow'] + loss_dict['F_Warp'] + loss_dict['W'] if opt.add_face_disc: loss_G += loss_dict['G_f_GAN'] + loss_dict['G_f_GAN_Feat'] loss_D += (loss_dict['D_f_fake'] + loss_dict['D_f_real']) * 0.5 # collect temporal losses loss_D_T = [] t_scales_act = min(t_scales, len(loss_dict_T)) for s in range(t_scales_act): loss_G += loss_dict_T[s]['G_T_GAN'] + loss_dict_T[s]['G_T_GAN_Feat'] + loss_dict_T[s]['G_T_Warp'] loss_D_T.append((loss_dict_T[s]['D_T_fake'] + loss_dict_T[s]['D_T_real']) * 0.5) ###################################### Backward Pass ################################# optimizer_G = modelG.module.optimizer_G optimizer_D = modelD.module.optimizer_D # update generator weights optimizer_G.zero_grad() loss_G.backward() optimizer_G.step() # update discriminator weights # individual frame discriminator optimizer_D.zero_grad() loss_D.backward() optimizer_D.step() # temporal discriminator for s in range(t_scales_act): optimizer_D_T = getattr(modelD.module, 'optimizer_D_T'+str(s)) optimizer_D_T.zero_grad() loss_D_T[s].backward() optimizer_D_T.step() if opt.debug: call(["nvidia-smi", "--format=csv", "--query-gpu=memory.used,memory.free"]) ############## Display results and errors ########## ### print out errors if total_steps % opt.print_freq == 0: t = (time.time() - iter_start_time) / opt.print_freq errors = {k: v.data.item() if not isinstance(v, int) else v for k, v in loss_dict.items()} for s in range(len(loss_dict_T)): errors.update({k+str(s): v.data.item() if not isinstance(v, int) else v for k, v in loss_dict_T[s].items()}) visualizer.print_current_errors(epoch, epoch_iter, errors, t) visualizer.plot_current_errors(errors, total_steps) ### display output images if save_fake: if opt.label_nc != 0: input_image = util.tensor2label(real_A[0, -1], opt.label_nc) elif opt.dataset_mode == 'pose': input_image = util.tensor2im(real_A[0, -1, :3]) if real_A.size()[2] == 6: input_image2 = util.tensor2im(real_A[0, -1, 3:]) input_image[input_image2 != 0] = input_image2[input_image2 != 0] else: c = 3 if opt.input_nc == 3 else 1 input_image = util.tensor2im(real_A[0, -1, :c], normalize=True) #changed to true if opt.use_instance: edges = util.tensor2im(real_A[0, -1, -1:,...], normalize=False) input_image += edges[:,:,np.newaxis] if opt.add_face_disc: ys, ye, xs, xe = modelD.module.get_face_region(real_A[0, -1:]) if ys is not None: input_image[ys, xs:xe, :] = input_image[ye, xs:xe, :] = input_image[ys:ye, xs, :] = input_image[ys:ye, xe, :] = 255 visual_list = [('input_image', input_image), ('fake_image', util.tensor2im(fake_B[0, -1])), ('fake_first_image', util.tensor2im(fake_B_first)), ('fake_raw_image', util.tensor2im(fake_B_raw[0, -1])), ('real_image', util.tensor2im(real_B[0, -1])), ('flow_ref', util.tensor2flow(flow_ref[0, -1])), ('conf_ref', util.tensor2im(conf_ref[0, -1], normalize=False))] if flow is not None: visual_list += [('flow', util.tensor2flow(flow[0, -1])), ('weight', util.tensor2im(weight[0, -1], normalize=False))] visuals = OrderedDict(visual_list) visualizer.display_current_results(visuals, epoch, total_steps) ### save latest model if total_steps % opt.save_latest_freq == 0: visualizer.vis_print('saving the latest model (epoch %d, total_steps %d)' % (epoch, total_steps)) modelG.module.save('latest') modelD.module.save('latest') np.savetxt(iter_path, (epoch, epoch_iter), delimiter=',', fmt='%d') if epoch_iter > dataset_size - opt.batchSize: epoch_iter = 0 break # end of epoch iter_end_time = time.time() visualizer.vis_print('End of epoch %d / %d \t Time Taken: %d sec' % (epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time)) ### save model for this epoch if epoch % opt.save_epoch_freq == 0: visualizer.vis_print('saving the model at the end of epoch %d, iters %d' % (epoch, total_steps)) modelG.module.save('latest') modelD.module.save('latest') modelG.module.save(epoch) modelD.module.save(epoch) np.savetxt(iter_path, (epoch+1, 0), delimiter=',', fmt='%d') ### linearly decay learning rate after certain iterations if epoch > opt.niter: modelG.module.update_learning_rate(epoch) modelD.module.update_learning_rate(epoch) ### gradually grow training sequence length if (epoch % opt.niter_step) == 0: data_loader.dataset.update_training_batch(epoch//opt.niter_step) modelG.module.update_training_batch(epoch//opt.niter_step) ### finetune all scales if (opt.n_scales_spatial > 1) and (opt.niter_fix_global != 0) and (epoch == opt.niter_fix_global): modelG.module.update_fixed_params() def reshape(tensors): if isinstance(tensors, list): return [reshape(tensor) for tensor in tensors] if tensors is None: return None _, _, ch, h, w = tensors.size() return tensors.contiguous().view(-1, ch, h, w) # get temporally subsampled frames for real/fake sequences def get_skipped_frames(B_all, B, t_scales, tD): B_all = torch.cat([B_all.detach(), B], dim=1) if
= self.layer_dict['fcc_{}'.format(i)].forward(out) if self.use_bn: self.layer_dict['fcc_bn_{}'.format(i)] = MetaBatchNormLayer(num_features=out.shape[1], args=self.args, use_per_step_bn_statistics=True) out = self.layer_dict['fcc_bn_{}'.format(i)].forward(out, num_step=0) out = F.leaky_relu(out) out = out.view(out.shape[0], -1) self.layer_dict['preds_linear'] = MetaLinearLayer(input_shape=(out.shape[0], np.prod(out.shape[1:])), num_filters=self.num_output_classes, use_bias=self.use_bias) out = self.layer_dict['preds_linear'](out) print("FCCActivationNormNetwork build", out.shape) def forward(self, x, num_step, params=None, training=False, backup_running_statistics=False, return_features=False): """ Forward propages through the network. If any params are passed then they are used instead of stored params. :param x: Input image batch. :param num_step: The current inner loop step number :param params: If params are None then internal parameters are used. If params are a dictionary with keys the same as the layer names then they will be used instead. :param training: Whether this is training (True) or eval time. :param backup_running_statistics: Whether to backup the running statistics in their backup store. Which is then used to reset the stats back to a previous state (usually after an eval loop, when we want to throw away stored statistics) :return: Logits of shape b, num_output_classes. """ param_dict = dict() if params is not None: params = {key: value[0] for key, value in params.items()} param_dict = extract_top_level_dict(current_dict=params) for name, param in list(self.layer_dict.named_parameters()) + list(self.layer_dict.items()): path_bits = name.split(".") layer_name = path_bits[0] if layer_name not in param_dict: param_dict[layer_name] = None out = x out = out.view(out.size(0), -1) for i in range(self.num_stages): out = self.layer_dict['fcc_{}'.format(i)](out, params=param_dict['fcc_{}'.format(i)]) if self.use_bn: out = self.layer_dict['fcc_bn_{}'.format(i)].forward(out, num_step=num_step, params=None, training=training, backup_running_statistics=backup_running_statistics) out = F.leaky_relu(out) features = out out = out.view(out.size(0), -1) out = self.layer_dict['preds_linear'](out, param_dict['preds_linear']) if return_features: return out, features else: return out def reset_parameters(self): for name, module in self.named_modules(): if type(module) == MetaLinearLayer: # print("reset", name) module.reset_parameters() def restore_backup_stats(self): """ Reset stored batch statistics from the stored backup. """ for name, module in self.named_modules(): if type(module) == MetaBatchNormLayer: module.restore_backup_stats() def zero_grad(self, params=None): if params is None: for param in self.parameters(): if param.requires_grad == True: if param.grad is not None: if torch.sum(param.grad) > 0: print(param.grad) param.grad.zero_() else: for name, param in params.items(): if param.requires_grad == True: if param.grad is not None: if torch.sum(param.grad) > 0: print(param.grad) param.grad.zero_() params[name].grad = None class SqueezeExciteLayer(nn.ModuleDict): def __init__(self, input_shape, num_filters, num_layers, num_support_set_steps, num_target_set_steps): super(SqueezeExciteLayer, self).__init__() self.input_shape = input_shape self.num_filters = num_filters self.num_layers = num_layers self.num_support_set_steps = num_support_set_steps self.num_target_set_steps = num_target_set_steps self.build_block() def build_block(self): self.layer_dict = nn.ModuleDict() x_dummy = torch.zeros(self.input_shape) out = x_dummy out = F.avg_pool2d(out, out.shape[-1]).squeeze() for i in range(self.num_layers - 1): self.layer_dict['attention_network_hidden_{}'.format(i)] = MetaLinearLayer(input_shape=out.shape, use_bias=True, num_filters=self.num_filters) out = self.layer_dict['attention_network_hidden_{}'.format(i)].forward(out, params=None) self.layer_dict['LeakyReLU_{}'.format(i)] = nn.LeakyReLU() out = self.layer_dict['LeakyReLU_{}'.format(i)].forward(out) self.layer_dict['attention_network_output_layer'] = MetaLinearLayer(input_shape=out.shape, use_bias=True, num_filters=x_dummy.shape[1]) channel_wise_attention_regions = self.layer_dict[ 'attention_network_output_layer'].forward( out, params=None) channel_wise_attention_regions = F.sigmoid(channel_wise_attention_regions) out = x_dummy * channel_wise_attention_regions.unsqueeze(2).unsqueeze(2) print('Built', type(self), 'with output', out.shape, self) def forward(self, x, num_step=0, params=None): param_dict = dict() if params is not None: params = {key: value for key, value in params.items()} param_dict = extract_top_level_dict(current_dict=params) for name, param in list(self.layer_dict.named_parameters()) + list(self.layer_dict.items()): path_bits = name.split(".") layer_name = path_bits[0] if layer_name not in param_dict: param_dict[layer_name] = None out = x out = F.avg_pool2d(out, out.shape[-1]).squeeze() for i in range(self.num_layers - 1): # print(out.shape) out = self.layer_dict[ 'attention_network_hidden_{}'.format(i)].forward( out, params=param_dict['attention_network_hidden_{}'.format(i)]) out = self.layer_dict['LeakyReLU_{}'.format(i)].forward(out) # print(out.shape) channel_wise_attention_regions = self.layer_dict[ 'attention_network_output_layer'].forward( out, params=param_dict['attention_network_output_layer']) channel_wise_attention_regions = F.sigmoid(channel_wise_attention_regions) out = x * channel_wise_attention_regions.unsqueeze(2).unsqueeze(2) return out class VGGActivationNormNetworkWithAttention(nn.Module): def __init__(self, input_shape, num_output_classes, use_channel_wise_attention, num_stages, num_filters, num_support_set_steps, num_target_set_steps, num_blocks_per_stage): """ Builds a multilayer convolutional network. It also provides functionality for passing external parameters to be used at inference time. Enables inner loop optimization readily. :param im_shape: The input image batch shape. :param num_output_classes: The number of output classes of the network. :param args: A named tuple containing the system's hyperparameters. :param device: The device to run this on. :param meta_classifier: A flag indicating whether the system's meta-learning (inner-loop) functionalities should be enabled. """ super(VGGActivationNormNetworkWithAttention, self).__init__() self.total_layers = 0 self.upscale_shapes = [] self.num_filters = num_filters self.num_stages = num_stages self.input_shape = input_shape self.use_channel_wise_attention = use_channel_wise_attention self.num_output_classes = num_output_classes self.num_blocks_per_stage = num_blocks_per_stage self.num_support_set_steps = num_support_set_steps self.num_target_set_steps = num_target_set_steps self.build_network() def build_network(self): """ Builds the network before inference is required by creating some dummy inputs with the same input as the self.im_shape tuple. Then passes that through the network and dynamically computes input shapes and sets output shapes for each layer. """ x = torch.zeros(self.input_shape) out = x self.layer_dict = nn.ModuleDict() for i in range(self.num_stages): for j in range(self.num_blocks_per_stage): if self.use_channel_wise_attention: self.layer_dict['attention_layer_{}_{}'.format(i, j)] = SqueezeExciteLayer(input_shape=out.shape, num_filters=0, num_layers=0, num_support_set_steps=self.num_support_set_steps, num_target_set_steps=self.num_target_set_steps) out = self.layer_dict['attention_layer_{}_{}'.format(i, j)].forward(out) self.layer_dict['conv_{}_{}'.format(i, j)] = MetaConvNormLayerLeakyReLU(input_shape=out.shape, num_filters=self.num_filters, kernel_size=3, stride=1, padding=1, use_bias=True, groups=1, per_step_bn_statistics=True, num_support_set_steps=self.num_support_set_steps, num_target_set_steps=self.num_target_set_steps) out = self.layer_dict['conv_{}_{}'.format(i, j)](out, training=True, num_step=0) out = F.max_pool2d(input=out, kernel_size=(2, 2), stride=2, padding=0) if self.use_channel_wise_attention: self.layer_dict['attention_pre_logit_layer'] = SqueezeExciteLayer(input_shape=out.shape, num_filters=0, num_layers=0, num_support_set_steps=self.num_support_set_steps, num_target_set_steps=self.num_target_set_steps) out = self.layer_dict['attention_pre_logit_layer'].forward(out) features_avg = F.avg_pool2d(out, out.shape[-1]).squeeze() out = features_avg self.layer_dict['linear'] = MetaLinearLayer(input_shape=out.shape, num_filters=self.num_output_classes, use_bias=True) out = self.layer_dict['linear'](out) print("VGGNetwork build", out.shape) def forward(self, x, num_step, dropout_training=None, params=None, training=False, backup_running_statistics=False, return_features=False): """ Forward propages through the network. If any params are passed then they are used instead of stored params. :param x: Input image batch. :param num_step: The current inner loop step number :param params: If params are None then internal parameters are used. If params are a dictionary with keys the same as the layer names then they will be used instead. :param training: Whether this is training (True) or eval time. :param backup_running_statistics: Whether to backup the running statistics in their backup store. Which is then used to reset the stats back to a previous state (usually after an eval loop, when we want to throw away stored statistics) :return: Logits of shape b, num_output_classes. """ param_dict = dict() if params is not None: params = {key: value[0] for key, value in params.items()} # print([key for key, value in param_dict.items()]) param_dict = extract_top_level_dict(current_dict=params) for name, param in list(self.layer_dict.named_parameters()) + list(self.layer_dict.items()): path_bits = name.split(".") layer_name = path_bits[0] if layer_name not in param_dict: param_dict[layer_name] = None out = x # print([key for key, value in param_dict.items() if value is not None]) for i in range(self.num_stages): for j in range(self.num_blocks_per_stage): if self.use_channel_wise_attention: out = self.layer_dict['attention_layer_{}_{}'.format(i, j)].forward(out, num_step=num_step, params=param_dict[ 'attention_layer_{}_{}'.format( i, j)]) out = self.layer_dict['conv_{}_{}'.format(i, j)](out, training=True, num_step=num_step, params=param_dict['conv_{}_{}'.format(i, j)]) out = F.max_pool2d(input=out, kernel_size=(2, 2), stride=2, padding=0) if self.use_channel_wise_attention: out = self.layer_dict['attention_pre_logit_layer'].forward(out, params=param_dict[ 'attention_pre_logit_layer']) features = out features_avg = F.avg_pool2d(out, out.shape[-1]).squeeze() # out = F.avg_pool2d(out, out.shape[-1]) # out = self.layer_dict['relational_pool'].forward(out, params=param_dict['relational_pool'], num_step=num_step) out = features_avg out = self.layer_dict['linear'](out, param_dict['linear']) if return_features: return out, features else: return out def restore_backup_stats(self): """ Reset stored batch statistics from the stored backup. """ for name, module in self.named_modules(): if type(module) == MetaBatchNormLayer: module.restore_backup_stats() def zero_grad(self, params=None): if params is None: for param in self.parameters(): if param.requires_grad == True: if param.grad is not None: if torch.sum(param.grad) > 0: print(param.grad) param.grad.zero_() else: for name, param in params.items(): if param.requires_grad == True: if param.grad is not None: if torch.sum(param.grad) > 0: print(param.grad) param.grad.zero_() params[name].grad = None class MetaBatchRelationalModule(nn.Module): def __init__(self, input_shape, use_coordinates=True, num_support_set_steps=0, num_target_set_steps=0, output_units=32): super(MetaBatchRelationalModule, self).__init__() self.input_shape = input_shape self.layer_dict = nn.ModuleDict() self.first_time = True self.use_coordinates = use_coordinates self.num_target_set_steps = num_target_set_steps self.num_support_set_steps = num_support_set_steps self.output_units = output_units self.build_block() def build_block(self): out_img = torch.zeros(self.input_shape) """g""" if len(out_img.shape) > 3: b, c, h, w = out_img.shape if h > 5: out_img = F.adaptive_avg_pool2d(out_img, output_size=5) print(out_img.shape) b, c, h, w = out_img.shape out_img = out_img.view(b, c, h * w) out_img = out_img.permute([0, 2, 1]) # h*w, c b, length, c = out_img.shape print(out_img.shape) # x_flat = (64 x 25 x 24) if self.use_coordinates: self.coord_tensor = [] for i in range(length): self.coord_tensor.append(torch.Tensor(np.array([i]))) self.coord_tensor = torch.stack(self.coord_tensor, dim=0).unsqueeze(0) if self.coord_tensor.shape[0] != out_img.shape[0]: self.coord_tensor = self.coord_tensor[0].unsqueeze(0).repeat([out_img.shape[0], 1, 1]) out_img = torch.cat([out_img, self.coord_tensor], dim=2) x_i = torch.unsqueeze(out_img, 1) # (1xh*wxc) x_i = x_i.repeat(1, length, 1, 1) # (h*wxh*wxc) x_j = torch.unsqueeze(out_img, 2) # (h*wx1xc) x_j = x_j.repeat(1, 1, length, 1) # (h*wxh*wxc) # concatenate all together per_location_feature = torch.cat([x_i, x_j], 3) # (h*wxh*wx2*c) out = per_location_feature.view( per_location_feature.shape[0] * per_location_feature.shape[1] * per_location_feature.shape[2], per_location_feature.shape[3]) # print(out.shape) for idx_layer in range(2): # print('test', out.shape) self.layer_dict['g_fcc_{}'.format(idx_layer)] = MetaLinearLayer(input_shape=out.shape, num_filters=64, use_bias=True) out = self.layer_dict['g_fcc_{}'.format(idx_layer)].forward(out) self.layer_dict['LeakyReLU_{}'.format(idx_layer)] = nn.LeakyReLU() out = self.layer_dict['LeakyReLU_{}'.format(idx_layer)].forward(out) #
<filename>emmet-builders/emmet/builders/molecules/atomic.py<gh_stars>0 from datetime import datetime from itertools import chain from math import ceil from typing import Optional, Iterable, Iterator, List, Dict from maggma.builders import Builder from maggma.core import Store from maggma.utils import grouper from emmet.core.qchem.task import TaskDocument from emmet.core.qchem.molecule import MoleculeDoc, evaluate_lot from emmet.core.molecules.atomic import ( PartialChargesDoc, PartialSpinsDoc, CHARGES_METHODS, SPINS_METHODS, ) from emmet.core.utils import jsanitize from emmet.builders.settings import EmmetBuildSettings __author__ = "<NAME>" SETTINGS = EmmetBuildSettings() class PartialChargesBuilder(Builder): """ The PartialChargesBuilder extracts partial charges data from a MoleculeDoc. Various methods can be used to define partial charges, including: - Mulliken - Restrained Electrostatic Potential (RESP) - Critic2 - Natural Bonding Orbital (NBO) population analysis This builder will attempt to build documents for each molecule with each method. For each molecule-method combination, the highest-quality data available (based on level of theory and electronic energy) will be used. The process is as follows: 1. Gather MoleculeDocs by formula 2. For each molecule, sort all associated tasks by level of theory and electronic energy 2. For each method: 2.1. Find task docs with necessary data to calculate partial charges by that method 2.2. Take best (defined by level of theory and electronic energy) task 2.3. Convert TaskDoc to PartialChargesDoc """ def __init__( self, tasks: Store, molecules: Store, charges: Store, query: Optional[Dict] = None, methods: Optional[List] = None, settings: Optional[EmmetBuildSettings] = None, **kwargs, ): self.tasks = tasks self.molecules = molecules self.charges = charges self.query = query if query else dict() self.methods = methods if methods else CHARGES_METHODS self.settings = EmmetBuildSettings.autoload(settings) self.kwargs = kwargs super().__init__(sources=[tasks, molecules], targets=[charges]) def ensure_indexes(self): """ Ensures indices on the collections needed for building """ # Basic search index for tasks self.tasks.ensure_index("task_id") self.tasks.ensure_index("last_updated") self.tasks.ensure_index("state") self.tasks.ensure_index("formula_alphabetical") # Search index for molecules self.molecules.ensure_index("molecule_id") self.molecules.ensure_index("last_updated") self.molecules.ensure_index("task_ids") self.molecules.ensure_index("formula_alphabetical") # Search index for charges self.charges.ensure_index("molecule_id") self.charges.ensure_index("method") self.charges.ensure_index("task_id") self.charges.ensure_index("last_updated") self.charges.ensure_index("formula_alphabetical") def prechunk(self, number_splits: int) -> Iterable[Dict]: # pragma: no cover """Prechunk the builder for distributed computation""" temp_query = dict(self.query) temp_query["deprecated"] = False self.logger.info("Finding documents to process") all_mols = list( self.molecules.query( temp_query, [self.molecules.key, "formula_alphabetical"] ) ) processed_docs = set([e for e in self.charges.distinct("molecule_id")]) to_process_docs = {d[self.molecules.key] for d in all_mols} - processed_docs to_process_forms = { d["formula_alphabetical"] for d in all_mols if d[self.molecules.key] in to_process_docs } N = ceil(len(to_process_forms) / number_splits) for formula_chunk in grouper(to_process_forms, N): yield {"query": {"formula_alphabetical": {"$in": list(formula_chunk)}}} def get_items(self) -> Iterator[List[Dict]]: """ Gets all items to process into partial charges documents. This does no datetime checking; relying on on whether task_ids are included in the charges Store Returns: generator or list relevant tasks and molecules to process into documents """ self.logger.info("Partial charges builder started") self.logger.info("Setting indexes") self.ensure_indexes() # Save timestamp to mark buildtime self.timestamp = datetime.utcnow() # Get all processed molecules temp_query = dict(self.query) temp_query["deprecated"] = False self.logger.info("Finding documents to process") all_mols = list( self.molecules.query( temp_query, [self.molecules.key, "formula_alphabetical"] ) ) processed_docs = set([e for e in self.charges.distinct("molecule_id")]) to_process_docs = {d[self.molecules.key] for d in all_mols} - processed_docs to_process_forms = { d["formula_alphabetical"] for d in all_mols if d[self.molecules.key] in to_process_docs } self.logger.info(f"Found {len(to_process_docs)} unprocessed documents") self.logger.info(f"Found {len(to_process_forms)} unprocessed formulas") # Set total for builder bars to have a total self.total = len(to_process_forms) for formula in to_process_forms: mol_query = dict(temp_query) mol_query["formula_alphabetical"] = formula molecules = list(self.molecules.query(criteria=mol_query)) yield molecules def process_item(self, items: List[Dict]) -> List[Dict]: """ Process the tasks into PartialChargesDocs Args: tasks List[Dict] : a list of MoleculeDocs in dict form Returns: [dict] : a list of new partial charges docs """ mols = [MoleculeDoc(**item) for item in items] formula = mols[0].formula_alphabetical mol_ids = [m.molecule_id for m in mols] self.logger.debug(f"Processing {formula} : {mol_ids}") charges_docs = list() for mol in mols: correct_charge_spin = [ e for e in mol.entries if e["charge"] == mol.charge and e["spin_multiplicity"] == mol.spin_multiplicity ] sorted_entries = sorted( correct_charge_spin, key=lambda x: (sum(evaluate_lot(x["level_of_theory"])), x["energy"]), ) for method in self.methods: # For each method, grab entries that have the relevant data relevant_entries = [ e for e in sorted_entries if e.get(method) is not None or e["output"].get(method) is not None ] if len(relevant_entries) == 0: continue # Grab task document of best entry best_entry = relevant_entries[0] task = best_entry["task_id"] task_doc = TaskDocument(**self.tasks.query_one({"task_id": int(task)})) doc = PartialChargesDoc.from_task( task_doc, molecule_id=mol.molecule_id, preferred_methods=[method], deprecated=False, ) charges_docs.append(doc) self.logger.debug(f"Produced {len(charges_docs)} charges docs for {formula}") return jsanitize([doc.dict() for doc in charges_docs], allow_bson=True) def update_targets(self, items: List[List[Dict]]): """ Inserts the new documents into the charges collection Args: items [[dict]]: A list of documents to update """ docs = list(chain.from_iterable(items)) # type: ignore # Add timestamp for item in docs: item.update( { "_bt": self.timestamp, } ) molecule_ids = list({item["molecule_id"] for item in docs}) if len(items) > 0: self.logger.info(f"Updating {len(docs)} partial charges documents") self.charges.remove_docs({self.charges.key: {"$in": molecule_ids}}) # Neither molecule_id nor method need to be unique, but the combination must be self.charges.update( docs=docs, key=["molecule_id", "method"], ) else: self.logger.info("No items to update") class PartialSpinsBuilder(Builder): """ The PartialSpinsBuilder extracts partial spin data from a MoleculeDoc. Various methods can be used to define partial atomic spins, including: - Mulliken - Natural Bonding Orbital (NBO) population analysis This builder will attempt to build documents for each molecule with each method. For each molecule-method combination, the highest-quality data available (based on level of theory and electronic energy) will be used. The process is as follows: 1. Gather MoleculeDocs by formula 2. For each molecule, sort all associated tasks by level of theory and electronic energy 2. For each method: 2.1. Find task docs with necessary data to calculate partial spins by that method 2.2. Take best (defined by level of theory and electronic energy) task 2.3. Convert TaskDoc to PartialChargesDoc """ def __init__( self, tasks: Store, molecules: Store, spins: Store, query: Optional[Dict] = None, methods: Optional[List] = None, settings: Optional[EmmetBuildSettings] = None, **kwargs, ): self.tasks = tasks self.molecules = molecules self.spins = spins self.query = query if query else dict() self.methods = methods if methods else SPINS_METHODS self.settings = EmmetBuildSettings.autoload(settings) self.kwargs = kwargs super().__init__(sources=[tasks, molecules], targets=[spins]) def ensure_indexes(self): """ Ensures indices on the collections needed for building """ # Basic search index for tasks self.tasks.ensure_index("task_id") self.tasks.ensure_index("last_updated") self.tasks.ensure_index("state") self.tasks.ensure_index("formula_alphabetical") # Search index for molecules self.molecules.ensure_index("molecule_id") self.molecules.ensure_index("last_updated") self.molecules.ensure_index("task_ids") self.molecules.ensure_index("formula_alphabetical") # Search index for charges self.spins.ensure_index("molecule_id") self.spins.ensure_index("method") self.spins.ensure_index("task_id") self.spins.ensure_index("last_updated") self.spins.ensure_index("formula_alphabetical") def prechunk(self, number_splits: int) -> Iterable[Dict]: # pragma: no cover """Prechunk the builder for distributed computation""" temp_query = dict(self.query) temp_query["deprecated"] = False self.logger.info("Finding documents to process") all_mols = list( self.molecules.query( temp_query, [self.molecules.key, "formula_alphabetical"] ) ) processed_docs = set([e for e in self.spins.distinct("molecule_id")]) to_process_docs = {d[self.molecules.key] for d in all_mols} - processed_docs to_process_forms = { d["formula_alphabetical"] for d in all_mols if d[self.molecules.key] in to_process_docs } N = ceil(len(to_process_forms) / number_splits) for formula_chunk in grouper(to_process_forms, N): yield {"query": {"formula_alphabetical": {"$in": list(formula_chunk)}}} def get_items(self) -> Iterator[List[Dict]]: """ Gets all items to process into partial spins documents. This does no datetime checking; relying on on whether task_ids are included in the spins Store Returns: generator or list relevant tasks and molecules to process into documents """ self.logger.info("Partial spins builder started") self.logger.info("Setting indexes") self.ensure_indexes() # Save timestamp to mark buildtime self.timestamp = datetime.utcnow() # Get all processed molecules temp_query = dict(self.query) temp_query["deprecated"] = False self.logger.info("Finding documents to process") all_mols = list( self.molecules.query( temp_query, [self.molecules.key, "formula_alphabetical"] ) ) processed_docs = set([e for e in self.spins.distinct("molecule_id")]) to_process_docs = {d[self.molecules.key] for d in all_mols} - processed_docs to_process_forms = { d["formula_alphabetical"] for d in all_mols if d[self.molecules.key] in to_process_docs } self.logger.info(f"Found {len(to_process_docs)} unprocessed documents") self.logger.info(f"Found {len(to_process_forms)} unprocessed formulas") # Set total for builder bars to have a total self.total = len(to_process_forms) for formula in to_process_forms: mol_query = dict(temp_query) mol_query["formula_alphabetical"] = formula molecules = list(self.molecules.query(criteria=mol_query)) yield molecules def process_item(self, items: List[Dict]) -> List[Dict]: """ Process the tasks into PartialSpinsDocs Args: tasks List[Dict] : a list of MoleculeDocs in dict form Returns: [dict] : a list of new partial spins docs """ mols = [MoleculeDoc(**item) for item in items] formula = mols[0].formula_alphabetical mol_ids = [m.molecule_id for m in mols] self.logger.debug(f"Processing {formula} : {mol_ids}") spins_docs = list() for mol in mols: # Molecule with spin multiplicity 1 has no partial spins if mol.spin_multiplicity == 1: continue correct_charge_spin =
<reponame>pbs/its import itertools import os import tempfile import unittest from io import BytesIO from pathlib import Path from unittest import TestCase from unittest.mock import patch from PIL import Image import its.errors from its.application import APP from its.optimize import has_transparent_background, optimize from its.pipeline import process_transforms def get_pixels(image): # List of all the possible coordinates in the image coords = list(itertools.product(range(image.width), range(image.height))) # list of all pixels in the image pixels = [image.getpixel(coord) for coord in coords] return pixels # for colored images with alpha pixel pair is like (r, g, b, a) # for white/black images with alpha pixel pair is like (90, 91) def compare_pixels(img1, img2, tolerance=0, is_white_or_black_image=False): number_of_color_indices = 3 if is_white_or_black_image: number_of_color_indices = 1 def pixel_matches(pixel1, pixel2, tolerance): matching_vals = [ abs(pixel1[i] - pixel2[i]) <= tolerance for i in range(number_of_color_indices) ] return all(matching_vals) img1_pixels = get_pixels(img1) img2_pixels = get_pixels(img2) matches = 0 total = len(img1_pixels) # both images should have the same number of pixels for pixel_pair in zip(img1_pixels, img2_pixels): if pixel_matches(pixel_pair[0], pixel_pair[1], tolerance): matches += 1 return matches / total class TestFitTransform(TestCase): @classmethod def setUpClass(self): self.img_dir = Path(__file__).parent / "images" @patch("its.transformations.fit.FitTransform.apply_transform") def test_default_fit_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "middle.png") test_image.info["filename"] = "middle.png" query = {"fit": "100x100"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_default_crop_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "middle.png") test_image.info["filename"] = "middle.png" query = {"crop": "100x100"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_focal_fit_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "top_left.png") test_image.info["filename"] = "top_left.png" query = {"fit": "1x1x1x1"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_focal_crop_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "top_left.png") test_image.info["filename"] = "top_left.png" query = {"crop": "1x1x1x1"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_focal_1x1_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "abstract.png") test_image.info["filename"] = "abstract.png" query = {"fit": "28x34x1x1"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_focalcrop_1x1_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "abstract.png") test_image.info["filename"] = "abstract.png" query = {"crop": "28x34x1x1"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_focal_100x100_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "abstract.png") test_image.info["filename"] = "abstract.png" query = {"fit": "1x1x100x100"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_focalcrop_100x100_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "abstract.png") test_image.info["filename"] = "abstract.png" query = {"crop": "1x1x100x100"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_smart_70x1_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "abstract_focus-70x1.png") test_image.info["filename"] = "abstract_focus-70x1.png" query = {"fit": "5x100"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) @patch("its.transformations.fit.FitTransform.apply_transform") def test_smartcrop_70x1_no_alpha(self, MockFitTransform): fit_transform = MockFitTransform() test_image = Image.open(self.img_dir / "abstract_focus-70x1.png") test_image.info["filename"] = "abstract_focus-70x1.png" query = {"crop": "5x100"} fit_transform.return_value = True fit_transform(test_image, query) fit_transform.assert_called_with(test_image, query) def test_invalid_fit_size(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"fit": "5x0"} with self.assertRaises(its.errors.ITSClientError): process_transforms(test_image, query) def test_invalid_crop_size(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"crop": "5x0"} with self.assertRaises(its.errors.ITSClientError): process_transforms(test_image, query) def test_invalid_focal_percentages(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"fit": "100x100x150x150"} with self.assertRaises(its.errors.ITSClientError): process_transforms(test_image, query) def test_invalid_crop_focal_percentages(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"crop": "100x100x150x150"} with self.assertRaises(its.errors.ITSClientError): process_transforms(test_image, query) class TestResizeTransform(TestCase): @classmethod def setUpClass(self): # current directory / images self.img_dir = Path(__file__).parent / "images" self.threshold = 0.5 def test_resize_size(self): test_image = Image.open(self.img_dir / "abstract.png") test_image.info["filename"] = "abstract.png" query = {"resize": "10x10"} result = process_transforms(test_image, query) self.assertEqual(result.size, (10, 10)) def test_resize_without_height(self): test_image = Image.open(self.img_dir / "abe.jpg") test_image.info["filename"] = "abe.jpg" query = {"resize": "100x"} result = process_transforms(test_image, query) self.assertEqual(result.width, 100) self.assertEqual(result.height, 131) def test_resize_without_width(self): test_image = Image.open(self.img_dir / "abe.jpg") test_image.info["filename"] = "abe.jpg" query = {"resize": "x100"} result = process_transforms(test_image, query) self.assertEqual(result.width, 76) self.assertEqual(result.height, 100) def test_resize_integrity_smaller(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"resize": "100x100"} expected = Image.open(self.img_dir / "expected/test_resize.png") actual = process_transforms(test_image, query) # can't use norm since resizing can cause noise comparison = compare_pixels(expected, actual) self.assertGreaterEqual(comparison, self.threshold) def test_resize_integrity_smaller_noscaleup(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"resize": "100x100,no-scale-up"} expected = Image.open(self.img_dir / "expected/test_resize.png") actual = process_transforms(test_image, query) # no-scale-up doesn't change assert actual.width == expected.width assert actual.height == expected.height comparison = compare_pixels(expected, actual) self.assertGreaterEqual(comparison, self.threshold) def test_resize_integrity_larger(self): test_image = Image.open(self.img_dir / "test.png") test_image.info["filename"] = "test.png" query = {"resize": "700x550"} expected = Image.open(self.img_dir / "expected/test_resize_700x550.png") actual = process_transforms(test_image, query) comparison = compare_pixels(expected, actual) self.assertGreaterEqual(comparison, self.threshold) def test_resize_integrity_larger_noscaleup(self): test_image = Image.open(self.img_dir / "logo.png") test_image.info["filename"] = "logo.png" query = {"resize": "700x700,no-scale-up"} # image doesn't scale up, so expect no change expected = Image.open(self.img_dir / "logo.png") actual = process_transforms(test_image, query) comparison = compare_pixels(expected, actual) assert actual.width == expected.width assert actual.height == expected.height self.assertGreaterEqual(comparison, self.threshold) def test_resize_integrity_larger_noscaleup_width_only(self): test_image = Image.open(self.img_dir / "seagull.jpg") test_image.info["filename"] = "seagull.jpg" query = {"resize": "1600x,no-scale-up"} expected = Image.open(self.img_dir / "seagull.jpg") actual = process_transforms(test_image, query) assert actual.width == expected.width assert actual.height == expected.height comparison = compare_pixels(expected, actual) self.assertGreaterEqual(comparison, self.threshold) def test_resize_integrity_larger_noscaleup_height_only(self): test_image = Image.open(self.img_dir / "seagull.jpg") test_image.info["filename"] = "seagull.jpg" query = {"resize": "x992,no-scale-up"} expected = Image.open(self.img_dir / "seagull.jpg") actual = process_transforms(test_image, query) assert actual.width == expected.width assert actual.height == expected.height comparison = compare_pixels(expected, actual) self.assertGreaterEqual(comparison, self.threshold) def test_invalid_resize(self): test_image = Image.open(self.img_dir / "test.png") query = {"resize": "100"} with self.assertRaises(its.errors.ITSClientError): process_transforms(test_image, query) def test_resize_format(self): test_image = Image.open(self.img_dir / "test.png") query = {"resize": "100x100", "format": "foo"} with self.assertRaises(its.errors.ITSClientError): result = process_transforms(test_image, query) optimize(result, query) class TestImageResults(TestCase): @classmethod def setUpClass(self): # current directory / images self.img_dir = Path(__file__).parent / "images" def test_jpg_progressive(self): test_image = Image.open(self.img_dir / "middle.png") result = optimize(test_image, {"format": "jpg"}) self.assertEqual(result.info["progressive"], 1) def test_jpg_quality_vs_size(self): test_image = Image.open(self.img_dir / "middle.png") quality_1 = optimize(test_image, {"quality": 1, "format": "jpg"}) with tempfile.NamedTemporaryFile(dir=".", delete=True) as tmp_file_1: quality_1.save(tmp_file_1.name, format=quality_1.format) q1_size = os.stat(tmp_file_1.name).st_size quality_10 = optimize(test_image, {"quality": 10, "format": "jpg"}) with tempfile.NamedTemporaryFile(dir=".", delete=True) as tmp_file_2: quality_10.save(tmp_file_2.name, format=quality_10.format) q10_size = os.stat(tmp_file_2.name).st_size self.assertLessEqual(q1_size, q10_size) def test_png_quality_vs_size(self): test_image = Image.open(self.img_dir / "test.png") quality_1 = optimize(test_image, {"quality": "1"}) with tempfile.NamedTemporaryFile(dir=".", delete=True) as tmp_file_1: quality_1.save(tmp_file_1.name, format=quality_1.format) q1_size = os.stat(tmp_file_1.name).st_size quality_10 = optimize(test_image, {"quality": "10"}) with tempfile.NamedTemporaryFile(dir=".", delete=True) as tmp_file_2: quality_10.save(tmp_file_2.name, format=quality_10.format) q10_size = os.stat(tmp_file_2.name).st_size self.assertLessEqual(q1_size, q10_size) class TestPipelineEndToEnd(TestCase): @classmethod def setUpClass(self): APP.config["TESTING"] = True self.client = APP.test_client() self.img_dir = Path(__file__).parent / "images" self.threshold = 0.99 def test_secret_png(self): response = self.client.get("tests/images/secretly-a-png.jpg.resize.800x450.jpg") assert response.status_code == 200 def test_cmyk_jpg_to_rgb_png(self): response = self.client.get("/tests/images/cmyk.jpg.resize.380x190.png") assert response.status_code == 200 def test_svg_passthrough(self): reference_image = BytesIO( open(self.img_dir / "wikipedia_logo.svg", "rb").read() ) response = self.client.get( "/tests/images/wikipedia_logo.svg?fit=10x10&format=png&resize=500x500" ) assert response.status_code == 200 assert response.mimetype == "image/svg+xml" assert response.data == reference_image.getvalue() def test_grayscale_png_to_jpg(self): response = self.client.get("tests/images/grayscale.png.fit.2048x876.jpg") assert response.status_code == 200 assert response.mimetype == "image/jpeg" def test_jpg_to_webp(self): response = self.client.get("tests/images/seagull.jpg?format=webp") assert response.status_code == 200 assert response.mimetype == "image/webp" def test_jpg_without_extension_to_png(self): response = self.client.get("tests/images/seagull.resize.900x500.png") assert response.status_code == 200 assert response.mimetype == "image/png" def test_jpg_without_extension_to_focalcrop(self): response = self.client.get("tests/images/seagull.focalcrop.312x464.50.50.png") assert response.status_code == 200 assert response.mimetype == "image/png" def test_focal_crop_without_filename_priority(self): # case 1: resize and crop with query parameters ref_img_500_500_50_10 = Image.open( "{}/expected/seagull-500-500-50-10.jpg".format(self.img_dir) ) response = self.client.get("/tests/images/seagull.jpg?fit=500x500x50x10") assert response.status_code == 200 assert response.mimetype == "image/jpeg" comparison = compare_pixels( ref_img_500_500_50_10, Image.open(BytesIO(response.data)), tolerance=10 ) self.assertGreaterEqual(comparison, 0.95) def test_focal_crop_filename_priority(self): # case 2: resize and crop with query parameters and filename focus: filename focus wins ref_img_500_500_10_90 = Image.open( "{}/expected/seagull-500-500-10-90.jpg".format(self.img_dir) ) response = self.client.get( "/tests/images/seagull_focus-10x90.jpg?fit=500x500x50x10" ) assert response.status_code == 200 assert response.mimetype == "image/jpeg" comparison = compare_pixels( ref_img_500_500_10_90, Image.open(BytesIO(response.data)), tolerance=10 ) self.assertGreaterEqual(comparison, 0.95) def test_small_vertical_resize(self): response = self.client.get("tests/images/vertical-line.png.resize.710x399.png") assert response.status_code == 200 assert response.mimetype == "image/png" def test_auto_format_flat_jpeg(self): response = self.client.get("tests/images/test.jpeg?format=auto") assert response.status_code == 200 assert response.mimetype == "image/png" def test_auto_format_complex_transparent_png(self): response = self.client.get("tests/images/transparent_complex.png?format=auto") assert response.status_code == 200 assert response.mimetype == "image/png" def test_transparent_png_with_icc(self): response = self.client.get("tests/images/transparent_complex_with_icc.png") assert response.status_code == 200 assert response.mimetype == "image/png" response_image = Image.open(BytesIO(response.data)) assert has_transparent_background(response_image) def test_auto_format_complex_opaque_png(self): response = self.client.get("tests/images/opaque_with_alpha.png?format=auto") assert response.status_code == 200 assert response.mimetype == "image/jpeg" def test_cache_control_on_200(self): response = self.client.get("tests/images/test.jpeg?format=auto") assert response.status_code == 200 assert response.mimetype == "image/png" assert response.headers["Cache-Control"] == "max-age=31536000" def test_auto_format_complex_jpeg(self): response = self.client.get("tests/images/seagull?format=auto") assert response.status_code == 200 assert response.mimetype == "image/jpeg" def test_icc_profile_converted(self): response = self.client.get("tests/images/jpeg_with_icc_profile.jpg") assert response.status_code == 200 assert response.mimetype == "image/jpeg" actual = Image.open(BytesIO(response.data)) expected = Image.open( self.img_dir / "expected/jpeg_with_icc_profile_target.jpg" ) comparison = compare_pixels(expected, actual) self.assertGreaterEqual(comparison, self.threshold) assert "icc_profile" not
<reponame>liquidinstruments/pymoku import math import logging import warnings from pymoku._instrument import to_reg_unsigned from pymoku._instrument import from_reg_unsigned from pymoku._instrument import to_reg_signed from pymoku._instrument import from_reg_signed from pymoku._instrument import deprecated from pymoku._instrument import MokuInstrument from pymoku._instrument import needs_commit from pymoku._instrument import ValueOutOfRangeException from pymoku._instrument import DAC_SMP_RATE from pymoku import _utils from pymoku._trigger import Trigger from pymoku._sweep_generator import SweepGenerator warnings.simplefilter('always', DeprecationWarning) log = logging.getLogger(__name__) REG_BASE_MOD_0 = 43 REG_BASE_MOD_1 = 60 REG_BASE_WAV_0 = 80 REG_BASE_WAV_1 = 104 REG_GATETHRESH_L_CH1 = 76 REG_GATETHRESH_H_CH1 = 77 REG_GATETHRESH_L_CH2 = 78 REG_GATETHRESH_H_CH2 = 79 _WG_WAVE_SINE = 0 _WG_WAVE_SQUARE = 1 _WG_MOD_NONE = 0 _WG_MOD_AMPL = 1 _WG_MOD_FREQ = 2 _WG_MOD_PHASE = 4 _WG_MODSOURCE_INT = 0 _WG_MODSOURCE_ADC = 1 _WG_MODSOURCE_DAC = 2 _WG_FREQSCALE = 1.0e9 / 2**64 _WG_FREQSCALE_SQR = 1.0e9 / 2**48 _WG_PERIODSCALE_SQR = 2**48 - 1 _WG_RISESCALE = 2**24 _WG_MAX_RISE = 1.0 / (2 ** 39 - 1) _WG_TIMESCALE = 1.0 / (2**32 - 1) # Doesn't wrap _WG_MOD_FREQ_MAX = 62.5e6 _WG_MOD_DEPTH_MAX = 2.0 ** 31 - 1 # 100% modulation depth in bits _WG_TRIG_ADC1 = 0 _WG_TRIG_ADC2 = 1 _WG_TRIG_DAC1 = 2 _WG_TRIG_DAC2 = 3 _WG_TRIG_EXT = 4 _WG_TRIG_INTER = 5 _WG_MOD_ADC1 = 0 _WG_MOD_ADC2 = 1 _WG_MOD_DAC1 = 2 _WG_MOD_DAC2 = 3 _WG_MOD_INTER = 4 _WG_MOD_GATE = 5 _WG_GATE_ADC = 0 _WG_GATE_DAC = 1 _WG_GATE_SWEEP = 2 _WG_GATE_EXT = 3 _WG_TRIG_MODE_OFF = 0 _WG_TRIG_MODE_GATE = 1 _WG_TRIG_MODE_START = 2 _WG_TRIG_MODE_NCYCLE = 3 _WG_TRIG_MODE_SWEEP = 4 _WG_TRIGLVL_ADC_MAX = 5.0 _WG_TRIGLVL_ADC_MIN = -5.0 _WG_TRIGLVL_DAC_MAX = 1.0 _WG_TRIGLVL_DAC_MIN = -1.0 class BasicWaveformGenerator(MokuInstrument): """ .. automethod:: pymoku.instruments.WaveformGenerator.__init__ """ def __init__(self): """ Create a new WaveformGenerator instance, ready to be attached to a Moku.""" super(BasicWaveformGenerator, self).__init__() self._register_accessors(_wavegen_reg_handlers) self.id = 4 self.type = "signal_generator" self._sweep1 = SweepGenerator(self, REG_BASE_WAV_0 + 3) self._sweep2 = SweepGenerator(self, REG_BASE_WAV_1 + 3) self.enable_reset_ch1 = False self.enable_reset_ch2 = False @needs_commit def set_defaults(self): super(BasicWaveformGenerator, self).set_defaults() self.enable_ch1 = True self.enable_ch2 = True self.out1_amplitude = 0 self.out2_amplitude = 0 self.adc1_statuslight = False self.adc2_statuslight = False # Init channel sweep gens: self._set_sweepgenerator(self._sweep1, 0, 0, 0, 0, 0, 0, 0) self._set_sweepgenerator(self._sweep2, 0, 0, 0, 0, 0, 0, 0) # Disable inputs on hardware that supports it self.en_in_ch1 = True self.en_in_ch2 = True # Configure front end: self._set_frontend(channel=1, fiftyr=True, atten=False, ac=False) self._set_frontend(channel=2, fiftyr=True, atten=False, ac=False) def _set_sweepgenerator(self, sweepgen, waveform=None, waitfortrig=None, frequency=None, offset=None, logsweep=None, duration=None, holdlast=None): sweepgen.waveform = 2 sweepgen.stop = (2**64 - 1) sweepgen.direction = 0 if waitfortrig is not None: sweepgen.waitfortrig = waitfortrig if offset is not None: sweepgen.start = offset / 360.0 * (2**64 - 1) if frequency is not None: sweepgen.step = frequency / _WG_FREQSCALE if duration is not None: sweepgen.duration = duration * 125.0e6 if logsweep is not None: sweepgen.logsweep = logsweep if holdlast is not None: sweepgen.holdlast = holdlast @needs_commit def gen_sinewave(self, ch, amplitude, frequency, offset=0, phase=0.0): """ Generate a Sine Wave with the given parameters on the given channel. :type ch: int; {1,2} :param ch: Channel on which to generate the wave :type amplitude: float, [0.0,2.0] Vpp :param amplitude: Waveform peak-to-peak amplitude :type frequency: float, [0,250e6] Hz :param frequency: Frequency of the wave :type offset: float, [-1.0,1.0] Volts :param offset: DC offset applied to the waveform :type phase: float, [0-360] degrees :param phase: Phase offset of the wave """ _utils.check_parameter_valid('set', ch, [1, 2], 'output channel') _utils.check_parameter_valid( 'range', amplitude, [0.0, 2.0], 'sinewave amplitude', 'Volts') _utils.check_parameter_valid( 'range', frequency, [0, 250e6], 'sinewave frequency', 'Hz') _utils.check_parameter_valid( 'range', offset, [-1.0, 1.0], 'sinewave offset', 'Volts') _utils.check_parameter_valid( 'range', phase, [0, 360], 'sinewave phase', 'degrees') # Ensure offset does not cause signal to exceed allowable 2.0Vpp range upper_voltage = offset + (amplitude / 2.0) lower_voltage = offset - (amplitude / 2.0) if (upper_voltage > 1.0) or (lower_voltage < -1.0): raise ValueOutOfRangeException( "Sinewave offset limited by amplitude (max output " "range 2.0Vpp).") if ch == 1: self.enable_ch1 = True self._set_sweepgenerator( sweepgen=self._sweep1, frequency=frequency, offset=phase) self.amplitude_ch1 = amplitude self.offset_ch1 = offset self.waveform_type_ch1 = _WG_WAVE_SINE self.phase_dly_ch1 = (11 * frequency / 125e6) % 1 * 2**32 elif ch == 2: self.enable_ch2 = True self._set_sweepgenerator( sweepgen=self._sweep2, frequency=frequency, offset=phase) self.amplitude_ch2 = amplitude self.offset_ch2 = offset self.waveform_type_ch2 = _WG_WAVE_SINE self.phase_dly_ch2 = (11 * frequency / 125e6) % 1 * 2**32 @needs_commit def gen_squarewave(self, ch, amplitude, frequency, offset=0.0, duty=0.5, risetime=0.0, falltime=0.0, phase=0.0): """ Generate a Square Wave with given parameters on the given channel. :type ch: int; {1,2} :param ch: Channel on which to generate the wave :type amplitude: float, [0, 2.0] volts :param amplitude: Waveform peak-to-peak amplitude :type frequency: float, [0, 100e6] hertz :param frequency: Frequency of the wave :type offset: float, [-1.0, 1.0] volts :param offset: DC offset applied to the waveform :type duty: float, [0, 1.0] :param duty: Fractional duty cycle :type risetime: float, [0, 1.0] :param risetime: Fraction of a cycle taken for the waveform to rise :type falltime: float [0, 1.0] :param falltime: Fraction of a cycle taken for the waveform to fall :type phase: float, degrees 0-360 :param phase: Phase offset of the wave """ _utils.check_parameter_valid('set', ch, [1, 2], 'output channel') _utils.check_parameter_valid( 'range', amplitude, [0.0, 2.0], 'squarewave amplitude', 'Volts') _utils.check_parameter_valid( 'range', frequency, [0, 100e6], 'squarewave frequency', 'Hz') _utils.check_parameter_valid( 'range', offset, [-1.0, 1.0], 'squarewave offset', 'Volts') _utils.check_parameter_valid( 'range', duty, [0, 1.0], 'squarewave duty', 'cycles') _utils.check_parameter_valid( 'range', risetime, [0, 1.0], 'squarewave risetime', 'cycles') _utils.check_parameter_valid( 'range', falltime, [0, 1.0], 'squarewave falltime', 'cycles') _utils.check_parameter_valid( 'range', phase, [0, 360], 'squarewave phase', 'degrees') # Ensure offset does not cause signal to exceed allowable 2.0Vpp range upper_voltage = offset + (amplitude / 2.0) lower_voltage = offset - (amplitude / 2.0) if (upper_voltage > 1.0) or (lower_voltage < -1.0): raise ValueOutOfRangeException( "Squarewave offset limited by amplitude (max output " "range 2.0Vpp).") frequency = float(frequency) if duty < risetime: raise ValueOutOfRangeException( "Squarewave duty too small for given rise time.") elif duty + falltime > 1: raise ValueOutOfRangeException( "Squarewave duty and fall time too big.") # ensure duty cycle and fall/rise time combinations don't overflow if frequency != 0: minedgetime = 4.0e-9 * frequency if risetime < minedgetime: risetime = minedgetime log.warning( "WARNING: Risetime restricted to minimum value of 4 ns.") if falltime < minedgetime: falltime = minedgetime log.warning( "WARNING: Falltime restricted to minimum value of 4 ns.") if duty < minedgetime: duty = minedgetime log.warning("WARNING: Duty cycle restricted to %s" % duty) if duty > 1 - minedgetime: duty = 1 - minedgetime log.warning("WARNING: Duty cycle restricted to %s" % duty) if risetime > 1 - minedgetime: risetime = 1 - minedgetime log.warning("WARNING: Risetime restricted to maximum value.") if falltime > 1 - minedgetime: falltime = 1 - minedgetime log.warning("WARNING: Falltime restricted to maximum value.") else: falltime = _WG_MAX_RISE risetime = _WG_MAX_RISE # Set rise/fall rate and t0, t1 and t2 t0 = risetime t1 = duty t2 = duty + falltime phase_dly = 0 if ch == 1: self.waveform_type_ch1 = _WG_WAVE_SQUARE self.enable_ch1 = True self._set_sweepgenerator(sweepgen=self._sweep1, frequency=frequency, offset=phase, holdlast=0) self.amplitude_ch1 = amplitude self.offset_ch1 = offset # This is overdefined, but saves the FPGA doing a tricky division self.t0_ch1 = t0 self.t1_ch1 = t1 self.t2_ch1 = t2 self.riserate_ch1 = risetime self.fallrate_ch1 = -falltime self.phase_dly_ch1 = phase_dly elif ch == 2: self.waveform_type_ch2 = _WG_WAVE_SQUARE self.enable_ch2 = True self._set_sweepgenerator(sweepgen=self._sweep2, frequency=frequency, offset=phase, holdlast=0) self.amplitude_ch2 = amplitude self.offset_ch2 = offset self.t0_ch2 = t0 self.t1_ch2 = t1 self.t2_ch2 = t2 self.riserate_ch2 = risetime self.fallrate_ch2 = -falltime self.phase_dly_ch2 = phase_dly @needs_commit def gen_rampwave( self, ch, amplitude, frequency, offset=0, symmetry=0.5, phase=0.0): """ Generate a Ramp with the given parameters on the given channel. This is a wrapper around the Square Wave generator, using the *riserate* and *fallrate* parameters to form the ramp. :type ch: int; {1,2} :param ch: Channel on which to generate the wave :type amplitude: float, [0, 2.0] volts :param amplitude: Waveform peak-to-peak amplitude :type frequency: float, [0, 100e6] hertz :param frequency: Frequency of the wave :type offset: float, [-1.0, 1.0] volts :param offset: DC offset applied to the waveform :type symmetry: float, [0, 1.0] :param symmetry: Fraction of the cycle rising. :type phase: float, degrees [0, 360] :param phase: Phase offset of the wave """ _utils.check_parameter_valid('set', ch, [1, 2], 'output channel') _utils.check_parameter_valid( 'range', amplitude, [0.0, 2.0], 'rampwave amplitude', 'Volts') _utils.check_parameter_valid( 'range', frequency, [0, 100e6], 'rampwave frequency', 'Hz') _utils.check_parameter_valid( 'range', offset, [-1.0, 1.0], 'rampwave offset', 'cycles') _utils.check_parameter_valid( 'range', symmetry, [0, 1.0], 'rampwave symmetry', 'fraction') _utils.check_parameter_valid( 'range', phase, [0, 360], 'rampwave phase', 'degrees') # Ensure offset does not cause signal to exceed allowable 2.0Vpp range
<reponame>AlexanderGolys/Drawing_cellar<gh_stars>0 import turtle as tt import random from abc import ABC, abstractmethod from enum import Enum, auto import math class Color: """ Class containing constant colors or random generators for colors used in program. """ cellar_background_color = (0xD3, 0xD3, 0xD3) white = (0xFF, 0xFF, 0xFF) black = (0, 0, 0) dark_gray = (0xA2, 0xA2, 0xA2) yellow = (0xFF, 0xE5, 0x7C) @staticmethod def random_color(): """ Picks random color from whole RGB palette. Return: tuple[int]: R, G and B chanel """ return random.randint(0, 0xFF), random.randint(0, 0xFF), random.randint(0, 0xFF) @staticmethod def random_gray(): """ Picks randomly gray color with every chanel having the same value from <0xCC, 0xFF> Return: tuple[int]: R, G and B chanel """ value = random.randint(0xDD, 0xFF) return value, value, value @staticmethod def random_beer_color(): """ Picks color for the beer's bottle. It returns in 50% slightly random variation of dark green, and in 50% slightly random variation of brown. Return: tuple[int]: R, G and B chanel """ coin = random.randint(0, 1) if coin == 0: return random.randint(0, 0x10), random.randint(0x70, 0x90), random.randint(0, 0x10) return random.randint(0x49, 0x69), random.randint(0x2C, 0x4C), random.randint(0, 0x2F) class GlobalSetup: """ Class containing global constants. """ # angles used to correctly position the turtle during drawing. up_angle = 0 down_angle = 180 left_angle = 90 right_angle = 270 window_shape = (1600, 900) # (width, height) w, h = window_shape padding = { "left": int(.15 * w), "right": int(.15 * w), "top": int(.15 * h), "bottom": int(.15 * h) } rack_thickness = 5 real_h = h - padding["top"] - padding["bottom"] real_w = w - padding["left"] - padding["right"] # values based on pure empirical experience gain during testing min_number_of_shelves = max(real_h//90, 3) max_number_of_shelves = max(real_h//40, 3) min_number_of_racks = max(real_w//250, 2) max_number_of_racks = max(real_w//100, 2) n_racks_threshold = (min_number_of_racks + max_number_of_racks)//2 n_racks = random.randint(min_number_of_racks, max_number_of_racks) # if there are more than some racks (denoted as n_racks_threshold) racks, items on the shelves appears too small, # and i there are less than some racks, small items look great, so item's size # is picked conditionally. # values based on pure empirical experience gain during testing if n_racks < n_racks_threshold: max_item_width = .18 min_item_width = .08 else: max_item_width = .27 min_item_width = .12 def __init__(self): """ Getting screen resolution. First method with PIL works only on Windows and MacOS. It wasn't tested, cause I work on Linux. Second method works on Linux only. It was tested and worked on my Fedora 31. Solutions are based on code from StackOverflow and blog.pythonlibrary.org with some modifications """ try: from PIL import ImageGrab img = ImageGrab.grab() self.screen_width, self.screen_height = img.size except: try: import subprocess cmd = ['xrandr'] cmd2 = ['grep', '*'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) p2 = subprocess.Popen(cmd2, stdin=p.stdout, stdout=subprocess.PIPE) p.stdout.close() resolution_string, junk = p2.communicate() resolution = resolution_string.split()[0] width, height = str(resolution).split('x') self.screen_width = int(width[2:]) self.screen_height = int(height[:-1]) except: self.screen_height = None self.screen_width = None class Coords: """ Class managing coordinates and changing them from middle screen to left bottom corner Attributes: coords (tuple[int]): coordinates from left-bottom corner x (int): x coordinate y (int): y coordinate """ def __init__(self, x, y): """ Args: x (int): width, x y (int): height, y """ self.coords = (x - GlobalSetup.window_shape[0] // 2, y - GlobalSetup.window_shape[1] // 2) self.x = self.coords[0] self.y = self.coords[1] def undo_shift(self): """ In case of adding coordinates, double shift from the centered is created. This method deletes it. Should be used in every case of adding two Coords objects. """ self.coords = (self.coords[0] + GlobalSetup.window_shape[0] // 2, self.coords[1] + GlobalSetup.window_shape[1] // 2) self.x = self.coords[0] self.y = self.coords[1] return self def __add__(self, other): """ Args: other (Coords): coordinate to add stored as Coords object. Return: Coords: Coords object after adding. Requires shifting before using!! """ return Coords(self.x + other.x, self.y + other.y) def add_unbiased(self, other): """ Args: other (tuple[int]): coordinate to add stored as tuple[int]. Return: Coords: Coords object after adding. Requires shifting before using!! """ return Coords(self.x + other[0], self.y + other[1]) class DrawingMethods: """ Set of methods drawing different shapes. """ @staticmethod def draw_rectangle(starting_coords: Coords, shape, bg_color, pen_color): """ Args: starting_coords (tuple of int): coords of left-bottom coords shape (tuple of int): tuple of width and height (width, height) bg_color: background color pen_color: pen color Warning: this method is not changing the turtle's settings to original (angle, color etc.) Using method from this class after performing this operation is perfectly fine. Using other drawing methods may require additional setting the turtle at the beginning. """ tt.up() tt.setpos(starting_coords.coords) tt.setheading(GlobalSetup.up_angle) tt.fillcolor(bg_color) tt.pencolor(pen_color) tt.begin_fill() tt.down() w, h = shape tt.forward(h) tt.right(90) tt.forward(w) tt.right(90) tt.forward(h) tt.setpos(starting_coords.coords) tt.end_fill() tt.update() @staticmethod def draw_triangle(starting_coords, length, bg_color, pen_color): """ This method perform drawing the equilateral triangle staying at the ground. Args: starting_coords (tuple of int): coords of left-bottom coords length (int): length of one side. bg_color: background color pen_color: pen color Warning: this method is not changing the turtle's settings to original (angle, color etc.) Using method from this class after performing this operation is perfectly fine. Using other drawing methods may require additional setting the turtle at the beginning. """ tt.up() tt.setpos(starting_coords.coords) tt.setheading(30) tt.fillcolor(bg_color) tt.pencolor(pen_color) tt.begin_fill() tt.down() tt.forward(length) tt.right(120) tt.forward(length) tt.right(120) tt.forward(length) tt.end_fill() tt.update() @staticmethod def draw_bottle(starting_coords, w, h, bg_color, pen_color): """ This method is drawing the bottle shape. Args: starting_coords (tuple of int): coords of left-bottom coords w (int): width h (int): height bg_color: background color pen_color: pen color Warning: this method is not changing the turtle's settings to original (angle, color etc.) Using method from this class after performing this operation is perfectly fine. Using other drawing methods may require additional setting the turtle at the beginning. """ tt.up() start_x, start_y = starting_coords.coords tt.setpos(starting_coords.coords) tt.setheading(GlobalSetup.up_angle) tt.fillcolor(bg_color) tt.pencolor(pen_color) tt.begin_fill() tt.down() tt.setpos(start_x, start_y + h//2) tt.setpos(start_x + w//3, start_y + h//2 + w//3) tt.setpos(start_x + w//3, start_y + 11 * h//12) tt.setpos(start_x + 2 * w//3, start_y + 11 * h//12) tt.setpos(start_x + 2 * w//3, start_y + h//2 + w//3) tt.setpos(start_x + w, start_y + h//2) tt.setpos(start_x + w, start_y) tt.setpos(starting_coords.coords) tt.end_fill() tt.update() class Screen: """ Describe basic image parameters. Attributes: pad (dict): Padding in pixels (keys: "left", "right", "top", "bottom") n_racks (int): Number of racks. racks (list of Rack objects): Racks on the picture. joint_rack_w (int): width of drawn image (joint width of all racks) """ def __init__(self, pad=GlobalSetup.padding): """ Args: pad (dict or None): List of padding values. If None, padding being 15% of w/h each side is created. Argument is optional (None by default). Raises: ValueError: width or height are bigger than screen resolution or less than 1. ValueError: padding values are to high and there is no space for racks TypeError: width or height are not integers """ gs = GlobalSetup() w, h = GlobalSetup.window_shape if not isinstance(h, int) or not isinstance(w, int): raise TypeError("Width and height must be integers.") if gs.screen_width is not None and gs.screen_height is not None: if h > gs.screen_height or w > gs.screen_width: raise ValueError("Window resolution cannot be bigger than screen resolution") self.height = h self.width = w self.n_racks = GlobalSetup.n_racks if pad is None: # creating default padding from 15% of w/h each side self.pad = { "left": int(.15 * w), "right": int(.15 * w), "top": int(.15 * h), "bottom": int(.15 * h) } else: self.pad = pad self.joint_rack_w = w - self.pad["left"] - self.pad["right"] # width of whole block of racks rack_w = self.joint_rack_w // self.n_racks # width of one rack self.rack_h = h - self.pad["top"] - self.pad["bottom"] # height of one rack if rack_w < 1 or self.rack_h < 1: raise ValueError("Paddings are too big.") # generating racks self.racks = [] coords = [self.pad["left"], self.pad["bottom"]] for _ in range(self.n_racks): self.racks.append(Rack(w=rack_w, h=self.rack_h, coords=coords)) coords = (coords[0] + rack_w, coords[1]) def setup(self): """ Basic initial setting """ tt.setup(self.width, self.height) tt.title("Dreamy cellar during pandemic") # tt.tracer(0, 0) tt.mode("logo") tt.colormode(255) tt.speed(10) def draw(self): """ Draw background and all racks on the screen. """ tt.hideturtle()
member value of dist # and a member value of id. Choose the one that has the smallest dist # If there is a close alternative, also within max_dist but with residue # number much closer to all the others in a group, take that one instead # This is to try and go along a chain and not jump unless necessary. # ca_dict[cb].append(group_args( # dist=dist, # id = ca, # resname_id = ca_residue_names[id2], # resname of ca atom # index_id = id2, #index of ca atom # other_resname_id = cb_residue_names[index_cb], # name of cb atom # other_index_id = index_cb, # index of cb atob for key in dd.keys(): groups = dd[key] best_group = None for group in groups: if (max_dist is not None) and (group.dist > max_dist): continue if best_group is None or group.dist < best_group.dist: best_group = group dd[key] = best_group # Now remove any duplicate id's target_id = self.duplicate_id(dd) while target_id: duplicate_list = [] for key in dd.keys(): if dd[key] and dd[key].id == target_id: duplicate_list.append(key) assert duplicate_list best_key = None for key in duplicate_list: if not best_key or dd[key].dist < dd[best_key].dist: best_key = key for key in duplicate_list: if key != best_key: dd[key] = None target_id = self.duplicate_id(dd) return group_args( dd = dd, ) def duplicate_id(self,dd): id_list = [] for key in dd.keys(): if dd[key]: id = dd[key].id if not id in id_list: id_list.append(id) else: return id return None def match_cb_to_ca(self, ca_sites=None, cb_as_list = None, ca_residue_names = None, cb_residue_names = None, max_dist = 2.,): ''' Identify cb sites that match ca sites If ca_residue_names and cb_residue names, require that residue names match ''' cb_dict = {} ca_dict = {} if not ca_residue_names: ca_residue_names = ca_sites.size() * ['CA'] if not cb_residue_names: cb_residue_names = len(cb_as_list) * ['CA'] for index_cb in range(len(cb_as_list)): cb = cb_as_list[index_cb] if cb is not None and cb != (-9999, -9999, -9999): cb_sites = flex.vec3_double() cb_sites.append(cb) dist, id1, id2 = cb_sites.min_distance_between_any_pair_with_id( ca_sites) ca = ca_sites[id2] if not (ca in cb_dict.keys()): cb_dict[ca] = [] if ca_residue_names[id2] != cb_residue_names[index_cb]: dist = 1.e+30 # do not match them cb_dict[ca].append( group_args( dist=dist, id=cb, resname_id = cb_residue_names[index_cb], # name of cb atom index_id = index_cb, # index of cb atob other_resname_id = ca_residue_names[id2], # resname of ca atom other_index_id = id2, #index of ca atom )) if not cb in ca_dict.keys(): ca_dict[cb] = [] ca_dict[cb].append(group_args( dist=dist, id = ca, resname_id = ca_residue_names[id2], # resname of ca atom index_id = id2, #index of ca atom other_resname_id = cb_residue_names[index_cb], # name of cb atom other_index_id = index_cb, # index of cb atob )) cb_dict_info = self.choose_best_set(cb_dict, max_dist = max_dist) ca_dict_info = self.choose_best_set(ca_dict, max_dist = max_dist) cb_dict = cb_dict_info.dd ca_dict = ca_dict_info.dd cb_as_list = [] # Make a list of all the ca_dict positions and the matching (or missing) # item from cb if not ca_residue_names: ca_residue_names = [None]*ca_sites.size() for ca,ca_resname in zip(ca_sites, ca_residue_names): group = cb_dict.get(ca) if group: cb_as_list.append(group.id) assert (not ca_resname) or (ca_resname == group.resname_id and ca_resname == group.other_resname_id) else: cb_as_list.append(None) return group_args( cb_as_list = cb_as_list, ) def propagate_model_from_other(self, other, model_id = 'model', other_model_id = 'model'): ''' Import a model from other with get_model_from_other (other_model_id), then set coordinates of corresponding atoms in model_id The model in other must have been extracted from the model in this object or one just like it with select_unique_by_ncs=True, and no atoms can have been added or removed. ''' if not self.model(): return # nothing to do # Get the imported hierarchy, shifted to match location of working one ph_imported_unique = self.get_model_from_other(other, other_model_id = other_model_id).get_hierarchy() # Get unique part of working hierarchy. Note this is not a deep_copy, # so modifying it changes original hierarchy and can be propagated model = self.get_model_by_id(model_id) model.search_for_ncs() ph_working_unique = model.get_master_hierarchy() assert ph_imported_unique.is_similar_hierarchy( ph_working_unique) # hierarchies must match # Replace the coordinates in ph_working_unique with ph_imported_unique new_coords=ph_imported_unique.atoms().extract_xyz() ph_working_unique.atoms().set_xyz(new_coords) # And propagate these sites to rest of molecule with internal ncs model.set_sites_cart_from_hierarchy(multiply_ncs=True) def add_crystal_symmetry_to_model_if_necessary(self, model, map_manager = None): ''' Take any model and add crystal symmetry if it is missing Changes model in place Parameters: model Also add unit_cell_crystal_symmetry if missing ''' if not model: return if not map_manager: map_manager = self.any_map_manager() assert map_manager is not None assert isinstance(model, mmtbx.model.manager) if (not model.crystal_symmetry()) or ( not model.crystal_symmetry().unit_cell()): map_manager.set_model_symmetries_and_shift_cart_to_match_map(model) def shift_any_model_to_match(self, model, map_manager = None): ''' Take any model and shift it to match the working shift_cart Also sets crystal_symmetry. Changes model in place Parameters: model ''' if not model: return assert isinstance(model, mmtbx.model.manager) if not map_manager: map_manager = self.get_any_map_manager() assert map_manager is not None self.add_crystal_symmetry_to_model_if_necessary( model, map_manager = map_manager) if not model.shift_cart(): model.set_shift_cart((0, 0, 0)) coordinate_shift = tuple( [s - o for s,o in zip(map_manager.shift_cart(),model.shift_cart())]) model.shift_model_and_set_crystal_symmetry( shift_cart = coordinate_shift, crystal_symmetry=map_manager.crystal_symmetry()) def get_model_from_other(self, other, other_model_id = 'model'): ''' Take a model with id other_model_id from other_map_model_manager with any boxing and origin shifts allowed, and put it in the same reference frame as the current model. Used to build up a model from pieces that were worked on in separate boxes. Changes model from other in place Parameters: other: Other map_model_manager containing a model ''' assert isinstance(other, map_model_manager) other_model = other.get_model_by_id(other_model_id) assert other_model is not None # Need model for get_model_from_other other_shift_cart = other_model.shift_cart() other_model.shift_model_back() # removes shift cart (adds -other_shift_cart) other_model.set_crystal_symmetry(self.crystal_symmetry()) other_model.set_unit_cell_crystal_symmetry(self.unit_cell_crystal_symmetry()) other_model.shift_model_and_set_crystal_symmetry( shift_cart = self.shift_cart()) return other_model # Methods to create a new map_model_manager with different sampling def as_map_model_manager_with_resampled_maps(self, sampling_ratio = 2): ''' Return a new map_model_manager with maps sampled more finely Parameter: sampling_ratio must be an integer Creates new maps, keeps same models ''' n_real = tuple([ int(sampling_ratio *n) for n in self.map_manager().map_data().all()]) map_id = 'map_manager' used_map_id_list = [map_id] fine_mm = self.get_map_manager_by_id(map_id ).resample_on_different_grid(n_real) new_mmm = map_model_manager(map_manager = fine_mm,) for model_id in self.model_id_list(): new_mmm.add_model_by_id(model = self.get_model_by_id(model_id), model_id = model_id) for map_id in self.map_id_list(): if not map_id in used_map_id_list: used_map_id_list.append(map_id) fine_mm = self.get_map_manager_by_id(map_id ).resample_on_different_grid(n_real) new_mmm.add_map_manager_by_id(map_manager = fine_mm, map_id = map_id) return new_mmm # Methods for producing Fourier coefficients and calculating maps def map_as_fourier_coefficients(self, d_min = None, d_max = None, map_id = 'map_manager'): ''' Return Miller array to resolution specified based on map with id map_id Note that the map_manager is always zero-based (origin at (0,0,0)). The Fourier coefficients represent the map in this location at (0, 0, 0) ''' # Checks map_manager = self.get_map_manager_by_id(map_id) assert map_manager is not None return map_manager.map_as_fourier_coefficients( d_min = d_min, d_max = d_max, ) def add_map_from_fourier_coefficients(self, map_coeffs, map_id = 'map_from_fourier_coefficients'): ''' Create map_manager from map_coeffs and add it to maps with map_id The map_coeffs must refer to a map with origin at (0, 0, 0) such as is produced by map_as_fourier_coefficients. ''' # Checks map_manager = self.map_manager() assert map_manager is not None new_map_manager = map_manager.fourier_coefficients_as_map_manager(map_coeffs) self.add_map_manager_by_id(map_manager = new_map_manager, map_id = map_id) def resolution_filter(self, d_min = None, d_max = None, map_id = 'map_manager', new_map_id = 'map_manager', ): ''' Resolution-filter a map with range of d_min to d_max and place in new map (can be the same) Typically used along with duplicate_map_manager to create a new map and filter it: rm.duplicate_map_manager(map_id='map_manager', new_map_id='resolution_filtered') rm.resolution_filter(map_id = 'resolution_filtered',) ''' assert d_min is None or isinstance(d_min, (int,float)) assert d_max is None or isinstance(d_max, (int,float)) assert (d_min,d_max).count(None) < 2 # need some limits map_coeffs = self.map_as_fourier_coefficients(map_id = map_id, d_min = d_min, d_max = d_max) self.add_map_from_fourier_coefficients(map_coeffs, map_id = new_map_id) # Methods for modifying model or map def remove_model_outside_map(self, model = None, boundary = 3, return_as_new_model=False): ''' Remove all the atoms in the model that are well outside the map (more than boundary). Boundary can be negative (remove inside box near edges) ''' assert boundary is not None if not model: model = self.model() if not model: return sites_frac = model.get_sites_frac() bf_a, bf_b, bf_c = model.crystal_symmetry().unit_cell( ).fractionalize((boundary, boundary, boundary)) ub_a, ub_b, ub_c = (1+bf_a, 1+bf_b, 1+bf_c) x,y,z = sites_frac.parts() s = ( (x < -bf_a ) | (y < -bf_b) | (z < -bf_c) | (x > ub_a )
Integer, float, Float)): return False q = Rt(-a * c, S(2)) if NonzeroQ(c * f + g * q): return True return False def replacement1297(a, c, d, e, f, g, x): q = Rt(-a * c, S(2)) return Dist( (c * f + g * q) / (c * d + e * q), Int(S(1) / sqrt(a + c * x ** S(4)), x), x ) + Dist( (-d * g + e * f) / (c * d + e * q), Int((-c * x ** S(2) + q) / (sqrt(a + c * x ** S(4)) * (d + e * x ** S(2))), x), x, ) def replacement1298(a, b, c, d1, d2, e1, e2, n, n2, non2, p, q, x): return Int( (d1 * d2 + e1 * e2 * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ) def replacement1299(a, b, c, d1, d2, e1, e2, n, n2, non2, p, q, x): return Dist( (d1 + e1 * x ** (n / S(2))) ** FracPart(q) * (d2 + e2 * x ** (n / S(2))) ** FracPart(q) * (d1 * d2 + e1 * e2 * x ** n) ** (-FracPart(q)), Int( (d1 * d2 + e1 * e2 * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ), x, ) def replacement1300(A, B, a, b, c, d, e, m, n, n2, p, q, x): return Dist( A, Int((d + e * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x), x, ) + Dist( B, Int( x ** m * (d + e * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ), x, ) def replacement1301(A, B, a, c, d, e, m, n, n2, p, q, x): return Dist( A, Int((a + c * x ** (S(2) * n)) ** p * (d + e * x ** n) ** q, x), x ) + Dist( B, Int(x ** m * (a + c * x ** (S(2) * n)) ** p * (d + e * x ** n) ** q, x), x ) def replacement1302(a, b, c, e, f, m, n, n2, p, q, x): return Dist( e ** (S(1) - (m + S(1)) / n) * f ** m / n, Subst( Int( (e * x) ** (q + S(-1) + (m + S(1)) / n) * (a + b * x + c * x ** S(2)) ** p, x, ), x, x ** n, ), x, ) def replacement1303(a, c, e, f, m, n, n2, p, q, x): return Dist( e ** (S(1) - (m + S(1)) / n) * f ** m / n, Subst( Int((e * x) ** (q + S(-1) + (m + S(1)) / n) * (a + c * x ** S(2)) ** p, x), x, x ** n, ), x, ) def replacement1304(a, b, c, e, f, m, n, n2, p, q, x): return Dist( e ** IntPart(q) * f ** m * x ** (-n * FracPart(q)) * (e * x ** n) ** FracPart(q), Int(x ** (m + n * q) * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x), x, ) def replacement1305(a, c, e, f, m, n, n2, p, q, x): return Dist( e ** IntPart(q) * f ** m * x ** (-n * FracPart(q)) * (e * x ** n) ** FracPart(q), Int(x ** (m + n * q) * (a + c * x ** (S(2) * n)) ** p, x), x, ) def replacement1306(a, b, c, e, f, m, n, n2, p, q, x): return Dist( f ** IntPart(m) * x ** (-FracPart(m)) * (f * x) ** FracPart(m), Int( x ** m * (e * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x ), x, ) def replacement1307(a, c, e, f, m, n, n2, p, q, x): return Dist( f ** IntPart(m) * x ** (-FracPart(m)) * (f * x) ** FracPart(m), Int(x ** m * (e * x ** n) ** q * (a + c * x ** (S(2) * n)) ** p, x), x, ) def replacement1308(a, b, c, d, e, m, n, n2, p, q, x): return Dist( S(1) / n, Subst(Int((d + e * x) ** q * (a + b * x + c * x ** S(2)) ** p, x), x, x ** n), x, ) def replacement1309(a, c, d, e, m, n, n2, p, q, x): return Dist( S(1) / n, Subst(Int((a + c * x ** S(2)) ** p * (d + e * x) ** q, x), x, x ** n), x, ) def replacement1310(a, b, c, d, e, m, n, n2, p, q, x): return Int( x ** (m + n * (S(2) * p + q)) * (d * x ** (-n) + e) ** q * (a * x ** (-S(2) * n) + b * x ** (-n) + c) ** p, x, ) def replacement1311(a, c, d, e, m, n, n2, p, q, x): return Int( x ** (m + n * (S(2) * p + q)) * (a * x ** (-S(2) * n) + c) ** p * (d * x ** (-n) + e) ** q, x, ) def replacement1312(a, b, c, d, e, m, n, n2, p, q, x): return Dist( S(1) / n, Subst( Int( x ** (S(-1) + (m + S(1)) / n) * (d + e * x) ** q * (a + b * x + c * x ** S(2)) ** p, x, ), x, x ** n, ), x, ) def replacement1313(a, b, c, d, e, f, m, n, n2, p, q, x): return Dist( c ** (-IntPart(p)) * (b / S(2) + c * x ** n) ** (-S(2) * FracPart(p)) * (a + b * x ** n + c * x ** (S(2) * n)) ** FracPart(p), Int( (f * x) ** m * (b / S(2) + c * x ** n) ** (S(2) * p) * (d + e * x ** n) ** q, x, ), x, ) def replacement1314(a, b, c, d, e, m, n, n2, p, q, x): return Dist( S(1) / n, Subst( Int( x ** (S(-1) + (m + S(1)) / n) * (d + e * x) ** q * (a + b * x + c * x ** S(2)) ** p, x, ), x, x ** n, ), x, ) def replacement1315(a, c, d, e, m, n, n2, p, q, x): return Dist( S(1) / n, Subst( Int( x ** (S(-1) + (m + S(1)) / n) * (a + c * x ** S(2)) ** p * (d + e * x) ** q, x, ), x, x ** n, ), x, ) def replacement1316(a, b, c, d, e, f, m, n, n2, p, q, x): return Dist( f ** IntPart(m) * x ** (-FracPart(m)) * (f * x) ** FracPart(m), Int( x ** m * (d + e * x ** n) ** q * (a + b * x ** n + c * x ** (S(2) * n)) ** p, x, ), x, ) def replacement1317(a, c, d, e, f, m, n, n2, p, q, x): return Dist( f ** IntPart(m) * x ** (-FracPart(m)) * (f * x) ** FracPart(m), Int(x ** m
import numpy as np from mikecore.DfsFile import DfsProjection, DfsTemporalAxis from mikecore.MeshFile import MeshFile from mikecore.DfsFactory import DfsFactory from mikecore.DfsBuilder import DfsBuilder from mikecore.DfsuFile import DfsuFile, DfsuFileType, DfsSimpleType, DataValueType, DfsuUtil from mikecore.eum import eumUnit, eumQuantity, eumItem #/ <summary> #/ Builder for creating a dfsu file. #/ <para> #/ The following must be set before calling <see cref="CreateFile"/>: #/ <see cref="SetProjection"/>, #/ <see cref="SetTimeInfo"/>, #/ <see cref="SetNodes(double[],double[],float[],int[])"/>, #/ <see cref="SetElements"/>. #/ </para> #/ <para> #/ For files with a vertical dimension, the <see cref="SetNumberOfSigmaLayers"/> must also be set. #/ </para> #/ <para> #/ Other setters are optional, and if not set, default values are written to the file. #/ </para> #/ <para> #/ Using the <see cref="SetFromMeshFile"/> will set the projection, nodes #/ and elements from the mesh file. #/ </para> #/ <para> #/ Be aware; setting the node and element id's to anything but the default #/ values can cause some tools to fail. #/ </para> #/ </summary> class DfsuBuilder: def __init__(self, dfsuFileType): self.__isSetProjection = False self.__isSetTimeInfo = False self.__isSetNodes = False self.__isSetConnectivity = False self.__isSetNumberOfSigmaLayers = False self.__dfsuFileType = dfsuFileType self.__numberOfSigmaLayers = -1 # Projection variables self.__dfsProjection = None # Time variables self.__timeAxis = None self.__startDateTime = None self.__timeStepInSeconds = -1 self.__numberOfTimeSteps = -1 # Node variables self.__nodeIds = None # this can be null, then set default id's, starting from 1 self.__x = None self.__y = None self.__z = None self.__code = None self.__zUnit = eumUnit.eumUmeter self.__zQuantity = None # Element variables self.__connectivity = None self.__elementIds = None # this can be null, then set default id's, starting from 1 # Dynamic item information self.__dynamicItemData = [] self.__dfsuFileType = dfsuFileType if dfsuFileType == DfsuFileType.Dfsu2D: self.FileTitle = "Area Series" elif dfsuFileType == DfsuFileType.DfsuVerticalColumn: self.FileTitle = "Vertical column series" elif dfsuFileType == DfsuFileType.DfsuVerticalProfileSigma: self.FileTitle = "2D vertical profile series" elif dfsuFileType == DfsuFileType.DfsuVerticalProfileSigmaZ: self.FileTitle = "2D vertical profile series" elif dfsuFileType == DfsuFileType.Dfsu3DSigma: self.FileTitle = "3D volume series" elif dfsuFileType == DfsuFileType.Dfsu3DSigmaZ: self.FileTitle = "3D volume series" else: self.FileTitle = "Area Series" self.ApplicationTitle = "" self.ApplicationVersion = 0 def SetProjection(self, projection: DfsProjection): """Set the geographical projection""" if isinstance(projection, DfsProjection): self.__dfsProjection = projection else: raise TypeError("projection must be DfsProjection") self.__isSetProjection = True #/ <summary> #/ Set the number of sigma layers in a file with a vertical dimension #/ </summary> #/ <remarks> #/ If called with a <see cref="DfsuFileType"/> that does not have any #/ vertical dimension, an <see cref="InvalidOperationException"/> is thrown. #/ </remarks> def SetNumberOfSigmaLayers(self, numberOfSigmaLayers: int): if self.__dfsuFileType == DfsuFileType.Dfsu2D: raise Exception("Can not set number of sigma layers on a 2D dfsu file") elif (self.__dfsuFileType == DfsuFileType.DfsuVerticalColumn # strictly speaking not required, but anyway... or self.__dfsuFileType == DfsuFileType.DfsuVerticalProfileSigma or self.__dfsuFileType == DfsuFileType.DfsuVerticalProfileSigmaZ or self.__dfsuFileType == DfsuFileType.Dfsu3DSigma or self.__dfsuFileType == DfsuFileType.Dfsu3DSigmaZ): self.__numberOfSigmaLayers = numberOfSigmaLayers self.__isSetNumberOfSigmaLayers = True else: raise Exception("dfsuFileType") #/ <summary> #/ Set a non-standard temporal axis for the dfsu file. WARNING: The dfsu file will not be valid in all contexts. #/ <para> #/ The standard dfsu file requires an <see cref="IDfsEqCalendarAxis"/> temporal axis. #/ You can use the <see cref="SetTimeInfo"/> method to define a valid <see cref="IDfsEqCalendarAxis"/> #/ axis for the dfsu file. #/ </para> #/ <para> #/ If you define another temporal axis than the <see cref="IDfsEqCalendarAxis"/> for a dfsu file, #/ be sure to test that the file works as intended in your context. #/ </para> #/ </summary> def SetTemporalAxis(self, timeAxis: DfsTemporalAxis): self.__timeAxis = timeAxis self.__isSetTimeInfo = True def SetTimeInfo(self, startDateTime, timeStepInSeconds): """Set time info, specifying an equidistant calendar axis, which is the default (always valid) temporal axis of a dfsu file.""" self.__startDateTime = startDateTime self.__timeStepInSeconds = timeStepInSeconds self.__isSetTimeInfo = True #/ <summary> #/ Sets the number of time steps in the file. #/ <para> #/ This is only required in streaming context, where it is not possible #/ to update the dfs header when everything is written to the file. #/ In a non-streaming context this should not be used. #/ </para> #/ <para> #/ This is a stage 1 method. #/ </para> #/ </summary> def SetNumberOfTimeSteps(self, numberOfTimeSteps: int): self.__numberOfTimeSteps = numberOfTimeSteps def SetNodes(self, x, y, z, code): """Set node coordinates and code. Depending on the projection string, node coordinates are in meters or degrees """ try: x = np.array(x, dtype=np.float64) except: raise TypeError("x must be array of float") try: y = np.array(y, dtype=np.float64) except: raise TypeError("y must be array of float") try: z = np.array(z, dtype=np.float32) except: raise TypeError("z must be array of float") try: code = np.array(code, dtype=np.int32) except: raise TypeError("code must be array of int") numberOfNodes = len(x) if (numberOfNodes != len(y) or numberOfNodes != len(z) or numberOfNodes != len(code)): raise Exception("All arguments must have same length. Lengths are: x={x}, y={y}, z={z}, code={code}".format(x=x.size, y=y.size, z=z.size, code=code.size)) if (self.__nodeIds != None and numberOfNodes != len(self.__nodeIds)): raise Exception("Arguments does not have same length as the number of node ids. These must match") self.__x = x self.__y = y self.__z = z self.__code = code self.__isSetNodes = True #/ <inheritdoc/> def SetZUnit(self, zUnit: eumUnit): # TODO: Fix! if (zUnit != eumUnit.eumUmeter and zUnit != eumUnit.eumUfeet and zUnit != eumUnit.eumUUnitUndefined): raise Exception("Currently only meter and feet unit is supported") self.__zUnit = zUnit #if (EUMWrapper.eumUnitsEqv(eumUnit.eumUmeter, zUnit)): # self.__zUnit = zUnit #else: # raise Exception("Unit of z coordinate is not a length unit") def SetNodeIds(self, nodeIds): """Set the node id's. Optional. If not set, default values are used (1,2,3,...)""" if (nodeIds is None): self.__nodeIds = None return if (self.__x != None and self.__x.size != nodeIds.size): raise Exception("Number of node id's does not match number of nodes", "nodeIds") self.__nodeIds = nodeIds def SetElements(self, connectivity): """Set element connectivity: For each element is specified which nodes the element consist of. The node is specified by its index into the list of nodes. """ if (connectivity is None): raise Exception("connectivity") if (len(connectivity) == 0): raise Exception("Element table has no rows. There must be at least one row") if (self.__elementIds != None and self.__elementIds.size != len(connectivity)): raise Exception("Number of elements is not the same as number of element ids. They must match") # Validate that element numbers are ok. if self.__dfsuFileType == DfsuFileType.Dfsu2D: # Check number of elements for i in range(len(connectivity)): elmnt = connectivity[i] if (3 > len(elmnt) or len(elmnt) > 4): raise Exception("All elements must have 3 or 4 nodes. Element number {id} has {size} nodes".format(id=i+1,size=len(elmnt))) elif self.__dfsuFileType == DfsuFileType.Dfsu3DSigma: # Check number of elements for i in range(len(connectivity)): elmnt = connectivity[i] if (len(elmnt) != 6 and len(elmnt) != 8): raise Exception("All elements must have 6 or 8 nodes. Element number {id} has {size} nodes".format(id=i+1,size=len(elmnt))) self.__connectivity = connectivity self.__isSetConnectivity = True def SetElementIds(self, elementIds): """Set the element id's. Optional. If not set, default values are used (1,2,3,...)""" if (self.__connectivity is not None) and (len(self.__connectivity) != elementIds.size): raise Exception("Number of element id's does not match number of elements", "elementIds") def SetFromMeshFile(self, meshFile: MeshFile): """Set projection, nodes and elements from mesh file. This is equivalent to calling SetProjection, SetNodes, SetElements """ self.__dfsProjection = DfsProjection.Create(meshFile.ProjectionString) self.__isSetProjection = True self.__nodeIds = meshFile.NodeIds self.__x = meshFile.X self.__y = meshFile.Y self.__z = meshFile.Z.astype(dtype=np.float32) self.__code = meshFile.Code self.__zUnit = meshFile.EumQuantity.Unit self.__isSetNodes = True self.__elementIds = meshFile.ElementIds self.__connectivity = meshFile.ElementTable self.__isSetConnectivity = True def AddDynamicItem(self, itemName: str, quantity): """Add a dynamic item. """ self.__dynamicItemData.append((itemName, quantity)) def Validate(self, dieOnError: bool = False): """Validate will return a string of issues from the item builder. When this returns an empty list, the item has been properly build. """ errors = [] if (not self.__isSetProjection): errors.append("Projection has not been set") if (not self.__isSetTimeInfo): errors.append("Time information has not been set") if (not self.__isSetNodes): errors.append("Nodes have not been set") if (not self.__isSetConnectivity): errors.append("Elements have not been set") if (not self.__isSetNumberOfSigmaLayers and self.__dfsuFileType != DfsuFileType.Dfsu2D): errors.append("Number of sigma layers has not been set") # Check that all nodenumbers are within the range of # number of nodes. check =
<gh_stars>1-10 #!/usr/bin/env python # Copyright 2021 Citrix Systems, Inc. All rights reserved. # Use of this software is governed by the license terms, if any, # which accompany or are included with this software. import re import logging from collections import OrderedDict import nspepi_common as common """ Parse tree implementation Example: Assume you had the command at line 123: add responder action foo respondwith "HTTP/1.1 403 Forbidden\r\n\r\n" -comment "My comment" then you would get the following parse tree (note: when generating a new parse tree that is a replacement for something in ns.conf you can just pass '' for the original text): CLICommand ('add', 'responder', 'action') | CLIPositionalParameter ('foo') | CLIPositionalParameter ('respondwith') | CLIPositionalParameter ('"HTTP/1.1 403 Forbidden\r\n\r\n"') | CLIKeywordParameter | CLIKeywordName ('comment') [note no '-'] | CLIKeywordValue ('My comment') This tree can be created by the following code: cmd = CLICommand('add', 'responder', 'action') # Note the 'quoted' parameter is defaulted to False below pp = CLIPositionalParameter('foo') cmd.add_positional(pp) pp = CLIPositionalParameter('respondwith') cmd.add_positional(pp) pp = CLIPositionalParameter(r'"HTTP/1.1 403 Forbidden\r\n\r\n"') cmd.add_positional(pp) kwn = CLIKeywordName('comment') kwp = CLIKeywordParameter(kwn) # Note the 'quoted' parameter to CLIKeywordValue is defaulted to False kwp.add_value('My comment') cmd.add_keyword(kwp) """ class CLIParseTreeNode(object): """ A CLI parse tree node """ must_quote_chars = re.compile('[ \t\r\n"\'\\\\()]') must_escape_chars = "\t\r\n\"\\" qquote_delims = "/{<|~$^+=&%@`?" def __init__(self): """ Create a CLI parse tree node object """ pass def normalize(self, val, make_str=False): """ Normalizes the string representation for an item in a CLI command so that it will correctly be understood by the CLI. val - the string value to normalize. make_str - to normalize when special characters are needed in string. Returns the normalized string. """ # Only uses double quotes if any quoting is needed. # This may put in quotes in some cases where they are not actually # needed. result = val str_len = len(val) if str_len == 0: result = '""' else: if (make_str or val[0] == '-' or val[0] == '#' or (val[0] == 'q' and str_len > 1 and val[1] in self.qquote_delims) or self.must_quote_chars.search(val)): result = '"' for ch in val: if ch in self.must_escape_chars: if ch == '\t': result += '\\t' elif ch == '\r': result += '\\r' elif ch == '\n': result += '\\n' else: result += '\\' + ch else: result += ch result += '"' return result class CLICommand(CLIParseTreeNode): """ A CLI configuration command """ def __init__(self, op, group, ot): """ Create a CLI command object upgraded - Indicates whether the command is upgraded or not adv_upgraded - In many places of the code, upgraded flag is used to determine if original policy is classic or advanced. If upgraded is true, then original policy is considered to be classic. But advanced policies can have SYS.EVAL_CLASSIC_EXPR, which needs to be converted as well. Here original policy is advanced but need to set upgrade flag after conversion. adv_upgraded should be used in such cases instead of upgraded. invalid - Indicates whether the command is invalid in 13.1 release. original_line - the text of the line that was parsed lineno - the line number (starting with 1) that the command occurs on op - the op-code for the command group - the group for the command ot - the object type """ self._upgraded = True self._adv_upgraded = True self._invalid = False self._original_line = "" self._lineno = 0 self._op = op self._group = group self._ot = ot self._positionals = [] self._keywords = OrderedDict() super(CLICommand, self).__init__() logging.debug('CLICommand created: op=' + op + ', group=' + group + ', ot=' + ot) def get_command_type(self): return [self._op, self._group, self._ot] @property def lineno(self): return self._lineno @lineno.setter def lineno(self, lineno): self._lineno = lineno logging.debug('CLICommand lineno set: ' + str(lineno)) @property def original_line(self): return self._original_line @original_line.setter def original_line(self, original_line): self._original_line = original_line self._upgraded = False self._adv_upgraded = False logging.debug('CLICommand original_line set: ' + original_line + ', upgraded set to False') @property def op(self): return self._op @op.setter def op(self, op): self._op = op logging.debug('CLICommand ot set: ' + op) @property def group(self): return self._group @group.setter def group(self, group): self._group = group logging.debug('CLICommand ot set: ' + group) @property def ot(self): return self._ot @ot.setter def ot(self, ot): self._ot = ot logging.debug('CLICommand ot set: ' + ot) def set_upgraded(self): """ Flags that this command was upgraded. """ self._upgraded = True logging.debug('CLICommand upgraded flag set') @property def upgraded(self): return self._upgraded def set_adv_upgraded(self): """ Flags that this advanced command was upgraded. """ self._adv_upgraded = True logging.debug('CLICommand adv_upgraded flag set') @property def adv_upgraded(self): return self._adv_upgraded def set_invalid(self): """ Flags that this command is invalid. """ self._invalid = True logging.debug('CLICommand invalid flag set') @property def invalid(self): return self._invalid def add_positional(self, positional_param): """ Adds a positional parameter at the end of the parameters. positional_param - the node containing the value of the parameter """ assert isinstance(positional_param, CLIPositionalParameter) self._positionals.append(positional_param) logging.debug('CLICommand positional parameter added: ' + str(positional_param)) def add_positional_list(self, positional_params): """ Adds a list of positional parameters. positional_params - a list of nodes containing the parameter values """ for pos in positional_params: assert isinstance(pos, CLIPositionalParameter) self._positionals.append(pos) logging.debug('CLICommand positional parameter added: ' + str(pos)) def remove_positional(self, inx): """ Removes the given positional parameter. NOTE: once a positional parameter is removed the following positional parameters' indexes are decremented by 1. inx - the (zero-based) index of the positional parameter. """ assert inx < len(self._positionals) and inx >= 0 del self._positionals[inx] self._upgraded = True logging.debug('CLICommand positional parameter removed at index: ' + str(inx)) def add_keyword(self, keyword_param): """ Adds a keyword parameter at the end of the parameters. keyword_param - the keyword parameter node to add """ assert isinstance(keyword_param, CLIKeywordParameter) self._keywords[keyword_param.name.name] = keyword_param logging.debug('CLICommand keyword parameter added: ' + str(keyword_param)) def add_keyword_list(self, keyword_params): """ Adds a list of keyword parameters. keyword_params - a list of keyword parameter nodes to add """ for kw in keyword_params: assert isinstance(kw, CLIKeywordParameter) self._keywords[kw.name.name] = kw logging.debug('CLICommand keyword parameter added: ' + str(kw)) def remove_keyword(self, name): """ Removes the given keyword parameter. name - the name of the keyword (without the "-") """ assert name in self._keywords del self._keywords[name] self._upgraded = True logging.debug('CLICommand keyword parameter removed with key: ' + str(name)) def remove_keyword_value(self, name, inx): """ Some keywords will have multiple values. This method removes a particular keyword value given by index inx in given keyword. name - the name of the keyword (without the "-") inx - the (zero-based) index of the keyword value. NOTE: once a keyword value is removed the following keyword values indexes are decremented by 1. """ assert name in self._keywords keyword_param = self._keywords[name] assert inx < len(keyword_param.values) and inx >= 0 del keyword_param.values[inx] self._upgraded = True logging.debug('CLICommand keyword parameter value removed at index: ' + str(inx) + " with key: " + str(name)) def keyword_exists(self, name): """ Determine whether the given keyword existins for this command. name - the name of the keyword (without the "-") Returns true iff the keyword exists for this command. """ return name in self._keywords def keyword_parameter(self, name): """ Gets the keyword parameter for the given keyword. name - the name of the keyword (without the "-") Returns the parameter or None if the keyword does not exist in this command. """ return self._keywords.get(name) def keyword_value(self, name): """ Gets the keyword value for the given keyword. name - the name of the keyword (without the "-") Returns the value or None if the keyword does not exist in this command. """ result = self._keywords.get(name) if result is not None: result = result.values return result def positional_value(self, inx): """ Gets the given positional parameter. inx - the (zero-based) index of the positional parameter. Returns the value or None if no such positional parameter exists. """ result = None if inx < len(self._positionals) and inx >= 0: result = self._positionals[inx] return result def get_number_of_params(self): """ Gets the number of parameters. """ no_of_params = len(self._positionals) + len(self._keywords) return no_of_params def __str__(self): """ Creates a readable string representation of the CLI node. Returns the string representation. """ if not (self._upgraded
''' 本模块储存着常用算符和积分方法 调用模块中的算符时应注意: 1、算符作用的多元函数的自变量需为列表(list、tuple、ndarray均可,下同) 2、算符作用的标量函数的输出值需为单个值 3、算符作用的矢量函数的输出值需为列表 This module stores the common operators and integration method When calling operators in the module, pay attention to: 1. The argument of the multivariate function acted by the operators should be list (list, tuple, ndarray, the same below) 2. The output value of scalar function acted by the operators should be a single value 3. The output value of vector function acted by the operators should be list ''' import numpy as np from scipy import constants as C from maysics.utils import grid_net from matplotlib import pyplot as plt def lim(f, x0, acc=0.01, method='both'): ''' 求极限 lim x→x0+ f(x) ≈ f(x+dx) lim x→x0- f(x) ≈ f(x-dx) lim x→x0 f(x) ≈ (f(x+dx) + f(x-dx)) / 2 参数 ---- f:函数类型 x0:取极限的点 acc:浮点数类型,可选,极限精度,即dx,默认为0.01 method:字符串类型,求极限方法,可选'both'、'rigth'或'+'(右极限)、'left'或'-'(左极限) Calculate the limit values lim x→x0+ f(x) ≈ f(x+dx) lim x→x0- f(x) ≈ f(x-dx) lim x→x0 f(x) ≈ (f(x+dx) + f(x-dx)) / 2 Parameters ---------- f: function x0: point of limit acc: float, callable, the accuracy of calculation, equals to dx, default=0.01 method: str, the method of calculation, 'both', 'right' or '+'(right limit), 'left' or '-'(left limit) are optional ''' if method == 'both': func1 = f(x0 + acc) func2 = f(x0 - acc) return 0.5 * (func1 + func2) elif method == '+' or method == 'right': return f(x0 + acc) elif method == '-' or method == 'left': return f(x0 - acc) else: raise Exception("Parameter 'method' must be one of 'both', 'right', '+', 'left', '-'.") def ha(f, m, U, acc=0.1): ''' 哈密顿算符:ha = - ħ**2 / 2m * ▽**2 + U 参数 ---- f:函数 m:数,粒子质量 U:数或函数,势能 acc:浮点数类型,可选,求导的精度,默认为0.1 返回 ---- 函数 Hamilton: ha = - ħ**2 / 2m * ▽**2 + U Parameters ---------- f: function m: num, the mass of the particle U: num or function, potential energy acc: float, callable, accuracy of derivation, default=0.1 Return ------ function ''' def obj(x): x = np.array(x, dtype=float) result = 0 for i in range(len(x)): func1 = 2 * f(x) x[i] += acc func2 = f(x) x[i] -= 2 * acc func3 = f(x) x[i] += acc de = (func2 + func3 - 2 * func1) / acc**2 result += de result *= (C.h / (2 * np.pi))**2 / (2 * m) if type(U).__name__ == 'function': result += U(x) * f(x) else: result += U * f(x) return result return obj def grad(f, x, acc=0.1): ''' 求标量函数梯度:▽f(x) 参数 ---- f:函数,要求函数f返回一个数值 x:数或数组,函数的输入值,不支持批量输入 acc:浮点数类型,可选,求导的精度,默认为0.1 返回 ---- 梯度函数值 ▽f(x) gradient of scalar function: ▽f(x) Parameters ---------- f: function, the function should return a number x: num or array, the input of the function, batch input is not supported acc: float, callable, accuracy of derivation, default=0.1 Return ------ value of gradient function ▽f(x) ''' x = np.array(x, dtype=float) d_list = [] acc2 = 0.5 * acc if len(x.shape) == 0: x += acc2 func1 = f(x) x -= acc func2 = f(x) x += acc2 d_list = (func1 - func2) / (acc) elif len(x.shape) == 1: for i in range(x.shape[0]): x[i] += acc2 func1 = f(x) x[i] -= acc func2 = f(x) de = (func1 - func2) / (acc) x[i] += acc2 d_list.append(de) d_list = np.array(d_list) elif len(x.shape) == 2: for i in range(x.shape[1]): x[0][i] += acc2 func1 = f(x) x[0][i] -= acc func2 = f(x) de = (np.array([func1]).T - np.array([func2]).T) / (acc) x[0][i] += acc2 d_list.append(de) d_list = [d_list] d_list = np.array(d_list) return d_list def nebla_dot(f, x, acc=0.1): ''' ▽点乘矢量函数:▽·f(x) 参数 ---- f:函数,要求函数f返回一个列表 x:数或数组,函数的输入值,不支持批量输入 acc:浮点数类型,可选,求导的精度,默认为0.1 返回 ---- 函数值 ▽·f(x) dot product between ▽ and vector function: ▽·f(x) Parameter --------- f: function, the function should return a list x: num or array, the input of the function, batch input is not supported acc: float, callable, accuracy of derivation, default=0.1 Return ------ value of function ▽·f(x) ''' x = np.array(x, dtype=float) result = [] if len(x.shape) == 1: for i in range(x.shape[0]): x[i] += acc * 0.5 func1 = f(x)[i] x[i] -= acc func2 = f(x)[i] x[i] += acc * 0.5 de = (func1 - func2) / acc result.append(de) else: for i in range(x.shape[1]): x[0][i] += acc * 0.5 func1 = f(x)[0][i] x[0][i] -= acc func2 = f(x)[0][i] x[0][i] += acc * 0.5 de = (func1 - func2) / acc result.append(de) result = [result] result = np.array(result) return result def _diff2forc(f, x, a, b, acc): if len(x.shape) == 1: x[b] += acc * 0.5 func1 = f(x)[a] x[b] -= acc func2 = f(x)[a] x[b] += acc * 0.5 de = (func1 - func2) / acc else: x[0][b] += acc * 0.5 func1 = f(x)[0][a] x[0][b] -= acc func2 = f(x)[0][a] x[0][b] += acc * 0.5 de = (func1 - func2) / acc return de def nebla_cross(f, x, acc=0.1): ''' ▽叉乘矢量函数:▽×f(x) 参数 ---- f:函数,要求函数是三维矢量函数 x:数或数组,函数的输入值,不支持批量输入 acc:浮点数类型,可选,求导的精度,默认为0.1 返回 ---- 函数值 ▽×f(x) ▽ cross vector function: ▽×f(x) Parameter --------- f: function, the function should be a three-dimension vector function x: num or array, the input of the function, batch input is not supported acc: float, callable, accuracy of derivation, default=0.1 Return ------ value of function ▽×f(x) ''' x = np.array(x, dtype=float) result = np.array([ _diff2forc(f, x, 2, 1, acc) -\ _diff2forc(f, x, 1, 2, acc), _diff2forc(f, x, 0, 2, acc) -\ _diff2forc(f, x, 2, 0, acc), _diff2forc(f, x, 1, 0, acc) -\ _diff2forc(f, x, 0, 1, acc)]) return result def laplace(f, x, acc=0.1): ''' △算子 = ▽**2 被作用函数的自变量x是列表 参数 ---- f:函数 x:一维数组或二维数组 acc:浮点数类型,可选,求导的精度,默认为0.1 返回 ---- 函数值△f(x) Laplace operator: △ = ▽**2 the argument x of the affected function should be a list Parameter --------- f: function x: 1-D or 2-D array acc: float, callable, accuracy of derivation, default=0.1 Return ------ value of function △f(x) ''' x = np.array(x, dtype=float) result = 0 if len(x.shape) == 1: for i in range(x.shape[0]): func1 = 2 * f(x) x[i] += acc func2 = f(x) x[i] -= 2 * acc func3 = f(x) x[i] += acc de = (func2 + func3 - func1) / acc**2 result += de else: for i in range(x.shape[1]): func1 = 2 * f(x) x[:, i] += acc func2 = f(x) x[:, i] -= 2 * acc func3 = f(x) x[:, i] += acc de = (func2 + func3 - func1) / acc**2 result += de return result def _mc_fit(func, condition, random_state, area, dim, args, param, loop, height): ''' 蒙特卡洛法积分 MonteCarlo method ''' np.random.seed(random_state) area = np.array(area) area_length = area[:, 1] - area[:, 0] V = area_length.prod() * height num = len(area_length) area_points = np.random.rand(loop, num) * area_length + area[:, 0] func_points = np.random.rand(loop) * height effect_points = 0 if dim == 1: if not condition: for i in range(loop): if func_points[i] <= func(area_points[i], **args): effect_points += 1 else: for i in range(loop): if func_points[i] <= func(area_points[i], **args) and condition(area_points[i], **param): effect_points += 1 elif dim == 2: func_points_2 = func(area_points, **args) if not condition: for i in range(loop): if func_points[i] <= func_points_2[i]: effect_points += 1 else: for i in range(loop): if func_points[i] <= func_points_2[i] and condition(area_points[i], **param): effect_points += 1 else: raise Exception("Parameter 'dim' must be one of 1 and 2.") effect_points_rate = effect_points / loop return V * effect_points_rate def _rect_fit(func, condition, area, dim, args, param, acc): ''' 矩形法积分 Rectangle method ''' dv = acc.prod() points_net = [] for i in range(len(area)): points_net.append(np.arange(area[i][0], area[i][1], acc[i])) points_net = grid_net(*points_net) if dim == 1: func_points=[] if not condition: for i in points_net: func_points.append(func(i, **args)) else: for i in points_net: if condition(i, **param): func_points.append(func(i, **args)) func_points = np.array(func_points) * dv elif dim == 2: points_net = points_net.tolist() if condition: for i in points_net[:]: if not condition(i, **param): points_net.remove(i) points_net = np.array(points_net) func_points = func(points_net, **args) *
True, seed: int = None) -> None: """ g = activation function z = w.T @ a_previous + b a = g(z) """ if seed: np.random.seed(seed) self.units = units # logger.info(f"Units per Layer: {self.units}") self.n_layers = len(self.units) activations = ['linear' if activation_str is None else activation_str for activation_str in activations] self.activation = [getattr(self, activation_str) for activation_str in activations] self.activation_derivative = [getattr(self, f"{activation_str}_derivative") for activation_str in activations] self.loss_functions = [getattr(self, loss_function) for loss_function in loss_functions] self.loss_function_derivatives = [getattr(self, f"{loss_function}_derivative") for loss_function in loss_functions] self.initialize_weights(symmetric_weights) def initialize_weights(self, symmetric_weights: bool): if symmetric_weights: self.biases = [np.random.randn(y, 1) for y in self.units[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(self.units[:-1], self.units[1:])] else: self.biases = [np.random.rand(y, 1) for y in self.units[1:]] self.weights = [np.random.rand(y, x) for x, y in zip(self.units[:-1], self.units[1:])] # logger.info(f"Shapes of biases: {[bias.shape for bias in self.biases]}") # logger.info(f"Shapes of weights: {[weights.shape for weights in self.weights]}") def train(self, data: np.ndarray, one_hot_y: np.ndarray, batch_size: int = 1, lr: float = 0.01, momentum: float = 0.0, max_epochs: int = 1000, early_stopping: Dict = None, shuffle: bool = False, regularization_param: float = 0.0, debug: Dict = None, save_data: bool = False, min_epoch: int = 1) -> Tuple[List, List, List]: # Set Default values if not debug: debug = {'epochs': 10 ** 10, 'batches': 10 ** 10, 'ff': False, 'bp': False, 'w': False, 'metrics': False} # Lists to gather accuracies and losses accuracies = [] losses = [] times = [] # --- Train Loop --- # # data_x, _ = self.x_y_split(data) data_x = data try: for epoch in range(min_epoch, max_epochs + 1): if epoch % debug['epochs'] == 0: logger.info(f"Epoch: {epoch}", color="red") show_epoch = True else: show_epoch = False epoch_timeit = timeit(internal_only=True) with epoch_timeit: # Shuffle if shuffle: shuffle_idx = np.random.permutation(data_x.shape[0]) data_x = data_x[shuffle_idx, :] one_hot_y = one_hot_y[shuffle_idx, :] # Create Mini-Batches train_batches = [(data_x[k:k + batch_size], one_hot_y[k:k + batch_size]) for k in range(0, data_x.shape[0], batch_size)] # Run mini-batches for batch_ind, (x_batch, one_hot_y_batch) in enumerate(train_batches): batch_ind += 1 if show_epoch and batch_ind % debug['batches'] == 0: logger.info(f" Batch: {batch_ind}", color='yellow') self.run_batch(batch_x=x_batch, batch_y=one_hot_y_batch, lr=lr, momentum=momentum, regularization_param=regularization_param, debug=debug) # Calculate Batch Accuracy and Losses if show_epoch and batch_ind % debug['batches'] == 0: accuracy, _ = self.accuracy(data_x, one_hot_y, debug) batch_losses = self.total_loss(data_x, one_hot_y, regularization_param, debug) self.print_stats(batch_losses, accuracy, data_x.shape[0], ' ') epoch_time = epoch_timeit.total # Gather Results times.append(epoch_time) accuracy, _ = self.accuracy(data_x, one_hot_y, debug) epoch_losses = self.total_loss(data_x, one_hot_y, regularization_param, debug) accuracies.append(accuracy / data_x.shape[0]) losses.append(epoch_losses) if save_data: self.save_model(epoch, accuracies, losses, times) # Calculate Epoch Accuracy and Losses if show_epoch: self.print_stats(epoch_losses, accuracy, data_x.shape[0], ' ') if early_stopping: if 'max_accuracy' in early_stopping and epoch > early_stopping['wait']: recent_accuracy = accuracies[-1] if recent_accuracy >= early_stopping['max_accuracy']: logger.info(f"Early stopping (Max acc): " f"{recent_accuracy} = {early_stopping['max_accuracy']}", color='yellow') break if 'accuracy' in early_stopping and epoch > early_stopping['wait']: recent_accuracy = accuracies[-1] * data_x.shape[0] previous_accuracy = accuracies[-2] * data_x.shape[0] if recent_accuracy - previous_accuracy < early_stopping['accuracy']: logger.info(f"Early stopping (acc): {recent_accuracy}-{previous_accuracy}" f" = {(recent_accuracy - previous_accuracy)} < " f"{early_stopping['accuracy']}", color='yellow') break if 'loss' in early_stopping and epoch > early_stopping['wait']: if losses[-1][0][1] - losses[-2][0][1] < early_stopping['loss']: print(losses[-1][0][1], losses[-2][0][1]) logger.info(f"Early stopping (loss): " f"{losses[-1][0][1]:5f}-{losses[-2][0][1]:5f} = " f"{(losses[-1][0][1] - losses[-2][0][1]):5f} < " f"{early_stopping['loss']}", color='yellow') break except KeyboardInterrupt: logger.warn(f"Forcefully stopped after epoch {epoch - 1}") if len(accuracies) > 0: logger.info(f"Finished after {epoch} epochs", color='red') logger.info(f"Avg epoch time: {sum(times) / len(times):.4f} sec(s)", color='yellow') logger.info(f"Accumulated epoch time: {sum(times):.4f} sec(s)", color='yellow') self.print_stats(epoch_losses, accuracy, data_x.shape[0], '') return accuracies, losses, times def test(self, data: np.ndarray, one_hot_y: np.ndarray, debug: Dict = None) \ -> Tuple[float, np.ndarray]: if not debug: debug = {'epochs': 10 ** 10, 'batches': 10 ** 10, 'ff': False, 'bp': False, 'w': False, 'metrics': False} # data_x, _ = self.x_y_split(data) data_x = data accuracy, predictions = self.accuracy(data_x, one_hot_y, debug) accuracy /= data_x.shape[0] return accuracy, predictions @staticmethod def print_stats(losses, accuracy, size, padding): for loss_type, loss in losses: logger.info(f"{padding}{loss_type} Loss: {loss:.5f}") logger.info(f"{padding}Accuracy: {accuracy}/{size}") def run_batch(self, batch_x: np.ndarray, batch_y: np.ndarray, lr: float, momentum: float, regularization_param: float, debug: Dict): for batch_iter, (row_x, row_y) in enumerate(zip(batch_x, batch_y)): row_x, row_y = row_x[np.newaxis, :], row_y[:, np.newaxis] z, a = self.feed_forward(row_x, debug) dw_, db_ = self.back_propagation(row_y, z, a, debug) if batch_iter == 0: dw = dw_ db = db_ else: dw = list(map(np.add, dw, dw_)) db = list(map(np.add, db, db_)) self.update_weights_and_biases(dw, db, lr, momentum, batch_iter + 1, regularization_param, debug) def feed_forward(self, batch_x: np.ndarray, debug: Dict = None) -> \ Tuple[List[np.ndarray], List[np.ndarray]]: if debug is None: debug = {'ff': False} z_ = batch_x.T z = [z_] a_ = z_ a = [a_] for l_ind, layer_units in enumerate(self.units[1:]): z_ = self.weights[l_ind] @ a_ + self.biases[l_ind] # a_ -> a_previous z.append(z_) a_ = self.activation[l_ind](z_) a.append(a_) if debug['ff']: if l_ind == 0: logger.info(" Feed Forward", color="cyan") logger.info(f" Layer: {l_ind}, units: {layer_units}", color="magenta") logger.info(f" z{z_.T} = w[{l_ind}]{self.weights[l_ind]} @ a_ + " f"b[{l_ind}]{self.biases[l_ind].T}") logger.info(f" a{a_.T} = g[{l_ind}](z{z_.T})") return z, a def back_propagation(self, batch_y: np.ndarray, z: List[np.ndarray], a: List[np.ndarray], debug: Dict) -> Tuple[List[np.ndarray], List[np.ndarray]]: db = [] dw = [] # Calculate back propagation input which is da of last layer da = self.loss_function_derivatives[0](z[-1], a[-1], batch_y) for l_ind, layer_units in list(enumerate(self.units))[-1:0:-1]: # layers: last->2nd g_prime = self.activation_derivative[l_ind - 1](z[l_ind]) try: dz = da * g_prime except Exception as e: print("l_ind: ", l_ind) print("layer_units: ", layer_units) print("da: ", da) print("g_prime: ", g_prime) raise e db_ = dz dw_ = dz @ a[l_ind - 1].T da = self.weights[l_ind - 1].T @ dz # To be used in the next iteration (previous layer) db.append(db_) dw.append(dw_) if debug['bp']: if layer_units == self.units[-1]: logger.info(" Back Propagation", color="cyan") logger.info(f" Layer: {l_ind}, units: {layer_units}", color="magenta") logger.info(f" g_prime{g_prime.shape} = activation_derivative[{l_ind - 1}]" f"(z[{l_ind}]{z[l_ind].shape})" f"{self.activation_derivative[l_ind - 1](z[l_ind]).shape} =\n" f"\t\t\t\t\t\t\t{g_prime.T}") logger.info(f" dz{dz.shape} = da{da.shape} * g_prime{g_prime.shape}") logger.info(f" db{db_.shape} = dz{dz.shape}") logger.info(f" dw = dz{dz.shape} @ a[{l_ind - 1}]{a[l_ind - 1].shape}") logger.info(f" da{da.shape} = self.weights[{l_ind - 1}].T" f"{self.weights[l_ind - 1].T.shape} @ dz{dz.shape} = \n" f"\t\t\t\t\t\t\t{da.T}") dw.reverse() db.reverse() return dw, db def update_weights_and_biases(self, dw: List[np.ndarray], db: List[np.ndarray], lr: float, momentum: float, batch_size: int, regularization_param: float, debug: Dict) -> None: for l_ind, layer_units in enumerate(self.units[:-1]): # self.weights[l_ind] -= (lr / batch_size) * dw[l_ind] self.weights[l_ind] = (1 - lr * (regularization_param / batch_size)) * self.weights[ l_ind] - (lr / batch_size) * dw[l_ind] + momentum * self.weights[l_ind] self.biases[l_ind] -= (lr / batch_size) * db[l_ind] if debug['w']: if l_ind == 0: logger.info(" Update Weights", color="cyan") logger.info(f" Layer: {l_ind}, units: {layer_units}", color="magenta") logger.info(f" w({self.weights[l_ind].shape}) -= " f"({lr}/{batch_size}) * dw({dw[l_ind].shape}") logger.info(f" b({self.weights[l_ind].shape}) -= " f"({lr}/{batch_size}) * db({db[l_ind].shape}") def save_model(self, epoch, accuracies, losses, times): self.save_pickle(var=self, path=f'data/bpnn/model_train_{epoch}.pickle') self.save_pickle(var=accuracies, path=f'data/bpnn/accuracies_train_{epoch}.pickle') self.save_pickle(var=losses, path=f'data/bpnn/losses_train_{epoch}.pickle') self.save_pickle(var=times, path=f'data/bpnn/times_train_{epoch}.pickle') @staticmethod def save_pickle(var: Any, path: str): with open(path, 'wb') as handle: pickle.dump(var, handle, protocol=pickle.HIGHEST_PROTOCOL) @classmethod def load_model_instance(cls, epoch: int): model = cls.load_pickle(f'data/bpnn/model_train_{epoch}.pickle') accuracies = cls.load_pickle(f'data/bpnn/accuracies_train_{epoch}.pickle') losses = cls.load_pickle(f'data/bpnn/losses_train_{epoch}.pickle') times = cls.load_pickle(f'data/bpnn/times_train_{epoch}.pickle') return model, accuracies, losses, times @staticmethod def load_pickle(path: str) -> Any: with open(path, 'rb') as handle: var = pickle.load(handle) return var @staticmethod def linear(z): return z linear_derivative = linear @staticmethod def sigmoid(z): """The sigmoid function.""" z = np.clip(z, -500, 500) # Handle np.exp overflow a = 1.0 / (1.0 + np.exp(-z)) return a @classmethod def sigmoid_derivative(cls, a): """Derivative of the sigmoid function.""" return cls.sigmoid(a) * (1 - cls.sigmoid(a)) @staticmethod def relu(z): return np.maximum(0.0, z).astype(z.dtype) @staticmethod def relu_derivative(a): return (a > 0).astype(a.dtype) @staticmethod def tanh(z): """ Should use different loss. """ return np.tanh(z) @staticmethod def tanh_derivative(a): """ Should use different loss. """ return 1 - a ** 2 @staticmethod def softmax(z): # y = np.exp(z - np.max(z)) # a = y / np.sum(np.exp(z)) from scipy.special import softmax a = softmax(z) return a softmax_derivative = sigmoid_derivative @staticmethod def classify(y: np.ndarray) -> np.ndarray: total = y.shape[0] prediction = np.zeros(total) prediction[y.argmax()] = prediction[y.argmax()] = 1 return prediction def predict(self, x: Iterable[np.ndarray], debug: bool = False) -> \ Tuple[List[np.ndarray], List[np.ndarray]]: y_predicted = [] y_raw_predictions = [] for x_row in x: if debug: logger.info(f" x_row: {x_row[:20].T}", color='white') x_row = x_row[np.newaxis, :] z, a = self.feed_forward(x_row) prediction_raw = a[-1] prediction = self.classify(prediction_raw) if debug: logger.info(f" prediction_raw: {prediction_raw.T}") logger.info(f" prediction:
self.trans[char] = u"ping" for char in u"坡泼颇婆破魄迫粕剖": self.trans[char] = u"po" for char in u"扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑濮": self.trans[char] = u"pu" for char in u"期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫": self.trans[char] = u"qi" for char in u"掐恰洽": self.trans[char] = u"qia" for char in u"牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉": self.trans[char] = u"qian" for char in u"枪呛腔羌墙蔷强抢": self.trans[char] = u"qiang" for char in u"橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍": self.trans[char] = u"qiao" for char in u"切茄且怯窃": self.trans[char] = u"qie" for char in u"钦侵亲秦琴勤芹擒禽寝沁": self.trans[char] = u"qin" for char in u"青轻氢倾卿清擎晴氰情顷请庆": self.trans[char] = u"qing" for char in u"琼穷": self.trans[char] = u"qiong" for char in u"秋丘邱球求囚酋泅": self.trans[char] = u"qiu" for char in u"趋区蛆曲躯屈驱渠取娶龋趣去": self.trans[char] = u"qu" for char in u"圈颧权醛泉全痊拳犬券劝": self.trans[char] = u"quan" for char in u"缺炔瘸却鹊榷确雀": self.trans[char] = u"que" for char in u"裙群": self.trans[char] = u"qun" for char in u"然燃冉染": self.trans[char] = u"ran" for char in u"瓤壤攘嚷让": self.trans[char] = u"rang" for char in u"饶扰绕": self.trans[char] = u"rao" for char in u"惹热": self.trans[char] = u"re" for char in u"壬仁人忍韧任认刃妊纫": self.trans[char] = u"ren" for char in u"扔仍": self.trans[char] = u"reng" for char in u"日": self.trans[char] = u"ri" for char in u"戎茸蓉荣融熔溶容绒冗": self.trans[char] = u"rong" for char in u"揉柔肉": self.trans[char] = u"rou" for char in u"茹蠕儒孺如辱乳汝入褥": self.trans[char] = u"ru" for char in u"软阮": self.trans[char] = u"ruan" for char in u"蕊瑞锐": self.trans[char] = u"rui" for char in u"闰润": self.trans[char] = u"run" for char in u"若弱": self.trans[char] = u"ruo" for char in u"撒洒萨": self.trans[char] = u"sa" for char in u"腮鳃塞赛": self.trans[char] = u"sai" for char in u"三叁伞散": self.trans[char] = u"san" for char in u"桑嗓丧": self.trans[char] = u"sang" for char in u"搔骚扫嫂": self.trans[char] = u"sao" for char in u"瑟色涩": self.trans[char] = u"se" for char in u"森": self.trans[char] = u"sen" for char in u"僧": self.trans[char] = u"seng" for char in u"莎砂杀刹沙纱傻啥煞": self.trans[char] = u"sha" for char in u"筛晒": self.trans[char] = u"shai" for char in u"珊苫杉山删煽衫闪陕擅赡膳善汕扇缮": self.trans[char] = u"shan" for char in u"墒伤商赏晌上尚裳": self.trans[char] = u"shang" for char in u"梢捎稍烧芍勺韶少哨邵绍": self.trans[char] = u"shao" for char in u"奢赊蛇舌舍赦摄射慑涉社设": self.trans[char] = u"she" for char in u"砷申呻伸身深娠绅神沈审婶甚肾慎渗": self.trans[char] = u"shen" for char in u"声生甥牲升绳省盛剩胜圣": self.trans[char] = u"sheng" for char in u"师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试": self.trans[char] = u"shi" for char in u"收手首守寿授售受瘦兽": self.trans[char] = u"shou" for char in u"蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱恕": self.trans[char] = u"shu" for char in u"刷耍": self.trans[char] = u"shua" for char in u"摔衰甩帅": self.trans[char] = u"shuai" for char in u"栓拴": self.trans[char] = u"shuan" for char in u"霜双爽": self.trans[char] = u"shuang" for char in u"谁水睡税": self.trans[char] = u"shui" for char in u"吮瞬顺舜": self.trans[char] = u"shun" for char in u"说硕朔烁": self.trans[char] = u"shuo" for char in u"斯撕嘶思私司丝死肆寺嗣四伺似饲巳": self.trans[char] = u"si" for char in u"松耸怂颂送宋讼诵": self.trans[char] = u"song" for char in u"搜艘擞": self.trans[char] = u"sou" for char in u"嗽苏酥俗素速粟僳塑溯宿诉肃": self.trans[char] = u"su" for char in u"酸蒜算": self.trans[char] = u"suan" for char in u"虽隋随绥髓碎岁穗遂隧祟": self.trans[char] = u"sui" for char in u"孙损笋": self.trans[char] = u"sun" for char in u"蓑梭唆缩琐索锁所": self.trans[char] = u"suo" for char in u"塌他它她塔獭挞蹋踏": self.trans[char] = u"ta" for char in u"胎苔抬台泰酞太态汰": self.trans[char] = u"tai" for char in u"坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭": self.trans[char] = u"tan" for char in u"汤塘搪堂棠膛唐糖倘躺淌趟烫": self.trans[char] = u"tang" for char in u"掏涛滔绦萄桃逃淘陶讨套": self.trans[char] = u"tao" for char in u"特": self.trans[char] = u"te" for char in u"藤腾疼誊": self.trans[char] = u"teng" for char in u"梯剔踢锑提题蹄啼体替嚏惕涕剃屉": self.trans[char] = u"ti" for char in u"兲天添填田甜恬舔腆": self.trans[char] = u"tian" for char in u"挑条迢眺跳": self.trans[char] = u"tiao" for char in u"贴铁帖": self.trans[char] = u"tie" for char in u"厅听烃汀廷停亭庭挺艇": self.trans[char] = u"ting" for char in u"通桐酮瞳同铜彤童桶捅筒统痛": self.trans[char] = u"tong" for char in u"偷投头透": self.trans[char] = u"tou" for char in u"凸秃突图徒途涂屠土吐兔": self.trans[char] = u"tu" for char in u"湍团": self.trans[char] = u"tuan" for char in u"推颓腿蜕褪退": self.trans[char] = u"tui" for char in u"吞屯臀": self.trans[char] = u"tun" for char in u"拖托脱鸵陀驮驼椭妥拓唾": self.trans[char] = u"tuo" for char in u"挖哇蛙洼娃瓦袜": self.trans[char] = u"wa" for char in u"歪外": self.trans[char] = u"wai" for char in u"豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕莞": self.trans[char] = u"wan" for char in u"汪王亡枉网往旺望忘妄": self.trans[char] = u"wang" for char in u"威巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫": self.trans[char] = u"wei" for char in u"瘟温蚊文闻纹吻稳紊问": self.trans[char] = u"wen" for char in u"嗡翁瓮": self.trans[char] = u"weng" for char in u"挝蜗涡窝我斡卧握沃": self.trans[char] = u"wo" for char in u"巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误": self.trans[char] = u"wu" for char in u"昔熙析西硒矽晰嘻吸锡牺稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细": self.trans[char] = u"xi" for char in u"瞎虾匣霞辖暇峡侠狭下厦夏吓": self.trans[char] = u"xia" for char in u"掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线": self.trans[char] = u"xian" for char in u"相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象": self.trans[char] = u"xiang" for char in u"萧硝霄削哮嚣销消宵淆晓小孝校肖啸笑效": self.trans[char] = u"xiao" for char in u"楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑": self.trans[char] = u"xie" for char in u"薪芯锌欣辛新忻心信衅": self.trans[char] = u"xin" for char in u"星腥猩惺兴刑型形邢行醒幸杏性姓": self.trans[char] = u"xing" for char in u"兄凶胸匈汹雄熊": self.trans[char] = u"xiong" for char in u"休修羞朽嗅锈秀袖绣": self.trans[char] = u"xiu" for char in u"墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续": self.trans[char] = u"xu" for char in u"轩喧宣悬旋玄选癣眩绚": self.trans[char] = u"xuan" for char in u"靴薛学穴雪血": self.trans[char] = u"xue" for char in u"勋熏循旬询寻驯巡殉汛训讯逊迅": self.trans[char] = u"xun" for char in u"压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶": self.trans[char] = u"ya" for char in u"焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验": self.trans[char] = u"yan" for char in u"殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾": self.trans[char] = u"yang" for char in u"邀腰妖瑶摇尧遥窑谣姚咬舀药要耀": self.trans[char] = u"yao" for char in u"椰噎耶爷野冶也页掖业叶曳腋夜液": self.trans[char] = u"ye" for char in u"一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎": self.trans[char] = u"yi" for char in u"茵荫因殷音阴姻吟银淫寅饮尹引隐印": self.trans[char] = u"yin" for char in u"英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映": self.trans[char] = u"ying" for char in u"哟": self.trans[char] = u"yo" for char in u"拥佣臃痈庸雍踊蛹咏泳涌永恿勇用": self.trans[char] = u"yong" for char in u"幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂": self.trans[char] = u"you" for char in u"淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉浴寓裕预豫驭": self.trans[char] = u"yu" for char in u"鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院": self.trans[char] = u"yuan" for char in u"曰约越跃钥岳粤月悦阅": self.trans[char] = u"yue" for char in u"耘云郧匀陨允运蕴酝晕韵孕": self.trans[char] = u"yun" for char in u"匝砸杂": self.trans[char] = u"za" for char in u"栽哉灾宰载再在": self.trans[char] = u"zai" for char in u"咱攒暂赞": self.trans[char] = u"zan" for char in u"赃脏葬": self.trans[char] = u"zang" for char in u"遭糟凿藻枣早澡蚤躁噪造皂灶燥": self.trans[char] = u"zao" for char in u"责择则泽": self.trans[char] = u"ze" for char in u"贼": self.trans[char] = u"zei" for char in u"怎": self.trans[char] = u"zen" for char in u"增憎曾赠": self.trans[char] = u"zeng" for char in u"扎喳渣札轧铡闸眨栅榨咋乍炸诈": self.trans[char] = u"zha" for char in u"摘斋宅窄债寨": self.trans[char] = u"zhai" for char in u"瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽": self.trans[char] = u"zhan" for char in u"樟章彰漳张掌涨杖丈帐账仗胀瘴障": self.trans[char] = u"zhang" for char in u"招昭找沼赵照罩兆肇召": self.trans[char] = u"zhao" for char in u"遮折哲蛰辙者锗蔗这浙": self.trans[char] = u"zhe" for char in u"珍斟真甄砧臻贞针侦枕疹诊震振镇阵圳": self.trans[char] = u"zhen" for char in u"蒸挣睁征狰争怔整拯正政帧症郑证": self.trans[char] = u"zheng" for char in u"芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒": self.trans[char] = u"zhi" for char in u"中盅忠钟衷终种肿重仲众": self.trans[char] = u"zhong" for char in u"舟周州洲诌粥轴肘帚咒皱宙昼骤": self.trans[char] = u"zhou" for char in u"珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑住注祝驻": self.trans[char] = u"zhu" for char in u"抓爪": self.trans[char] = u"zhua" for char in u"拽": self.trans[char] = u"zhuai" for char in u"专砖转撰赚篆": self.trans[char] = u"zhuan" for char in u"桩庄装妆撞壮状": self.trans[char] = u"zhuang" for char in u"椎锥追赘坠缀": self.trans[char] = u"zhui" for char in u"谆准": self.trans[char] = u"zhun" for char in u"捉拙卓桌琢茁酌啄着灼浊": self.trans[char] = u"zhuo" for char in u"兹咨资姿滋淄孜紫仔籽滓子自渍字": self.trans[char] = u"zi" for char in u"鬃棕踪宗综总纵": self.trans[char] = u"zong" for char in u"邹走奏揍": self.trans[char] = u"zou" for char in u"租足卒族祖诅阻组": self.trans[char] = u"zu" for char in u"钻纂": self.trans[char] = u"zuan" for char in u"嘴醉最罪": self.trans[char] = u"zui" for char in u"尊遵": self.trans[char] = u"zun" for char in u"昨左佐柞做作坐座": self.trans[char] = u"zuo" # from: https://www.wikidata.org/wiki/MediaWiki:Gadget-SimpleTransliterate.js self.trans[u"ଂ"] = "anusvara" self.trans[u"ઇ"] = "i" self.trans[u"എ"] = "e" self.trans[u"ગ"] = "ga" self.trans[u"ਜ"] = "ja" self.trans[u"ഞ"] = "nya" self.trans[u"ଢ"] = "ddha" self.trans[u"ધ"] = "dha" self.trans[u"ਬ"] = "ba" self.trans[u"മ"] = "ma" self.trans[u"ଲ"] = "la" self.trans[u"ષ"] = "ssa" self.trans[u"਼"] = "nukta" self.trans[u"ാ"] = "aa" self.trans[u"ୂ"] = "uu" self.trans[u"ે"] = "e" self.trans[u"ੌ"] = "au" self.trans[u"ൎ"] = "reph" self.trans[u"ੜ"] = "rra" self.trans[u"՞"] = "?" self.trans[u"ୢ"] = "l" self.trans[u"૧"] = "1" self.trans[u"੬"] = "6" self.trans[u"൮"] = "8" self.trans[u"୲"] = "quarter" self.trans[u"ൾ"] = "ll" self.trans[u"ਇ"] = "i" self.trans[u"ഉ"] = "u" self.trans[u"ઌ"] = "l" self.trans[u"ਗ"] = "ga" self.trans[u"ങ"] = "nga" self.trans[u"ଝ"] = "jha" self.trans[u"જ"] = "ja" self.trans[u"؟"] = "?" self.trans[u"ਧ"] = "dha" self.trans[u"ഩ"] = "nnna" self.trans[u"ଭ"] = "bha" self.trans[u"બ"] = "ba" self.trans[u"ഹ"] = "ha" self.trans[u"ଽ"] = "avagraha" self.trans[u"઼"] = "nukta" self.trans[u"ੇ"] = "ee" self.trans[u"୍"] = "virama" self.trans[u"ૌ"] = "au" self.trans[u"੧"] = "1" self.trans[u"൩"] = "3" self.trans[u"୭"] = "7" self.trans[u"૬"] = "6" self.trans[u"൹"] = "mark" self.trans[u"ਖ਼"] = "khha" self.trans[u"ਂ"] = "bindi" self.trans[u"ഈ"] = "ii" self.trans[u"ઍ"] = "e" self.trans[u"ଌ"] = "l" self.trans[u"ഘ"] = "gha" self.trans[u"ઝ"] = "jha" self.trans[u"ଡ଼"] = "rra" self.trans[u"ਢ"] = "ddha" self.trans[u"ന"]
<reponame>ajouellette/critical-shells import os import sys import numpy as np from mpi4py import MPI from astropy.cosmology import FlatLambdaCDM import astropy.units as u import h5py from gadgetutils.snapshot import ParticleData from gadgetutils.utils import sphere_volume, mean_pos_pbc import time profile = False def get_density(pd, center, radius): """Get average enclosed density of a sphere from a ParticleData instance.""" n = pd.query_radius(center, radius, count_only=True) return n * pd.part_mass / sphere_volume(radius, a=pd.a) def find_critical_shell(pd, center, crit_dens, crit_ratio=2, center_tol=1e-3, rcrit_tol=1e-5, maxiters=100, findCOM=True): """Find a critical shell starting from given center. Parameters: pd: a ParticleData instance center: ndarray (1,3) - Initial guess for center of shell crit_dens: float - Critical density of universe crit_ratio: float - Ratio of critical shell density to critical density center_tol: float, optional - Tolerance for center convergence rcrit_tol: float, optional - Tolerance for radius convergence maxiters: int, optional - Maximum number of iterations Returns: center: ndarray (1,3) - Center of shell radius: float - Radius of shell n_parts: int - Number of particles enclosed center_converged: bool density_converged: bool """ center_converged = True if findCOM: radius = 5e-3 center_converged = False # find center of largest substructure for iters in range(1, 20): ind = pd.query_radius(center, radius) if len(ind) == 0: radius += 5e-3 continue new_center = mean_pos_pbc(pd.pos[ind], pd.box_size) if np.linalg.norm(center - new_center) < center_tol: center_converged = True break center = new_center radius += 5e-3 else: iters = 0 # initial bracket for radius of critical shell r_low = 5e-4 r_high = 0.5 density_low = get_density(pd, center, r_low) # potentially need a better lower bound if no particles within initial radius while density_low == 0: r_low += 5e-4 density_low = get_density(pd, center, r_low) density_high = get_density(pd, center, r_high) # check that guess actually brackets root if not (density_low / crit_dens > crit_ratio and density_high / crit_dens < crit_ratio): print("error initial guesses not good enough", (r_low, density_low / crit_dens), (r_high, density_high / crit_dens)) return center, 0, 0, center_converged, False density_converged = False for i in range(iters+1, maxiters): r_mid = (r_low + r_high) / 2 ind = pd.query_radius(center, r_mid) if len(ind) == 0: break # ideally shouldn't happen, some problem with convergence center = mean_pos_pbc(pd.pos[ind], pd.box_size) density_mid = get_density(pd, center, r_mid) if density_mid / crit_dens == crit_ratio: density_converged = True break val_low = density_low / crit_dens - crit_ratio val_mid = density_mid / crit_dens - crit_ratio val_high = density_high / crit_dens - crit_ratio if val_low * val_mid < 0: r_high = r_mid density_high = density_mid elif val_mid * val_high < 0: r_low = r_mid density_low = density_mid else: print("convergence error, this should not happen") return center, r_mid, 0, center_converged, False if (r_high - r_low) / 2 < rcrit_tol: density_converged = True break # number of particles n_parts = pd.query_radius(center, r_mid, count_only=True) return center, r_mid, n_parts, center_converged, density_converged def check_duplicate(centers, radii, center, radius=0, check_dup_len=10): """Check if a shell is a duplicate or contained within another shell.""" for i in range(np.max((0, len(centers) - check_dup_len)), len(centers)): if np.linalg.norm(centers[i] - center) < radii[i] + radius: return i return -1 def print_conv_error(c_conv, d_conv, fof_i, sh_i=0): print("Did not converge ({}, {}):".format(fof_i, sh_i), "center" if not c_conv else '', "density" if not d_conv else '') def print_dup_error(fof_i, sh_i, center, radius): print("Skipping duplicate: fof {}, sh {} ".format(fof_i, sh_i), center, radius) def main(): if profile: import cProfile pr = cProfile.Profile() pr.enable() comm = MPI.COMM_WORLD rank = comm.Get_rank() n_ranks = comm.Get_size() np.random.seed(10) min_n_particles = 10 if len(sys.argv) != 3: if rank == 0: print("Error: need data dir and snapshot number") sys.exit(1) data_dir = sys.argv[1] snap_num = sys.argv[2] snap_file = data_dir + "/snapshot_"+snap_num+".hdf5" fof_file = data_dir + "/fof_subhalo_tab_"+snap_num+".hdf5" if not (os.path.exists(snap_file) and os.path.exists(fof_file)): if rank == 0: print("Error: data files not found") sys.exit(1) if rank == 0: print(f"Using data file {snap_file}") print(f"And FoF group catalog {fof_file}") time_start = time.perf_counter() # load particle data and construct tree of positions pd = ParticleData(snap_file, load_vels=False, make_tree=True) comm.Barrier() time_end = time.perf_counter() if rank == 0: print(f"Time to load data and construct trees {(time_end - time_start)/60:.2f}" + " minutes") print("Memory usage after tree construction:") os.system("free -h") # Use H0 = 100 to factor out h, calculate critical density cosmo = FlatLambdaCDM(H0=100, Om0=pd.OmegaMatter) crit_dens_a100 = cosmo.critical_density(-0.99).to(u.Msun / u.Mpc**3).value # load FoF group data with h5py.File(fof_file) as fof_tab_data: if rank == 0: load = 2000 if profile else fof_tab_data["Header"].attrs["Ngroups_Total"] fof_pos_all = fof_tab_data["Group"]["GroupPos"][:load] fof_sh_num_all = fof_tab_data["Group"]["GroupNsubs"][:load] comm.Barrier() sh_pos = fof_tab_data["Subhalo"]["SubhaloPos"][:] sh_offsets = fof_tab_data["Group"]["GroupFirstSub"][:] if rank == 0: # some debug info print() print(f"a = {pd.a:.2f}") print(f"Critical density at a = 100: {crit_dens_a100:.3e}") print(f"Particle mass: {pd.part_mass:.3e}") print(f"Processing {len(fof_pos_all)} FoF groups on {n_ranks} MPI ranks" + f", {len(fof_pos_all)//n_ranks} per rank") avg, res = divmod(len(fof_pos_all), n_ranks) count = np.array([avg+1 if r < res else avg for r in range(n_ranks)]) displ = np.array([sum(count[:r]) for r in range(n_ranks)]) # randomize data before scattering to make load more even shuffle = np.arange(len(fof_pos_all)) np.random.shuffle(shuffle) else: fof_pos_all = np.empty(0) fof_sh_num_all = np.empty(0) count = np.zeros(n_ranks, dtype=int) displ = 0 shuffle = None comm.Bcast(count, root=0) fof_pos = np.zeros((count[rank], 3), dtype=np.float32) fof_sh_num = np.zeros(count[rank], dtype=np.int32) comm.Scatterv([fof_pos_all[shuffle], 3*count, 3*displ, MPI.FLOAT], fof_pos) comm.Scatterv([fof_sh_num_all[shuffle], count, displ, MPI.INT], fof_sh_num) if rank != 0: shuffle = np.zeros(sum(count), dtype=int) comm.Bcast(shuffle, root=0) radii = [] centers = [] n_parts = [] parents = [] part_ids = np.array([], dtype=int) time_start = time.perf_counter() for i in range(len(fof_pos)): # overall unshuffled index of fof group fof_i = shuffle[sum(count[:rank]) + i] print(f"{rank} Processing FoF group {fof_i}, {fof_sh_num[i]} subgroups") # fof group with no subgroups if fof_sh_num[i] == 0: print("No subgroups, using fof position", fof_i) center_i = fof_pos[i] center, radius, n, c_conv, d_conv = find_critical_shell(pd, center_i, crit_dens_a100) if c_conv and d_conv and n >= min_n_particles: print("Found halo:", center, radius) radii.append(radius) centers.append(center) n_parts.append(n) parents.append([fof_i, 0]) ind = pd.query_radius(center, radius) part_ids = np.hstack((part_ids, pd.ids[ind])) else: print_conv_error(c_conv, d_conv, fof_i) # process subgroups for j in range(fof_sh_num[i]): # overall index of subgroup sh_i = sh_offsets[fof_i] + j center_i = sh_pos[sh_i] # check if initial center is within a sphere already found dup = check_duplicate(centers, radii, center_i, check_dup_len=j) if dup != -1: print_dup_error(fof_i, j, centers[dup], radii[dup]) continue center, radius, n, c_conv, d_conv = find_critical_shell(pd, center_i, crit_dens_a100, findCOM=False) # check if final center is within a sphere already found dup = check_duplicate(centers, radii, center, radius=radius, check_dup_len=j) if dup != -1: print_dup_error(fof_i, j, centers[dup], radii[dup]) continue if c_conv and d_conv and n > min_n_particles: print("Found halo:", center, radius) radii.append(radius) centers.append(center) n_parts.append(n) parents.append([fof_i, sh_i]) ind = pd.query_radius(center, radius) part_ids = np.hstack((part_ids, pd.ids[ind])) else: print_conv_error(c_conv, d_conv, fof_i, sh_i) # TODO: clean up gathering final data centers = np.array(centers, dtype=np.float64) radii = np.array(radii, dtype=np.float64) n_parts = np.array(n_parts) parents = np.array(parents) len_shells = np.array(len(centers)) len_particles = np.array(len(part_ids)) total_length = np.array(0) total_particles = np.array(0) comm.Reduce(len_shells, total_length, op=MPI.SUM, root=0) comm.Reduce(len_particles, total_particles, op=MPI.SUM, root=0) lengths_c = np.array(comm.gather(3 * len_shells, root=0)) lengths_r = np.array(comm.gather(len_shells, root=0)) lengths_p = np.array(comm.gather(2 * len_shells, root=0)) lengths_part = np.array(comm.gather(len_particles, root=0)) displ_c = None displ_r = None displ_p = None displ_part = None all_centers = None all_radii = None all_n_parts = None all_parents = None all_part_ids = None if rank == 0: displ_c = np.array([sum(lengths_c[:r]) for r in range(n_ranks)]) displ_r = np.array([sum(lengths_r[:r]) for r in range(n_ranks)]) displ_p = np.array([sum(lengths_p[:r]) for r in range(n_ranks)]) displ_part = np.array([sum(lengths_part[:r]) for r in range(n_ranks)]) all_centers = np.zeros((total_length, 3)) all_radii = np.zeros(total_length) all_n_parts = np.zeros(total_length, dtype=int) all_parents = np.zeros((total_length, 2), dtype=int) all_part_ids = np.zeros(total_particles, dtype=int) comm.Barrier() time_end = time.perf_counter() # Gather all data together on node 0 comm.Gatherv(centers, [all_centers, lengths_c, displ_c, MPI.DOUBLE], root=0) comm.Gatherv(radii, [all_radii, lengths_r, displ_r, MPI.DOUBLE], root=0) comm.Gatherv(n_parts, [all_n_parts, lengths_r, displ_r, MPI.LONG], root=0) comm.Gatherv(parents, [all_parents, lengths_p, displ_p, MPI.LONG], root=0) comm.Gatherv(part_ids, [all_part_ids, lengths_part, displ_part, MPI.LONG], root=0) if rank == 0: masses = pd.part_mass * all_n_parts print(f"Finished in {(time_end - time_start)/60:.2f} minutes") print(f"{len(all_radii)} critical shells found with more than {min_n_particles}" + " particles") # save data as hdf5 if not profile: catalog_file = data_dir + "-analysis/critical_shells.hdf5" print("Saving filtered catalog to ", catalog_file) with h5py.File(catalog_file, 'w') as f: # attributes f.attrs["Nshells"] = len(all_centers) f.attrs["NparticlesTotal"] = len(all_part_ids) # datasets f.create_dataset("Centers", data=all_centers) f.create_dataset("Radii", data=all_radii) f.create_dataset("Nparticles", data=all_n_parts) f.create_dataset("Masses", data=masses) f.create_dataset("Parents", data=all_parents) f.create_dataset("ParticleIDs", data=all_part_ids) print("Done.") if profile: pr.disable()
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """sub-networks of EPP-MVSNet""" import numpy as np import mindspore import mindspore.ops as P from mindspore import nn from mindspore import Tensor, Parameter from src.modules import depth_regression, soft_argmin, entropy class BasicBlockA(nn.Cell): """BasicBlockA""" def __init__(self, in_channels, out_channels, stride): super(BasicBlockA, self).__init__() self.conv2d_0 = nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1, pad_mode="pad") self.conv2d_1 = nn.Conv2d(in_channels, out_channels, 1, stride=stride, padding=0, pad_mode="valid") self.batchnorm2d_2 = nn.BatchNorm2d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.batchnorm2d_3 = nn.BatchNorm2d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_4 = nn.ReLU() self.conv2d_5 = nn.Conv2d(out_channels, out_channels, 3, stride=1, padding=(1, 1, 1, 1), pad_mode="pad") self.batchnorm2d_6 = nn.BatchNorm2d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_8 = nn.ReLU() def construct(self, x): """construct""" x1 = self.conv2d_0(x) x1 = self.batchnorm2d_2(x1) x1 = self.relu_4(x1) x1 = self.conv2d_5(x1) x1 = self.batchnorm2d_6(x1) res = self.conv2d_1(x) res = self.batchnorm2d_3(res) out = P.Add()(x1, res) out = self.relu_8(out) return out class BasicBlockB(nn.Cell): """BasicBlockB""" def __init__(self, in_channels, out_channels): super(BasicBlockB, self).__init__() self.conv2d_0 = nn.Conv2d(in_channels, out_channels, 3, stride=1, padding=1, pad_mode="pad") self.batchnorm2d_1 = nn.BatchNorm2d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_2 = nn.ReLU() self.conv2d_3 = nn.Conv2d(in_channels, out_channels, 3, stride=1, padding=1, pad_mode="pad") self.batchnorm2d_4 = nn.BatchNorm2d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_6 = nn.ReLU() def construct(self, x): """construct""" x1 = self.conv2d_0(x) x1 = self.batchnorm2d_1(x1) x1 = self.relu_2(x1) x1 = self.conv2d_3(x1) x1 = self.batchnorm2d_4(x1) res = x out = P.Add()(x1, res) out = self.relu_6(out) return out class UNet2D(nn.Cell): """UNet2D""" def __init__(self): super(UNet2D, self).__init__() self.conv2d_0 = nn.Conv2d(3, 16, 5, stride=2, padding=2, pad_mode="pad") self.batchnorm2d_1 = nn.BatchNorm2d(16, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.leakyrelu_2 = nn.LeakyReLU(alpha=0.009999999776482582) self.convblocka_0 = BasicBlockA(16, 32, 1) self.convblockb_0 = BasicBlockB(32, 32) self.convblocka_1 = BasicBlockA(32, 64, 2) self.convblockb_1 = BasicBlockB(64, 64) self.convblocka_2 = BasicBlockA(64, 128, 2) self.convblockb_2 = BasicBlockB(128, 128) self.conv2dbackpropinput_51 = P.Conv2DBackpropInput(64, 3, stride=2, pad=1, pad_mode="pad") self.conv2dbackpropinput_51_weight = Parameter(Tensor( np.random.uniform(0, 1, (128, 64, 3, 3)).astype(np.float32))) self.conv2d_54 = nn.Conv2d(128, 64, 3, stride=1, padding=1, pad_mode="pad") self.convblockb_3 = BasicBlockB(64, 64) self.conv2dbackpropinput_62 = P.Conv2DBackpropInput(32, 3, stride=2, pad=1, pad_mode="pad") self.conv2dbackpropinput_62_weight = Parameter(Tensor( np.random.uniform(0, 1, (64, 32, 3, 3)).astype(np.float32))) self.conv2d_65 = nn.Conv2d(64, 32, 3, stride=1, padding=1, pad_mode="pad") self.convblockb_4 = BasicBlockB(32, 32) self.conv2d_52 = nn.Conv2d(128, 32, 3, stride=1, padding=1, pad_mode="pad") self.conv2d_63 = nn.Conv2d(64, 32, 3, stride=1, padding=1, pad_mode="pad") self.conv2d_73 = nn.Conv2d(32, 32, 3, stride=1, padding=1, pad_mode="pad") self.concat = P.Concat(axis=1) param_dict = mindspore.load_checkpoint("./ckpts/feat_ext.ckpt") params_not_loaded = mindspore.load_param_into_net(self, param_dict, strict_load=True) print(params_not_loaded) def construct(self, imgs): """construct""" _, _, h, w = imgs.shape x = self.conv2d_0(imgs) x = self.batchnorm2d_1(x) x = self.leakyrelu_2(x) x1 = self.convblocka_0(x) x1 = self.convblockb_0(x1) x2 = self.convblocka_1(x1) x2 = self.convblockb_1(x2) x3 = self.convblocka_2(x2) x3 = self.convblockb_2(x3) x2_upsample = self.conv2dbackpropinput_51(x3, self.conv2dbackpropinput_51_weight, (x2.shape[0], x2.shape[1], h // 4, w // 4)) x2_upsample = self.concat((x2_upsample, x2,)) x2_upsample = self.conv2d_54(x2_upsample) x2_upsample = self.convblockb_3(x2_upsample) x1_upsample = self.conv2dbackpropinput_62(x2_upsample, self.conv2dbackpropinput_62_weight, (x1.shape[0], x1.shape[1], h // 2, w // 2)) x1_upsample = self.concat((x1_upsample, x1,)) x1_upsample = self.conv2d_65(x1_upsample) x1_upsample = self.convblockb_4(x1_upsample) x3_final = self.conv2d_52(x3) x2_final = self.conv2d_63(x2_upsample) x1_final = self.conv2d_73(x1_upsample) return x3_final, x2_final, x1_final class ConvBnReLu(nn.Cell): """ConvBnReLu""" def __init__(self, in_channels, out_channels): super(ConvBnReLu, self).__init__() self.conv3d_0 = nn.Conv3d(in_channels, out_channels, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.batchnorm3d_1 = nn.BatchNorm3d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.leakyrelu_2 = nn.LeakyReLU(alpha=0.009999999776482582) def construct(self, x): """construct""" x = self.conv3d_0(x) x = self.batchnorm3d_1(x) x = self.leakyrelu_2(x) return x class CostCompression(nn.Cell): """CostCompression""" def __init__(self): super(CostCompression, self).__init__() self.basicblock_0 = ConvBnReLu(8, 64) self.basicblock_1 = ConvBnReLu(64, 64) self.basicblock_2 = ConvBnReLu(64, 8) param_dict = mindspore.load_checkpoint("./ckpts/stage1_cost_compression.ckpt") params_not_loaded = mindspore.load_param_into_net(self, param_dict, strict_load=True) print(params_not_loaded) def construct(self, x): """construct""" x = self.basicblock_0(x) x = self.basicblock_1(x) x = self.basicblock_2(x) return x class Pseudo3DBlock_A(nn.Cell): """Pseudo3DBlock_A""" def __init__(self, in_channels, out_channels): super(Pseudo3DBlock_A, self).__init__() self.conv3d_0 = nn.Conv3d(in_channels, out_channels, (1, 3, 3), stride=1, padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_1 = nn.Conv3d(out_channels, out_channels, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.batchnorm3d_2 = nn.BatchNorm3d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_3 = nn.ReLU() self.conv3d_4 = nn.Conv3d(out_channels, out_channels, (1, 3, 3), stride=1, padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_5 = nn.Conv3d(out_channels, out_channels, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.batchnorm3d_6 = nn.BatchNorm3d(out_channels, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_8 = nn.ReLU() def construct(self, x): """construct""" x1 = self.conv3d_0(x) x1 = self.conv3d_1(x1) x1 = self.batchnorm3d_2(x1) x1 = self.relu_3(x1) x1 = self.conv3d_4(x1) x1 = self.conv3d_5(x1) x1 = self.batchnorm3d_6(x1) res = x out = P.Add()(x1, res) out = self.relu_8(out) return out class Pseudo3DBlock_B(nn.Cell): """Pseudo3DBlock_B""" def __init__(self): super(Pseudo3DBlock_B, self).__init__() self.conv3d_0 = nn.Conv3d(8, 8, (1, 3, 3), stride=(1, 2, 2), padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_1 = nn.Conv3d(8, 16, (1, 1, 1), stride=2, padding=0, pad_mode="valid") self.conv3d_2 = nn.Conv3d(8, 16, (3, 1, 1), stride=(2, 1, 1), padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.batchnorm3d_3 = nn.BatchNorm3d(16, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.batchnorm3d_4 = nn.BatchNorm3d(16, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_5 = nn.ReLU() self.conv3d_6 = nn.Conv3d(16, 16, (1, 3, 3), stride=1, padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_7 = nn.Conv3d(16, 16, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.batchnorm3d_8 = nn.BatchNorm3d(16, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.relu_10 = nn.ReLU() def construct(self, x): """construct""" x1 = self.conv3d_0(x) x1 = self.conv3d_2(x1) x1 = self.batchnorm3d_4(x1) x1 = self.relu_5(x1) x1 = self.conv3d_6(x1) x1 = self.conv3d_7(x1) x1 = self.batchnorm3d_8(x1) res = self.conv3d_1(x) res = self.batchnorm3d_3(res) out = P.Add()(x1, res) out = self.relu_10(out) return out class CoarseStageRegFuse(nn.Cell): """CoarseStageRegFuse""" def __init__(self): super(CoarseStageRegFuse, self).__init__() self.basicblocka_0 = Pseudo3DBlock_A(8, 8) self.basicblockb_0 = Pseudo3DBlock_B() self.conv3dtranspose_21 = nn.Conv3dTranspose(16, 8, 3, stride=2, padding=1, pad_mode="pad", output_padding=1) self.conv3d_23 = nn.Conv3d(16, 8, (1, 3, 3), stride=1, padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_24 = nn.Conv3d(8, 8, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.conv3d_25 = nn.Conv3d(8, 1, 3, stride=1, padding=1, pad_mode="pad") self.concat_1 = P.Concat(axis=1) self.squeeze_1 = P.Squeeze(axis=1) param_dict = mindspore.load_checkpoint("./ckpts/stage1_reg_fuse.ckpt") params_not_loaded = mindspore.load_param_into_net(self, param_dict, strict_load=True) print(params_not_loaded) def construct(self, fused_interim, depth_values): """construct""" x1 = self.basicblocka_0(fused_interim) x2 = self.basicblockb_0(x1) x1_upsample = self.conv3dtranspose_21(x2) cost_volume = self.concat_1((x1_upsample, x1)) cost_volume = self.conv3d_23(cost_volume) cost_volume = self.conv3d_24(cost_volume) score_volume = self.conv3d_25(cost_volume) score_volume = self.squeeze_1(score_volume) prob_volume, _, prob_map = soft_argmin(score_volume, dim=1, keepdim=True, window=2) est_depth = depth_regression(prob_volume, depth_values, keep_dim=True) return est_depth, prob_map, prob_volume class CoarseStageRegPair(nn.Cell): """CoarseStageRegPair""" def __init__(self): super(CoarseStageRegPair, self).__init__() self.basicblocka_0 = Pseudo3DBlock_A(8, 8) self.basicblockb_0 = Pseudo3DBlock_B() self.conv3dtranspose_21 = nn.Conv3dTranspose(16, 8, 3, stride=2, padding=1, pad_mode="pad", output_padding=1) self.concat_22 = P.Concat(axis=1) self.conv3d_23 = nn.Conv3d(16, 8, (1, 3, 3), stride=1, padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_24 = nn.Conv3d(8, 8, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.conv3d_25 = nn.Conv3d(8, 1, 3, stride=1, padding=1, pad_mode="pad") self.conv2d_38 = nn.Conv2d(1, 8, 3, stride=1, padding=1, pad_mode="pad") self.batchnorm2d_39 = nn.BatchNorm2d(num_features=8, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.leakyrelu_40 = nn.LeakyReLU(alpha=0.009999999776482582) self.conv2d_41 = nn.Conv2d(8, 8, 3, stride=1, padding=1, pad_mode="pad") self.batchnorm2d_42 = nn.BatchNorm2d(num_features=8, eps=9.999999747378752e-06, momentum=0.8999999761581421) self.leakyrelu_43 = nn.LeakyReLU(alpha=0.009999999776482582) self.conv2d_45 = nn.Conv2d(8, 1, 3, stride=1, padding=1, pad_mode="pad") self.conv2d_46 = nn.Conv2d(8, 1, 3, stride=1, padding=1, pad_mode="pad") self.concat_1 = P.Concat(axis=1) self.squeeze_1 = P.Squeeze(axis=1) param_dict = mindspore.load_checkpoint("./ckpts/stage1_reg_pair.ckpt") params_not_loaded = mindspore.load_param_into_net(self, param_dict, strict_load=True) print(params_not_loaded) def construct(self, cost_volume, depth_values): """construct""" x1 = self.basicblocka_0(cost_volume) x2 = self.basicblockb_0(x1) x1_upsample = self.conv3dtranspose_21(x2) interim = self.concat_1((x1_upsample, x1)) interim = self.conv3d_23(interim) interim = self.conv3d_24(interim) score_volume = self.conv3d_25(interim) score_volume = self.squeeze_1(score_volume) prob_volume, _ = soft_argmin(score_volume, dim=1, keepdim=True) est_depth = depth_regression(prob_volume, depth_values, keep_dim=True) entropy_ = entropy(prob_volume, dim=1, keepdim=True) x = self.conv2d_38(entropy_) x = self.batchnorm2d_39(x) x = self.leakyrelu_40(x) x = self.conv2d_41(x) x = self.batchnorm2d_42(x) x = self.leakyrelu_43(x) out = P.Add()(x, entropy_) uncertainty_map = self.conv2d_45(out) occ = self.conv2d_46(out) return interim, est_depth, uncertainty_map, occ class StageRegFuse(nn.Cell): """StageRegFuse""" def __init__(self, ckpt_path): super(StageRegFuse, self).__init__() self.basicblocka_0 = Pseudo3DBlock_A(8, 8) self.basicblocka_1 = Pseudo3DBlock_A(8, 8) self.basicblockb_0 = Pseudo3DBlock_B() self.basicblocka_2 = Pseudo3DBlock_A(16, 16) self.conv3dtranspose_38 = nn.Conv3dTranspose(16, 8, 3, stride=2, padding=1, pad_mode="pad", output_padding=1) self.concat_39 = P.Concat(axis=1) self.conv3d_40 = nn.Conv3d(16, 8, (1, 3, 3), stride=1, padding=(0, 0, 1, 1, 1, 1), pad_mode="pad") self.conv3d_41 = nn.Conv3d(8, 8, (3, 1, 1), stride=1, padding=(1, 1, 0, 0, 0, 0), pad_mode="pad") self.conv3d_42 = nn.Conv3d(8, 1, 3, stride=1, padding=1, pad_mode="pad") self.concat_1 = P.Concat(axis=1) self.squeeze_1 = P.Squeeze(axis=1) param_dict = mindspore.load_checkpoint(ckpt_path) params_not_loaded = mindspore.load_param_into_net(self, param_dict, strict_load=True) print(params_not_loaded) def construct(self, fused_interim, depth_values): """construct""" x1 = self.basicblocka_0(fused_interim) x1 = self.basicblocka_1(x1) x2
from __future__ import absolute_import from __future__ import print_function import veriloggen import types_axi_slave_readwrite_lite_simultaneous expected_verilog = """ module test; reg CLK; reg RST; wire [32-1:0] sum; reg [32-1:0] myaxi_awaddr; reg [4-1:0] myaxi_awcache; reg [3-1:0] myaxi_awprot; reg myaxi_awvalid; wire myaxi_awready; reg [32-1:0] myaxi_wdata; reg [4-1:0] myaxi_wstrb; reg myaxi_wvalid; wire myaxi_wready; wire [2-1:0] myaxi_bresp; wire myaxi_bvalid; reg myaxi_bready; reg [32-1:0] myaxi_araddr; reg [4-1:0] myaxi_arcache; reg [3-1:0] myaxi_arprot; reg myaxi_arvalid; wire myaxi_arready; wire [32-1:0] myaxi_rdata; wire [2-1:0] myaxi_rresp; wire myaxi_rvalid; reg myaxi_rready; reg [32-1:0] _axi_awaddr; wire [4-1:0] _axi_awcache; wire [3-1:0] _axi_awprot; reg _axi_awvalid; wire _axi_awready; reg [32-1:0] _axi_wdata; reg [4-1:0] _axi_wstrb; reg _axi_wvalid; wire _axi_wready; wire [2-1:0] _axi_bresp; wire _axi_bvalid; wire _axi_bready; reg [32-1:0] _axi_araddr; wire [4-1:0] _axi_arcache; wire [3-1:0] _axi_arprot; reg _axi_arvalid; wire _axi_arready; wire [32-1:0] _axi_rdata; wire [2-1:0] _axi_rresp; wire _axi_rvalid; wire _axi_rready; assign _axi_awcache = 3; assign _axi_awprot = 0; assign _axi_bready = 1; assign _axi_arcache = 3; assign _axi_arprot = 0; reg [3-1:0] outstanding_wcount_0; wire [32-1:0] _tmp_1; assign _tmp_1 = _axi_awaddr; always @(*) begin myaxi_awaddr = _tmp_1; end wire [4-1:0] _tmp_2; assign _tmp_2 = _axi_awcache; always @(*) begin myaxi_awcache = _tmp_2; end wire [3-1:0] _tmp_3; assign _tmp_3 = _axi_awprot; always @(*) begin myaxi_awprot = _tmp_3; end wire _tmp_4; assign _tmp_4 = _axi_awvalid; always @(*) begin myaxi_awvalid = _tmp_4; end assign _axi_awready = myaxi_awready; wire [32-1:0] _tmp_5; assign _tmp_5 = _axi_wdata; always @(*) begin myaxi_wdata = _tmp_5; end wire [4-1:0] _tmp_6; assign _tmp_6 = _axi_wstrb; always @(*) begin myaxi_wstrb = _tmp_6; end wire _tmp_7; assign _tmp_7 = _axi_wvalid; always @(*) begin myaxi_wvalid = _tmp_7; end assign _axi_wready = myaxi_wready; assign _axi_bresp = myaxi_bresp; assign _axi_bvalid = myaxi_bvalid; wire _tmp_8; assign _tmp_8 = _axi_bready; always @(*) begin myaxi_bready = _tmp_8; end wire [32-1:0] _tmp_9; assign _tmp_9 = _axi_araddr; always @(*) begin myaxi_araddr = _tmp_9; end wire [4-1:0] _tmp_10; assign _tmp_10 = _axi_arcache; always @(*) begin myaxi_arcache = _tmp_10; end wire [3-1:0] _tmp_11; assign _tmp_11 = _axi_arprot; always @(*) begin myaxi_arprot = _tmp_11; end wire _tmp_12; assign _tmp_12 = _axi_arvalid; always @(*) begin myaxi_arvalid = _tmp_12; end assign _axi_arready = myaxi_arready; assign _axi_rdata = myaxi_rdata; assign _axi_rresp = myaxi_rresp; assign _axi_rvalid = myaxi_rvalid; wire _tmp_13; assign _tmp_13 = _axi_rready; always @(*) begin myaxi_rready = _tmp_13; end reg [32-1:0] read_fsm; localparam read_fsm_init = 0; reg [32-1:0] rsum; reg __axi_cond_0_1; reg __axi_cond_1_1; assign _axi_rready = (read_fsm == 1) || (read_fsm == 3); reg [32-1:0] write_fsm; localparam write_fsm_init = 0; reg __axi_cond_2_1; reg [32-1:0] wdata; reg __axi_cond_3_1; reg __axi_cond_4_1; reg __axi_cond_5_1; main uut ( .CLK(CLK), .RST(RST), .sum(sum), .myaxi_awaddr(myaxi_awaddr), .myaxi_awcache(myaxi_awcache), .myaxi_awprot(myaxi_awprot), .myaxi_awvalid(myaxi_awvalid), .myaxi_awready(myaxi_awready), .myaxi_wdata(myaxi_wdata), .myaxi_wstrb(myaxi_wstrb), .myaxi_wvalid(myaxi_wvalid), .myaxi_wready(myaxi_wready), .myaxi_bresp(myaxi_bresp), .myaxi_bvalid(myaxi_bvalid), .myaxi_bready(myaxi_bready), .myaxi_araddr(myaxi_araddr), .myaxi_arcache(myaxi_arcache), .myaxi_arprot(myaxi_arprot), .myaxi_arvalid(myaxi_arvalid), .myaxi_arready(myaxi_arready), .myaxi_rdata(myaxi_rdata), .myaxi_rresp(myaxi_rresp), .myaxi_rvalid(myaxi_rvalid), .myaxi_rready(myaxi_rready) ); initial begin CLK = 0; forever begin #5 CLK = !CLK; end end initial begin RST = 0; _axi_awaddr = 0; _axi_awvalid = 0; _axi_wdata = 0; _axi_wstrb = 0; _axi_wvalid = 0; _axi_araddr = 0; _axi_arvalid = 0; outstanding_wcount_0 = 0; read_fsm = read_fsm_init; rsum = 0; __axi_cond_0_1 = 0; __axi_cond_1_1 = 0; write_fsm = write_fsm_init; __axi_cond_2_1 = 0; wdata = 100; __axi_cond_3_1 = 0; __axi_cond_4_1 = 0; __axi_cond_5_1 = 0; #100; RST = 1; #100; RST = 0; #100000; $finish; end always @(posedge CLK) begin if(RST) begin outstanding_wcount_0 <= 0; _axi_araddr <= 0; _axi_arvalid <= 0; __axi_cond_0_1 <= 0; __axi_cond_1_1 <= 0; _axi_awaddr <= 0; _axi_awvalid <= 0; __axi_cond_2_1 <= 0; _axi_wdata <= 0; _axi_wvalid <= 0; _axi_wstrb <= 0; __axi_cond_3_1 <= 0; __axi_cond_4_1 <= 0; __axi_cond_5_1 <= 0; end else begin if(__axi_cond_0_1) begin _axi_arvalid <= 0; end if(__axi_cond_1_1) begin _axi_arvalid <= 0; end if(__axi_cond_2_1) begin _axi_awvalid <= 0; end if(__axi_cond_3_1) begin _axi_wvalid <= 0; end if(__axi_cond_4_1) begin _axi_awvalid <= 0; end if(__axi_cond_5_1) begin _axi_wvalid <= 0; end if(_axi_wvalid && _axi_wready && !(_axi_bvalid && _axi_bready) && (outstanding_wcount_0 < 7)) begin outstanding_wcount_0 <= outstanding_wcount_0 + 1; end if(!(_axi_wvalid && _axi_wready) && (_axi_bvalid && _axi_bready) && (outstanding_wcount_0 > 0)) begin outstanding_wcount_0 <= outstanding_wcount_0 - 1; end if((read_fsm == 0) && (_axi_arready || !_axi_arvalid)) begin _axi_araddr <= 1024; _axi_arvalid <= 1; end __axi_cond_0_1 <= 1; if(_axi_arvalid && !_axi_arready) begin _axi_arvalid <= _axi_arvalid; end if((read_fsm == 2) && (_axi_arready || !_axi_arvalid)) begin _axi_araddr <= 2048; _axi_arvalid <= 1; end __axi_cond_1_1 <= 1; if(_axi_arvalid && !_axi_arready) begin _axi_arvalid <= _axi_arvalid; end if((write_fsm == 0) && (_axi_awready || !_axi_awvalid)) begin _axi_awaddr <= 1024; _axi_awvalid <= 1; end __axi_cond_2_1 <= 1; if(_axi_awvalid && !_axi_awready) begin _axi_awvalid <= _axi_awvalid; end if((write_fsm == 1) && ((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid))) begin _axi_wdata <= wdata; _axi_wvalid <= 1; _axi_wstrb <= { 4{ 1'd1 } }; end __axi_cond_3_1 <= 1; if(_axi_wvalid && !_axi_wready) begin _axi_wvalid <= _axi_wvalid; end if((write_fsm == 2) && (_axi_awready || !_axi_awvalid)) begin _axi_awaddr <= 1024; _axi_awvalid <= 1; end __axi_cond_4_1 <= 1; if(_axi_awvalid && !_axi_awready) begin _axi_awvalid <= _axi_awvalid; end if((write_fsm == 3) && ((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid))) begin _axi_wdata <= wdata; _axi_wvalid <= 1; _axi_wstrb <= { 4{ 1'd1 } }; end __axi_cond_5_1 <= 1; if(_axi_wvalid && !_axi_wready) begin _axi_wvalid <= _axi_wvalid; end end end localparam read_fsm_1 = 1; localparam read_fsm_2 = 2; localparam read_fsm_3 = 3; localparam read_fsm_4 = 4; localparam read_fsm_5 = 5; always @(posedge CLK) begin if(RST) begin read_fsm <= read_fsm_init; rsum <= 0; end else begin case(read_fsm) read_fsm_init: begin if(_axi_arready || !_axi_arvalid) begin read_fsm <= read_fsm_1; end end read_fsm_1: begin if(_axi_rready && _axi_rvalid) begin rsum <= rsum + _axi_rdata; end if(_axi_rready && _axi_rvalid) begin read_fsm <= read_fsm_2; end end read_fsm_2: begin if(_axi_arready || !_axi_arvalid) begin read_fsm <= read_fsm_3; end end read_fsm_3: begin if(_axi_rready && _axi_rvalid) begin rsum <= rsum + _axi_rdata; end if(_axi_rready && _axi_rvalid) begin read_fsm <= read_fsm_4; end end read_fsm_4: begin $display("rsum=%d expected_rsum=%d", rsum, 768); read_fsm <= read_fsm_5; end endcase end end localparam write_fsm_1 = 1; localparam write_fsm_2 = 2; localparam write_fsm_3 = 3; localparam write_fsm_4 = 4; localparam write_fsm_5 = 5; localparam write_fsm_6 = 6; localparam write_fsm_7 = 7; localparam write_fsm_8 = 8; localparam write_fsm_9 = 9; localparam write_fsm_10 = 10; localparam write_fsm_11 = 11; localparam write_fsm_12 = 12; localparam write_fsm_13 = 13; localparam write_fsm_14 = 14; localparam write_fsm_15 = 15; always @(posedge CLK) begin if(RST) begin write_fsm <= write_fsm_init; wdata <= 100; end else begin case(write_fsm) write_fsm_init: begin wdata <= 100; if(_axi_awready || !_axi_awvalid) begin write_fsm <= write_fsm_1; end end write_fsm_1: begin if((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid)) begin write_fsm <= write_fsm_2; end end write_fsm_2: begin wdata <= 200; if(_axi_awready || !_axi_awvalid) begin write_fsm <= write_fsm_3; end end write_fsm_3: begin if((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid)) begin write_fsm <= write_fsm_4; end end write_fsm_4: begin write_fsm <= write_fsm_5; end write_fsm_5: begin write_fsm <= write_fsm_6; end write_fsm_6: begin write_fsm <= write_fsm_7; end write_fsm_7: begin write_fsm <= write_fsm_8; end write_fsm_8: begin write_fsm <= write_fsm_9; end write_fsm_9: begin write_fsm <= write_fsm_10; end write_fsm_10: begin write_fsm <= write_fsm_11; end write_fsm_11: begin write_fsm <= write_fsm_12; end write_fsm_12: begin write_fsm <= write_fsm_13; end write_fsm_13: begin write_fsm <= write_fsm_14; end write_fsm_14: begin $display("sum=%d expected_sum=%d", sum, 300); write_fsm <= write_fsm_15; end endcase end end endmodule module main ( input CLK, input RST, output reg [32-1:0] sum, input [32-1:0] myaxi_awaddr, input [4-1:0] myaxi_awcache, input [3-1:0] myaxi_awprot, input myaxi_awvalid, output myaxi_awready, input [32-1:0] myaxi_wdata, input [4-1:0] myaxi_wstrb, input myaxi_wvalid, output myaxi_wready, output [2-1:0] myaxi_bresp, output reg myaxi_bvalid, input myaxi_bready, input [32-1:0] myaxi_araddr, input [4-1:0] myaxi_arcache, input [3-1:0] myaxi_arprot, input myaxi_arvalid, output myaxi_arready, output reg [32-1:0] myaxi_rdata, output [2-1:0] myaxi_rresp, output reg myaxi_rvalid, input myaxi_rready ); assign myaxi_bresp = 0; assign myaxi_rresp = 0; reg [32-1:0] fsm; localparam fsm_init = 0; reg [32-1:0] addr_0; reg writevalid_1; reg readvalid_2; reg prev_awvalid_3; reg prev_arvalid_4; assign myaxi_awready = (fsm == 0) && (!writevalid_1 && !readvalid_2 && !myaxi_bvalid && prev_awvalid_3); assign myaxi_arready = (fsm == 0) && (!readvalid_2 && !writevalid_1 && prev_arvalid_4
<gh_stars>0 #!/usr/bin/python # # Copyright 2018 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. import pdb import argparse import functools import os import json import math from collections import defaultdict import random import numpy as np import pdb import pprint import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torchvision.models as models #from sg2im.data.coco_ss import CocoSceneGraphDataset, coco_collate_fn #from sg2im.data.coco_contour import CocoSceneGraphDataset, coco_collate_fn from sg2im.data.coco_contour_debug import CocoSceneGraphDataset, coco_collate_fn #from sg2im.data.coco import CocoSceneGraphDataset, coco_collate_fn from sg2im.discriminators import PatchDiscriminator, AcCropDiscriminator, CondGANPatchDiscriminator, CondGANDiscriminator #from sg2im.losses import get_gan_losses from sg2im.metrics import jaccard from sg2im.model_layout_contour_single import Sg2ImModel # 59% model #from sg2im.model_layout_contour_8pt_dbug import Sg2ImModel #from sg2im.model_layout import Sg2ImModel from sg2im.utils import int_tuple, float_tuple, str_tuple from sg2im.utils import timeit, bool_flag, LossManager import sg2im.db_utils as db_utils #### #from sg2im.perceptual_loss import FeatureExtractor from sg2im.data.utils import imagenet_deprocess_batch #from sg2im.data.utils import perc_process_batch #from sg2im.logger import Logger from imageio import imwrite import sg2im.vis as vis #torch.backends.cudnn.benchmark = True COCO_DIR = os.path.expanduser('/dataset/coco_stuff') #COCO_DIR = os.path.expanduser('/Users/brigitsc/sandbox/sg2im/datasets/coco') parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='coco', choices=['vg', 'coco']) # Optimization hyperparameters parser.add_argument('--batch_size', default=32, type=int) parser.add_argument('--num_iterations', default=1000000, type=int) parser.add_argument('--learning_rate', default=1e-4, type=float) # Switch the generator to eval mode after this many iterations parser.add_argument('--eval_mode_after', default=100000, type=int) # Dataset options common to both VG and COCO parser.add_argument('--image_size', default='64,64', type=int_tuple) parser.add_argument('--num_train_samples', default=None, type=int) parser.add_argument('--num_val_samples', default=1024, type=int) parser.add_argument('--shuffle_val', default=False, type=bool_flag) parser.add_argument('--loader_num_workers', default=4, type=int) parser.add_argument('--include_relationships', default=True, type=bool_flag) # COCO-specific options parser.add_argument('--coco_train_image_dir', default=os.path.join(COCO_DIR, 'images/train2017')) parser.add_argument('--coco_val_image_dir', default=os.path.join(COCO_DIR, 'images/val2017')) parser.add_argument('--coco_train_instances_json', default=os.path.join(COCO_DIR, 'annotations/instances_train2017.json')) parser.add_argument('--coco_train_stuff_json', default=os.path.join(COCO_DIR, 'annotations/stuff_train2017.json')) parser.add_argument('--coco_val_instances_json', default=os.path.join(COCO_DIR, 'annotations/instances_val2017.json')) parser.add_argument('--coco_val_stuff_json', default=os.path.join(COCO_DIR, 'annotations/stuff_val2017.json')) parser.add_argument('--instance_whitelist', default=None, type=str_tuple) parser.add_argument('--stuff_whitelist', default=None, type=str_tuple) parser.add_argument('--coco_include_other', default=False, type=bool_flag) parser.add_argument('--min_object_size', default=0.02, type=float) parser.add_argument('--min_objects_per_image', default=3, type=int) parser.add_argument('--coco_stuff_only', default=True, type=bool_flag) parser.add_argument('--random_seed', default=42, type=int) #For comparative results/debug, use in val_loader # triplet options parser.add_argument('--triplet_box_net', default=False, type=int) parser.add_argument('--triplet_mask_size', default=0, type=int) # embedding for contextual search parser.add_argument('--triplet_embedding_size', default=0, type=int) # Generator options parser.add_argument('--mask_size', default=16, type=int) # Set this to 0 to use no masks parser.add_argument('--embedding_dim', default=128, type=int) parser.add_argument('--gconv_dim', default=128, type=int) parser.add_argument('--gconv_hidden_dim', default=512, type=int) parser.add_argument('--gconv_num_layers', default=5, type=int) parser.add_argument('--mlp_normalization', default='none', type=str) parser.add_argument('--refinement_network_dims', default='1024,512,256,128,64', type=int_tuple) parser.add_argument('--normalization', default='batch') parser.add_argument('--activation', default='leakyrelu-0.2') parser.add_argument('--layout_noise_dim', default=32, type=int) parser.add_argument('--use_boxes_pred_after', default=-1, type=int) ## scene_graph conditioning on GAN parser.add_argument('--sg_context_dim', default=0, type=int) parser.add_argument('--sg_context_dim_d', default=0, type=int) parser.add_argument('--image_patch_discr', default=True, type=bool_flag) parser.add_argument('--gcnn_pooling', default='sum') parser.add_argument('--layout_for_discrim', default=False, type=bool_flag) parser.add_argument('--matching_aware_loss', default=False, type=bool_flag) # Generator losses parser.add_argument('--mask_loss_weight', default=0, type=float) parser.add_argument('--l1_pixel_loss_weight', default=1.0, type=float) parser.add_argument('--bbox_pred_loss_weight', default=10, type=float) parser.add_argument('--predicate_pred_loss_weight', default=0, type=float) # DEPRECATED parser.add_argument('--perceptual_loss_weight', default=0, type=float) parser.add_argument('--grayscale_perceptual', action='store_true', help='Calculate perceptual loss with grayscale images') parser.add_argument('--log_perceptual', action='store_true', help='Take logarithm of perceptual loss') # Generic discriminator options parser.add_argument('--discriminator_loss_weight', default=0.01, type=float) parser.add_argument('--gan_loss_type', default='gan') parser.add_argument('--d_clip', default=None, type=float) parser.add_argument('--d_normalization', default='batch') parser.add_argument('--d_padding', default='valid') parser.add_argument('--d_activation', default='leakyrelu-0.2') # Object discriminator parser.add_argument('--d_obj_arch', default='C4-64-2,C4-128-2,C4-256-2') parser.add_argument('--crop_size', default=32, type=int) parser.add_argument('--d_obj_weight', default=1.0, type=float) # multiplied by d_loss_weight parser.add_argument('--ac_loss_weight', default=0.1, type=float) # Image discriminator parser.add_argument('--d_img_arch', default='C4-64-2,C4-128-2,C4-256-2') parser.add_argument('--d_img_weight', default=1.0, type=float) # multiplied by d_loss_weight # Output options parser.add_argument('--print_every', default=10, type=int) parser.add_argument('--timing', default=False, type=bool_flag) parser.add_argument('--output_dir', default=os.getcwd()) parser.add_argument('--checkpoint', default='sg2im-models/coco64.pt') parser.add_argument('--device', default='gpu', choices=['cpu', 'gpu']) def add_loss(total_loss, curr_loss, loss_dict, loss_name, weight=1, logarithm=False): curr_loss = curr_loss * weight if logarithm: curr_loss = torch.log(curr_loss) loss_dict[loss_name] = curr_loss.item() if total_loss is not None: total_loss += curr_loss else: total_loss = curr_loss return total_loss def check_args(args): H, W = args.image_size for _ in args.refinement_network_dims[1:]: H = H // 2 if H == 0: raise ValueError("Too many layers in refinement network") def build_model(args, vocab): kwargs = { 'vocab': vocab, 'image_size': args.image_size, 'embedding_dim': args.embedding_dim, 'gconv_dim': args.gconv_dim, 'gconv_hidden_dim': args.gconv_hidden_dim, 'gconv_num_layers': args.gconv_num_layers, 'mlp_normalization': args.mlp_normalization, 'refinement_dims': args.refinement_network_dims, 'normalization': args.normalization, 'activation': args.activation, 'mask_size': args.mask_size, 'layout_noise_dim': args.layout_noise_dim, 'triplet_box_net': args.triplet_box_net, 'triplet_mask_size': args.triplet_mask_size, 'triplet_embedding_size': args.triplet_embedding_size, } model = Sg2ImModel(**kwargs) return model, kwargs def build_coco_dsets(args): dset_kwargs = { 'image_dir': args.coco_train_image_dir, 'instances_json': args.coco_train_instances_json, 'stuff_json': args.coco_train_stuff_json, 'stuff_only': args.coco_stuff_only, 'image_size': args.image_size, 'mask_size': args.mask_size, 'max_samples': args.num_train_samples, 'min_object_size': args.min_object_size, 'min_objects_per_image': args.min_objects_per_image, 'instance_whitelist': args.instance_whitelist, 'stuff_whitelist': args.stuff_whitelist, 'include_other': args.coco_include_other, 'include_relationships': args.include_relationships, 'seed': args.random_seed } train_dset = None #train_dset = CocoSceneGraphDataset(**dset_kwargs) #num_objs = train_dset.total_objects() #num_imgs = len(train_dset) #print('Training dataset has %d images and %d objects' % (num_imgs, num_objs)) #print('(%.2f objects per image)' % (float(num_objs) / num_imgs)) dset_kwargs['image_dir'] = args.coco_val_image_dir dset_kwargs['instances_json'] = args.coco_val_instances_json dset_kwargs['stuff_json'] = args.coco_val_stuff_json dset_kwargs['max_samples'] = args.num_val_samples # *deactivate* randomization for val (for consistent results) dset_kwargs['seed'] = args.random_seed val_dset = CocoSceneGraphDataset(**dset_kwargs) #assert train_dset.vocab == val_dset.vocab #vocab = json.loads(json.dumps(train_dset.vocab)) vocab = json.loads(json.dumps(val_dset.vocab)) return vocab, train_dset, val_dset def min_max_bbox_fr_contours(contours_pred): cp = contours_pred.view(-1,12,2) min_pts, _ = cp.min(1) # second val is indices max_pts, _ = cp.max(1) boxes_pred = torch.cat([min_pts, max_pts], dim=1) return boxes_pred def build_loaders(args): if args.dataset == 'coco': vocab, train_dset, val_dset = build_coco_dsets(args) collate_fn = coco_collate_fn loader_kwargs = { 'batch_size': args.batch_size, 'num_workers': args.loader_num_workers, 'shuffle': True, 'collate_fn': collate_fn, } #train_loader = DataLoader(train_dset, **loader_kwargs) train_loader = None loader_kwargs['shuffle'] = args.shuffle_val val_loader = DataLoader(val_dset, **loader_kwargs) return vocab, train_loader, val_loader #def check_model(args, t, loader, model, logger=None, log_tag='', write_images=False): def check_model(args, t, loader, model, log_tag='', write_images=False): if torch.cuda.is_available(): float_dtype = torch.cuda.FloatTensor long_dtype = torch.cuda.LongTensor else: float_dtype = torch.FloatTensor long_dtype = torch.LongTensor num_samples = 0 all_losses = defaultdict(list) total_iou = 0 total_boxes = 0 ################### if not os.path.isdir(args.output_dir): os.mkdir(args.output_dir) print('Created %s' %args.output_dir) img_dir = args.output_dir+'/img_dir' if not os.path.isdir(img_dir): os.mkdir(img_dir) print('Created %s' %img_dir) ################## t = 0 # relationship (triplet) database triplet_db = dict() # iterate over all batches of images with torch.no_grad(): for batch in loader: # TODO: HERE if torch.cuda.is_available(): batch = [tensor.cuda() for tensor in batch] else: batch = [tensor for tensor in batch] masks = None if len(batch) == 6: # VG imgs, objs, boxes, triples, obj_to_img, triple_to_img = batch #elif len(batch) == 8: # COCO # imgs, objs, boxes, masks, triples, obj_to_img, triple_to_img, triplet_masks = batch #elif len(batch) == 9: # COCO # imgs, objs, boxes, masks, triples, obj_to_img, triple_to_img, triplet_masks, triplet_contours = batch elif len(batch) == 10: # COCO imgs, objs, boxes, masks, triples, obj_to_img, triple_to_img, triplet_masks, triplet_contours, obj_contours = batch #elif len(batch) == 7: # imgs, objs, boxes, masks, triples, obj_to_img, triple_to_img = batch predicates = triples[:, 1] # Run the model as it has been run during training model_masks = masks model_out = model(objs, triples, obj_to_img, boxes_gt=boxes, masks_gt=model_masks) # imgs_pred, boxes_pred, masks_pred, predicate_scores = model_out imgs_pred, boxes_pred, masks_pred, objs_vec, layout, layout_boxes, layout_masks, obj_to_img, sg_context_pred, sg_context_pred_d, predicate_scores, obj_embeddings, pred_embeddings, triple_boxes_pred, triple_boxes_gt, triplet_masks_pred, triplet_contours_pred, obj_contours_pred = model_out #imgs_pred, boxes_pred, masks_pred, objs_vec, layout, layout_boxes, layout_masks, obj_to_img, sg_context_pred, sg_context_pred_d, predicate_scores, obj_embeddings, pred_embeddings, triple_boxes_pred, triple_boxes_gt, triplet_masks_pred, triplet_contours_pred = model_out #imgs_pred, boxes_pred, masks_pred, objs_vec, layout, layout_boxes, layout_masks, obj_to_img, sg_context_pred, sg_context_pred_d, predicate_scores, obj_embeddings, pred_embeddings, triple_boxes_pred, triple_boxes_gt, triplet_masks_pred = model_out # Run model without GT boxes to get predicted layout masks # use this when to get layout boxes/masks using predicted boxes #model_out = model(objs, triples, obj_to_img) #layout_boxes, layout_masks = model_out[5], model_out[6] # if obj contours are predicted, derive bounding box from these; # if GT boxes are passed in, layout_masks are GT boxes if obj_contours_pred is not None and boxes_pred is None: boxes_pred = min_max_bbox_fr_contours(obj_contours_pred) if 0: import matplotlib.pyplot as plt cc = obj_contours.clone().view(-1,12,2) cp = obj_contours_pred.view(-1,12,2).clone().detach() cp = cp.cpu().numpy() bb = boxes[0].view(2,2) bbp = boxes_pred.clone().detach() bbp = bbp[0].view(2,2) fig, ax = plt.subplots() #ax.imshow(masks[0]) # without mask, origin will be LLHC ax.scatter(cc[0,:,0],cc[0,:,1], linewidth=0.5) ax.scatter(cp[0,:,0],cp[0,:,1], linewidth=0.5) ax.scatter(bb[:,0],bb[:,1], linewidth=1.0, marker="x") ax.scatter(bbp[:,0],bbp[:,1], linewidth=1.0, marker="x") plt.show() # display masks masks_pred = masks_pred.detach() np_masks_pred = [mask.cpu().numpy() for mask in masks_pred] fig = plt.figure() ax1 = fig.add_subplot(1,2,1) ax1.imshow(masks[0]) ax2 = fig.add_subplot(1,2,2) ax2.imshow(np_masks_pred[0]) plt.show() pdb.set_trace() num_batch_samples = imgs.size(0) num_samples += num_batch_samples if num_samples >= args.num_val_samples: break super_boxes = [] # open file to record all triplets, per image, in a batch file_path = os.path.join(img_dir, 'all_batch_triplets.txt') f = open(file_path,'w') ### embedding stuff below here #### for i in range(0,num_batch_samples): print('Processing image', i+1, 'of batch size', args.batch_size) f.write('---------- image ' + str(i) + '----------\n') # from batch: objs, triples, triple_to_img, objs_to_img (need indices in that to select to tie triplets to image) # from model: obj_embed, pred_embed # find all triple indices for specific image # all triples for image i # TODO: clean up code so it is numpy() equivalent in all places tr_index = np.where(triple_to_img.cpu().numpy() == i) tr_img = triples.cpu().numpy()[tr_index, :] tr_img = np.squeeze(tr_img, axis=0) # 8 point triple boxes np_triple_boxes_gt = np.array(triple_boxes_gt).astype(float) tr_img_boxes = np_triple_boxes_gt[tr_index] assert len(tr_img) == len(tr_img_boxes) # vocab['object_idx_to_name'], vocab['pred_idx_to_name'] # s,o: indices for "objs" array (yields 'object_idx' for 'object_idx_to_name') # p: use this value as is (yields 'pred_idx' for 'pred_idx_to_name') s, p, o = np.squeeze(np.split(tr_img, 3, axis=1)) # iterate over all triplets in image to form (subject, predicat, object) tuples relationship_data = [] num_triples = len(tr_img) # need to iterate over all triples
<gh_stars>1-10 import torch from torch import nn as nn from torch.nn import functional as F from torch.autograd import Variable, Function import numpy as np """ 3D Squeeze and Excitation Modules ***************************** 3D Extensions of the following 2D squeeze and excitation blocks: 1. `Channel Squeeze and Excitation <https://arxiv.org/abs/1709.01507>`_ 2. `Spatial Squeeze and Excitation <https://arxiv.org/abs/1803.02579>`_ 3. `Channel and Spatial Squeeze and Excitation <https://arxiv.org/abs/1803.02579>`_ 4. `New Project & Excite block, designed specifically for 3D inputs https://arxiv.org/pdf/1906.04649v1.pdf` Coded by -- <NAME> (https://github.com/arickm) Retrieved from https://github.com/ai-med/squeeze_and_excitation/blob/master/squeeze_and_excitation/squeeze_and_excitation_3D.py """ class ChannelSELayer3D(nn.Module): """ 3D extension of Squeeze-and-Excitation (SE) block described in: *Hu et al., Squeeze-and-Excitation Networks, arXiv:1709.01507* *Zhu et al., AnatomyNet, arXiv:arXiv:1808.05238* """ def __init__(self, num_channels, reduction_ratio=2): """ :param num_channels: No of input channels :param reduction_ratio: By how much should the num_channels should be reduced """ super(ChannelSELayer3D, self).__init__() self.avg_pool = nn.AdaptiveAvgPool3d(1) num_channels_reduced = num_channels // reduction_ratio self.reduction_ratio = reduction_ratio self.fc1 = nn.Linear(num_channels, num_channels_reduced, bias=True) self.fc2 = nn.Linear(num_channels_reduced, num_channels, bias=True) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, input_tensor): """ :param input_tensor: X, shape = (batch_size, num_channels, D, H, W) :return: output tensor """ batch_size, num_channels, D, H, W = input_tensor.size() # Average along each channel squeeze_tensor = self.avg_pool(input_tensor) # channel excitation fc_out_1 = self.relu(self.fc1(squeeze_tensor.view(batch_size, num_channels))) fc_out_2 = self.sigmoid(self.fc2(fc_out_1)) output_tensor = torch.mul( input_tensor, fc_out_2.view(batch_size, num_channels, 1, 1, 1) ) return output_tensor class SpatialSELayer3D(nn.Module): """ 3D extension of SE block -- squeezing spatially and exciting channel-wise described in: *Roy et al., Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks, MICCAI 2018* """ def __init__(self, num_channels): """ :param num_channels: No of input channels """ super(SpatialSELayer3D, self).__init__() self.conv = nn.Conv3d(num_channels, 1, 1) self.sigmoid = nn.Sigmoid() def forward(self, input_tensor, weights=None): """ :param weights: weights for few shot learning :param input_tensor: X, shape = (batch_size, num_channels, D, H, W) :return: output_tensor """ # channel squeeze batch_size, channel, D, H, W = input_tensor.size() if weights: weights = weights.view(1, channel, 1, 1) out = F.conv2d(input_tensor, weights) else: out = self.conv(input_tensor) squeeze_tensor = self.sigmoid(out) # spatial excitation output_tensor = torch.mul( input_tensor, squeeze_tensor.view(batch_size, 1, D, H, W) ) return output_tensor class ChannelSpatialSELayer3D(nn.Module): """ 3D extension of concurrent spatial and channel squeeze & excitation: *<NAME> al., Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks, arXiv:1803.02579* """ def __init__(self, num_channels, reduction_ratio=2): """ :param num_channels: No of input channels :param reduction_ratio: By how much should the num_channels should be reduced """ super(ChannelSpatialSELayer3D, self).__init__() self.cSE = ChannelSELayer3D(num_channels, reduction_ratio) self.sSE = SpatialSELayer3D(num_channels) def forward(self, input_tensor): """ :param input_tensor: X, shape = (batch_size, num_channels, D, H, W) :return: output_tensor """ output_tensor = torch.max(self.cSE(input_tensor), self.sSE(input_tensor)) return output_tensor class ProjectExciteLayer(nn.Module): """ Project & Excite Module, specifically designed for 3D inputs *quote* """ def __init__(self, num_channels, reduction_ratio=2): """ :param num_channels: No of input channels :param reduction_ratio: By how much should the num_channels should be reduced """ super(ProjectExciteLayer, self).__init__() num_channels_reduced = num_channels // reduction_ratio self.reduction_ratio = reduction_ratio self.relu = nn.ReLU() self.conv_c = nn.Conv3d( in_channels=num_channels, out_channels=num_channels_reduced, kernel_size=1, stride=1, ) self.conv_cT = nn.Conv3d( in_channels=num_channels_reduced, out_channels=num_channels, kernel_size=1, stride=1, ) self.sigmoid = nn.Sigmoid() def forward(self, input_tensor): """ :param input_tensor: X, shape = (batch_size, num_channels, D, H, W) :return: output tensor """ batch_size, num_channels, D, H, W = input_tensor.size() # Project: # Average along channels and different axes squeeze_tensor_w = F.adaptive_avg_pool3d(input_tensor, (1, 1, W)) squeeze_tensor_h = F.adaptive_avg_pool3d(input_tensor, (1, H, 1)) squeeze_tensor_d = F.adaptive_avg_pool3d(input_tensor, (D, 1, 1)) # tile tensors to original size and add: final_squeeze_tensor = sum( [ squeeze_tensor_w.view(batch_size, num_channels, 1, 1, W), squeeze_tensor_h.view(batch_size, num_channels, 1, H, 1), squeeze_tensor_d.view(batch_size, num_channels, D, 1, 1), ] ) # Excitation: final_squeeze_tensor = self.sigmoid( self.conv_cT(self.relu(self.conv_c(final_squeeze_tensor))) ) output_tensor = torch.mul(input_tensor, final_squeeze_tensor) return output_tensor """ Based on https://github.com/ozan-oktay/Attention-Gated-Networks Published in https://arxiv.org/abs/1804.03999 if attention: self.attention = GridAttention( in_channels=in_channels // 2, gating_channels=in_channels, dim=dim ) Note: Usually called at end of upblock... # taken from https://elektronn3.readthedocs.io/en/latest/source/elektronn3.models.unet.html # ELEKTRONN3 - Neural Network Toolkit """ class GridAttention(nn.Module): def __init__( self, in_channels, gating_channels, inter_channels=None, dim=3, sub_sample_factor=2, ): super().__init__() assert dim in [2, 3] # Downsampling rate for the input featuremap if isinstance(sub_sample_factor, tuple): self.sub_sample_factor = sub_sample_factor elif isinstance(sub_sample_factor, list): self.sub_sample_factor = tuple(sub_sample_factor) else: self.sub_sample_factor = tuple([sub_sample_factor]) * dim # Default parameter set self.dim = dim self.sub_sample_kernel_size = self.sub_sample_factor # Number of channels (pixel dimensions) self.in_channels = in_channels self.gating_channels = gating_channels self.inter_channels = inter_channels if self.inter_channels is None: self.inter_channels = in_channels // 2 if self.inter_channels == 0: self.inter_channels = 1 if dim == 3: conv_nd = nn.Conv3d bn = nn.BatchNorm3d self.upsample_mode = "trilinear" elif dim == 2: conv_nd = nn.Conv2d bn = nn.BatchNorm2d self.upsample_mode = "bilinear" else: raise NotImplementedError # Output transform self.w = nn.Sequential( conv_nd( in_channels=self.in_channels, out_channels=self.in_channels, kernel_size=1, ), bn(self.in_channels), ) # Theta^T * x_ij + Phi^T * gating_signal + bias self.theta = conv_nd( in_channels=self.in_channels, out_channels=self.inter_channels, kernel_size=self.sub_sample_kernel_size, stride=self.sub_sample_factor, bias=False, ) self.phi = conv_nd( in_channels=self.gating_channels, out_channels=self.inter_channels, kernel_size=1, stride=1, padding=0, bias=True, ) self.psi = conv_nd( in_channels=self.inter_channels, out_channels=1, kernel_size=1, stride=1, bias=True, ) self.init_weights() def forward(self, x, g): # theta => (b, c, t, h, w) -> (b, i_c, t, h, w) -> (b, i_c, thw) # phi => (b, g_d) -> (b, i_c) theta_x = self.theta(x) # g (b, c, t', h', w') -> phi_g (b, i_c, t', h', w') # Relu(theta_x + phi_g + bias) -> f = (b, i_c, thw) -> (b, i_c, t/s1, h/s2, w/s3) phi_g = F.interpolate( self.phi(g), size=theta_x.shape[2:], mode=self.upsample_mode, align_corners=False, ) f = F.relu(theta_x + phi_g, inplace=True) # psi^T * f -> (b, psi_i_c, t/s1, h/s2, w/s3) sigm_psi_f = torch.sigmoid(self.psi(f)) # upsample the attentions and multiply sigm_psi_f = F.interpolate( sigm_psi_f, size=x.shape[2:], mode=self.upsample_mode, align_corners=False ) y = sigm_psi_f.expand_as(x) * x wy = self.w(y) return wy, sigm_psi_f def init_weights(self): def weight_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.kaiming_normal_(m.weight.data, a=0, mode="fan_in") elif classname.find("Linear") != -1: nn.init.kaiming_normal_(m.weight.data, a=0, mode="fan_in") elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0.0) self.apply(weight_init) class DummyAttention(nn.Module): def forward(self, x, g): return x, None ''' Add 3D deformable convolution... from https://github.com/KrakenLeaf/deform_conv_pytorch/ archive message >> ''' # 2D # --------------------------------------------------------------------------------------------- # Original code of ChunhuanLin : https://github.com/ChunhuanLin/deform_conv_pytorch class DeformConv2D(nn.Module): def __init__(self, inc, outc, kernel_size=3, padding=1, bias=None): super(DeformConv2D, self).__init__() self.kernel_size = kernel_size self.padding = padding self.zero_padding = nn.ZeroPad2d(padding) self.conv_kernel = nn.Conv2d(inc, outc, kernel_size=kernel_size, stride=kernel_size, bias=bias) def forward(self, x, offset): dtype = offset.data.type() ks = self.kernel_size N = offset.size(1) // 2 # Change offset's order from [x1, x2, ..., y1, y2, ...] to [x1, y1, x2, y2, ...] # Codes below are written to make sure same results of MXNet implementation. # You can remove them, and it won't influence the module's performance. offsets_index = Variable(torch.cat([torch.arange(0, 2*N, 2), torch.arange(1, 2*N+1, 2)]), requires_grad=False).type_as(x).long() offsets_index = offsets_index.unsqueeze(dim=0).unsqueeze(dim=-1).unsqueeze(dim=-1).expand(*offset.size()) offset = torch.gather(offset, dim=1, index=offsets_index) # ------------------------------------------------------------------------ if self.padding: x = self.zero_padding(x) # interpolation points p (Eq. 2) # ------------------------------ # (b, 2N, h, w) p = self._get_p(offset, dtype) # (b, h, w, 2N) p = p.contiguous().permute(0, 2, 3, 1) # Regular grid points q (Eq. 3) # ----------------------------- q_lt = Variable(p.data, requires_grad=False).floor() q_rb = q_lt + 1 q_lt = torch.cat([torch.clamp(q_lt[..., :N], 0, x.size(2)-1), torch.clamp(q_lt[..., N:], 0, x.size(3)-1)], dim=-1).long() q_rb = torch.cat([torch.clamp(q_rb[..., :N], 0, x.size(2)-1), torch.clamp(q_rb[..., N:], 0, x.size(3)-1)], dim=-1).long() q_lb = torch.cat([q_lt[..., :N], q_rb[..., N:]], -1) q_rt = torch.cat([q_rb[..., :N], q_lt[..., N:]], -1) # (b, h, w, N) mask = torch.cat([p[..., :N].lt(self.padding)+p[..., :N].gt(x.size(2)-1-self.padding), p[..., N:].lt(self.padding)+p[..., N:].gt(x.size(3)-1-self.padding)], dim=-1).type_as(p) mask = mask.detach() # Detach from computational graph floor_p = p - (p - torch.floor(p)) p = p*(1-mask) + floor_p*mask p = torch.cat([torch.clamp(p[..., :N], 0, x.size(2)-1), torch.clamp(p[..., N:], 0, x.size(3)-1)], dim=-1) # Interpolation kernel (Eq. 4) # ----------------------------- # bilinear kernel (b, h, w, N) g_lt = (1 + (q_lt[..., :N].type_as(p) - p[..., :N])) * (1 + (q_lt[..., N:].type_as(p) - p[..., N:])) # g(qx, px) * g(qy, py) g_rb = (1 - (q_rb[..., :N].type_as(p) - p[..., :N])) * (1 - (q_rb[..., N:].type_as(p) - p[..., N:])) g_lb = (1 + (q_lb[..., :N].type_as(p) - p[..., :N])) * (1 - (q_lb[..., N:].type_as(p) - p[..., N:])) g_rt = (1 - (q_rt[..., :N].type_as(p) - p[..., :N])) * (1 + (q_rt[..., N:].type_as(p) - p[..., N:])) # Interpolation - x(q) (Eq. 3) # ---------------------------- # (b, c, h, w, N) x_q_lt = self._get_x_q(x, q_lt, N) x_q_rb = self._get_x_q(x, q_rb, N) x_q_lb = self._get_x_q(x, q_lb, N) x_q_rt
- starttime)))) def export_pings_to_file(self, output_directory: str = None, file_format: str = 'csv', csv_delimiter=' ', filter_by_detection: bool = True, z_pos_down: bool = True, export_by_identifiers: bool = True): """ Run the export module to export point cloud relevant data to file, see export.export_pings_to_file """ written_files = self.export.export_pings_to_file(output_directory=output_directory, file_format=file_format, csv_delimiter=csv_delimiter, filter_by_detection=filter_by_detection, z_pos_down=z_pos_down, export_by_identifiers=export_by_identifiers) return written_files def export_lines_to_file(self, linenames: list, output_directory: str = None, file_format: str = 'csv', csv_delimiter=' ', filter_by_detection: bool = True, z_pos_down: bool = True, export_by_identifiers: bool = True): """ Run the export module to export only the data belonging to the given lines to file, see export.export_lines_to_file """ written_files = self.export.export_lines_to_file(linenames=linenames, output_directory=output_directory, file_format=file_format, csv_delimiter=csv_delimiter, filter_by_detection=filter_by_detection, z_pos_down=z_pos_down, export_by_identifiers=export_by_identifiers) return written_files def export_soundings_to_file(self, datablock: list, output_directory: str = None, file_format: str = 'csv', csv_delimiter=' ', filter_by_detection: bool = True, z_pos_down: bool = True): """ Run the export module to export given soundings to file, see export.export_soundings_to_file """ self.export.export_soundings_to_file(datablock, output_directory, file_format, csv_delimiter, filter_by_detection, z_pos_down) def export_variable(self, dataset_name: str, var_name: str, dest_path: str, reduce_method: str = None, zero_centered: bool = False): """ Run the export module to export the given variable to csv, writing to the provided path, see export.export_variable_to_csv """ self.export.export_variable_to_csv(dataset_name, var_name, dest_path, reduce_method, zero_centered) def export_dataset(self, dataset_name: str, dest_path: str): """ Run the export module to export each variable in the given dataset to one csv, writing to the provided path, see export.export_dataset_to_csv """ self.export.export_dataset_to_csv(dataset_name, dest_path) def _submit_data_to_cluster(self, rawping: xr.Dataset, mode: str, idx_by_chunk: list, max_chunks_at_a_time: int, timestmp: str, prefixes: str, dump_data: bool = True, skip_dask: bool = False, prefer_pp_nav: bool = True, vdatum_directory: str = None): """ For all of the main processes, we break up our inputs into chunks, appended to a list (data_for_workers). Knowing the capacity of the cluster memory, we can determine how many chunks to run at a time (max_chunks_at_a_time) and submit map those chunks to the cluster workers. Append the resulting futures to the futures_repo and wait inbetween mappings. This limits the memory used so that we don't run out. Parameters ---------- rawping xarray Dataset for the ping records mode one of ['orientation', 'bpv', sv_corr', 'georef', 'tpu'] idx_by_chunk values are the integer indexes of the pings to use, coords are the time of ping max_chunks_at_a_time maximum number of data chunks to load and process at a time timestmp timestamp of the installation parameters instance used prefixes prefix identifier for the tx/rx, will vary for dual head systems dump_data if True dump the tx/rx vectors to the multibeam datastore. Set this to false for an entirely in memory workflow prefer_pp_nav if True will use post-processed navigation/height (SBET) vdatum_directory if 'NOAA MLLW' 'NOAA MHW' is the vertical reference, a path to the vdatum directory is required here skip_dask if True will not use the dask.distributed client to submit tasks, will run locally instead """ # clear out the intermediate data just in case there is old data there sys_ident = rawping.system_identifier self.intermediate_dat[sys_ident][mode][timestmp] = [] tot_runs = int(np.ceil(len(idx_by_chunk) / max_chunks_at_a_time)) for rn in range(tot_runs): starttime = perf_counter() start_r = rn * max_chunks_at_a_time end_r = min(start_r + max_chunks_at_a_time, len(idx_by_chunk)) # clamp for last run idx_by_chunk_subset = idx_by_chunk[start_r:end_r].copy() if mode == 'orientation': kluster_function = distrib_run_build_orientation_vectors chunk_function = self._generate_chunks_orientation comp_time = 'orientation_time_complete' chunkargs = [rawping, idx_by_chunk_subset, timestmp, prefixes] elif mode == 'bpv': kluster_function = distrib_run_build_beam_pointing_vector chunk_function = self._generate_chunks_bpv comp_time = 'bpv_time_complete' chunkargs = [rawping, idx_by_chunk_subset, timestmp] elif mode == 'sv_corr': kluster_function = distributed_run_sv_correct chunk_function = self._generate_chunks_svcorr comp_time = 'sv_time_complete' profnames, casts, cast_times, castlocations = self.multibeam.return_all_profiles() cast_chunks = self.return_cast_idx_nearestintime(cast_times, idx_by_chunk_subset, silent=(rn != 0)) addtl_offsets = self.return_additional_xyz_offsets(rawping, prefixes, timestmp, idx_by_chunk_subset) chunkargs = [rawping, cast_chunks, casts, prefixes, timestmp, addtl_offsets] elif mode == 'georef': kluster_function = distrib_run_georeference chunk_function = self._generate_chunks_georef comp_time = 'georef_time_complete' z_offset = float(self.multibeam.xyzrph[prefixes[0] + '_z'][timestmp]) chunkargs = [rawping, idx_by_chunk_subset, prefixes, timestmp, z_offset, prefer_pp_nav, vdatum_directory] elif mode == 'tpu': kluster_function = distrib_run_calculate_tpu chunk_function = self._generate_chunks_tpu comp_time = 'tpu_time_complete' chunkargs = [rawping, idx_by_chunk_subset, timestmp] else: self.logger.error('Mode must be one of ["orientation", "bpv", "sv_corr", "georef", "tpu"]') raise ValueError('Mode must be one of ["orientation", "bpv", "sv_corr", "georef", "tpu"]') data_for_workers = chunk_function(*chunkargs, silent=(rn != 0)) try: futs = self.client.map(kluster_function, data_for_workers) if self.show_progress: progress(futs, multi=False) endtimes = [len(c) for c in idx_by_chunk] futs_with_endtime = [[f, endtimes[cnt]] for cnt, f in enumerate(futs)] self.intermediate_dat[sys_ident][mode][timestmp].extend(futs_with_endtime) wait(self.intermediate_dat[sys_ident][mode][timestmp]) except: # get here if client is closed or not setup for cnt, dat in enumerate(data_for_workers): endtime = len(idx_by_chunk[cnt]) data = kluster_function(dat) self.intermediate_dat[sys_ident][mode][timestmp].append([data, endtime]) if dump_data: self.__setattr__(comp_time, datetime.utcnow().strftime('%c')) self.write_intermediate_futs_to_zarr(mode, rawping.system_identifier, timestmp, skip_dask=skip_dask) endtime = perf_counter() self.logger.info('Processing chunk {} out of {} complete: {}'.format(rn + 1, tot_runs, seconds_to_formatted_string(int(endtime - starttime)))) def write_intermediate_futs_to_zarr(self, mode: str, sys_ident: str, timestmp: str, skip_dask: bool = False): """ Flush some of the intermediate data that was mapped to the cluster (and lives in futures objects) to disk, puts it in the multibeam, as the time dimension should be the same. Mode allows for selecting the output from one of the main processes for writing. Parameters ---------- mode one of ['orientation', 'bpv', sv_corr', 'georef', 'tpu'] sys_ident the multibeam system identifier attribute, used as a key to find the intermediate data timestmp timestamp of the installation parameters instance used skip_dask if True will not use the dask.distributed client to submit tasks, will run locally instead """ if mode == 'orientation': mode_settings = ['orientation', ['tx', 'rx', 'processing_status'], 'orientation vectors', {'_compute_orientation_complete': self.orientation_time_complete, 'current_processing_status': 1, 'reference': {'tx': 'unit vector', 'rx': 'unit vector'}, 'units': {'tx': ['+ forward', '+ starboard', '+ down'], 'rx': ['+ forward', '+ starboard', '+ down']}}] elif mode == 'bpv': mode_settings = ['bpv', ['rel_azimuth', 'corr_pointing_angle', 'processing_status'], 'beam pointing vectors', {'_compute_beam_vectors_complete': self.bpv_time_complete, 'current_processing_status': 2, 'reference': {'rel_azimuth': 'vessel heading', 'corr_pointing_angle': 'vertical in geographic reference frame'}, 'units': {'rel_azimuth': 'radians', 'corr_pointing_angle': 'radians'}}] elif mode == 'sv_corr': mode_settings = ['sv_corr', ['alongtrack', 'acrosstrack', 'depthoffset', 'processing_status'], 'sv corrected data', {'svmode': 'nearest in time', '_sound_velocity_correct_complete': self.sv_time_complete, 'current_processing_status': 3, 'reference': {'alongtrack': 'reference', 'acrosstrack': 'reference', 'depthoffset': 'transmitter'}, 'units': {'alongtrack': 'meters (+ forward)', 'acrosstrack': 'meters (+ starboard)', 'depthoffset': 'meters (+ down)'}}] elif mode == 'georef': crs = self.horizontal_crs.to_epsg() if crs is None: # gets here if there is no valid EPSG for this transformation crs = self.horizontal_crs.to_string() if self.vert_ref == 'NOAA MLLW': vertcrs = datum_to_wkt('mllw', self.multibeam.raw_ping[0].min_lon, self.multibeam.raw_ping[0].min_lat, self.multibeam.raw_ping[0].max_lon, self.multibeam.raw_ping[0].max_lat) elif self.vert_ref == 'NOAA MHW': vertcrs = datum_to_wkt('mhw', self.multibeam.raw_ping[0].min_lon, self.multibeam.raw_ping[0].min_lat, self.multibeam.raw_ping[0].max_lon, self.multibeam.raw_ping[0].max_lat) else: vertcrs = 'Unknown' mode_settings = ['georef', ['x', 'y', 'z', 'corr_heave', 'corr_altitude', 'datum_uncertainty', 'geohash', 'processing_status'], 'georeferenced soundings data', {'horizontal_crs': crs, 'vertical_reference': self.vert_ref, 'vertical_crs': vertcrs, '_georeference_soundings_complete': self.georef_time_complete, 'current_processing_status': 4, 'reference': {'x': 'reference', 'y': 'reference', 'z': 'reference', 'corr_heave': 'transmitter', 'corr_altitude': 'transmitter to ellipsoid'}, 'units': {'x': 'meters (+ forward)', 'y': 'meters (+ starboard)', 'z': 'meters (+ down)', 'corr_heave': 'meters (+ down)', 'corr_altitude': 'meters (+ up)'}}] elif mode == 'tpu': mode_settings = ['tpu', ['tvu', 'thu', 'processing_status'], 'total horizontal and vertical uncertainty', {'_total_uncertainty_complete': self.tpu_time_complete, 'vertical_reference': self.vert_ref, 'current_processing_status': 5, 'reference': {'tvu': 'None', 'thu': 'None'}, 'units': {'tvu': 'meters (+ down)', 'thu': 'meters'}}] else: self.logger.error('Mode must be one of ["orientation", "bpv", "sv_corr", "georef", "tpu"]') raise ValueError('Mode must be one of ["orientation", "bpv", "sv_corr", "georef", "tpu"]') futs_data = [] for f in self.intermediate_dat[sys_ident][mode_settings[0]][timestmp]: try: futs_data.extend([self.client.submit(combine_arrays_to_dataset, f[0], mode_settings[1])]) except: # client is not setup or closed, this is if you want to run on just your machine futs_data.extend([combine_arrays_to_dataset(f[0], mode_settings[1])]) if futs_data: if not skip_dask: time_arrs = self.client.gather(self.client.map(_return_xarray_time, futs_data)) else: time_arrs = [_return_xarray_time(tr) for tr in futs_data] self.write('ping', futs_data, attributes=mode_settings[3], time_array=time_arrs, sys_id=sys_ident, skip_dask=skip_dask) self.intermediate_dat[sys_ident][mode_settings[0]][timestmp] = [] def return_total_pings(self, min_time: float = None, max_time: float = None): """ Get the total ping count, optionally within the provided mintime maxtime range Parameters ---------- min_time the minimum time desired from the raw_ping dataset max_time the maximum time desired from the raw_ping dataset Returns ------- int total number of pings for this dataset """ total_pings = 0 if min_time is not None or max_time is not None: if min_time is None: min_time = np.min([rp.time.values[0] for rp in self.multibeam.raw_ping]) if max_time is None: max_time = np.max([rp.time.values[-1] for rp in self.multibeam.raw_ping]) for ra in self.multibeam.raw_ping: slice_ra = slice_xarray_by_dim(ra, dimname='time', start_time=min_time, end_time=max_time) try: total_pings +=
"""Utilities for with-statement contexts. See PEP 343. Original source code: https://hg.python.org/cpython/file/3.4/Lib/contextlib.py Not implemented: - redirect_stdout; """ import sys from collections import deque from ucontextlib import * class AbstractAsyncContextManager(object): "compabilibty" pass class closing(object): """Context to automatically close something at the end of a block. Code like this: with closing(<module>.open(<arguments>)) as f: <block> is equivalent to this: f = <module>.open(<arguments>) try: <block> finally: f.close() """ def __init__(self, thing): self.thing = thing def __enter__(self): return self.thing def __exit__(self, *exc_info): self.thing.close() class suppress: """Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement. with suppress(FileNotFoundError): os.remove(somefile) # Execution still resumes here if the file was already removed """ def __init__(self, *exceptions): self._exceptions = exceptions def __enter__(self): pass def __exit__(self, exctype, excinst, exctb): # Unlike isinstance and issubclass, CPython exception handling # currently only looks at the concrete type hierarchy (ignoring # the instance and subclass checking hooks). While Guido considers # that a bug rather than a feature, it's a fairly hard one to fix # due to various internal implementation details. suppress provides # the simpler issubclass based semantics, rather than trying to # exactly reproduce the limitations of the CPython interpreter. # # See http://bugs.python.org/issue12029 for more details return exctype is not None and issubclass(exctype, self._exceptions) class _AsyncGeneratorContextManager(AbstractAsyncContextManager): def __init__(self, func, args, kwds): self.gen = func(*args, **kwds) self.func, self.args, self.kwds = func, args, kwds async def __aenter__(self): try: return await self.gen.__anext__() except StopAsyncIteration: raise RuntimeError("generator didn't yield") from None async def __aexit__(self, typ, value, traceback): if typ is None: try: await self.gen.__anext__() except StopAsyncIteration: return else: raise RuntimeError("generator didn't stop") else: if value is None: value = typ() # See _GeneratorContextManager.__exit__ for comments on subtleties # in this implementation try: await self.gen.athrow(typ, value, traceback) raise RuntimeError("generator didn't stop after athrow()") except StopAsyncIteration as exc: return exc is not value except RuntimeError as exc: if exc is value: return False # Avoid suppressing if a StopIteration exception # was passed to throw() and later wrapped into a RuntimeError # (see PEP 479 for sync generators; async generators also # have this behavior). But do this only if the exception wrapped # by the RuntimeError is actully Stop(Async)Iteration (see # issue29692). if isinstance(value, (StopIteration, StopAsyncIteration)): if exc.__cause__ is value: return False raise except BaseException as exc: if exc is not value: raise def asynccontextmanager(func): """@asynccontextmanager decorator. Typical usage: @asynccontextmanager async def some_async_generator(<arguments>): <setup> try: yield <value> finally: <cleanup> This makes this: async with some_async_generator(<arguments>) as <variable>: <body> equivalent to this: <setup> try: <variable> = <value> <body> finally: <cleanup> """ @wraps(func) def helper(*args, **kwds): return _AsyncGeneratorContextManager(func, args, kwds) return helper class _BaseExitStack: """A base class for ExitStack and AsyncExitStack.""" @staticmethod def _create_exit_wrapper(cm, cm_exit): return MethodType(cm_exit, cm) @staticmethod def _create_cb_wrapper(callback, *args, **kwds): def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) return _exit_wrapper def __init__(self): self._exit_callbacks = deque() def pop_all(self): """Preserve the context stack by transferring it to a new instance.""" new_stack = type(self)() new_stack._exit_callbacks = self._exit_callbacks self._exit_callbacks = deque() return new_stack def push(self, exit): """Registers a callback with the standard __exit__ method signature. Can suppress exceptions the same way __exit__ method can. Also accepts any object with an __exit__ method (registering a call to the method instead of the object itself). """ # We use an unbound method rather than a bound method to follow # the standard lookup behaviour for special methods. _cb_type = type(exit) try: exit_method = _cb_type.__exit__ except AttributeError: # Not a context manager, so assume it's a callable. self._push_exit_callback(exit) else: self._push_cm_exit(exit, exit_method) return exit # Allow use as a decorator. def enter_context(self, cm): """Enters the supplied context manager. If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. """ # We look up the special methods on the type to match the with # statement. _cm_type = type(cm) _exit = _cm_type.__exit__ result = _cm_type.__enter__(cm) self._push_cm_exit(cm, _exit) return result def callback(self, callback, *args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper) return callback # Allow use as a decorator def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods.""" _exit_wrapper = self._create_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, True) def _push_exit_callback(self, callback, is_sync=True): self._exit_callbacks.append((is_sync, callback)) # Inspired by discussions on http://bugs.python.org/issue13585 class ExitStack(_BaseExitStack, AbstractContextManager): """Context manager for dynamic management of a stack of exit callbacks. For example: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception. """ def __enter__(self): return self def __exit__(self, *exc_details): received_exc = exc_details[0] is not None # We manipulate the exception state so it behaves as though # we were actually nesting multiple with statements frame_exc = sys.exc_info()[1] def _fix_exception_context(new_exc, old_exc): # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ if exc_context is old_exc: # Context is already set correctly (see issue 20317) return if exc_context is None or exc_context is frame_exc: break new_exc = exc_context # Change the end of the chain to point to the exception # we expect it to reference new_exc.__context__ = old_exc # Callbacks are invoked in LIFO order to match the behaviour of # nested context managers suppressed_exc = False pending_raise = False while self._exit_callbacks: is_sync, cb = self._exit_callbacks.pop() assert is_sync try: if cb(*exc_details): suppressed_exc = True pending_raise = False exc_details = (None, None, None) except: new_exc_details = sys.exc_info() # simulate the stack of exceptions by setting the context _fix_exception_context(new_exc_details[1], exc_details[1]) pending_raise = True exc_details = new_exc_details if pending_raise: try: # bare "raise exc_details[1]" replaces our carefully # set-up context fixed_ctx = exc_details[1].__context__ raise exc_details[1] except BaseException: exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc def close(self): """Immediately unwind the context stack.""" self.__exit__(None, None, None) # Inspired by discussions on https://bugs.python.org/issue29302 class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager): """Async context manager for dynamic management of a stack of exit callbacks. For example: async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) for i in range(5)] # All opened connections will automatically be released at the # end of the async with statement, even if attempts to open a # connection later in the list raise an exception. """ @staticmethod def _create_async_exit_wrapper(cm, cm_exit): return MethodType(cm_exit, cm) @staticmethod def _create_async_cb_wrapper(callback, *args, **kwds): async def _exit_wrapper(exc_type, exc, tb): await callback(*args, **kwds) return _exit_wrapper async def enter_async_context(self, cm): """Enters the supplied async context manager. If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method. """ _cm_type = type(cm) _exit = _cm_type.__aexit__ result = await _cm_type.__aenter__(cm) self._push_async_cm_exit(cm, _exit) return result def push_async_exit(self, exit): """Registers a coroutine function with the standard __aexit__ method signature. Can suppress exceptions the same way __aexit__ method can. Also accepts any object with an __aexit__ method (registering a call to the method instead of the object itself). """ _cb_type = type(exit) try: exit_method = _cb_type.__aexit__ except AttributeError: # Not an async context manager, so assume it's a coroutine function self._push_exit_callback(exit, False) else: self._push_async_cm_exit(exit, exit_method) return exit # Allow use as a decorator def push_async_callback(self, callback, *args, **kwds): """Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions. """ _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper, False) return callback # Allow use as a decorator async def aclose(self): """Immediately unwind the context stack.""" await self.__aexit__(None, None, None) def _push_async_cm_exit(self, cm, cm_exit): """Helper to correctly register coroutine function to __aexit__ method.""" _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, False) async def __aenter__(self): return self async def __aexit__(self, *exc_details): received_exc =
1), (7, 31, 0, -3): (1, 1), (7, 31, 0, -2): (0, 1), (7, 31, 0, -1): (-1, 1), (7, 31, 0, 0): (-1, 1), (7, 31, 0, 1): (-1, 0), (7, 31, 0, 2): (-1, -1), (7, 31, 0, 3): (-1, -1), (7, 31, 0, 4): (-1, 1), (7, 31, 0, 5): (-1, 1), (7, 31, 1, -5): (1, 1), (7, 31, 1, -4): (1, 1), (7, 31, 1, -3): (1, 1), (7, 31, 1, -2): (-1, 1), (7, 31, 1, -1): (-1, 1), (7, 31, 1, 0): (-1, 1), (7, 31, 1, 1): (-1, 0), (7, 31, 1, 2): (-1, -1), (7, 31, 1, 3): (-1, -1), (7, 31, 1, 4): (-1, 1), (7, 31, 1, 5): (-1, 1), (7, 31, 2, -5): (1, 1), (7, 31, 2, -4): (1, 1), (7, 31, 2, -3): (1, 1), (7, 31, 2, -2): (1, 0), (7, 31, 2, -1): (1, -1), (7, 31, 2, 0): (1, 1), (7, 31, 2, 1): (1, 0), (7, 31, 2, 2): (1, 0), (7, 31, 2, 3): (1, 0), (7, 31, 2, 4): (-1, 1), (7, 31, 2, 5): (-1, 1), (7, 31, 3, -5): (0, 1), (7, 31, 3, -4): (0, 1), (7, 31, 3, -3): (0, 1), (7, 31, 3, -2): (0, 0), (7, 31, 3, -1): (0, -1), (7, 31, 3, 0): (0, 1), (7, 31, 3, 1): (0, 1), (7, 31, 3, 2): (0, 1), (7, 31, 3, 3): (0, 1), (7, 31, 3, 4): (0, 1), (7, 31, 3, 5): (0, 1), (7, 31, 4, -5): (0, 1), (7, 31, 4, -4): (0, 1), (7, 31, 4, -3): (0, 1), (7, 31, 4, -2): (0, 0), (7, 31, 4, -1): (-1, -1), (7, 31, 4, 0): (0, 1), (7, 31, 4, 1): (0, 1), (7, 31, 4, 2): (0, 1), (7, 31, 4, 3): (0, 1), (7, 31, 4, 4): (0, 1), (7, 31, 4, 5): (0, 1), (7, 31, 5, -5): (0, 1), (7, 31, 5, -4): (0, 1), (7, 31, 5, -3): (0, 1), (7, 31, 5, -2): (0, 0), (7, 31, 5, -1): (-1, -1), (7, 31, 5, 0): (0, 1), (7, 31, 5, 1): (0, 1), (7, 31, 5, 2): (0, 1), (7, 31, 5, 3): (0, 1), (7, 31, 5, 4): (0, 1), (7, 31, 5, 5): (0, 1), (7, 32, -5, -5): (0, 1), (7, 32, -5, -4): (0, 1), (7, 32, -5, -3): (0, 1), (7, 32, -5, -2): (0, 1), (7, 32, -5, -1): (0, 1), (7, 32, -5, 0): (0, 1), (7, 32, -5, 1): (0, 0), (7, 32, -5, 2): (-1, -1), (7, 32, -5, 3): (0, 1), (7, 32, -5, 4): (0, 1), (7, 32, -5, 5): (0, 1), (7, 32, -4, -5): (0, 1), (7, 32, -4, -4): (-1, 1), (7, 32, -4, -3): (-1, 1), (7, 32, -4, -2): (-1, 1), (7, 32, -4, -1): (0, 1), (7, 32, -4, 0): (0, 1), (7, 32, -4, 1): (0, 0), (7, 32, -4, 2): (-1, -1), (7, 32, -4, 3): (-1, 1), (7, 32, -4, 4): (-1, 1), (7, 32, -4, 5): (-1, 1), (7, 32, -3, -5): (0, 1), (7, 32, -3, -4): (0, 1), (7, 32, -3, -3): (-1, 1), (7, 32, -3, -2): (-1, 1), (7, 32, -3, -1): (0, 1), (7, 32, -3, 0): (0, 1), (7, 32, -3, 1): (0, 0), (7, 32, -3, 2): (-1, -1), (7, 32, -3, 3): (-1, -1), (7, 32, -3, 4): (-1, -1), (7, 32, -3, 5): (-1, 1), (7, 32, -2, -5): (0, 1), (7, 32, -2, -4): (0, 1), (7, 32, -2, -3): (0, 1), (7, 32, -2, -2): (-1, 1), (7, 32, -2, -1): (-1, 1), (7, 32, -2, 0): (-1, 1), (7, 32, -2, 1): (-1, 0), (7, 32, -2, 2): (-1, -1), (7, 32, -2, 3): (-1, -1), (7, 32, -2, 4): (-1, -1), (7, 32, -2, 5): (-1, 1), (7, 32, -1, -5): (-1, 1), (7, 32, -1, -4): (-1, 1), (7, 32, -1, -3): (-1, 1), (7, 32, -1, -2): (-1, 1), (7, 32, -1, -1): (-1, 1), (7, 32, -1, 0): (-1, 1), (7, 32, -1, 1): (-1, 0), (7, 32, -1, 2): (-1, -1), (7, 32, -1, 3): (-1, 0), (7, 32, -1, 4): (-1, -1), (7, 32, -1, 5): (-1, 1), (7, 32, 0, -5): (1, 1), (7, 32, 0, -4): (1, 1), (7, 32, 0, -3): (1, 1), (7, 32, 0, -2): (-1, 1), (7, 32, 0, -1): (-1, 1), (7, 32, 0, 0): (-1, 0), (7, 32, 0, 1): (-1, -1), (7, 32, 0, 2): (-1, -1), (7, 32, 0, 3): (-1, -1), (7, 32, 0, 4): (-1, 1), (7, 32, 0, 5): (-1, 1), (7, 32, 1, -5): (1, 1), (7, 32, 1, -4): (1, 1), (7, 32, 1, -3): (1, 1), (7, 32, 1, -2): (-1, 1), (7, 32, 1, -1): (-1, 1), (7, 32, 1, 0): (-1, 1), (7, 32, 1, 1): (-1, 0), (7, 32, 1, 2): (-1, -1), (7, 32, 1, 3): (-1, 1), (7, 32, 1, 4): (-1, 1), (7, 32, 1, 5): (-1, 1), (7, 32, 2, -5): (1, 1), (7, 32, 2, -4): (1, 1), (7, 32, 2, -3): (1, 0), (7, 32, 2, -2): (1, -1), (7, 32, 2, -1): (1, 1), (7, 32, 2, 0): (1, 0), (7, 32, 2, 1): (1, 0), (7, 32, 2, 2): (1, 0), (7, 32, 2, 3): (-1, 1), (7, 32, 2, 4): (-1, 1), (7, 32, 2, 5): (-1, 1), (7, 32, 3, -5): (0, 1), (7, 32, 3, -4): (0, 1), (7, 32, 3, -3): (0, 0), (7, 32, 3, -2): (0, -1), (7, 32, 3, -1): (0, 1), (7, 32, 3, 0): (0, 1), (7, 32, 3, 1): (0, 1), (7, 32, 3, 2): (0, 1), (7, 32, 3, 3): (0, 1), (7, 32, 3, 4): (0, 1), (7, 32, 3, 5): (0, 1), (7, 32, 4, -5): (0, 1), (7, 32, 4, -4): (0, 1), (7, 32, 4, -3): (0, 0), (7, 32, 4, -2): (-1, -1), (7, 32, 4, -1): (0, 1), (7, 32, 4, 0): (0, 1), (7, 32, 4, 1): (0, 1), (7, 32, 4, 2): (0, 1), (7, 32, 4, 3): (0, 1), (7, 32, 4, 4): (0, 1), (7, 32, 4, 5): (0, 1), (7, 32, 5, -5): (0, 1), (7, 32, 5, -4): (0, 1), (7, 32, 5, -3): (0, 0), (7, 32, 5, -2): (-1, -1), (7, 32, 5, -1): (0, 1), (7, 32, 5, 0): (0, 1), (7, 32, 5, 1): (0, 1), (7, 32, 5, 2): (0, 1), (7, 32, 5, 3): (0, 1), (7, 32, 5, 4): (0, 1), (7, 32, 5, 5): (0, 1), (7, 33, -5, -5): (0, 1), (7, 33, -5, -4): (0, 1), (7, 33, -5, -3): (0, 1), (7, 33, -5, -2): (0, 1), (7, 33, -5, -1): (0, 1), (7, 33, -5, 0): (0, 1), (7, 33, -5, 1): (0, 0), (7, 33, -5, 2): (-1, -1), (7, 33, -5, 3): (0, 1), (7, 33, -5, 4): (0, 1), (7, 33, -5, 5): (0, 1), (7, 33, -4, -5): (-1, 1), (7, 33, -4, -4): (-1, 1), (7, 33, -4, -3): (-1, 1), (7, 33, -4, -2): (0, 1), (7, 33, -4, -1): (0, 1), (7, 33, -4, 0): (0, 1), (7, 33, -4, 1): (0, 0), (7, 33, -4, 2): (-1, -1), (7, 33, -4, 3): (-1, 1), (7, 33, -4, 4): (-1, 1), (7, 33, -4, 5): (-1, 1), (7, 33, -3, -5): (0, 1), (7, 33, -3, -4): (-1, 1), (7, 33, -3, -3): (-1, 1), (7, 33, -3, -2): (0, 1), (7, 33, -3, -1): (0, 1), (7, 33, -3, 0): (0, 1), (7,
<reponame>universvm/sequence-recovery-benchmark<filename>benchmark/visualization.py """Functions for visualizing metrics and comparing different models""" import pandas as pd from benchmark import config import ampal from benchmark import get_cath import gzip from pathlib import Path import numpy as np import numpy as np import matplotlib.pyplot as plt import seaborn as sns import matplotlib.patches as mpatches from sklearn import metrics import matplotlib.backends.backend_pdf from scipy.stats import entropy from typing import List from benchmark import version def _annotate_ampalobj_with_data_tag( ampal_structure, data_to_annotate, tags, ) -> ampal.assembly: """ Assigns a data point to each residue equivalent to the prediction the tag value. The original value of the tag will be reset to the minimum value to allow for a more realistic color comparison. Parameters ---------- ampal_structure : ampal.Assembly or ampal.AmpalContainer Ampal structure to be modified. If an ampal.AmpalContainer is passed, this will take the first Assembly in the ampal.AmpalContainer `ampal_structure[0]`. data_to_annotate : numpy.ndarray of numpy.ndarray of floats Numpy array with data points to annotate (x, n) where x is the numer of arrays with data points (eg, [ entropy, accuracy ] , x = 2n) and n is the number of residues in the structure. tags : t.List[str] List of string tags of the pdb object (eg. "b-factor") Returns ------- ampal_structure : Assembly Ampal structure with modified B-factor and occupancy values. Notes ----- Leo's code. Same as _annotate_ampalobj_with_data_tag from TIMED but can deal with missing unnatural amino acids for compatibility with EvoEF2.""" assert len(tags) == len( data_to_annotate ), "The number of tags to annotate and the type of data to annotate have different lengths." if len(data_to_annotate) > 1: assert len(data_to_annotate[0]) == len(data_to_annotate[1]), ( f"Data to annotatate has shape {len(data_to_annotate[0])} and " f"{len(data_to_annotate[1])}. They should be the same." ) for i, tag in enumerate(tags): # Reset existing values: for atom in ampal_structure.get_atoms(ligands=True, inc_alt_states=True): atom.tags[tag] = np.min(data_to_annotate[i]) # Apply data as tag: for i, tag in enumerate(tags): # Check if chain is Polypeptide (it might be DNA for example...) if isinstance(ampal_structure, ampal.Polypeptide): if len(ampal_structure) != len(data_to_annotate[i]): # EvoEF2 predictions drop uncommon amino acids if len(ampal_structure) - ampal_structure.sequence.count("X") == len( data_to_annotate[i] ): for residue in ampal_structure: counter = 0 if ampal.amino_acids.get_aa_letter(residue) == "X": continue else: for atom in residue: atom.tags[tag] = data_to_annotate[i][counter] counter += 1 else: print("Length is not equal") return for residue, data_val in zip(ampal_structure, data_to_annotate[i]): for atom in residue: atom.tags[tag] = data_val return ampal_structure def show_accuracy( df: pd.DataFrame, pdb: str, predictions: dict, output: Path, path_to_pdbs: Path, ignore_uncommon: bool, ) -> None: """ Parameters ---------- df: pd.DataFrame CATH dataframe. pdb: str PDB code to visualize, format: pdb+CHAIN. predictions: dict Dictionary with predicted sequences, key is PDB+chain. name: str Location of the .pdf file, also title of the plot. output: Path Path to output directory. path_to_pdbs: Path Path to the directory with PDB files. ignore_uncommon=True If True, ignores uncommon residues in accuracy calculations. score_sequence=False True if dictionary contains sequences, False if probability matrices(matrix shape n,20).""" accuracy = [] pdb_df = df[df.PDB == pdb] sequence, prediction, _, _, _ = get_cath.format_sequence( pdb_df, predictions, False, ignore_uncommon, ) entropy_arr = entropy(prediction, base=2, axis=1) prediction = list(get_cath.most_likely_sequence(prediction)) for resa, resb in zip(sequence, prediction): """correct predictions are given constant score so they stand out in the figure. e.g., spectrum q, blue_white_red, maximum=6,minimum=-6 gives nice plots. Bright red shows correct predictions Red shades indicate substitutions with positive score, white=0, blue shades show substiutions with negative score. cartoon putty shows nice entropy visualization.""" if resa == resb: accuracy.append(6) # incorrect predictions are coloured by blossum62 score. else: accuracy.append(get_cath.lookup_blosum62(resa, resb)) path_to_protein = path_to_pdbs / pdb[1:3] / f"pdb{pdb}.ent.gz" with gzip.open(path_to_protein, "rb") as protein: assembly = ampal.load_pdb(protein.read().decode(), path=False) # Deals with structures from NMR as ampal returns Container of Assemblies if isinstance(assembly, ampal.AmpalContainer): warnings.warn(f"Selecting the first state from the NMR structure {assembly.id}") assembly = assembly[0] # select correct chain assembly = assembly[pdb_df.chain.values[0]] curr_annotated_structure = _annotate_ampalobj_with_data_tag( assembly, [accuracy, entropy_arr], tags=["occupancy","bfactor"] ) with open(output, "w") as f: f.write(curr_annotated_structure.pdb) def ramachandran_plot( sequence: List[chr], prediction: List[chr], torsions: List[List[float]], name: str ) -> None: """Plots predicted and true Ramachandran plots for each amino acid. All plots are normalized by true residue count. Takes at least a minute to plot these, so don't plot if not neccessary. Parameters ---------- sequence: List[chr] List with correctly formated (get_cath.format_format_angle_sequence()) sequence. prediction: List[chr] List with correctly formated predictions. Amino acid sequence, not arrays. torsions: List[List[float]] List wit correctly formated torsion angles. name: str Name and location of the figure.""" fig, ax = plt.subplots(20, 3, figsize=(15, 100)) plt.figtext(0.1, 0.99,s='Version: '+version.__version__,figure=fig,fontdict={"size": 12}) # get angles for each amino acids for k, amino_acid in enumerate(config.acids): predicted_angles = [ x for x, residue in zip(torsions, prediction) if residue == amino_acid ] predicted_psi = [ x[2] for x in predicted_angles if (x[2] != None) & (x[1] != None) ] predicted_phi = [ x[1] for x in predicted_angles if (x[1] != None) & (x[2] != None) ] true_angles = [ x for x, residue in zip(torsions, list(sequence)) if residue == amino_acid ] true_psi = [x[2] for x in true_angles if (x[2] != None) & (x[1] != None)] true_phi = [x[1] for x in true_angles if (x[1] != None) & (x[2] != None)] # make a histogram and normalize by residue count array, xedges, yedges = [ x for x in np.histogram2d( predicted_psi, predicted_phi, bins=50, range=[[-180, 180], [-180, 180]] ) ] array = array / len(true_psi) true_array, xedges, yedges = [ x for x in np.histogram2d( true_psi, true_phi, bins=50, range=[[-180, 180], [-180, 180]] ) ] true_array = true_array / len(true_psi) difference = true_array - array # get minimum and maximum counts for true and predicted sequences, use this to keep color maping in both plots identical. Easier to see overprediction. minimum = np.amin([array, true_array]) maximum = np.amax([array, true_array]) # change 0 counts to NaN to show white space. # make Ramachandran plot for predictions. for i, rows in enumerate(array): for j, cols in enumerate(rows): if cols == 0.0: array[i][j] = np.NaN im = ax[k][0].imshow( array, interpolation="none", norm=None, extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap="viridis", vmax=maximum, vmin=minimum, ) fig.colorbar(im, ax=ax[k][0], fraction=0.046) ax[k][0].set_xlim(-180, 180) ax[k][0].set_ylim(-180, 180) ax[k][0].set_xticks(np.arange(-180, 220, 40)) ax[k][0].set_yticks(np.arange(-180, 220, 40)) ax[k][0].set_ylabel("Psi") ax[k][0].set_xlabel("Phi") ax[k][0].set_title(f"Predicted {amino_acid}") # Make Ramachandran plot for true sequence. for i, rows in enumerate(true_array): for j, cols in enumerate(rows): if cols == 0.0: true_array[i][j] = np.NaN im = ax[k][1].imshow( true_array, interpolation="none", norm=None, extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap="viridis", vmax=maximum, vmin=minimum, ) fig.colorbar(im, ax=ax[k][1], fraction=0.046) ax[k][1].set_xlim(-180, 180) ax[k][1].set_ylim(-180, 180) ax[k][1].set_xticks(np.arange(-180, 220, 40)) ax[k][1].set_yticks(np.arange(-180, 220, 40)) ax[k][1].set_ylabel("Psi") ax[k][1].set_xlabel("Phi") ax[k][1].set_title(f"True {amino_acid}") # Make difference plots. for i, rows in enumerate(difference): for j, cols in enumerate(rows): if cols == 0.0: difference[i][j] = np.NaN im = ax[k][2].imshow( difference, interpolation="none", norm=None, extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap="viridis", ) fig.colorbar(im, ax=ax[k][2], fraction=0.046) ax[k][2].set_xlim(-180, 180) ax[k][2].set_ylim(-180, 180) ax[k][2].set_xticks(np.arange(-180, 220, 40)) ax[k][2].set_yticks(np.arange(-180, 220, 40)) ax[k][2].set_ylabel("Psi") ax[k][2].set_xlabel("Phi") ax[k][2].set_title(f"True-Predicted {amino_acid}") plt.tight_layout() plt.savefig(name + "_Ramachandran_plot.pdf") plt.close() def append_zero_residues(arr: np.array) -> np.array: """Sets missing residue count to 0. Needed for per residue metrics plot. Parameters ---------- arr:np.array Array returned by np.unique() with residues and their counts. Returns ------- np.array with added mising residues and 0 counts.""" if len(arr[0]) != 20: temp_dict = {res_code: res_count for res_code, res_count in zip(arr[0], arr[1])} for residue in config.acids: if residue not in temp_dict: temp_dict[residue] = 0 arr = [[], []] arr[1] = [x[1] for x in sorted(temp_dict.items())] arr[0] = [x[0] for x in sorted(temp_dict.items())] return arr def make_model_summary( df: pd.DataFrame, predictions: dict, name: str, path_to_pdb: Path, ignore_uncommon: bool = False, ) -> None: """ Makes a .pdf report whith model metrics. Includes prediction bias, accuracy and macro recall for each secondary structure, accuracy and recall correlation with protein resolution, confusion matrices and accuracy, recall and f1 score for each resiude. Parameters ---------- df: pd.DataFrame CATH dataframe. predictions: dict Dictionary with predicted sequences, key is PDB+chain. name: str Location of the .pdf file, also title of the plot. path_to_pdb: Path Path to the directory with PDB files. ignore_uncommon=True If True, ignores uncommon residues in accuracy calculations. """ fig, ax = plt.subplots(ncols=5, nrows=5, figsize=(30, 40)) #print version plt.figtext(0.1, 0.99,s='Version: '+version.__version__,figure=fig,fontdict={"size": 12}) # show residue distribution and
utils.load_bert_weight_from_ckpt( bert_model=bert_encoder, bert_ckpt_dir=bert_ckpt_dir, repl_patterns=ub.models.bert_sngp.CHECKPOINT_REPL_PATTERNS) logging.info('Loaded BERT checkpoint %s', bert_ckpt_dir) metrics.update({ 'test/negative_log_likelihood': tf.keras.metrics.Mean(), 'test/auroc': tf.keras.metrics.AUC(curve='ROC'), 'test/aupr': tf.keras.metrics.AUC(curve='PR'), 'test/brier': tf.keras.metrics.MeanSquaredError(), 'test/brier_weighted': tf.keras.metrics.MeanSquaredError(), 'test/ece': rm.metrics.ExpectedCalibrationError(num_bins=FLAGS.num_ece_bins), 'test/acc': tf.keras.metrics.Accuracy(), 'test/acc_weighted': tf.keras.metrics.Accuracy(), 'test/eval_time': tf.keras.metrics.Mean(), 'test/stddev': tf.keras.metrics.Mean(), 'test/precision': tf.keras.metrics.Precision(), 'test/recall': tf.keras.metrics.Recall(), 'test/f1': tfa_metrics.F1Score( num_classes=num_classes, average='micro', threshold=FLAGS.ece_label_threshold) }) for policy in ('uncertainty', 'toxicity'): metrics.update({ 'test_{}/calibration_auroc'.format(policy): tc_metrics.CalibrationAUC(curve='ROC'), 'test_{}/calibration_auprc'.format(policy): tc_metrics.CalibrationAUC(curve='PR') }) for fraction in FLAGS.fractions: metrics.update({ 'test_{}/collab_acc_{}'.format(policy, fraction): rm.metrics.OracleCollaborativeAccuracy( fraction=float(fraction), num_bins=FLAGS.num_approx_bins), 'test_{}/abstain_prec_{}'.format(policy, fraction): tc_metrics.AbstainPrecision( abstain_fraction=float(fraction), num_approx_bins=FLAGS.num_approx_bins), 'test_{}/abstain_recall_{}'.format(policy, fraction): tc_metrics.AbstainRecall( abstain_fraction=float(fraction), num_approx_bins=FLAGS.num_approx_bins), 'test_{}/collab_auroc_{}'.format(policy, fraction): tc_metrics.OracleCollaborativeAUC( oracle_fraction=float(fraction), num_bins=FLAGS.num_approx_bins), 'test_{}/collab_auprc_{}'.format(policy, fraction): tc_metrics.OracleCollaborativeAUC( oracle_fraction=float(fraction), curve='PR', num_bins=FLAGS.num_approx_bins), }) for dataset_name, test_dataset in test_datasets.items(): if dataset_name != 'ind': metrics.update({ 'test/nll_{}'.format(dataset_name): tf.keras.metrics.Mean(), 'test/auroc_{}'.format(dataset_name): tf.keras.metrics.AUC(curve='ROC'), 'test/aupr_{}'.format(dataset_name): tf.keras.metrics.AUC(curve='PR'), 'test/brier_{}'.format(dataset_name): tf.keras.metrics.MeanSquaredError(), 'test/brier_weighted_{}'.format(dataset_name): tf.keras.metrics.MeanSquaredError(), 'test/ece_{}'.format(dataset_name): rm.metrics.ExpectedCalibrationError(num_bins=FLAGS.num_ece_bins ), 'test/acc_{}'.format(dataset_name): tf.keras.metrics.Accuracy(), 'test/acc_weighted_{}'.format(dataset_name): tf.keras.metrics.Accuracy(), 'test/eval_time_{}'.format(dataset_name): tf.keras.metrics.Mean(), 'test/stddev_{}'.format(dataset_name): tf.keras.metrics.Mean(), 'test/precision_{}'.format(dataset_name): tf.keras.metrics.Precision(), 'test/recall_{}'.format(dataset_name): tf.keras.metrics.Recall(), 'test/f1_{}'.format(dataset_name): tfa_metrics.F1Score( num_classes=num_classes, average='micro', threshold=FLAGS.ece_label_threshold) }) for policy in ('uncertainty', 'toxicity'): metrics.update({ 'test_{}/calibration_auroc_{}'.format(policy, dataset_name): tc_metrics.CalibrationAUC(curve='ROC'), 'test_{}/calibration_auprc_{}'.format(policy, dataset_name): tc_metrics.CalibrationAUC(curve='PR'), }) for fraction in FLAGS.fractions: metrics.update({ 'test_{}/collab_acc_{}_{}'.format(policy, fraction, dataset_name): rm.metrics.OracleCollaborativeAccuracy( fraction=float(fraction), num_bins=FLAGS.num_approx_bins), 'test_{}/abstain_prec_{}_{}'.format(policy, fraction, dataset_name): tc_metrics.AbstainPrecision( abstain_fraction=float(fraction), num_approx_bins=FLAGS.num_approx_bins), 'test_{}/abstain_recall_{}_{}'.format(policy, fraction, dataset_name): tc_metrics.AbstainRecall( abstain_fraction=float(fraction), num_approx_bins=FLAGS.num_approx_bins), 'test_{}/collab_auroc_{}_{}'.format(policy, fraction, dataset_name): tc_metrics.OracleCollaborativeAUC( oracle_fraction=float(fraction), num_bins=FLAGS.num_approx_bins), 'test_{}/collab_auprc_{}_{}'.format(policy, fraction, dataset_name): tc_metrics.OracleCollaborativeAUC( oracle_fraction=float(fraction), curve='PR', num_bins=FLAGS.num_approx_bins), }) @tf.function def generate_sample_weight(labels, class_weight, label_threshold=0.7): """Generate sample weight for weighted accuracy calculation.""" if label_threshold != 0.7: logging.warning('The class weight was based on `label_threshold` = 0.7, ' 'and weighted accuracy/brier will be meaningless if ' '`label_threshold` is not equal to this value, which is ' 'recommended by Jigsaw Conversation AI team.') labels_int = tf.cast(labels > label_threshold, tf.int32) sample_weight = tf.gather(class_weight, labels_int) return sample_weight @tf.function def train_step(iterator, dataset_name, num_steps): """Training StepFn.""" def step_fn(inputs): """Per-Replica StepFn.""" features, labels, _ = utils.create_feature_and_label(inputs) with tf.GradientTape() as tape: logits = model(features, training=True) if isinstance(logits, (list, tuple)): # If model returns a tuple of (logits, covmat), extract logits logits, _ = logits if FLAGS.use_bfloat16: logits = tf.cast(logits, tf.float32) loss_logits = tf.squeeze(logits, axis=1) if FLAGS.loss_type == 'cross_entropy': logging.info('Using cross entropy loss') negative_log_likelihood = tf.nn.sigmoid_cross_entropy_with_logits( labels, loss_logits) elif FLAGS.loss_type == 'focal_cross_entropy': logging.info('Using focal cross entropy loss') negative_log_likelihood = tfa_losses.sigmoid_focal_crossentropy( labels, loss_logits, alpha=FLAGS.focal_loss_alpha, gamma=FLAGS.focal_loss_gamma, from_logits=True) elif FLAGS.loss_type == 'mse': logging.info('Using mean squared error loss') loss_probs = tf.nn.sigmoid(loss_logits) negative_log_likelihood = tf.keras.losses.mean_squared_error( labels, loss_probs) elif FLAGS.loss_type == 'mae': logging.info('Using mean absolute error loss') loss_probs = tf.nn.sigmoid(loss_logits) negative_log_likelihood = tf.keras.losses.mean_absolute_error( labels, loss_probs) negative_log_likelihood = tf.reduce_mean(negative_log_likelihood) l2_loss = sum(model.losses) loss = negative_log_likelihood + l2_loss # Scale the loss given the TPUStrategy will reduce sum all gradients. scaled_loss = loss / strategy.num_replicas_in_sync grads = tape.gradient(scaled_loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) probs = tf.nn.sigmoid(logits) # Cast labels to discrete for ECE computation. ece_labels = tf.cast(labels > FLAGS.ece_label_threshold, tf.float32) one_hot_labels = tf.one_hot(tf.cast(ece_labels, tf.int32), depth=num_classes) ece_probs = tf.concat([1. - probs, probs], axis=1) auc_probs = tf.squeeze(probs, axis=1) pred_labels = tf.math.argmax(ece_probs, axis=-1) sample_weight = generate_sample_weight( labels, class_weight['train/{}'.format(dataset_name)], FLAGS.ece_label_threshold) metrics['train/negative_log_likelihood'].update_state( negative_log_likelihood) metrics['train/accuracy'].update_state(labels, pred_labels) metrics['train/accuracy_weighted'].update_state( ece_labels, pred_labels, sample_weight=sample_weight) metrics['train/auroc'].update_state(labels, auc_probs) metrics['train/loss'].update_state(loss) metrics['train/ece'].add_batch(ece_probs, label=ece_labels) metrics['train/precision'].update_state(ece_labels, pred_labels) metrics['train/recall'].update_state(ece_labels, pred_labels) metrics['train/f1'].update_state(one_hot_labels, ece_probs) for _ in tf.range(tf.cast(num_steps, tf.int32)): strategy.run(step_fn, args=(next(iterator),)) @tf.function def test_step(iterator, dataset_name): """Evaluation StepFn.""" def step_fn(inputs): """Per-Replica StepFn.""" features, labels, _ = utils.create_feature_and_label(inputs) eval_start_time = time.time() # Compute ensemble prediction over Monte Carlo forward-pass samples. logits_list = [] stddev_list = [] for _ in range(FLAGS.num_mc_samples): logits = model(features, training=False) if isinstance(logits, (list, tuple)): # If model returns a tuple of (logits, covmat), extract both. logits, covmat = logits else: covmat = tf.eye(test_batch_size) if FLAGS.use_bfloat16: logits = tf.cast(logits, tf.float32) covmat = tf.cast(covmat, tf.float32) logits = ed.layers.utils.mean_field_logits( logits, covmat, mean_field_factor=FLAGS.gp_mean_field_factor) stddev = tf.sqrt(tf.linalg.diag_part(covmat)) logits_list.append(logits) stddev_list.append(stddev) eval_time = (time.time() - eval_start_time) / FLAGS.per_core_batch_size # Logits dimension is (num_samples, batch_size, num_classes). logits_list = tf.stack(logits_list, axis=0) stddev_list = tf.stack(stddev_list, axis=0) stddev = tf.reduce_mean(stddev_list, axis=0) probs_list = tf.nn.sigmoid(logits_list) probs = tf.reduce_mean(probs_list, axis=0) # Cast labels to discrete for ECE computation. ece_labels = tf.cast(labels > FLAGS.ece_label_threshold, tf.float32) one_hot_labels = tf.one_hot(tf.cast(ece_labels, tf.int32), depth=num_classes) ece_probs = tf.concat([1. - probs, probs], axis=1) pred_labels = tf.math.argmax(ece_probs, axis=-1) auc_probs = tf.squeeze(probs, axis=1) # Use normalized binary predictive variance as the confidence score. # Since the prediction variance p*(1-p) is within range (0, 0.25), # normalize it by maximum value so the confidence is between (0, 1). calib_confidence = 1. - probs * (1. - probs) / .25 ce = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.broadcast_to( labels, [FLAGS.num_mc_samples, labels.shape[0]]), logits=tf.squeeze(logits_list, axis=-1) ) negative_log_likelihood = -tf.reduce_logsumexp( -ce, axis=0) + tf.math.log(float(FLAGS.num_mc_samples)) negative_log_likelihood = tf.reduce_mean(negative_log_likelihood) sample_weight = generate_sample_weight( labels, class_weight['test/{}'.format(dataset_name)], FLAGS.ece_label_threshold) if dataset_name == 'ind': metrics['test/negative_log_likelihood'].update_state( negative_log_likelihood) metrics['test/auroc'].update_state(labels, auc_probs) metrics['test/aupr'].update_state(labels, auc_probs) metrics['test/brier'].update_state(labels, auc_probs) metrics['test/brier_weighted'].update_state( tf.expand_dims(labels, -1), probs, sample_weight=sample_weight) metrics['test/ece'].add_batch(ece_probs, label=ece_labels) metrics['test/acc'].update_state(ece_labels, pred_labels) metrics['test/acc_weighted'].update_state( ece_labels, pred_labels, sample_weight=sample_weight) metrics['test/eval_time'].update_state(eval_time) metrics['test/stddev'].update_state(stddev) metrics['test/precision'].update_state(ece_labels, pred_labels) metrics['test/recall'].update_state(ece_labels, pred_labels) metrics['test/f1'].update_state(one_hot_labels, ece_probs) for policy in ('uncertainty', 'toxicity'): # calib_confidence or decreasing toxicity score. confidence = 1. - probs if policy == 'toxicity' else calib_confidence binning_confidence = tf.squeeze(confidence) metrics['test_{}/calibration_auroc'.format(policy)].update_state( ece_labels, pred_labels, confidence) metrics['test_{}/calibration_auprc'.format(policy)].update_state( ece_labels, pred_labels, confidence) for fraction in FLAGS.fractions: metrics['test_{}/collab_acc_{}'.format(policy, fraction)].add_batch( ece_probs, label=ece_labels, custom_binning_score=binning_confidence) metrics['test_{}/abstain_prec_{}'.format( policy, fraction)].update_state(ece_labels, pred_labels, confidence) metrics['test_{}/abstain_recall_{}'.format( policy, fraction)].update_state(ece_labels, pred_labels, confidence) metrics['test_{}/collab_auroc_{}'.format( policy, fraction)].update_state( labels, auc_probs, custom_binning_score=binning_confidence) metrics['test_{}/collab_auprc_{}'.format( policy, fraction)].update_state( labels, auc_probs, custom_binning_score=binning_confidence) else: metrics['test/nll_{}'.format(dataset_name)].update_state( negative_log_likelihood) metrics['test/auroc_{}'.format(dataset_name)].update_state( labels, auc_probs) metrics['test/aupr_{}'.format(dataset_name)].update_state( labels, auc_probs) metrics['test/brier_{}'.format(dataset_name)].update_state( labels, auc_probs) metrics['test/brier_weighted_{}'.format(dataset_name)].update_state( tf.expand_dims(labels, -1), probs, sample_weight=sample_weight) metrics['test/ece_{}'.format(dataset_name)].add_batch( ece_probs, label=ece_labels) metrics['test/acc_{}'.format(dataset_name)].update_state( ece_labels, pred_labels) metrics['test/acc_weighted_{}'.format(dataset_name)].update_state( ece_labels, pred_labels, sample_weight=sample_weight) metrics['test/eval_time_{}'.format(dataset_name)].update_state( eval_time) metrics['test/stddev_{}'.format(dataset_name)].update_state(stddev) metrics['test/precision_{}'.format(dataset_name)].update_state( ece_labels, pred_labels) metrics['test/recall_{}'.format(dataset_name)].update_state( ece_labels, pred_labels) metrics['test/f1_{}'.format(dataset_name)].update_state( one_hot_labels, ece_probs) for policy in ('uncertainty', 'toxicity'): # calib_confidence or decreasing toxicity score. confidence = 1. - probs if policy == 'toxicity' else calib_confidence binning_confidence = tf.squeeze(confidence) metrics['test_{}/calibration_auroc_{}'.format( policy, dataset_name)].update_state(ece_labels, pred_labels, confidence) metrics['test_{}/calibration_auprc_{}'.format( policy, dataset_name)].update_state(ece_labels, pred_labels, confidence) for fraction in FLAGS.fractions: metrics['test_{}/collab_acc_{}_{}'.format( policy, fraction, dataset_name)].add_batch( ece_probs, label=ece_labels, custom_binning_score=binning_confidence) metrics['test_{}/abstain_prec_{}_{}'.format( policy, fraction, dataset_name)].update_state(ece_labels, pred_labels, confidence) metrics['test_{}/abstain_recall_{}_{}'.format( policy, fraction, dataset_name)].update_state(ece_labels, pred_labels, confidence) metrics['test_{}/collab_auroc_{}_{}'.format( policy, fraction, dataset_name)].update_state( labels, auc_probs, custom_binning_score=binning_confidence) metrics['test_{}/collab_auprc_{}_{}'.format( policy, fraction, dataset_name)].update_state( labels, auc_probs, custom_binning_score=binning_confidence) strategy.run(step_fn, args=(next(iterator),)) @tf.function def final_eval_step(iterator): """Final Evaluation StepFn to save prediction to directory.""" def step_fn(inputs): bert_features, labels, additional_labels = utils.create_feature_and_label( inputs) logits = model(bert_features, training=False) if isinstance(logits, (list, tuple)): # If model returns a tuple of (logits, covmat), extract both. logits, covmat = logits else: covmat = tf.eye(test_batch_size) if FLAGS.use_bfloat16: logits = tf.cast(logits, tf.float32) covmat = tf.cast(covmat, tf.float32) logits = ed.layers.utils.mean_field_logits( logits, covmat, mean_field_factor=FLAGS.gp_mean_field_factor) features = inputs['input_ids'] return features, logits, labels, additional_labels (per_replica_texts, per_replica_logits, per_replica_labels, per_replica_additional_labels) = ( strategy.run(step_fn, args=(next(iterator),))) if strategy.num_replicas_in_sync > 1: texts_list = tf.concat(per_replica_texts.values, axis=0) logits_list = tf.concat(per_replica_logits.values, axis=0) labels_list = tf.concat(per_replica_labels.values, axis=0) additional_labels_dict = {} for additional_label in utils.IDENTITY_LABELS: if additional_label in per_replica_additional_labels: additional_labels_dict[additional_label] = tf.concat( per_replica_additional_labels[additional_label], axis=0) else: texts_list = per_replica_texts logits_list = per_replica_logits labels_list = per_replica_labels additional_labels_dict = {} for additional_label in utils.IDENTITY_LABELS: if additional_label in per_replica_additional_labels: additional_labels_dict[ additional_label] = per_replica_additional_labels[ additional_label] return texts_list, logits_list, labels_list, additional_labels_dict if FLAGS.prediction_mode: # Prediction and exit. for dataset_name, test_dataset in test_datasets.items(): test_iterator = iter(test_dataset) # pytype: disable=wrong-arg-types message = 'Final eval on dataset {}'.format(dataset_name) logging.info(message) texts_all = [] logits_all = [] labels_all = [] additional_labels_all_dict = {} if 'identity' in dataset_name: for identity_label_name in utils.IDENTITY_LABELS: additional_labels_all_dict[identity_label_name] = [] try: with tf.experimental.async_scope(): for step in range(steps_per_eval[dataset_name]): if step % 20 == 0: message = 'Starting to run eval step {}/{} of dataset: {}'.format( step, steps_per_eval[dataset_name], dataset_name) logging.info(message) (text_step, logits_step, labels_step, additional_labels_dict_step) = final_eval_step(test_iterator) texts_all.append(text_step) logits_all.append(logits_step) labels_all.append(labels_step) if 'identity' in dataset_name: for identity_label_name in utils.IDENTITY_LABELS: additional_labels_all_dict[identity_label_name].append( additional_labels_dict_step[identity_label_name]) except (StopIteration, tf.errors.OutOfRangeError): tf.experimental.async_clear_error() logging.info('Done with eval on %s', dataset_name) texts_all = tf.concat(texts_all, axis=0) logits_all = tf.concat(logits_all, axis=0) labels_all = tf.concat(labels_all, axis=0) additional_labels_all = [] if additional_labels_all_dict: for identity_label_name in utils.IDENTITY_LABELS: additional_labels_all.append( tf.concat( additional_labels_all_dict[identity_label_name], axis=0)) additional_labels_all = tf.convert_to_tensor(additional_labels_all) utils.save_prediction( texts_all.numpy(), path=os.path.join(FLAGS.output_dir, 'texts_{}'.format(dataset_name))) utils.save_prediction( labels_all.numpy(), path=os.path.join(FLAGS.output_dir, 'labels_{}'.format(dataset_name))) utils.save_prediction( logits_all.numpy(), path=os.path.join(FLAGS.output_dir, 'logits_{}'.format(dataset_name))) if 'identity' in dataset_name: utils.save_prediction( additional_labels_all.numpy(), path=os.path.join(FLAGS.output_dir, 'additional_labels_{}'.format(dataset_name))) logging.info('Done with testing on %s', dataset_name) else: # Execute train / eval loop. start_time = time.time() train_iterators = {} for dataset_name, train_dataset in train_datasets.items(): train_iterators[dataset_name] = iter(train_dataset) for epoch in range(initial_epoch, FLAGS.train_epochs): logging.info('Starting to run epoch: %s', epoch) for dataset_name, train_iterator in train_iterators.items(): try: with tf.experimental.async_scope(): train_step( train_iterator, dataset_name, dataset_steps_per_epoch[dataset_name]) current_step = ( epoch * total_steps_per_epoch + dataset_steps_per_epoch[dataset_name]) max_steps = total_steps_per_epoch * FLAGS.train_epochs time_elapsed = time.time() - start_time steps_per_sec = float(current_step) / time_elapsed eta_seconds = (max_steps - current_step) / steps_per_sec message = ('{:.1%} completion: epoch {:d}/{:d}. {:.1f} steps/s. ' 'ETA: {:.0f} min. Time elapsed: {:.0f} min'.format( current_step
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 cloudify.decorators import workflow from cloudify.workflows.tasks_graph import forkjoin from cloudify.workflows import tasks as workflow_tasks def _get_all_nodes_instances(ctx): node_instances = set() for node in ctx.nodes: for instance in node.instances: node_instances.add(instance) return node_instances class InstallationTasksReferences(object): def __init__(self): self.send_event_creating = {} self.set_state_creating = {} self.set_state_started = {} class NodeInstallationTasksSequenceCreator(object): """ This class is used to create a tasks sequence installing one node instance. Considering the order of tasks executions, it enforces the proper dependencies only in context of this particular node instance. """ def create(self, instance, graph, installation_tasks): """ :param installation_tasks: instance of InstallationTasksReferences :param instance: node instance to generate the installation tasks for """ sequence = graph.sequence() sequence.add( instance.set_state('initializing'), forkjoin( installation_tasks.set_state_creating[instance.id], installation_tasks.send_event_creating[instance.id] ), instance.execute_operation('cloudify.interfaces.lifecycle.create'), instance.set_state('created'), forkjoin(*_relationship_operations( instance, 'cloudify.interfaces.relationship_lifecycle.preconfigure' )), forkjoin( instance.set_state('configuring'), instance.send_event('Hey Configuring node') ), instance.execute_operation( 'cloudify.interfaces.lifecycle.configure'), instance.set_state('configured'), forkjoin(*_relationship_operations( instance, 'cloudify.interfaces.relationship_lifecycle.postconfigure' )), forkjoin( instance.set_state('starting'), instance.send_event('Hey Starting node') ), instance.execute_operation('cloudify.interfaces.lifecycle.start')) # If this is a host node, we need to add specific host start # tasks such as waiting for it to start and installing the agent # worker (if necessary) if _is_host_node(instance): sequence.add(*_host_post_start(instance)) sequence.add( forkjoin( instance.execute_operation( 'cloudify.interfaces.monitoring.start'), *_relationship_operations( instance, 'cloudify.interfaces.relationship_lifecycle.establish' )), installation_tasks.set_state_started[instance.id]) class InstallationTasksGraphFinisher(object): def __init__(self, graph, node_instances, intact_nodes, tasks): self.graph = graph self.node_instances = node_instances self.intact_nodes = intact_nodes self.tasks = tasks def _enforce_correct_src_trg_order(self, instance, rel): """ make a dependency between the create tasks (event, state) and the started state task of the target """ target_set_started = self.tasks.set_state_started[rel.target_id] node_set_creating = self.tasks.set_state_creating[instance.id] node_event_creating = self.tasks.send_event_creating[instance.id] self.graph.add_dependency(node_set_creating, target_set_started) self.graph.add_dependency(node_event_creating, target_set_started) def finish_creation(self): # Create task dependencies based on node relationships for instance in self.node_instances: for rel in instance.relationships: self._enforce_correct_src_trg_order(instance, rel) class RuntimeInstallationTasksGraphFinisher(InstallationTasksGraphFinisher): def _enforce_correct_src_trg_order(self, instance, rel): # Handle only nodes within self.node_instances, others are running if rel.target_node_instance in self.node_instances: super(RuntimeInstallationTasksGraphFinisher, self)._enforce_correct_src_trg_order(instance, rel) def finish_creation(self): super(RuntimeInstallationTasksGraphFinisher, self).finish_creation() # Add operations for intact nodes depending on a node instance # belonging to node_instances (which are being reinstalled) for instance in self.intact_nodes: for rel in instance.relationships: if rel.target_node_instance in self.node_instances: trg_started = self.tasks.set_state_started[rel.target_id] establish_ops = _relationship_operations_with_target( rel, 'cloudify.interfaces.relationship_lifecycle.establish') for establish_op, _ in establish_ops: self.graph.add_task(establish_op) self.graph.add_dependency(establish_op, trg_started) def _install_node_instances(ctx, node_instances, intact_nodes, node_tasks_seq_creator, graph_finisher_cls): # switch to graph mode (operations on the context return tasks instead of # result instances) graph = ctx.graph_mode() # We need reference to the create event/state tasks and the started # task so we can later create a proper dependency between nodes and # their relationships. We use the below tasks as part of a single node # workflow, and to create the dependency (at the bottom) tasks = InstallationTasksReferences() for instance in node_instances: tasks.send_event_creating[instance.id] = instance.send_event( 'Hey Creating node') tasks.set_state_creating[instance.id] = instance.set_state('creating') tasks.set_state_started[instance.id] = instance.set_state('started') # Create node linear task sequences # For each node, we create a "task sequence" in which all tasks # added to it will be executed in a sequential manner for instance in node_instances: node_tasks_seq_creator.create(instance, graph, tasks) graph_finisher_cls( graph, node_instances, intact_nodes, tasks ).finish_creation() graph.execute() class UninstallationTasksReferences(object): def __init__(self): self.set_state_stopping = {} self.set_state_deleted = {} self.stop_node = {} self.stop_monitor = {} self.delete_node = {} class NodeUninstallationTasksSequenceCreator(object): def create(self, instance, graph, uninstallation_tasks): unlink_tasks_with_target_ids = _relationship_operations_with_targets( instance, 'cloudify.interfaces.relationship_lifecycle.unlink') sequence = graph.sequence() sequence.add( uninstallation_tasks.set_state_stopping[instance.id], instance.send_event('Stopping node') ) if _is_host_node(instance): sequence.add(*_host_pre_stop(instance)) sequence.add( uninstallation_tasks.stop_node[instance.id], instance.set_state('stopped'), forkjoin(*[task for task, _ in unlink_tasks_with_target_ids]), instance.set_state('deleting'), instance.send_event('Deleting node'), uninstallation_tasks.delete_node[instance.id], uninstallation_tasks.set_state_deleted[instance.id] ) # adding the stop monitor task not as a part of the sequence, # as it can happen in parallel with any other task, and is only # dependent on the set node state 'stopping' task graph.add_task(uninstallation_tasks.stop_monitor[instance.id]) graph.add_dependency( uninstallation_tasks.stop_monitor[instance.id], uninstallation_tasks.set_state_stopping[instance.id] ) # augmenting the stop node, stop monitor and delete node tasks with # error handlers _set_send_node_event_on_error_handler( uninstallation_tasks.stop_node[instance.id], instance, "Error occurred while stopping node - ignoring...") _set_send_node_event_on_error_handler( uninstallation_tasks.stop_monitor[instance.id], instance, "Error occurred while stopping monitor - ignoring...") _set_send_node_event_on_error_handler( uninstallation_tasks.delete_node[instance.id], instance, "Error occurred while deleting node - ignoring...") _set_send_node_evt_on_failed_unlink_handlers( instance, unlink_tasks_with_target_ids) class UninstallationTasksGraphFinisher(object): def __init__(self, graph, node_instances, intact_nodes, tasks): self.graph = graph self.node_instances = node_instances self.intact_nodes = intact_nodes self.tasks = tasks def _enforce_correct_src_trg_order(self, instance, rel): """ make a dependency between the target's stopping task and the deleted state task of the current node """ self.graph.add_dependency( self.tasks.set_state_stopping[rel.target_id], self.tasks.set_state_deleted[instance.id] ) def finish_creation(self): # Create task dependencies based on node relationships for instance in self.node_instances: for rel in instance.relationships: self._enforce_correct_src_trg_order(instance, rel) class RuntimeUninstallationTasksGraphFinisher( UninstallationTasksGraphFinisher): def _enforce_correct_src_trg_order(self, instance, rel): if rel.target_node_instance in self.node_instances: super(RuntimeUninstallationTasksGraphFinisher, self)._enforce_correct_src_trg_order(instance, rel) def finish_creation(self): super(RuntimeUninstallationTasksGraphFinisher, self).finish_creation() for instance in self.intact_nodes: for rel in instance.relationships: if rel.target_node_instance in self.node_instances: target_stopped = self.tasks.stop_node[rel.target_id] unlink_tasks = _relationship_operations_with_target( rel, 'cloudify.interfaces.relationship_lifecycle.unlink') for unlink_task, _ in unlink_tasks: self.graph.add_task(unlink_task) self.graph.add_dependency(unlink_task, target_stopped) _set_send_node_evt_on_failed_unlink_handlers( instance, unlink_tasks) def _uninstall_node_instances(ctx, node_instances, intact_nodes, node_tasks_seq_creator, graph_finisher_cls, graph=None): if not graph: # switch to graph mode (operations on the context return tasks instead # of result instances) graph = ctx.graph_mode() tasks_refs = UninstallationTasksReferences() for instance in node_instances: # We need reference to the set deleted state tasks and the set # stopping state tasks so we can later create a proper dependency # between nodes and their relationships. We use the below tasks as # part of a single node workflow, and to create the dependency # (at the bottom) tasks_refs.set_state_stopping[instance.id] = instance.set_state( 'stopping') tasks_refs.set_state_deleted[instance.id] = instance.set_state( 'deleted') # We need reference to the stop node tasks, stop monitor tasks and # delete node tasks as we augment them with on_failure error # handlers later on tasks_refs.stop_node[instance.id] = instance.execute_operation( 'cloudify.interfaces.lifecycle.stop') tasks_refs.stop_monitor[instance.id] = instance.execute_operation( 'cloudify.interfaces.monitoring.stop') tasks_refs.delete_node[instance.id] = instance.execute_operation( 'cloudify.interfaces.lifecycle.delete') # Create node linear task sequences # For each node, we create a "task sequence" in which all tasks # added to it will be executed in a sequential manner for instance in node_instances: node_tasks_seq_creator.create(instance, graph, tasks_refs) graph_finisher_cls( graph, node_instances, intact_nodes, tasks_refs ).finish_creation() graph.execute() def _set_send_node_event_on_error_handler(task, node_instance, error_message): def send_node_event_error_handler(tsk): node_instance.send_event(error_message) return workflow_tasks.HandlerResult.ignore() task.on_failure = send_node_event_error_handler def _set_send_node_evt_on_failed_unlink_handlers(instance, tasks_with_targets): for unlink_task, target_id in tasks_with_targets: _set_send_node_event_on_error_handler( unlink_task, instance, "Error occurred while unlinking node from node {0} - " "ignoring...".format(target_id) ) def _relationship_operations(node_instance, operation): tasks_with_targets = _relationship_operations_with_targets( node_instance, operation) return [task for task, _ in tasks_with_targets] def _relationship_operations_with_targets(node_instance, operation): tasks = [] for relationship in node_instance.relationships: tasks += _relationship_operations_with_target(relationship, operation) return tasks def _relationship_operations_with_target(relationship, operation): return [ (relationship.execute_source_operation(operation), relationship.target_id), (relationship.execute_target_operation(operation), relationship.target_id) ] def _is_host_node(node_instance): return 'cloudify.nodes.Compute' in node_instance.node.type_hierarchy def _wait_for_host_to_start(host_node_instance): task = host_node_instance.execute_operation( 'cloudify.interfaces.host.get_state') # handler returns True if if get_state returns False, # this means, that get_state will be re-executed until # get_state returns True def node_get_state_handler(tsk): host_started = tsk.async_result.get() if host_started: return workflow_tasks.HandlerResult.cont() else: return workflow_tasks.HandlerResult.retry( ignore_total_retries=True) if not task.is_nop(): task.on_success = node_get_state_handler return task def _host_post_start(host_node_instance): plugins_to_install = filter(lambda plugin: plugin['install'], host_node_instance.node.plugins_to_install) tasks = [_wait_for_host_to_start(host_node_instance)] if host_node_instance.node.properties['install_agent'] is True: tasks += [ host_node_instance.send_event('Installing worker'), host_node_instance.execute_operation( 'cloudify.interfaces.worker_installer.install'), host_node_instance.execute_operation( 'cloudify.interfaces.worker_installer.start'), ] if plugins_to_install: tasks += [ host_node_instance.send_event('Installing host plugins'), host_node_instance.execute_operation( 'cloudify.interfaces.plugin_installer.install', kwargs={ 'plugins': plugins_to_install}), host_node_instance.execute_operation( 'cloudify.interfaces.worker_installer.restart', send_task_events=False) ] tasks += [ host_node_instance.execute_operation( 'cloudify.interfaces.monitoring_agent.install'), host_node_instance.execute_operation( 'cloudify.interfaces.monitoring_agent.start'), ] return tasks def _host_pre_stop(host_node_instance): tasks = [] tasks += [ host_node_instance.execute_operation( 'cloudify.interfaces.monitoring_agent.stop'), host_node_instance.execute_operation( 'cloudify.interfaces.monitoring_agent.uninstall'), ] if host_node_instance.node.properties['install_agent'] is True: tasks += [ host_node_instance.send_event('Uninstalling worker'), host_node_instance.execute_operation( 'cloudify.interfaces.worker_installer.stop'), host_node_instance.execute_operation( 'cloudify.interfaces.worker_installer.uninstall') ] for task in tasks: if task.is_remote(): _set_send_node_event_on_error_handler( task, host_node_instance, 'Error occurred while uninstalling worker - ignoring...') return tasks @workflow def execute_operation(ctx, operation, operation_kwargs, allow_kwargs_override, run_by_dependency_order, type_names, node_ids, node_instance_ids, **kwargs): """ A generic workflow for executing arbitrary operations on nodes """ graph = ctx.graph_mode() send_event_starting_tasks = {} send_event_done_tasks = {} # filtering node instances filtered_node_instances = [] for node in ctx.nodes: if node_ids and node.id not in node_ids: continue if type_names and not next((type_name for type_name in type_names if type_name in node.type_hierarchy), None): continue for instance in node.instances: if node_instance_ids and instance.id not in node_instance_ids: continue filtered_node_instances.append(instance)
assert lst_0_v_0["VersionId"] == vid_s assert lst_0_v_0["VersionStages"] == ["AWSCURRENT"] # lst_0_v_1 = lst_0["Versions"][1] assert lst_0_v_1["VersionId"] == vid_0 assert lst_0_v_1["VersionStages"] == ["one", "two", "three"] put_1 = sm_client.put_secret_value( SecretId=secret_name, SecretString="S2", VersionStages=["one", "two", "three", "four"] ) vid_1 = put_1["VersionId"] assert len({vid_s, vid_0, vid_1}) == 3 lst_1 = sm_client.list_secret_version_ids(SecretId=secret_name) assert len(lst_1["Versions"]) == 2 # lst_1_v_0 = lst_1["Versions"][0] assert lst_1_v_0["VersionId"] == vid_s assert lst_1_v_0["VersionStages"] == ["AWSCURRENT"] # lst_1_v_1 = lst_1["Versions"][1] assert lst_1_v_1["VersionId"] == vid_1 assert lst_1_v_1["VersionStages"] == ["one", "two", "three", "four"] def test_non_versioning_version_stages_no_replacement(self, sm_client): secret_name = f"s-{short_uid()}" create = sm_client.create_secret(Name=secret_name, SecretString="S0") vid_s = create["VersionId"] put_0 = sm_client.put_secret_value( SecretId=secret_name, SecretString="S1", VersionStages=["one", "two", "three"] ) vid_0 = put_0["VersionId"] assert vid_0 != vid_s lst_0 = sm_client.list_secret_version_ids(SecretId=secret_name) assert len(lst_0["Versions"]) == 2 # lst_0_v_0 = lst_0["Versions"][0] assert lst_0_v_0["VersionId"] == vid_s assert lst_0_v_0["VersionStages"] == ["AWSCURRENT"] # lst_0_v_1 = lst_0["Versions"][1] assert lst_0_v_1["VersionId"] == vid_0 assert lst_0_v_1["VersionStages"] == ["one", "two", "three"] put_1 = sm_client.put_secret_value( SecretId=secret_name, SecretString="S2", VersionStages=["one", "two", "four"] ) vid_1 = put_1["VersionId"] assert len({vid_s, vid_0, vid_1}) == 3 lst_1 = sm_client.list_secret_version_ids(SecretId=secret_name) assert len(lst_1["Versions"]) == 3 # lst_1_v_0 = lst_1["Versions"][0] assert lst_1_v_0["VersionId"] == vid_s assert lst_1_v_0["VersionStages"] == ["AWSCURRENT"] # lst_1_v_1 = lst_1["Versions"][1] assert lst_1_v_1["VersionId"] == vid_0 assert lst_1_v_1["VersionStages"] == ["three"] # lst_1_v_2 = lst_1["Versions"][2] assert lst_1_v_2["VersionId"] == vid_1 assert lst_1_v_2["VersionStages"] == ["one", "two", "four"] @staticmethod def secretsmanager_http_json_headers(amz_target: str) -> Dict: headers = aws_stack.mock_aws_request_headers("secretsmanager") headers["X-Amz-Target"] = amz_target return headers def secretsmanager_http_json_post(self, amz_target: str, http_body: json) -> requests.Response: ep_url: str = aws_stack.get_local_service_url("secretsmanager") http_headers: Dict = self.secretsmanager_http_json_headers(amz_target) return requests.post(ep_url, headers=http_headers, data=json.dumps(http_body)) def secretsmanager_http_create_secret_string( self, secret_name: str, secret_string: str ) -> requests.Response: http_body: json = {"Name": secret_name, "SecretString": secret_string} return self.secretsmanager_http_json_post("secretsmanager.CreateSecret", http_body) @staticmethod def secretsmanager_http_create_secret_string_val_res( res: requests.Response, secret_name: str ) -> json: assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_name return res_json def secretsmanager_http_delete_secret(self, secret_id: str) -> requests.Response: http_body: json = {"SecretId": secret_id} return self.secretsmanager_http_json_post("secretsmanager.DeleteSecret", http_body) @staticmethod def secretsmanager_http_delete_secret_val_res(res: requests.Response, secret_id: str) -> json: assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_id return res_json def secretsmanager_http_get_secret_value(self, secret_id: str) -> requests.Response: http_body: json = {"SecretId": secret_id} return self.secretsmanager_http_json_post("secretsmanager.GetSecretValue", http_body) @staticmethod def secretsmanager_http_get_secret_value_val_res( res: requests.Response, secret_name: str, secret_string: str, version_id: str ) -> json: assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_name assert res_json["SecretString"] == secret_string assert res_json["VersionId"] == version_id return res_json def secretsmanager_http_get_secret_value_with( self, secret_id: str, version_stage: str ) -> requests.Response: http_body: json = {"SecretId": secret_id, "VersionStage": version_stage} return self.secretsmanager_http_json_post("secretsmanager.GetSecretValue", http_body) @staticmethod def secretsmanager_http_get_secret_value_with_val_res( res: requests.Response, secret_name: str, secret_string: str, version_id: str, version_stage: str, ) -> json: res_json = TestSecretsManager.secretsmanager_http_get_secret_value_val_res( res, secret_name, secret_string, version_id ) assert res_json["VersionStages"] == [version_stage] return res_json def secretsmanager_http_list_secret_version_ids(self, secret_id: str) -> requests.Response: http_body: json = {"SecretId": secret_id} return self.secretsmanager_http_json_post("secretsmanager.ListSecretVersionIds", http_body) @staticmethod def secretsmanager_http_list_secret_version_ids_val_res( res: requests.Response, secret_name: str, versions: json ) -> json: assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_name res_versions: [json] = res_json["Versions"] assert len(res_versions) == len(versions) assert len(set([rv["VersionId"] for rv in res_versions])) == len(res_versions) assert len(set([v["VersionId"] for v in versions])) == len(versions) for version in versions: vs_in_res: [json] = list( filter(lambda rv: rv["VersionId"] == version["VersionId"], res_versions) ) assert len(vs_in_res) == 1 v_in_res = vs_in_res[0] assert v_in_res["VersionStages"] == version["VersionStages"] return res_json def secretsmanager_http_put_secret_value( self, secret_id: str, secret_string: str ) -> requests.Response: http_body: json = { "SecretId": secret_id, "SecretString": secret_string, } return self.secretsmanager_http_json_post("secretsmanager.PutSecretValue", http_body) @staticmethod def secretsmanager_http_put_secret_value_val_res( res: requests.Response, secret_name: str ) -> json: assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_name return res_json def secretsmanager_http_put_pending_secret_value( self, secret_id: str, secret_string: str ) -> requests.Response: http_body: json = { "SecretId": secret_id, "SecretString": secret_string, "VersionStages": ["AWSPENDING"], } return self.secretsmanager_http_json_post("secretsmanager.PutSecretValue", http_body) @staticmethod def secretsmanager_http_put_pending_secret_value_val_res( res: requests.Response, secret_name: str ) -> json: return TestSecretsManager.secretsmanager_http_put_secret_value_val_res(res, secret_name) def secretsmanager_http_put_secret_value_with( self, secret_id: str, secret_string: str, client_request_token: Optional[str] ) -> requests.Response: http_body: json = { "SecretId": secret_id, "SecretString": secret_string, "ClientRequestToken": client_request_token, } return self.secretsmanager_http_json_post("secretsmanager.PutSecretValue", http_body) @staticmethod def secretsmanager_http_put_secret_value_with_val_res( res: requests.Response, secret_name: str, client_request_token: str ) -> json: assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_name assert res_json["VersionId"] == client_request_token return res_json def secretsmanager_http_update_secret( self, secret_id: str, secret_string: str, client_request_token: Optional[str] ): http_body: json = {"SecretId": secret_id, "SecretString": secret_string} if client_request_token: http_body["ClientRequestToken"] = client_request_token return self.secretsmanager_http_json_post("secretsmanager.UpdateSecret", http_body) @staticmethod def secretsmanager_http_update_secret_val_res( res: requests.Response, secret_name: str, client_request_token: Optional[str] ): assert res.status_code == 200 res_json: json = res.json() assert res_json["Name"] == secret_name if client_request_token: assert res_json["VersionId"] == client_request_token return res_json def secretsmanager_http_put_secret_value_with_version( self, secret_id: str, secret_string: str, client_request_token: Optional[str], version_stages: List[str], ) -> requests.Response: http_body: json = { "SecretId": secret_id, "SecretString": secret_string, "ClientRequestToken": client_request_token, "VersionStages": version_stages, } return self.secretsmanager_http_json_post("secretsmanager.PutSecretValue", http_body) @staticmethod def secretsmanager_http_put_secret_value_with_version_val_res( res: requests.Response, secret_name: str, client_request_token: Optional[str], version_stages: List[str], ) -> json: req_version_id: str if client_request_token is None: assert res.status_code == 200 req_version_id = res.json()["VersionId"] else: req_version_id = client_request_token res_json = TestSecretsManager.secretsmanager_http_put_secret_value_with_val_res( res, secret_name, req_version_id ) assert res_json["VersionStages"] == version_stages return res_json def test_http_update_secret_with_missing_client_request_token(self): secret_name = f"s-{short_uid()}" # Create v0. secret_string_v0: str = "secret_string_v0" cr_v0_res_json: json = self.secretsmanager_http_create_secret_string_val_res( self.secretsmanager_http_create_secret_string(secret_name, secret_string_v0), secret_name, ) version_id_v0 = cr_v0_res_json["VersionId"] # Update with client request token. secret_string_v1: str = "secret_string_v1" version_id_v1: str = str(uuid.uuid4()) self.secretsmanager_http_update_secret_val_res( self.secretsmanager_http_update_secret(secret_name, secret_string_v1, version_id_v1), secret_name, version_id_v1, ) # Get. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v1, version_id_v1, ) # Update without client request token. secret_string_v2: str = "secret_string_v2" res_update_json = self.secretsmanager_http_update_secret_val_res( self.secretsmanager_http_update_secret(secret_name, secret_string_v2, None), secret_name, None, ) version_id_v2 = res_update_json["VersionId"] assert version_id_v2 != version_id_v1 assert version_id_v2 != version_id_v0 # Get. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v2, version_id_v2, ) def test_http_put_secret_value_with_new_custom_client_request_token(self): secret_name = f"s-{short_uid()}" # Create v0. secret_string_v0: str = "MySecretString" cr_v0_res_json: json = self.secretsmanager_http_create_secret_string_val_res( self.secretsmanager_http_create_secret_string(secret_name, secret_string_v0), secret_name, ) # # Check v0 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v0, cr_v0_res_json["VersionId"], ) # Update v0 with predefined ClientRequestToken. secret_string_v1: str = "MyNewSecretString" # crt_v1: str = str(uuid.uuid4()) while crt_v1 == cr_v0_res_json["VersionId"]: crt_v1 = str(uuid.uuid4()) # self.secretsmanager_http_put_secret_value_val_res( self.secretsmanager_http_put_secret_value_with(secret_name, secret_string_v1, crt_v1), secret_name, ) # # Check v1 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v1, crt_v1, ) # # Check versioning base consistency. versions_v0_v1: json = [ {"VersionId": cr_v0_res_json["VersionId"], "VersionStages": ["AWSPREVIOUS"]}, {"VersionId": crt_v1, "VersionStages": ["AWSCURRENT"]}, ] self.secretsmanager_http_list_secret_version_ids_val_res( self.secretsmanager_http_list_secret_version_ids(secret_name), secret_name, versions_v0_v1, ) self.secretsmanager_http_delete_secret_val_res( self.secretsmanager_http_delete_secret(secret_name), secret_name ) def test_http_put_secret_value_with_duplicate_client_request_token(self): secret_name = f"s-{short_uid()}" # Create v0. secret_string_v0: str = "MySecretString" cr_v0_res_json: json = self.secretsmanager_http_create_secret_string_val_res( self.secretsmanager_http_create_secret_string(secret_name, secret_string_v0), secret_name, ) # # Check v0 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v0, cr_v0_res_json["VersionId"], ) # Update v0 with duplicate ClientRequestToken. secret_string_v1: str = "MyNewSecretString" # crt_v1: str = cr_v0_res_json["VersionId"] # self.secretsmanager_http_put_secret_value_val_res( self.secretsmanager_http_put_secret_value_with(secret_name, secret_string_v1, crt_v1), secret_name, ) # # Check v1 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v1, crt_v1, ) # # Check versioning base consistency. versions_v0_v1: json = [{"VersionId": crt_v1, "VersionStages": ["AWSCURRENT"]}] self.secretsmanager_http_list_secret_version_ids_val_res( self.secretsmanager_http_list_secret_version_ids(secret_name), secret_name, versions_v0_v1, ) self.secretsmanager_http_delete_secret_val_res( self.secretsmanager_http_delete_secret(secret_name), secret_name ) def test_http_put_secret_value_with_null_client_request_token(self): secret_name = f"s-{short_uid()}" # Create v0. secret_string_v0: str = "MySecretString" cr_v0_res_json: json = self.secretsmanager_http_create_secret_string_val_res( self.secretsmanager_http_create_secret_string(secret_name, secret_string_v0), secret_name, ) # # Check v0 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v0, cr_v0_res_json["VersionId"], ) # Update v0 with null ClientRequestToken. secret_string_v1: str = "MyNewSecretString" # pv_v1_res_json = self.secretsmanager_http_put_secret_value_val_res( self.secretsmanager_http_put_secret_value_with(secret_name, secret_string_v1, None), secret_name, ) # # Check v1 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v1, pv_v1_res_json["VersionId"], ) # # Check versioning base consistency. versions_v0_v1: json = [ {"VersionId": cr_v0_res_json["VersionId"], "VersionStages": ["AWSPREVIOUS"]}, {"VersionId": pv_v1_res_json["VersionId"], "VersionStages": ["AWSCURRENT"]}, ] self.secretsmanager_http_list_secret_version_ids_val_res( self.secretsmanager_http_list_secret_version_ids(secret_name), secret_name, versions_v0_v1, ) self.secretsmanager_http_delete_secret_val_res( self.secretsmanager_http_delete_secret(secret_name), secret_name ) def test_http_put_secret_value_with_undefined_client_request_token(self): secret_name = f"s-{short_uid()}" # Create v0. secret_string_v0: str = "MySecretString" cr_v0_res_json: json = self.secretsmanager_http_create_secret_string_val_res( self.secretsmanager_http_create_secret_string(secret_name, secret_string_v0), secret_name, ) # # Check v0 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v0, cr_v0_res_json["VersionId"], ) # Update v0 with undefined ClientRequestToken. secret_string_v1: str = "MyNewSecretString" # pv_v1_res_json = self.secretsmanager_http_put_secret_value_val_res( self.secretsmanager_http_put_secret_value(secret_name, secret_string_v1), secret_name ) # # Check v1 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v1, pv_v1_res_json["VersionId"], ) # # Check versioning base consistency. versions_v0_v1: json = [ {"VersionId": cr_v0_res_json["VersionId"], "VersionStages": ["AWSPREVIOUS"]}, {"VersionId": pv_v1_res_json["VersionId"], "VersionStages": ["AWSCURRENT"]}, ] self.secretsmanager_http_list_secret_version_ids_val_res( self.secretsmanager_http_list_secret_version_ids(secret_name), secret_name, versions_v0_v1, ) self.secretsmanager_http_delete_secret_val_res( self.secretsmanager_http_delete_secret(secret_name), secret_name ) def test_http_put_secret_value_duplicate_req(self): secret_name = f"s-{short_uid()}" # Create v0. secret_string_v0: str = "MySecretString" cr_v0_res_json: json = self.secretsmanager_http_create_secret_string_val_res( self.secretsmanager_http_create_secret_string(secret_name, secret_string_v0), secret_name, ) # # Check v0 base consistency. self.secretsmanager_http_get_secret_value_val_res( self.secretsmanager_http_get_secret_value(secret_name), secret_name, secret_string_v0, cr_v0_res_json["VersionId"], ) # Duplicate update. self.secretsmanager_http_put_secret_value_val_res( self.secretsmanager_http_put_secret_value_with( secret_name, secret_string_v0, cr_v0_res_json["VersionId"] ), secret_name, ) # # Check v1 base
# -*- coding: utf-8 -*- ''' raeting module provides constants and values for the RAET protocol Packet Data Format. The data used to initialize a packet is an ordered dict with several fields most of the fields are shared with the header data format below so only the unique fields are shown here. Unique Packet data fields sh: source host ip address (ipv4) Default: '' sp: source ip port Default: 7532 dh: destination host ip address (ipv4) Default: '127.0.0.1' dp: destination host ip port Default 7532 Header Data Format. The .data in the packet header is an ordered dict which is used to either create a packet to transmit or holds the field from a received packet. What fields are included in a header is dependent on the header kind. Header encoding. When the head kind is json = 0,then certain optimizations are used to minimize the header length. The header field keys are two bytes long If a header field value is the default then the field is not included Lengths are encoded as hex strings The flags are encoded as a double char hex string in field 'fg' header data = { hk: header kind (HeadKind) Default 0 hl: header length (HeadLen) Default 0 vn: version (Version) Default 0 sd: Source Device ID (SDID) dd: Destination Device ID (DDID) cf: Corresponder Flag (CrdrFlag) Default 0 bf: BroadCast Flag (BcstFlag) Default 0 si: Session ID (SID) Default 0 ti: Transaction ID (TID) Default 0 sk: Service Kind (SrvcKind) pk: Packet Kind (PcktKind) sf: Succedent Flag (ScdtFlag) Default 0 Send segments or ordered packets without waiting for interleafed acks oi: order index (OrdrIndx) Default 0 dt: Datetime Stamp (Datetime) Default 0 sn: Segment Number (SegNum) Default 0 sc: Segment Count (SegCnt) Default 1 pf: Pending Segment Flag (PendFlag) Default 0 Not the last segment more pending af: All Flag (AllFlag) Default 0 Resend all segments not just one nk: Neck header kind (NeckKind) Default 0 nl: Neck header length (NeckLen) Default 0 bk: body kind (BodyKind) Default 0 bl: body length (BodyLen) Default 0 tk: tail kind (TailKind) Default 0 tl: tail length (TailLen) Default 0 fg: flags packed (Flags) Default '00' hs 2 char Hex string with bits (0, 0, af, pf, 0, sf, bf, cf) Zeros are TBD flags } Body Data Format The Body .data is a Mapping Body Encoding When the body kind is json = 0, then the .data is json encoded Body Decoding ''' # pylint: disable=C0103 # Import python libs from collections import namedtuple, Mapping try: import simplejson as json except ImportError: import json # Import ioflo libs from ioflo.base.odicting import odict RAET_PORT = 7530 RAET_TEST_PORT = 7531 MAX_HEAD_LEN = 255 JSON_END = '\r\n\r\n' HEAD_KINDS = odict([('raet', 0), ('json', 1), ('binary', 2), ('unknown', 255)]) HEAD_KIND_NAMES = odict((v, k) for k, v in HEAD_KINDS.iteritems()) # inverse map HeadKind = namedtuple('HeadKind', HEAD_KINDS.keys()) headKinds = HeadKind(**HEAD_KINDS) # headKinds.json is '00' VERSIONS = odict([('0.1', 0)]) VERSION_NAMES = odict((v, k) for k, v in VERSIONS.iteritems()) VERSION = VERSIONS.values()[0] NECK_KINDS = odict([('nada', 0), ('nacl', 1), ('sha2', 2), ('crc64', 2), ('unknown', 255)]) NECK_KIND_NAMES = odict((v, k) for k, v in NECK_KINDS.iteritems()) # inverse map NeckKind = namedtuple('NeckKind', NECK_KINDS.keys()) neckKinds = NeckKind(**NECK_KINDS) # bytes NECK_SIZES = odict([('nada', 0), ('nacl', 64), ('sha2', 0), ('crc64', 8), ('unknown', 0)]) NeckSize = namedtuple('NeckSize', NECK_SIZES.keys()) neckSizes = NeckSize(**NECK_SIZES) BODY_KINDS = odict([('nada', 0), ('json', 1), ('msgpck', 1), ('unknown', 255)]) BODY_KIND_NAMES = odict((v, k) for k, v in BODY_KINDS.iteritems()) # inverse map BodyKind = namedtuple('BodyKind', BODY_KINDS.keys()) bodyKinds = BodyKind(**BODY_KINDS) TAIL_KINDS = odict([('nada', 0), ('nacl', 1), ('crc16', 2), ('crc64', 3), ('unknown', 255)]) TAIL_KIND_NAMES = odict((v, k) for k, v in TAIL_KINDS.iteritems()) # inverse map TailKind = namedtuple('TailKind', TAIL_KINDS.keys()) tailKinds = TailKind(**TAIL_KINDS) # bytes TAIL_SIZES = odict([('nada', 0), ('nacl', 8), ('crc16', 2), ('crc64', 8), ('unknown', 0)]) TailSize = namedtuple('TailSize', TAIL_SIZES.keys()) tailSizes = TailSize(**TAIL_SIZES) SERVICE_KINDS = odict([('fireforget', 0), ('ackretry', 1), ( 'unknown', 255)]) SERVICE_KIND_NAMES = odict((v, k) for k, v in SERVICE_KINDS.iteritems()) # inverse map ServiceKind = namedtuple('ServiceKind', SERVICE_KINDS.keys()) serviceKinds = ServiceKind(**SERVICE_KINDS) PACKET_KINDS = odict([('data', 0), ('req', 1), ('ack', 8), ('nack', 9), ('unknown', 255)]) PACKET_KIND_NAMES = odict((v, k) for k, v in PACKET_KINDS.iteritems()) # inverse map PacketKind = namedtuple('PacketKind', PACKET_KINDS.keys()) packetKinds = PacketKind(**PACKET_KINDS) # head fields that may be included in json header if not default value PACKET_DEFAULTS = odict([ ('sh', ''), ('sp', 7530), ('dh', '127.0.0.1'), ('dp', 7530), ('hk', 0), ('hl', 0), ('vn', 0), ('sd', 0), ('dd', 0), ('cf', 0), ('bf', 0), ('si', 0), ('ti', 0), ('sk', 0), ('pk', 0), ('sf', 0), ('oi', 0), ('dt', 0), ('sn', 0), ('sc', 1), ('pf', 0), ('af', 0), ('nk', 0), ('nl', 0), ('bk', 0), ('bl', 0), ('tk', 0), ('tl', 0), ('fg', '00'), ]) PACKET_FIELDS = ['sh', 'sp', 'dh', 'dp', 'hk', 'hl', 'vn', 'sd', 'dd', 'cf', 'bf', 'si', 'ti', 'sk', 'pk', 'sf', 'oi', 'dt', 'sn', 'sc', 'pf', 'af', 'nk', 'nl', 'bk', 'bl', 'tk', 'tl', 'fg'] HEAD_FIELDS = ['hk', 'hl', 'vn', 'sd', 'dd', 'cf', 'bf', 'si', 'ti', 'sk', 'pk', 'sf', 'oi', 'dt', 'sn', 'sc', 'pf', 'af', 'nk', 'nl', 'bk', 'bl', 'tk', 'tl', 'fg'] PACKET_FLAGS = ['af', 'pf', 'sf', 'bf', 'cf'] PACKET_FLAG_FIELDS = ['', '', 'af', 'pf', '', 'sf', 'bf', 'cf'] class RaetError(Exception): """Used to indicate error in RAET Protocol usage: msg = "Invalid device id '{0}'".format(did) raise raeting.RaetError(msg) """ def __init__(self, message=None): self.message = message # description of error super(RaetError, self).__init__(message) def __str__(self): return "{0}: {1}.\n".format(self.__class__.__name__, self.message) def defaultData(data=None): ''' Returns defaulted data ''' if data is None: data = odict() for part in DATA_PARTS: # make sure all parts in data if part not in data: data[part] = odict() if 'pack' not in data: data['pack'] = '' return data def updateMissing(kit, defaults): ''' Update kit dict with item from default if item missing in kit ''' for k, v in defaults.items(): if k not in kit: kit[k] = v def packPacket(data): ''' Uses data to create packed version and assigns to pack field in data Also returns packed packet ''' meta = data['meta'] head = data['head'] neck = data['neck'] body = data['body'] tail = data['tail'] packBody(meta, body) packTail(meta, body, tail) packHead(meta, head) packNeck(meta, head, neck) data['pack'] = '{0}{1}{2}{3}'.format(head['pack'], neck['pack'], body['pack'], tail['pack']) return data['pack'] def packBody(meta, body): ''' Uses meta, and body data to create packed version updates fields in body ''' body['pack'] = '' if meta.get('bk') == bodyKinds.json: kit = body.get('raw', '') or body.get('data', {}) packed = json.dumps(kit, separators=(',', ':')) body['pack'] = packed meta['bl'] = len(body['pack']) def packTail(meta, body, tail): ''' Uses meta, and body data to create packed version of tail and updates meta and tail ''' tail['pack'] = '' if meta.get('tk') == tailKinds.nada: pass meta['tl'] = len(tail['pack']) def packHead(meta, head): ''' Uses meta and head data to create packed version and assigns to pack field in head ''' meta['error'] = '' head['pack'] = '' if head.get('hk') == headKinds.json: kit = odict() for field in META_LEN_FIELDS: head[field] = meta[field] for field in META_KIND_FIELDS: head[field] = meta[field] for k, v in HEAD_DEFAULTS.items(): if v is None: kit[k] = head[k] else: if head[k] != v: kit[k] = head[k] kit['hl'] = '00' # need hex string so fixed length and jsonable packed = json.dumps(kit, separators=(',', ':'), encoding='ascii',) packed = '{0}{1}'.format(packed, JSON_END) hl = len(packed) if hl > MAX_HEAD_LEN: meta['error'] = "Head length of {0}, exceeds max of {1}".format(hl, MAX_HEAD_LEN) meta['hl'] = 0 return meta['hl'] = head['hl'] = hl #subsitute true length converted to 2 byte hex string packed = packed.replace('"hl":"00"', '"hl":"{0}"'.format("{0:02x}".format(hl)[-2:]), 1) head['pack'] = packed def packNeck(meta, head, neck): ''' Signs the head and puts auth signature into neck ''' neck['pack'] = '' if meta.get('nk') == neckKinds.nada: pass meta['nl'] = len(neck['pack']) def parsePacket(data): ''' Parses raw packet data in data['pack'] and updates data ''' meta = data['meta'] head = data['head'] neck = data['neck'] body = data['body'] tail = data['tail'] pack = data['pack'] updateMissing(meta, META_DEFAULTS) meta['error'] = '' rest = parseHead(pack, meta, head) rest = parseNeck(rest, meta, neck) if not vouchHead(meta, head, neck): return rest = parseBody(rest, meta, body) rest = parseTail(rest, meta, tail) if not verifyBody(meta, head, tail): return return rest def parseHead(pack, meta, head): ''' Parses and removes head from pack and returns remainder updates meta and head dicts: ''' meta['error'] = '' #need to test for Header type and version if pack.startswith('{"hk":0,') and JSON_END in pack: # json header meta['hk'] = headKinds.json front, sep, back = pack.partition(JSON_END) pack =
1, x] or mask_2d[y - 1, x] or mask_2d[y, x + 1] or mask_2d[y, x - 1] or mask_2d[y + 1, x + 1] or mask_2d[y + 1, x - 1] or mask_2d[y - 1, x + 1] or mask_2d[y - 1, x - 1] ): return True else: return False @decorator_util.jit() def total_edge_pixels_from(mask_2d: np.ndarray) -> int: """ Returns the total number of edge-pixels in a mask. An edge pixel is defined as a pixel on the mask which is unmasked (has a `False`) value and at least 1 of its 8 direct neighbors is masked (is `True`). Parameters ---------- mask_2d : np.ndarray The mask for which the total number of edge pixels is computed. Returns ------- int The total number of edge pixels. """ edge_pixel_total = 0 for y in range(1, mask_2d.shape[0] - 1): for x in range(1, mask_2d.shape[1] - 1): if not mask_2d[y, x]: if check_if_edge_pixel(mask_2d=mask_2d, y=y, x=x): edge_pixel_total += 1 return edge_pixel_total @decorator_util.jit() def edge_1d_indexes_from(mask_2d: np.ndarray) -> np.ndarray: """ Returns a 1D array listing all edge pixel indexes in the mask. An edge pixel is defined as a pixel on the mask which is unmasked (has a `False`) value and at least 1 of its 8 direct neighbors is masked (is `True`). Parameters ---------- mask_2d : np.ndarray The mask for which the 1D edge pixel indexes are computed. Returns ------- np.ndarray The 1D indexes of all edge pixels on the mask. """ edge_pixel_total = total_edge_pixels_from(mask_2d) edge_pixels = np.zeros(edge_pixel_total) edge_index = 0 regular_index = 0 for y in range(1, mask_2d.shape[0] - 1): for x in range(1, mask_2d.shape[1] - 1): if not mask_2d[y, x]: if ( mask_2d[y + 1, x] or mask_2d[y - 1, x] or mask_2d[y, x + 1] or mask_2d[y, x - 1] or mask_2d[y + 1, x + 1] or mask_2d[y + 1, x - 1] or mask_2d[y - 1, x + 1] or mask_2d[y - 1, x - 1] ): edge_pixels[edge_index] = regular_index edge_index += 1 regular_index += 1 return edge_pixels @decorator_util.jit() def check_if_border_pixel( mask_2d: np.ndarray, edge_pixel_slim: int, native_to_slim: np.ndarray ) -> bool: """ Checks if an input [y,x] pixel on the input `mask` is a border-pixel. A borders pixel is a pixel which: 1) is not fully surrounding by `False` mask values. 2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards, left, right). The borders pixels are thus pixels which are on the exterior edge of the mask. For example, the inner ring of edge pixels in an annular mask are edge pixels but not borders pixels. Parameters ---------- mask_2d : np.ndarray The mask for which the input pixel is checked if it is a border pixel. edge_pixel_slim : int The edge pixel index in 1D that is checked if it is a border pixel (this 1D index is mapped to 2d via the array `sub_native_index_for_sub_slim_index_2d`). native_to_slim : np.ndarray An array describing the native 2D array index that every slimmed array index maps too. Returns ------- bool If `True` the pixel on the mask is a border pixel, else a `False` is returned because it is not. """ edge_pixel_index = int(edge_pixel_slim) y = int(native_to_slim[edge_pixel_index, 0]) x = int(native_to_slim[edge_pixel_index, 1]) if ( np.sum(mask_2d[0:y, x]) == y or np.sum(mask_2d[y, x : mask_2d.shape[1]]) == mask_2d.shape[1] - x - 1 or np.sum(mask_2d[y : mask_2d.shape[0], x]) == mask_2d.shape[0] - y - 1 or np.sum(mask_2d[y, 0:x]) == x ): return True else: return False @decorator_util.jit() def total_border_pixels_from(mask_2d, edge_pixels, native_to_slim): """ Returns the total number of border-pixels in a mask. A borders pixel is a pixel which: 1) is not fully surrounding by `False` mask values. 2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards, left, right). The borders pixels are thus pixels which are on the exterior edge of the mask. For example, the inner ring of edge pixels in an annular mask are edge pixels but not borders pixels. Parameters ---------- mask_2d : np.ndarray The mask for which the total number of border pixels is computed. edge_pixel_1d : int The edge pixel index in 1D that is checked if it is a border pixel (this 1D index is mapped to 2d via the array `sub_native_index_for_sub_slim_index_2d`). native_to_slim : np.ndarray An array describing the 2D array index that every 1D array index maps too. Returns ------- int The total number of border pixels. """ border_pixel_total = 0 for i in range(edge_pixels.shape[0]): if check_if_border_pixel(mask_2d, edge_pixels[i], native_to_slim): border_pixel_total += 1 return border_pixel_total @decorator_util.jit() def border_slim_indexes_from(mask_2d: np.ndarray) -> np.ndarray: """ Returns a slim array of shape [total_unmasked_border_pixels] listing all borders pixel indexes in the mask. A borders pixel is a pixel which: 1) is not fully surrounding by `False` mask values. 2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards, left, right). The borders pixels are thus pixels which are on the exterior edge of the mask. For example, the inner ring of edge pixels in an annular mask are edge pixels but not borders pixels. Parameters ---------- mask_2d : np.ndarray The mask for which the slimmed border pixel indexes are calculated. Returns ------- np.ndarray The slimmed indexes of all border pixels on the mask. """ edge_pixels = edge_1d_indexes_from(mask_2d=mask_2d) sub_native_index_for_sub_slim_index_2d = native_index_for_slim_index_2d_from( mask_2d=mask_2d, sub_size=1 ) border_pixel_total = total_border_pixels_from( mask_2d=mask_2d, edge_pixels=edge_pixels, native_to_slim=sub_native_index_for_sub_slim_index_2d, ) border_pixels = np.zeros(border_pixel_total) border_pixel_index = 0 for edge_pixel_index in range(edge_pixels.shape[0]): if check_if_border_pixel( mask_2d=mask_2d, edge_pixel_slim=edge_pixels[edge_pixel_index], native_to_slim=sub_native_index_for_sub_slim_index_2d, ): border_pixels[border_pixel_index] = edge_pixels[edge_pixel_index] border_pixel_index += 1 return border_pixels def sub_border_pixel_slim_indexes_from( mask_2d: np.ndarray, sub_size: int ) -> np.ndarray: """ Returns a slim array of shape [total_unmasked_border_pixels] listing all sub-borders pixel indexes in the mask. A borders pixel is a pixel which: 1) is not fully surrounding by `False` mask values. 2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards, left, right). The borders pixels are thus pixels which are on the exterior edge of the mask. For example, the inner ring of edge pixels in an annular mask are edge pixels but not borders pixels. A sub-border pixel is, for a border-pixel, the pixel within that border pixel which is furthest from the origin of the mask. Parameters ---------- mask_2d : np.ndarray The mask for which the 1D border pixel indexes are calculated. sub_size : int The size of the sub-grid in each mask pixel. Returns ------- np.ndarray The 1D indexes of all border sub-pixels on the mask. """ border_pixels = border_slim_indexes_from(mask_2d=mask_2d) sub_border_pixels = np.zeros(shape=border_pixels.shape[0]) sub_slim_indexes_for_slim_index = sub_slim_indexes_for_slim_index_via_mask_2d_from( mask_2d=mask_2d, sub_size=sub_size ) sub_grid_2d_slim = grid_2d_util.grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=(1.0, 1.0), sub_size=sub_size, origin=(0.0, 0.0) ) mask_centre = grid_2d_util.grid_2d_centre_from(grid_2d_slim=sub_grid_2d_slim) for (border_1d_index, border_pixel) in enumerate(border_pixels): sub_border_pixels_of_border_pixel = sub_slim_indexes_for_slim_index[ int(border_pixel) ] sub_border_pixels[ border_1d_index ] = grid_2d_util.furthest_grid_2d_slim_index_from( grid_2d_slim=sub_grid_2d_slim, slim_indexes=sub_border_pixels_of_border_pixel, coordinate=mask_centre, ) return sub_border_pixels @decorator_util.jit() def buffed_mask_2d_from(mask_2d: np.ndarray, buffer: int = 1) -> np.ndarray: """ Returns a buffed mask from an input mask, where the buffed mask is the input mask but all `False` entries in the mask are buffed by an integer amount in all 8 surrouning pixels. Parameters ---------- mask_2d : np.ndarray The mask whose `False` entries are buffed. buffer : int The number of pixels around each `False` entry that pixel are buffed in all 8 directions. Returns ------- np.ndarray The buffed mask. """ buffed_mask_2d = mask_2d.copy() for y in range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]): if not mask_2d[y, x]: for y0 in range(y - buffer, y + 1 + buffer): for x0 in range(x - buffer, x + 1 + buffer): if ( y0 >= 0 and x0 >= 0 and y0 <= mask_2d.shape[0] - 1 and x0 <= mask_2d.shape[1] - 1 ): buffed_mask_2d[y0, x0] = False return buffed_mask_2d def rescaled_mask_2d_from(mask_2d: np.ndarray, rescale_factor: float) -> np.ndarray: """ Returns a rescaled mask from an input mask, where the rescaled mask is the input mask but rescaled to a larger or smaller size depending on the `rescale_factor`.
dict dictionary containing the output ind_rad : int radar index """ if procstatus == 0: return None, None keep_points = dscfg.get('keep_points', False) if procstatus == 2: if not keep_points or dscfg['initialized'] == 0: return None, None return ( {'selfconsistency_points': dscfg['global_data']['selfconsistency_points']}, None) temp = None iso0 = None hydro = None for datatypedescr in dscfg['datatype']: radarnr, _, datatype, _, _ = get_datatype_fields(datatypedescr) if datatype == 'dBZc': refl = 'corrected_reflectivity' if datatype == 'dBZ': refl = 'reflectivity' if datatype == 'ZDRc': zdr = 'corrected_differential_reflectivity' if datatype == 'ZDR': zdr = 'differential_reflectivity' if datatype == 'PhiDPc': phidp = 'corrected_differential_phase' if datatype == 'PhiDP': phidp = 'differential_phase' if datatype == 'TEMP': temp = 'temperature' if datatype == 'H_ISO0': iso0 = 'height_over_iso0' if datatype == 'hydro': hydro = 'radar_echo_classification' if datatype == 'RhoHV': rhohv = 'cross_correlation_ratio' if datatype == 'RhoHVc': rhohv = 'corrected_cross_correlation_ratio' if datatype == 'uRhoHV': rhohv = 'uncorrected_cross_correlation_ratio' ind_rad = int(radarnr[5:8])-1 if radar_list[ind_rad] is None: warn('No valid radar') return None, None radar = radar_list[ind_rad] if ((refl not in radar.fields) or (zdr not in radar.fields) or (phidp not in radar.fields) or (rhohv not in radar.fields)): warn('Unable to estimate reflectivity bias using selfconsistency. ' + 'Missing data') return None, None # determine which freezing level reference if temp is not None: if temp in radar.fields: temp_ref = 'temperature' else: warn('COSMO temperature field not available. ' + 'Using fixed freezing level height to determine liquid phase') temp_ref = 'fixed_fzl' elif iso0 is not None: if iso0 in radar.fields: temp_ref = 'height_over_iso0' else: warn('Height over iso0 field not available. ' + 'Using fixed freezing level height to determine liquid phase') temp_ref = 'fixed_fzl' else: warn('Field to obtain the freezing level was not specified. ' + 'Using fixed freezing level height') temp_ref = 'fixed_fzl' # determine freezing level height if necessary fzl = None if temp_ref == 'fixed_fzl': if 'fzl' in dscfg: fzl = dscfg['fzl'] else: fzl = 2000. warn('Freezing level height not defined. Using default ' + str(fzl)+' m') # get self-consistency parametrization or curves parametrization = dscfg.get('parametrization', 'None') if dscfg['initialized'] == 0: # get frequency band freq = dscfg.get('frequency', None) if freq is None: if (radar.instrument_parameters is not None and 'frequency' in radar.instrument_parameters): freq = radar.instrument_parameters['frequency']['data'][0] else: warn('Unable to estimate Zh bias using ' + 'self-consistency. Unknown radar frequency') return None, None freq_band = pyart.retrieve.get_freq_band(freq) if parametrization == 'None': # find unique elevations el_vec = np.unique( (10.*np.round(radar.elevation['data'], decimals=1)).astype(int)) zdr_kdpzh_list = list() el_list = list() for el in el_vec: fname = ( dscfg['configpath'] + 'selfconsistency/' + 'selfconsistency_zdr_zhkdp_'+freq_band+'band_temp10_elev' + '{:03d}'.format(el)+'_mu05.txt') zdr_kdpzh_table = read_selfconsistency(fname) if zdr_kdpzh_table is not None: zdr_kdpzh_list.append(zdr_kdpzh_table) el_list.append((el/10.).astype(int)) if not el_list: warn('Unable to retrieve Zh bias using self-consistency. ' + 'No selfconsistency files for the radar elevations.') return None, None zdr_kdpzh_dict = {'zdr_kdpzh': zdr_kdpzh_list, 'elev': el_list, 'freq_band': freq_band} else: zdr_kdpzh_dict = {'zdr_kdpzh': None, 'elev': None, 'freq_band': freq_band} dscfg['global_data'] = {'zdr_kdpzh_dict': zdr_kdpzh_dict} if keep_points: dscfg['global_data'].update({'selfconsistency_points': { 'zdr': [], 'kdp': [], 'zh': [], 'timeinfo': dscfg['timeinfo'], 'parametrization': parametrization, 'zdr_kdpzh_dict': zdr_kdpzh_dict }}) dscfg['initialized'] = 1 if dscfg['initialized'] == 1: # get user defined values rsmooth = dscfg.get('rsmooth', 2000.) min_rhohv = dscfg.get('min_rhohv', 0.92) filter_rain = dscfg.get('filter_rain', True) max_phidp = dscfg.get('max_phidp', 20.) ml_thickness = dscfg.get('ml_thickness', 700.) rcell = dscfg.get('rcell', 15000.) dphidp_min = dscfg.get('dphidp_min', 2.) dphidp_max = dscfg.get('dphidp_max', 16.) check_wet_radome = dscfg.get('check_wet_radome', True) wet_radome_refl = dscfg.get('wet_radome_refl', 25.) wet_radome_rng_min = dscfg.get('wet_radome_rng_min', 2000.) wet_radome_rng_max = dscfg.get('wet_radome_rng_max', 4000.) wet_radome_ngates_min = dscfg.get('wet_radome_ngates_min', 180) valid_gates_only = dscfg.get('valid_gates_only', False) rkdp = dscfg.get('rkdp', 6000.) r_res = radar.range['data'][1]-radar.range['data'][0] smooth_wind_len = int(rsmooth/r_res) kdp_wind_len = int(rkdp/r_res) min_rcons = int(rcell/r_res) wet_radome_len_min = int(wet_radome_rng_min/r_res) wet_radome_len_max = int(wet_radome_rng_max/r_res) refl_bias, selfconsistency_dict = pyart.correct.selfconsistency_bias( radar, dscfg['global_data']['zdr_kdpzh_dict'], min_rhohv=min_rhohv, filter_rain=filter_rain, max_phidp=max_phidp, smooth_wind_len=smooth_wind_len, doc=15, fzl=fzl, thickness=ml_thickness, min_rcons=min_rcons, dphidp_min=dphidp_min, dphidp_max=dphidp_max, parametrization=parametrization, refl_field=refl, phidp_field=phidp, zdr_field=zdr, temp_field=temp, iso0_field=iso0, hydro_field=hydro, rhohv_field=rhohv, temp_ref=temp_ref, check_wet_radome=check_wet_radome, wet_radome_refl=wet_radome_refl, wet_radome_len_min=wet_radome_len_min, wet_radome_len_max=wet_radome_len_max, valid_gates_only=valid_gates_only, keep_points=keep_points, kdp_wind_len=kdp_wind_len) if keep_points: if selfconsistency_dict is not None: dscfg['global_data']['selfconsistency_points']['zdr'].extend( selfconsistency_dict['zdr']) dscfg['global_data']['selfconsistency_points']['zh'].extend( selfconsistency_dict['zh']) dscfg['global_data']['selfconsistency_points']['kdp'].extend( selfconsistency_dict['kdp']) # prepare for exit new_dataset = {'radar_out': deepcopy(radar)} new_dataset['radar_out'].fields = dict() new_dataset['radar_out'].add_field('reflectivity_bias', refl_bias) return new_dataset, ind_rad def process_selfconsistency_bias2(procstatus, dscfg, radar_list=None): """ Estimates the reflectivity bias by means of the selfconsistency algorithm by Gourley Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set configuration. Accepted Configuration Keywords:: datatype : list of string. Dataset keyword The input data types parametrization : str The type of parametrization for the self-consistency curves. Can be 'None', 'Gourley', 'Wolfensberger', 'Louf', 'Gorgucci' or 'Vaccarono' 'None' will use tables from config files. Default 'None'. fzl : float. Dataset keyword Default freezing level height. Default 2000. rsmooth : float. Dataset keyword length of the smoothing window [m]. Default 2000. min_rhohv : float. Dataset keyword minimum valid RhoHV. Default 0.92 filter_rain : Bool. Dataset keyword If True the hydrometeor classification is used to filter out gates that are not rain. Default True max_phidp : float. Dataset keyword maximum valid PhiDP [deg]. Default 20. ml_thickness : float. Dataset keyword Melting layer thickness [m]. Default 700. rcell : float. Dataset keyword length of continuous precipitation to consider the precipitation cell a valid phidp segment [m]. Default 15000. frequency : float. Dataset keyword the radar frequency [Hz]. If None that of the key frequency in attribute instrument_parameters of the radar object will be used. If the key or the attribute are not present the selfconsistency will not be computed check_wet_radome : Bool. Dataset keyword if True the average reflectivity of the closest gates to the radar is going to be check to find out whether there is rain over the radome. If there is rain no bias will be computed. Default True. wet_radome_refl : Float. Dataset keyword Average reflectivity [dBZ] of the gates close to the radar to consider the radome as wet. Default 25. wet_radome_rng_min, wet_radome_rng_max : Float. Dataset keyword Min and max range [m] of the disk around the radar used to compute the average reflectivity to determine whether the radome is wet. Default 2000 and 4000. wet_radome_ngates_min : int Minimum number of valid gates to consider that the radome is wet. Default 180 keep_points : Bool If True the ZDR, ZH and KDP of the gates used in the self- consistency algorithm are going to be stored for further analysis. Default False bias_per_gate : Bool If True the bias per gate will be computed radar_list : list of Radar objects Optional. list of radar objects Returns ------- new_dataset : dict dictionary containing the output ind_rad : int radar index """ if procstatus == 0: return None, None keep_points = dscfg.get('keep_points', False) bias_type = dscfg.get('bias_type', 'cumulative') provide_confidence = dscfg.get('provide_confidence', False) nsamples_confidence = dscfg.get('nsamples_confidence', 1000) if procstatus == 2: if dscfg['initialized'] == 0: return None, None dataset = None if bias_type == 'cumulative': kdp_obs = np.ma.array( dscfg['global_data']['kdp_data_dict']['kdp_obs']) kdp_sim = np.ma.array( dscfg['global_data']['kdp_data_dict']['kdp_sim']) reflectivity_bias = { 'value': 10.*np.ma.log10( np.ma.sum(kdp_sim)/np.ma.sum(kdp_obs)), 'npoints': kdp_obs.size, 'timeinfo': dscfg['global_data']['kdp_data_dict']['timeinfo'], 'bias_type': 'cumulative'} if provide_confidence: samples = ratio_bootstrapping( kdp_sim, kdp_obs, nsamples=nsamples_confidence) reflectivity_bias.update( {'samples': 10.*np.ma.log10(samples)}) dataset = {'reflectivity_bias': reflectivity_bias} if keep_points: if dataset is None: dataset = {'selfconsistency_points': dscfg['global_data']['selfconsistency_points']} else: dataset.update( {'selfconsistency_points': dscfg['global_data']['selfconsistency_points']}) return dataset, None temp = None iso0 = None hydro = None phidp = None for datatypedescr in dscfg['datatype']: radarnr, _, datatype, _, _ = get_datatype_fields(datatypedescr) if datatype == 'dBZc': refl = 'corrected_reflectivity' if datatype == 'dBZ': refl = 'reflectivity' if datatype == 'ZDRc': zdr = 'corrected_differential_reflectivity' if datatype == 'ZDR': zdr = 'differential_reflectivity' if datatype == 'PhiDPc': phidp = 'corrected_differential_phase' if datatype == 'PhiDP': phidp = 'differential_phase' if datatype == 'KDPc': kdp = 'corrected_specific_differential_phase' if datatype == 'KDP': kdp = 'specific_differential_phase' if datatype == 'TEMP': temp = 'temperature' if datatype == 'H_ISO0': iso0 = 'height_over_iso0' if datatype == 'hydro': hydro = 'radar_echo_classification' if datatype == 'RhoHV': rhohv = 'cross_correlation_ratio' if datatype == 'RhoHVc': rhohv = 'corrected_cross_correlation_ratio' if datatype == 'uRhoHV': rhohv = 'uncorrected_cross_correlation_ratio' ind_rad = int(radarnr[5:8])-1 if radar_list[ind_rad] is None: warn('No valid radar') return None, None radar = radar_list[ind_rad] if ((refl not in radar.fields) or (zdr not in radar.fields) or (kdp
<reponame>KrzysztofKoch1/edk2<gh_stars>10-100 ## @file # This file is for installed package information database operations # # Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials are licensed and made available # under the terms and conditions of the BSD License which accompanies this # distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ''' Dependency ''' ## # Import Modules # from os.path import dirname import os import Logger.Log as Logger from Logger import StringTable as ST from Library.Parsing import GetWorkspacePackage from Library.Parsing import GetWorkspaceModule from Library.Parsing import GetPkgInfoFromDec from Library.Misc import GetRelativePath from Library import GlobalData from Logger.ToolError import FatalError from Logger.ToolError import EDK1_INF_ERROR from Logger.ToolError import UNKNOWN_ERROR (DEPEX_CHECK_SUCCESS, DEPEX_CHECK_MODULE_NOT_FOUND, \ DEPEX_CHECK_PACKAGE_NOT_FOUND, DEPEX_CHECK_DP_NOT_FOUND) = (0, 1, 2, 3) ## DependencyRules # # This class represents the dependency rule check mechanism # # @param object: Inherited from object class # class DependencyRules(object): def __init__(self, Datab, ToBeInstalledPkgList=None): self.IpiDb = Datab self.WsPkgList = GetWorkspacePackage() self.WsModuleList = GetWorkspaceModule() self.PkgsToBeDepend = [(PkgInfo[1], PkgInfo[2]) for PkgInfo in self.WsPkgList] # Add package info from the DIST to be installed. self.PkgsToBeDepend.extend(self.GenToBeInstalledPkgList(ToBeInstalledPkgList)) def GenToBeInstalledPkgList(self, ToBeInstalledPkgList): if not ToBeInstalledPkgList: return [] RtnList = [] for Dist in ToBeInstalledPkgList: for Package in Dist.PackageSurfaceArea: RtnList.append((Package[0], Package[1])) return RtnList ## Check whether a module exists by checking the Guid+Version+Name+Path combination # # @param Guid: Guid of a module # @param Version: Version of a module # @param Name: Name of a module # @param Path: Path of a module # @return: True if module existed, else False # def CheckModuleExists(self, Guid, Version, Name, Path): Logger.Verbose(ST.MSG_CHECK_MODULE_EXIST) ModuleList = self.IpiDb.GetModInPackage(Guid, Version, Name, Path) ModuleList.extend(self.IpiDb.GetStandaloneModule(Guid, Version, Name, Path)) Logger.Verbose(ST.MSG_CHECK_MODULE_EXIST_FINISH) if len(ModuleList) > 0: return True else: return False ## Check whether a module depex satisfied. # # @param ModuleObj: A module object # @param DpObj: A distribution object # @return: True if module depex satisfied # False else # def CheckModuleDepexSatisfied(self, ModuleObj, DpObj=None): Logger.Verbose(ST.MSG_CHECK_MODULE_DEPEX_START) Result = True Dep = None if ModuleObj.GetPackageDependencyList(): Dep = ModuleObj.GetPackageDependencyList()[0] for Dep in ModuleObj.GetPackageDependencyList(): # # first check whether the dependency satisfied by current workspace # Exist = self.CheckPackageExists(Dep.GetGuid(), Dep.GetVersion()) # # check whether satisfied by current distribution # if not Exist: if DpObj is None: Result = False break for GuidVerPair in DpObj.PackageSurfaceArea.keys(): if Dep.GetGuid() == GuidVerPair[0]: if Dep.GetVersion() is None or \ len(Dep.GetVersion()) == 0: Result = True break if Dep.GetVersion() == GuidVerPair[1]: Result = True break else: Result = False break if not Result: Logger.Error("CheckModuleDepex", UNKNOWN_ERROR, \ ST.ERR_DEPENDENCY_NOT_MATCH % (ModuleObj.GetName(), \ Dep.GetPackageFilePath(), \ Dep.GetGuid(), \ Dep.GetVersion())) return Result ## Check whether a package exists in a package list specified by PkgsToBeDepend. # # @param Guid: Guid of a package # @param Version: Version of a package # @return: True if package exist # False else # def CheckPackageExists(self, Guid, Version): Logger.Verbose(ST.MSG_CHECK_PACKAGE_START) Found = False for (PkgGuid, PkgVer) in self.PkgsToBeDepend: if (PkgGuid == Guid): # # if version is not empty and not equal, then not match # if Version and (PkgVer != Version): Found = False break else: Found = True break else: Found = False Logger.Verbose(ST.MSG_CHECK_PACKAGE_FINISH) return Found ## Check whether a package depex satisfied. # # @param PkgObj: A package object # @param DpObj: A distribution object # @return: True if package depex satisified # False else # def CheckPackageDepexSatisfied(self, PkgObj, DpObj=None): ModuleDict = PkgObj.GetModuleDict() for ModKey in ModuleDict.keys(): ModObj = ModuleDict[ModKey] if self.CheckModuleDepexSatisfied(ModObj, DpObj): continue else: return False return True ## Check whether a DP exists. # # @param Guid: Guid of a Distribution # @param Version: Version of a Distribution # @return: True if Distribution exist # False else def CheckDpExists(self, Guid, Version): Logger.Verbose(ST.MSG_CHECK_DP_START) DpList = self.IpiDb.GetDp(Guid, Version) if len(DpList) > 0: Found = True else: Found = False Logger.Verbose(ST.MSG_CHECK_DP_FINISH) return Found ## Check whether a DP depex satisfied by current workspace for Install # # @param DpObj: A distribution object # @return: True if distribution depex satisfied # False else # def CheckInstallDpDepexSatisfied(self, DpObj): return self.CheckDpDepexSatisfied(DpObj) # # Check whether multiple DP depex satisfied by current workspace for Install # # @param DpObjList: A distribution object list # @return: True if distribution depex satisfied # False else # def CheckTestInstallPdDepexSatisfied(self, DpObjList): for DpObj in DpObjList: if self.CheckDpDepexSatisfied(DpObj): for PkgKey in DpObj.PackageSurfaceArea.keys(): PkgObj = DpObj.PackageSurfaceArea[PkgKey] self.PkgsToBeDepend.append((PkgObj.Guid, PkgObj.Version)) else: return False, DpObj return True, DpObj ## Check whether a DP depex satisfied by current workspace # (excluding the original distribution's packages to be replaced) for Replace # # @param DpObj: A distribution object # @param OrigDpGuid: The original distribution's Guid # @param OrigDpVersion: The original distribution's Version # def ReplaceCheckNewDpDepex(self, DpObj, OrigDpGuid, OrigDpVersion): self.PkgsToBeDepend = [(PkgInfo[1], PkgInfo[2]) for PkgInfo in self.WsPkgList] OrigDpPackageList = self.IpiDb.GetPackageListFromDp(OrigDpGuid, OrigDpVersion) for OrigPkgInfo in OrigDpPackageList: Guid, Version = OrigPkgInfo[0], OrigPkgInfo[1] if (Guid, Version) in self.PkgsToBeDepend: self.PkgsToBeDepend.remove((Guid, Version)) return self.CheckDpDepexSatisfied(DpObj) ## Check whether a DP depex satisfied by current workspace. # # @param DpObj: A distribution object # def CheckDpDepexSatisfied(self, DpObj): for PkgKey in DpObj.PackageSurfaceArea.keys(): PkgObj = DpObj.PackageSurfaceArea[PkgKey] if self.CheckPackageDepexSatisfied(PkgObj, DpObj): continue else: return False for ModKey in DpObj.ModuleSurfaceArea.keys(): ModObj = DpObj.ModuleSurfaceArea[ModKey] if self.CheckModuleDepexSatisfied(ModObj, DpObj): continue else: return False return True ## Check whether a DP could be removed from current workspace. # # @param DpGuid: File's guid # @param DpVersion: File's version # @retval Removable: True if distribution could be removed, False Else # @retval DependModuleList: the list of modules that make distribution can not be removed # def CheckDpDepexForRemove(self, DpGuid, DpVersion): Removable = True DependModuleList = [] WsModuleList = self.WsModuleList # # remove modules that included in current DP # List of item (FilePath) DpModuleList = self.IpiDb.GetDpModuleList(DpGuid, DpVersion) for Module in DpModuleList: if Module in WsModuleList: WsModuleList.remove(Module) else: Logger.Warn("UPT\n", ST.ERR_MODULE_NOT_INSTALLED % Module) # # get packages in current Dp and find the install path # List of item (PkgGuid, PkgVersion, InstallPath) DpPackageList = self.IpiDb.GetPackageListFromDp(DpGuid, DpVersion) DpPackagePathList = [] WorkSP = GlobalData.gWORKSPACE for (PkgName, PkgGuid, PkgVersion, DecFile) in self.WsPkgList: if PkgName: pass DecPath = dirname(DecFile) if DecPath.find(WorkSP) > -1: InstallPath = GetRelativePath(DecPath, WorkSP) DecFileRelaPath = GetRelativePath(DecFile, WorkSP) else: InstallPath = DecPath DecFileRelaPath = DecFile if (PkgGuid, PkgVersion, InstallPath) in DpPackageList: DpPackagePathList.append(DecFileRelaPath) DpPackageList.remove((PkgGuid, PkgVersion, InstallPath)) # # the left items in DpPackageList are the packages that installed but not found anymore # for (PkgGuid, PkgVersion, InstallPath) in DpPackageList: Logger.Warn("UPT", ST.WARN_INSTALLED_PACKAGE_NOT_FOUND%(PkgGuid, PkgVersion, InstallPath)) # # check modules to see if has dependency on package of current DP # for Module in WsModuleList: if (not VerifyRemoveModuleDep(Module, DpPackagePathList)): Removable = False DependModuleList.append(Module) return (Removable, DependModuleList) ## Check whether a DP could be replaced by a distribution containing NewDpPkgList # from current workspace. # # @param OrigDpGuid: original Dp's Guid # @param OrigDpVersion: original Dp's version # @param NewDpPkgList: a list of package information (Guid, Version) in new Dp # @retval Replaceable: True if distribution could be replaced, False Else # @retval DependModuleList: the list of modules that make distribution can not be replaced # def CheckDpDepexForReplace(self, OrigDpGuid, OrigDpVersion, NewDpPkgList): Replaceable = True DependModuleList = [] WsModuleList = self.WsModuleList # # remove modules that included in current DP # List of item (FilePath) DpModuleList = self.IpiDb.GetDpModuleList(OrigDpGuid, OrigDpVersion) for Module in DpModuleList: if Module in WsModuleList: WsModuleList.remove(Module) else: Logger.Warn("UPT\n", ST.ERR_MODULE_NOT_INSTALLED % Module) OtherPkgList = NewDpPkgList # # get packages in current Dp and find the install path # List of item (PkgGuid, PkgVersion, InstallPath) DpPackageList = self.IpiDb.GetPackageListFromDp(OrigDpGuid, OrigDpVersion) DpPackagePathList = [] WorkSP = GlobalData.gWORKSPACE for (PkgName, PkgGuid, PkgVersion, DecFile) in self.WsPkgList: if PkgName: pass DecPath = dirname(DecFile) if DecPath.find(WorkSP) > -1: InstallPath = GetRelativePath(DecPath, WorkSP) DecFileRelaPath = GetRelativePath(DecFile, WorkSP) else: InstallPath = DecPath DecFileRelaPath = DecFile if (PkgGuid, PkgVersion, InstallPath) in DpPackageList: DpPackagePathList.append(DecFileRelaPath) DpPackageList.remove((PkgGuid, PkgVersion, InstallPath)) else: OtherPkgList.append((PkgGuid, PkgVersion)) # # the left items in DpPackageList are the packages that installed but not found anymore # for (PkgGuid, PkgVersion, InstallPath) in DpPackageList: Logger.Warn("UPT", ST.WARN_INSTALLED_PACKAGE_NOT_FOUND%(PkgGuid, PkgVersion, InstallPath)) # # check modules to see if it can be
<filename>ec2_gui.pyw import sys try: import wx except ImportError: print 'Looks like you do not have wx installed.' print 'You can install it here (you want the unicode version):' print 'http://www.wxpython.org/download.php' print 'Your python version: ' + str(sys.version_info[0:2]) sys.exit(1) import wxPython.wx import wx.grid as gridlib import wx.lib.scrolledpanel as scrolled import os import ConfigParser import logging import copy import ast import datetime import time import subprocess import random try: import boto except ImportError: print 'Looks like you do not have boto installed.' print 'You can install it like this:' print '-' * 20 print 'git clone https://github.com/boto/boto.git' print 'cd boto' print 'sudo python setup.py install' print '-' * 20 sys.exit(1) import boto.ec2 from boto.ec2.connection import EC2Connection from boto.ec2.autoscale import AutoScaleConnection from boto.ec2.autoscale import LaunchConfiguration from boto.ec2.autoscale import Tag from boto.ec2.autoscale import AutoScalingGroup from boto.ec2.autoscale import ScalingPolicy from boto.ec2.cloudwatch import CloudWatchConnection from boto.ec2.cloudwatch import MetricAlarm class ASG_Functionality(): def __init__(self, logLevel=logging.CRITICAL, logger=None): """ This class contains the functionality needed to communicate with Amazon's Auto Scaling Group. :param logLevel: Verbosity level of this command (DEBUG|INFO|WARNING|CRITICAL). :type logLevel: logging.logLevel :param logger: Optionally specificy a logger. Useful for multithreading. :type logger: logging logger """ if logger is None: #- Create the logger: self.log = logging.getLogger(__name__) self.log.handlers = [] ch = logging.StreamHandler() ch.setFormatter(logging.Formatter('%(message)s')) self.log.addHandler(ch) self.log.setLevel(logLevel) self.identityFile = None else: self.log = logger #- OK, now connect to the region: self.connectToRegion() def connectToRegion(self): #- Connect to us-east-1 region: if 'AWS_ACCESS_KEY' in os.environ and 'AWS_SECRET_KEY' in os.environ: self.conn = AutoScaleConnection(os.environ['AWS_ACCESS_KEY'], os.environ['AWS_SECRET_KEY']) self.cwconn = CloudWatchConnection(os.environ['AWS_ACCESS_KEY'], os.environ['AWS_SECRET_KEY']) else: #- Maybe you can connect with the credentials in ~/.boto self.conn = AutoScaleConnection() self.cwconn = CloudWatchConnection() def printAllASGs(self, logger=None): if logger is None: logger = self.log all_asgs = self.safeFunc(self.conn.get_all_groups) if len(all_asgs) == 0: return 'No ASGs could be located!' else: retText = 'Total Number of ASGs: ' + str(len(all_asgs)) + '\n' for asg in all_asgs: retText = retText + '\n' + self.prettyPrintAsg(asg) return retText def prettyPrintAsg(self, asgObj, logger=None): """ This function prints out vital information of an ASG object. :param asgObj: boto ASG object. :type asgObj: string :param logger: Optionally specificy a logger. Useful for multithreading. :type logger: logging logger """ if logger is None: logger = self.log retText = '' #- General Information on ASG: data = sorted([[i[0], str(i[1]).strip()] for i in vars(asgObj).items()]) for el in self.safeFunc(self.conn.get_all_activities, asgObj): data.append(['Activity:', str(el.description)]) #- Print Launch Configuration Info: data.append(['launch configurations:', '']) for el in self.safeFunc(self.conn.get_all_launch_configurations, names=[str(asgObj.launch_config_name)]): data.append(['\t----------Launch Description', '']) data = data + sorted([['\t' + i[0], str(i[1]).strip()] for i in vars(el).items()]) #- Print Scaling Policies Info: scalingPolicies = self.safeFunc(self.conn.get_all_policies, as_group=asgObj.name) data.append(['scaling policies:', '']) for policy in scalingPolicies: data.append(['\t---------Scaling Policy Description', '']) data = data + sorted([['\t' + i[0], str(i[1]).strip()] for i in vars(policy).items()]) #- Print Alarms: data.append(['\talarms:', str(policy.alarms)]) for alarm in policy.alarms: data.append(['\t\t----------Alarm Description', '']) data = data + sorted([['\t\t' + i[0], str(i[1]).strip()] for i in vars(alarm).items()]) for cw_alarm in self.safeFunc(self.cwconn.describe_alarms, alarm_names=[alarm.name]): data = data + sorted([['\t\t' + i[0], str(i[1]).strip()] for i in vars(cw_alarm).items()]) retText = retText + '\n--------------------------------\n' retText = retText + '-------------- ASG -------------\n' retText = retText + '--------------------------------\n' retText = retText + self.prettyPrintColumns(data) return retText def prettyPrintColumns(self, data, padding=None): """ This funciton returns a user friendly column output string. :param data: A list of strings. :type data: list of strings :param padding: The number of spaces between columns Default is 2. :type padding: int :return: text Example (output of _sectionPrint):: data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']] print prettyPrintColumns(data) a b c aaaaaaaaaa b c a bbbbbbbbbb c """ if len(data) == 0: return "" padding = 2 if padding is None else padding #- Invert roles to columns: dataPrime = zip(*data) #- Calculate the max column width for each column: column_widths = [] for i in range(0, len(data[0])): column_widths.append(len(max(dataPrime[i], key=len)) + padding) #- Modify the data directly with padding: for i in range(0, len(data)): for ii in range(0, len(column_widths) - 1): data[i][ii] = data[i][ii].ljust(column_widths[ii]) retStr = '' for row in data: retStr = retStr + "".join(word for word in row) + '\n' return retStr def safeFunc(self, func, *args, **kwargs): logger = self.log if 'logger' in kwargs: logger = kwargs['logger'] del kwargs['logger'] attempts = 60 retVal = None done_waiting_string = 'Done Waiting. Raising Exception.' while True: sleeptime = random.random() * 3 try: retVal = func(*args, **kwargs) except Exception as ex: if not hasattr(ex, 'error_code'): raise if ex.error_code == "AlreadyExists": attempts = attempts - 1 logger.critical(ex.error_message + " " + str(sleeptime * 30) + " seconds), try again " + str(attempts) + " times...") if attempts == 0: logger.critical(done_waiting_string) raise ex time.sleep(sleeptime * 30) elif ex.error_code == "Throttling": attempts = attempts - 1 logger.critical(ex.error_message + " " + str(sleeptime * 30) + " seconds), try again " + str(attempts) + " times...") if attempts == 0: logger.critical(done_waiting_string) raise ex time.sleep(sleeptime) elif ex.error_code == "ValidationError": attempts = attempts - 1 logger.critical(ex.error_message + " " + str(sleeptime * 30) + " seconds), try again " + str(attempts) + " times...") if attempts == 0: logger.critical(done_waiting_string) raise ex time.sleep(sleeptime * 30) else: for i, j in vars(ex).items(): logger.critical(i + " === " + str(j)) raise else: break return retVal class EC2_Functionality(): def __init__(self, logLevel=logging.CRITICAL, logger=None): """ Helper class to talk to EC2. :param logLevel: Verbosity level of this command (DEBUG|INFO|WARNING|CRITICAL). :type logLevel: logging.logLevel :param logger: Optionally specificy a logger. Useful for multithreading. :type logger: logging logger """ if logger is None: #- Create the logger: self.log = logging.getLogger(__name__) self.log.handlers = [] ch = logging.StreamHandler() ch.setFormatter(logging.Formatter('%(message)s')) self.log.addHandler(ch) self.log.setLevel(logLevel) self.identityFile = None else: self.log = logger #- OK, now connect to the region: self.connectToRegion() def connectToRegion(self): #- Connect to us-east-1 region: if 'AWS_ACCESS_KEY' in os.environ and 'AWS_SECRET_KEY' in os.environ: self.conn = EC2Connection(os.environ['AWS_ACCESS_KEY'], os.environ['AWS_SECRET_KEY']) else: #- Maybe you can connect with the credentials in ~/.boto or with IAM Role: self.conn = EC2Connection() self.log.critical('Connected to Region: ' + self.conn.region.name) def createTags(self, resource_ids=[], dict_of_tags={}, logger=None): """ This function creates tags on resource ID. :param resource_ids: A list of AWS resource IDs. :type resource_ids: list of strings :param dict_of_tags: A dict of tags. :type dict_of_tags: dict :param logger: Optionally specificy a logger. Useful for multithreading. :type logger: logging logger """ if logger is None: logger = self.log logger.critical('Creating Tags: ' + str(dict_of_tags) + 'on resource IDs: ' + str(resource_ids)) image = self.conn.create_tags(resource_ids, dict_of_tags) def getInstanceById(self, instanceId, logger=None): """ This function returns an instance object based on an instance AWS ID. :param imageId: The AWS Instance ID. :type imageId: string :param logger: Optionally specificy a logger. Useful for multithreading. :type logger: logging logger :return: boto instance object """ if logger is None: logger = self.log logger.critical('Finding instance ' + instanceId + '... ') reservations = self.conn.get_all_instances(instance_ids=[instanceId]) for reservation in reservations: for instance in reservation.instances: if instance.id == instanceId: logger.critical('Returning instance ' + instanceId + '... ') return instance return None def getAllInstances(self): """ This function returns a list of all instance objects. :return: list of boto instance objects """ return [i for r in self.conn.get_all_instances() for i in r.instances] def terminateInstanceById(self, instanceId, logger=None): """ This function terminates an instance by it's AWS ID. :param instanceId: AWS Instance ID that you wish to terminate. :type instanceId: string :param logger: Optionally specificy a logger. Useful for multithreading. :type logger: logging logger """ if logger is None: logger = self.log logger.critical('\nTerminating Instance: ' + instanceId) instance = self.getInstanceById(instanceId) if instance is None: logger.critical('***Error: Instance not found: ' + instanceId) else: while instance.state != 'terminated': instance.terminate() instance.update() if instance.state == 'shutting-down': break logger.critical('Waiting for terminated state. Currently: ' + instance.state) time.sleep(10) logger.critical('Instance ' + instanceId + ' is terminated or is terminating!') class AsgInfoDialog(scrolled.ScrolledPanel): def __init__(self, parent): scrolled.ScrolledPanel.__init__(self, parent, -1) vbox = wx.BoxSizer(wx.VERTICAL) asgObj = ASG_Functionality(logger=None) self.tText = asgObj.printAllASGs() font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) desc = wx.StaticText(self, -1, self.tText) desc.SetForegroundColour("Blue") desc.SetFont(font) #- Create the toolbar and all its widgets: toolbar = parent.CreateToolBar() x = toolbar.AddLabelTool(wx.ID_ANY, 'ASG', wx.Bitmap(os.path.join(os.path.dirname(__file__), os.path.join('data', 'copy.png')))) toolbar.Realize() parent.Bind(wx.EVT_TOOL, self.onCopyF, x) vbox.Add(desc, 0, wx.ALIGN_LEFT|wx.ALL, 5) self.SetSizer(vbox) self.SetAutoLayout(1) self.SetupScrolling() def onCopyF(self, event): print 'putting text
read_only: ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk """ pulumi.set(__self__, "pd_name", pd_name) if fs_type is not None: pulumi.set(__self__, "fs_type", fs_type) if partition is not None: pulumi.set(__self__, "partition", partition) if read_only is not None: pulumi.set(__self__, "read_only", read_only) @property @pulumi.getter(name="pdName") def pd_name(self) -> str: """ Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk """ return pulumi.get(self, "pd_name") @property @pulumi.getter(name="fsType") def fs_type(self) -> Optional[str]: """ Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk TODO: how do we prevent errors in the filesystem from compromising the machine """ return pulumi.get(self, "fs_type") @property @pulumi.getter def partition(self) -> Optional[int]: """ The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk """ return pulumi.get(self, "partition") @property @pulumi.getter(name="readOnly") def read_only(self) -> Optional[bool]: """ ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk """ return pulumi.get(self, "read_only") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DatadogAgentSpecAgentConfigVolumesGitRepo(dict): """ GitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container. """ def __init__(__self__, *, repository: str, directory: Optional[str] = None, revision: Optional[str] = None): """ GitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container. :param str repository: Repository URL :param str directory: Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. :param str revision: Commit hash for the specified revision. """ pulumi.set(__self__, "repository", repository) if directory is not None: pulumi.set(__self__, "directory", directory) if revision is not None: pulumi.set(__self__, "revision", revision) @property @pulumi.getter def repository(self) -> str: """ Repository URL """ return pulumi.get(self, "repository") @property @pulumi.getter def directory(self) -> Optional[str]: """ Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. """ return pulumi.get(self, "directory") @property @pulumi.getter def revision(self) -> Optional[str]: """ Commit hash for the specified revision. """ return pulumi.get(self, "revision") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DatadogAgentSpecAgentConfigVolumesGlusterfs(dict): """ Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md """ def __init__(__self__, *, endpoints: str, path: str, read_only: Optional[bool] = None): """ Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md :param str endpoints: EndpointsName is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod :param str path: Path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod :param bool read_only: ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod """ pulumi.set(__self__, "endpoints", endpoints) pulumi.set(__self__, "path", path) if read_only is not None: pulumi.set(__self__, "read_only", read_only) @property @pulumi.getter def endpoints(self) -> str: """ EndpointsName is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod """ return pulumi.get(self, "endpoints") @property @pulumi.getter def path(self) -> str: """ Path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod """ return pulumi.get(self, "path") @property @pulumi.getter(name="readOnly") def read_only(self) -> Optional[bool]: """ ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod """ return pulumi.get(self, "read_only") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DatadogAgentSpecAgentConfigVolumesHostPath(dict): """ HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath --- TODO(jonesdl) We need to restrict who can use host directory mounts and who can/can not mount host directories as read/write. """ def __init__(__self__, *, path: str, type: Optional[str] = None): """ HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath --- TODO(jonesdl) We need to restrict who can use host directory mounts and who can/can not mount host directories as read/write. :param str path: Path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath :param str type: Type for HostPath Volume Defaults to "" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath """ pulumi.set(__self__, "path", path) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def path(self) -> str: """ Path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath """ return pulumi.get(self, "path") @property @pulumi.getter def type(self) -> Optional[str]: """ Type for HostPath Volume Defaults to "" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath """ return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DatadogAgentSpecAgentConfigVolumesIscsi(dict): """ ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md """ def __init__(__self__, *, iqn: str, lun: int, target_portal: str, chap_auth_discovery: Optional[bool] = None, chap_auth_session: Optional[bool] = None, fs_type: Optional[str] = None, initiator_name: Optional[str] = None, iscsi_interface: Optional[str] = None, portals: Optional[Sequence[str]] = None, read_only: Optional[bool] = None, secret_ref: Optional['outputs.DatadogAgentSpecAgentConfigVolumesIscsiSecretRef'] = None): """ ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md :param str iqn: Target iSCSI Qualified Name. :param int lun: iSCSI Target Lun number. :param str target_portal: iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260). :param bool chap_auth_discovery: whether support iSCSI Discovery CHAP authentication :param bool chap_auth_session: whether support iSCSI Session CHAP authentication :param str fs_type: Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi TODO: how do we prevent errors in the filesystem from compromising the machine :param str initiator_name: Custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface <target portal>:<volume name> will be created for the connection. :param str iscsi_interface: iSCSI Interface Name that uses an iSCSI transport. Defaults to 'default' (tcp). :param Sequence[str] portals: iSCSI Target Portal List. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260). :param bool read_only: ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. :param 'DatadogAgentSpecAgentConfigVolumesIscsiSecretRefArgs' secret_ref: CHAP Secret for iSCSI target and initiator authentication """ pulumi.set(__self__, "iqn", iqn) pulumi.set(__self__, "lun", lun) pulumi.set(__self__, "target_portal", target_portal) if chap_auth_discovery is not None: pulumi.set(__self__, "chap_auth_discovery", chap_auth_discovery) if chap_auth_session is not None: pulumi.set(__self__, "chap_auth_session", chap_auth_session) if fs_type is not None: pulumi.set(__self__, "fs_type", fs_type) if initiator_name is not None:
import tensorflow as tf import tensorflow_probability as tfp # from tensorflow_probability import edward2 as ed2 tfd = tfp.distributions tfb = tfp.bijectors tfp_kernels = tfp.positive_semidefinite_kernels import sys sys.path.insert(0, './self_py_fun') from self_py_fun.PreFun import * # import scipy as sp import seaborn as sns # from scipy.spatial.distance import pdist, squareform plt.style.use('ggplot') sns.set_context('notebook') # https://wookayin.github.io/tensorflow-talk-debugging/#29 # https://colab.research.google.com/github/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/TensorFlow_Probability_Case_Study_Covariance_Estimation.ipynb#scrollTo=znG_AtTR7qob # Multivariate normal parametrized by loc and Cholesky precision matrix. class MVNPrecisionCholesky(tfd.TransformedDistribution): def __init__(self, loc, precision_cholesky, re_batch_ndims, name=None): super(MVNPrecisionCholesky, self).__init__( distribution=tfd.Independent( tfd.Normal(loc=tf.zeros_like(loc, dtype='float32'), scale=tf.ones_like(loc, dtype='float32')), reinterpreted_batch_ndims=re_batch_ndims), bijector=tfb.Chain([ tfb.Affine(shift=loc), tfb.Invert(tfb.Affine(scale_tril=precision_cholesky, adjoint=True)), ]), name=name) class PriorModel: num_rep = 12 DAT_TYPE = 'float32' eps_value = tf.keras.backend.epsilon() def __init__(self, n_length, num_electrode): self.n_length = n_length self.num_electrode = num_electrode @staticmethod def generate_delta(mean_vec, hyper_delta_var, convert_to_numpy=False): delta_rv = tfd.MultivariateNormalDiag( loc=mean_vec, scale_identity_multiplier=hyper_delta_var) delta_sample = tf.squeeze(delta_rv.sample(1), axis=0) if convert_to_numpy: delta_sample = tf.keras.backend.eval(delta_sample) return delta_sample @staticmethod def compute_delta_log_lhd(mean_vec, hyper_delta_var, target_delta_value): delta_rv = tfd.MultivariateNormalDiag( loc=mean_vec, scale_identity_multiplier=hyper_delta_var ) return tf.reduce_sum(delta_rv.log_prob(target_delta_value)) def generate_pres_chky_matrix(self, df, channel_dim=1, convert_to_numpy=False): pres_chky_rv = tfd.Wishart( df=df, scale=tf.eye(self.n_length, self.n_length, [channel_dim]), input_output_cholesky=True, validate_args=True ) pres_chky_sample = tf.squeeze(pres_chky_rv.sample(1), axis=0) if convert_to_numpy: pres_chky_sample = tf.keras.backend.eval(pres_chky_sample) return pres_chky_sample def compute_pres_chky_log_lhd(self, df, pres_chky_matrix_value, channel_dim=1): pres_chky_rv = tfd.Wishart( df=df, scale=tf.eye(self.n_length, self.n_length, [channel_dim]), input_output_cholesky=True) return tf.reduce_sum(pres_chky_rv.log_prob(pres_chky_matrix_value)) # https://www.math.wustl.edu/~sawyer/hmhandouts/Wishart.pdf # Potential reference: # https://amstat.tandfonline.com/doi/abs/10.1080/01621459.1966.10502018#.Xc12Cy2ZNgc def generate_pres_chky_2(self, sigma_r_sq, channel_dim=1, convert_to_numpy=False): uni_normal_rv = tfd.MultivariateNormalDiag( loc=tf.zeros([channel_dim, self.n_length*(self.n_length+1)/2]), scale_identity_multiplier=sigma_r_sq ) # Need to modify the main-diagonal term with another chi-square random variable w/ # df n-i+1. # Convert multi-1d array to an upper-triangular matrix (with channel_dim batch) df_vec = tf.range(self.n_length, dtype=self.DAT_TYPE)+1 df_vec = df_vec[::-1] df_vec = tf.tile(df_vec[tf.newaxis, :], [channel_dim, 1]) diag_chisq_rv = tfd.Chi2(df=df_vec) uni_normal_sample = tf.squeeze(uni_normal_rv.sample(1), axis=0) chisq_sample = tf.squeeze(diag_chisq_rv.sample(1), axis=0) if convert_to_numpy: uni_normal_sample = tf.keras.backend.eval(uni_normal_sample) chisq_sample = tf.keras.backend.eval(chisq_sample) return uni_normal_sample, chisq_sample @staticmethod def convert_1d_array_to_upper_triangular(uni_normal_sample, chisq_sample, convert_to_numpy=False): uni_normal_sample = tfd.fill_triangular(uni_normal_sample, upper=True) uni_normal_sample = tf.linalg.set_diag(uni_normal_sample, tf.sqrt(chisq_sample)) if convert_to_numpy: uni_normal_sample = tf.keras.backend.eval(uni_normal_sample) return uni_normal_sample @staticmethod def compute_pres_upper_tri(cov_matrix, convert_to_numpy=False): pres_matrix = tf.linalg.inv(cov_matrix) upper_tri_sample = tf.transpose(tf.linalg.cholesky(pres_matrix), [0, 2, 1]) if convert_to_numpy: upper_tri_sample = tf.keras.backend.eval(upper_tri_sample) return upper_tri_sample @staticmethod def convert_upper_triangular_to_1d_array(upper_tri_sample, convert_to_numpy=False): upper_tri_sample = tfd.fill_triangular_inverse(upper_tri_sample, upper=True) if convert_to_numpy: upper_tri_sample = tf.keras.backend.eval(upper_tri_sample) return upper_tri_sample def compute_pres_chky_log_lhd_2(self, sigma_r_sq, uni_normal_sample, chisq_sample, channel_dim=1): # Notice that uni_normal_sample is long_array uni_normal_rv = tfd.MultivariateNormalDiag( loc=tf.zeros([channel_dim, self.n_length*(self.n_length+1)/2]), scale_identity_multiplier=sigma_r_sq ) normal_log_lhd = tf.reduce_sum(uni_normal_rv.log_prob(uni_normal_sample)) df_vec = tf.range(self.n_length, dtype=self.DAT_TYPE) + 1 df_vec = df_vec[::-1] df_vec = tf.tile(df_vec[tf.newaxis, :], [channel_dim, 1]) diag_chisq_rv = tfd.Chi2(df=df_vec) chisq_log_lhd = tf.reduce_sum(diag_chisq_rv.log_prob(chisq_sample)) return normal_log_lhd + chisq_log_lhd def generate_eta_and_compute_log_lhd( self, pres_chky, letter_dim, rep_dim, flash_num, convert_to_numpy=False, channel_dim=1): std_normal_rv = tfd.MultivariateNormalDiag( loc=tf.zeros([channel_dim, self.n_length]), scale_identity_multiplier=tf.ones([])) dim_temp = letter_dim * rep_dim * flash_num eta = std_normal_rv.sample([dim_temp]) log_lhd_xi = tf.reduce_sum(std_normal_rv.log_prob(eta)) log_abs_diag_value = tf.reduce_sum(tf.linalg.logdet(pres_chky)) # log_abs_diag_value = tf.reduce_sum(tf.math.log(self.eps_value + tf.abs(tf.linalg.diag_part(pres_chky)))) log_lhd_pres_chky = dim_temp * log_abs_diag_value # Solve eta from pres_chky_1 * eta = normal_vector eta = tf.transpose(eta, [1, 0, 2])[..., tf.newaxis] # eta should have shape (channel_dim, ..., n_length, 1) # pres_chky should have shape (channel_dim, n_length, n_length) # print('eta has shape {}'.format(eta.shape)) # print('pres_chky has shape {}'.format(pres_chky.shape)) def _solve_eta_per_channel(elems): pres_chky_chan = elems[0] eta_chan = elems[1] pres_chky_chan = tf.tile(pres_chky_chan[tf.newaxis, ...], [dim_temp, 1, 1]) eta_chan = tf.linalg.triangular_solve(pres_chky_chan, eta_chan, lower=False) return eta_chan elems = (pres_chky, eta) eta_solve = tf.map_fn(_solve_eta_per_channel, elems, dtype=self.DAT_TYPE) eta_solve = tf.transpose(tf.squeeze(eta_solve, axis=-1), [1, 0, 2]) if convert_to_numpy: eta_solve = tf.keras.backend.eval(eta_solve) return eta_solve, log_lhd_xi+log_lhd_pres_chky @staticmethod def generate_pres_e(alpha, beta, convert_to_numpy=False, channel_dim=1): pres_e_rv = tfd.Gamma( concentration=alpha*tf.ones([channel_dim]), rate=beta*tf.ones([channel_dim]) ) pres_e = tf.squeeze(pres_e_rv.sample(1), axis=0) if convert_to_numpy: pres_e = tf.keras.backend.eval(pres_e) return pres_e @staticmethod def compute_pres_e_log_lhd(alpha, beta, pres_e, channel_dim=1): pres_e_rv = tfd.Gamma( concentration=alpha*tf.ones([channel_dim]), rate=beta*tf.ones([channel_dim]) ) return tf.reduce_sum(pres_e_rv.log_prob(pres_e)) class ReArrangeBetaSigma: # Global constants: num_rep = 12 f_sum = 2 nf_sum = num_rep - f_sum DAT_TYPE = 'float32' def __init__(self, n_multiple, num_electrode, flash_and_pause_length): self.n_multiple = n_multiple self.num_electrode = num_electrode self.flash_and_pause_length = flash_and_pause_length self.n_length = int(n_multiple * flash_and_pause_length) def tile_and_combine_delta(self, letter_dim, repet_dim, delta_1, delta_0, channel_dim=1): assert delta_1.shape == (channel_dim, self.n_length), \ print('delta_1 has wrong input shape!') assert delta_0.shape == (channel_dim, self.n_length), \ print('delta_0 has wrong input shape!') delta_1 = tf.convert_to_tensor(delta_1)[tf.newaxis, ...] delta_0 = tf.convert_to_tensor(delta_0)[tf.newaxis, ...] dim_1 = letter_dim * repet_dim * self.f_sum dim_0 = letter_dim * repet_dim * self.nf_sum delta_1 = tf.tile(delta_1, multiples=[dim_1, 1, 1]) delta_1 = tf.reshape(tf.transpose(delta_1, perm=[1, 0, 2]), shape=[channel_dim, dim_1, self.n_length]) delta_0 = tf.tile(delta_0, multiples=[dim_0, 1, 1]) delta_0 = tf.reshape(tf.transpose(delta_0, perm=[1, 0, 2]), shape=[channel_dim, dim_0, self.n_length]) delta_combined = tf.concat([delta_1, delta_0], axis=1) return delta_combined # Need to absorb this numpy function within tensorflow graph (especially for prediction) def create_permute_beta_id(self, letter_dim, repet_dim, eeg_type): dim_temp = letter_dim * repet_dim * self.num_rep assert eeg_type.shape == (dim_temp,), print('eeg_type has wrong input shape!') id_beta = np.zeros([dim_temp]) - 1 id_beta[eeg_type == 1] = np.arange(self.f_sum*letter_dim*repet_dim) id_beta[eeg_type != 1] = np.arange(self.f_sum*letter_dim*repet_dim, dim_temp) return id_beta.astype('int32') # This function requires further editing in terms of the dimension rearrangement. def permute_beta_by_type(self, letter_dim, repet_dim, beta_combined, id_beta, channel_dim=1): dim_temp = letter_dim * repet_dim * self.num_rep assert beta_combined.shape == (dim_temp, channel_dim, self.n_length), \ print('beta_combined has wrong input shape!') # 2280, 16, 25 # beta_combined = tf.reshape(beta_combined, [channel_dim, # dim_temp, # self.n_length]) beta_combined = tf.gather(beta_combined, id_beta, axis=0, name='beta_permuted') beta_combined = tf.reshape(beta_combined, [letter_dim, repet_dim*self.num_rep, channel_dim, self.n_length]) beta_combined = tf.transpose(beta_combined, [0, 2, 1, 3]) # print('beta_combined has shape {}'.format(beta_combined.shape)) beta_combined = tf.reshape(beta_combined, [letter_dim, channel_dim, repet_dim*self.num_rep*self.n_length, 1]) return beta_combined # The following functions are based on Bayesian generative model # which may apply tensorflow and tensorflow-probability. # Notice that the design matrix can be automatically broadcast # w.r.t channel batch and letter batch. def create_design_mat_gen_bayes_seq(self, repetition_dim): r""" :param repetition_dim: integer :return: design_x, with output shape [(num_rep*num_repetition+n_multiple-1)*flash_and_pause_length, num_rep*num_repetition*n_length] """ # Create a zero matrix dm_row = (repetition_dim*self.num_rep + self.n_multiple - 1) * self.flash_and_pause_length dm_col = repetition_dim*self.num_rep*self.n_length dm = np.zeros([dm_row, dm_col]) id_block = np.eye(self.n_length) for trial_id in range(repetition_dim*self.num_rep): row_id_low = trial_id * self.flash_and_pause_length row_id_upp = row_id_low + self.n_length col_id_low = trial_id * self.n_length col_id_upp = col_id_low + self.n_length dm[row_id_low:row_id_upp, col_id_low:col_id_upp] = id_block return dm def create_joint_beta_tilta( self, letter_dim, repet_dim, beta_combined, id_beta, design_x, channel_dim=1 ): r""" :param letter_dim: integer :param repet_dim: integer :param beta_combined: array_like, (channe_dim, letter_dim, noise_size*n_length, 1) :param id_beta: array_like, or None :param design_x: array_like, (channel_dim, letter_dim, seq_length, noise_size*n_length) :param channel_dim: array_like :return: For design_x, we can ignore the outer-2 batch as long as the rightmost 2 dimensions are correct. For id_beta, if none, it implies that the beta_combined has already been permuted. """ if id_beta is not None: beta_combined = self.permute_beta_by_type( letter_dim, repet_dim, beta_combined, id_beta, channel_dim) seq_x = design_x @ beta_combined return seq_x @staticmethod def convert_from_pres_to_cov(pres_chky_mat, convert_to_numpy=False): pres_chky_mat_inv = tf.linalg.inv(pres_chky_mat) cov_mat = tf.matmul(pres_chky_mat_inv, tf.transpose(pres_chky_mat_inv, [0, 2, 1])) if convert_to_numpy: cov_mat = tf.keras.backend.eval(cov_mat) return cov_mat @staticmethod def convert_from_cov_to_pres(cov_mat, convert_to_numpy=False): prec_chky_mat = tf.linalg.cholesky(tf.linalg.inv(cov_mat)) if convert_to_numpy: prec_chky_mat = tf.keras.backend.eval(prec_chky_mat) return prec_chky_mat def create_trial_specific_cov_fn(self, trial_i, unit_pres_mat_value, rep_dim, channel_dim=1): assert unit_pres_mat_value.shape == (channel_dim, self.n_length, self.n_length) unit_cov_fn_value = self.convert_from_pres_to_cov(unit_pres_mat_value) large_cov_size = (self.num_rep * rep_dim + self.n_multiple - 1) * self.flash_and_pause_length upp_left = trial_i*self.flash_and_pause_length low_right = large_cov_size - trial_i*self.flash_and_pause_length - self.n_length paddings = tf.constant([[0, 0], [upp_left, low_right], [upp_left, low_right]]) large_cov_value = tf.pad(unit_cov_fn_value, paddings, "constant") return large_cov_value def create_collapsed_cov_fn(self, letter_dim, rep_dim, unit_target_pres_value, unit_nt_pres_value, eeg_type, channel_dim=1): trial_sum = self.num_rep * rep_dim trn_total_seq = (trial_sum+self.n_multiple-1) * self.flash_and_pause_length eeg_type = np.reshape(eeg_type, [letter_dim, trial_sum]) collapsed_cov_fn = tf.zeros([channel_dim, trn_total_seq, trn_total_seq]) for letter_id in range(letter_dim): collapsed_cov_fn_letter = tf.zeros([channel_dim, trn_total_seq, trn_total_seq]) for trial_i in range(trial_sum): if eeg_type[letter_id, trial_i] == 1: collapsed_cov_fn_letter += self.create_trial_specific_cov_fn( trial_i, unit_target_pres_value, rep_dim) else: collapsed_cov_fn_letter += self.create_trial_specific_cov_fn( trial_i, unit_nt_pres_value, rep_dim) collapsed_cov_fn = tf.concat([collapsed_cov_fn, collapsed_cov_fn_letter], axis=0) collapsed_cov_fn = tf.reshape(collapsed_cov_fn[channel_dim:, ...], [letter_dim, self.num_electrode, trn_total_seq, trn_total_seq]) # should have shape (19, 16, 920, 920) return collapsed_cov_fn class MVNJointModel: def __init__(self, n_length, num_electrode, re_batch_ndims=2): self.n_length = n_length self.num_electrode = num_electrode self.re_batch_ndims = re_batch_ndims def generate_pseudo_signals(self, y_tilta, prec_chky_tilta=None, cov_tilta=None, sample_batch=1, convert_to_numpy=False, channel_dim=1): assert prec_chky_tilta is not None or cov_tilta is not None, \ print('Missing covariance component.') if prec_chky_tilta is None: prec_chky_tilta = tf.linalg.cholesky(tf.linalg.inv(cov_tilta)) jitter = 0.1 * tf.eye(self.n_length, self.n_length, [channel_dim]) mvn_rv = MVNPrecisionCholesky( loc=y_tilta, precision_cholesky=prec_chky_tilta+jitter, re_batch_ndims=self.re_batch_ndims) pseudo_signal = mvn_rv.sample(sample_batch) if sample_batch == 1: pseudo_signal = tf.squeeze(pseudo_signal, axis=0) if convert_to_numpy: pseudo_signal = tf.keras.backend.eval(pseudo_signal) return pseudo_signal def compute_log_lhd(self, y_tilta, y_value, prec_chky_tilta=None, cov_tilta=None, sum_over_letter=True): assert prec_chky_tilta is not None or cov_tilta is not None, \ print('Missing covariance component.') if prec_chky_tilta is None: prec_chky_tilta = tf.linalg.cholesky(tf.linalg.inv(cov_tilta)) mvn_rv = MVNPrecisionCholesky( loc=y_tilta, precision_cholesky=prec_chky_tilta, re_batch_ndims=self.re_batch_ndims) mvn_log_prob = mvn_rv.log_prob(y_value) if sum_over_letter: mvn_log_prob = tf.reduce_sum(mvn_log_prob, axis=0) return mvn_log_prob class WLSOpt(EEGPreFun): # class-level global constant def __init__(self, *args, **kwargs): super(WLSOpt, self).__init__(*args, **kwargs) # Create the bijector for chky matrices self.unconstrained_to_precison_chky = tfb.Chain([
<gh_stars>1-10 # File Name:api.py # # This file is for connection to zenpy module. # # Copyright: 2016@nephoscale # # Start date: July 14th, 2016 # # Dependancies: # zenpy: # Github: https://github.com/facetoe/zenpy # Python: pip install zenpy # ndg-httpsclient: # pip install ndg-httpsclient from keystoneauth1 import identity from keystoneauth1 import session from zenpy.lib.api_objects import Ticket, User, Comment, Attachment from zenpy.lib.exception import APIException, RecordNotFoundException from django.conf import settings import keystoneclient import logging as LOG try: import json except: import simlejson as json import zenpy import random, string import pytz, tzlocal, datetime import urllib import os class Zendesk: """ Class which will be used to integrate with horizon """ _request = _ks_user = _zenpy = _ks_tenant = _zendesk_admin = None def __init__(self, request): """ # | Init function to configure the object # | # | @Arguments: # | <ks_usher_id>: Keystone user id """ #Checking the auth version and calling the create token method accordingly keystone_auth_version = getattr(settings, 'KEYSTONE_AUTH_VERSION', 'v3') try: if keystone_auth_version == 'v3': self.keystone = self._manageV3(request) else: self.keystone = self._manageV2(request) self._request = request except Exception as e: LOG.error(str(e)) if hasattr(e, 'http_status'): if e.http_status == 401: raise ZendeskError(401, "Unable to login to horizon as admin.") if e.http_status == 404: raise ZendeskError(404, "No user found in keystone with id " + keystone_user_id) # If some other error occured, then throw exception as unknown error # Because these errors are not relavant to the end user. raise ZendeskError(500, "Unknown error occured.") else: raise ZendeskError(500, "Unknown error occured.") zendesk_cred = { "email" : getattr(settings, 'ZENDESK_ADMIN_EMAIL', ''), "password" : getattr(settings, 'ZENDESK_ADMIN_PASSWORD', ''), "subdomain" : getattr(settings, 'ZENDESK_SUBDOMAIN' '') } self._zenpy = zenpy.Zenpy(**zendesk_cred) # Currently as we are not supporting dynamic timezone, # so the following codes are commented. Later this codes will be # used. # Need to get the zendesk admin's timezone # get_admin = self._zenpy.search("email:" + getattr(settings, 'ZE def _manageV2(self, request): # | Function to manage the v2 login # | # | Arguments: Void # | # | Returns: None if request.session.get('zendesksupport', None): zendesksupport_session = request.session['zendesksupport'] # if ( 'ks_user_email' in zendesksupport_session) and ('tenant_id' in zendesksupport_session): # if zendesksupport_session['tenant_id'] == request.user.tenant_id: # return self.keystones #None #Getting the details of the user tenant_id = getattr(settings, 'KEYSTONE_ADMIN_TENANT_ID', '') tenant_name = getattr(settings, 'KEYSTONE_ADMIN_TENANT_NAME', '') user_id = getattr(settings, 'KEYSTONE_ADMIN_USER_ID', '') user_name = getattr(settings, 'KEYSTONE_ADMIN_USERNAME', '') auth_url = getattr(settings, 'KEYSTONE_ADMIN_AUTH_URL', '') password = getattr(settings, 'KEYSTONE_ADMIN_PASSWORD', '') #Making the dictionary to save the data keystone_cred = {} #Saving the details to dictioanry if tenant_id: keystone_cred['tenant_id'] = tenant_id else: keystone_cred['tenant_name'] = tenant_name if user_id: keystone_cred['user_id'] = user_id else: keystone_cred['username'] = user_name keystone_cred['password'] = password keystone_cred['auth_url'] = auth_url auth = identity.v2.Password(**keystone_cred) sess = session.Session(auth=auth) keystone = keystoneclient.v2_0.client.Client(session=sess) #self.keystones = keystone #request.session['keystone_support'] = keystone user = keystone.users.get(request.user.id) tenant = keystone.tenants.get(request.user.tenant_id) request.session['zendesksupport'] = {} request.session['zendesksupport']['tenant_id'] = tenant.id #Role related section roles = keystone.roles.roles_for_user(user=user.id, tenant=user.tenantId) set_role = ['admin', 'service'] for role in roles: if role.name in set_role: request.session['role_check'] = True else: request.session['role_check'] = False # If user has email store it in session if hasattr(user, 'email'): if user.email: request.session['zendesksupport']['ks_user_email'] = user.email request.session['zendesksupport']['ks_user_id'] = user.id #If the user have submitter id then saving it to session if hasattr(user, 'submitter_id'): request.session['zendesksupport']['submitter_id'] = user.submitter_id #Setting the default time zone user_timezone = 'UTC' all_tz = [] for tz in pytz.all_timezones: # Get all the supported timezones, # which will be used to validate all_tz.append(tz) # If user has timezone, store it in session if hasattr(tenant, 'timezone'): if tenant.timezone in all_tz: user_timezone = tenant.timezone request.session['zendesksupport']['user_timezone'] = user_timezone request.session['zendesksupport']['timezone_offset'] = datetime.datetime.now(pytz.timezone(user_timezone)).strftime('%z') return keystone def _manageV3(self, request): # | Function to manage the v3 login # | # | Arguments: None # | # | Returns None if request.session.get('zendesksupport', None): zendesksupport_session = request.session['zendesksupport'] #if ( 'ks_user_email' in zendesksupport_session) and ('tenant_id' in zendesksupport_session): # if zendesksupport_session['tenant_id'] == request.user.project_id: # return None proj_id = getattr(settings, 'KEYSTONE_ADMIN_PROJECT_ID', '') proj_name = getattr(settings, 'KEYSTONE_ADMIN_PROJECT_NAME', '') proj_domain_id = getattr(settings, 'KEYSTONE_ADMIN_PROJECT_DOMAIN_ID', '') proj_domain_name = getattr(settings, 'KEYSTONE_ADMIN_PROJECT_DOMAIN_NAME', '') user_id = getattr(settings, 'KEYSTONE_ADMIN_USER_ID', '') user_name = getattr(settings, 'KEYSTONE_ADMIN_USERNAME', '') user_domain_id = getattr(settings, 'KEYSTONE_ADMIN_USER_DOMAIN_ID', '') user_domain_name = getattr(settings, 'KEYSTONE_ADMIN_USER_DOMAIN_NAME', '') auth_url = getattr(settings, 'KEYSTONE_ADMIN_AUTH_URL', '') password = getattr(settings, 'KEYSTONE_ADMIN_PASSWORD', '') keystone_cred = {} if proj_id: keystone_cred['project_id'] = proj_id else: keystone_cred['project_name'] = proj_name if user_id: keystone_cred['user_id'] = user_id else: keystone_cred['username'] = user_name if proj_domain_id: keystone_cred['project_domain_id'] = proj_domain_id else: keystone_cred['project_domain_name'] = proj_domain_name if user_domain_id: keystone_cred['user_domain_id'] = user_domain_id else: keystone_cred['user_domain_name'] = user_domain_name keystone_cred['auth_url'] = auth_url keystone_cred['password'] = password auth = identity.v3.Password(**keystone_cred) sess = session.Session(auth=auth) keystone = keystoneclient.v3.client.Client(session=sess) #self.keystones = keystone user = keystone.users.get(request.user.id) project = keystone.projects.get(request.user.project_id) request.session['zendesksupport'] = {} request.session['zendesksupport']['tenant_id'] = request.user.project_id #Role related section roles = keystone.roles.list(user=user.id, project=user.default_project_id) set_role = ['admin', 'service'] for role in roles: if role.name in set_role: request.session['role_check'] = True else: request.session['role_check'] = False # If user has email store it in session if hasattr(user, 'email'): if user.email: request.session['zendesksupport']['ks_user_email'] = user.email request.session['zendesksupport']['ks_user_id'] = user.id user_timezone = 'UTC' all_tz = [] for tz in pytz.all_timezones: # Get all the supported timezones, # which will be used to validate all_tz.append(tz) # If user has timezone, store it in session if hasattr(project, 'timezone'): if project.timezone in all_tz: user_timezone = project.timezone request.session['zendesksupport']['user_timezone'] = user_timezone request.session['zendesksupport']['timezone_offset'] = datetime.datetime.now(pytz.timezone(user_timezone)).strftime('%z') return keystone def _get_zendesk_user_id(self, selected_user= None): """ # | Function to get keystone user detail. # | Also this function will create a user with random password # | if no user found. # | # | Arguments: None # | # | Return Type: User object """ #Checking the user is selected user_selected = False if selected_user != None: if selected_user['user'] != '': user_selected = True user_data = selected_user['user'] user_data = user_data.split('--') email = user_data[1] zend_name = user_data[2] ks_id = user_data[0] else: email = self._request.session['zendesksupport']['ks_user_email'] else: if 'zendesk_user_id' in self._request.session['zendesksupport']: return self._request.session['zendesksupport']['zendesk_user_id'] if not self._user_has_email(): # | If there is no email, then there is # | no point to check the user, simple return False raise False email = self._request.session['zendesksupport']['ks_user_email'] users = self._zenpy.search("email:" + email, type="user") # Search user by email, will result maximum one user oly if users.count != 1: # | If no user found, then create a new user if user_selected: pass else: zend_name = self._request.user #Creating new user with the details set new_user = User(name=str(zend_name), email=email, password=self._random_pass()) #uid = self._zenpy.users.create(new_user).id uid = self._zenpy.users.create_or_update(new_user).id self._request.session['zendesksupport']['zendesk_user_id'] = uid extra = {"submitter_id": uid} if user_selected: self.keystone.users.update(ks_id, **extra) else: self.keystone.users.update(self._request.session['zendesksupport']['ks_user_id'], **extra) return uid for user in users: # | As there will be only one user # | so return at first attempt itself. self._request.session['zendesksupport']['zendesk_user_id'] = user.id return user.id def _random_pass(self): """ # | Function to create a random password # | # | Arguments: None # | # | Returns: Random 13 charcter password """ pass_length = 13 chars = string.ascii_letters + string.digits + '!@#$%^&*()' rnd = random.SystemRandom() return "".join(rnd.choice(chars) for i in range(pass_length)) def create_attachment(self, files = []): """ # | Function to add attachment (Currently this is only for upload) # | # | @Arguments: files - list of uploaded files # | @Return: a list of token after uploading the attachments to zendesk """ #Initializing token_list = [] #Looping through each file and uploading them for file in files: name = os.path.basename(file) upload_instance = self._zenpy.attachments.upload(fp=file, target_name = name) token_list.append(upload_instance.token) #Delete the file after upload since it's of no further use os.remove(file) return token_list def list_tickets(self, search_query = {}): """ # | Function to get the available tickets of the user # | # | @Arguments: Void # | # | @Return Type: Result Generator object """ if not self._user_has_email(): LOG.error("No email address found for the user") raise ZendeskError(403, "No email address found for the user") try: search_query['requester'] = self._request.session['zendesksupport']['ks_user_email'] search_query_str = "" for query in search_query: search_query_str += "%s:%s," % (urllib.quote(query), urllib.quote(search_query[query])) search_query_str = search_query_str.strip(",") LOG.info("query string for zendesk => %s" % search_query_str) tickets = self._zenpy.search(search_query_str, type="ticket") modified_list = {} # Okay now we got the tickets from zendesk # But it's time
if last_stat_time: expires_in = last_stat_time + self.__stat_ttl - now if expires_in > 0: return None else: del self.__notfound[name] # Is there an up-to-date compiled version on disk? if self._compiled_is_current(name): compiled_template = self._load_compiled(self._compiled_filename(name)) if compiled_template: return self.store(name, compiled_template) # Now fetch template from source, compile, and cache. tmpl = self._load(name, t_name) if tmpl: tmpl = self._compile(tmpl, self._compiled_filename(name)) return self.store(name, tmpl.data) # Template could not be found. Add to the negative/notfound cache. self.__notfound[name] = now return None def _compile(self, data, compfile=None): """Private method called to parse the template text and compile it into a runtime form. Creates and delegates a template.parser.Parser object to handle the compilation, or uses the object passed in PARSER. On success, the compiled template is stored in the 'data' attribute of the 'data' object and returned. On error, an exception is raised, or None is returned if the TOLERANT flag is set. The optional 'compiled' parameter may be passed to specify the name of a compiled template file to which the generated Python code should be written. Errors are (for now...) silently ignored, assuming that failures to open a file for writing are intentional (e.g directory write permission). """ if data is None: return None text = data.text error = None if not self.__parser: self.__parser = Config.parser(self.__params) # discard the template text - we don't need it any more # del data.text parsedoc = self.__parser.parse(text, data) parsedoc["METADATA"].setdefault("name", data.name) parsedoc["METADATA"].setdefault("modtime", data.time) # write the Python code to the file compfile, if defined if compfile: basedir = os.path.dirname(compfile) if not os.path.isdir(basedir): try: os.makedirs(basedir) except IOError as e: error = Error("failed to create compiled templates " "directory: %s (%s)" % (basedir, e)) if not error: try: self.__document.write_python_file(compfile, parsedoc) except Exception as e: error = Error("cache failed to write %s: %s" % ( os.path.basename(compfile), e)) if error is None and data.time is not None: if not compfile: raise Error("invalid null filename") ctime = int(data.time) os.utime(compfile, (ctime, ctime)) if not error: data.data = Document(parsedoc) return data if self.__tolerant: return None else: raise error def _compiled_is_current(self, template_name): """Returns True if template_name and its compiled name exists and they have the same mtime. """ compiled_name = self._compiled_filename(template_name) if not compiled_name: return False compiled_mtime = modtime(compiled_name) if not compiled_mtime: return False template_mtime = self._template_modified(template_name) if not template_mtime: return False return compiled_mtime == template_mtime def _template_modified(self, path): """Returns the last modified time of the given path, or None if the path does not exist. Override if templates are not on disk, for example. """ if path: return modtime(path) else: return None def _template_content(self, path, modtime=None): """Fetches content pointed to by 'path'. Stores the modification time of the file in the "modtime" attribute of the 'modtime' argument, if it is present. """ if not path: raise Error("No path specified to fetch content from") f = None try: f = open(path) if modtime is not None: modtime.modtime = os.fstat(f.fileno()).st_mtime return f.read() finally: if f: f.close() def _fetch_path(self, name): """Fetch a file from cache or disk by specification of an absolute cache name (e.g. 'header') or filename relative to one of the INCLUDE_PATH directories. If the file isn't already cached and can be found and loaded, it is compiled and cached under the full filename. """ # The template may have been stored using a non-filename name # so look for the plain name in the cache first. slot = self.__lookup.get(name) if slot: # Cached entry exists, so refresh slot and extract data. self._refresh(slot) return slot.data paths = self.paths() # Search the INCLUDE_PATH for the file, in cache or on disk. for dir in paths: path = os.path.join(dir, name) data = self._fetch(path, name) if data: return data # Not found in INCLUDE_PATH, now try DEFAULT. if self.__default is not None and name != self.__default: return self._fetch_path(self.__default) # We could not handle this template name. return None def _compiled_filename(self, path): if not (self.__compile_ext or self.__compile_dir): return None if os.name == "nt": path = path.replace(":", "") compiled = "%s%s" % (path, self.__compile_ext) if self.__compile_dir: # Can't use os.path.join here; compiled may be absolute. compiled = "%s%s%s" % (self.__compile_dir, os.path.sep, compiled) return compiled def _modified(self, name, time=None): """When called with a single argument, it returns the modification time of the named template. When called with a second argument it returns true if 'name' has been modified since 'time'. """ load = self._template_modified(name) if not load: return int(bool(time)) if time: return int(load > time) else: return load def _refresh(self, slot): """Private method called to mark a cache slot as most recently used. A reference to the slot list should be passed by parameter. The slot is relocated to the head of the linked list. If the file from which the data was loaded has been updated since it was compiled, then it is re-loaded from disk and re-compiled. """ data = None now = time.time() expires_in_sec = slot.stat + self.__stat_ttl - now if expires_in_sec <= 0: slot.stat = now template_mtime = self._template_modified(slot.name) if template_mtime is None or template_mtime != slot.load: try: data = self._load(slot.name, slot.data.name) data = self._compile(data) except: slot.stat = 0 raise else: slot.data = data.data slot.load = data.time if self.__head is not slot: # remove existing slot from usage chain... if hasattr(slot, '__next__'): slot_next = getattr(slot, '__next__') elif hasattr(slot, 'next'): slot_next = getattr(slot, 'next') if slot.prev: slot.prev.next = slot_next else: self.__head = slot_next if slot_next: slot_next.prev = slot.prev else: self.__tail = slot.prev # ...and add to start of list head = self.__head if head: head.prev = slot slot.prev = None slot_next = head self.__head = slot return data def _load_compiled(self, path): try: return Document.evaluate_file(path) except TemplateException as e: raise Error("compiled template %s: %s" % (path, e)) def _store(self, name, data, compfile=None): """Private method called to add a data item to the cache. If the cache size limit has been reached then the oldest entry at the tail of the list is removed and its slot relocated to the head of the list and reused for the new data item. If the cache is under the size limit, or if no size limit is defined, then the item is added to the head of the list. Returns compiled template. """ # Return if memory cache disabled. if self.__size is not None and not self.__size: return data.data # Extract the compiled template from the data object. data = data.data # Check the modification time -- extra stat here. load = self._modified(name) if self.__size is not None and self.__slots >= self.__size: # cache has reached size limit, so reuse oldest entry # remove entry from tail or list slot = self.__tail slot.prev.next = None self.__tail = slot.prev # remove name lookup for old node del self.__lookup[slot.name] # add modified node to head of list head = self.__head if head: head.prev = slot slot.reset(name, data, load, time.time(), None, head) self.__head = slot # add name lookup for new node self.__lookup[name] = slot else: # cache is under size limit, or none is defined head = self.__head slot = Slot(name, data, load, time.time(), None, head) if head: head.prev = slot self.__head = slot if not self.__tail: self.__tail = slot # add lookup from name to slot and increment nslots self.__lookup[name] = slot self.__slots += 1 return data def paths(self): """Evaluates the INCLUDE_PATH list, ignoring any blank entries, and calling any callable or objects to return dynamically generated path lists. Returns a new list of paths or raises an exception on error. """ ipaths = self.__include_path[:] opaths = [] count = self.MAX_DIRS while ipaths and count > 0: count -= 1 dir = ipaths.pop(0) if not dir: continue # dir can be a sub or object ref which returns a reference # to a dynamically generated list of search paths if isinstance(dir, collections.Callable): ipaths[:0] = dir() else: try: paths = dir.paths except AttributeError: pass else: if isinstance(paths, collections.Callable):
# Copyright (c) 2020-2021, <NAME> # License: MIT License from typing import ( TYPE_CHECKING, List, Iterable, Tuple, Optional, Dict, Sequence, ) import math import itertools from ezdxf.math import ( Vec3, Z_AXIS, OCS, Matrix44, BoundingBox, ConstructionEllipse, cubic_bezier_from_ellipse, Bezier4P, Bezier3P, BSpline, reverse_bezier_curves, bulge_to_arc, ) from ezdxf.query import EntityQuery from .path import Path from .commands import Command from . import converter if TYPE_CHECKING: from ezdxf.eztypes import Vertex, Layout, EntityQuery __all__ = [ "bbox", "fit_paths_into_box", "transform_paths", "transform_paths_to_ocs", "render_lwpolylines", "render_polylines2d", "render_polylines3d", "render_lines", "render_hatches", "render_mpolygons", "render_splines_and_polylines", "add_bezier4p", "add_bezier3p", "add_ellipse", "add_2d_polyline", "add_spline", "to_multi_path", "single_paths", ] MAX_DISTANCE = 0.01 MIN_SEGMENTS = 4 G1_TOL = 1e-4 IS_CLOSE_TOL = 1e-10 def to_multi_path(paths: Iterable[Path]) -> Path: """Returns a multi-path object from all given paths and their sub-paths. .. versionadded:: 0.17 """ multi_path = Path() for p in paths: multi_path.extend_multi_path(p) return multi_path def single_paths(paths: Iterable[Path]) -> Iterable[Path]: """Yields all given paths and their sub-paths as single path objects. .. versionadded:: 0.17 """ for p in paths: if p.has_sub_paths: yield from p.sub_paths() else: yield p def transform_paths(paths: Iterable[Path], m: Matrix44) -> List[Path]: """Transform multiple :class:`Path` objects at once by transformation matrix `m`. Returns a list of the transformed :class:`Path` objects. Args: paths: iterable of :class:`Path` objects m: transformation matrix of type :class:`~ezdxf.math.Matrix44` """ def decompose(path: Path): vertices.append(path.start) commands.append(Command.START_PATH) for cmd in path: commands.extend(itertools.repeat(cmd.type, len(cmd))) vertices.extend(cmd) def rebuild(vertices): # localize variables: start_path, line_to, curve3_to, curve4_to, move_to = Command path = None collect = [] for vertex, cmd in zip(vertices, commands): if cmd == start_path: if path is not None: transformed_paths.append(path) path = Path(vertex) elif cmd == line_to: path.line_to(vertex) elif cmd == curve3_to: collect.append(vertex) if len(collect) == 2: path.curve3_to(collect[0], collect[1]) collect.clear() elif cmd == curve4_to: collect.append(vertex) if len(collect) == 3: path.curve4_to(collect[0], collect[1], collect[2]) collect.clear() elif cmd == move_to: path.move_to(vertex) if path is not None: transformed_paths.append(path) vertices = [] commands = [] transformed_paths = [] for path in paths: decompose(path) if len(commands): rebuild(m.transform_vertices(vertices)) return transformed_paths def transform_paths_to_ocs(paths: Iterable[Path], ocs: OCS) -> List[Path]: """Transform multiple :class:`Path` objects at once from WCS to OCS. Returns a list of the transformed :class:`Path` objects. Args: paths: iterable of :class:`Path` objects ocs: OCS transformation of type :class:`~ezdxf.math.OCS` """ t = ocs.matrix.copy() t.transpose() return transform_paths(paths, t) def bbox( paths: Iterable[Path], flatten=0.01, segments: int = 16 ) -> BoundingBox: """Returns the :class:`~ezdxf.math.BoundingBox` for the given paths. Args: paths: iterable of :class:`~ezdxf.path.Path` objects flatten: value != 0 for bounding box calculation from the flattened path and value == 0 for bounding box from the control vertices. Default value is 0.01 as max flattening distance. segments: minimal segment count for flattening """ box = BoundingBox() for p in paths: if flatten: box.extend(p.flattening(distance=abs(flatten), segments=segments)) else: box.extend(p.control_vertices()) return box def fit_paths_into_box( paths: Iterable[Path], size: Tuple[float, float, float], uniform: bool = True, source_box: BoundingBox = None, ) -> List[Path]: """Scale the given `paths` to fit into a box of the given `size`, so that all path vertices are inside this borders. If `source_box` is ``None`` the default source bounding box is calculated from the control points of the `paths`. `Note:` if the target size has a z-size of 0, the `paths` are projected into the xy-plane, same is true for the x-size, projects into the yz-plane and the y-size, projects into and xz-plane. Args: paths: iterable of :class:`~ezdxf.path.Path` objects size: target box size as tuple of x-, y- ond z-size values uniform: ``True`` for uniform scaling source_box: pass precalculated source bounding box, or ``None`` to calculate the default source bounding box from the control vertices """ paths = list(paths) if len(paths) == 0: return paths if source_box is None: current_box = bbox(paths, flatten=0) else: current_box = source_box if not current_box.has_data or current_box.size == (0, 0, 0): return paths target_size = Vec3(size) if target_size == (0, 0, 0) or min(target_size) < 0: raise ValueError("invalid target size") if uniform: sx, sy, sz = _get_uniform_scaling(current_box.size, target_size) else: sx, sy, sz = _get_non_uniform_scaling(current_box.size, target_size) m = Matrix44.scale(sx, sy, sz) return transform_paths(paths, m) def _get_uniform_scaling(current_size: Vec3, target_size: Vec3): TOL = 1e-6 scale_x = math.inf if current_size.x > TOL and target_size.x > TOL: scale_x = target_size.x / current_size.x scale_y = math.inf if current_size.y > TOL and target_size.y > TOL: scale_y = target_size.y / current_size.y scale_z = math.inf if current_size.z > TOL and target_size.z > TOL: scale_z = target_size.z / current_size.z uniform_scale = min(scale_x, scale_y, scale_z) if uniform_scale is math.inf: raise ArithmeticError("internal error") scale_x = uniform_scale if target_size.x > TOL else 0 scale_y = uniform_scale if target_size.y > TOL else 0 scale_z = uniform_scale if target_size.z > TOL else 0 return scale_x, scale_y, scale_z def _get_non_uniform_scaling(current_size: Vec3, target_size: Vec3): TOL = 1e-6 scale_x = 1.0 if current_size.x > TOL: scale_x = target_size.x / current_size.x scale_y = 1.0 if current_size.y > TOL: scale_y = target_size.y / current_size.y scale_z = 1.0 if current_size.z > TOL: scale_z = target_size.z / current_size.z return scale_x, scale_y, scale_z # Path to entity converter and render utilities: def render_lwpolylines( layout: "Layout", paths: Iterable[Path], *, distance: float = MAX_DISTANCE, segments: int = MIN_SEGMENTS, extrusion: "Vertex" = Z_AXIS, dxfattribs: Optional[Dict] = None ) -> EntityQuery: """Render the given `paths` into `layout` as :class:`~ezdxf.entities.LWPolyline` entities. The `extrusion` vector is applied to all paths, all vertices are projected onto the plane normal to this extrusion vector. The default extrusion vector is the WCS z-axis. The plane elevation is the distance from the WCS origin to the start point of the first path. Args: layout: the modelspace, a paperspace layout or a block definition paths: iterable of :class:`Path` objects distance: maximum distance, see :meth:`Path.flattening` segments: minimum segment count per Bézier curve extrusion: extrusion vector for all paths dxfattribs: additional DXF attribs Returns: created entities in an :class:`~ezdxf.query.EntityQuery` object .. versionadded:: 0.16 """ lwpolylines = list( converter.to_lwpolylines( paths, distance=distance, segments=segments, extrusion=extrusion, dxfattribs=dxfattribs, ) ) for lwpolyline in lwpolylines: layout.add_entity(lwpolyline) return EntityQuery(lwpolylines) def render_polylines2d( layout: "Layout", paths: Iterable[Path], *, distance: float = 0.01, segments: int = 4, extrusion: "Vertex" = Z_AXIS, dxfattribs: Optional[Dict] = None ) -> EntityQuery: """Render the given `paths` into `layout` as 2D :class:`~ezdxf.entities.Polyline` entities. The `extrusion` vector is applied to all paths, all vertices are projected onto the plane normal to this extrusion vector.The default extrusion vector is the WCS z-axis. The plane elevation is the distance from the WCS origin to the start point of the first path. Args: layout: the modelspace, a paperspace layout or a block definition paths: iterable of :class:`Path` objects distance: maximum distance, see :meth:`Path.flattening` segments: minimum segment count per Bézier curve extrusion: extrusion vector for all paths dxfattribs: additional DXF attribs Returns: created entities in an :class:`~ezdxf.query.EntityQuery` object .. versionadded:: 0.16 """ polylines2d = list( converter.to_polylines2d( paths, distance=distance, segments=segments, extrusion=extrusion, dxfattribs=dxfattribs, ) ) for polyline2d in polylines2d: layout.add_entity(polyline2d) return EntityQuery(polylines2d) def render_hatches( layout: "Layout", paths: Iterable[Path], *, edge_path: bool = True, distance: float = MAX_DISTANCE, segments: int = MIN_SEGMENTS, g1_tol: float = G1_TOL, extrusion: "Vertex" = Z_AXIS, dxfattribs: Optional[Dict] = None ) -> EntityQuery: """Render the given `paths` into `layout` as :class:`~ezdxf.entities.Hatch` entities. The `extrusion` vector is applied to all paths, all vertices are projected onto the plane normal to this extrusion vector. The default extrusion vector is the WCS z-axis. The plane elevation is the distance from the WCS origin to the start point of the first path. Args: layout: the modelspace, a paperspace layout or a block definition paths: iterable of :class:`Path` objects edge_path: ``True`` for edge paths build of LINE and SPLINE edges, ``False`` for only LWPOLYLINE paths as boundary paths distance: maximum distance, see :meth:`Path.flattening` segments: minimum segment count per Bézier curve to flatten polyline paths g1_tol: tolerance for G1 continuity check to separate SPLINE edges extrusion: extrusion vector for all paths dxfattribs: additional DXF attribs Returns: created entities in an :class:`~ezdxf.query.EntityQuery` object .. versionadded:: 0.16 """ hatches = list( converter.to_hatches( paths, edge_path=edge_path, distance=distance, segments=segments, g1_tol=g1_tol, extrusion=extrusion, dxfattribs=dxfattribs, ) ) for hatch in hatches: layout.add_entity(hatch) return EntityQuery(hatches) def render_mpolygons( layout: "Layout", paths: Iterable[Path], *, distance: float = MAX_DISTANCE, segments: int = MIN_SEGMENTS, extrusion: "Vertex" = Z_AXIS, dxfattribs: Optional[Dict] = None ) -> EntityQuery: """Render the given `paths` into `layout` as :class:`~ezdxf.entities.MPolygon` entities.
<filename>paycheck/cross_validate.py import glob import csv from collections import defaultdict, Counter from itertools import cycle import tempfile import os from os.path import join import logging from traceback import format_exc import sys import json import click import numpy.random import numpy import biom from biom import Table import skbio.io from sklearn.model_selection import StratifiedKFold, KFold from pandas import DataFrame from qiime2 import Artifact from qiime2.plugins import clawback, feature_classifier from q2_types.feature_data import DNAIterator from scipy.sparse import dok_matrix @click.command() @click.option( "--empirical-samples", required=True, type=click.Path(exists=True), help="Sample table with SVs for observation ids (biom)", ) @click.option( "--ref-taxa", required=True, type=click.Path(exists=True), help="Greengenes reference taxa (tsv)", ) @click.option( "--ref-seqs", required=True, type=click.Path(exists=True), help="Greengenes reference sequences (fasta)", ) @click.option( "--results-dir", required=True, type=click.Path(exists=True), help="Directory that will contain the result subdirectories", ) @click.option( "--intermediate-dir", default=tempfile.TemporaryDirectory(), type=click.Path(exists=True), help="Directory for checkpointing", ) @click.option( "--k", type=int, default=5, help="Number of folds for cross validation (default 5)", ) @click.option( "--n-jobs", type=int, default=1, help="Number of jobs for parallel classification", ) @click.option("--log-file", type=click.Path(), help="Log file") @click.option( "--log-level", type=click.Choice("DEBUG INFO WARNING ERROR CRITICAL".split()), default="WARNING", help="Log level", ) def generate_folds( empirical_samples, ref_taxa, ref_seqs, results_dir, intermediate_dir, k, n_jobs, log_file, log_level, ): # set up logging setup_logging(log_level, log_file) logging.info(locals()) # Reduce the empirical samples to pure taxonomy-level information biom_path = join(intermediate_dir, "taxonomy_samples.biom") if not os.path.exists(biom_path): taxonomy_samples = map_svs_to_taxa( empirical_samples, ref_taxa, ref_seqs, n_jobs ) with biom.util.biom_open(biom_path, "w") as biom_file: taxonomy_samples.to_hdf5(biom_file, "paycheck") taxonomy_samples = biom.load_table(biom_path) logging.info("Got taxonomy samples") # Generate folds # Generate reference sequence folds seq_ids, seq_strata, taxon_defaults = get_sequence_strata( k, ref_taxa, ref_seqs, n_jobs ) skf = StratifiedKFold(n_splits=k, shuffle=True) seq_split = skf.split(seq_ids, seq_strata) # Generate empirical sample folds kf = KFold(n_splits=k, shuffle=True) sample_ids = taxonomy_samples.ids() sample_split = kf.split(sample_ids) # Save them down for i, ((seq_train, seq_test), (sample_train, sample_test)) in enumerate( zip(seq_split, sample_split) ): fold = join(intermediate_dir, "fold-" + str(i)) os.mkdir(fold) with open(join(fold, "seq_train.json"), "w") as fh: json.dump([seq_ids[j] for j in seq_train], fh) with open(join(fold, "seq_test.json"), "w") as fh: json.dump([seq_ids[j] for j in seq_test], fh) with open(join(fold, "sample_train.json"), "w") as fh: json.dump([sample_ids[j] for j in sample_train], fh) with open(join(fold, "sample_test.json"), "w") as fh: json.dump([sample_ids[j] for j in sample_test], fh) taxon_defaults_file = join(intermediate_dir, "taxon_defaults.json") with open(taxon_defaults_file, "w") as fh: json.dump(taxon_defaults, fh) folds = glob.glob(join(intermediate_dir, "fold-*")) logging.info("Got folds") # For each fold for fold in folds: # Simulate the test samples test_samples, expected = simulate_samples( taxonomy_samples, fold, taxon_defaults, ref_taxa, ref_seqs ) # Generate the class weights from the training samples train_taxa, train_seqs, ref_seqs_art, weights = get_train_artifacts( taxonomy_samples, fold, taxon_defaults, ref_taxa, ref_seqs ) # Save out the expected taxonomies and abundances save_expected(results_dir, test_samples, expected, train_taxa) logging.info("Done expected results for " + fold) # Save the test seqs, training taxa, training seqs, and weights weights_file = join(fold, "weights.qza") weights.save(weights_file) # training_seqs_file = join(fold,'train_seqs.qza') # train_seqs.save(training_seqs_file) training_taxa_file = join(fold, "train_taxa.qza") train_taxa.save(training_taxa_file) # test_seqs_file = join(fold,'ref_seqs_art.qza') # ref_seqs_art.save(test_seqs_file) logging.info("Done " + fold) @click.command() @click.option( "--ref-taxa", required=True, type=click.Path(exists=True), help="Greengenes reference taxa (tsv)", ) @click.option( "--ref-seqs", required=True, type=click.Path(exists=True), help="Greengenes reference sequences (fasta)", ) @click.option( "--classifier-spec", required=True, type=click.File("r"), help="JSON-formatted q2-feature-classifier classifier spec", ) @click.option( "--obs-dir", required=True, type=str, help="Subdirectory into which the results will be saved", ) @click.option( "--results-dir", required=True, type=click.Path(exists=True), help="Directory that will contain the result subdirectories", ) @click.option( "--intermediate-dir", default=tempfile.TemporaryDirectory(), type=click.Path(exists=True), help="Directory for checkpointing", ) @click.option( "--n-jobs", type=int, default=1, help="Number of jobs for parallel classification", ) @click.option("--log-file", type=click.Path(), help="Log file") @click.option( "--log-level", type=click.Choice("DEBUG INFO WARNING ERROR CRITICAL".split()), default="WARNING", help="Log level", ) @click.option( "--confidence", required=True, type=float, help="Number of Confidence" ) @click.option( "--classifier-directory", required=True, type=str, help="Directory of Classifier", ) @click.option( "--weighted/--not-weighted", default=True, type=bool, help="Perform weighted classification" ) def cross_validate_classifier( ref_taxa, ref_seqs, classifier_spec, obs_dir, results_dir, intermediate_dir, n_jobs, log_file, log_level, confidence, classifier_directory, weighted ): classifier_spec = classifier_spec.read() # set up logging setup_logging(log_level, log_file) logging.info(locals()) # load folds taxon_defaults_file = join(intermediate_dir, "taxon_defaults.json") with open(taxon_defaults_file) as fh: taxon_defaults = json.load(fh) folds = glob.glob(join(intermediate_dir, "fold-*")) logging.info("Got folds") # load ref_seq _, ref_seqs = load_references(ref_taxa, ref_seqs) ref_seqs = Artifact.import_data( "FeatureData[Sequence]", DNAIterator(ref_seqs) ) # for each fold for fold in folds: # load new file for different folds weights_file = join(fold, "weights.qza") training_taxa_file = join(fold, "train_taxa.qza") # load the simulated test samples test_samples = load_simulated_samples(fold, results_dir) # load the test seqs, training taxa, traing seqs, and weights weights = Artifact.load(weights_file) if weighted else None # test_seqs = Artifact.load(test_seqs_file) train_taxa = Artifact.load(training_taxa_file) # train the weighted classifier and classify the test samples classification = classify_samples_sklearn( test_samples, train_taxa, ref_seqs, classifier_spec, confidence, n_jobs, weights, ) # save the classified taxonomy artifacts save_observed( classifier_directory, test_samples, classification, obs_dir ) logging.info("Done " + fold) @click.command() @click.option( "--ref-taxa", required=True, type=click.Path(exists=True), help="Greengenes reference taxa (tsv)", ) @click.option( "--ref-seqs", required=True, type=click.Path(exists=True), help="Greengenes reference sequences (fasta)", ) @click.option( "--classifier-spec", required=True, type=str, # EEE ugly hack - fix me help="ClassifierSpecification QIIME 2 Artifact (qza)" ) @click.option( "--obs-dir", required=True, type=str, help="Subdirectory into which the results will be saved", ) @click.option( "--results-dir", required=True, type=click.Path(exists=True), help="Directory that will contain the result subdirectories", ) @click.option( "--intermediate-dir", default=tempfile.TemporaryDirectory(), type=click.Path(exists=True), help="Directory for checkpointing", ) @click.option( "--n-jobs", type=int, default=1, help="Number of jobs for parallel classification", ) @click.option("--log-file", type=click.Path(), help="Log file") @click.option( "--log-level", type=click.Choice("DEBUG INFO WARNING ERROR CRITICAL".split()), default="WARNING", help="Log level", ) @click.option( "--confidence", required=True, type=float, help="Number of Confidence" ) @click.option( "--classifier-directory", required=True, type=str, help="Directory of Classifier", ) @click.option( "--sequence-encoder", type=str, default="Seq2VecEncoder", help="Sequence Encoder", ) @click.option( "--read-length", type=int, default=150, help="Read length for classifier" ) @click.option( "--vec-length", type=int, default=300, help="Seq2Vec encoded vector length" ) @click.option( "--batch-size", type=int, default=2048, help="Batch size for fitting and prediction", ) @click.option( "--epochs", type=int, default=5, help="Number of training epochs" ) def cross_validate_keras( ref_taxa, ref_seqs, classifier_spec, obs_dir, results_dir, intermediate_dir, n_jobs, log_file, log_level, confidence, classifier_directory, sequence_encoder, read_length, vec_length, batch_size, epochs, ): classifier_spec = Artifact.load(classifier_spec) # set up logging setup_logging(log_level, log_file) logging.info(locals()) # load folds taxon_defaults_file = join(intermediate_dir, "taxon_defaults.json") with open(taxon_defaults_file) as fh: taxon_defaults = json.load(fh) folds = glob.glob(join(intermediate_dir, "fold-*")) logging.info("Got folds") # load ref_seq _, ref_seqs = load_references(ref_taxa, ref_seqs) ref_seqs = Artifact.import_data( "FeatureData[Sequence]", DNAIterator(ref_seqs) ) # for each fold for fold in folds: # load new file for different folds weights_file = join(fold, "weights.qza") training_taxa_file = join(fold, "train_taxa.qza") # load the simulated test samples test_samples = load_simulated_samples(fold, results_dir) # check to see whether we have already done this fold if check_observed(classifier_directory, test_samples, obs_dir): logging.info("Skipping " + fold) continue # load the test seqs, training taxa, traing seqs, and weights weights = Artifact.load(weights_file) # test_seqs = Artifact.load(test_seqs_file) train_taxa = Artifact.load(training_taxa_file) # train the weighted classifier and classify the test samples classification = classify_samples_keras( test_samples, train_taxa, ref_seqs, classifier_spec, confidence, n_jobs, weights=weights, sequence_encoder=sequence_encoder, read_length=read_length, vec_length=vec_length, batch_size=batch_size, epochs=epochs, ) # save the classified taxonomy artifacts save_observed( classifier_directory, test_samples, classification, obs_dir ) logging.info("Done " + fold) @click.command() @click.option( "--ref-taxa", required=True, type=click.Path(exists=True), help="Greengenes reference taxa (tsv)", ) @click.option( "--ref-seqs", required=True, type=click.Path(exists=True), help="Greengenes reference sequences (fasta)", ) @click.option( "--obs-dir", required=True, type=str, help="Subdirectory into which the results will be saved", ) @click.option( "--results-dir", required=True, type=click.Path(exists=True), help="Directory that will contain the result subdirectories", ) @click.option( "--intermediate-dir", default=tempfile.TemporaryDirectory(), type=click.Path(exists=True), help="Directory for checkpointing", ) @click.option("--log-file", type=click.Path(), help="Log file") @click.option( "--log-level", type=click.Choice("DEBUG INFO WARNING ERROR CRITICAL".split()), default="WARNING", help="Log level", ) @click.option( "--confidence", required=True, type=float, help="Number of Confidence" ) @click.option( "--classifier-directory", required=True, type=str, help="Directory of Classifier", ) @click.option( "--weights", required=False, type=click.Path(exists=True), help="Taxonomic weights - uniform assumed if absent (qza)" ) def cross_validate_stochastic( ref_taxa, ref_seqs, obs_dir, results_dir, intermediate_dir, log_file, log_level, confidence, classifier_directory, weights ): # set up logging setup_logging(log_level, log_file) logging.info(locals()) # load folds taxon_defaults_file = join(intermediate_dir, "taxon_defaults.json") with open(taxon_defaults_file) as fh: taxon_defaults = json.load(fh) folds = glob.glob(join(intermediate_dir, "fold-*")) logging.info("Got folds") # load ref_seq ref_taxa, ref_seqs = load_references(ref_taxa, ref_seqs) ref_seqs = Artifact.import_data( "FeatureData[Sequence]", DNAIterator(ref_seqs) ) if weights: # load the weights weights = Artifact.load(weights) # create a perfect classifier classifier = create_stochastic_classifier( ref_taxa, ref_seqs, confidence, weights=weights.view(Table) ) else: # create a perfect classifier classifier = create_stochastic_classifier( ref_taxa, ref_seqs, confidence ) # for each fold for fold in folds: # load the simulated test samples test_samples = load_simulated_samples(fold, results_dir) # check to see whether we have already done this fold if check_observed(classifier_directory, test_samples, obs_dir): logging.info("Skipping " + fold) continue # train the weighted classifier and classify the test samples classification = classify_samples_stochastic( classifier, ref_seqs, test_samples ) # save the classified taxonomy artifacts save_observed( classifier_directory, test_samples, classification, obs_dir ) logging.info("Done " + fold) @click.command() @click.option( "--ref-taxa", required=True, type=click.Path(exists=True), help="Greengenes reference taxa (tsv)", ) @click.option( "--ref-seqs", required=True, type=click.Path(exists=True), help="Greengenes reference sequences (fasta)", ) @click.option( "--obs-dir", required=True, type=str, help="Subdirectory into which the results will be saved", ) @click.option( "--results-dir", required=True, type=click.Path(exists=True), help="Directory that will contain the result subdirectories", ) @click.option( "--intermediate-dir", default=tempfile.TemporaryDirectory(), type=click.Path(exists=True), help="Directory for checkpointing", ) @click.option("--log-file", type=click.Path(), help="Log file") @click.option( "--log-level", type=click.Choice("DEBUG INFO WARNING ERROR CRITICAL".split()), default="WARNING", help="Log level", ) @click.option( "--confidence", required=True, type=float, help="Number of Confidence" ) @click.option( "--classifier-directory", required=True, type=str, help="Directory of Classifier", ) @click.option( "--weights", required=False, type=click.Path(exists=True), help="Taxonomic weights - uniform assumed if absent (qza)" ) def cross_validate_perfect( ref_taxa, ref_seqs, obs_dir, results_dir, intermediate_dir, log_file, log_level, confidence, classifier_directory, weights ): # set up logging setup_logging(log_level, log_file) logging.info(locals()) # load folds taxon_defaults_file = join(intermediate_dir, "taxon_defaults.json") with
arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24, arg25, arg26) MPDSGeosClassicSimSimulation = _geosclassic.MPDSGeosClassicSimSimulation class mpds_grid(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, mpds_grid, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, mpds_grid, name) __repr__ = _swig_repr __swig_setmethods__["nx"] = _geosclassic.mpds_grid_nx_set __swig_getmethods__["nx"] = _geosclassic.mpds_grid_nx_get if _newclass: nx = _swig_property(_geosclassic.mpds_grid_nx_get, _geosclassic.mpds_grid_nx_set) __swig_setmethods__["ny"] = _geosclassic.mpds_grid_ny_set __swig_getmethods__["ny"] = _geosclassic.mpds_grid_ny_get if _newclass: ny = _swig_property(_geosclassic.mpds_grid_ny_get, _geosclassic.mpds_grid_ny_set) __swig_setmethods__["nz"] = _geosclassic.mpds_grid_nz_set __swig_getmethods__["nz"] = _geosclassic.mpds_grid_nz_get if _newclass: nz = _swig_property(_geosclassic.mpds_grid_nz_get, _geosclassic.mpds_grid_nz_set) __swig_setmethods__["sx"] = _geosclassic.mpds_grid_sx_set __swig_getmethods__["sx"] = _geosclassic.mpds_grid_sx_get if _newclass: sx = _swig_property(_geosclassic.mpds_grid_sx_get, _geosclassic.mpds_grid_sx_set) __swig_setmethods__["sy"] = _geosclassic.mpds_grid_sy_set __swig_getmethods__["sy"] = _geosclassic.mpds_grid_sy_get if _newclass: sy = _swig_property(_geosclassic.mpds_grid_sy_get, _geosclassic.mpds_grid_sy_set) __swig_setmethods__["sz"] = _geosclassic.mpds_grid_sz_set __swig_getmethods__["sz"] = _geosclassic.mpds_grid_sz_get if _newclass: sz = _swig_property(_geosclassic.mpds_grid_sz_get, _geosclassic.mpds_grid_sz_set) __swig_setmethods__["ox"] = _geosclassic.mpds_grid_ox_set __swig_getmethods__["ox"] = _geosclassic.mpds_grid_ox_get if _newclass: ox = _swig_property(_geosclassic.mpds_grid_ox_get, _geosclassic.mpds_grid_ox_set) __swig_setmethods__["oy"] = _geosclassic.mpds_grid_oy_set __swig_getmethods__["oy"] = _geosclassic.mpds_grid_oy_get if _newclass: oy = _swig_property(_geosclassic.mpds_grid_oy_get, _geosclassic.mpds_grid_oy_set) __swig_setmethods__["oz"] = _geosclassic.mpds_grid_oz_set __swig_getmethods__["oz"] = _geosclassic.mpds_grid_oz_get if _newclass: oz = _swig_property(_geosclassic.mpds_grid_oz_get, _geosclassic.mpds_grid_oz_set) __swig_setmethods__["nxy"] = _geosclassic.mpds_grid_nxy_set __swig_getmethods__["nxy"] = _geosclassic.mpds_grid_nxy_get if _newclass: nxy = _swig_property(_geosclassic.mpds_grid_nxy_get, _geosclassic.mpds_grid_nxy_set) __swig_setmethods__["nxyz"] = _geosclassic.mpds_grid_nxyz_set __swig_getmethods__["nxyz"] = _geosclassic.mpds_grid_nxyz_get if _newclass: nxyz = _swig_property(_geosclassic.mpds_grid_nxyz_get, _geosclassic.mpds_grid_nxyz_set) def __init__(self): this = _geosclassic.new_mpds_grid() try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _geosclassic.delete_mpds_grid __del__ = lambda self: None mpds_grid_swigregister = _geosclassic.mpds_grid_swigregister mpds_grid_swigregister(mpds_grid) def MPDSCmpGrid(arg1, arg2): return _geosclassic.MPDSCmpGrid(arg1, arg2) MPDSCmpGrid = _geosclassic.MPDSCmpGrid def MPDSCopyGrid(arg1, arg2): return _geosclassic.MPDSCopyGrid(arg1, arg2) MPDSCopyGrid = _geosclassic.MPDSCopyGrid def MPDSGridCoordToId(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGridCoordToId(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGridCoordToId = _geosclassic.MPDSGridCoordToId def MPDSGridIdToCoord(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGridIdToCoord(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGridIdToCoord = _geosclassic.MPDSGridIdToCoord def MPDSInitGrid(arg1): return _geosclassic.MPDSInitGrid(arg1) MPDSInitGrid = _geosclassic.MPDSInitGrid def MPDSPrintGrid(arg1, arg2, arg3): return _geosclassic.MPDSPrintGrid(arg1, arg2, arg3) MPDSPrintGrid = _geosclassic.MPDSPrintGrid def MPDSReadGrid(arg1, arg2): return _geosclassic.MPDSReadGrid(arg1, arg2) MPDSReadGrid = _geosclassic.MPDSReadGrid def MPDSValidateGrid(arg1, arg2): return _geosclassic.MPDSValidateGrid(arg1, arg2) MPDSValidateGrid = _geosclassic.MPDSValidateGrid class mpds_image(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, mpds_image, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, mpds_image, name) __repr__ = _swig_repr __swig_setmethods__["grid"] = _geosclassic.mpds_image_grid_set __swig_getmethods__["grid"] = _geosclassic.mpds_image_grid_get if _newclass: grid = _swig_property(_geosclassic.mpds_image_grid_get, _geosclassic.mpds_image_grid_set) __swig_setmethods__["nvar"] = _geosclassic.mpds_image_nvar_set __swig_getmethods__["nvar"] = _geosclassic.mpds_image_nvar_get if _newclass: nvar = _swig_property(_geosclassic.mpds_image_nvar_get, _geosclassic.mpds_image_nvar_set) __swig_setmethods__["nxyzv"] = _geosclassic.mpds_image_nxyzv_set __swig_getmethods__["nxyzv"] = _geosclassic.mpds_image_nxyzv_get if _newclass: nxyzv = _swig_property(_geosclassic.mpds_image_nxyzv_get, _geosclassic.mpds_image_nxyzv_set) __swig_setmethods__["varName"] = _geosclassic.mpds_image_varName_set __swig_getmethods__["varName"] = _geosclassic.mpds_image_varName_get if _newclass: varName = _swig_property(_geosclassic.mpds_image_varName_get, _geosclassic.mpds_image_varName_set) __swig_setmethods__["var"] = _geosclassic.mpds_image_var_set __swig_getmethods__["var"] = _geosclassic.mpds_image_var_get if _newclass: var = _swig_property(_geosclassic.mpds_image_var_get, _geosclassic.mpds_image_var_set) def __init__(self): this = _geosclassic.new_mpds_image() try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _geosclassic.delete_mpds_image __del__ = lambda self: None mpds_image_swigregister = _geosclassic.mpds_image_swigregister mpds_image_swigregister(mpds_image) def MPDSCopyImage(arg1, arg2): return _geosclassic.MPDSCopyImage(arg1, arg2) MPDSCopyImage = _geosclassic.MPDSCopyImage def MPDSFreeImage(arg1): return _geosclassic.MPDSFreeImage(arg1) MPDSFreeImage = _geosclassic.MPDSFreeImage def MPDSGetImageOneVarValueIndex(arg1, arg2, arg3, arg4, arg5): return _geosclassic.MPDSGetImageOneVarValueIndex(arg1, arg2, arg3, arg4, arg5) MPDSGetImageOneVarValueIndex = _geosclassic.MPDSGetImageOneVarValueIndex def MPDSGetImageNumberVarValueMissing(arg1, arg2): return _geosclassic.MPDSGetImageNumberVarValueMissing(arg1, arg2) MPDSGetImageNumberVarValueMissing = _geosclassic.MPDSGetImageNumberVarValueMissing def MPDSGetImageOneVarValueMean(arg1, arg2, arg3): return _geosclassic.MPDSGetImageOneVarValueMean(arg1, arg2, arg3) MPDSGetImageOneVarValueMean = _geosclassic.MPDSGetImageOneVarValueMean def MPDSGetImageOneVarValuePdf(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGetImageOneVarValuePdf(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGetImageOneVarValuePdf = _geosclassic.MPDSGetImageOneVarValuePdf def MPDSGetImageOneVarValueRange(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGetImageOneVarValueRange(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGetImageOneVarValueRange = _geosclassic.MPDSGetImageOneVarValueRange def MPDSGetImageOneVarValueSD(arg1, arg2, arg3, arg4): return _geosclassic.MPDSGetImageOneVarValueSD(arg1, arg2, arg3, arg4) MPDSGetImageOneVarValueSD = _geosclassic.MPDSGetImageOneVarValueSD def MPDSGetImageVarStats(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGetImageVarStats(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGetImageVarStats = _geosclassic.MPDSGetImageVarStats def MPDSGetImageVarStatsLocal(arg1, arg2, arg3, arg4): return _geosclassic.MPDSGetImageVarStatsLocal(arg1, arg2, arg3, arg4) MPDSGetImageVarStatsLocal = _geosclassic.MPDSGetImageVarStatsLocal def MPDSGetImageVarValueMean(arg1, arg2): return _geosclassic.MPDSGetImageVarValueMean(arg1, arg2) MPDSGetImageVarValueMean = _geosclassic.MPDSGetImageVarValueMean def MPDSGetImageVarValuePdf(arg1, arg2, arg3, arg4, arg5): return _geosclassic.MPDSGetImageVarValuePdf(arg1, arg2, arg3, arg4, arg5) MPDSGetImageVarValuePdf = _geosclassic.MPDSGetImageVarValuePdf def MPDSGetImageVarValueRange(arg1, arg2, arg3, arg4, arg5): return _geosclassic.MPDSGetImageVarValueRange(arg1, arg2, arg3, arg4, arg5) MPDSGetImageVarValueRange = _geosclassic.MPDSGetImageVarValueRange def MPDSGetImageVarValueSD(arg1, arg2, arg3): return _geosclassic.MPDSGetImageVarValueSD(arg1, arg2, arg3) MPDSGetImageVarValueSD = _geosclassic.MPDSGetImageVarValueSD def MPDSGetImageVarVectorMissing(arg1, arg2, arg3): return _geosclassic.MPDSGetImageVarVectorMissing(arg1, arg2, arg3) MPDSGetImageVarVectorMissing = _geosclassic.MPDSGetImageVarVectorMissing def MPDSGetNImageOneVarValuePdf(arg1, arg2, arg3, arg4, arg5, arg6, arg7): return _geosclassic.MPDSGetNImageOneVarValuePdf(arg1, arg2, arg3, arg4, arg5, arg6, arg7) MPDSGetNImageOneVarValuePdf = _geosclassic.MPDSGetNImageOneVarValuePdf def MPDSGetNImageVarValuePdf(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGetNImageVarValuePdf(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGetNImageVarValuePdf = _geosclassic.MPDSGetNImageVarValuePdf def MPDSImageToImage(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9): return _geosclassic.MPDSImageToImage(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) MPDSImageToImage = _geosclassic.MPDSImageToImage def MPDSInitImage(arg1): return _geosclassic.MPDSInitImage(arg1) MPDSInitImage = _geosclassic.MPDSInitImage def MPDSMallocImage(arg1, arg2, arg3): return _geosclassic.MPDSMallocImage(arg1, arg2, arg3) MPDSMallocImage = _geosclassic.MPDSMallocImage def MPDSPrintImage(arg1, arg2, arg3): return _geosclassic.MPDSPrintImage(arg1, arg2, arg3) MPDSPrintImage = _geosclassic.MPDSPrintImage def MPDSPrintImageInfo(arg1, arg2, arg3, arg4): return _geosclassic.MPDSPrintImageInfo(arg1, arg2, arg3, arg4) MPDSPrintImageInfo = _geosclassic.MPDSPrintImageInfo def MPDSReadImage(arg1, arg2, arg3): return _geosclassic.MPDSReadImage(arg1, arg2, arg3) MPDSReadImage = _geosclassic.MPDSReadImage def MPDSReadImageGslibBinary(arg1, arg2): return _geosclassic.MPDSReadImageGslibBinary(arg1, arg2) MPDSReadImageGslibBinary = _geosclassic.MPDSReadImageGslibBinary def MPDSTransformLinearImageVar(arg1, arg2, arg3, arg4): return _geosclassic.MPDSTransformLinearImageVar(arg1, arg2, arg3, arg4) MPDSTransformLinearImageVar = _geosclassic.MPDSTransformLinearImageVar def MPDSTransformExplicitImageVar(arg1, arg2, arg3, arg4, arg5): return _geosclassic.MPDSTransformExplicitImageVar(arg1, arg2, arg3, arg4, arg5) MPDSTransformExplicitImageVar = _geosclassic.MPDSTransformExplicitImageVar def MPDSValidateImage(arg1, arg2, arg3): return _geosclassic.MPDSValidateImage(arg1, arg2, arg3) MPDSValidateImage = _geosclassic.MPDSValidateImage def MPDSWriteImage(arg1, arg2, arg3, arg4): return _geosclassic.MPDSWriteImage(arg1, arg2, arg3, arg4) MPDSWriteImage = _geosclassic.MPDSWriteImage def MPDSWriteImageGslibBinary(arg1, arg2): return _geosclassic.MPDSWriteImageGslibBinary(arg1, arg2) MPDSWriteImageGslibBinary = _geosclassic.MPDSWriteImageGslibBinary def MPDSFree(arg1): return _geosclassic.MPDSFree(arg1) MPDSFree = _geosclassic.MPDSFree def MPDSFreeArray2D(arg1): return _geosclassic.MPDSFreeArray2D(arg1) MPDSFreeArray2D = _geosclassic.MPDSFreeArray2D def MPDSFreeArray3D(arg1): return _geosclassic.MPDSFreeArray3D(arg1) MPDSFreeArray3D = _geosclassic.MPDSFreeArray3D def MPDSFreeArray4D(arg1): return _geosclassic.MPDSFreeArray4D(arg1) MPDSFreeArray4D = _geosclassic.MPDSFreeArray4D def MPDSMalloc(arg1, arg2, arg3): return _geosclassic.MPDSMalloc(arg1, arg2, arg3) MPDSMalloc = _geosclassic.MPDSMalloc def MPDSMallocArray2D(arg1, arg2, arg3, arg4): return _geosclassic.MPDSMallocArray2D(arg1, arg2, arg3, arg4) MPDSMallocArray2D = _geosclassic.MPDSMallocArray2D def MPDSMallocArray3D(arg1, arg2, arg3, arg4, arg5): return _geosclassic.MPDSMallocArray3D(arg1, arg2, arg3, arg4, arg5) MPDSMallocArray3D = _geosclassic.MPDSMallocArray3D def MPDSMallocArray4D(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSMallocArray4D(arg1, arg2, arg3, arg4, arg5, arg6) MPDSMallocArray4D = _geosclassic.MPDSMallocArray4D def MPDSRealloc(arg1, arg2, arg3, arg4): return _geosclassic.MPDSRealloc(arg1, arg2, arg3, arg4) MPDSRealloc = _geosclassic.MPDSRealloc class mpds_pointSet(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, mpds_pointSet, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, mpds_pointSet, name) __repr__ = _swig_repr __swig_setmethods__["npoint"] = _geosclassic.mpds_pointSet_npoint_set __swig_getmethods__["npoint"] = _geosclassic.mpds_pointSet_npoint_get if _newclass: npoint = _swig_property(_geosclassic.mpds_pointSet_npoint_get, _geosclassic.mpds_pointSet_npoint_set) __swig_setmethods__["x"] = _geosclassic.mpds_pointSet_x_set __swig_getmethods__["x"] = _geosclassic.mpds_pointSet_x_get if _newclass: x = _swig_property(_geosclassic.mpds_pointSet_x_get, _geosclassic.mpds_pointSet_x_set) __swig_setmethods__["y"] = _geosclassic.mpds_pointSet_y_set __swig_getmethods__["y"] = _geosclassic.mpds_pointSet_y_get if _newclass: y = _swig_property(_geosclassic.mpds_pointSet_y_get, _geosclassic.mpds_pointSet_y_set) __swig_setmethods__["z"] = _geosclassic.mpds_pointSet_z_set __swig_getmethods__["z"] = _geosclassic.mpds_pointSet_z_get if _newclass: z = _swig_property(_geosclassic.mpds_pointSet_z_get, _geosclassic.mpds_pointSet_z_set) __swig_setmethods__["nvar"] = _geosclassic.mpds_pointSet_nvar_set __swig_getmethods__["nvar"] = _geosclassic.mpds_pointSet_nvar_get if _newclass: nvar = _swig_property(_geosclassic.mpds_pointSet_nvar_get, _geosclassic.mpds_pointSet_nvar_set) __swig_setmethods__["varName"] = _geosclassic.mpds_pointSet_varName_set __swig_getmethods__["varName"] = _geosclassic.mpds_pointSet_varName_get if _newclass: varName = _swig_property(_geosclassic.mpds_pointSet_varName_get, _geosclassic.mpds_pointSet_varName_set) __swig_setmethods__["var"] = _geosclassic.mpds_pointSet_var_set __swig_getmethods__["var"] = _geosclassic.mpds_pointSet_var_get if _newclass: var = _swig_property(_geosclassic.mpds_pointSet_var_get, _geosclassic.mpds_pointSet_var_set) def __init__(self): this = _geosclassic.new_mpds_pointSet() try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _geosclassic.delete_mpds_pointSet __del__ = lambda self: None mpds_pointSet_swigregister = _geosclassic.mpds_pointSet_swigregister mpds_pointSet_swigregister(mpds_pointSet) def MPDSCopyPointSet(arg1, arg2): return _geosclassic.MPDSCopyPointSet(arg1, arg2) MPDSCopyPointSet = _geosclassic.MPDSCopyPointSet def MPDSFreePointSet(arg1): return _geosclassic.MPDSFreePointSet(arg1) MPDSFreePointSet = _geosclassic.MPDSFreePointSet def MPDSGetIndexInGridForPointSet(arg1, arg2, arg3, arg4): return _geosclassic.MPDSGetIndexInGridForPointSet(arg1, arg2, arg3, arg4) MPDSGetIndexInGridForPointSet = _geosclassic.MPDSGetIndexInGridForPointSet def MPDSGetPointSetInfo(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18): return _geosclassic.MPDSGetPointSetInfo(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18) MPDSGetPointSetInfo = _geosclassic.MPDSGetPointSetInfo def MPDSGetXYZIndexInGridForPointSet(arg1, arg2, arg3, arg4, arg5, arg6): return _geosclassic.MPDSGetXYZIndexInGridForPointSet(arg1, arg2, arg3, arg4, arg5, arg6) MPDSGetXYZIndexInGridForPointSet = _geosclassic.MPDSGetXYZIndexInGridForPointSet def MPDSImageToPointSet(arg1, arg2): return _geosclassic.MPDSImageToPointSet(arg1, arg2) MPDSImageToPointSet = _geosclassic.MPDSImageToPointSet def MPDSInitPointSet(arg1): return _geosclassic.MPDSInitPointSet(arg1) MPDSInitPointSet = _geosclassic.MPDSInitPointSet def MPDSMallocPointSet(arg1, arg2, arg3): return _geosclassic.MPDSMallocPointSet(arg1, arg2, arg3) MPDSMallocPointSet = _geosclassic.MPDSMallocPointSet def MPDSPointSetToImage(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10): return _geosclassic.MPDSPointSetToImage(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) MPDSPointSetToImage = _geosclassic.MPDSPointSetToImage def MPDSPrintPointSet(arg1, arg2, arg3): return _geosclassic.MPDSPrintPointSet(arg1, arg2, arg3) MPDSPrintPointSet = _geosclassic.MPDSPrintPointSet def MPDSPrintPointSetInfo(arg1, arg2, arg3): return _geosclassic.MPDSPrintPointSetInfo(arg1, arg2, arg3) MPDSPrintPointSetInfo = _geosclassic.MPDSPrintPointSetInfo def MPDSReadPointSet(arg1, arg2): return _geosclassic.MPDSReadPointSet(arg1, arg2) MPDSReadPointSet = _geosclassic.MPDSReadPointSet def MPDSValidatePointSet(arg1, arg2): return _geosclassic.MPDSValidatePointSet(arg1, arg2) MPDSValidatePointSet = _geosclassic.MPDSValidatePointSet def MPDSWritePointSet(arg1, arg2, arg3, arg4): return _geosclassic.MPDSWritePointSet(arg1, arg2, arg3, arg4) MPDSWritePointSet = _geosclassic.MPDSWritePointSet MPDS_WARNING_MSG_00001 = _geosclassic.MPDS_WARNING_MSG_00001 MPDS_WARNING_MSG_00002 = _geosclassic.MPDS_WARNING_MSG_00002 MPDS_WARNING_MSG_00003 = _geosclassic.MPDS_WARNING_MSG_00003 MPDS_WARNING_MSG_00010 = _geosclassic.MPDS_WARNING_MSG_00010 MPDS_WARNING_MSG_00012 = _geosclassic.MPDS_WARNING_MSG_00012 MPDS_WARNING_MSG_00014 = _geosclassic.MPDS_WARNING_MSG_00014 MPDS_WARNING_MSG_00020 = _geosclassic.MPDS_WARNING_MSG_00020 MPDS_WARNING_MSG_00021 = _geosclassic.MPDS_WARNING_MSG_00021 MPDS_WARNING_MSG_00025 = _geosclassic.MPDS_WARNING_MSG_00025 MPDS_WARNING_MSG_00027 = _geosclassic.MPDS_WARNING_MSG_00027 MPDS_WARNING_MSG_00026 = _geosclassic.MPDS_WARNING_MSG_00026 MPDS_WARNING_MSG_00030 = _geosclassic.MPDS_WARNING_MSG_00030 MPDS_WARNING_MSG_00031 = _geosclassic.MPDS_WARNING_MSG_00031 MPDS_WARNING_MSG_00032 = _geosclassic.MPDS_WARNING_MSG_00032 MPDS_WARNING_MSG_00033 = _geosclassic.MPDS_WARNING_MSG_00033 MPDS_WARNING_MSG_00034 = _geosclassic.MPDS_WARNING_MSG_00034 MPDS_WARNING_MSG_00035 = _geosclassic.MPDS_WARNING_MSG_00035 MPDS_WARNING_MSG_00036 = _geosclassic.MPDS_WARNING_MSG_00036 MPDS_WARNING_MSG_00038 = _geosclassic.MPDS_WARNING_MSG_00038 MPDS_WARNING_MSG_00039 = _geosclassic.MPDS_WARNING_MSG_00039 MPDS_WARNING_MSG_00040 = _geosclassic.MPDS_WARNING_MSG_00040 MPDS_WARNING_MSG_00041 = _geosclassic.MPDS_WARNING_MSG_00041 MPDS_WARNING_MSG_00042 = _geosclassic.MPDS_WARNING_MSG_00042 MPDS_WARNING_MSG_00043 = _geosclassic.MPDS_WARNING_MSG_00043 MPDS_WARNING_MSG_00044 = _geosclassic.MPDS_WARNING_MSG_00044 MPDS_WARNING_MSG_00045 = _geosclassic.MPDS_WARNING_MSG_00045 MPDS_WARNING_MSG_00046 = _geosclassic.MPDS_WARNING_MSG_00046 MPDS_WARNING_MSG_00049 = _geosclassic.MPDS_WARNING_MSG_00049 MPDS_WARNING_MSG_00050 = _geosclassic.MPDS_WARNING_MSG_00050 MPDS_WARNING_MSG_00051 = _geosclassic.MPDS_WARNING_MSG_00051 MPDS_WARNING_MSG_00055 = _geosclassic.MPDS_WARNING_MSG_00055 MPDS_WARNING_MSG_00060 = _geosclassic.MPDS_WARNING_MSG_00060 MPDS_WARNING_MSG_00061 = _geosclassic.MPDS_WARNING_MSG_00061 MPDS_WARNING_MSG_00062 = _geosclassic.MPDS_WARNING_MSG_00062 MPDS_WARNING_MSG_00063 = _geosclassic.MPDS_WARNING_MSG_00063 MPDS_WARNING_MSG_00070 = _geosclassic.MPDS_WARNING_MSG_00070 MPDS_WARNING_MSG_00071 = _geosclassic.MPDS_WARNING_MSG_00071 MPDS_WARNING_MSG_00080 = _geosclassic.MPDS_WARNING_MSG_00080 MPDS_WARNING_MSG_00100 = _geosclassic.MPDS_WARNING_MSG_00100 MPDS_WARNING_MSG_00111 = _geosclassic.MPDS_WARNING_MSG_00111 MPDS_WARNING_MSG_00115 = _geosclassic.MPDS_WARNING_MSG_00115 MPDS_WARNING_MSG_00120 = _geosclassic.MPDS_WARNING_MSG_00120 MPDS_WARNING_MSG_00150 = _geosclassic.MPDS_WARNING_MSG_00150 MPDS_WARNING_MSG_00160 = _geosclassic.MPDS_WARNING_MSG_00160 MPDS_WARNING_MSG_00210 = _geosclassic.MPDS_WARNING_MSG_00210 MPDS_WARNING_MSG_00212 = _geosclassic.MPDS_WARNING_MSG_00212 MPDS_WARNING_MSG_00214 = _geosclassic.MPDS_WARNING_MSG_00214 MPDS_WARNING_MSG_02001 = _geosclassic.MPDS_WARNING_MSG_02001 MPDS_WARNING_MSG_02002 = _geosclassic.MPDS_WARNING_MSG_02002 MPDS_WARNING_MSG_02005 = _geosclassic.MPDS_WARNING_MSG_02005 MPDS_WARNING_MSG_02012 = _geosclassic.MPDS_WARNING_MSG_02012 MPDS_WARNING_MSG_02015 = _geosclassic.MPDS_WARNING_MSG_02015 MPDS_WARNING_MSG_02016 = _geosclassic.MPDS_WARNING_MSG_02016 MPDS_WARNING_MSG_02020 = _geosclassic.MPDS_WARNING_MSG_02020 MPDS_WARNING_MSG_05044 = _geosclassic.MPDS_WARNING_MSG_05044 MPDS_WARNING_MSG_05045 = _geosclassic.MPDS_WARNING_MSG_05045 MPDS_WARNING_MSG_05125 = _geosclassic.MPDS_WARNING_MSG_05125 MPDS_WARNING_MSG_05127 = _geosclassic.MPDS_WARNING_MSG_05127 MPDS_WARNING_MSG_05126 = _geosclassic.MPDS_WARNING_MSG_05126 MPDS_WARNING_MSG_05100 = _geosclassic.MPDS_WARNING_MSG_05100 MPDS_WARNING_MSG_05101 = _geosclassic.MPDS_WARNING_MSG_05101 MPDS_WARNING_MSG_05102 = _geosclassic.MPDS_WARNING_MSG_05102 MPDS_WARNING_MSG_05103 = _geosclassic.MPDS_WARNING_MSG_05103 MPDS_WARNING_MSG_05104 = _geosclassic.MPDS_WARNING_MSG_05104 MPDS_WARNING_MSG_05105 = _geosclassic.MPDS_WARNING_MSG_05105 MPDS_WARNING_MSG_05120 = _geosclassic.MPDS_WARNING_MSG_05120 MPDS_WARNING_MSG_05130 = _geosclassic.MPDS_WARNING_MSG_05130 MPDS_WARNING_MSG_05131 = _geosclassic.MPDS_WARNING_MSG_05131 MPDS_WARNING_MSG_05200 = _geosclassic.MPDS_WARNING_MSG_05200 MPDS_WARNING_MSG_08001 = _geosclassic.MPDS_WARNING_MSG_08001 MPDS_WARNING_MSG_99998 = _geosclassic.MPDS_WARNING_MSG_99998 MPDS_MAX_NWARNING = _geosclassic.MPDS_MAX_NWARNING MPDS_SHOW_PROGRESS_MONITOR = _geosclassic.MPDS_SHOW_PROGRESS_MONITOR MPDS_MAX_PROGRESS_NAME_LENGTH = _geosclassic.MPDS_MAX_PROGRESS_NAME_LENGTH class mpds_progressMonitor(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, mpds_progressMonitor, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, mpds_progressMonitor, name) __repr__ = _swig_repr __swig_setmethods__["progressName"] = _geosclassic.mpds_progressMonitor_progressName_set __swig_getmethods__["progressName"] = _geosclassic.mpds_progressMonitor_progressName_get if _newclass: progressName = _swig_property(_geosclassic.mpds_progressMonitor_progressName_get, _geosclassic.mpds_progressMonitor_progressName_set) __swig_setmethods__["warningNumber"] = _geosclassic.mpds_progressMonitor_warningNumber_set __swig_getmethods__["warningNumber"] = _geosclassic.mpds_progressMonitor_warningNumber_get if _newclass: warningNumber = _swig_property(_geosclassic.mpds_progressMonitor_warningNumber_get, _geosclassic.mpds_progressMonitor_warningNumber_set) __swig_setmethods__["nrealization"] = _geosclassic.mpds_progressMonitor_nrealization_set __swig_getmethods__["nrealization"] = _geosclassic.mpds_progressMonitor_nrealization_get if _newclass: nrealization = _swig_property(_geosclassic.mpds_progressMonitor_nrealization_get, _geosclassic.mpds_progressMonitor_nrealization_set) __swig_setmethods__["currentRealization"]
outputmode(mode=None): raise NotImplementedError def colormode(mode=None, range=1.0): raise NotImplementedError #--- COLOR SPACE ------------------------------------------------------------------------------------- # Transformations between RGB, HSB, CIE XYZ and CIE LAB color spaces. # http://www.easyrgb.com/math.php def rgb_to_hsb(r, g, b): """ Converts the given R,G,B values to H,S,B (between 0.0-1.0). """ h, s, v = 0, 0, max(r, g, b) d = v - min(r, g, b) if v != 0: s = d / float(v) if s != 0: if r == v: h = 0 + (g-b) / d elif g == v: h = 2 + (b-r) / d else : h = 4 + (r-g) / d h = h / 6.0 % 1 return h, s, v def hsb_to_rgb(h, s, v): """ Converts the given H,S,B color values to R,G,B (between 0.0-1.0). """ if s == 0: return v, v, v h = h % 1 * 6.0 i = floor(h) f = h - i x = v * (1-s) y = v * (1-s * f) z = v * (1-s * (1-f)) if i > 4: return v, x, y return [(v,z,x), (y,v,x), (x,v,z), (x,y,v), (z,x,v)][int(i)] def rgb_to_xyz(r, g, b): """ Converts the given R,G,B values to CIE X,Y,Z (between 0.0-1.0). """ r, g, b = [ch > 0.04045 and ((ch+0.055) / 1.055) ** 2.4 or ch / 12.92 for ch in r, g, b] r, g, b = [ch * 100.0 for ch in r, g, b] r, g, b = ( # Observer = 2, Illuminant = D65 r * 0.4124 + g * 0.3576 + b * 0.1805, r * 0.2126 + g * 0.7152 + b * 0.0722, r * 0.0193 + g * 0.1192 + b * 0.9505) return r/95.047, g/100.0, b/108.883 def xyz_to_rgb(x, y, z): """ Converts the given CIE X,Y,Z color values to R,G,B (between 0.0-1.0). """ x, y, z = x*95.047, y*100.0, z*108.883 x, y, z = [ch / 100.0 for ch in x, y, z] r = x * 3.2406 + y * -1.5372 + z * -0.4986 g = x * -0.9689 + y * 1.8758 + z * 0.0415 b = x * -0.0557 + y * -0.2040 + z * 1.0570 r, g, b = [ch > 0.0031308 and 1.055 * ch**(1/2.4) - 0.055 or ch * 12.92 for ch in r, g, b] return r, g, b def rgb_to_lab(r, g, b): """ Converts the given R,G,B values to CIE L,A,B (between 0.0-1.0). """ x, y, z = rgb_to_xyz(r, g, b) x, y, z = [ch > 0.008856 and ch**(1/3.0) or (ch*7.787) + (16/116.0) for ch in x, y, z] l, a, b = y*116-16, 500*(x-y), 200*(y-z) l, a, b = l/100.0, (a+86)/(86+98), (b+108)/(108+94) return l, a, b def lab_to_rgb(l, a, b): """ Converts the given CIE L,A,B color values to R,G,B (between 0.0-1.0). """ l, a, b = l*100, a*(86+98)-86, b*(108+94)-108 y = (l+16)/116.0 x = y + a/500.0 z = y - b/200.0 x, y, z = [ch**3 > 0.008856 and ch**3 or (ch-16/116.0)/7.787 for ch in x, y, z] return xyz_to_rgb(x, y, z) def luminance(r, g, b): """ Returns an indication (0.0-1.0) of how bright the color appears. """ return (r*0.2125 + g*0.7154 + b+0.0721) * 0.5 def darker(clr, step=0.2): """ Returns a copy of the color with a darker brightness. """ h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b) r, g, b = hsb_to_rgb(h, s, max(0, b-step)) return Color(r, g, b, len(clr)==4 and clr[3] or 1) def lighter(clr, step=0.2): """ Returns a copy of the color with a lighter brightness. """ h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b) r, g, b = hsb_to_rgb(h, s, min(1, b+step)) return Color(r, g, b, len(clr)==4 and clr[3] or 1) darken, lighten = darker, lighter #--- COLOR ROTATION ---------------------------------------------------------------------------------- # Approximation of the RYB color wheel. # In HSB, colors hues range from 0 to 360, # but on the color wheel these values are not evenly distributed. # The second tuple value contains the actual value on the wheel (angle). _colorwheel = [ ( 0, 0), ( 15, 8), ( 30, 17), ( 45, 26), ( 60, 34), ( 75, 41), ( 90, 48), (105, 54), (120, 60), (135, 81), (150, 103), (165, 123), (180, 138), (195, 155), (210, 171), (225, 187), (240, 204), (255, 219), (270, 234), (285, 251), (300, 267), (315, 282), (330, 298), (345, 329), (360, 360) ] def rotate_ryb(h, s, b, angle=180): """ Rotates the given H,S,B color (0.0-1.0) on the RYB color wheel. The RYB colorwheel is not mathematically precise, but focuses on aesthetically pleasing complementary colors. """ h = h*360 % 360 # Find the location (angle) of the hue on the RYB color wheel. for i in range(len(_colorwheel)-1): (x0, y0), (x1, y1) = _colorwheel[i], _colorwheel[i+1] if y0 <= h <= y1: a = geometry.lerp(x0, x1, t=(h-y0)/(y1-y0)) break # Rotate the angle and retrieve the hue. a = (a+angle) % 360 for i in range(len(_colorwheel)-1): (x0, y0), (x1, y1) = _colorwheel[i], _colorwheel[i+1] if x0 <= a <= x1: h = geometry.lerp(y0, y1, t=(a-x0)/(x1-x0)) break return h/360.0, s, b def complement(clr): """ Returns the color opposite on the color wheel. The complementary color contrasts with the given color. """ if not isinstance(clr, Color): clr = Color(clr) return clr.rotate(180) def analog(clr, angle=20, d=0.1): """ Returns a random adjacent color on the color wheel. Analogous color schemes can often be found in nature. """ h, s, b = rgb_to_hsb(*clr[:3]) h, s, b = rotate_ryb(h, s, b, angle=random(-angle,angle)) s *= 1 - random(-d,d) b *= 1 - random(-d,d) return Color(h, s, b, len(clr)==4 and clr[3] or 1, colorspace=HSB) #--- COLOR MIXIN ------------------------------------------------------------------------------------- # Drawing commands like rect() have optional parameters fill and stroke to set the color directly. def color_mixin(**kwargs): fill = kwargs.get("fill", _fill) stroke = kwargs.get("stroke", _stroke) strokewidth = kwargs.get("strokewidth", _strokewidth) strokestyle = kwargs.get("strokestyle", _strokestyle) return (fill, stroke, strokewidth, strokestyle) #--- COLOR PLANE ------------------------------------------------------------------------------------- # Not part of the standard API but too convenient to leave out. def colorplane(x, y, width, height, *a): """ Draws a rectangle that emits a different fill color from each corner. An optional number of colors can be given: - four colors define top left, top right, bottom right and bottom left, - three colors define top left, top right and bottom, - two colors define top and bottom, - no colors assumes black top and white bottom gradient. """ if len(a) == 2: # Top and bottom colors. clr1, clr2, clr3, clr4 = a[0], a[0], a[1], a[1] elif len(a) == 4: # Top left, top right, bottom right, bottom left. clr1, clr2, clr3, clr4 = a[0], a[1], a[2], a[3] elif len(a) == 3: # Top left, top right, bottom. clr1, clr2, clr3, clr4 = a[0], a[1], a[2], a[2] elif len(a) == 0: # Black top, white bottom. clr1 = clr2 = (0,0,0,1) clr3 = clr4 = (1,1,1,1) glPushMatrix() glTranslatef(x, y, 0) glScalef(width, height, 1) glBegin(GL_QUADS) glColor4f(clr1[0], clr1[1], clr1[2], clr1[3] * _alpha); glVertex2f(-0.0, 1.0) glColor4f(clr2[0], clr2[1], clr2[2], clr2[3] * _alpha); glVertex2f( 1.0, 1.0) glColor4f(clr3[0], clr3[1], clr3[2], clr3[3] * _alpha); glVertex2f( 1.0, -0.0) glColor4f(clr4[0], clr4[1], clr4[2], clr4[3] * _alpha); glVertex2f(-0.0, -0.0) glEnd() glPopMatrix() #===================================================================================================== #--- TRANSFORMATIONS --------------------------------------------------------------------------------- # Unlike NodeBox, all transformations are CORNER-mode and originate from the bottom-left corner. # Example: using Transform to get a transformed path. # t = Transform() # t.rotate(45) # p = BezierPath() # p.rect(10,10,100,70) # p = t.transform_path(p) # p.contains(x,y) # now we can check if the mouse is in the transformed shape. Transform = geometry.AffineTransform def push(): """ Pushes the transformation state. Subsequent transformations (translate, rotate, scale) remain in effect until pop() is called. """ glPushMatrix() def pop(): """ Pops the transformation state. This reverts the transformation to before the last push(). """ glPopMatrix() def translate(x, y, z=0): """ By default, the origin of the layer or canvas is at the bottom left. This origin point will be moved by (x,y) pixels. """ glTranslatef(round(x), round(y), round(z)) def rotate(degrees, axis=(0,0,1)): """ Rotates the transformation state, i.e. all subsequent drawing primitives are rotated. Rotations work
import unittest import numpy as np import os import shutil import json from pathlib import Path from unittest.mock import patch, MagicMock from appdirs import user_cache_dir import geopandas as gpd import warnings import shutil from ausdex.seifa_vic.data_wrangling import preprocess_victorian_datasets from ausdex.seifa_vic.seifa_vic import Metric import pandas as pd from typer.testing import CliRunner from ausdex import main from ausdex.seifa_vic.data_io import ( get_data_links, load_aurin_config, load_aurin_data, download_from_aurin, get_aurin_wfs, load_shapefile_data, load_victorian_suburbs_metadata, ) from ausdex.files import get_cached_path import json import datetime MOCKED_FILES = [ "seifa_1986_aurin.geojson", "seifa_1991_aurin.geojson", "state_suburb_codes_2011..csv.zip", "seifa_1996_aurin.geojson", "seifa_2001_aurin.geojson", "seifa_2006.geojson", "victoria_councils", "victoria_suburbs", "victoria_councils.geojson", "victoria_suburbs.geojson", "seifa_2006_cd.xls", "seifa_suburb_2011.xls", "seifa_suburb_2016.xls", "mock_completed.csv", "aurin_schemas.json", "seifa_2011_sa1.xls", "seifa_2016_sa1.xls", "sa1_gis_2011.geojson", "sa1_gis_2016.geojson", ] def fake_data_cached_path(filename): return ( Path(__file__).parent.resolve() / "testdata" / "ausdex" / "mock_gis" / filename ) def mock_user_get_cached_path(filename): print(f"using cached test data for {filename}") if filename in MOCKED_FILES: if filename == "state_suburb_codes_2011..csv.zip": fcp = fake_data_cached_path("SSC_2011_AUST.csv") print(f"loading test file from {fcp}") return fcp else: fcp = fake_data_cached_path(filename) print(f"loading test file from {fcp}") return fcp else: cache_dir = Path(user_cache_dir("ausdex")) cache_dir.mkdir(exist_ok=True, parents=True) return cache_dir / filename def mock_load_shapefile_data(filename): if filename == "seifa_2006_cd_shapefile": return gpd.read_file(mock_user_get_cached_path("seifa_2006.geojson")) elif filename == "sa1_gis_2011": return gpd.read_file(mock_user_get_cached_path("sa1_gis_2011.geojson")) elif filename == "sa1_gis_2016": return gpd.read_file(mock_user_get_cached_path("sa1_gis_2016.geojson")) def mock_preproces_vic_datasets(force_rebuild=False, save_file=False): print("loading mocked completed dataset") return pd.read_csv(mock_user_get_cached_path("mock_completed.csv")) class TestSeifaVicSetup(unittest.TestCase): @patch( "ausdex.seifa_vic.data_io.get_cached_path", lambda filename: mock_user_get_cached_path(filename), ) @patch( "ausdex.seifa_vic.data_wrangling.load_shapefile_data", lambda filename: mock_load_shapefile_data(filename), ) def test_preprocess_victorian_datasets(self): df = preprocess_victorian_datasets(force_rebuild=True, save_file=False) cols = [ "ieo_score", "ier_score", "irsad_score", "rirsa_score", "uirsa_score", "irsd_score", "year", "Site_suburb", ] for col in cols: assert col in df.columns, f"{col} not in dataset" self.assertEqual(df.year.max(), 2016) self.assertEqual(df.year.min(), 1986) self.assertIn("ASCOT - BALLARAT", df.Site_suburb.unique()) self.assertNotIn("ASCOT - BALLARAT CITY", df.Site_suburb.unique()) def test_group_repeat_names_vic(self): from ausdex.seifa_vic.data_wrangling import group_repeat_names_vic ids = [ "VIC2961", "VIC2967", "VIC2976", "VIC2984", "VIC2990", "VIC2969", "VIC2963", ] fixed_suburbs = [ "BELLFIELD - GRAMPIANS", "BELLFIELD - BANYULE", "<NAME> - SWAN HILL", "HILLSIDE - MELTON", "RE<NAME> - MITCHELL", "SPRINGFIELD - <NAME>", "<NAME> - HEPBURN", ] for id, suburb in zip(ids, fixed_suburbs): x = {"loc_pid": id, "suburb_name_combined": "test_failed"} value = group_repeat_names_vic(x) self.assertAlmostEqual(value, suburb) x = {"loc_pid": "wrong", "suburb_name_combined": "test_failed"} value = group_repeat_names_vic(x) self.assertEqual(value, "test_failed") @patch( "ausdex.seifa_vic.seifa_vic.preprocess_victorian_datasets", lambda force_rebuild: mock_preproces_vic_datasets(False) if force_rebuild == True else None, ) def test_assemble_data_cli(self): runner = CliRunner() result = runner.invoke(main.app, ["seifa-vic-assemble"]) assert result.exit_code == 0 assert "Data loaded" in result.stdout @patch( "ausdex.seifa_vic.seifa_vic.preprocess_victorian_datasets", lambda force_rebuild: mock_preproces_vic_datasets(False), ) class TestSeifaInterpolation(unittest.TestCase): def setUp(self) -> None: from ausdex.seifa_vic.seifa_vic import interpolate_vic_suburb_seifa self.interpolate = interpolate_vic_suburb_seifa return super().setUp() def test_interpolation_null(self): value = self.interpolate( [1980, 1987], "ABBOTSFORD", "ier_score", ) # self.assertTrue(value[0] == np.nan) # print(value) self.assertTrue(np.isnan(value[0])) self.assertAlmostEqual(value[1], 955.5048835511469, places=3) def test_suburb_guess_misspelt(self): value = self.interpolate( [1980, 1987], "ABBOTSFORDXX", "ier_score", guess_misspelt=True, ) self.assertTrue(np.isnan(value[0])) self.assertAlmostEqual(value[1], 955.5048835511469, places=3) def test_interpolation_negative(self): value = self.interpolate( 2200, "ASCOT - BALLARAT", Metric["ier_score"], fill_value="extrapolate" ) # self.assertTrue(value[0] == np.nan) # print(value) self.assertTrue(value == 0) def test_interpolation_onevalue(self): from ausdex.seifa_vic import SeifaVic seifa_vic = SeifaVic(False) seifa_vic.df = pd.DataFrame( { "Site_suburb": ["TEST_SUB1", "test_sub2"], "ier_score": [36.4, 38.5], "year": [2000, 2011], } ) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") out = seifa_vic.get_seifa_interpolation( 2011, "TEST_SUB1", "ier_score", fill_value="extrapolate" ) self.assertEqual(36.4, out) assert len(w) == 1 assert ( "Suburb 'TEST_SUB1' only has one value for ier_score, assuming flat line" in str(w[-1].message) ) def test_interpolation_novalue(self): with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") value = self.interpolate( 2200, "Fake", "ier_score", fill_value="extrapolate" ) # self.assertTrue(value[0] == np.nan) # print(value) self.assertTrue(np.isnan(value)) assert len(w) == 1 assert "No suburb named 'FAKE'. Returning NaN." in str(w[-1].message) def test_interpolation_extrapolate(self): value = self.interpolate( pd.Series([1980, 2000]), "ABBOTSFORD", "ier_score", fill_value="extrapolate", ) self.assertAlmostEqual(value[0], 868.1914314671592, places=3) self.assertAlmostEqual(value[1], 1055.278795, places=3) def test_interpolate_boundary_value(self): value = self.interpolate( np.array([1980, 1986]), "ABBOTSFORD", "ieo_score", fill_value="boundary_value", ) self.assertAlmostEqual(value[0], value[1], places=3) def test_interpolate_multiple_suburbs(self): value = self.interpolate( ["1-7-1980", "31-10-1986"], pd.Series(["kew", "ABBOTSFORD"]), "ieo_score", fill_value="boundary_value", ) self.assertAlmostEqual(value[0], 1179.648871, places=3) self.assertAlmostEqual(994.3434, value[1], places=3) def test_interpolate_multiple_suburbs_array(self): value = self.interpolate( pd.Series(["1-7-1980", "31-10-1986"]), pd.Series(["kew", "ABBOTSFORD"]).values, "ieo_score", fill_value="boundary_value", ) self.assertAlmostEqual(value[0], 1179.648871, places=3) self.assertAlmostEqual(994.3434, value[1], places=3) def test_interpolate_list_datetimes_datetimes(self): value = self.interpolate( pd.Series([datetime.datetime(1980, 7, 1), datetime.datetime(1986, 10, 31)]), pd.Series(["kew", "ABBOTSFORD"]).values, "ieo_score", fill_value="boundary_value", ) self.assertAlmostEqual(value[0], 1179.648871, places=3) self.assertAlmostEqual(994.3434, value[1], places=3) def test_interpolate_single_datetime(self): value = self.interpolate( datetime.datetime(1986, 10, 31), "kew", "ieo_score", fill_value="boundary_value", ) self.assertAlmostEqual(value, 1179.9308, places=3) # self.assertAlmostEqual(1013.1802726224083, value[1], places=3) def test_interpolate_lga(self): value = self.interpolate( datetime.datetime(1996, 10, 31), "ASCOT", "ieo_score", lga="Greater Bendigo", ) self.assertAlmostEqual(value, 973.18854015, places=3) # self.assertAlmostEqual(1013.1802726224083, value[1], places=3 def test_interpolate_lga_list(self): value = self.interpolate( [datetime.datetime(1996, 10, 31), datetime.datetime(1986, 10, 31)], ["ASCOT", "kew"], "ieo_score", lga=["Greater Bendigo", "Boroondara"], ) self.assertAlmostEqual(value[0], 973.18854015, places=3) self.assertAlmostEqual(value[1], 1179.9308, places=3) def test_interpolate_lga_series(self): value = self.interpolate( pd.Series( [datetime.datetime(1996, 10, 31), datetime.datetime(1986, 10, 31)] ), pd.Series(["ASCOT", "kew"]), "ieo_score", lga=pd.Series(["Greater Bendigo", "Boroondara"]), ) self.assertAlmostEqual(value[0], 973.18854015, places=3) self.assertAlmostEqual(value[1], 1179.9308, places=3) def test_seifa_vic_cli(self): runner = CliRunner() result = runner.invoke( main.app, ["seifa-vic", "1991", "abbotsford", "ier_score"] ) assert result.exit_code == 0 assert "1005.03" in result.stdout def test_seifa_vic_cli_lga(self): runner = CliRunner() result = runner.invoke( main.app, [ "seifa-vic", "1996-10-31", "ascot", "ieo_score", "--lga", "Greater Bendigo", ], ) assert result.exit_code == 0 assert "973.19" in result.stdout def test_get_repeated_names(self): from ausdex.seifa_vic.seifa_vic import get_repeated_names names = get_repeated_names() assert "ASCOT - BALLARAT" in names def patch_get_cached_path_schema(file) -> Path: new_filename = "schema_" + file local_path = Path(__file__).parent / "testdata" / "tmp" / new_filename if local_path.exists() == True: local_path.unlink() return local_path def patch_download_from_aurin(wfs_aurin, dataset, links, local_path): print("patching aurin download for schema") schema = wfs_aurin.get_schema(links[dataset]) Path(local_path).parent.mkdir(exist_ok=True) with open(local_path, "w") as file: json.dump(schema, file) def patch_open_geopandas(file): print("patching open geopandas") with open(file, "r") as f: out = json.load(f) return out def load_aurin_schema(): fname = mock_user_get_cached_path("aurin_schemas.json") with open(fname, "r") as f: out = json.load(f) return out def patch_unzip(local_path, new_path_name): new_path_name.mkdir(exist_ok=True, parents=True) (new_path_name / "shapefile.shp").touch() (new_path_name / "shapefile.shx").touch() def patch_open_geopandas_2(filename): return filename @patch( "ausdex.seifa_vic.data_io.get_aurin_creds_path", lambda: Path(__file__).parent / "aurin_creds_dummy.json", ) class TestDataIO(unittest.TestCase): def setUp(self) -> None: aurin_creds = Path(__file__).parent / "aurin_creds_dummy.json" self.aurin_dummy_creds = aurin_creds print(aurin_creds) if aurin_creds.exists() == True: aurin_creds.unlink() aurin_creds.parent.mkdir(exist_ok=True, parents=True) return super().setUp() def tearDown(self) -> None: if self.aurin_dummy_creds.exists() == True: os.remove(self.aurin_dummy_creds) if (Path(__file__).parent / "testdata" / "tmp").exists() == True: shutil.rmtree((Path(__file__).parent / "testdata" / "tmp")) return super().tearDown() @patch("ausdex.seifa_vic.data_io._get_input", lambda msg: "test_username") @patch("ausdex.seifa_vic.data_io._get_getpass", lambda msg: "<PASSWORD>") @patch("ausdex.seifa_vic.data_io.get_config_ini", lambda: Path("does not exist")) def test_make_aurin_config_as_json(self): from ausdex.seifa_vic.data_io import get_aurin_creds_path load_aurin_config() with open(get_aurin_creds_path(), "r") as file: creds = json.load(file) self.assertEqual(creds["username"], "test_username") self.assertEqual(creds["password"], "<PASSWORD>") @patch( "ausdex.seifa_vic.data_io.download_from_aurin", lambda wfs_aurin, dataset, links, local_path: patch_download_from_aurin( wfs_aurin, dataset, links, local_path ), ) @patch( "ausdex.seifa_vic.data_io.open_geopandas", lambda file: patch_open_geopandas(file), ) @patch( "ausdex.seifa_vic.data_io.get_cached_path", lambda filename: patch_get_cached_path_schema(filename), ) def test_aurin_data(self): datasets = [ "seifa_2001_aurin", "seifa_1996_aurin", "seifa_1991_aurin", "seifa_1986_aurin", ] saved_schema = load_aurin_schema() data = load_aurin_data(datasets) for d, dset in zip(data, datasets): self.assertDictEqual(saved_schema[dset], d) @patch( "ausdex.seifa_vic.data_io.get_cached_path", lambda filename: mock_user_get_cached_path(filename), ) def test_aurin_already_downloaded(self): gdf = load_aurin_data("seifa_2001_aurin") self.assertIn("geometry", gdf[0].columns) def test_aurin_download(self): wfs = get_aurin_wfs() links = get_data_links() test_aurin_dl = get_cached_path("test_aurin_dl.geojson") download_from_aurin( wfs, "seifa_2001_aurin", links, test_aurin_dl, bbox=(125, -42.01, 125.01, -42.0), ) def test_load_victorian_suburbs_metadata(self): df = load_victorian_suburbs_metadata() self.assertIn("locality_pid", df.columns) self.assertIn("locality_name", df.columns) @patch( "ausdex.seifa_vic.data_io.open_geopandas", lambda file: patch_open_geopandas_2(file), ) @patch( "ausdex.seifa_vic.data_io.unzip", lambda local_path, new_path_name: patch_unzip(local_path, new_path_name), ) @patch("ausdex.seifa_vic.data_io.cached_download", lambda url, local_path: None) @patch( "ausdex.seifa_vic.data_io.get_data_links", lambda: {"test_dataset": "test_dataset_folder"}, ) def test_load_shapefile_data(self): out_file = load_shapefile_data("test_dataset") print(out_file) self.assertIn("shp", out_file.name) self.assertIn("unzipped", out_file.parent.name) shutil.rmtree(out_file.parent) @patch( "ausdex.seifa_vic.data_io.get_cached_path", lambda filename: mock_user_get_cached_path(filename), ) @patch( "ausdex.seifa_vic.data_wrangling.load_shapefile_data", lambda filename: mock_load_shapefile_data(filename), ) @patch( "ausdex.seifa_vic.seifa_vic.preprocess_victorian_datasets", lambda force_rebuild: mock_preproces_vic_datasets(False), ) class TestSeifaGisViz(unittest.TestCase): def setUp(self) -> None: from ausdex import seifa_vic self.seifa_vic = seifa_vic self.tmp = Path("tmp") self.tmp.mkdir(exist_ok=True) return super().setUp() def tearDown(self) -> None: shutil.rmtree(self.tmp) return super().tearDown() def test_seifa_gis(self): from ausdex.seifa_vic import get_seifa_gis gdf = get_seifa_gis("05-11-2015", "ier_score", fill_value="extrapolate") print(gdf.shape) self.assertEqual(type(gdf), gpd.GeoDataFrame) self.assertIn("Site_suburb", gdf.columns) self.assertIn("ier_score", gdf.columns) def test_seifa_map(self): from ausdex.seifa_vic import get_seifa_map fig = get_seifa_map( "05-11-2015", Metric["ier_score"], fill_value="extrapolate", simplify=0.001 ) # fig.write_json('tests/testdata/ausdex/mock_gis/test_map.json') fig.write_json(self.tmp / "test_map.json") import filecmp self.assertTrue( filecmp.cmp( "tests/testdata/ausdex/mock_gis/test_map.json", self.tmp / "test_map.json", ) ) def test_seifa_plot(self): from ausdex.seifa_vic import create_timeseries_chart fig = create_timeseries_chart( ["abbotsford", "ASCOT - BALLARAT"], Metric["irsd_score"] ) # fig.write_json('tests/testdata/ausdex/mock_gis/test_fig.json') fig.write_json(self.tmp / "test_fig.json") import filecmp self.assertTrue( filecmp.cmp( "tests/testdata/ausdex/mock_gis/test_fig.json", self.tmp / "test_fig.json", ) ) def test_seifa_vic_gis_cli(self): runner = CliRunner() result = runner.invoke( main.app, [ "seifa-vic-gis", "05-11-2015", "ier_score", str(self.tmp / "tmp_gis.geojson"), ], ) assert result.exit_code == 0 gdf = gpd.read_file(self.tmp / "tmp_gis.geojson") self.assertEqual(type(gdf), gpd.GeoDataFrame) self.assertIn("Site_suburb", gdf.columns) self.assertIn("ier_score", gdf.columns) def test_seifa_vic_map_cli(self): runner = CliRunner() result = runner.invoke( main.app, [ "seifa-vic-map", "05-11-2015", "ier_score", str(self.tmp / "test_map.html"), "--fill-value", "extrapolate", "--min-y", "-37.5", ], ) assert result.exit_code == 0 assert (self.tmp / "test_map.html").exists() def test_seifa_vic_plot_cli(self): runner = CliRunner() result = runner.invoke( main.app, [ "seifa-vic-plot", "ier_score", str(self.tmp / "test_plot.html"), "abbotsford", "ASCOT - BALLARAT", ], ) assert result.exit_code == 0 assert (self.tmp / "test_plot.html").exists() def test_gis_clipping(self): from ausdex.gis_utils import clip_gdf from ausdex.seifa_vic import get_seifa_gis gdf = get_seifa_gis("05-11-2015", "ier_score", fill_value="extrapolate") gdf_clip_one = clip_gdf(gdf, min_y=-37.5) self.assertEqual(gdf_clip_one.shape[0], 1) self.assertIn("ASCOT", gdf_clip_one.Site_suburb[0]) from shapely.geometry import Polygon clip_gs = gpd.GeoSeries( Polygon( [ [143.805,
in range(len(MTs_sample[:,0])): # Get theta and phi rotations, assuming that have been random orientation from Lune space varied diagonallised MT: # (Note: based on rotation of theta and phi about y and z axes after diagonal MT from Lune params created) MT_curr = MTs_sample[ii,:] MTp_curr = MTp_sample[ii] full_MT_curr = get_full_MT_array(MT_curr) w,v = eigh(full_MT_curr) # Find eigenvalues and associated eigenvectors for the symetric (Hermitian) MT matrix (for eigenvalue w[i], eigenvector is v[:,i]) lambda_1 = w[0] lambda_2 = w[1] lambda_3 = w[2] mt_22 = full_MT_curr[1,1] mt_33 = full_MT_curr[2,2] theta = np.arccos((2*mt_33 - (lambda_1 + lambda_3))/(2.*(lambda_3 - lambda_1))) phi = np.arccos((2*mt_22 - (lambda_1 + lambda_2))/(2.*(lambda_2 - lambda_1))) val, theta_bin_idx = find_nearest(theta_bin_vals,theta) val, phi_bin_idx = find_nearest(phi_bin_vals,phi) # And update bins: theta_phi_bins[theta_bin_idx, phi_bin_idx] += MTp_curr theta_phi_bins_num_samples[theta_bin_idx, phi_bin_idx] += 1. if MTp_curr>theta_phi_bins_max_prob_vals[theta_bin_idx, phi_bin_idx]: theta_phi_bins_max_prob_vals[theta_bin_idx, phi_bin_idx] = MTp_curr # Mask zero probabilities: theta_phi_bins[theta_phi_bins==0] = np.nan theta_phi_bins_max_prob_vals[theta_phi_bins==0] = np.nan # And plot results: # Set up figure: fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) # Plot data: theta_grid, phi_grid = np.meshgrid(theta_bin_vals, phi_bin_vals) ax.pcolormesh(theta_grid, phi_grid, np.transpose(theta_phi_bins_max_prob_vals), cmap="inferno") ax.set_xlabel('$\theta$ (rad)') ax.set_ylabel('$\phi$ (rad)') # Plot max value: if len(six_MT_max_prob)>0: full_MT_max_prob = get_full_MT_array(six_MT_max_prob) w,v = eigh(full_MT_max_prob) # Find eigenvalues and associated eigenvectors for the symetric (Hermitian) MT matrix (for eigenvalue w[i], eigenvector is v[:,i]) lambda_1 = w[0] lambda_2 = w[1] lambda_3 = w[2] mt_22 = full_MT_max_prob[1,1] mt_33 = full_MT_max_prob[2,2] theta = np.arccos((2*mt_33 - (lambda_1 + lambda_3))/(2.*(lambda_3 - lambda_1))) phi = np.arccos((2*mt_22 - (lambda_1 + lambda_2))/(2.*(lambda_2 - lambda_1))) val, theta_bin_idx = find_nearest(theta_bin_vals,theta) val, phi_bin_idx = find_nearest(phi_bin_vals,phi) # And convert to absolute value to plot within bin space: theta = np.abs(theta) phi = np.abs(phi) ax.scatter(theta,phi, c="gold", alpha=0.8,s=250, marker="*") # And show/save figure: if len(figure_filename)>0: plt.savefig(figure_filename, dpi=600) else: plt.show() def run(inversion_type, event_uid, datadir, plot_outdir='plots', radiation_MT_phase="P", plot_Lune_switch=True, plot_uncertainty_switch=False, plot_wfs_separately_switch=False, plot_multi_medium_greens_func_inv_switch=False, multi_medium_greens_func_inv_separate_phase_amp_ratios=False, plot_absolute_probability_switch=True, plot_wfs_on_focal_mech_switch=True, lower_upper_hemi_switch="upper", plot_max_prob_on_Lune_switch=False, plot_das_wfs_switch=False, fs_das=1000., DC_switch_slip_vector=False, num_MT_solutions_to_plot=1): """Function to run main script. ------------------ Inputs ------------------ Required arguments: inversion_type - Type of inversion to plot for. Obviously has to match the inversion undertaken. (type: str) event_uid - The UID (unique id) of the event inverted for. It is the numbers in the inversion .pkl out filename. (type: str) datadir - Path to where the inversion outputs are saved (type: str) Optional arguments: plot_outdir - Path to where the inversion plot outputs are saved (default: plots) (type: str) radiation_MT_phase - Radiation phase to plot (= "P" or "S") (Defalt = "P") (type: str) plot_uncertainty_switch - If True, plots uncertainty in direction/orientation of focal mechanism solution (default is False) (type bool) plot_Lune_switch - If True, plots Lune (default is True) (type bool) plot_max_prob_on_Lune_switch - If True, plots maximum probability solution for each point on Lune, rather than binned probability (default is False) (type bool) plot_wfs_separately_switch - If true, plots waveforms separately (default is False) (type bool) plot_multi_medium_greens_func_inv_switch - Set as True if plotting multi medium greens function inversion results (default is False) (type bool) multi_medium_greens_func_inv_separate_phase_amp_ratios - If inverted for separate phase amplitude ratios for multi medium greens functions, set this as True (default is False) (type bool) plot_wfs_on_focal_mech_switch - If True, plots waveforms on focal mechanism plot (default is True) (type bool) lower_upper_hemi_switch - Controls plotting of lower or upper hemisphere plot. Can be lower or upper. Default is upper. (str) plot_das_wfs_switch - Switch to plot DAS data, if DAS data used in inversion (default is False) (type bool) fs_das - Sampling rate of the DAS data (default is 1000.0) (type float) DC_switch_slip_vector - If True, will switch slip vector to the other nodal plane. Default is False. (type bool) num_MT_solutions_to_plot - The number of fault plane solutions to plot on the focal sphere. Currently only implemented for DC fault plane plotting. (type int) ------------------ Outputs ------------------ Various outputs as .png files, saved to the directory specified (e.g. "plots/") """ # Plot for inversion: print("Plotting data for inversion") # Get inversion filenames: MT_data_filename = os.path.join(datadir, event_uid+"_FW_"+inversion_type+".pkl") MT_waveforms_data_filename = os.path.join(datadir, event_uid+"_FW_"+inversion_type+".wfs") try: os.mkdir(plot_outdir) except FileExistsError: print("") print("Processing data for:", MT_data_filename) # Import MT data and associated waveforms: uid, MTp, MTp_absolute, MTs, stations = load_MT_dict_from_file(MT_data_filename) wfs_dict = load_MT_waveforms_dict_from_file(MT_waveforms_data_filename) # And use absolute probabilities, if specified (and if data is available): if plot_absolute_probability_switch: if len(MTp_absolute)>0: MTp_for_Lune = MTp.copy() MTp = MTp_absolute else: MTp_for_Lune = MTp.copy() # Get most likely solution and plot: index_MT_max_prob = np.argmax(MTp) # Index of most likely MT solution MTp_max_prob_value = np.max(MTp) # Similarity value for most likely MT solution MT_max_prob = MTs[:,index_MT_max_prob] # If solution is for multiple medium greens function solution, separate MT data from relative amplitude ratio: if plot_multi_medium_greens_func_inv_switch: MT_max_prob_tmp = MT_max_prob[0:6] if multi_medium_greens_func_inv_separate_phase_amp_ratios: amp_ratio_direct_vs_indirect_P = MT_max_prob[-3] # Proportion of amplitude that is from direct vs indirect radiation amp_ratio_direct_vs_indirect_S = MT_max_prob[-2] # Proportion of amplitude that is from direct vs indirect radiation amp_ratio_direct_vs_indirect_surface = MT_max_prob[-1] # Proportion of amplitude that is from direct vs indirect radiation MT_max_prob = MT_max_prob_tmp print("----------------------") print(" ") print("Amplitude ratios of direct to indirect radiation (P, S, surface):", amp_ratio_direct_vs_indirect_P, amp_ratio_direct_vs_indirect_S, amp_ratio_direct_vs_indirect_surface) print("(Note: Although gives values for all phases, only phases specified in original solution are actually relevent).") print(" ") print("----------------------") else: amp_ratio_direct_vs_indirect = MT_max_prob[-1] # Proportion of amplitude that is from direct vs indirect radiation MT_max_prob = MT_max_prob_tmp print("----------------------") print(" ") print("Amplitude ratio of direct to indirect radiation:", amp_ratio_direct_vs_indirect) print(" ") print("----------------------") if inversion_type == "full_mt" or inversion_type == "full_mt_Lune_samp": inversion_type = "unconstrained" # And get full MT matrix: full_MT_max_prob = get_full_MT_array(MT_max_prob) # Plot MT solutions and radiation pattern of most likely on sphere: MTs_to_plot = full_MT_max_prob #MTs_max_gau_loc radiation_pattern_MT = MT_max_prob # 6 moment tensor to plot radiation pattern for for plot_plane in ["EN","EZ","NZ"]: figure_filename = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_"+plot_plane+".png") plot_full_waveform_result_beachball(MTs_to_plot, wfs_dict, radiation_pattern_MT=radiation_pattern_MT, MTp_max_prob_value=MTp_max_prob_value, stations=stations, lower_upper_hemi_switch=lower_upper_hemi_switch, figure_filename=figure_filename, num_MT_solutions_to_plot=1, inversion_type=inversion_type, radiation_MT_phase=radiation_MT_phase, plot_plane=plot_plane, plot_uncertainty_switch=plot_uncertainty_switch, uncertainty_MTs=MTs, uncertainty_MTp=MTp, plot_wfs_on_focal_mech_switch=plot_wfs_on_focal_mech_switch) # And plot waveforms separately (if specified): if plot_wfs_separately_switch: plot_fname = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_separate_wfs"+".png") plot_wfs_of_most_likely_soln_separate_plot(stations, wfs_dict, plot_fname) # And plot Lune for solution: if plot_Lune_switch: plot_Lune(MTs, MTp_for_Lune, six_MT_max_prob=radiation_pattern_MT, frac_to_sample=1.0, figure_filename=os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_Lune.png"), plot_max_prob_on_Lune=plot_max_prob_on_Lune_switch) ###plot_slip_vector_distribution(MTs, MTp, six_MT_max_prob=MT_max_prob, frac_to_sample=0.01, figure_filename="Plots/"+MT_data_filename.split("/")[-1].split(".")[0]+"_slip_vector_dist.png") # And plot DAS waveforms, if specified: if plot_das_wfs_switch: plot_fname = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_DAS_wfs"+".png") plot_wfs_of_most_likely_soln_separate_plot_das(wfs_dict, plot_fname, fs=1000.) elif inversion_type == "DC": # And get full MT matrix: full_MT_max_prob = get_full_MT_array(MT_max_prob) # Get sampled MT solutions, based upon number of MT solutions to plot: MTs_sample = get_frac_of_MTs_using_MT_probs(MTs, MTp, num_MT_solutions_to_plot) # Plot MT solutions and radiation pattern of most likely on sphere: MTs_to_plot = MTs_sample #full_MT_max_prob #MTs_max_gau_loc radiation_pattern_MT = MT_max_prob # 6 moment tensor to plot radiation pattern for for plot_plane in ["EN","EZ","NZ"]: figure_filename = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_"+plot_plane+".png") plot_full_waveform_result_beachball(MTs_to_plot, wfs_dict, radiation_pattern_MT=radiation_pattern_MT, MTp_max_prob_value=MTp_max_prob_value, stations=stations, lower_upper_hemi_switch=lower_upper_hemi_switch, figure_filename=figure_filename, num_MT_solutions_to_plot=num_MT_solutions_to_plot, inversion_type=inversion_type, radiation_MT_phase=radiation_MT_phase, plot_plane=plot_plane, plot_uncertainty_switch=plot_uncertainty_switch, uncertainty_MTs=MTs, uncertainty_MTp=MTp, plot_wfs_on_focal_mech_switch=plot_wfs_on_focal_mech_switch, DC_switch_slip_vector=DC_switch_slip_vector) # And plot waveforms separately (if specified): if plot_wfs_separately_switch: plot_fname = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_separate_wfs"+".png") plot_wfs_of_most_likely_soln_separate_plot(stations, wfs_dict, plot_fname) # And plot DAS waveforms, if specified: if plot_das_wfs_switch: plot_fname = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_DAS_wfs"+".png") plot_wfs_of_most_likely_soln_separate_plot_das(wfs_dict, plot_fname, fs=1000.) elif inversion_type == "single_force": full_MT_max_prob = MT_max_prob # Plot MT solutions and radiation pattern of most likely on sphere: MTs_to_plot = full_MT_max_prob #MTs_max_gau_loc radiation_pattern_MT = MT_max_prob # 6 moment tensor to plot radiation pattern for for plot_plane in ["EN","EZ","NZ"]: figure_filename = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_"+plot_plane+".png") plot_full_waveform_result_beachball(MTs_to_plot, wfs_dict, radiation_pattern_MT=radiation_pattern_MT, MTp_max_prob_value=MTp_max_prob_value, stations=stations, lower_upper_hemi_switch=lower_upper_hemi_switch, figure_filename=figure_filename, num_MT_solutions_to_plot=1, inversion_type=inversion_type, radiation_MT_phase=radiation_MT_phase, plot_plane=plot_plane, plot_uncertainty_switch=plot_uncertainty_switch, uncertainty_MTs=MTs, uncertainty_MTp=MTp, plot_wfs_on_focal_mech_switch=plot_wfs_on_focal_mech_switch) # And plot waveforms separately (if specified): if plot_wfs_separately_switch: plot_fname = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_separate_wfs"+".png") plot_wfs_of_most_likely_soln_separate_plot(stations, wfs_dict, plot_fname) # And plot DAS waveforms, if specified: if plot_das_wfs_switch: plot_fname = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_DAS_wfs"+".png") plot_wfs_of_most_likely_soln_separate_plot_das(wfs_dict, plot_fname, fs=1000.) elif inversion_type == "DC_single_force_couple": full_MT_max_prob = get_full_MT_array(MT_max_prob[0:6]) radiation_pattern_MT = MT_max_prob[0:6] single_force_vector_max_prob = MT_max_prob[6:9] amp_prop_DC = MT_max_prob[9] # Proportion of amplitude that is DC # Plot MT solutions and radiation pattern of most likely on sphere: for plot_plane in ["EN","EZ","NZ"]: figure_filename = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_"+plot_plane+"_DC_component.png") plot_full_waveform_result_beachball(full_MT_max_prob, wfs_dict, radiation_pattern_MT=radiation_pattern_MT, MTp_max_prob_value=MTp_max_prob_value, stations=stations, lower_upper_hemi_switch=lower_upper_hemi_switch, figure_filename=figure_filename, num_MT_solutions_to_plot=1, inversion_type="DC", radiation_MT_phase=radiation_MT_phase, plot_plane=plot_plane, plot_uncertainty_switch=plot_uncertainty_switch, uncertainty_MTs=MTs, uncertainty_MTp=MTp, plot_wfs_on_focal_mech_switch=plot_wfs_on_focal_mech_switch) figure_filename = os.path.join(plot_outdir, MT_data_filename.split("/")[-1].split(".")[0]+"_"+plot_plane+"_SF_component.png") plot_full_waveform_result_beachball(single_force_vector_max_prob, wfs_dict, radiation_pattern_MT=single_force_vector_max_prob, MTp_max_prob_value=MTp_max_prob_value, stations=stations, lower_upper_hemi_switch=lower_upper_hemi_switch, figure_filename=figure_filename, num_MT_solutions_to_plot=1, inversion_type="single_force", radiation_MT_phase=radiation_MT_phase, plot_plane=plot_plane, plot_uncertainty_switch=plot_uncertainty_switch, uncertainty_MTs=MTs, uncertainty_MTp=MTp, plot_wfs_on_focal_mech_switch=plot_wfs_on_focal_mech_switch) # And plot probability distribution for DC vs. single force: figure_filename =
if retall: ret.profile_map = profile ret.extractionApertures = extractionApertures ret.background_map = background ret.variance_map = variance0 ret.goodpixelmask = goodpixelmask ret.function_args = args ret.function_kw = kw return ret def spextractor(frame, gain, readnoise, framevar=None, badpixelmask=None, mode='superExtract', trace=None, options=None, trace_options=None, verbose=False): """Extract a spectrum from a frame using one of several methods. :INPUTS: frame : 2D Numpy array or filename Contains a single spectral trace. gain : None or scalar Gain of data contained in 'frame;' i.e., number of collected photoelectrons equals frame * gain. readnoise : None or scalar Read noise of detector, in electrons. framevar : None, 2D Numpy array, or filename Variance of values in 'frame.' If and only if framevar is None, use gain and readnoise to compute variance. badpixelmask : None, 2D Numpy array, or filename Mask of bad pixels in 'frame.' Bad pixels are set to 1, good pixels are set to 0. mode : str Which spectral extraction mode to use. Options are: superExtract -- see :func:`superExtract` optimalExtract -- see :func:`optimalExtract` spline -- see :func:`extractSpectralProfiles` Must also input trace_options. trace : None, or 1D Numpy Array Spectral trace location: fractional pixel index along the entire spectral trace. If None, :func:`traceorders` will be called using the options in 'trace_options.' options : None or dict Keyword options to be passed to the appropriate spectral extraction algorithm. Note that you should be able to pass the same sets of parameters to :func:`superExtract` and :func:`optimalExtract` (the necessary parameter sets overlap, but are not identical). trace_options : None or dict Keyword options to be passed to :func:`traceorders` (if no trace is input, or if mode='spline') :RETURNS: spectrum, error or variance of spectrum, sky background, ... :NOTES: When 'optimalextract' is used: if len(bkg_radii)==2 then the background apertures will be reset based on the median location of the trace. If extract_radius is a singleton, it will be similarly redefined. :EXAMPLE: :: frame = pyfits.getdata('spectral_filename.fits') gain, readnoise = 3.3, 30 output = spec.spextractor(frame, gain, readnoise, mode='superExtract', \ options=dict(bord=2, bkg_radii=[20, 30], extract_radius=15, \ polyspacing=1./3, pord=5, verbose=True, trace=trace, \ qmode='slow-linear')) output2 = spec.spextractor(frame, gain, readnoise, mode='optimalExtract', \ options=dict(bkg_radii=[20,30], extract_radius=15, bord=2, \ bsigma=3, pord=3, psigma=8, csigma=5, verbose=1)) """ # 2012-09-03 11:12 IJMC: Created from tools import array_or_filename # Parse inputs: frame = array_or_filename(frame) framevar = array_or_filename(framevar, noneoutput=np.abs(frame) / gain + (readnoise / gain)**2) if options is None: options = dict(dispaxis=0) if verbose and not options.has_key('verbose'): options['verbose'] = verbose if trace is None: if trace_options is None: trace_options = dict(pord=2) if not trace_options.has_key('dispaxis'): if options.has_key('dispaxis'): trace_options['dispaxis'] = options['dispaxis'] trace_coef = traceorders(frame, **trace_options) trace = np.polyval(trace_coef.ravel(), np.arange(frame.shape[1-options['dispaxis']])) options['trace'] = trace ################################################## # Extract spectrum in one of several ways: ################################################## if mode.lower()=='superextract': ret = superExtract(frame, framevar, gain, readnoise, **options) elif mode.lower()=='spline': # First, set things up: try: trace_coef += 0.0 except: trace_coef = np.polyfit(np.arange(trace.size), trace, trace_options['pord']).reshape(1, trace_options['pord']+1) trace_options['retall'] = True if not trace_options.has_key('bkg_radii'): if options.has_key('bkg_radii') and len(options['bkg_radii'])==2: trace_options['bkg_radii'] = options['bkg_radii'] if not trace_options.has_key('extract_radius'): if options.has_key('extract_radius') and not hasattr(options['extract_radius'], '__iter__'): trace_options['extract_radius'] = options['extract_radius'] prof = makeprofile(frame, trace_coef, **trace_options) ret = extractSpectralProfiles(prof, **trace_options) elif mode.lower()=='optimalextract': # First, re-define bkg_radii and extract_radius (if necessary): options = dict().update(options) # prevents alterations of options if options.has_key('bkg_radii') and len(options['bkg_radii'])==2: t0 = np.median(trace) bkg_radii = [t0-options['bkg_radii'][1], t0-options['bkg_radii'][0], t0+options['bkg_radii'][0], t0+options['bkg_radii'][1]] options['bkg_radii'] = bkg_radii if verbose: print "Re-defining background apertures: ", bkg_radii if options.has_key('extract_radius') and \ (not hasattr(options['extract_radius'], '__iter__') or \ (len(options['extract_radius'])==1)): extract_radius = [t0 - options['extract_radius'], \ t0 + options['extract_radius']] options['extract_radius'] = extract_radius if verbose: print "Re-defining extraction aperture: ", extract_radius ret = optimalExtract(frame, framevar, gain, readnoise, **options) else: print "No valid spectral extraction mode specified!" ret = -1 return ret def scaleSpectralSky_pca(frame, skyframes, variance=None, mask=None, badpixelmask=None, npca=3, gain=3.3, readnoise=30): """ Use PCA and blank sky frames to subtract frame : str or NumPy array data frame to subtract sky from. Assumed to be in ADU, not electrons (see gain and readnoise) npca : int number of PCA components to remove f0 = pyfits.getdata(odome.procsci[0]) mask = pyfits.getdata(odome._proc + 'skyframes_samplemask.fits').astype(bool) badpixelmask = pyfits.getdata( odome.badpixelmask).astype(bool) The simplest way to fit sky to a 'frame' containing bright spectral is to include the spectral-trace regions in 'mask' but set the 'variance' of those regions extremely high (to de-weight them in the least-squares fit). To use for multi-object data, consider running multiple times (once per order) Returns the best-fit sky frame as determined from the first 'npca' PCA components. """ # 2012-09-17 16:41 IJMC: Created from scipy import sparse from pcsa import pca # Parse inputs if not isinstance(frame, np.ndarray): frame = pyfits.getdata(frame) if variance is None: variance = np.abs(frame)/gain + (readnoise/gain)**2 else: variance = np.array(variance, copy=False) weights = 1./variance nx, ny = frame.shape n_tot = nx*ny if badpixelmask is None: badpixelmask = np.zeros((nx, ny), dtype=bool) elif isinstance(badpixelmask, str): badpixelmask = pyfits.getdata(badpixelmask).astype(bool) else: badpixelmask = np.array(badpixelmask).astype(bool) weights[badpixelmask] = 0. if mask is None: mask = np.ones(frame.shape, dtype=bool) n_elem = n_tot else: n_elem = mask.astype(bool).sum() maskind = mask.nonzero() if isinstance(skyframes, np.ndarray) and skyframes.ndim==3: pass else: skyframes = np.array([pyfits.getdata(fn) for fn in skyframes]) skyframes_ind = np.array([sf[maskind] for sf in skyframes]) frame_ind = frame[maskind] pcaframes = np.zeros((npca, n_elem), dtype=np.float32) iter = 0 pcas = [] for jj in range(npca): pcas.append(pca(skyframes_ind, None, ord=jj+1)) pcaframes[0] = pcas[0][0][0] for jj in range(1, npca): pcaframes[jj] = (pcas[jj][0] - pcas[jj-1][0])[0] # del pcas svecs = sparse.csr_matrix(pcaframes).transpose() fitcoef, efitcoef = an.lsqsp(svecs, frame_ind, weights[maskind]) skyvalues = (fitcoef.reshape(npca, 1) * pcaframes).sum(0) #eskyvalues = (np.diag(efitcoef).reshape(npca, 1) * pcaframes).sum(0) skyframe = np.zeros((nx, ny), dtype=float) skyframe[maskind] = skyvalues return skyframe def scaleSpectralSky_dsa(subframe, variance=None, badpixelmask=None, nk=31, pord=1, nmed=3, gain=3.3, readnoise=30, dispaxis=0, spatial_index=None): """ Use difference-imaging techniques to subtract moderately tilted sky background. Doesn't work so well! subframe : NumPy array data subframe containing sky data to be subtracted (and, perhaps, an object's spectral trace). Assumed to be in ADU, not electrons (see gain and readnoise) variance : None or NumPy array variance of each pixel in 'subframe' nmed : int size of 2D median filter pord : int degree of spectral tilt. Keep this number low! nk : int Number of kernel pixels in :func:`dia.dsa` nmed : int Size of window for 2D median filter (to reject bad pixels, etc.) dispaxis : int set dispersion axis: 0 = horizontal and 1 = vertical gain, readnoise : ints If 'variance' is None, these are used to estimate the uncertainties. spatial_index : None, or 1D NumPy array of type bool Which spatial rows (if dispaxis=0) to use when fitting the tilt of sky lines across the spectrum. If you want to use all, set to None. If you want to ignore some (e.g., because there's a bright object's spectrum there) then set those rows' elements of spatial_index to 'False'. :NOTES: Note that (in my experience!) this approach works better when you set all weights to unity, rather than using the suggested (photon + read noise) variances. Returns the best-fit sky frame. """ # 2012-09-17 16:41 IJMC: Created from scipy import signal import dia # Parse inputs if not isinstance(subframe, np.ndarray): subframe = pyfits.getdata(subframe) if variance is None: variance = np.abs(subframe)/gain + (readnoise/gain)**2 else: variance = np.array(variance, copy=False) weights = 1./variance if badpixelmask is None: badpixelmask = np.zeros(subframe.shape, dtype=bool) elif isinstance(badpixelmask, str): badpixelmask = pyfits.getdata(badpixelmask).astype(bool) else: badpixelmask = np.array(badpixelmask).astype(bool) weights[badpixelmask] = 0. if dispaxis==1: subframe = subframe.transpose() variance = variance.transpose() weights = weights.transpose() badpixelmask = badpixelmask.transpose() sub = subframe if nmed > 1: ss = signal.medfilt2d(sub, nmed) else: ss = sub.copy() ref = np.median(ss, axis=0) n, nlam = ss.shape if spatial_index is None: spatial_index = np.arange(n) else: spatial_index = np.array(spatial_index, copy=False).nonzero() gaussianpar = np.zeros((n, 4)) for ii in range(n): test = dia.dsa(ref, ss[ii], nk, w=weights[ii], noback=True) gaussianpar[ii] = fitGaussian(test[1])[0] position_fit = an.polyfitr(np.arange(n)[spatial_index], gaussianpar[:,2][spatial_index], pord, 3) positions = np.polyval(position_fit, np.arange(n)) width_fit = np.median(gaussianpar[:,1]) skyframe = 0*ss testDC_spec = np.ones(nlam) testx = np.arange(nk, dtype=float) lsqfits = np.zeros((n,2)) for ii in range(n): testgaussian = gaussian([1, width_fit, positions[ii], 0.], testx) testgaussian /= testgaussian.sum() testspectrum = dia.rconvolve1d(ref, testgaussian) skyframe[ii] = testspectrum
import cv2 import numpy as np from lanms import merge_quadrangle_n9 as la_nms from mmdet.core import BitmapMasks from mmdet.datasets.builder import PIPELINES from numpy.linalg import norm import mmocr.utils.check_argument as check_argument from .textsnake_targets import TextSnakeTargets @PIPELINES.register_module() class DRRGTargets(TextSnakeTargets): """Generate the ground truth targets of DRRG: Deep Relational Reasoning Graph Network for Arbitrary Shape Text Detection. [https://arxiv.org/abs/2003.07493]. This code was partially adapted from https://github.com/GXYM/DRRG licensed under the MIT license. Args: orientation_thr (float): The threshold for distinguishing between head edge and tail edge among the horizontal and vertical edges of a quadrangle. resample_step (float): The step size for resampling the text center line. num_min_comps (int): The minimum number of text components, which should be larger than k_hop1 mentioned in paper. num_max_comps (int): The maximum number of text components. min_width (float): The minimum width of text components. max_width (float): The maximum width of text components. center_region_shrink_ratio (float): The shrink ratio of text center regions. comp_shrink_ratio (float): The shrink ratio of text components. comp_w_h_ratio (float): The width to height ratio of text components. min_rand_half_height(float): The minimum half-height of random text components. max_rand_half_height (float): The maximum half-height of random text components. jitter_level (float): The jitter level of text component geometric features. """ def __init__(self, orientation_thr=2.0, resample_step=8.0, num_min_comps=9, num_max_comps=600, min_width=8.0, max_width=24.0, center_region_shrink_ratio=0.3, comp_shrink_ratio=1.0, comp_w_h_ratio=0.3, text_comp_nms_thr=0.25, min_rand_half_height=8.0, max_rand_half_height=24.0, jitter_level=0.2): super().__init__() self.orientation_thr = orientation_thr self.resample_step = resample_step self.num_max_comps = num_max_comps self.num_min_comps = num_min_comps self.min_width = min_width self.max_width = max_width self.center_region_shrink_ratio = center_region_shrink_ratio self.comp_shrink_ratio = comp_shrink_ratio self.comp_w_h_ratio = comp_w_h_ratio self.text_comp_nms_thr = text_comp_nms_thr self.min_rand_half_height = min_rand_half_height self.max_rand_half_height = max_rand_half_height self.jitter_level = jitter_level def dist_point2line(self, point, line): assert isinstance(line, tuple) point1, point2 = line d = abs(np.cross(point2 - point1, point - point1)) / ( norm(point2 - point1) + 1e-8) return d def draw_center_region_maps(self, top_line, bot_line, center_line, center_region_mask, top_height_map, bot_height_map, sin_map, cos_map, region_shrink_ratio): """Draw attributes of text components on text center regions. Args: top_line (ndarray): The points composing the top side lines of text polygons. bot_line (ndarray): The points composing bottom side lines of text polygons. center_line (ndarray): The points composing the center lines of text instances. center_region_mask (ndarray): The text center region mask. top_height_map (ndarray): The map on which the distance from points to top side lines will be drawn for each pixel in text center regions. bot_height_map (ndarray): The map on which the distance from points to bottom side lines will be drawn for each pixel in text center regions. sin_map (ndarray): The map of vector_sin(top_point - bot_point) that will be drawn on text center regions. cos_map (ndarray): The map of vector_cos(top_point - bot_point) will be drawn on text center regions. region_shrink_ratio (float): The shrink ratio of text center regions. """ assert top_line.shape == bot_line.shape == center_line.shape assert (center_region_mask.shape == top_height_map.shape == bot_height_map.shape == sin_map.shape == cos_map.shape) assert isinstance(region_shrink_ratio, float) h, w = center_region_mask.shape for i in range(0, len(center_line) - 1): top_mid_point = (top_line[i] + top_line[i + 1]) / 2 bot_mid_point = (bot_line[i] + bot_line[i + 1]) / 2 sin_theta = self.vector_sin(top_mid_point - bot_mid_point) cos_theta = self.vector_cos(top_mid_point - bot_mid_point) tl = center_line[i] + (top_line[i] - center_line[i]) * region_shrink_ratio tr = center_line[i + 1] + ( top_line[i + 1] - center_line[i + 1]) * region_shrink_ratio br = center_line[i + 1] + ( bot_line[i + 1] - center_line[i + 1]) * region_shrink_ratio bl = center_line[i] + (bot_line[i] - center_line[i]) * region_shrink_ratio current_center_box = np.vstack([tl, tr, br, bl]).astype(np.int32) cv2.fillPoly(center_region_mask, [current_center_box], color=1) cv2.fillPoly(sin_map, [current_center_box], color=sin_theta) cv2.fillPoly(cos_map, [current_center_box], color=cos_theta) current_center_box[:, 0] = np.clip(current_center_box[:, 0], 0, w - 1) current_center_box[:, 1] = np.clip(current_center_box[:, 1], 0, h - 1) min_coord = np.min(current_center_box, axis=0).astype(np.int32) max_coord = np.max(current_center_box, axis=0).astype(np.int32) current_center_box = current_center_box - min_coord box_sz = (max_coord - min_coord + 1) center_box_mask = np.zeros((box_sz[1], box_sz[0]), dtype=np.uint8) cv2.fillPoly(center_box_mask, [current_center_box], color=1) inds = np.argwhere(center_box_mask > 0) inds = inds + (min_coord[1], min_coord[0]) inds_xy = np.fliplr(inds) top_height_map[(inds[:, 0], inds[:, 1])] = self.dist_point2line( inds_xy, (top_line[i], top_line[i + 1])) bot_height_map[(inds[:, 0], inds[:, 1])] = self.dist_point2line( inds_xy, (bot_line[i], bot_line[i + 1])) def generate_center_mask_attrib_maps(self, img_size, text_polys): """Generate text center region masks and geometric attribute maps. Args: img_size (tuple): The image size (height, width). text_polys (list[list[ndarray]]): The list of text polygons. Returns: center_lines (list): The list of text center lines. center_region_mask (ndarray): The text center region mask. top_height_map (ndarray): The map on which the distance from points to top side lines will be drawn for each pixel in text center regions. bot_height_map (ndarray): The map on which the distance from points to bottom side lines will be drawn for each pixel in text center regions. sin_map (ndarray): The sin(theta) map where theta is the angle between vector (top point - bottom point) and vector (1, 0). cos_map (ndarray): The cos(theta) map where theta is the angle between vector (top point - bottom point) and vector (1, 0). """ assert isinstance(img_size, tuple) assert check_argument.is_2dlist(text_polys) h, w = img_size center_lines = [] center_region_mask = np.zeros((h, w), np.uint8) top_height_map = np.zeros((h, w), dtype=np.float32) bot_height_map = np.zeros((h, w), dtype=np.float32) sin_map = np.zeros((h, w), dtype=np.float32) cos_map = np.zeros((h, w), dtype=np.float32) for poly in text_polys: assert len(poly) == 1 polygon_points = poly[0].reshape(-1, 2) _, _, top_line, bot_line = self.reorder_poly_edge(polygon_points) resampled_top_line, resampled_bot_line = self.resample_sidelines( top_line, bot_line, self.resample_step) resampled_bot_line = resampled_bot_line[::-1] center_line = (resampled_top_line + resampled_bot_line) / 2 if self.vector_slope(center_line[-1] - center_line[0]) > 2: if (center_line[-1] - center_line[0])[1] < 0: center_line = center_line[::-1] resampled_top_line = resampled_top_line[::-1] resampled_bot_line = resampled_bot_line[::-1] else: if (center_line[-1] - center_line[0])[0] < 0: center_line = center_line[::-1] resampled_top_line = resampled_top_line[::-1] resampled_bot_line = resampled_bot_line[::-1] line_head_shrink_len = np.clip( (norm(top_line[0] - bot_line[0]) * self.comp_w_h_ratio), self.min_width, self.max_width) / 2 line_tail_shrink_len = np.clip( (norm(top_line[-1] - bot_line[-1]) * self.comp_w_h_ratio), self.min_width, self.max_width) / 2 num_head_shrink = int(line_head_shrink_len // self.resample_step) num_tail_shrink = int(line_tail_shrink_len // self.resample_step) if len(center_line) > num_head_shrink + num_tail_shrink + 2: center_line = center_line[num_head_shrink:len(center_line) - num_tail_shrink] resampled_top_line = resampled_top_line[ num_head_shrink:len(resampled_top_line) - num_tail_shrink] resampled_bot_line = resampled_bot_line[ num_head_shrink:len(resampled_bot_line) - num_tail_shrink] center_lines.append(center_line.astype(np.int32)) self.draw_center_region_maps(resampled_top_line, resampled_bot_line, center_line, center_region_mask, top_height_map, bot_height_map, sin_map, cos_map, self.center_region_shrink_ratio) return (center_lines, center_region_mask, top_height_map, bot_height_map, sin_map, cos_map) def generate_rand_comp_attribs(self, num_rand_comps, center_sample_mask): """Generate random text components and their attributes to ensure the the number of text components in an image is larger than k_hop1, which is the number of one hop neighbors in KNN graph. Args: num_rand_comps (int): The number of random text components. center_sample_mask (ndarray): The region mask for sampling text component centers . Returns: rand_comp_attribs (ndarray): The random text component attributes (x, y, h, w, cos, sin, comp_label=0). """ assert isinstance(num_rand_comps, int) assert num_rand_comps > 0 assert center_sample_mask.ndim == 2 h, w = center_sample_mask.shape max_rand_half_height = self.max_rand_half_height min_rand_half_height = self.min_rand_half_height max_rand_height = max_rand_half_height * 2 max_rand_width = np.clip(max_rand_height * self.comp_w_h_ratio, self.min_width, self.max_width) margin = int( np.sqrt((max_rand_height / 2)**2 + (max_rand_width / 2)**2)) + 1 if 2 * margin + 1 > min(h, w): assert min(h, w) > (np.sqrt(2) * (self.min_width + 1)) max_rand_half_height = max(min(h, w) / 4, self.min_width / 2 + 1) min_rand_half_height = max(max_rand_half_height / 4, self.min_width / 2) max_rand_height = max_rand_half_height * 2 max_rand_width = np.clip(max_rand_height * self.comp_w_h_ratio, self.min_width, self.max_width) margin = int( np.sqrt((max_rand_height / 2)**2 + (max_rand_width / 2)**2)) + 1 inner_center_sample_mask = np.zeros_like(center_sample_mask) inner_center_sample_mask[margin:h - margin, margin:w - margin] = \ center_sample_mask[margin:h - margin, margin:w - margin] kernel_size = int(np.clip(max_rand_half_height, 7, 21)) inner_center_sample_mask = cv2.erode( inner_center_sample_mask, np.ones((kernel_size, kernel_size), np.uint8)) center_candidates = np.argwhere(inner_center_sample_mask > 0) num_center_candidates = len(center_candidates) sample_inds = np.random.choice(num_center_candidates, num_rand_comps) rand_centers = center_candidates[sample_inds] rand_top_height = np.random.randint( min_rand_half_height, max_rand_half_height, size=(len(rand_centers), 1)) rand_bot_height = np.random.randint( min_rand_half_height, max_rand_half_height, size=(len(rand_centers), 1)) rand_cos = 2 * np.random.random(size=(len(rand_centers), 1)) - 1 rand_sin = 2 * np.random.random(size=(len(rand_centers), 1)) - 1 scale = np.sqrt(1.0 / (rand_cos**2 + rand_sin**2 + 1e-8)) rand_cos = rand_cos * scale rand_sin = rand_sin * scale height = (rand_top_height + rand_bot_height) width = np.clip(height * self.comp_w_h_ratio, self.min_width, self.max_width) rand_comp_attribs = np.hstack([ rand_centers[:, ::-1], height, width, rand_cos, rand_sin, np.zeros_like(rand_sin) ]).astype(np.float32) return rand_comp_attribs def jitter_comp_attribs(self, comp_attribs, jitter_level): """Jitter text components attributes. Args: comp_attribs (ndarray): The text component attributes. jitter_level (float): The jitter level of text components attributes. Returns: jittered_comp_attribs (ndarray): The jittered text component attributes (x, y, h, w, cos, sin, comp_label).