input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
from __future__ import print_function
# import os
import sys
import copy
import numpy as np
from collections import OrderedDict, Sequence
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH - " \
"Computational Materials Design (CM) Department"
__version__ = "1.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "production"
__date__ = "Sep 1, 2017"
class SparseListElement(object):
"""
Handle single element of a sparse lisr
Args:
ind: index
val: value
"""
def __init__(self, ind, val):
self.index = ind
self.value = val
def __str__(self):
return '({}: {})'.format(self.index, self.value)
class SparseList(object):
"""
Object to represent a single sparse list
Internal representation like a dict
External representation like a list
Args:
sparse_list: dict object with {index: val}
default: default value for all elements not given by index in sparse_list
length: length of the list
"""
def __init__(self, sparse_list, default=None, length=None):
if isinstance(sparse_list, dict):
self._dict = sparse_list.copy()
if "_" in self._dict.keys():
default = self._dict["_"]
del self._dict["_"]
if length is None:
raise ValueError('Length must be provided in dict input mode')
self._length = length
elif isinstance(sparse_list, (list, np.ndarray)):
# self._dict = {el: [] for el in set(sparse_list)}
self._dict = {}
for i, el in enumerate(sparse_list):
self._dict[i] = el
self._length = len(sparse_list)
if length is not None:
if length != self._length:
raise ValueError('Incompatible length of new list')
self._default = default
def _val_data_type(self):
"""
Returns:
"""
if isinstance(self.values(), dict):
pass
print(self.values())
data_0 = self.values()[0]
if isinstance(data_0, list):
if isinstance(data_0[0], bool):
return "list_bool"
else:
raise ValueError('tags which have as elements lists or tensors are not implemented')
else:
return "scalar"
def to_hdf(self, hdf, key):
"""
Args:
hdf:
key:
Returns:
"""
if len(self.list()) > 0:
# Convert to array and store
hdf[key] = np.array(self.list())
elif len(self.values()) > 0:
print('sparse array: ', key, len(self.values()))
data_type = self._val_data_type()
my_dict = OrderedDict()
my_dict["index"] = self.keys()
if data_type is "list_bool":
my_dict["values"] = [sum([2 ** i * int(v) for i, v in enumerate(val)]) for val in self.values()]
else:
my_dict["values"] = self.values()
print("values: ", self.values())
hdf[key] = my_dict
def __len__(self):
return self._length
def __copy__(self):
return SparseList(sparse_list=self._dict, default=self._default, length=self._length)
def keys(self):
"""
Returns:
indices of non-sparse elements
"""
return self._dict.keys()
def values(self):
"""
Returns:
values of non-sparse elements
"""
return self._dict.values()
def items(self):
"""
Returns:
index, value pairs of non-sparse elements
"""
return self._dict.items()
def list(self):
"""
convert sparse list into full list
Returns:
list representation
"""
full_list = [self._default for _ in range(self._length)]
for i, val in self._dict.items():
full_list[i] = val
return full_list
def __iter__(self):
if self._default is None:
for i, val in self._dict.items():
yield SparseListElement(i, val)
else:
for i, val in enumerate(self.list()):
yield val
def __getitem__(self, item):
if isinstance(item, (int, np.integer)):
if item in self._dict:
return self._dict[item]
return self._default
if isinstance(item, slice):
ind_list = range(len(self))[item]
elif isinstance(item, (list, tuple, np.ndarray)):
if len(item) == 0:
ind_list = []
else:
if isinstance(item[0], (int, np.integer)):
ind_list = item
elif isinstance(item[0], (bool, np.bool_)):
ind_list = []
for i, bo in enumerate(item):
if bo:
ind_list.append(i)
else:
raise ValueError('Unknown item type: ' + str(type(item)))
sliced_dict = {j: self._dict[ind] for j, ind in enumerate(ind_list) if ind in self._dict}
return self.__class__(sliced_dict, default=self._default, length=len(ind_list))
def __setitem__(self, key, value):
if isinstance(key, (int, np.integer)):
if key > len(self):
raise IndexError
self._dict[key] = value
return
elif isinstance(key, slice):
key = range(len(self))[key]
if max(key) > self._length:
raise IndexError
for i in key:
self._dict[i] = value
def __delitem__(self, key):
# programmed for simplicity, not for performance
ind_list = list(range(len(self)))
if isinstance(key, (list, np.ndarray, tuple)):
indexes = sorted(list(key), reverse=True)
for index in indexes:
del ind_list[index]
else:
del ind_list[key]
new_list = self[ind_list]
self._dict = new_list._dict
self._length = new_list._length
self._default = new_list._default
def __add__(self, other):
if not (isinstance(other, SparseList)):
raise AssertionError()
if not (self._default == other._default):
raise AssertionError()
new_list = self.__copy__()
shifted_dict = {i + self._length: val for i, val in other._dict.items()}
new_list._dict.update(shifted_dict)
new_list._length += len(other)
return new_list
def __mul__(self, other):
if not isinstance(other, (int, np.integer)):
raise ValueError('Multiplication defined only for SparseArray*integers')
overall_list = other * np.arange(len(self)).tolist()
new_dic = dict()
for k in self.keys():
for val in np.argwhere(np.array(overall_list) == k).flatten():
new_dic[val] = self[k]
return self.__class__(new_dic, default=self._default, length=other * len(self))
def __rmul__(self, other):
if isinstance(other, int):
return self * other
def __str__(self):
if self._default is None:
return "[" + " ".join([str(el) for el in self]) + "]"
else:
# return "[" + " ".join([str(el) + os.sep for el in self.list()]) + "]"
return "[" + " ".join([str(el) for el in self.list()]) + "]"
def __repr__(self):
return str(self.list())
def sparse_index(index_list, length, default_val=True):
"""
Args:
index_list:
length:
default_val:
Returns:
"""
new_dict = {i: default_val for i in index_list}
return SparseList(new_dict, length=length)
class SparseArrayElement(object):
"""
Single element of a SparseArray
Args:
**qwargs:
"""
def __init__(self, **qwargs):
self._lists = dict()
if qwargs:
self._lists = qwargs
def __getattr__(self, item):
if item in self._lists.keys():
return self._lists[item]
raise AttributeError('Object has no attribute {} {}'.format(self.__class__, item))
def __str__(self):
out_str = ""
for key, val in self._lists.items():
out_str += '{}: {}'.format(key, val)
return out_str
def __eq__(self, other):
if not (isinstance(other, SparseArrayElement)):
raise AssertionError()
conditions = []
for key in self._lists.keys():
try:
if isinstance(self._lists[key], np.ndarray):
conditions += list(np.equal(self._lists[key], other._lists[key]))
else:
conditions.append(self._lists[key] == other._lists[key])
except KeyError:
conditions.append(False)
return all(conditions)
class SparseArray(object):
"""
Administrate object that consists of several sparse lists (tags) and full lists that have identical indices and
length
Args:
**qwargs: dictionary containing lists and SparseLists (tags) (must have identical length)
"""
def __init__(self, length=None, **qwargs):
self._lists = dict()
self._length = length
for key in qwargs:
value = qwargs[key]
if self._length is None:
self._length = len(value)
else:
if not len(self) == len(value):
raise ValueError('Inconsistent vector lengths {} {} {}'.format(key, len(self), len(value)))
self._lists[key] = value
def __setitem__(self, key, value):
# exclude hidden variables (starting with _ from being added to _lists
# if (not hasattr(self, '_lists')) or (key[0] == "_"):
# self.__dict__[key] = value
# return
# el
if isinstance(value, SparseList):
self._lists[key] = value
return
elif isinstance(value, (Sequence, np.ndarray)):
if len(value) == len(self):
self._lists[key] = value
return
else:
raise ValueError(
'Length of array object and new list are inconsistent: {} {} {}'.format(key, len(value), len(self)))
raise ValueError('Unsupported argument: ' + str(type(value)))
def __getattr__(self, item):
# if not (item in ["_lists"]):
# print "item: ", item, hasattr(self, item)
if sys.version_info.major > 2:
if '_lists' in dir(self): # Python 3
if item in self._lists.keys():
return self._lists[item]
else:
if hasattr(self, '_lists'):
if item in self._lists.keys():
return self._lists[item]
return object.__getattribute__(self, item)
# raise AttributeError("%r object has no attribute %r" %(self.__class__, item))
def __delitem__(self, key):
for k in self.keys():
if len(self._lists[k]) == 0:
# ensure ASE compatibility
print('Empty key in SparseList: ', k, key)
continue
# print "del: ", k, key
if isinstance(self._lists[k], np.ndarray):
self._lists[k] = np.delete(self._lists[k], key, axis=0)
self._length = len(self._lists[k])
elif isinstance(self._lists[k], (list, tuple)):
if isinstance(key, (list, np.ndarray, tuple)):
indexes = sorted(list(key), reverse=True)
for index in indexes:
del self._lists[k][index]
else:
del self._lists[k][key]
else:
del self._lists[k][key]
# self._length = len(self._lists[k])
def check_consistency(self):
"""
Returns:
"""
for key, val in self._lists.items():
# for val in self._lists.values():
# print ("consistency: ", key, len(val), len(self))
if not (len(val) == self._length):
raise AssertionError()
def __str__(self):
out_str = "\n"
for key, val in self._lists.items():
out_str += key + " := [" + " ".join([str(el) for el in val]) + "] \n"
return out_str
def __len__(self):
if hasattr(self, '_length'):
return self._length
else:
return 0
def __getitem__(self, item):
new_dict = {}
if isinstance(item, int):
for key, value in self._lists.items():
if value[item] is not None:
new_dict[key] = value[item]
return SparseArrayElement(**new_dict)
elif isinstance(item, (str, np.str, np.str_)):
return self._lists[item]
elif isinstance(item, (list, np.ndarray)):
# print("key(__getitem__) len, type, item[0]: ", len(item), type(item), item[0])
if len(item) == len(self):
if isinstance(item[0], (np.bool_, bool)):
item = np.arange(len(item))[item]
for key, value in self._lists.items():
# print ('key: ', key, type(value))
if isinstance(item, slice):
new_dict[key] = value[item]
else:
if isinstance(value, (list, tuple)):
new_dict[key] = [value[i] for i in item]
else:
if len(value) > 0:
try:
new_dict[key] = value[item]
except IndexError:
print('Index error:: ', key, item, | |
import MySQLdb
import suds
from suds.client import Client
from suds.xsd.doctor import Import, ImportDoctor
from suds.plugin import MessagePlugin
import traceback
class MagentoApiMessagePlugin(MessagePlugin):
def marshalled(self, context):
body = context.envelope.getChild("Body")
call = context.envelope.childAtPath("Body/call")
if call:
resourcePath = call.getChild("resourcePath")
if resourcePath is not None and (str(resourcePath.getText()) == 'sales_order_shipment.create' or str(resourcePath.getText()) == 'sales_order_invoice.create'):
args = call.getChild("args")
if args:
item = args.getChild("item")
if item:
item.set("xsi:type","http://xml.apache.org/xml-soap:Map")
return context
class Adaptor(object):
"""Adaptor contain MySQL cursor object.
"""
def __init__(self, mySQLConn=None):
self._mySQLConn = mySQLConn
self._mySQLCursor = self._mySQLConn.cursor(MySQLdb.cursors.DictCursor)
@property
def mySQLCursor(self):
"""MySQL Server cursor object.
"""
return self._mySQLCursor
def disconnect(self):
self._mySQLConn.close()
def rollback(self):
self._mySQLConn.rollback()
def commit(self):
self._mySQLConn.commit()
class ApiAdaptor(object):
"""Adaptor contain API connection
"""
def __init__(self,apiConn=None,apiSessionId=None):
self._apiConn = apiConn
self._apiSessionId = apiSessionId
@property
def apiConn(self):
return self._apiConn
@property
def apiSessionId(self):
return self._apiSessionId
def disconnect(self):
if self._apiSessionId is not None and self._apiConn is not None:
try:
result = self._apiConn.service.endSession(self._apiSessionId)
self.logger.info("Logout Magento 1 API: sessionId = {0}".format(self._apiSessionId))
except Exception as e:
self.logger.exception("Failed to logout Magento 1 API with error: {0}".format(e))
raise
class Mage1Connector(object):
"""Magento 1 connection with functions.
"""
GETPRODUCTIDBYSKUSQL = """SELECT distinct entity_id FROM catalog_product_entity WHERE sku = %s;"""
ENTITYMETADATASQL = """
SELECT eet.entity_type_id, eas.attribute_set_id
FROM eav_entity_type eet, eav_attribute_set eas
WHERE eet.entity_type_id = eas.entity_type_id
AND eet.entity_type_code = %s
AND eas.attribute_set_name = %s;"""
ATTRIBUTEMETADATASQL = """
SELECT DISTINCT t1.attribute_id, t2.entity_type_id, t1.backend_type, t1.frontend_input
FROM eav_attribute t1, eav_entity_type t2
WHERE t1.entity_type_id = t2.entity_type_id
AND t1.attribute_code = %s
AND t2.entity_type_code = %s;"""
ISENTITYEXITSQL = """SELECT count(*) as count FROM {0}_entity WHERE entity_id = %s;"""
ISATTRIBUTEVALUEEXITSQL = """
SELECT count(*) as count
FROM {0}_entity_{1}
WHERE attribute_id = %s
AND store_id = %s
AND {2} = %s;"""
REPLACEATTRIBUTEVALUESQL = """REPLACE INTO {0}_entity_{1} ({2}) values ({3});"""
UPDATEENTITYUPDATEDATSQL = """UPDATE {0}_entity SET updated_at = UTC_TIMESTAMP() WHERE entity_id = %s;"""
GETOPTIONIDSQL = """
SELECT t2.option_id
FROM eav_attribute_option t1, eav_attribute_option_value t2
WHERE t1.option_id = t2.option_id
AND t1.attribute_id = %s
AND t2.value = %s
AND t2.store_id = %s;"""
INSERTCATALOGPRODUCTENTITYEESQL = """
INSERT INTO catalog_product_entity
(entity_id, created_in, updated_in, attribute_set_id, type_id, sku, has_options, required_options, created_at, updated_at)
VALUES(0, 1, 2147483647, %s, %s, %s, 0, 0, UTC_TIMESTAMP(), UTC_TIMESTAMP());"""
INSERTCATALOGPRODUCTENTITYSQL = """
INSERT INTO catalog_product_entity
(attribute_set_id, type_id, sku, has_options, required_options, created_at, updated_at)
VALUES(%s, %s, %s, 0, 0, UTC_TIMESTAMP(), UTC_TIMESTAMP());"""
UPDATECATALOGPRODUCTSQL = """
UPDATE catalog_product_entity
SET attribute_set_id = %s,
type_id = %s,
updated_at = UTC_TIMESTAMP()
WHERE {0} = %s;"""
INSERTEAVATTRIBUTEOPTIONSQL = """INSERT INTO eav_attribute_option (attribute_id) VALUES (%s);"""
OPTIONVALUEEXISTSQL = """
SELECT COUNT(*) as cnt FROM eav_attribute_option_value
WHERE option_id = %s
AND store_id = %s;"""
INSERTOPTIONVALUESQL = """INSERT INTO eav_attribute_option_value (option_id, store_id, value) VALUES (%s, %s, %s);"""
UPDATEOPTIONVALUESQL = """UPDATE eav_attribute_option_value SET value = %s WHERE option_id = %s AND store_id = %s;"""
GETATTRIBUTESBYENTITYTYPEANDATTRIBUTESETSQL = """
SELECT
a.entity_type_id, b.entity_type_code,
d.attribute_set_id, d.attribute_set_name,
a.attribute_id, a.attribute_code,
a.backend_type, a.frontend_input, a.frontend_label, a.is_required, a.is_user_defined
FROM eav_attribute a
INNER JOIN eav_entity_attribute c on (a.attribute_id = c.attribute_id and a.entity_type_id = c.entity_type_id)
INNER JOIN eav_attribute_set d on (c.attribute_set_id = d.attribute_set_id)
INNER JOIN eav_entity_type b on (a.entity_type_id = b.entity_type_id)
WHERE b.entity_type_code = %s and d.attribute_set_name = %s
"""
GETATTRIBUTESBYENTITYTYPESQL = """
SELECT
a.entity_type_id, b.entity_type_code,
a.attribute_id, a.attribute_code,
a.backend_type, a.frontend_input, a.frontend_label, a.is_required, a.is_user_defined
FROM eav_attribute a
INNER JOIN eav_entity_type b on (a.entity_type_id = b.entity_type_id)
WHERE b.entity_type_code = %s
"""
GETATTRIBUTEVALUESQL = "SELECT value FROM {0}_entity_{1} WHERE attribute_id = %s AND entity_id = %s"
GETATTRIBUTEOPTIONVALUESQL = """
SELECT
t3.value
FROM
eav_attribute_option t2,
eav_attribute_option_value t3
WHERE
t2.option_id = t3.option_id
AND t2.attribute_id = %s
AND t3.option_id = %s
AND t3.store_id = %s
"""
EXPORTPRODUCTSSQL = """
SELECT a.*, b.attribute_set_name
FROM catalog_product_entity a
INNER JOIN eav_attribute_set b ON a.attribute_set_id = b.attribute_set_id
WHERE updated_at >= %s AND b.attribute_set_name LIKE %s
"""
EXPORTPRODUCTSCOUNTSQL = """
SELECT count(*) AS total
FROM catalog_product_entity a
INNER JOIN eav_attribute_set b ON a.attribute_set_id = b.attribute_set_id
WHERE updated_at >= %s AND b.attribute_set_name LIKE %s
"""
EXPORTSTOCKSQL = """
SELECT a.item_id, b.sku, 'admin' as website_code, a.qty, a.is_in_stock
FROM cataloginventory_stock_item a
INNER JOIN catalog_product_entity b on a.product_id = b.entity_id
WHERE b.updated_at >= %s
"""
EXPORTSTOCKCOUNTSQL = """
SELECT count(*) AS total
FROM cataloginventory_stock_item a
INNER JOIN catalog_product_entity b on a.product_id = b.entity_id
WHERE b.updated_at >= %s
"""
ISCANINVOICESQL = """
SELECT entity_id, increment_id, base_grand_total, base_total_invoiced
FROM sales_flat_order
WHERE increment_id = %s
"""
GETINVOICEINCIDSQL = """
SELECT t1.increment_id
FROM sales_flat_order t0, sales_flat_invoice t1
WHERE t0.entity_id = t1.order_id
AND t0.increment_id = %s
"""
GETORDERLINEITEMBYSKUSQL = """
SELECT a.item_id
FROM sales_flat_order_item a, sales_flat_order b
WHERE a.parent_item_id is null AND
a.order_id = b.entity_id AND
a.sku = %s AND
b.increment_id = %s
"""
EXPORTMEDIAIMAGESSQL = """
SELECT
t0.sku,
CONCAT('{0}', t1.value) as 'value',
%s as 'type'
FROM
catalog_product_entity t0,
catalog_product_entity_varchar t1,
eav_attribute t2
WHERE t0.entity_id = t1.entity_id
AND t1.attribute_id = t2.attribute_id
AND t2.attribute_code = %s
AND t0.updated_at >= %s
"""
EXPORTMEDIAGALLERYSQL = """
SELECT
t0.sku,
CONCAT('{0}', t1.value) as 'value',
t2.store_id,
t2.position,
t2.label,
'mage1' as 'media_source',
'media_gallery' as 'type'
FROM
catalog_product_entity t0,
catalog_product_entity_media_gallery t1,
catalog_product_entity_media_gallery_value t2
WHERE t0.entity_id = t1.entity_id
AND t1.value_id = t2.value_id
AND t0.updated_at >= %s
"""
def __init__(self, setting=None, logger=None):
self.setting = setting
self.logger = logger
self._adaptor = None
self._apiAdaptor = None
def connect(self,type=None):
"""Initiate the connect with MySQL server or API connection.
"""
if type == 'API':
suds.bindings.binding.envns = ('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/')
imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
imp.filter.add('urn:Magento')
doctor = ImportDoctor(imp)
if 'MAGE1APIHTTPUSERNAME' in self.setting:
mageApiConn = Client(
self.setting['MAGE1WSDL'],
doctor=doctor,
plugins=[MagentoApiMessagePlugin()],
username = self.setting['MAGE1APIHTTPUSERNAME'],
password = self.setting['<PASSWORD>'])
else :
mageApiConn = Client(
self.setting['MAGE1WSDL'],
doctor=doctor,
plugins=[MagentoApiMessagePlugin()])
apiSessionId = mageApiConn.service.login(self.setting['MAGE1APIUSER'], self.setting['MAGE1APIKEY'])
return ApiAdaptor(mageApiConn,apiSessionId)
elif type == "CURSOR":
mySQLConn = MySQLdb.connect(user=self.setting['MAGE1DBUSERNAME'],
passwd=self.setting['<PASSWORD>'],
db=self.setting['MAGE1DB'],
host=self.setting['MAGE1DBSERVER'],
port=self.setting['MAGE1DBPORT'],
charset="utf8",
use_unicode=False)
log = "Open Mage1 DB connection"
self.logger.info(log)
return Adaptor(mySQLConn)
else:
return None
@property
def adaptor(self):
self._adaptor = self.connect(type="CURSOR") if self._adaptor is None else self._adaptor
return self._adaptor
@property
def apiAdaptor(self):
self._apiAdaptor = self.connect(type="API") if self._apiAdaptor is None else self._apiAdaptor
return self._apiAdaptor
def getEntityMetaData(self, entityTypeCode='catalog_product', attributeSet='Default'):
self.adaptor.mySQLCursor.execute(self.ENTITYMETADATASQL, [entityTypeCode, attributeSet])
entityMetadata = self.adaptor.mySQLCursor.fetchone()
if entityMetadata is not None:
return entityMetadata
else:
log = "attribute_set/entity_type_code: {0}/{1} not existed".format(attributeSet, entityTypeCode)
raise Exception(log)
def getAttributeMetadata(self, attributeCode, entityTypeCode):
self.adaptor.mySQLCursor.execute(self.ATTRIBUTEMETADATASQL, [attributeCode, entityTypeCode])
attributeMetadata = self.adaptor.mySQLCursor.fetchone()
if attributeMetadata is None or len(attributeMetadata) < 4 :
log = "Entity Type/Attribute Code: {0}/{1} does not exist".format(entityTypeCode, attributeCode)
raise Exception(log)
if attributeCode == 'url_key' and self.setting['VERSION'] == "EE":
dataType = attributeCode
else:
dataType = attributeMetadata['backend_type']
return (dataType, attributeMetadata)
def isEntityExit(self, entityTypeCode, entityId):
sql = self.ISENTITYEXITSQL.format(entityTypeCode)
self.adaptor.mySQLCursor.execute(sql, [entityId])
exist = self.adaptor.mySQLCursor.fetchone()
return exist['count']
def isAttributeValueExit(self, entityTypeCode, dataType, attributeId, storeId, entityId):
key = 'row_id' if self.setting['VERSION'] == "EE" else 'entity_id'
sql = self.ISATTRIBUTEVALUEEXITSQL.format(entityTypeCode, dataType, key)
self.adaptor.mySQLCursor.execute(sql, [attributeId, storeId, entityId])
exist = self.adaptor.mySQLCursor.fetchone()
return exist['count']
def replaceAttributeValue(self, entityTypeCode, dataType, entityId, attributeId, value, storeId=0):
if entityTypeCode == 'catalog_product' or entityTypeCode == 'catalog_category':
cols = "entity_id, attribute_id, store_id, value"
if self.setting['VERSION'] == "EE":
cols = "row_id, attribute_id, store_id, value"
vls = "%s, %s, {0}, %s".format(storeId)
param = [entityId, attributeId, value]
else:
cols = "entity_id, attribute_id, value"
vls = "%s, %s, %s"
param = [entityId, attributeId, value]
sql = self.REPLACEATTRIBUTEVALUESQL.format(entityTypeCode, dataType, cols, vls)
self.adaptor.mySQLCursor.execute("SET FOREIGN_KEY_CHECKS = 0")
self.adaptor.mySQLCursor.execute(sql, param)
self.adaptor.mySQLCursor.execute("SET FOREIGN_KEY_CHECKS = 1")
def updateEntityUpdatedAt(self, entityTypeCode, entityId):
sql = self.UPDATEENTITYUPDATEDATSQL.format(entityTypeCode)
self.adaptor.mySQLCursor.execute(sql, [entityId])
def setAttributeOptionValues(self, attributeId, options, entityTypeCode="catalog_product", adminStoreId=0, updateExistingOption=False):
optionId = self.getOptionId(attributeId, options[adminStoreId], adminStoreId)
if optionId is None:
self.adaptor.mySQLCursor.execute(self.INSERTEAVATTRIBUTEOPTIONSQL, [attributeId])
optionId = self.adaptor.mySQLCursor.lastrowid
for (storeId, optionValue) in options.items():
self.adaptor.mySQLCursor.execute(self.OPTIONVALUEEXISTSQL, [optionId, storeId])
exist = self.adaptor.mySQLCursor.fetchone()
if not exist or exist['cnt'] == 0 :
self.adaptor.mySQLCursor.execute(self.INSERTOPTIONVALUESQL, [optionId, storeId, optionValue])
elif exist['cnt'] >0 and updateExistingOption == True:
self.adaptor.mySQLCursor.execute(self.UPDATEOPTIONVALUESQL, [optionValue, optionId, storeId])
return optionId
def setMultiSelectOptionIds(self, attributeId, values, entityTypeCode="catalog_product", adminStoreId=0, delimiter="|"):
values = values.strip('"').strip("'").strip("\n").strip()
listValues = [v.strip() for v in values.split(delimiter)]
listOptionIds = []
for value in listValues:
options = {0: value}
optionId = self.setAttributeOptionValues(attributeId, options, entityTypeCode=entityTypeCode, adminStoreId=adminStoreId)
listOptionIds.append(str(optionId))
optionIds = ",".join(listOptionIds) if len(listOptionIds) > 0 else None
return optionIds
def getOptionId(self, attributeId, value, adminStoreId=0):
self.adaptor.mySQLCursor.execute(self.GETOPTIONIDSQL, [attributeId, value, adminStoreId])
res = self.adaptor.mySQLCursor.fetchone()
optionId = None
if res is not None:
optionId = res['option_id']
return optionId
def getMultiSelectOptionIds(self, attributeId, values, adminStoreId=0, delimiter="|"):
if values is None:
return [None]
values = values.strip('"').strip("'").strip("\n").strip()
listValues = [v.strip() for v in values.split(delimiter)]
listOptionIds = []
for value in listValues:
optionId = self.getOptionId(attributeId, value, adminStoreId=adminStoreId)
listOptionIds.append(str(optionId))
optionIds = ",".join(listOptionIds) if len(listOptionIds) > 0 else None
| |
"""
Base class for gdb-remote test cases.
"""
from __future__ import division, print_function
import errno
import os
import os.path
import random
import re
import select
import socket
import subprocess
import sys
import tempfile
import time
from lldbsuite.test import configuration
from lldbsuite.test.lldbtest import *
from lldbsuite.support import seven
from lldbgdbserverutils import *
import logging
class _ConnectionRefused(IOError):
pass
class GdbRemoteTestCaseFactory(type):
def __new__(cls, name, bases, attrs):
newattrs = {}
for attrname, attrvalue in attrs.items():
if not attrname.startswith("test"):
newattrs[attrname] = attrvalue
continue
# If any debug server categories were explicitly tagged, assume
# that list to be authoritative. If none were specified, try
# all of them.
all_categories = set(["debugserver", "llgs"])
categories = set(
getattr(attrvalue, "categories", [])) & all_categories
if not categories:
categories = all_categories
for cat in categories:
@decorators.add_test_categories([cat])
@wraps(attrvalue)
def test_method(self, attrvalue=attrvalue):
return attrvalue(self)
method_name = attrname + "_" + cat
test_method.__name__ = method_name
test_method.debug_server = cat
newattrs[method_name] = test_method
return super(GdbRemoteTestCaseFactory, cls).__new__(
cls, name, bases, newattrs)
@add_metaclass(GdbRemoteTestCaseFactory)
class GdbRemoteTestCaseBase(Base):
# Default time out in seconds. The timeout is increased tenfold under Asan.
DEFAULT_TIMEOUT = 20 * (10 if ('ASAN_OPTIONS' in os.environ) else 1)
# Default sleep time in seconds. The sleep time is doubled under Asan.
DEFAULT_SLEEP = 5 * (2 if ('ASAN_OPTIONS' in os.environ) else 1)
_GDBREMOTE_KILL_PACKET = b"$k#6b"
# Start the inferior separately, attach to the inferior on the stub
# command line.
_STARTUP_ATTACH = "attach"
# Start the inferior separately, start the stub without attaching, allow
# the test to attach to the inferior however it wants (e.g. $vAttach;pid).
_STARTUP_ATTACH_MANUALLY = "attach_manually"
# Start the stub, and launch the inferior with an $A packet via the
# initial packet stream.
_STARTUP_LAUNCH = "launch"
# GDB Signal numbers that are not target-specific used for common
# exceptions
TARGET_EXC_BAD_ACCESS = 0x91
TARGET_EXC_BAD_INSTRUCTION = 0x92
TARGET_EXC_ARITHMETIC = 0x93
TARGET_EXC_EMULATION = 0x94
TARGET_EXC_SOFTWARE = 0x95
TARGET_EXC_BREAKPOINT = 0x96
_verbose_log_handler = None
_log_formatter = logging.Formatter(
fmt='%(asctime)-15s %(levelname)-8s %(message)s')
def setUpBaseLogging(self):
self.logger = logging.getLogger(__name__)
if len(self.logger.handlers) > 0:
return # We have set up this handler already
self.logger.propagate = False
self.logger.setLevel(logging.DEBUG)
# log all warnings to stderr
handler = logging.StreamHandler()
handler.setLevel(logging.WARNING)
handler.setFormatter(self._log_formatter)
self.logger.addHandler(handler)
def isVerboseLoggingRequested(self):
# We will report our detailed logs if the user requested that the "gdb-remote" channel is
# logged.
return any(("gdb-remote" in channel)
for channel in lldbtest_config.channels)
def getDebugServer(self):
method = getattr(self, self.testMethodName)
return getattr(method, "debug_server", None)
def setUp(self):
super(GdbRemoteTestCaseBase, self).setUp()
self.setUpBaseLogging()
self.debug_monitor_extra_args = []
if self.isVerboseLoggingRequested():
# If requested, full logs go to a log file
self._verbose_log_handler = logging.FileHandler(
self.getLogBasenameForCurrentTest() + "-host.log")
self._verbose_log_handler.setFormatter(self._log_formatter)
self._verbose_log_handler.setLevel(logging.DEBUG)
self.logger.addHandler(self._verbose_log_handler)
self.test_sequence = GdbRemoteTestSequence(self.logger)
self.set_inferior_startup_launch()
self.port = self.get_next_port()
self.stub_sends_two_stop_notifications_on_kill = False
if configuration.lldb_platform_url:
if configuration.lldb_platform_url.startswith('unix-'):
url_pattern = '(.+)://\[?(.+?)\]?/.*'
else:
url_pattern = '(.+)://(.+):\d+'
scheme, host = re.match(
url_pattern, configuration.lldb_platform_url).groups()
if configuration.lldb_platform_name == 'remote-android' and host != 'localhost':
self.stub_device = host
self.stub_hostname = 'localhost'
else:
self.stub_device = None
self.stub_hostname = host
else:
self.stub_hostname = "localhost"
debug_server = self.getDebugServer()
if debug_server == "debugserver":
self._init_debugserver_test()
else:
self._init_llgs_test()
def tearDown(self):
self.logger.removeHandler(self._verbose_log_handler)
self._verbose_log_handler = None
TestBase.tearDown(self)
def build(self, *args, **kwargs):
self.buildDefault(*args, **kwargs)
def getLocalServerLogFile(self):
return self.getLogBasenameForCurrentTest() + "-server.log"
def setUpServerLogging(self, is_llgs):
if len(lldbtest_config.channels) == 0:
return # No logging requested
if lldb.remote_platform:
log_file = lldbutil.join_remote_paths(
lldb.remote_platform.GetWorkingDirectory(), "server.log")
else:
log_file = self.getLocalServerLogFile()
if is_llgs:
self.debug_monitor_extra_args.append("--log-file=" + log_file)
self.debug_monitor_extra_args.append(
"--log-channels={}".format(":".join(lldbtest_config.channels)))
else:
self.debug_monitor_extra_args = [
"--log-file=" + log_file, "--log-flags=0x800000"]
def get_next_port(self):
return 12000 + random.randint(0, 3999)
def reset_test_sequence(self):
self.test_sequence = GdbRemoteTestSequence(self.logger)
def _init_llgs_test(self):
reverse_connect = True
if lldb.remote_platform:
# Reverse connections may be tricky due to firewalls/NATs.
reverse_connect = False
# FIXME: This is extremely linux-oriented
# Grab the ppid from /proc/[shell pid]/stat
err, retcode, shell_stat = self.run_platform_command(
"cat /proc/$$/stat")
self.assertTrue(
err.Success() and retcode == 0,
"Failed to read file /proc/$$/stat: %s, retcode: %d" %
(err.GetCString(),
retcode))
# [pid] ([executable]) [state] [*ppid*]
pid = re.match(r"^\d+ \(.+\) . (\d+)", shell_stat).group(1)
err, retcode, ls_output = self.run_platform_command(
"ls -l /proc/%s/exe" % pid)
self.assertTrue(
err.Success() and retcode == 0,
"Failed to read file /proc/%s/exe: %s, retcode: %d" %
(pid,
err.GetCString(),
retcode))
exe = ls_output.split()[-1]
# If the binary has been deleted, the link name has " (deleted)" appended.
# Remove if it's there.
self.debug_monitor_exe = re.sub(r' \(deleted\)$', '', exe)
else:
self.debug_monitor_exe = get_lldb_server_exe()
self.debug_monitor_extra_args = ["gdbserver"]
self.setUpServerLogging(is_llgs=True)
self.reverse_connect = reverse_connect
def _init_debugserver_test(self):
self.debug_monitor_exe = get_debugserver_exe()
self.setUpServerLogging(is_llgs=False)
self.reverse_connect = True
# The debugserver stub has a race on handling the 'k' command, so it sends an X09 right away, then sends the real X notification
# when the process truly dies.
self.stub_sends_two_stop_notifications_on_kill = True
def forward_adb_port(self, source, target, direction, device):
adb = ['adb'] + (['-s', device] if device else []) + [direction]
def remove_port_forward():
subprocess.call(adb + ["--remove", "tcp:%d" % source])
subprocess.call(adb + ["tcp:%d" % source, "tcp:%d" % target])
self.addTearDownHook(remove_port_forward)
def _verify_socket(self, sock):
# Normally, when the remote stub is not ready, we will get ECONNREFUSED during the
# connect() attempt. However, due to the way how ADB forwarding works, on android targets
# the connect() will always be successful, but the connection will be immediately dropped
# if ADB could not connect on the remote side. This function tries to detect this
# situation, and report it as "connection refused" so that the upper layers attempt the
# connection again.
triple = self.dbg.GetSelectedPlatform().GetTriple()
if not re.match(".*-.*-.*-android", triple):
return # Not android.
can_read, _, _ = select.select([sock], [], [], 0.1)
if sock not in can_read:
return # Data is not available, but the connection is alive.
if len(sock.recv(1, socket.MSG_PEEK)) == 0:
raise _ConnectionRefused() # Got EOF, connection dropped.
def create_socket(self):
try:
sock = socket.socket(family=socket.AF_INET)
except OSError as e:
if e.errno != errno.EAFNOSUPPORT:
raise
sock = socket.socket(family=socket.AF_INET6)
logger = self.logger
triple = self.dbg.GetSelectedPlatform().GetTriple()
if re.match(".*-.*-.*-android", triple):
self.forward_adb_port(
self.port,
self.port,
"forward",
self.stub_device)
logger.info(
"Connecting to debug monitor on %s:%d",
self.stub_hostname,
self.port)
connect_info = (self.stub_hostname, self.port)
try:
sock.connect(connect_info)
except socket.error as serr:
if serr.errno == errno.ECONNREFUSED:
raise _ConnectionRefused()
raise serr
def shutdown_socket():
if sock:
try:
# send the kill packet so lldb-server shuts down gracefully
sock.sendall(GdbRemoteTestCaseBase._GDBREMOTE_KILL_PACKET)
except:
logger.warning(
"failed to send kill packet to debug monitor: {}; ignoring".format(
sys.exc_info()[0]))
try:
sock.close()
except:
logger.warning(
"failed to close socket to debug monitor: {}; ignoring".format(
sys.exc_info()[0]))
self.addTearDownHook(shutdown_socket)
self._verify_socket(sock)
return sock
def set_inferior_startup_launch(self):
self._inferior_startup = self._STARTUP_LAUNCH
def set_inferior_startup_attach(self):
self._inferior_startup = self._STARTUP_ATTACH
def set_inferior_startup_attach_manually(self):
self._inferior_startup = self._STARTUP_ATTACH_MANUALLY
def get_debug_monitor_command_line_args(self, attach_pid=None):
commandline_args = self.debug_monitor_extra_args
if attach_pid:
commandline_args += ["--attach=%d" % attach_pid]
if self.reverse_connect:
commandline_args += ["--reverse-connect", self.connect_address]
else:
if lldb.remote_platform:
commandline_args += ["*:{}".format(self.port)]
else:
commandline_args += ["localhost:{}".format(self.port)]
return commandline_args
def get_target_byte_order(self):
inferior_exe_path = self.getBuildArtifact("a.out")
target = self.dbg.CreateTarget(inferior_exe_path)
return target.GetByteOrder()
def launch_debug_monitor(self, attach_pid=None, logfile=None):
if self.reverse_connect:
family, type, proto, _, addr = socket.getaddrinfo("localhost", 0, proto=socket.IPPROTO_TCP)[0]
sock = socket.socket(family, type, proto)
sock.settimeout(self.DEFAULT_TIMEOUT)
sock.bind(addr)
sock.listen(1)
addr = sock.getsockname()
self.connect_address = "[{}]:{}".format(*addr)
# Create the command line.
commandline_args = self.get_debug_monitor_command_line_args(
attach_pid=attach_pid)
# Start the server.
server = self.spawnSubprocess(
self.debug_monitor_exe,
commandline_args,
install_remote=False)
self.assertIsNotNone(server)
if self.reverse_connect:
self.sock = sock.accept()[0]
self.sock.settimeout(self.DEFAULT_TIMEOUT)
return server
def connect_to_debug_monitor(self, attach_pid=None):
if self.reverse_connect:
# Create the stub.
server = self.launch_debug_monitor(attach_pid=attach_pid)
self.assertIsNotNone(server)
# Schedule debug monitor to be shut down during teardown.
logger = self.logger
self._server = Server(self.sock, server)
return server
# We're using a random port algorithm to try not to collide with other ports,
# and retry a max # times.
attempts = 0
MAX_ATTEMPTS = 20
while attempts < MAX_ATTEMPTS:
server = self.launch_debug_monitor(attach_pid=attach_pid)
# Schedule debug monitor to be shut down during teardown.
logger = self.logger
connect_attemps = 0
MAX_CONNECT_ATTEMPTS = 10
while connect_attemps < MAX_CONNECT_ATTEMPTS:
# Create a socket to talk to the server
try:
logger.info("Connect attempt %d", connect_attemps + 1)
self.sock = self.create_socket()
self._server = Server(self.sock, server)
return server
except _ConnectionRefused as serr:
# Ignore, and try again.
pass
time.sleep(0.5)
connect_attemps += 1
# We should close the server here to be safe.
server.terminate()
# Increment attempts.
print(
"connect to debug monitor on port %d failed, attempt #%d of %d" %
(self.port, attempts + 1, MAX_ATTEMPTS))
attempts += 1
# And wait a random length of time before next attempt, to avoid
# collisions.
time.sleep(random.randint(1, 5))
# Now grab a new port number.
self.port = self.get_next_port()
raise Exception(
"failed to | |
<reponame>miguelsousa/robothon
# pylint: disable-msg=E1002
"""MA: a facility for dealing with missing observations
MA is generally used as a numpy.array look-alike.
by <NAME>.
Copyright 1999, 2000, 2001 Regents of the University of California.
Released for unlimited redistribution.
Adapted for numpy_core 2005 by <NAME> and
(mainly) <NAME>.
Subclassing of the base ndarray 2006 by <NAME>.
pgmdevlist_AT_gmail_DOT_com
Improvements suggested by <NAME> (reggie_AT_merfinllc_DOT_com)
:author: <NAME>
:contact: pierregm_at_uga_dot_edu
"""
__author__ = "<NAME>"
__docformat__ = "restructuredtext en"
__all__ = ['MAError', 'MaskType', 'MaskedArray',
'bool_', 'complex_', 'float_', 'int_', 'object_',
'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue',
'amax', 'amin', 'anom', 'anomalies', 'any', 'arange',
'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2',
'arctanh', 'argmax', 'argmin', 'argsort', 'around',
'array', 'asarray','asanyarray',
'bitwise_and', 'bitwise_or', 'bitwise_xor',
'ceil', 'choose', 'clip', 'common_fill_value', 'compress',
'compressed', 'concatenate', 'conjugate', 'cos', 'cosh', 'count',
'default_fill_value', 'diagonal', 'divide', 'dump', 'dumps',
'empty', 'empty_like', 'equal', 'exp',
'fabs', 'fmod', 'filled', 'floor', 'floor_divide','fix_invalid',
'frombuffer', 'fromfunction',
'getdata','getmask', 'getmaskarray', 'greater', 'greater_equal',
'hypot',
'identity', 'ids', 'indices', 'inner', 'innerproduct',
'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray',
'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log10',
'logical_and', 'logical_not', 'logical_or', 'logical_xor',
'make_mask', 'make_mask_descr', 'make_mask_none', 'mask_or', 'masked',
'masked_array', 'masked_equal', 'masked_greater',
'masked_greater_equal', 'masked_inside', 'masked_invalid',
'masked_less','masked_less_equal', 'masked_not_equal',
'masked_object','masked_outside', 'masked_print_option',
'masked_singleton','masked_values', 'masked_where', 'max', 'maximum',
'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value',
'multiply',
'negative', 'nomask', 'nonzero', 'not_equal',
'ones', 'outer', 'outerproduct',
'power', 'product', 'ptp', 'put', 'putmask',
'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize',
'right_shift', 'round_',
'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'sometrue', 'sort',
'sqrt', 'std', 'subtract', 'sum', 'swapaxes',
'take', 'tan', 'tanh', 'transpose', 'true_divide',
'var', 'where',
'zeros']
import cPickle
import operator
import numpy as np
from numpy import ndarray, amax, amin, iscomplexobj, bool_, complex_, float_,\
int_, object_
from numpy import array as narray
import numpy.core.umath as umath
import numpy.core.numerictypes as ntypes
from numpy import expand_dims as n_expand_dims
import warnings
MaskType = np.bool_
nomask = MaskType(0)
np.seterr(all='ignore')
def doc_note(initialdoc, note):
if initialdoc is None:
return
newdoc = """
%s
Notes
-----
%s
"""
return newdoc % (initialdoc, note)
#####--------------------------------------------------------------------------
#---- --- Exceptions ---
#####--------------------------------------------------------------------------
class MAError(Exception):
"Class for MA related errors."
def __init__ (self, args=None):
"Creates an exception."
Exception.__init__(self, args)
self.args = args
def __str__(self):
"Calculates the string representation."
return str(self.args)
__repr__ = __str__
#####--------------------------------------------------------------------------
#---- --- Filling options ---
#####--------------------------------------------------------------------------
# b: boolean - c: complex - f: floats - i: integer - O: object - S: string
default_filler = {'b': True,
'c' : 1.e20 + 0.0j,
'f' : 1.e20,
'i' : 999999,
'O' : '?',
'S' : 'N/A',
'u' : 999999,
'V' : '???',
}
max_filler = ntypes._minvals
max_filler.update([(k, -np.inf) for k in [np.float32, np.float64]])
min_filler = ntypes._maxvals
min_filler.update([(k, +np.inf) for k in [np.float32, np.float64]])
if 'float128' in ntypes.typeDict:
max_filler.update([(np.float128, -np.inf)])
min_filler.update([(np.float128, +np.inf)])
def default_fill_value(obj):
"""Calculate the default fill value for the argument object.
"""
if hasattr(obj,'dtype'):
defval = default_filler[obj.dtype.kind]
elif isinstance(obj, np.dtype):
if obj.subdtype:
defval = default_filler[obj.subdtype[0].kind]
else:
defval = default_filler[obj.kind]
elif isinstance(obj, float):
defval = default_filler['f']
elif isinstance(obj, int) or isinstance(obj, long):
defval = default_filler['i']
elif isinstance(obj, str):
defval = default_filler['S']
elif isinstance(obj, complex):
defval = default_filler['c']
else:
defval = default_filler['O']
return defval
def minimum_fill_value(obj):
"""Calculate the default fill value suitable for taking the
minimum of ``obj``.
"""
if hasattr(obj, 'dtype'):
objtype = obj.dtype
filler = min_filler[objtype]
if filler is None:
raise TypeError, 'Unsuitable type for calculating minimum.'
return filler
elif isinstance(obj, float):
return min_filler[ntypes.typeDict['float_']]
elif isinstance(obj, int):
return min_filler[ntypes.typeDict['int_']]
elif isinstance(obj, long):
return min_filler[ntypes.typeDict['uint']]
elif isinstance(obj, np.dtype):
return min_filler[obj]
else:
raise TypeError, 'Unsuitable type for calculating minimum.'
def maximum_fill_value(obj):
"""Calculate the default fill value suitable for taking the maximum
of ``obj``.
"""
if hasattr(obj, 'dtype'):
objtype = obj.dtype
filler = max_filler[objtype]
if filler is None:
raise TypeError, 'Unsuitable type for calculating minimum.'
return filler
elif isinstance(obj, float):
return max_filler[ntypes.typeDict['float_']]
elif isinstance(obj, int):
return max_filler[ntypes.typeDict['int_']]
elif isinstance(obj, long):
return max_filler[ntypes.typeDict['uint']]
elif isinstance(obj, np.dtype):
return max_filler[obj]
else:
raise TypeError, 'Unsuitable type for calculating minimum.'
def _check_fill_value(fill_value, ndtype):
ndtype = np.dtype(ndtype)
fields = ndtype.fields
if fill_value is None:
if fields:
fdtype = [(_[0], _[1]) for _ in ndtype.descr]
fill_value = np.array(tuple([default_fill_value(fields[n][0])
for n in ndtype.names]),
dtype=fdtype)
else:
fill_value = default_fill_value(ndtype)
elif fields:
fdtype = [(_[0], _[1]) for _ in ndtype.descr]
if isinstance(fill_value, ndarray):
try:
fill_value = np.array(fill_value, copy=False, dtype=fdtype)
except ValueError:
err_msg = "Unable to transform %s to dtype %s"
raise ValueError(err_msg % (fill_value,fdtype))
else:
fval = np.resize(fill_value, len(ndtype.descr))
fill_value = [np.asarray(f).astype(desc[1]).item()
for (f, desc) in zip(fval, ndtype.descr)]
fill_value = np.array(tuple(fill_value), copy=False, dtype=fdtype)
else:
if isinstance(fill_value, basestring) and (ndtype.char not in 'SV'):
fill_value = default_fill_value(ndtype)
else:
# In case we want to convert 1e+20 to int...
try:
fill_value = np.array(fill_value, copy=False, dtype=ndtype).item()
except OverflowError:
fill_value = default_fill_value(ndtype)
return fill_value
def set_fill_value(a, fill_value):
"""Set the filling value of a, if a is a masked array. Otherwise,
do nothing.
Returns
-------
None
"""
if isinstance(a, MaskedArray):
a._fill_value = _check_fill_value(fill_value, a.dtype)
return
def get_fill_value(a):
"""Return the filling value of a, if any. Otherwise, returns the
default filling value for that type.
"""
if isinstance(a, MaskedArray):
result = a.fill_value
else:
result = default_fill_value(a)
return result
def common_fill_value(a, b):
"""Return the common filling value of a and b, if any.
If a and b have different filling values, returns None.
"""
t1 = get_fill_value(a)
t2 = get_fill_value(b)
if t1 == t2:
return t1
return None
#####--------------------------------------------------------------------------
def filled(a, value = None):
"""Return a as an array with masked data replaced by value. If
value is None, get_fill_value(a) is used instead. If a is already
a ndarray, a itself is returned.
Parameters
----------
a : maskedarray or array_like
An input object.
value : {var}, optional
Filling value. If not given, the output of get_fill_value(a)
is used instead.
Returns
-------
a : array_like
"""
if hasattr(a, 'filled'):
return a.filled(value)
elif isinstance(a, ndarray):
# Should we check for contiguity ? and a.flags['CONTIGUOUS']:
return a
elif isinstance(a, dict):
return np.array(a, 'O')
else:
return np.array(a)
#####--------------------------------------------------------------------------
def get_masked_subclass(*arrays):
"""Return the youngest subclass of MaskedArray from a list of
(masked) arrays. In case of siblings, the first takes over.
"""
if len(arrays) == 1:
arr = arrays[0]
if isinstance(arr, MaskedArray):
rcls = type(arr)
else:
rcls = MaskedArray
else:
arrcls = [type(a) for a in arrays]
rcls = arrcls[0]
if not issubclass(rcls, MaskedArray):
rcls = MaskedArray
for cls in arrcls[1:]:
if issubclass(cls, rcls):
rcls = cls
return rcls
#####--------------------------------------------------------------------------
def get_data(a, subok=True):
"""Return the _data part of a (if any), or a as a ndarray.
Parameters
----------
a : array_like
A ndarray or a subclass of.
subok : bool
Whether to force the output to a 'pure' ndarray (False) or to
return a subclass of ndarray if approriate (True).
"""
data = getattr(a, '_data', np.array(a, subok=subok))
if not subok:
return data.view(ndarray)
return data
getdata = get_data
def fix_invalid(a, mask=nomask, copy=True, fill_value=None):
"""Return (a copy of) a where invalid data (nan/inf) are masked
and replaced by fill_value.
Note that a copy is performed by default (just in case...).
Parameters
----------
a : array_like
A (subclass of) ndarray.
copy : bool
Whether to use a copy of a (True) or to fix a in place (False).
fill_value : {var}, optional
Value used for fixing invalid data. If not given, the output
of get_fill_value(a) is used instead.
Returns
-------
b : MaskedArray
"""
a = masked_array(a, copy=copy, mask=mask, subok=True)
#invalid = (numpy.isnan(a._data) | numpy.isinf(a._data))
invalid = np.logical_not(np.isfinite(a._data))
if not invalid.any():
return a
a._mask |= invalid
if fill_value is None:
fill_value = a.fill_value
a._data[invalid] = fill_value
return a
#####--------------------------------------------------------------------------
#---- --- Ufuncs ---
#####--------------------------------------------------------------------------
ufunc_domain = {}
ufunc_fills = {}
class _DomainCheckInterval:
"""Define a valid interval, so that :
``domain_check_interval(a,b)(x) = true`` where
``x < a`` or ``x > b``.
"""
def __init__(self, a, b):
"domain_check_interval(a,b)(x) = true where x < a or y > b"
if (a > b):
(a, b) = (b, a)
self.a = a
self.b = b
def __call__ (self, x):
"Execute the call behavior."
return umath.logical_or(umath.greater (x, self.b),
umath.less(x, self.a))
#............................
class _DomainTan:
"""Define a valid interval for the `tan` function, so that:
``domain_tan(eps) = True`` where ``abs(cos(x)) < eps``
"""
def __init__(self, eps):
"domain_tan(eps) = true where abs(cos(x)) < eps)"
self.eps = eps
def __call__ (self, x):
"Executes the call behavior."
return umath.less(umath.absolute(umath.cos(x)), self.eps)
#............................
class _DomainSafeDivide:
"""Define a domain for safe division."""
def __init__ (self, tolerance=None):
self.tolerance = tolerance
def __call__ (self, a, b):
# Delay the selection of the tolerance to here in order to reduce numpy
# import times. The calculation of these parameters | |
#!/usr/bin/env python3
"""
This module contains the make-toc function which tries to create a
valid table of contents file for SE projects.
Strictly speaking, the generate_toc() function should be a class member of SeEpub. But
the function is very big and it makes editing easier to put in a separate file.
"""
from enum import Enum
from pathlib import Path
from typing import Tuple, List
import regex
from lxml import etree
import se
import se.formatting
import se.easy_xml
from se.easy_xml import EasyXmlTree, EasyXmlElement
class BookDivision(Enum):
"""
Enum to indicate the division of a particular ToC item.
"""
NONE = 0
ARTICLE = 1
SUBCHAPTER = 2
CHAPTER = 3
DIVISION = 4
PART = 5
VOLUME = 6
class Position(Enum):
"""
Enum to indicate whether a landmark is frontmatter, bodymatter or backmatter.
"""
NONE = 0
FRONT = 1
BODY = 2
BACK = 3
class TocItem:
"""
Small class to hold data on each table of contents item
found in the project.
"""
# pylint: disable=too-many-instance-attributes
file_link = ""
level = 0
roman = ""
title = ""
subtitle = ""
title_is_ordinal = False
lang = ""
id = ""
epub_type = ""
division = BookDivision.NONE
place = Position.FRONT
@property
def toc_link(self) -> str:
"""
Generates the hyperlink for the ToC item.
INPUTS:
None
OUTPUTS:
the linking tag line eg <a href=... depending on the data found.
"""
out_string = ""
if not self.title:
raise se.InvalidInputException(f"Couldn't find title in: [path][link=file://{self.file_link}]{self.file_link}[/][/].")
if self.subtitle and self.lang:
# test for a foreign language subtitle, and adjust accordingly
self.subtitle = f"<span xml:lang=\"{self.lang}\">{self.subtitle}</span>"
# If the title is entirely Roman numeral, put epub:type within <a>.
if regex.search(r"^<span epub:type=\"z3998:roman\">[IVXLC]+<\/span>$", self.title):
# title is a pure roman number
if self.subtitle == "": # put the roman flag inside the <a> tag
out_string += f"<a href=\"text/{self.file_link}\" epub:type=\"z3998:roman\">{self.roman}</a>\n"
else:
out_string += f"<a href=\"text/{self.file_link}\"><span epub:type=\"z3998:roman\">{self.roman}</span>: {self.subtitle}</a>\n"
else:
# title has text other than a roman numeral
if self.subtitle != "" and (self.title_is_ordinal or (self.division in [BookDivision.PART, BookDivision.DIVISION, BookDivision.VOLUME])):
# Use the subtitle only if we're a Part or Division or Volume or if title was an ordinal
out_string += f"<a href=\"text/{self.file_link}\">{self.title}"
# Don't append a colon if the ordinal already ends in punctuation, for example `1.` or `(a)`
if not regex.search(r"\p{Punctuation}$", self.title):
out_string += ":"
out_string += f" {self.subtitle}</a>\n"
else:
# test for a foreign language title, and adjust accordingly
if self.lang:
out_string += f"<a href=\"text/{self.file_link}\" xml:lang=\"{self.lang}\">{self.title}</a>\n"
else:
out_string += f"<a href=\"text/{self.file_link}\">{self.title}</a>\n"
return out_string
def landmark_link(self, work_type: str = "fiction", work_title: str = "WORK_TITLE"):
"""
Generates the landmark item (including list item tags) for the ToC item
INPUTS:
work_type: ("fiction" or "non-fiction")
work_title: the title of the book, eg "<NAME>"
OUTPUTS:
the linking string to be included in landmarks section.
"""
out_string = ""
if self.place == Position.FRONT:
out_string = f"<li>\n<a href=\"text/{self.file_link}\" epub:type=\"frontmatter {self.epub_type}\">{self.title}</a>\n</li>\n"
if self.place == Position.BODY:
out_string = f"<li>\n<a href=\"text/{self.file_link}\" epub:type=\"bodymatter z3998:{work_type}\">{work_title}</a>\n</li>\n"
if self.place == Position.BACK:
out_string = f"<li>\n<a href=\"text/{self.file_link}\" epub:type=\"backmatter {self.epub_type}\">{self.title}</a>\n</li>\n"
return out_string
def get_place(node: EasyXmlElement) -> Position:
"""
Returns place of file in ebook, eg frontmatter, backmatter, etc.
INPUTS:
node: EasyXmlElement representation of the file
OUTPUTS:
a Position enum value indicating the place in the book
"""
epub_type = node.get_attr("epub:type")
if not epub_type:
return Position.NONE
if "backmatter" in epub_type:
retval = Position.BACK
elif "frontmatter" in epub_type:
retval = Position.FRONT
elif "bodymatter" in epub_type:
retval = Position.BODY
else:
retval = Position.NONE
return retval
def add_landmark(dom: EasyXmlTree, textf: str, landmarks: list):
"""
Adds an item to landmark list with appropriate details.
INPUTS:
dom: EasyXmlTree representation of the file we are indexing in ToC
textf: path to the file
landmarks: the list of landmark items we are building
OUTPUTS:
None
"""
epub_type = ""
sections = dom.xpath("//body/*[name() = 'section' or name() = 'article']")
if not sections:
raise se.InvalidInputException("Couldn't locate first section")
epub_type = sections[0].get_attr("epub:type")
bodys = dom.xpath("//body")
if not bodys:
raise se.InvalidInputException("Couldn't locate body")
if not epub_type: # some productions don't have an epub:type in outermost section, so get it from body tag
epub_type = bodys[0].get_attr("epub:type")
if epub_type in ["frontmatter", "bodymatter", "backmatter"]:
return # if epub_type is ONLY frontmatter, bodymatter, backmatter, we don't want this as a landmark
landmark = TocItem()
if epub_type:
landmark.epub_type = epub_type
landmark.file_link = textf
landmark.place = get_place(bodys[0])
if epub_type == "halftitlepage":
landmark.title = "Half Title"
else:
landmark.title = dom.xpath("//head/title/text()", True) # Use the page title as the landmark entry title.
if landmark.title is None:
# This is a bit desperate, use this only if there's no proper <title> tag in file.
landmark.title = landmark.epub_type.capitalize()
landmarks.append(landmark)
def process_landmarks(landmarks_list: list, work_type: str, work_title: str):
"""
Runs through all found landmark items and writes them to the toc file.
INPUTS:
landmarks_list: the completed list of landmark items
work_type: "fiction" or "non-fiction"
work_title: the title of the book
OUTPUTS:
None
"""
# we don't want frontmatter items to be included once we've started the body items
started_body = False
for item in landmarks_list:
if item.place == Position.BODY:
started_body = True
if started_body and item.place == Position.FRONT:
item.place = Position.NONE
front_items = [item for item in landmarks_list if item.place == Position.FRONT]
body_items = [item for item in landmarks_list if item.place == Position.BODY]
back_items = [item for item in landmarks_list if item.place == Position.BACK]
out_string = ""
for item in front_items:
out_string += item.landmark_link()
if body_items:
out_string += body_items[0].landmark_link(work_type, work_title) # Just the first bodymatter item.
for item in back_items:
out_string += item.landmark_link()
return out_string
def process_items(item_list: list) -> str:
"""
Runs through all found toc items and returns them as a string.
INPUTS:
item_list: list of ToC items
OUTPUTS:
A string representing (possibly nested) html lists of the structure of the ToC
"""
unclosed_ol = 0 # Keep track of how many ordered lists we open.
out_string = ""
# Process all but last item so we can look ahead.
for index in range(0, len(item_list) - 1): # Ignore very last item, which is a dummy.
this_item = item_list[index]
next_item = item_list[index + 1]
# Check to see if next item is at same, lower or higher level than us.
if next_item.level == this_item.level: # SIMPLE
out_string += "<li>\n"
out_string += this_item.toc_link
out_string += "</li>\n"
if next_item.level > this_item.level: # PARENT, start a new ol list
out_string += "<li>\n"
out_string += this_item.toc_link
out_string += "<ol>\n"
unclosed_ol += 1
if next_item.level < this_item.level: # LAST CHILD, close off the list
out_string += "<li>\n"
out_string += this_item.toc_link
out_string += "</li>\n" # Close off this item.
torepeat = this_item.level - next_item.level
while torepeat and unclosed_ol: # neither can go below zero
# We need to repeat a few times as may be jumping back from eg h5 to h2
out_string += "</ol>\n" # End of embedded list.
out_string += "</li>\n" # End of parent item.
unclosed_ol -= 1
torepeat -= 1
return out_string
def output_toc(item_list: list, landmark_list, toc_path: str, work_type: str, work_title: str) -> str:
"""
Outputs the contructed ToC based on the lists of items and landmarks found,
either to stdout or overwriting the existing ToC file
INPUTS:
item_list: list of ToC items (the first part of the ToC)
landmark_list: list of landmark items (the second part of the ToC)
work_type: "fiction" or "non-fiction"
work_title: the title of the book
OUTPUTS:
a html string representing the new ToC
"""
if len(item_list) < 2:
raise se.InvalidInputException("Too few ToC items found.")
try:
with open(toc_path, encoding="utf8") as file:
toc_dom = se.easy_xml.EasyXhtmlTree(file.read())
except Exception as ex:
raise se.InvalidInputException(f"Existing ToC not found. Exception: {ex}")
# There should be exactly two nav sections.
navs = toc_dom.xpath("//nav")
if len(navs) < 2:
raise se.InvalidInputException("Existing ToC has too few nav sections.")
# now remove and then re-add the ol sections to clear them
for nav in navs:
ols = nav.xpath("./ol") # just want the immediate ol children
for ol_item in ols:
ol_item.remove()
# this is ugly and stupid, but I can't figure out an easier way to do it
item_ol = EasyXmlElement(etree.Element("ol"), toc_dom.namespaces)
item_ol.lxml_element.text = "TOC_ITEMS"
navs[0].append(item_ol)
landmark_ol = EasyXmlElement(etree.Element("ol"), toc_dom.namespaces)
landmark_ol.lxml_element.text = "LANDMARK_ITEMS"
navs[1].append(landmark_ol)
xhtml = toc_dom.to_string()
xhtml = xhtml.replace("TOC_ITEMS", process_items(item_list))
xhtml = xhtml.replace("LANDMARK_ITEMS", process_landmarks(landmark_list, work_type, work_title))
return se.formatting.format_xhtml(xhtml)
def get_parent_id(hchild: EasyXmlElement) -> str:
"""
Climbs up the document tree looking for parent id in a <section> tag.
INPUTS:
hchild: a heading tag for which we want to find the parent id
OUTPUTS:
the id of the parent section
"""
# position() = 1 gets the nearest ancestor
parents = hchild.xpath("./ancestor::*[name() = 'section' or name() = 'article'][@id][position() = 1]")
if parents:
return parents[0].get_attr("id")
return ""
def extract_strings(node: EasyXmlElement) -> str:
"""
Returns string representation of a tag, ignoring linefeeds
INPUTS:
node: a tag as xpath node
OUTPUTS:
just the string contents of the tag
"""
out_string = node.inner_xml()
out_string = strip_notes(out_string)
return regex.sub(r"[\n\t]", "", out_string)
def process_headings(dom: EasyXmlTree, textf: str, toc_list: list, nest_under_halftitle: bool, single_file: bool):
"""
Find headings in current file and extract title data
into items added to toc_list.
INPUTS:
dom: an EasyXmlTree representation of the current file
textf: the path to the file
toc_list: the list of ToC items we are building
nest_under_halftitle: does this item need to be nested?
single_file: is there only a single content item in the production?
OUTPUTS:
None
"""
body = dom.xpath("//body")
place = Position.NONE
if body:
place = get_place(body[0])
else:
raise se.InvalidInputException("Couldn't locate body node")
is_toplevel = True
# Find all the hgroups and h1, h2 etc headings.
heads = dom.xpath("//hgroup | //h1 | //h2 | //h3 | //h4 | //h5 | //h6")
# special treatment where we can't find any header or hgroups
if not heads: # May be a dedication or an epigraph, with no heading tag.
if single_file and nest_under_halftitle:
# There's a halftitle, but only this one content file with no subsections,
# so leave out of ToC because the Toc | |
of the chief satellite (must be between 0 and 1)
cP : float
Power charging urgency constant. Higher values implies a lower
chance of the spacecraft transiting into charging mode at urgently
lower power levels.
Returns
-------
T : numpy.ndarray
Transition matrix of size (N+1) x (N+1), where N is the number of
deputy satellites and N+1 is the total number of states.
'''
epsilon = ( 1.0 - P ) ** cP
transition_matrix = ( 1.0 - epsilon ) * np.eye( n+1 )
transition_matrix[0 ,0] = 1.0
transition_matrix[1:,0] = epsilon
return transition_matrix
###############################################################################
###############################################################################
# Define the softmax rewards vector for this scenario.
def reward( P, cP, mu, charge_duration, slew_times ):
''' Immediate rewards vector; dynamic rewards that depend on power levels
and hallucinated slewing times for attitude control manoeuvres. Requires a
list of attitude manoeuvre slew times, therefore, the agent must first
perform a single bound hallucination prior to calling the rewards function
so as to determine the reward distribution.
Parameters
----------
n : int
Number of deputy satellites.
P : float
Power level of the chief satellite (must be between 0 and 1)
cP : float
Power charging urgency constant. Higher values implies a lower
chance of the spacecraft transiting into charging mode at urgently
lower power levels.
mu : float
Hyper-parameter for the soft-max implementation of the rewards.
charge_duration : float
Estimated duration required for charging the spacecraft.
slew_times : list
A list of length n of all the slew times required for the chief to
point to a deputy spacecraft.
Returns
-------
rewards_array : numpy.ndarray
Row vector of length (n+1), where first element corresponds to the
reward of charging, and subsequent elements correspond (in order)
to the reward of establishing links with the deputies.
'''
epsilon = ( 1.0 - max(0.0, P) ) ** cP
total_time = charge_duration + sum( slew_times )
slew_times = np.array( slew_times )
Rp = epsilon / math.exp( mu * ( charge_duration / total_time ) )
reward = [Rp]
for slew_time in slew_times:
if slew_time == 0.0:
reward.append(0.0)
else:
Rd = (1.0 - epsilon) / math.exp( mu * ( slew_time / total_time ) )
reward.append(Rd)
return np.array(reward)
###############################################################################
###############################################################################
# Define a function to perform a Bellman update.
def bellman_update( reward, gamma, transition, utility ):
'''Bellman equation update, for a specific action (bound to the transition
model based on that action).
Parameters
----------
reward : numpy.ndarray
Array of length (n+1), where n = number of deputy satellites.
gamma : float
Discount factor.
transition : numpy.ndarray
Matrix of length (n+1) x (n+1), where n = number of deputy satellites.
utility : numpy.ndarray
Utility, or value array, from the previous step.
Returns
-------
utility_update : numpy.ndarray
Updated utility, or value array.
'''
utility_update = reward + gamma * ( transition @ utility )
return utility_update
###############################################################################
###############################################################################
### ###
### Begin dynamics simulation for the random policy. ###
### ###
###############################################################################
###############################################################################
if mode == modes[0]:
# Hard rule-based charging
charge_cutoff = 0.2
# Select a random spacecraft
sDi = np.random.randint( 0, len(sDs) )
sD = sDs[ sDi ]
A = sDi + 1
# Initialise the time counter.
t = 0.0
while True:
# Get the reference, either sun-pointing or target deputy.
if A == 0:
dcmRN, wRN = targeting.reference_sun()
else:
dcmRN, wRN = targeting.reference_deputy( dt, sC, sD, dcmRN )
# Compute the feedback errors and control torques.
aBR, wBR, aBN, wBN, torq, intgErr = feedback.control_QRT( t, dt, ct,
Kp, Ki, Kd,
aBN, wBN,
wRN, dcmRN,
inertia,
torq,
intgErr )
# Update the positions and velocities of the spacecrafts
sC.twobody_propagate( dt )
for sDz in sDs:
sDz.twobody_propagate( dt )
# Update the time and power
t += dt
power -= pdrain
# Update matrices for plotting.
aBN_array = np.vstack( [aBN_array, aBN.q] )
aBR_array = np.vstack( [aBR_array, aBR.q] )
wBN_array = np.vstack( [wBN_array, np.append(wBN, norm(wBN))] )
wBR_array = np.vstack( [wBR_array, np.append(wBR, norm(wBR))] )
trq_array = np.vstack( [trq_array, np.append(torq, norm(torq))] )
# Break the while loop if action is sun-pointing and there are no more
# deputy spacecraft left to link to.
if A == 0 and len(sDs) == 0:
# print("In sun-pointing mode, but no deputies left. Exiting.")
# print("Time is ", str(t), "\n")
break
# Check if there is a need to re-select the spacecraft.
if sum(np.abs(aBR[1:])) < 0.001 and abs(aBR[0]) > 0.999:
# If the spacecraft is in sun-pointing mode, we need to let the
# simulation continue running until the charging time is complete.
# Once charging time is complete, then we bring the chief back
# into hallucination mode where it will begin search again.
if A == 0:
power = power + pdrain + pcharge
# Pick a deputy once the the battery charges to full.
if power >= 1.0:
sDi = np.random.randint( 0, len(sDs) )
sD = sDs [ sDi ]
A = sDi + 1
# print("Established sun pointing mode. Charge finished.")
# print("Now picking a random deputy ", str(A))
# print("Time is ", str(t), "\n")
torq = np.zeros(3) # Stop all torque for now.
dcmRN = np.eye(3) # Reset the reference DCM.
# If the spacecraft is in deputy-pointing mode, we need to drop
# the current deputy out of our current state space since our
# mission has been achieved. Then, we need to bring the chief into
# hallucination mode again so it will be able to pick a new action
# or a new deputy or possibly even into sun-pointing mode.
elif A != 0:
#print("Established communications with Deputy ", str(A))
del sDs[ sDi ]
if len(sDs) > 0:
# Pick a deputy if there is sufficient battery left.
if power > charge_cutoff:
sDi = np.random.randint( 0, len(sDs) )
sD = sDs [ sDi ]
A = sDi + 1
torq = np.zeros(3) # Stop all torque for now.
dcmRN = np.eye(3) # Reset the reference DCM.
# print("Sufficient power, picking deputy ", str(A))
# print("Time is ", str(t), "\n")
# Else, go into sun-pointing mode.
else:
sDi = None
sD = None
A = 0
torq = np.zeros(3) # Stop all torque for now.
dcmRN = np.eye(3) # Reset the reference DCM.
# print("Insufficient power, going into sun-pointing.")
# print("Time is ", str(t), "\n")
else:
# print("Finished random pointing scenario.")
# print("Time is ", str(t), "\n")
break
###############################################################################
###############################################################################
# if mode == modes[0]:
# plt.figure(1)
# plt.title("Body-to-Inertial Attitude (Quarternion)")
# plt.plot(aBN_array)
# plt.xlabel("Time (seconds)")
# plt.ylabel("Attitude Coordinate")
# plt.legend(["Q1", "Q2", "Q3", "Q4"])
# plt.grid()
# plt.figure(2)
# plt.title("Body-to-Reference Attitude (Quarternion)")
# plt.plot(aBR_array)
# plt.xlabel("Time (seconds)")
# plt.ylabel("Attitude Coordinate")
# plt.legend(["Q1", "Q2", "Q3", "Q4"])
# plt.grid()
# plt.figure(3)
# plt.title("Body-to-Inertial Angular Velocity (rad/s)")
# plt.plot(wBN_array)
# plt.xlabel("Time (seconds)")
# plt.ylabel("Omega Component")
# plt.legend(["wx", "wy", "wz", "Norm"])
# plt.grid()
# plt.figure(4)
# plt.title("Body-to-Reference Angular Velocity (rad/s)")
# plt.plot(wBR_array)
# plt.xlabel("Time (seconds)")
# plt.ylabel("Omega Component")
# plt.legend(["wX", "wY", "wZ", "Norm"])
# plt.grid()
# plt.figure(5)
# plt.title("Torque Distribution (N.m)")
# plt.plot(trq_array)
# plt.xlabel("Time (seconds)")
# plt.ylabel("Omega Component")
# plt.legend(["TX", "TY", "TZ", "Norm"])
# plt.grid()
###############################################################################
###############################################################################
### ###
### Begin dynamics simulation for greedy search. ###
### ###
###############################################################################
###############################################################################
if mode == modes[1]:
# Flag for hallucinating the dynamics to some depth in greedy search.
# This flag must be initialised before the while loop (important!).
hallucination_mode_on = True
# Begin a time counter.
t = 0.0
# Initialise a list of deputies that have been selected.
selected = []
# Begin dynamics and reinforcement learning simulation
while True:
| |
<filename>f3dasm/simulator/abaqus/abaqus_src/modelling/step.py
'''
Created on 2020-04-08 14:55:21
Last modified on 2020-04-22 16:06:23
Python 2.7.16
v0.1
@author: <NAME> (<EMAIL>)
Main goal
---------
Define abaqus steps.
References
----------
1. Simulia (2015). ABAQUS 2016: Scripting Reference Guide
'''
#%% imports
# abaqus
from abaqusConstants import (LANCZOS, DEFAULT, SOLVER_DEFAULT, OFF,
AUTOMATIC, NONE, DIRECT, RAMP, FULL_NEWTON,
PROPAGATED, LINEAR, ALL, DISPLACEMENT, ON,
AC_ON)
# standard library
import abc
#%% abstract classes
class Step(object):
__metaclass__ = abc.ABCMeta
def __init__(self, name, previous, model=None):
'''
Parameters
----------
name : str
previous : str
Previous step
model : abaqus mdb object
'''
self.name = name
self.previous = previous
# computations
if model:
self.create_step(model)
def create_step(self, model):
# get method
create_step = getattr(model, self.method_name)
# create step
create_step(name=self.name, previous=self.previous, **self.args)
#%% particular step definition
class StaticStep(Step):
method_name = 'StaticStep'
def __init__(self, name, previous='Initial', model=None, description='',
timePeriod=1., nlgeom=OFF, stabilizationMethod=NONE,
stabilizationMagnitude=2e-4, adiabatic=OFF,
timeIncrementationMethod=AUTOMATIC, maxNumInc=100,
initialInc=None, minInc=None, maxInc=None,
matrixSolver=DIRECT, matrixStorage=SOLVER_DEFAULT,
amplitude=RAMP, extrapolation=LINEAR, fullyPlastic='',
noStop=OFF, maintainAttributes=False,
useLongTermSolution=OFF, solutionTechnique=FULL_NEWTON,
reformKernel=8, convertSDI=PROPAGATED,
adaptiveDampingRatio=0.05, continueDampingFactors=OFF):
'''
Parameters
----------
description : str
Step description.
timePeriod : float
Total time period.
nlgeom : bool
Whether to allow for geometric nonlinearity.
stabilizationMethod : abaqus constant
Stabilization type.
stabilizationMagnitude : float
Damping intensity of the automatic damping algorithm. Ignored if
stabilizationMethod=None.
adiabatic : bool
Whether to perform an adiabatic stress analysis.
timeIncrementationMethod : abaqus constant
maxNumInc : int
Number of incrementations in a step.
initalInc : float
Initial time increment.
minInc : float
Minimum tome increment allowed.
maxInc : float
Maximum time increment allowed.
matrixSolver : abaqus constant
Type of solver.
matrixStorage : abaqus constant
Type of matrix storage.
amplitude : abaqus constant
Amplitude variation for loading magnitudes during the step.
extrapolation : abaqus constant
Type of extrapolation to use in determining the incremental solution
for a nonlinear analysis.
fullyPlastic : str
Region being monitored for fully plastic behavior.
noStop : bool
Whether to accept the solution to an increment after the maximum
number of interations allowed has been completed, even if the
equilibrium tolerances are not satisfied.
maintainAttributes : bool
Whether to retain attributes from an existing step with the same
name.
useLongTermSolution : bool
Whether to obtain the fully relaxed long-term elastic solution with
time-domain viscoelasticity or the long-term elastic-plastic solution
for two-layer viscoplasticity.
solutionTechnique : abaqus constant
Technique used for solving nonlinear equations.
reformKernel : int
Number of quasi-Newton iterations allowed before the kernel matrix
is reformed.
convertSDI : abaqus constant
Whether to force a new iteration if severe discontinuities occur
during an iteration.
adaptiveDampingRatio : float
Maximum allowable ratio of the stabilization energy to the total
strain energy. Ignored if stabilizationMethod=None.
continueDampingFactors : bool
Whether this step will carry over the damping factors from the
results of the preceding general step.
Notes
-----
-for further informations see p49-134 of [1].
'''
# computations
initialInc = timePeriod if initialInc is None else initialInc
minInc = min(initialInc, timePeriod * 1e-5) if minInc is None else minInc
maxInc = timePeriod if maxInc is None else maxInc
# create args dict
self.args = {'description': description,
'timePeriod': timePeriod,
'nlgeom': nlgeom,
'stabilizationMethod': stabilizationMethod,
'stabilizationMagnitude': stabilizationMagnitude,
'adiabatic': adiabatic,
'timeIncrementationMethod': timeIncrementationMethod,
'maxNumInc': maxNumInc,
'initialInc': initialInc,
'minInc': minInc,
'maxInc': maxInc,
'matrixSolver': matrixSolver,
'matrixStorage': matrixStorage,
'amplitude': amplitude,
'extrapolation': extrapolation,
'fullyPlastic': fullyPlastic,
'noStop': noStop,
'maintainAttributes': maintainAttributes,
'useLongTermSolution': useLongTermSolution,
'solutionTechnique': solutionTechnique,
'reformKernel': reformKernel,
'convertSDI': convertSDI,
'adaptiveDampingRatio': adaptiveDampingRatio,
'continueDampingFactors': continueDampingFactors}
# initialize parent
Step.__init__(self, name, previous, model=model)
class StaticRiksStep(Step):
method_name = 'StaticRiksStep'
def __init__(self, name, previous='Initial', model=None,
description='', nlgeom=OFF, adiabatic=OFF, maxLPF=None,
nodeOn=OFF, maximumDisplacement=0., dof=0, region=None,
timeIncrementationMethod=AUTOMATIC, maxNumInc=100,
totalArcLength=1., initialArcInc=None, minArcInc=None,
maxArcInc=None, matrixStorage=SOLVER_DEFAULT,
extrapolation=LINEAR, fullyPlastic='', noStop=OFF,
maintainAttributes=False, useLongTermSolution=OFF,
convertSDI=PROPAGATED):
'''
Parameters
----------
description : str
Step description.
nlgeom : bool
Whether to allow for geometric nonlinearity.
adiabatic : bool
Whether to perform an adiabatic stress analysis.
maxLPF : float
Maximum value of the load proportionality factor.
nodeOn : bool
Whether to monitor the finishing displacement value at a node.
maximumDisplacement : float
Value of the total displacement (or rotation) at the node node and
degree of freedom that, if crossed during an increment, ends the
step at the current increment. Only applicable when nodeOn=ON.
dof : int
Degree of freedom being monitored. Only applicable when nodeOn=ON
region : abaqus region object
Vertex at which the finishing displacement value is being monitored.
Only applicable when nodeOn=ON.
timeIncrementationMethod : abaqus constant
maxNumInc : int
Number of incrementations in a step.
totalArcLength : float
Total load proportionality factor associated with the load in this
step.
initialArcInc : float
Initial load proportionality factor.
minArcInc : float
Minimum arc length increment allowed.
maxArcInc : Maximum arc length increment allowed.
matrixStorage : abaqus constant
Type of matrix storage.
extrapolation : abaqus constant
Type of extrapolation to use in determining the incremental solution
for a nonlinear analysis.
fullyPlastic : str
Region being monitored for fully plastic behavior.
noStop : bool
Whether to accept the solution to an increment after the maximum
number of interations allowed has been completed, even if the
equilibrium tolerances are not satisfied.
maintainAttributes : bool
Whether to retain attributes from an existing step with the same
name.
useLongTermSolution : bool
Whether to obtain the fully relaxed long-term elastic solution with
time-domain viscoelasticity or the long-term elastic-plastic solution
for two-layer viscoplasticity.
convertSDI : abaqus constant
Whether to force a new iteration if severe discontinuities occur
during an iteration.
Notes
-----
-for further informations see p49-128 of [1].
'''
# computations
initialArcInc = totalArcLength if initialArcInc is None else initialArcInc
minArcInc = min(initialArcInc, 1e-5 * totalArcLength) if minArcInc is None else minArcInc
maxArcInc = totalArcLength if maxArcInc is None else maxArcInc
# create arg dict
self.args = {'description': description,
'nlgeom': nlgeom,
'adiabatic': adiabatic,
'maxLPF': maxLPF,
'nodeOn': nodeOn,
'maximumDisplacement': maximumDisplacement,
'dof': dof,
'timeIncrementationMethod': timeIncrementationMethod,
'maxNumInc': maxNumInc,
'totalArcLength': totalArcLength,
'initialArcInc': initialArcInc,
'minArcInc': minArcInc,
'maxArcInc': maxArcInc,
'matrixStorage': matrixStorage,
'extrapolation': extrapolation,
'fullyPlastic': fullyPlastic,
'noStop': noStop,
'maintainAttributes': maintainAttributes,
'useLongTermSolution': useLongTermSolution,
'convertSDI': convertSDI,
}
if nodeOn is ON and region:
self.args['region'] = region
# initialize parent
Step.__init__(self, name, previous, model=model)
class BuckleStep(Step):
method_name = 'BuckleStep'
def __init__(self, name, previous='Initial', model=None, numEigen=20,
description='', eigensolver=LANCZOS, minEigen=None,
maxEigen=None, vectors=None, maxIterations=30, blockSize=DEFAULT,
maxBlocks=DEFAULT, matrixStorage=SOLVER_DEFAULT,
maintainAttributes=False):
'''
Parameters
----------
numEigen : int
Number of eigenvalues to be estimated.
description : str
Step description.
eigensolver : abaqus constant
minEigen : float
Minimum eigenvalue of interest. Ignored if eigensolver!=LANCZOS.
maxEigen : float
Maximum eigenvalue of interest.
vectors : int
Number of vectors used in each iteration.
maxIterations : int
Maximum number of iterations.
blockSize : abaqus constant or int
Size of the Lanczos block steps. Ignored if eigensolver!=LANCZOS.
maxBlocks : abaqus constant or int
Maximum number of Lanczos block steps within each Lanczos run.
Ignored if eigensolver!=LANCZOS.
matrixStorage : abaqus constant
Type of matrix storage.
maintainAttributes : bool
Whether to retain attributes from an existing step with the same
name.
Notes
-----
-for further informations see p49-10 of [1].
'''
# computations
vectors = min(2 * numEigen, numEigen * 8) if vectors is None else vectors
# create arg dict
self.args = {'numEigen': numEigen,
'description': description,
'eigensolver': eigensolver,
'minEigen': minEigen,
'maxEigen': maxEigen,
'vectors': vectors,
'maxIterations': maxIterations,
'blockSize': blockSize,
'maxBlocks': maxBlocks,
'matrixStorage': matrixStorage,
'maintainAttributes': maintainAttributes}
# initialize parent
Step.__init__(self, name, previous, model=model)
class FrequencyStep(Step):
method_name = 'FrequencyStep'
def __init__(self, name, previous='Initial', model=None, eigensolver=LANCZOS,
numEigen=ALL, description='', shift=0., minEigen=None,
maxEigen=None, vectors=None, maxIterations=30, blockSize=DEFAULT,
maxBlocks=DEFAULT, normalization=DISPLACEMENT,
propertyEvaluationFrequency=None, projectDamping=ON,
acousticDamping=AC_ON, acousticRangeFactor=1.,
frictionDamping=OFF, matrixStorage=SOLVER_DEFAULT,
maintainAttributes=False, simLinearDynamics=OFF,
residualModes=OFF, substructureCutoffMultiplier=5.,
firstCutoffMultiplier=1.7, secondCutoffMultiplier=1.1,
residualModeRegion=None, residualModeDof=None,
limitSavedEigenVectorRegion=None):
'''
Parameters
----------
eigensolver : abaqus constant
Arguments ignored if eigenSolver!=LANCZOS: blockSize, maxBlocks,
normalization, propertyEvaluationFrequency.
Arguments ignored if eigenSolver!=LANCZOS or AMS: minEigen,
maxEigen, acousticCoupling.
Arguments ignored if eigenSolver!=AMS: projectDamping,
acousticRangeFactor, substructureCutoffMultiplier,
firstCutoffMultiplier, secondCutoffMultiplier, residualModeRegion,
regionalModeDof, limitSavedEigenVectorRegion.
numEigen : int or abaqus constant
Number of eigenvalues to be estimated.
description : str
Step description.
shift : float
Shift point in cycles per time.
minEigen : float
Minimum eigenvalue of interest.
maxEigen : float
Maximum eigenvalue of interest.
vectors : int
Number of vectors used in each iteration.
maxIterations : int
Maximum number of iterations.
blockSize : abaqus constant or int
Size of the Lanczos block steps.
maxBlocks : abaqus constant | |
= params["R18"]
R19 = params["R19"]
R20 = params["R20"]
R21 = params["R21"]
return (
Rs
+ (R1 / (1 + w * 1j * t_values[0]))
+ (R2 / (1 + w * 1j * t_values[1]))
+ (R3 / (1 + w * 1j * t_values[2]))
+ (R4 / (1 + w * 1j * t_values[3]))
+ (R5 / (1 + w * 1j * t_values[4]))
+ (R6 / (1 + w * 1j * t_values[5]))
+ (R7 / (1 + w * 1j * t_values[6]))
+ (R8 / (1 + w * 1j * t_values[7]))
+ (R9 / (1 + w * 1j * t_values[8]))
+ (R10 / (1 + w * 1j * t_values[9]))
+ (R11 / (1 + w * 1j * t_values[10]))
+ (R12 / (1 + w * 1j * t_values[11]))
+ (R13 / (1 + w * 1j * t_values[12]))
+ (R14 / (1 + w * 1j * t_values[13]))
+ (R15 / (1 + w * 1j * t_values[14]))
+ (R16 / (1 + w * 1j * t_values[15]))
+ (R17 / (1 + w * 1j * t_values[16]))
+ (R18 / (1 + w * 1j * t_values[17]))
+ (R19 / (1 + w * 1j * t_values[18]))
+ (R20 / (1 + w * 1j * t_values[19]))
+ (R21 / (1 + w * 1j * t_values[20]))
)
def KK_RC22_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
<NAME> (<EMAIL> / <EMAIL>)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
R7 = params["R7"]
R8 = params["R8"]
R9 = params["R9"]
R10 = params["R10"]
R11 = params["R11"]
R12 = params["R12"]
R13 = params["R13"]
R14 = params["R14"]
R15 = params["R15"]
R16 = params["R16"]
R17 = params["R17"]
R18 = params["R18"]
R19 = params["R19"]
R20 = params["R20"]
R21 = params["R21"]
R22 = params["R22"]
return (
Rs
+ (R1 / (1 + w * 1j * t_values[0]))
+ (R2 / (1 + w * 1j * t_values[1]))
+ (R3 / (1 + w * 1j * t_values[2]))
+ (R4 / (1 + w * 1j * t_values[3]))
+ (R5 / (1 + w * 1j * t_values[4]))
+ (R6 / (1 + w * 1j * t_values[5]))
+ (R7 / (1 + w * 1j * t_values[6]))
+ (R8 / (1 + w * 1j * t_values[7]))
+ (R9 / (1 + w * 1j * t_values[8]))
+ (R10 / (1 + w * 1j * t_values[9]))
+ (R11 / (1 + w * 1j * t_values[10]))
+ (R12 / (1 + w * 1j * t_values[11]))
+ (R13 / (1 + w * 1j * t_values[12]))
+ (R14 / (1 + w * 1j * t_values[13]))
+ (R15 / (1 + w * 1j * t_values[14]))
+ (R16 / (1 + w * 1j * t_values[15]))
+ (R17 / (1 + w * 1j * t_values[16]))
+ (R18 / (1 + w * 1j * t_values[17]))
+ (R19 / (1 + w * 1j * t_values[18]))
+ (R20 / (1 + w * 1j * t_values[19]))
+ (R21 / (1 + w * 1j * t_values[20]))
+ (R22 / (1 + w * 1j * t_values[21]))
)
def KK_RC23_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
<NAME> (<EMAIL> / <EMAIL>)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
R7 = params["R7"]
R8 = params["R8"]
R9 = params["R9"]
R10 = params["R10"]
R11 = params["R11"]
R12 = params["R12"]
R13 = params["R13"]
R14 = params["R14"]
R15 = params["R15"]
R16 = params["R16"]
R17 = params["R17"]
R18 = params["R18"]
R19 = params["R19"]
R20 = params["R20"]
R21 = params["R21"]
R22 = params["R22"]
R23 = params["R23"]
return (
Rs
+ (R1 / (1 + w * 1j * t_values[0]))
+ (R2 / (1 + w * 1j * t_values[1]))
+ (R3 / (1 + w * 1j * t_values[2]))
+ (R4 / (1 + w * 1j * t_values[3]))
+ (R5 / (1 + w * 1j * t_values[4]))
+ (R6 / (1 + w * 1j * t_values[5]))
+ (R7 / (1 + w * 1j * t_values[6]))
+ (R8 / (1 + w * 1j * t_values[7]))
+ (R9 / (1 + w * 1j * t_values[8]))
+ (R10 / (1 + w * 1j * t_values[9]))
+ (R11 / (1 + w * 1j * t_values[10]))
+ (R12 / (1 + w * 1j * t_values[11]))
+ (R13 / (1 + w * 1j * t_values[12]))
+ (R14 / (1 + w * 1j * t_values[13]))
+ (R15 / (1 + w * 1j * t_values[14]))
+ (R16 / (1 + w * 1j * t_values[15]))
+ (R17 / (1 + w * 1j * t_values[16]))
+ (R18 / (1 + w * 1j * t_values[17]))
+ (R19 / (1 + w * 1j * t_values[18]))
+ (R20 / (1 + w * 1j * t_values[19]))
+ (R21 / (1 + w * 1j * t_values[20]))
+ (R22 / (1 + w * 1j * t_values[21]))
+ (R23 / (1 + w * 1j * t_values[22]))
)
def KK_RC24_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
<NAME> (<EMAIL> / <EMAIL>)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
R7 = params["R7"]
R8 = params["R8"]
R9 = params["R9"]
R10 = params["R10"]
R11 = params["R11"]
R12 = params["R12"]
R13 = params["R13"]
R14 = params["R14"]
R15 = params["R15"]
R16 = params["R16"]
R17 = params["R17"]
R18 = params["R18"]
R19 = params["R19"]
R20 = params["R20"]
R21 = params["R21"]
R22 = params["R22"]
R23 = params["R23"]
R24 = params["R24"]
return (
Rs
+ (R1 / (1 + w * 1j * t_values[0]))
+ (R2 / (1 + w * 1j * t_values[1]))
+ (R3 / (1 + w * 1j * t_values[2]))
+ (R4 / (1 + w * 1j * t_values[3]))
+ (R5 / (1 + w * 1j * t_values[4]))
+ (R6 / (1 + w * 1j * t_values[5]))
+ (R7 / (1 + w * 1j * t_values[6]))
+ (R8 / (1 + w * 1j * t_values[7]))
+ (R9 / (1 + w * 1j * t_values[8]))
+ (R10 / (1 + w * 1j * t_values[9]))
+ (R11 / (1 + w * 1j * t_values[10]))
+ (R12 / (1 + w * 1j * t_values[11]))
+ (R13 / (1 + w * 1j * t_values[12]))
+ (R14 / (1 + w * 1j * t_values[13]))
+ (R15 / (1 + w * 1j * t_values[14]))
+ (R16 / (1 + w * 1j * t_values[15]))
+ (R17 / (1 + w * 1j * t_values[16]))
+ (R18 / (1 + w * 1j * t_values[17]))
+ (R19 / (1 + w * 1j * t_values[18]))
+ (R20 / (1 + w * 1j * t_values[19]))
+ (R21 / (1 + w * 1j * t_values[20]))
+ (R22 / (1 + w * 1j * t_values[21]))
+ (R23 / (1 + w * 1j * t_values[22]))
+ (R24 / (1 + w * 1j * t_values[23]))
)
def KK_RC25_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
<NAME> (<EMAIL> / <EMAIL>)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
R7 = params["R7"]
R8 = params["R8"]
R9 = params["R9"]
R10 = params["R10"]
R11 = params["R11"]
R12 = params["R12"]
R13 = params["R13"]
R14 = params["R14"]
R15 = params["R15"]
R16 = params["R16"]
R17 = params["R17"]
R18 = params["R18"]
R19 = params["R19"]
R20 = params["R20"]
R21 = params["R21"]
R22 = params["R22"]
R23 = params["R23"]
R24 = params["R24"]
R25 = params["R25"]
return (
Rs
+ (R1 / (1 + w * 1j | |
# -*- coding: utf-8 -*-
import abc
import logging
import datetime
import functools
import httplib as http
import time
import urlparse
import uuid
from flask import request
from oauthlib.oauth2.rfc6749.errors import MissingTokenError
from requests.exceptions import HTTPError as RequestsHTTPError
from modularodm import fields, Q
from modularodm.storage.base import KeyExistsException
from modularodm.validators import MaxLengthValidator, URLValidator
from requests_oauthlib import OAuth1Session
from requests_oauthlib import OAuth2Session
from framework.auth import cas
from framework.exceptions import HTTPError, PermissionsError
from framework.mongo import ObjectId, StoredObject
from framework.mongo.utils import unique_on
from framework.mongo.validators import string_required
from framework.sessions import session
from website import settings
from website.oauth.utils import PROVIDER_LOOKUP
from website.security import random_string
from website.util import web_url_for, api_v2_url
logger = logging.getLogger(__name__)
OAUTH1 = 1
OAUTH2 = 2
generate_client_secret = functools.partial(random_string, length=40)
@unique_on(['provider', 'provider_id'])
class ExternalAccount(StoredObject):
"""An account on an external service.
Note that this object is not and should not be aware of what other objects
are associated with it. This is by design, and this object should be kept as
thin as possible, containing only those fields that must be stored in the
database.
The ``provider`` field is a de facto foreign key to an ``ExternalProvider``
object, as providers are not stored in the database.
"""
_id = fields.StringField(default=lambda: str(ObjectId()), primary=True)
# The OAuth credentials. One or both of these fields should be populated.
# For OAuth1, this is usually the "oauth_token"
# For OAuth2, this is usually the "access_token"
oauth_key = fields.StringField()
# For OAuth1, this is usually the "oauth_token_secret"
# For OAuth2, this is not used
oauth_secret = fields.StringField()
# Used for OAuth2 only
refresh_token = fields.StringField()
expires_at = fields.DateTimeField()
scopes = fields.StringField(list=True, default=lambda: list())
# The `name` of the service
# This lets us query for only accounts on a particular provider
provider = fields.StringField(required=True)
# The proper 'name' of the service
# Needed for account serialization
provider_name = fields.StringField(required=True)
# The unique, persistent ID on the remote service.
provider_id = fields.StringField()
# The user's name on the external service
display_name = fields.StringField()
# A link to the user's profile on the external service
profile_url = fields.StringField()
def __repr__(self):
return '<ExternalAccount: {}/{}>'.format(self.provider,
self.provider_id)
class ExternalProviderMeta(abc.ABCMeta):
"""Keeps track of subclasses of the ``ExternalProvider`` object"""
def __init__(cls, name, bases, dct):
super(ExternalProviderMeta, cls).__init__(name, bases, dct)
if not isinstance(cls.short_name, abc.abstractproperty):
PROVIDER_LOOKUP[cls.short_name] = cls
class ExternalProvider(object):
"""A connection to an external service (ex: GitHub).
This object contains no credentials, and is not saved in the database.
It provides an unauthenticated session with the provider, unless ``account``
has been set - in which case, it provides a connection authenticated as the
``ExternalAccount`` instance.
Conceptually, this can be thought of as an extension of ``ExternalAccount``.
It's a separate object because this must be subclassed for each provider,
and ``ExternalAccount`` instances are stored within a single collection.
"""
__metaclass__ = ExternalProviderMeta
# Default to OAuth v2.0.
_oauth_version = OAUTH2
# Providers that have expiring tokens must override these
auto_refresh_url = None
refresh_time = 0 # When to refresh the oauth_key (seconds)
expiry_time = 0 # If/When the refresh token expires (seconds). 0 indicates a non-expiring refresh token
def __init__(self, account=None):
super(ExternalProvider, self).__init__()
# provide an unauthenticated session by default
self.account = account
def __repr__(self):
return '<{name}: {status}>'.format(
name=self.__class__.__name__,
status=self.account.provider_id if self.account else 'anonymous'
)
@abc.abstractproperty
def auth_url_base(self):
"""The base URL to begin the OAuth dance"""
pass
@property
def auth_url(self):
"""The URL to begin the OAuth dance.
This property method has side effects - it at least adds temporary
information to the session so that callbacks can be associated with
the correct user. For OAuth1, it calls the provider to obtain
temporary credentials to start the flow.
"""
# create a dict on the session object if it's not already there
if session.data.get('oauth_states') is None:
session.data['oauth_states'] = {}
if self._oauth_version == OAUTH2:
# build the URL
oauth = OAuth2Session(
self.client_id,
redirect_uri=web_url_for('oauth_callback',
service_name=self.short_name,
_absolute=True),
scope=self.default_scopes,
)
url, state = oauth.authorization_url(self.auth_url_base)
# save state token to the session for confirmation in the callback
session.data['oauth_states'][self.short_name] = {'state': state}
elif self._oauth_version == OAUTH1:
# get a request token
oauth = OAuth1Session(
client_key=self.client_id,
client_secret=self.client_secret,
)
# request temporary credentials from the provider
response = oauth.fetch_request_token(self.request_token_url)
# store them in the session for use in the callback
session.data['oauth_states'][self.short_name] = {
'token': response.get('oauth_token'),
'secret': response.get('oauth_token_secret'),
}
url = oauth.authorization_url(self.auth_url_base)
return url
@abc.abstractproperty
def callback_url(self):
"""The provider URL to exchange the code for a token"""
pass
@abc.abstractproperty
def client_id(self):
"""OAuth Client ID. a/k/a: Application ID"""
pass
@abc.abstractproperty
def client_secret(self):
"""OAuth Client Secret. a/k/a: Application Secret, Application Key"""
pass
default_scopes = list()
@abc.abstractproperty
def name(self):
"""Human-readable name of the service. e.g.: ORCiD, GitHub"""
pass
@abc.abstractproperty
def short_name(self):
"""Name of the service to be used internally. e.g.: orcid, github"""
pass
def auth_callback(self, user, **kwargs):
"""Exchange temporary credentials for permanent credentials
This is called in the view that handles the user once they are returned
to the OSF after authenticating on the external service.
"""
if 'error' in request.args:
return False
# make sure the user has temporary credentials for this provider
try:
cached_credentials = session.data['oauth_states'][self.short_name]
except KeyError:
raise PermissionsError('OAuth flow not recognized.')
if self._oauth_version == OAUTH1:
request_token = request.args.get('oauth_token')
# make sure this is the same user that started the flow
if cached_credentials.get('token') != request_token:
raise PermissionsError('Request token does not match')
response = OAuth1Session(
client_key=self.client_id,
client_secret=self.client_secret,
resource_owner_key=cached_credentials.get('token'),
resource_owner_secret=cached_credentials.get('secret'),
verifier=request.args.get('oauth_verifier'),
).fetch_access_token(self.callback_url)
elif self._oauth_version == OAUTH2:
state = request.args.get('state')
# make sure this is the same user that started the flow
if cached_credentials.get('state') != state:
raise PermissionsError('Request token does not match')
try:
response = OAuth2Session(
self.client_id,
redirect_uri=web_url_for(
'oauth_callback',
service_name=self.short_name,
_absolute=True
),
).fetch_token(
self.callback_url,
client_secret=self.client_secret,
code=request.args.get('code'),
)
except (MissingTokenError, RequestsHTTPError):
raise HTTPError(http.SERVICE_UNAVAILABLE)
# pre-set as many values as possible for the ``ExternalAccount``
info = self._default_handle_callback(response)
# call the hook for subclasses to parse values from the response
info.update(self.handle_callback(response))
return self._set_external_account(user, info)
def _set_external_account(self, user, info):
try:
# create a new ``ExternalAccount`` ...
self.account = ExternalAccount(
provider=self.short_name,
provider_id=info['provider_id'],
provider_name=self.name,
)
self.account.save()
except KeyExistsException:
# ... or get the old one
self.account = ExternalAccount.find_one(
Q('provider', 'eq', self.short_name) &
Q('provider_id', 'eq', info['provider_id'])
)
assert self.account is not None
# ensure that provider_name is correct
self.account.provider_name = self.name
# required
self.account.oauth_key = info['key']
# only for OAuth1
self.account.oauth_secret = info.get('secret')
# only for OAuth2
self.account.expires_at = info.get('expires_at')
self.account.refresh_token = info.get('refresh_token')
# additional information
self.account.display_name = info.get('display_name')
self.account.profile_url = info.get('profile_url')
self.account.save()
# add it to the user's list of ``ExternalAccounts``
if self.account not in user.external_accounts:
user.external_accounts.append(self.account)
user.save()
return True
def _default_handle_callback(self, data):
"""Parse as much out of the key exchange's response as possible.
This should not be over-ridden in subclasses.
"""
if self._oauth_version == OAUTH1:
key = data.get('oauth_token')
secret = data.get('oauth_token_secret')
values = {}
if key:
values['key'] = key
if secret:
values['secret'] = secret
return values
elif self._oauth_version == OAUTH2:
key = data.get('access_token')
refresh_token = data.get('refresh_token')
expires_at = data.get('expires_at')
scopes = data.get('scope')
values = {}
if key:
values['key'] = key
if scopes:
values['scope'] = scopes
if refresh_token:
values['refresh_token'] = refresh_token
if expires_at:
values['expires_at'] = datetime.datetime.fromtimestamp(
float(expires_at)
)
return values
@abc.abstractmethod
def handle_callback(self, response):
"""Hook for allowing subclasses to parse information from the callback.
Subclasses should implement this method to provide `provider_id`
and `profile_url`.
Values provided by ``self._default_handle_callback`` can be over-ridden
here as well, in the unexpected case that they are parsed incorrectly
by default.
:param response: The JSON returned by the provider during the exchange
:return dict:
"""
pass
def refresh_oauth_key(self, force=False, extra={}, resp_auth_token_key='access_token',
resp_refresh_token_key='refresh_token', resp_expiry_fn=None):
"""Handles the refreshing of an oauth_key for account associated with this provider.
Not all addons need to use this, as some do not have oauth_keys that expire.
Subclasses must define the following for this functionality:
`auto_refresh_url` - URL to use when refreshing tokens. Must use HTTPS
`refresh_time` - Time (in seconds) that the oauth_key should be refreshed after.
Typically half the duration of validity. Cannot be 0.
Providers may have different keywords in their response bodies, kwargs
`resp_*_key` allow subclasses to override these if necessary.
kwarg `resp_expiry_fn` allows subclasses to specify a function that will return the
datetime-formatted oauth_key expiry key, given a successful refresh response from
`auto_refresh_url`. A default using 'expires_at' as a key is provided.
| |
% {"value": value, "lineno": lineno, })
return False
value = value
enumerations = ['yes', 'no', 'highlighted']
if value not in enumerations:
lineno = self.gds_get_node_lineno_()
self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd enumeration restriction on renderInstructionsType1' % {"value" : encode_str_2_3(value), "lineno": lineno} )
result = False
def hasContent_(self):
if (
(1 if type(self.valueOf_) in [int,float] else self.valueOf_)
):
return True
else:
return False
def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='numericRenderInstructionsType', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('numericRenderInstructionsType')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'numericRenderInstructionsType':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespaceprefix_ = self.ns_prefix_ + ':'
showIndent(outfile, level, pretty_print)
outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='numericRenderInstructionsType')
if self.hasContent_():
outfile.write('>')
outfile.write(self.convert_unicode(self.valueOf_))
self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='numericRenderInstructionsType', pretty_print=pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='numericRenderInstructionsType'):
if self.code is not None and 'code' not in already_processed:
already_processed.add('code')
outfile.write(' code=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.code), input_name='code')), ))
if self.renderInstructions is not None and 'renderInstructions' not in already_processed:
already_processed.add('renderInstructions')
outfile.write(' renderInstructions=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.renderInstructions), input_name='renderInstructions')), ))
def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='numericRenderInstructionsType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node, gds_collector_=None):
self.gds_collector_ = gds_collector_
if SaveElementTreeNode:
self.gds_elementtree_node_ = node
already_processed = set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('code', node)
if value is not None and 'code' not in already_processed:
already_processed.add('code')
self.code = value
value = find_attr_value_('renderInstructions', node)
if value is not None and 'renderInstructions' not in already_processed:
already_processed.add('renderInstructions')
self.renderInstructions = value
self.validate_renderInstructionsType1(self.renderInstructions) # validate type renderInstructionsType1
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
pass
# end class numericRenderInstructionsType
class transitDepotListType(GeneratedsSuper):
"""The list of TNT depots that will be handling the consignment between
the origin and destination depots.The list of TNT depots that will be
handling the consignment between
the origin and destination depots."""
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, transitDepot=None, actionDepot=None, sortDepot=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
if transitDepot is None:
self.transitDepot = []
else:
self.transitDepot = transitDepot
self.transitDepot_nsprefix_ = None
if actionDepot is None:
self.actionDepot = []
else:
self.actionDepot = actionDepot
self.actionDepot_nsprefix_ = None
if sortDepot is None:
self.sortDepot = []
else:
self.sortDepot = sortDepot
self.sortDepot_nsprefix_ = None
def factory(*args_, **kwargs_):
if CurrentSubclassModule_ is not None:
subclass = getSubclassFromModule_(
CurrentSubclassModule_, transitDepotListType)
if subclass is not None:
return subclass(*args_, **kwargs_)
if transitDepotListType.subclass:
return transitDepotListType.subclass(*args_, **kwargs_)
else:
return transitDepotListType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ns_prefix_(self):
return self.ns_prefix_
def set_ns_prefix_(self, ns_prefix):
self.ns_prefix_ = ns_prefix
def get_transitDepot(self):
return self.transitDepot
def set_transitDepot(self, transitDepot):
self.transitDepot = transitDepot
def add_transitDepot(self, value):
self.transitDepot.append(value)
def insert_transitDepot_at(self, index, value):
self.transitDepot.insert(index, value)
def replace_transitDepot_at(self, index, value):
self.transitDepot[index] = value
def get_actionDepot(self):
return self.actionDepot
def set_actionDepot(self, actionDepot):
self.actionDepot = actionDepot
def add_actionDepot(self, value):
self.actionDepot.append(value)
def insert_actionDepot_at(self, index, value):
self.actionDepot.insert(index, value)
def replace_actionDepot_at(self, index, value):
self.actionDepot[index] = value
def get_sortDepot(self):
return self.sortDepot
def set_sortDepot(self, sortDepot):
self.sortDepot = sortDepot
def add_sortDepot(self, value):
self.sortDepot.append(value)
def insert_sortDepot_at(self, index, value):
self.sortDepot.insert(index, value)
def replace_sortDepot_at(self, index, value):
self.sortDepot[index] = value
def hasContent_(self):
if (
self.transitDepot or
self.actionDepot or
self.sortDepot
):
return True
else:
return False
def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='transitDepotListType', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('transitDepotListType')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'transitDepotListType':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespaceprefix_ = self.ns_prefix_ + ':'
showIndent(outfile, level, pretty_print)
outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='transitDepotListType')
if self.hasContent_():
outfile.write('>%s' % (eol_, ))
self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='transitDepotListType', pretty_print=pretty_print)
showIndent(outfile, level, pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='transitDepotListType'):
pass
def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='transitDepotListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for transitDepot_ in self.transitDepot:
namespaceprefix_ = self.transitDepot_nsprefix_ + ':' if (UseCapturedNS_ and self.transitDepot_nsprefix_) else ''
transitDepot_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='transitDepot', pretty_print=pretty_print)
for actionDepot_ in self.actionDepot:
namespaceprefix_ = self.actionDepot_nsprefix_ + ':' if (UseCapturedNS_ and self.actionDepot_nsprefix_) else ''
actionDepot_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='actionDepot', pretty_print=pretty_print)
for sortDepot_ in self.sortDepot:
namespaceprefix_ = self.sortDepot_nsprefix_ + ':' if (UseCapturedNS_ and self.sortDepot_nsprefix_) else ''
sortDepot_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='sortDepot', pretty_print=pretty_print)
def build(self, node, gds_collector_=None):
self.gds_collector_ = gds_collector_
if SaveElementTreeNode:
self.gds_elementtree_node_ = node
already_processed = set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
if nodeName_ == 'transitDepot':
obj_ = depotType.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.transitDepot.append(obj_)
obj_.original_tagname_ = 'transitDepot'
elif nodeName_ == 'actionDepot':
obj_ = actionDepotType.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.actionDepot.append(obj_)
obj_.original_tagname_ = 'actionDepot'
elif nodeName_ == 'sortDepot':
obj_ = sortDepotType.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.sortDepot.append(obj_)
obj_.original_tagname_ = 'sortDepot'
# end class transitDepotListType
class actionDepotType(GeneratedsSuper):
"""Details relevant to an action transit TNT depot."""
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, depotCode=None, actionDayOfWeek=None, actionDate=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
self.depotCode = depotCode
self.depotCode_nsprefix_ = None
self.actionDayOfWeek = actionDayOfWeek
self.actionDayOfWeek_nsprefix_ = None
if isinstance(actionDate, BaseStrType_):
initvalue_ = datetime_.datetime.strptime(actionDate, '%Y-%m-%d').date()
else:
initvalue_ = actionDate
self.actionDate = initvalue_
self.actionDate_nsprefix_ = None
def factory(*args_, **kwargs_):
if CurrentSubclassModule_ is not None:
subclass = getSubclassFromModule_(
CurrentSubclassModule_, actionDepotType)
if subclass is not None:
return subclass(*args_, **kwargs_)
if actionDepotType.subclass:
return actionDepotType.subclass(*args_, **kwargs_)
else:
return actionDepotType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ns_prefix_(self):
return self.ns_prefix_
def set_ns_prefix_(self, ns_prefix):
self.ns_prefix_ = ns_prefix
def get_depotCode(self):
return self.depotCode
def set_depotCode(self, depotCode):
self.depotCode = depotCode
def get_actionDayOfWeek(self):
return self.actionDayOfWeek
def set_actionDayOfWeek(self, actionDayOfWeek):
self.actionDayOfWeek = actionDayOfWeek
def get_actionDate(self):
return self.actionDate
def set_actionDate(self, actionDate):
self.actionDate = actionDate
def hasContent_(self):
if (
self.depotCode is not None or
self.actionDayOfWeek is not None or
self.actionDate is not None
):
return True
else:
return False
def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='actionDepotType', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('actionDepotType')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'actionDepotType':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespaceprefix_ = self.ns_prefix_ + ':'
showIndent(outfile, level, pretty_print)
outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='actionDepotType')
if self.hasContent_():
outfile.write('>%s' % (eol_, ))
self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='actionDepotType', pretty_print=pretty_print)
showIndent(outfile, level, pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='actionDepotType'):
pass
def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='actionDepotType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.depotCode is not None:
namespaceprefix_ = self.depotCode_nsprefix_ + ':' if (UseCapturedNS_ and self.depotCode_nsprefix_) else ''
showIndent(outfile, level, pretty_print)
outfile.write('<%sdepotCode>%s</%sdepotCode>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.depotCode), input_name='depotCode')), namespaceprefix_ , eol_))
if self.actionDayOfWeek is not None:
namespaceprefix_ = self.actionDayOfWeek_nsprefix_ + ':' if (UseCapturedNS_ and self.actionDayOfWeek_nsprefix_) else ''
showIndent(outfile, level, pretty_print)
outfile.write('<%sactionDayOfWeek>%s</%sactionDayOfWeek>%s' % (namespaceprefix_ , self.gds_format_integer(self.actionDayOfWeek, input_name='actionDayOfWeek'), namespaceprefix_ , eol_))
if self.actionDate is not None:
namespaceprefix_ = self.actionDate_nsprefix_ + ':' if (UseCapturedNS_ and self.actionDate_nsprefix_) else ''
showIndent(outfile, level, pretty_print)
outfile.write('<%sactionDate>%s</%sactionDate>%s' % (namespaceprefix_ , self.gds_format_date(self.actionDate, input_name='actionDate'), namespaceprefix_ , eol_))
def build(self, node, gds_collector_=None):
self.gds_collector_ = gds_collector_
if SaveElementTreeNode:
self.gds_elementtree_node_ = node
already_processed = set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
if nodeName_ == 'depotCode':
value_ = child_.text
value_ = self.gds_parse_string(value_, node, 'depotCode')
value_ = self.gds_validate_string(value_, node, 'depotCode')
self.depotCode = value_
self.depotCode_nsprefix_ = child_.prefix
elif nodeName_ == 'actionDayOfWeek' and child_.text:
sval_ = child_.text
| |
<gh_stars>1-10
"""
Copyright 2019 Inmanta
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.
Contact: <EMAIL>
"""
import base64
import inspect
import logging
import traceback
import typing
import uuid
from collections import defaultdict
from concurrent.futures import Future
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, TypeVar, Union, cast, overload
from tornado import concurrent
from inmanta import const, data, protocol, resources
from inmanta.agent import io
from inmanta.agent.cache import AgentCache
from inmanta.const import ParameterSource, ResourceState
from inmanta.data.model import AttributeStateChange, ResourceIdStr
from inmanta.protocol import Result, json_encode
from inmanta.stable_api import stable_api
from inmanta.types import SimpleTypes
from inmanta.util import hash_file
if typing.TYPE_CHECKING:
import inmanta.agent.agent
from inmanta.agent.io.local import IOBase
LOGGER = logging.getLogger(__name__)
T = TypeVar("T")
T_FUNC = TypeVar("T_FUNC", bound=Callable[..., Any])
@stable_api
class provider(object): # noqa: N801
"""
A decorator that registers a new handler.
:param resource_type: The type of the resource this handler provides an implementation for.
For example, :inmanta:entity:`std::File`
:param name: A name to reference this provider.
"""
def __init__(self, resource_type: str, name: str) -> None:
self._resource_type = resource_type
self._name = name
def __call__(self, function):
"""
The wrapping
"""
Commander.add_provider(self._resource_type, self._name, function)
return function
@stable_api
class SkipResource(Exception):
"""
A handler should raise this exception when a resource should be skipped. The resource will be marked as skipped
instead of failed.
"""
@stable_api
class ResourcePurged(Exception):
"""
If the :func:`~inmanta.agent.handler.CRUDHandler.read_resource` method raises this exception, the agent will
mark the current state of the resource as purged.
"""
class InvalidOperation(Exception):
"""
This exception is raised by the context or handler methods when an invalid operation is performed.
"""
@stable_api
def cache(
func: Optional[T_FUNC] = None,
ignore: typing.List[str] = [],
timeout: int = 5000,
for_version: bool = True,
cache_none: bool = True,
# deprecated parameter kept for backwards compatibility: if set, overrides cache_none
cacheNone: Optional[bool] = None, # noqa: N803
call_on_delete: Optional[Callable[[Any], None]] = None,
) -> Union[T_FUNC, Callable[[T_FUNC], T_FUNC]]:
"""
decorator for methods in resource handlers to provide caching
this decorator works similar to memoization:
when the decorate method is called, its return value is cached,
for subsequent calls, the cached value is used instead of the actual value
The name of the method + the arguments of the method form the cache key
If an argument named version is present and for_version is True,
the cache entry is flushed after this version has been deployed
If an argument named resource is present,
it is assumed to be a resource and its ID is used, without the version information
:param timeout: the number of second this cache entry should live
:param for_version: if true, this value is evicted from the cache when this deploy is ready
:param ignore: a list of argument names that should not be part of the cache key
:param cache_none: cache returned none values
:param call_on_delete: A callback function that is called when the value is removed from the cache,
with the value as argument.
"""
def actual(f: Callable) -> T_FUNC:
myignore = set(ignore)
sig = inspect.signature(f)
myargs = list(sig.parameters.keys())[1:]
def wrapper(self, *args: object, **kwds: object) -> object:
kwds.update(dict(zip(myargs, args)))
def bound(**kwds):
return f(self, **kwds)
return self.cache.get_or_else(
f.__name__,
bound,
for_version,
timeout,
myignore,
cacheNone if cacheNone is not None else cache_none,
**kwds,
call_on_delete=call_on_delete,
)
# Too much magic to type statically
return cast(T_FUNC, wrapper)
if func is None:
return actual
else:
return actual(func)
@stable_api
class HandlerContext(object):
"""
Context passed to handler methods for state related "things"
"""
def __init__(
self,
resource: resources.Resource,
dry_run: bool = False,
action_id: Optional[uuid.UUID] = None,
logger: Optional[logging.Logger] = None,
) -> None:
self._resource = resource
self._dry_run = dry_run
self._cache: Dict[str, Any] = {}
self._purged = False
self._updated = False
self._created = False
self._change = const.Change.nochange
self._changes: Dict[str, AttributeStateChange] = {}
if action_id is None:
action_id = uuid.uuid4()
self._action_id = action_id
self._status: Optional[ResourceState] = None
self._logs: List[data.LogLine] = []
self.logger: logging.Logger
if logger is None:
self.logger = LOGGER
else:
self.logger = logger
self._facts: List[Dict[str, Any]] = []
def set_fact(self, fact_id: str, value: str) -> None:
"""
Send a fact to the Inmanta server.
:param fact_id: The name of the fact.
:param value: The actual value of the fact.
"""
resource_id = self._resource.id.resource_str()
fact = {
"id": fact_id,
"source": ParameterSource.fact.value,
"value": value,
"resource_id": resource_id,
}
self._facts.append(fact)
@property
def facts(self) -> List[Dict[str, Any]]:
return self._facts
@property
def action_id(self) -> uuid.UUID:
return self._action_id
@property
def status(self) -> Optional[const.ResourceState]:
return self._status
@property
def logs(self) -> List[data.LogLine]:
return self._logs
def set_status(self, status: const.ResourceState) -> None:
"""
Set the status of the handler operation.
"""
self._status = status
def is_dry_run(self) -> bool:
"""
Is this a dryrun?
"""
return self._dry_run
def get(self, name: str) -> Any:
return self._cache[name]
def contains(self, key: str) -> bool:
return key in self._cache
def set(self, name: str, value: Any) -> None:
self._cache[name] = value
def set_created(self) -> None:
self._created = True
if self._change is not const.Change.nochange:
raise InvalidOperation(f"Unable to set {const.Change.created} operation, {self._change} already set.")
self._change = const.Change.created
def set_purged(self) -> None:
self._purged = True
if self._change is not const.Change.nochange:
raise InvalidOperation(f"Unable to set {const.Change.purged} operation, {self._change} already set.")
self._change = const.Change.purged
def set_updated(self) -> None:
self._updated = True
if self._change is not const.Change.nochange:
raise InvalidOperation(f"Unable to set {const.Change.updated} operation, {self._change} already set.")
self._change = const.Change.updated
@property
def changed(self) -> bool:
return self._created or self._updated or self._purged
@property
def change(self) -> const.Change:
return self._change
def add_change(self, name: str, desired: object, current: object = None) -> None:
"""
Report a change of a field. This field is added to the set of updated fields
:param name: The name of the field that was updated
:param desired: The desired value to which the field was updated (or should be updated)
:param current: The value of the field before it was updated
"""
self._changes[name] = AttributeStateChange(current=current, desired=desired)
def add_changes(self, **kwargs: SimpleTypes) -> None:
"""
Report a list of changes at once as kwargs
:param key: The name of the field that was updated. This field is also added to the set of updated fields
:param value: The desired value of the field.
To report the previous value of the field, use the add_change method
"""
for field, value in kwargs.items():
self._changes[field] = AttributeStateChange(desired=value)
def fields_updated(self, fields: str) -> None:
"""
Report that fields have been updated
"""
for field in fields:
if field not in self._changes:
self._changes[fields] = AttributeStateChange()
@overload # noqa: F811
def update_changes(self, changes: Dict[str, AttributeStateChange]) -> None:
pass
@overload # noqa: F811
def update_changes(self, changes: Dict[str, Dict[str, Optional[SimpleTypes]]]) -> None:
pass
@overload # noqa: F811
def update_changes(self, changes: Dict[str, Tuple[SimpleTypes, SimpleTypes]]) -> None:
pass
def update_changes( # noqa: F811
self,
changes: Union[
Dict[str, AttributeStateChange],
Dict[str, Dict[str, Optional[SimpleTypes]]],
Dict[str, Tuple[SimpleTypes, SimpleTypes]],
],
) -> None:
"""
Update the changes list with changes
:param changes: This should be a dict with a value a dict containing "current" and "desired" keys
"""
for attribute, change in changes.items():
if isinstance(change, dict):
self._changes[attribute] = AttributeStateChange(
current=change.get("current", None), desired=change.get("desired", None)
)
elif isinstance(change, tuple):
if len(change) != 2:
raise InvalidOperation(
f"Reported changes for {attribute} not valid. Tuple changes should contain 2 element."
)
self._changes[attribute] = AttributeStateChange(current=change[0], desired=change[1])
elif isinstance(change, AttributeStateChange):
self._changes[attribute] = change
else:
raise InvalidOperation(f"Reported changes for {attribute} not in a type that is recognized.")
@property
def changes(self) -> Dict[str, AttributeStateChange]:
return self._changes
def log_msg(self, level: int, msg: str, args: Sequence[object], kwargs: Dict[str, object]) -> None:
if len(args) > 0:
raise Exception("Args not supported")
if "exc_info" in kwargs:
exc_info = kwargs["exc_info"]
kwargs["traceback"] = traceback.format_exc()
else:
exc_info = False
try:
json_encode(kwargs)
except Exception as e:
raise Exception("Exception during serializing log message arguments") from e
log = data.LogLine.log(level, msg, **kwargs)
self.logger.log(level, "resource %s: %s", self._resource.id.resource_version_str(), log._data["msg"], exc_info=exc_info)
self._logs.append(log)
def debug(self, msg: str, *args: object, | |
<reponame>icesat-2UT/PhoREAL<filename>source_code/icesatBin.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 13:45:53 2020
@author: eguenther
"""
import os
import argparse
import ctypes
from shutil import copyfile
from numpy.ctypeslib import ndpointer
import pandas as pd
import numpy as np
try:
from scipy import stats
except:
print('scipy.stats import failed')
from scipy import interpolate
import h5py
import time
from icesatReader import get_atl03_struct
from icesatReader import get_atl08_struct
root = os.path.dirname(__file__)
superFilterFile_windows = os.path.join(root,'closest_x64.dll')
superFilterFile_linux = os.path.join(root,'phorealc.so')
def indexMatch(measuredArray,truthArray):
A = np.array(measuredArray)
B = np.array(truthArray)
C = np.empty((len(B)))
if os.name == 'nt':
lib = ctypes.cdll.LoadLibrary(os.path.abspath(superFilterFile_windows))
else:
lib = ctypes.cdll.LoadLibrary(os.path.abspath(superFilterFile_linux))
fun = lib.cfun
fun.restype = None
fun.argtypes = [ndpointer(ctypes.c_double, flags="C_CONTIGUOUS"),
ctypes.c_size_t,
ndpointer(ctypes.c_double, flags="C_CONTIGUOUS"),
ndpointer(ctypes.c_double, flags="C_CONTIGUOUS"),
ctypes.c_size_t]
fun(A, A.size, B, C, B.size)
# print("Complete")
return np.array(C).astype(int)
def get_max100(series):
try:
max98 = np.nanmax(series)
except:
max98 = np.nan
return max98
def get_max98(series):
try:
max98 = np.percentile(series, 98)
except:
max98 = np.nan
return max98
def get_max95(series):
try:
max95 = np.percentile(series, 95)
except:
max95 = np.nan
return max95
def get_max90(series):
try:
max90 = np.percentile(series, 90)
except:
max90 = np.nan
return max90
def get_max85(series):
try:
max85 = np.percentile(series, 85)
except:
max85 = np.nan
return max85
def get_max80(series):
try:
max80 = np.percentile(series, 80)
except:
max80 = np.nan
return max80
def get_max75(series):
try:
max75 = np.percentile(series, 75)
except:
max75 = np.nan
return max75
def get_max70(series):
try:
max70 = np.percentile(series, 70)
except:
max70 = np.nan
return max70
def get_max65(series):
try:
max65 = np.percentile(series, 65)
except:
max65 = np.nan
return max65
def get_max60(series):
try:
max60 = np.percentile(series, 60)
except:
max60 = np.nan
return max60
def get_max55(series):
try:
max55 = np.percentile(series, 55)
except:
max55 = np.nan
return max55
def get_max50(series):
try:
max50 = np.percentile(series, 50)
except:
max50 = np.nan
return max50
def get_max45(series):
try:
max45 = np.percentile(series, 45)
except:
max45 = np.nan
return max45
def get_max40(series):
try:
max40 = np.percentile(series, 40)
except:
max40 = np.nan
return max40
def get_max35(series):
try:
max35 = np.percentile(series, 35)
except:
max35 = np.nan
return max35
def get_max30(series):
try:
max30 = np.percentile(series, 30)
except:
max30 = np.nan
return max30
def get_max25(series):
try:
max25 = np.percentile(series, 25)
except:
max25 = np.nan
return max25
def get_max20(series):
try:
max20 = np.percentile(series, 20)
except:
max20 = np.nan
return max20
def get_max15(series):
try:
max15 = np.percentile(series, 15)
except:
max15 = np.nan
return max15
def get_max10(series):
try:
max10 = np.percentile(series, 10)
except:
max10 = np.nan
return max10
def get_max5(series):
try:
max5 = np.percentile(series, 5)
except:
max5 = np.nan
return max5
def get_min(series):
try:
min0 = np.percentile(series, 0)
except:
min0 = np.nan
return min0
def get_len(series):
try:
length = len(series)
except:
length = np.nan
return length
def get_len_unique(series):
try:
length = len(np.unique(series))
except:
length = np.nan
return length
def get_range(series):
try:
r = np.ptp(series)
except:
r = np.nan
return r
def get_std(series):
try:
s = np.std(series)
except:
s = np.nan
return s
def get_mode(series):
try:
mode = stats.mode(np.array(series))[0][0]
except:
mode = np.nan
return mode
def get_mean(series):
try:
m = np.mean(series)
except:
m = np.nan
return m
def above_op(series):
q_list = [0,10,20,25,30,40,50,60,70,75,80,90,98,100]
try:
all_percent = [np.percentile(series, q_list)]
except:
# all_percent = np.nan
all_percent = np.array([np.nan, np.nan,np.nan,np.nan,np.nan,np.nan,
np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,
np.nan,np.nan])
return all_percent
def calculate_seg_meteric(df_in, df_out, classification, operation, field,
outfield, key_field = 'bin_id',
classfield = 'classification'):
df_filter = df_in[df_in[classfield].isin(classification)]
zgroup = df_filter.groupby(key_field)
zout = zgroup.aggregate(operation)
zout[key_field] = zout.index
zout = zout.reset_index(drop = True)
# zout['segment_id_beg'] = zout['seg_id']
zout[outfield] = zout[field]
zout = zout.filter([outfield,key_field])
df_out = df_out.merge(zout, on=key_field,how='left')
return df_out
def create_key_df(df, field, res):
start = np.min(df[field])
stop = np.max(df[field])
beg = np.arange(start,stop,res)
mid = beg + (res / 2)
end = beg + (res)
res_field = end - beg
key_df = pd.DataFrame(beg,columns=['beg_id'])
key_df = pd.concat([key_df,pd.DataFrame(mid
,columns=['mid_id'])],axis=1)
key_df = pd.concat([key_df,pd.DataFrame(
end,columns=['end_id'])],axis=1)
key_df = pd.concat([key_df,pd.DataFrame(
res_field,columns=['res'])],axis=1)
key_df = pd.concat([key_df,pd.DataFrame(
mid,columns=['bin_id'])],axis=1)
return key_df
def get_target_keys(key_df, df, field, res = -1):
if len(np.unique(key_df.res)) == 1:
res = key_df.res[0]
elif res != -1:
res = res
else:
res = key_df.res[0]
# res = 1
mid = np.array(df[field])
target_mid = np.array(key_df.mid_id)
minInd = indexMatch(target_mid, mid)
datalen = len(target_mid)
minInd[minInd >= datalen] = (datalen - 1)
include = np.zeros(len(mid))
seg_at_comp = np.array([target_mid[x] for x in minInd])
# seg_id_truth = np.array([seg_id[x] for x in index])
diff = np.abs(seg_at_comp - mid)
include[diff <= (res/2)] = 1
target_key = np.array(key_df.bin_id[minInd])
return target_key, include
def agg_keys(key_df, df, agg_list, key = 'bin_id'):
for i in agg_list:
# print(i)
dt2 = time.time()
agg = i.split(';')
if 'perfect' in agg[2]:
c = 'perfect_class'
elif('bathy' in agg[0]):
c = 'Label'
else:
c = 'classification'
class_str = agg[4]
class_list_str = class_str.strip('][').split(',')
class_list = []
if len(class_list_str) > 0:
for j in range(0,len(class_list_str)):
class_list.append(int(class_list_str[j]))
if 'median' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
np.median,agg[2],agg[1],
key_field = key,
classfield = c)
elif 'count' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
np.size,agg[2],agg[1], key_field = key,
classfield = c)
elif 'count_unique' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_len_unique,agg[2],agg[1], key_field = key,
classfield = c)
elif 'range' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
np.ptp,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max100' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max100,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max98' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max98,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max95' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max95,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max90' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max90,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max85' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max85,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max80' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max95,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max75' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max75,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max70' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max70,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max65' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max65,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max60' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max60,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max55' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max55,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max50' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max50,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max45' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max45,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max40' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max40,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max35' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max35,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max30' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max30,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max25' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max25,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max20' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max20,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max15' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max15,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max10' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max10,agg[2],agg[1], key_field = key,
classfield = c)
elif 'max5' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_max5,agg[2],agg[1], key_field = key,
classfield = c)
elif 'min' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_min,agg[2],agg[1], key_field = key,
classfield = c)
elif 'mode' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_mode,agg[2],agg[1], key_field = key,
classfield = c)
elif 'std' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_std,agg[2],agg[1], key_field = key,
classfield = c)
elif 'mean' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_mean,agg[2],agg[1], key_field = key,
classfield = c)
elif 'get_len' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, class_list,
get_len,agg[2],agg[1], key_field = key,
classfield = c)
elif 'rh_canopy' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, [1],
np.median,agg[2],'ground', key_field = key,
classfield = c)
key_df = calculate_seg_meteric(df, key_df, [2,3],
np.median,agg[2],'canopy', key_field = key,
classfield = c)
key_df[agg[1]] = key_df.canopy - key_df.ground
key_df[agg[1]][key_df[agg[1]] < 0] = 0
key_df[agg[1]][key_df[agg[1]] > 130] = np.nan
key_df = key_df.drop(columns=['ground','canopy'])
elif 'radiometry' in agg[3]:
key_df = calculate_seg_meteric(df, key_df, [-1,0,1,2,3],
get_len_unique,agg[2],'unique_time', key_field = key,
classfield = c)
key_df = calculate_seg_meteric(df, key_df, class_list, | |
# Copyright 2021 Hathor Labs
#
# 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 hashlib
from abc import ABC, abstractmethod, abstractproperty
from collections import deque
from threading import Lock
from typing import Any, Dict, FrozenSet, Iterable, Iterator, List, NamedTuple, Optional, Set, Tuple, cast
from weakref import WeakValueDictionary
from intervaltree.interval import Interval
from structlog import get_logger
from hathor.conf import HathorSettings
from hathor.indexes import IndexesManager, TokensIndex, TransactionsIndex, WalletIndex
from hathor.pubsub import HathorEvents, PubSubManager
from hathor.transaction.base_transaction import BaseTransaction
from hathor.transaction.block import Block
from hathor.transaction.storage.block_height_index import BlockHeightIndex
from hathor.transaction.storage.exceptions import TransactionDoesNotExist, TransactionIsNotABlock
from hathor.transaction.storage.traversal import BFSWalk
from hathor.transaction.transaction import Transaction
from hathor.transaction.transaction_metadata import TransactionMetadata, ValidationState
from hathor.util import not_none
settings = HathorSettings()
INF_HEIGHT: int = 1_000_000_000_000
class AllTipsCache(NamedTuple):
timestamp: int
tips: Set[Interval]
merkle_tree: bytes
hashes: List[bytes]
class _DirDepValue(Dict[bytes, ValidationState]):
"""This class is used to add a handy method to values on dependency indexes."""
def is_ready(self) -> bool:
"""True if all deps' validation are fully connected."""
return all(val.is_fully_connected() for val in self.values())
class _AddToCacheItem(NamedTuple):
height: int
hash: bytes
timestamp: int
class TransactionStorage(ABC):
"""Legacy sync interface, please copy @deprecated decorator when implementing methods."""
pubsub: Optional[PubSubManager]
with_index: bool
wallet_index: Optional[WalletIndex]
tokens_index: Optional[TokensIndex]
block_index: Optional[IndexesManager]
tx_index: Optional[IndexesManager]
all_index: Optional[IndexesManager]
log = get_logger()
def __init__(self):
from hathor.transaction.genesis import BLOCK_GENESIS
# Weakref is used to guarantee that there is only one instance of each transaction in memory.
self._tx_weakref: WeakValueDictionary[bytes, BaseTransaction] = WeakValueDictionary()
self._tx_weakref_disabled: bool = False
# This lock is needed everytime a storage is getting a tx from the weakref and,
# in the case the tx is not there, it creates a new object to save there.
# We were having some concurrent access and two different objects were being saved
# in the weakref, what is an error (https://github.com/HathorNetwork/hathor-core/issues/70)
# With this lock we guarantee there isn't going to be any problem with concurrent access
self._weakref_lock_per_hash: WeakValueDictionary[bytes, Lock] = WeakValueDictionary()
# This is a global lock used to prevent concurrent access when getting the tx lock in the dict above
self._weakref_lock: Lock = Lock()
# Cache for the best block tips
# This cache is updated in the consensus algorithm.
self._best_block_tips_cache = None
# If should create lock when getting a transaction
self._should_lock = False
# Provide local logger
self.log = self.log.new()
# Cache for the latest timestamp of all tips with merkle tree precalculated to be used on the sync algorithm
# This cache is invalidated every time a new tx or block is added to the cache and
# self._all_tips_cache.timestamp is always self.latest_timestamp
self._all_tips_cache: Optional[AllTipsCache] = None
# Initialize cache for genesis transactions.
self._genesis_cache: Dict[bytes, BaseTransaction] = {}
# Key storage attribute to save if the full node is running a full verification
self._running_full_verification_attribute: str = 'running_full_verification'
# Key storage attribute to save if the manager is running
self._manager_running_attribute: str = 'manager_running'
# Key storage attribute to save if the node has clean db
self._clean_db_attribute: str = 'clean_db'
# Cache of block hash by height
self._block_height_index = BlockHeightIndex()
# Direct and reverse dependency mapping (i.e. needs and needed by)
self._dir_dep_index: Dict[bytes, _DirDepValue] = {}
self._rev_dep_index: Dict[bytes, Set[bytes]] = {}
self._txs_with_deps_ready: Set[bytes] = set()
# Needed txs (key: tx missing, value: requested by)
self._needed_txs_index: Dict[bytes, Tuple[int, bytes]] = {}
# Hold txs that have not been confirmed
self._mempool_tips_index: Set[bytes] = set()
# Hold blocks that can be used as the next parent block
# XXX: if there is more than one they must all have the same score, must always have at least one hash
self._parent_blocks_index: Set[bytes] = {BLOCK_GENESIS.hash}
# rev-dep-index methods:
def count_deps_index(self) -> int:
"""Count total number of txs with dependencies."""
return len(self._dir_dep_index)
def _get_validation_state(self, tx: bytes) -> ValidationState:
"""Query database for the validation state of a transaction, returns INITIAL when tx does not exist."""
tx_meta = self.get_metadata(tx)
if tx_meta is None:
return ValidationState.INITIAL
return tx_meta.validation
def _update_deps(self, deps: _DirDepValue) -> None:
"""Propagate the new validation state of the given deps."""
for tx, validation in deps.items():
self._update_validation(tx, validation)
def _update_validation(self, tx: bytes, validation: ValidationState) -> None:
"""Propagate the new validation state of a given dep."""
for cousin in self._rev_dep_index[tx].copy():
deps = self._dir_dep_index[cousin]
# XXX: this check serves to avoid calling is_ready() when nothing changed
if deps[tx] != validation:
deps[tx] = validation
if deps.is_ready():
self.del_from_deps_index(cousin)
self._txs_with_deps_ready.add(cousin)
def add_to_deps_index(self, tx: bytes, deps: Iterable[bytes]) -> None:
"""Call to add all dependencies a transaction has."""
# deps are immutable for a given hash
_deps = _DirDepValue((dep, self._get_validation_state(dep)) for dep in deps)
# short circuit add directly to ready
if _deps.is_ready():
self._txs_with_deps_ready.add(tx)
return
# add direct deps
if __debug__ and tx in self._dir_dep_index:
# XXX: dependencies set must be immutable
assert self._dir_dep_index[tx].keys() == _deps.keys()
self._dir_dep_index[tx] = _deps
# add reverse dep
for rev_dep in _deps:
if rev_dep not in self._rev_dep_index:
self._rev_dep_index[rev_dep] = set()
self._rev_dep_index[rev_dep].add(tx)
def del_from_deps_index(self, tx: bytes) -> None:
"""Call to remove tx from all reverse dependencies, for example when validation is complete."""
_deps = self._dir_dep_index.pop(tx, _DirDepValue())
for rev_dep in _deps.keys():
rev_deps = self._rev_dep_index[rev_dep]
if tx in rev_deps:
rev_deps.remove(tx)
if not rev_deps:
del self._rev_dep_index[rev_dep]
def is_ready_for_validation(self, tx: bytes) -> bool:
""" Whether a tx can be fully validated (implies fully connected).
"""
return tx in self._txs_with_deps_ready
def remove_ready_for_validation(self, tx: bytes) -> None:
""" Removes from ready for validation set.
"""
self._txs_with_deps_ready.discard(tx)
def next_ready_for_validation(self, *, dry_run: bool = False) -> Iterator[bytes]:
""" Yields and removes all txs ready for validation even if they become ready while iterating.
"""
if dry_run:
cur_ready = self._txs_with_deps_ready.copy()
else:
cur_ready, self._txs_with_deps_ready = self._txs_with_deps_ready, set()
while cur_ready:
yield from iter(cur_ready)
if dry_run:
cur_ready = self._txs_with_deps_ready - cur_ready
else:
cur_ready, self._txs_with_deps_ready = self._txs_with_deps_ready, set()
def iter_deps_index(self) -> Iterator[bytes]:
"""Iterate through all hashes depended by any tx or block."""
yield from self._rev_dep_index.keys()
def get_rev_deps(self, tx: bytes) -> FrozenSet[bytes]:
"""Get all txs that depend on the given tx (i.e. its reverse depdendencies)."""
return frozenset(self._rev_dep_index.get(tx, set()))
def children_from_deps(self, tx: bytes) -> List[bytes]:
"""Return the hashes of all reverse dependencies that are children of the given tx.
That is, they depend on `tx` because they are children of `tx`, and not because `tx` is an input. This is
useful for pre-filling the children metadata, which would otherwise only be updated when
`update_initial_metadata` is called on the child-tx.
"""
return [not_none(rev.hash) for rev in map(self.get_transaction, self.get_rev_deps(tx)) if tx in rev.parents]
# needed-txs-index methods:
def has_needed_tx(self) -> bool:
"""Whether there is any tx on the needed tx index."""
return bool(self._needed_txs_index)
def is_tx_needed(self, tx: bytes) -> bool:
"""Whether a tx is in the requested tx list."""
return tx in self._needed_txs_index
def needed_index_height(self, tx: bytes) -> int:
"""Indexed height from the needed tx index."""
return self._needed_txs_index[tx][0]
def remove_from_needed_index(self, tx: bytes) -> None:
"""Remove tx from needed txs index, tx doesn't need to be in the index."""
self._needed_txs_index.pop(tx, None)
def get_next_needed_tx(self) -> bytes:
"""Choose the start hash for downloading the needed txs"""
# This strategy maximizes the chance to download multiple txs on the same stream
# find the tx with highest "height"
# XXX: we could cache this onto `needed_txs` so we don't have to fetch txs every time
height, start_hash, tx = max((h, s, t) for t, (h, s) in self._needed_txs_index.items())
self.log.debug('next needed tx start', needed=len(self._needed_txs_index), start=start_hash.hex(),
height=height, needed_tx=tx.hex())
return start_hash
def add_needed_deps(self, tx: BaseTransaction) -> None:
if isinstance(tx, Block):
height = tx.get_metadata().height
else:
assert isinstance(tx, Transaction)
first_block = tx.get_metadata().first_block
if first_block is None:
# XXX: consensus did not run yet to update first_block, what should we do?
# I'm defaulting the height to `inf` (practically), this should make it heightest priority when
# choosing which transactions to fetch next
height = INF_HEIGHT
else:
block = self.get_transaction(first_block)
assert | |
<reponame>mchelen-gov/integrations-core
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import random
import time
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, cast
import click
from .....fs import basepath, chdir
from .....subprocess import SubprocessError, run_command
from .....utils import get_next
from ....config import APP_DIR
from ....constants import CHANGELOG_LABEL_PREFIX, CHANGELOG_TYPE_NONE, get_root
from ....github import get_pr, get_pr_from_hash, get_pr_labels, get_pr_milestone, parse_pr_number
from ....trello import TrelloClient
from ....utils import format_commit_id
from ...console import CONTEXT_SETTINGS, abort, echo_failure, echo_info, echo_success, echo_waiting, echo_warning
from .fixed_cards_mover import FixedCardsMover
from .rc_build_cards_updater import RCBuildCardsUpdater
from .tester_selector.tester_selector import TesterSelector, TrelloUser, create_tester_selector
def create_trello_card(
client: TrelloClient,
testerSelector: TesterSelector,
teams: List[str],
pr_num: int,
pr_title: str,
pr_url: str,
pr_labels: List[str],
pr_body: str,
dry_run: bool,
pr_author: str,
config: dict,
card_assignments: dict,
) -> None:
labels = ', '.join(f'`{label}`' for label in sorted(pr_labels))
body = f'''\
Pull request: {pr_url}
Author: `{pr_author}`
Labels: {labels}
{pr_body}'''
for team in teams:
tester_name, member = pick_card_member(config, pr_author, team.lower(), card_assignments)
if member is None:
tester = _select_trello_tester(client, testerSelector, team, pr_author, pr_num, pr_url)
if tester:
member = tester.id
tester_name = tester.full_name
if dry_run:
echo_success(f'Will create a card for {tester_name}: ', nl=False)
echo_info(pr_title)
continue
creation_attempts = 3
for attempt in range(3):
rate_limited, error, response = client.create_card(team, pr_title, body, member)
if rate_limited:
wait_time = 10
echo_warning(
'Attempt {} of {}: A rate limit in effect, retrying in {} '
'seconds...'.format(attempt + 1, creation_attempts, wait_time)
)
time.sleep(wait_time)
elif error:
if attempt + 1 == creation_attempts:
echo_failure(f'Error: {error}')
break
wait_time = 2
echo_warning(
'Attempt {} of {}: An error has occurred, retrying in {} '
'seconds...'.format(attempt + 1, creation_attempts, wait_time)
)
time.sleep(wait_time)
else:
echo_success(f'Created card for team {team}: ', nl=False)
echo_info(response.json().get('url'))
break
def _select_trello_tester(
trello: TrelloClient, testerSelector: TesterSelector, team: str, pr_author: str, pr_num: int, pr_url: str
) -> Optional[TrelloUser]:
team_label = None
for label, t in trello.label_team_map.items():
if t == team:
team_label = label
break
trello_user = None
if team_label in trello.label_github_team_map:
github_team = trello.label_github_team_map[team_label]
if pr_author:
trello_user = testerSelector.get_next_tester(pr_author, github_team, pr_num)
else:
echo_warning(f'Invalid team {team} for {pr_url}')
if not trello_user:
echo_warning(f'Cannot assign tester for {pr_author} {pr_url}')
return None
return trello_user
def _all_synced_with_remote(refs: Sequence[str]) -> bool:
fetch_command = 'git fetch --dry'
result = run_command(fetch_command, capture=True, check=True)
return all(ref not in result.stderr for ref in refs)
def _get_and_parse_commits(base_ref: str, target_ref: str) -> List[Tuple[str, str]]:
echo_info(f'Getting diff between {base_ref!r} and {target_ref!r}... ', nl=False)
# Outputs as '<sign> <commit_hash> <subject line>', e.g.:
# '+ 32837dac944b9dcc23d6b54370657d661226c3ac Update README.md (#8778)'
diff_command = f'git --no-pager cherry -v {base_ref} {target_ref}'
try:
result = run_command(diff_command, capture=True, check=True)
except SubprocessError:
echo_failure('Failed!')
raise
echo_success('Success!')
lines: List[str] = result.stdout.splitlines()
commits = []
for line in reversed(lines):
sign, commit_hash, commit_subject = line.split(' ', 2)
if sign == '-':
echo_info(f'Skipping {commit_subject}, it was cherry-picked in {base_ref}')
continue
commits.append((commit_hash, commit_subject))
return commits
def get_commits_between(base_ref: str, target_ref: str, *, root: str) -> List[Tuple[str, str]]:
with chdir(root):
if not _all_synced_with_remote((base_ref, target_ref)):
abort(f'Your repository is not sync with the remote repository. Please run `git fetch` in {root!r} folder.')
try:
return _get_and_parse_commits(base_ref, target_ref)
except SubprocessError as exc:
echo_failure(str(exc))
echo_failure('Unable to get the diff.')
echo_info(
f'HINT: ensure {base_ref!r} and {target_ref!r} both refer to a valid git reference '
'(such as a tag or a release branch).'
)
raise click.Abort
def pick_card_member(config: dict, author: str, team: str, card_assignments: dict) -> Tuple[Any, Any]:
"""Return a member to assign to the created issue.
In practice, it returns one trello user which is not the PR author, for the given team.
For it to work, you need a `trello_users_$team` table in your ddev configuration,
with keys being github users and values being their corresponding trello IDs (not names).
For example::
[trello_users_integrations]
john = "xxxxxxxxxxxxxxxxxxxxx"
alice = "yyyyyyyyyyyyyyyyyyyy"
"""
users = config.get(f'trello_users_{team}')
if not users:
return None, None
if team not in card_assignments:
# initialize map team -> user -> QA cards assigned
team_members = list(users)
random.shuffle(team_members)
card_assignments[team] = dict.fromkeys(team_members, 0)
member = min([member for member in card_assignments[team] if member != author], key=card_assignments[team].get)
card_assignments[team][member] += 1
return member, users[member]
@click.command(
context_settings=CONTEXT_SETTINGS, short_help='Create a Trello card for each change that needs to be tested'
)
@click.argument('base_ref')
@click.argument('target_ref')
@click.option('--milestone', help='The PR milestone to filter by')
@click.option('--dry-run', '-n', is_flag=True, help='Only show the changes')
@click.option(
'--update-rc-builds-cards', is_flag=True, help='Update cards in RC builds column with `target_ref` version'
)
@click.option(
'--move-cards',
is_flag=True,
help='Do not create a card for a change, but move the existing card from '
+ '`HAVE BUGS - FIXME` or `FIXED - Ready to Rebuild` to INBOX team',
)
@click.pass_context
def testable(
ctx: click.Context,
base_ref: str,
target_ref: str,
milestone: str,
dry_run: bool,
update_rc_builds_cards: bool,
move_cards: bool,
) -> None:
"""
Create a Trello card for changes since a previous release (referenced by `BASE_REF`)
that need to be tested for the next release (referenced by `TARGET_REF`).
`BASE_REF` and `TARGET_REF` can be any valid git references. It practice, you should use either:
* A tag: `7.16.1`, `7.17.0-rc.4`, ...
* A release branch: `6.16.x`, `7.17.x`, ...
* The `master` branch.
NOTE: using a minor version shorthand (e.g. `7.16`) is not supported, as it is ambiguous.
Example: assuming we are working on the release of 7.17.0, we can...
* Create cards for changes between a previous Agent release and `master` (useful when preparing an initial RC):
`$ ddev release trello testable 7.16.1 origin/master`
* Create cards for changes between a previous RC and `master` (useful when preparing a new RC, and a separate
release branch was not created yet):
`$ ddev release trello testable 7.17.0-rc.2 origin/master`
* Create cards for changes between a previous RC and a release branch (useful to only review changes in a
release branch that has diverged from `master`):
`$ ddev release trello testable 7.17.0-rc.4 7.17.x`
* Create cards for changes between two arbitrary tags, e.g. between RCs:
`$ ddev release trello testable 7.17.0-rc.4 7.17.0-rc.5`
TIP: run with `ddev -x release trello testable` to force the use of the current directory.
To avoid GitHub's public API rate limits, you need to set
`github.user`/`github.token` in your config file or use the
`DD_GITHUB_USER`/`DD_GITHUB_TOKEN` environment variables.
See trello subcommand for details on how to setup access:
`ddev release trello -h`.
"""
root = get_root()
repo = basepath(root)
if repo not in ('integrations-core', 'datadog-agent'):
abort(f'Repo `{repo}` is unsupported.')
commits = get_commits_between(base_ref, target_ref, root=root)
num_changes = len(commits)
if not num_changes:
echo_warning('No changes.')
return
if repo == 'integrations-core':
options = {
'1': 'Integrations',
'2': 'Infra-Integrations',
'3': 'Containers',
'4': 'Core',
'5': 'Platform',
'6': 'Tools and Libraries',
'7': 'Database Monitoring',
's': 'Skip',
'q': 'Quit',
}
else:
options = {
'1': 'Core',
'2': 'Containers',
'3': 'Logs',
'4': 'Platform',
'5': 'Networks',
'6': 'Processes',
'7': 'Trace',
'8': 'Integrations',
'9': 'Infra-Integrations',
'10': 'Tools and Libraries',
'11': 'Database Monitoring',
's': 'Skip',
'q': 'Quit',
}
default_option = get_next(options)
options_prompt = f'Choose an option (default {options[default_option]}): '
options_text = '\n' + '\n'.join('{} - {}'.format(key, value) for key, value in options.items())
commit_ids: Set[str] = set()
user_config = cast(Dict[Any, Any], ctx.obj)
trello = TrelloClient(user_config)
fixed_cards_mover = None
if move_cards:
fixed_cards_mover = FixedCardsMover(trello, dry_run)
rc_build_cards_updater = None
if update_rc_builds_cards:
rc_build_cards_updater = RCBuildCardsUpdater(trello, target_ref)
card_assignments: Dict[str, Dict[str, int]] = {}
github_teams = trello.label_github_team_map.values()
testerSelector = create_tester_selector(trello, repo, github_teams, user_config, APP_DIR)
for i, (commit_hash, commit_subject) in enumerate(commits, 1):
commit_id = parse_pr_number(commit_subject)
if commit_id is not None:
api_response = get_pr(commit_id, user_config, raw=True)
if api_response.status_code == 401:
abort('Access denied. Please ensure your GitHub token has correct permissions.')
elif api_response.status_code == 403:
echo_failure(
'Error getting info for #{}. Please set a GitHub HTTPS '
'token to avoid rate limits.'.format(commit_id)
)
continue
elif api_response.status_code == 404:
echo_info(f'Skipping #{commit_id}, not a pull request...')
continue
api_response.raise_for_status()
pr_data = api_response.json()
else:
try:
api_response = get_pr_from_hash(commit_hash, repo, user_config, raw=True)
if api_response.status_code == 401:
abort('Access denied. Please ensure your GitHub token has correct permissions.')
elif api_response.status_code == 403:
echo_failure(
'Error getting info for #{}. Please set a GitHub HTTPS '
'token to avoid rate limits.'.format(commit_hash)
)
continue
api_response.raise_for_status()
pr_data = api_response.json()
pr_data = pr_data.get('items', [{}])[0]
# Commit to master
except IndexError:
pr_data = {
'number': commit_hash,
'html_url': f'https://github.com/DataDog/{repo}/commit/{commit_hash}',
}
commit_id = str(pr_data.get('number', ''))
if commit_id and commit_id in commit_ids:
echo_info(f'Already seen PR #{commit_id}, skipping it.')
continue
commit_ids.add(commit_id)
pr_labels = sorted(get_pr_labels(pr_data))
documentation_pr = False
nochangelog_pr = | |
<filename>Cinema 4D/appdir_common/plugins/DazToC4D/lib/Materials.py
from __future__ import division
from xml.etree.ElementTree import TreeBuilder
import c4d
import os
import sys
from shutil import copyfile
from c4d import documents, gui
from .Utilities import dazToC4Dutils
from .CustomIterators import ObjectIterator, TagIterator
from .Definitions import RES_DIR
from .MaterialHelpers import MaterialHelpers
from .CustomCmd import Cinema4DCommands as dzc4d
try:
import redshift
except:
pass
class Materials:
def checkStdMats(self):
doc = c4d.documents.GetActiveDocument()
docMaterials = doc.GetMaterials()
noStd = True
for mat in docMaterials:
matName = mat.GetName()
if mat.GetType() == 5703:
noStd = False
if noStd == True:
gui.MessageDialog(
"No standard mats found. This scene was already converted"
)
return noStd
def fixGenEyes(self, path):
folder_DazToC4D_res = RES_DIR # Adds the res folder to the path
folder_DazToC4D_xtra = os.path.join(
folder_DazToC4D_res, "xtra"
) # Adds the res folder to the path
file_G3_IrisFixMap = os.path.join(folder_DazToC4D_xtra, "G3_Iris_Alpha.psd")
destination_G3_IrisFixMap = os.path.join(path, "G3_Iris_Alpha.psd")
try:
copyfile(file_G3_IrisFixMap, destination_G3_IrisFixMap)
except:
print("Iris Map transfer...Skipped.")
doc = c4d.documents.GetActiveDocument()
docMaterials = doc.GetMaterials()
for mat in docMaterials:
if "Iris" in mat.GetName():
matDiffuseMap = ""
try:
matDiffuseMap = mat[c4d.MATERIAL_COLOR_SHADER][
c4d.BITMAPSHADER_FILENAME
]
except:
pass
skipThis = False
if "3duG3FTG2_Eyes" in matDiffuseMap:
skipThis = True
if skipThis == False and os.path.exists(destination_G3_IrisFixMap):
mat[c4d.MATERIAL_USE_ALPHA] = True
shda = c4d.BaseList2D(c4d.Xbitmap)
shda[c4d.BITMAPSHADER_FILENAME] = destination_G3_IrisFixMap
mat[c4d.MATERIAL_ALPHA_SHADER] = shda
mat.InsertShader(shda)
def specificFiguresFixes(self):
doc = c4d.documents.GetActiveDocument()
figureModel = ""
def findMatName(matToFind):
matFound = None
sceneMats = doc.GetMaterials()
for mat in sceneMats:
matName = mat.GetName()
if matToFind in matName:
matFound = mat
return matFound
return matFound
# TOON GENERATION 2
doc = documents.GetActiveDocument()
sceneMats = doc.GetMaterials()
# ZOMBIE ... GEN3...
if findMatName("Cornea") != None and findMatName("EyeMoisture") == None:
mat = findMatName("Cornea")
mat[c4d.MATERIAL_USE_ALPHA] = False
for mat in sceneMats:
matName = mat.GetName()
if "Eyelashes" in matName:
if mat[c4d.MATERIAL_ALPHA_SHADER] == None:
try:
shaderColor = c4d.BaseList2D(
c4d.Xcolor
) # create a bitmap shader for the material
mat.InsertShader(shaderColor)
mat[c4d.MATERIAL_USE_ALPHA] = True
mat[c4d.MATERIAL_ALPHA_SHADER] = shaderColor
mat[c4d.MATERIAL_ALPHA_SHADER][c4d.COLORSHADER_BRIGHTNESS] = 0.0
except:
pass
c4d.EventAdd()
def transpMapFix(self, mat):
if mat[c4d.MATERIAL_TRANSPARENCY_SHADER] != None:
mat[c4d.MATERIAL_ALPHA_SHADER] = mat[c4d.MATERIAL_TRANSPARENCY_SHADER]
mat[c4d.MATERIAL_USE_TRANSPARENCY] = 0
mat[c4d.MATERIAL_USE_ALPHA] = 1
mat[c4d.MATERIAL_TRANSPARENCY_SHADER] = None
def fixMaterials(self):
doc = c4d.documents.GetActiveDocument()
# Process for all materials of scene
docMaterials = doc.GetMaterials()
for mat in docMaterials:
self.transpMapFix(mat)
matName = mat.GetName()
eyesMats = [
"Eyelashes",
"Cornea",
"EyeMoisture",
"EyeMoisture2",
"Sclera",
"Irises",
]
layer = mat.GetReflectionLayerIndex(0)
mat[c4d.MATERIAL_NORMAL_STRENGTH] = 0.25
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.05
try: # Remove extra layers stuff...
mat.RemoveReflectionLayerIndex(1)
mat.RemoveReflectionLayerIndex(2)
mat.RemoveReflectionLayerIndex(3)
mat.RemoveReflectionLayerIndex(4)
except:
pass
if matName in eyesMats:
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS
] = 0.13
if (
"Moisture" in matName
or "Cornea" in matName
or "Tear" in matName
or "EyeReflection" in matName
):
mat[c4d.MATERIAL_COLOR_COLOR] = c4d.Vector(0.2, 0.2, 0.2)
mat[c4d.MATERIAL_USE_TRANSPARENCY] = True
mat[c4d.MATERIAL_TRANSPARENCY_COLOR] = c4d.Vector(0.9, 0.9, 0.9)
mat[c4d.MATERIAL_TRANSPARENCY_REFRACTION] = 1.0
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_DISTRIBUTION
] = 0 # 0 = Reflection(legacy)
mat[c4d.MATERIAL_USE_TRANSPARENCY] = True
mat[c4d.MATERIAL_TRANSPARENCY_FRESNEL] = False
mat[c4d.MATERIAL_TRANSPARENCY_EXITREFLECTIONS] = False
mat[c4d.MATERIAL_TRANSPARENCY_COLOR] = c4d.Vector(0.95, 0.95, 0.95)
mat[c4d.MATERIAL_TRANSPARENCY_REFRACTION] = 1.33
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_COLOR_COLOR] = c4d.Vector(
1.0, 1.0, 1.0
)
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS] = 0.0
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION
] = 0.7
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.0
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_BUMP] = 0.0
if "Eyes" in matName:
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.0
if "Pupils" in matName:
mat[c4d.MATERIAL_USE_REFLECTION] = False
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.0
if "Teeth" in matName:
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_DISTRIBUTION
] = 0 # 0 = Reflection(legacy)
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS
] = 0.07
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION
] = 0.09
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.03
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_BUMP] = 0.25
if "Mouth" in matName:
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_DISTRIBUTION
] = 0 # 0 = Reflection(legacy)
if "Sclera" in matName:
mat[c4d.MATERIAL_USE_REFLECTION] = False
mat[c4d.MATERIAL_GLOBALILLUM_RECEIVE_STRENGTH] = 2
if "Iris" in matName:
mat[c4d.MATERIAL_USE_REFLECTION] = False
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_REFLECTION
] = 0.0
mat[layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR] = 0.0
mat[
layer.GetDataID() + c4d.REFLECTION_LAYER_MAIN_DISTRIBUTION
] = 0 # 0 = Reflection(legacy)
if "Eyelash" in matName:
mat[c4d.MATERIAL_COLOR_SHADER] = None
mat[c4d.MATERIAL_COLOR_COLOR] = c4d.Vector(0.0, 0.0, 0.0)
try:
mat[c4d.MATERIAL_ALPHA_SHADER][c4d.BITMAPSHADER_FILENAME][
c4d.BITMAPSHADER_EXPOSURE
] = 1.0
except:
print("Exposure Skipped...")
c4d.CallCommand(12253, 12253) # Render All Materials
c4d.EventAdd()
def stdMatExtrafixes(self):
def setRenderToPhysical():
try:
rdata = doc.GetActiveRenderData()
vpost = rdata.GetFirstVideoPost()
rdata[c4d.RDATA_RENDERENGINE] = c4d.RDATA_RENDERENGINE_PHYSICAL
while vpost:
if vpost.CheckType(c4d.VPxmbsampler):
break
vpost = vpost.GetNext()
if not vpost:
vpost = c4d.BaseList2D(c4d.VPxmbsampler)
rdata.InsertVideoPost(vpost)
c4d.EventAdd()
except:
pass
def findMatName(matToFind):
matFound = None
sceneMats = doc.GetMaterials()
for mat in sceneMats:
matName = mat.GetName()
if matToFind in matName:
matFound = mat
return matFound
return matFound
doc = c4d.documents.GetActiveDocument()
# --- Fix duplicated Moisture material...??
myMaterials = doc.GetMaterials()
for mat in myMaterials:
if "EyeMoisture" in mat.GetName():
mat.SetName("EyeMoisture2")
return TreeBuilder
setRenderToPhysical()
figureModel = "Genesis8"
if findMatName("EyeReflection"):
figureModel = "Genesis2"
if findMatName("Fingernails"):
figureModel = "Genesis3"
# FIX MATERIAL NAMES etc... USE THIS FOR ALL CONVERTIONS NOT JUST OCTANE!
if findMatName("1_SkinFace") == None and findMatName("1_Nostril") != None:
try:
findMatName("1_Nostril").SetName("1_SkinFace")
except:
pass
if findMatName("3_SkinHand") == None and findMatName("3_SkinFoot") != None:
try:
findMatName("3_SkinFoot").SetName("3_ArmsLegs")
except:
pass
sceneMats = doc.GetMaterials()
for mat in sceneMats:
matName = mat.GetName()
try:
mat[c4d.MATERIAL_ALPHA_SHADER][c4d.BITMAPSHADER_WHITEPOINT] = 0.5
except:
pass
try:
layerTransp = mat.GetReflectionLayerTrans()
mat[
layerTransp.GetDataID() + c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS
] = 0.0
except:
pass
# GENESIS 3 Patches -------------------------
if (
figureModel == "Genesis3"
or figureModel == "Genesis2"
or figureModel == "Genesis8"
):
if "Cornea" in matName:
bmpPath = "CACA"
shaderColor = c4d.BaseList2D(
c4d.Xcolor
) # create a bitmap shader for the material
# bmpShader[c4d.BITMAPSHADER_FILENAME] = bmpPath
mat.InsertShader(shaderColor)
mat[c4d.MATERIAL_USE_ALPHA] = True
mat[c4d.MATERIAL_ALPHA_SHADER] = shaderColor
mat[c4d.MATERIAL_ALPHA_SHADER][c4d.COLORSHADER_BRIGHTNESS] = 0.0
if "Moisture" in matName or "Tear" in matName:
mat[c4d.MATERIAL_USE_ALPHA] = True
mat[c4d.MATERIAL_ALPHA_SHADER] = None
mat[c4d.MATERIAL_COLOR_COLOR] = c4d.Vector(0, 0, 0)
mat[c4d.MATERIAL_TRANSPARENCY_REFRACTION] = 1.0
if "Sclera" in matName:
try:
mat[c4d.MATERIAL_COLOR_SHADER][
c4d.BITMAPSHADER_WHITEPOINT
] = 0.8
except:
pass
c4d.EventAdd()
def addLipsMaterial(self):
doc = documents.GetActiveDocument()
obj = doc.GetFirstObject()
scene = ObjectIterator(obj)
objTags = TagIterator(obj)
for ob in scene:
objTags = TagIterator(ob)
if objTags:
for tag in objTags:
matSel = tag[c4d.TEXTURETAG_RESTRICTION]
if matSel == "Lips":
try:
old_mat = tag[c4d.TEXTURETAG_MATERIAL]
doc.SetActiveMaterial(old_mat)
c4d.CallCommand(300001022, 300001022) # Copy
c4d.CallCommand(300001023, 300001023) # Paste
newMat = doc.GetFirstMaterial()
newMat[c4d.ID_BASELIST_NAME] = "Lips"
tag[c4d.TEXTURETAG_MATERIAL] = newMat
except:
pass
c4d.EventAdd()
def matSetSpec(self, setting, value):
doc = c4d.documents.GetActiveDocument()
# Process for all materials of scene
docMaterials = doc.GetMaterials()
for mat in docMaterials:
matName = mat.GetName()
skinMats = [
"MainSkin",
"Legs",
"Torso",
"Arms",
"Face",
"Fingernails",
"Toenails",
"EyeSocket",
"Ears",
"Feet",
"Nipples",
"Forearms",
"Hips",
"Neck",
"Shoulders",
"Hands",
"Head",
"Nostrils",
]
for x in skinMats:
if x in matName:
if mat.GetType() == 1038954: # Vray
if setting == "Rough":
mat[c4d.VRAYSTDMATERIAL_REFLECTGLOSSINESS] = (
1.0 - value / 100
)
if setting == "Weight":
colorValue = value / 100
mat[c4d.VRAYSTDMATERIAL_REFLECTCOLOR] = c4d.Vector(
colorValue, colorValue, colorValue
)
if mat.GetType() == 5703: # Standard
layer = mat.GetReflectionLayerIndex(0)
if setting == "Rough":
mat[
layer.GetDataID()
+ c4d.REFLECTION_LAYER_MAIN_VALUE_ROUGHNESS
] = (value / 100)
if setting == "Weight":
mat[
layer.GetDataID()
+ c4d.REFLECTION_LAYER_MAIN_VALUE_SPECULAR
] = (value / 100)
if mat.GetType() == 1029501: # Octane
if setting == "Weight":
mat[c4d.OCT_MATERIAL_SPECULAR_FLOAT] = value / 100
if setting == "Rough":
mat[c4d.OCT_MATERIAL_ROUGHNESS_FLOAT] = value / 100
if mat.GetType() == 1036224: # Redshift
gvNodeMaster = redshift.GetRSMaterialNodeMaster(mat)
rootNode_ShaderGraph = gvNodeMaster.GetRoot()
output = rootNode_ShaderGraph.GetDown()
RShader = output.GetNext()
gvNodeMaster = redshift.GetRSMaterialNodeMaster(mat)
nodeRoot = gvNodeMaster.GetRoot()
rsMaterial = nodeRoot.GetDown().GetNext()
if setting == "Weight":
rsMaterial[c4d.REDSHIFT_SHADER_MATERIAL_REFL_WEIGHT] = (
value / 100
)
rsMaterial[c4d.REDSHIFT_SHADER_MATERIAL_REFL_IOR] = (
value / 10
)
if setting == "Rough":
rsMaterial[c4d.REDSHIFT_SHADER_MATERIAL_REFL_ROUGHNESS] = (
value / 100
)
# TODO: Verify if necessary with Material Rework
def eyeLashAndOtherFixes(self):
"""
Hard Code Changes to Eyelashes plus other Eye Mats
"""
doc = c4d.documents.GetActiveDocument()
docMaterials = doc.GetMaterials()
irisMap = ""
for mat in docMaterials: # Lashes fix... Gen2 and maybe others...
matName = mat.GetName()
if "Lashes" in matName:
try:
mat[c4d.MATERIAL_COLOR_SHADER] = None
except:
print("mat skip...")
pass
if "Iris" in matName:
try:
irisMap = mat[c4d.MATERIAL_COLOR_SHADER][c4d.BITMAPSHADER_FILENAME]
except:
pass
for mat in docMaterials: # Iris fix Gen2 and maybe others...
if mat[c4d.MATERIAL_COLOR_SHADER]:
if mat[c4d.MATERIAL_COLOR_SHADER].GetType() == 5833:
matTexture = mat[c4d.MATERIAL_COLOR_SHADER][
c4d.BITMAPSHADER_FILENAME
]
matName = mat.GetName()
if irisMap == matTexture:
if "Sclera" not in matName:
mat[c4d.MATERIAL_USE_REFLECTION] = False
for mat in docMaterials: # Fix to Tear.. Gen2...
matName = mat.GetName()
if "Tear" in matName:
mat[c4d.MATERIAL_TRANSPARENCY_COLOR] = c4d.Vector(0.94, 0.94, 0.94)
# Unused code to be deleted
def reduceMatFix(self):
doc = c4d.documents.GetActiveDocument()
myMaterials = doc.GetMaterials()
matHead = False
matTorso = False
matLegs = False
matHands = False
for mat in myMaterials:
# print mat.GetName()
if "Torso" in mat.GetName():
matTorso = | |
from typing import Optional, Union, Sequence
import math
import numpy as np
import torch
from torch import nn
from torch.nn.init import kaiming_normal_
from models.gls_parameters.switch_link_functions import (
IndividualLink,
SharedLink,
IdentityLink,
)
from torch_extensions.ops import (
cov_and_chol_from_invcholesky_param,
matvec,
batch_diag_matrix,
matmul,
)
from experiments.base_config import SwitchLinkType
from models.base_gls import ControlInputs, GLSParams
def filter_out_none(dic: dict):
return {key: val for key, val in dic.items() if val is not None}
class GLSParameters(nn.Module):
def __init__(
self,
n_state: int,
n_obs: int,
n_ctrl_state: Optional[int],
n_ctrl_obs: Optional[int],
n_switch: int,
n_base_A: Optional[int],
n_base_B: Optional[int],
n_base_C: Optional[int],
n_base_D: Optional[int],
n_base_R: int,
n_base_Q: int,
switch_link_type: SwitchLinkType,
switch_link_dims_hidden: tuple = tuple(),
switch_link_activations: nn.Module = nn.LeakyReLU(0.1, inplace=True),
make_cov_from_cholesky_avg=False,
b_fn: Optional[nn.Module] = None,
d_fn: Optional[nn.Module] = None,
init_scale_A: (float, None) = None,
init_scale_B: (float, None) = None,
init_scale_C: Optional[float] = None,
init_scale_D: Optional[float] = None,
init_scale_Q_diag: Optional[Union[float, Sequence[float]]] = None,
init_scale_R_diag: Optional[Union[float, Sequence[float]]] = None,
requires_grad_A: bool = True,
requires_grad_B: bool = True,
requires_grad_C: bool = True,
requires_grad_D: bool = True,
requires_grad_R: bool = True,
requires_grad_Q: bool = True,
full_cov_R: bool = True,
full_cov_Q: bool = True,
LQinv_logdiag_limiter: Optional[nn.Module] = None,
LRinv_logdiag_limiter: Optional[nn.Module] = None,
LRinv_logdiag_scaling: Optional[float] = None,
LQinv_logdiag_scaling: Optional[float] = None,
A_scaling: Optional[float] = None,
B_scaling: Optional[float] = None,
C_scaling: Optional[float] = None,
D_scaling: Optional[float] = None,
eye_init_A: bool = True, # False -> orthogonal
):
super().__init__()
self.make_cov_from_cholesky_avg = make_cov_from_cholesky_avg
self.LQinv_logdiag_limiter = (
LQinv_logdiag_limiter
if LQinv_logdiag_limiter is not None
else torch.nn.Identity()
)
self.LRinv_logdiag_limiter = (
LRinv_logdiag_limiter
if LRinv_logdiag_limiter is not None
else torch.nn.Identity()
)
# scaling factors: trick to roughly correct for wrong assumption in ADAM
# that all params should receive similar total updates (gradient norm)
# and thus have similar scale. --> Should fix ADAM though!
self._LRinv_logdiag_scaling = LRinv_logdiag_scaling
self._LQinv_logdiag_scaling = LQinv_logdiag_scaling
self._A_scaling = A_scaling
self._B_scaling = B_scaling
self._C_scaling = C_scaling
self._D_scaling = D_scaling
self.b_fn = b_fn
self.d_fn = d_fn
# ***** Switch Link function *****
n_bases = [
n
for n in [
n_base_A,
n_base_B,
n_base_C,
n_base_D,
n_base_R,
n_base_Q,
]
if n is not None
]
if switch_link_type == SwitchLinkType.identity:
assert len(set(n_bases)) == 1 and n_bases[0] == n_switch, (
f"n_base: {n_bases} should match switch dim {n_switch} "
f"when using identity link."
)
elif switch_link_type == SwitchLinkType.shared:
assert len(set(n_bases)) == 1
names_and_dims_out = filter_out_none(
{
"A": n_base_A,
"B": n_base_B,
"C": n_base_C,
"D": n_base_D,
"R": n_base_R,
"Q": n_base_Q,
}
)
if switch_link_type.value == SwitchLinkType.individual.value:
self.link_transformers = IndividualLink(
dim_in=n_switch,
names_and_dims_out=names_and_dims_out,
dims_hidden=switch_link_dims_hidden,
activations_hidden=switch_link_activations,
)
elif switch_link_type.value == SwitchLinkType.identity.value:
self.link_transformers = IdentityLink(
names=tuple(names_and_dims_out.keys())
)
elif switch_link_type.value == SwitchLinkType.shared.value:
dims = [dim for dim in names_and_dims_out.values()] # strip None
assert len(set(dims)) == 1
dim_out = dims[0]
self.link_transformers = SharedLink(
dim_in=n_switch,
dim_out=dim_out,
names=tuple(names_and_dims_out.keys()),
)
else:
raise Exception(f"unknown switch link type: {switch_link_type}")
# ***** Initialise GLS Parameters *****
if n_base_Q is not None:
if full_cov_Q: # tril part is always initialised zero
self.LQinv_tril = nn.Parameter(
torch.zeros((n_base_Q, n_obs, n_obs)),
requires_grad=requires_grad_Q,
)
else:
self.register_parameter("LQinv_tril", None)
init_scale_Q_diag = (
init_scale_Q_diag
if init_scale_Q_diag is not None
else [1e-4, 1e0]
)
if isinstance(init_scale_Q_diag, (list, tuple)):
self._LQinv_logdiag = nn.Parameter(
self.make_cov_init(
init_scale_cov_diag=init_scale_Q_diag,
n_base=n_base_Q,
dim_cov=n_obs,
),
requires_grad=requires_grad_Q,
)
else:
self._LQinv_logdiag = nn.Parameter(
torch.ones((n_base_Q, n_obs))
* -math.log(init_scale_Q_diag),
requires_grad=requires_grad_Q,
)
# Cannot use setter with nn.Module and nn.Parameter
self._LQinv_logdiag.data /= self._LQinv_logdiag_scaling
if n_base_R is not None:
if full_cov_R: # tril part is always initialised zero
self.LRinv_tril = nn.Parameter(
torch.zeros((n_base_R, n_state, n_state)),
requires_grad=requires_grad_R,
)
else:
self.register_parameter("LRinv_tril", None)
init_scale_R_diag = (
init_scale_R_diag
if init_scale_R_diag is not None
else [1e-4, 1e0]
)
if isinstance(init_scale_R_diag, (list, tuple)):
self._LRinv_logdiag = nn.Parameter(
self.make_cov_init(
init_scale_cov_diag=init_scale_R_diag,
n_base=n_base_R,
dim_cov=n_state,
),
requires_grad=requires_grad_R,
)
else:
self._LRinv_logdiag = nn.Parameter(
torch.ones((n_base_R, n_state))
* -math.log(init_scale_R_diag),
requires_grad=requires_grad_R,
)
# Cannot use setter with nn.Module and nn.Parameter
self._LRinv_logdiag.data /= self._LRinv_logdiag_scaling
if n_base_A is not None:
if init_scale_A is not None:
init_scale_A = torch.tensor(init_scale_A)
else:
init_var_avg_R = torch.mean(
torch.exp(-2 * self.LRinv_logdiag), dim=0,
)
# Heuristic: transition var + innovation noise var = 1, where\
# transition and noise param are averaged from base mats.
init_var_A = 1 - init_var_avg_R
init_scale_A = (torch.sqrt(init_var_A))[None, :, None]
if eye_init_A:
A_diag = torch.eye(n_state).repeat(n_base_A, 1, 1)
else:
A_diag = torch.nn.init.orthogonal_(
torch.empty(n_base_A, n_state, n_state),
)
# broadcast basemat-dim and columns -> scale columns; or scalar
self._A = nn.Parameter(
init_scale_A * A_diag, requires_grad=requires_grad_A,
)
# Cannot use setter with nn.Module and nn.Parameter
self._A.data /= self._A_scaling
else:
self.register_parameter("_A", None)
if n_base_B is not None:
if init_scale_B is not None:
self._B = nn.Parameter(
init_scale_B
* torch.randn(n_base_B, n_state, n_ctrl_state),
requires_grad=requires_grad_B,
)
else:
self._B = nn.Parameter(
torch.stack(
[
kaiming_normal_(
tensor=torch.empty(n_state, n_ctrl_state),
nonlinearity="linear",
)
for n in range(n_base_B)
],
dim=0,
),
requires_grad=requires_grad_B,
)
self._B.data /= self._B_scaling
else:
self.register_parameter("_B", None)
if n_base_C is not None:
if init_scale_C is not None:
self._C = nn.Parameter(
init_scale_C * torch.randn(n_base_C, n_obs, n_state),
requires_grad=requires_grad_C,
)
else:
self._C = nn.Parameter(
torch.stack(
[
kaiming_normal_(
tensor=torch.empty(n_obs, n_state),
nonlinearity="linear",
)
for n in range(n_base_C)
],
dim=0,
),
requires_grad=requires_grad_C,
)
self._C.data /= self._C_scaling
else:
self.register_parameter("_C", None)
if n_base_D is not None:
if init_scale_D is not None:
self._D = nn.Parameter(
init_scale_D * torch.randn(n_base_D, n_obs, n_ctrl_obs),
requires_grad=requires_grad_D,
)
else:
self._D = nn.Parameter(
torch.stack(
[
kaiming_normal_(
tensor=torch.empty(n_obs, n_ctrl_obs),
nonlinearity="linear",
)
for n in range(n_base_D)
],
dim=0,
),
requires_grad=requires_grad_D,
)
self._D.data /= self._D_scaling
else:
self.register_parameter("_D", None)
@staticmethod
def _scale_mat(mat, scaling):
return mat if (mat is None or scaling is None) else mat * scaling
@property
def LQinv_logdiag(self):
return self._scale_mat(
self._LQinv_logdiag, self._LQinv_logdiag_scaling,
)
@property
def LRinv_logdiag(self):
return self._scale_mat(
self._LRinv_logdiag, self._LRinv_logdiag_scaling,
)
@property
def A(self):
return self._scale_mat(self._A, self._A_scaling)
@property
def B(self):
return self._scale_mat(self._B, self._B_scaling)
@property
def C(self):
return self._scale_mat(self._C, self._C_scaling)
@property
def D(self):
return self._scale_mat(self._D, self._D_scaling)
@staticmethod
def make_cov_init(init_scale_cov_diag: (tuple, list), n_base, dim_cov):
def _make_single_cov_linspace_init(
init_scale_cov_diag: (tuple, list), n_base
):
assert len(init_scale_cov_diag) == 2
log_scale_cov = torch.log(torch.tensor(init_scale_cov_diag))
Lmatinv_logdiag = -torch.linspace(
log_scale_cov[0], log_scale_cov[1], n_base
)
idxs = list(range(Lmatinv_logdiag.shape[-1]))
np.random.shuffle(idxs)
Lmatinv_logdiag = Lmatinv_logdiag[..., torch.tensor(idxs)]
return Lmatinv_logdiag
cov = _make_single_cov_linspace_init(
init_scale_cov_diag=init_scale_cov_diag, n_base=n_base,
)
cov = cov[..., None].repeat(
cov.ndim * (1,) + (dim_cov,)
) # same scale for all dims.
return cov
@staticmethod
def var_from_average_scales(
weights: torch.Tensor, Linv_logdiag: torch.Tensor
):
Lmat_diag = torch.exp(-1 * Linv_logdiag)
Lmat_diag_weighted = torch.einsum("...k,kq->...q", weights, Lmat_diag)
mat_diag_weighted = Lmat_diag_weighted ** 2
return mat_diag_weighted, Lmat_diag_weighted
@staticmethod
def var_from_average_variances(
weights: torch.Tensor, Linv_logdiag: torch.Tensor
):
mat_diag = torch.exp(-2 * Linv_logdiag)
mat_diag_weighted = torch.einsum("...k,kq->...q", weights, mat_diag)
Lmat_diag_weighted = torch.sqrt(mat_diag_weighted)
return mat_diag_weighted, Lmat_diag_weighted
@staticmethod
def var_from_average_log_scales(
weights: torch.Tensor, Linv_logdiag: torch.Tensor
):
Linv_logdiag_weighted = torch.einsum(
"...k,kq->...q", weights, Linv_logdiag
)
mat_diag_weighted = torch.exp(-2 * Linv_logdiag_weighted)
Lmat_diag_weighted = torch.exp(-1 * Linv_logdiag_weighted)
return mat_diag_weighted, Lmat_diag_weighted
@staticmethod
def cov_from_average_scales(
weights: torch.Tensor,
Linv_logdiag: torch.Tensor,
Linv_tril: (torch.Tensor, None),
):
if Linv_tril is None:
(
mat_diag_weighted,
Lmat_diag_weighted,
) = GLSParameters.var_from_average_scales(
weights=weights, Linv_logdiag=Linv_logdiag,
)
mat_weighted = batch_diag_matrix(mat_diag_weighted)
Lmat_weighted = batch_diag_matrix(Lmat_diag_weighted)
else:
Lmat = torch.inverse(
torch.tril(Linv_tril, -1)
+ batch_diag_matrix(torch.exp(Linv_logdiag))
)
Lmat_weighted = torch.einsum("...k,koi->...oi", weights, Lmat)
mat_weighted = matmul(
Lmat_weighted, Lmat_weighted.transpose(-1, -2)
) # LL^T
return mat_weighted, Lmat_weighted
@staticmethod
def cov_from_average_variances(
weights: torch.Tensor,
Linv_logdiag: torch.Tensor,
Linv_tril: (torch.Tensor, None),
):
if Linv_tril is None:
(
mat_diag_weighted,
Lmat_diag_weighted,
) = GLSParameters.var_from_average_variances(
weights=weights, Linv_logdiag=Linv_logdiag,
)
mat_weighted = batch_diag_matrix(mat_diag_weighted)
Lmat_weighted = batch_diag_matrix(Lmat_diag_weighted)
else:
mat, _ = cov_and_chol_from_invcholesky_param(
Linv_tril=Linv_tril, Linv_logdiag=Linv_logdiag,
)
mat_weighted = torch.einsum("...k,kq->...q", weights, mat)
Lmat_weighted = torch.cholesky(mat_weighted)
return mat_weighted, Lmat_weighted
@staticmethod
def cov_from_average_log_scales(
weights: torch.Tensor,
Linv_logdiag: torch.Tensor,
Linv_tril: (torch.Tensor, None),
):
if Linv_tril is None:
(
mat_diag_weighted,
Lmat_diag_weighted,
) = GLSParameters.var_from_average_log_scales(
weights=weights, Linv_logdiag=Linv_logdiag,
)
mat_weighted = batch_diag_matrix(mat_diag_weighted)
Lmat_weighted = batch_diag_matrix(Lmat_diag_weighted)
else:
raise Exception("No can do.")
return mat_weighted, Lmat_weighted
def compute_bias(self, s, u=None, bias_fn=None, bias_matrix=None):
if bias_fn is None and bias_matrix is None:
b = None
else:
b_nonlin = bias_fn(s) if bias_fn is not None else 0.0
b_lin = matvec(bias_matrix, u) if bias_matrix is not None else 0.0
b = b_lin + b_nonlin
return b
def forward(self, switch, controls: Optional[ControlInputs]) -> GLSParams:
weights = self.link_transformers(switch)
# biases to state (B/b) and observation (D/d)
B = (
torch.einsum("...k,koi->...oi", weights.B, self.B)
if self.B is not None
else None
)
D = (
torch.einsum("...k,koi->...oi", weights.D, self.D)
if self.D is not None
else None
)
b = self.compute_bias(
s=switch,
u=controls.state if controls is not None else None,
bias_fn=self.b_fn,
bias_matrix=B,
)
d = self.compute_bias(
s=switch,
u=controls.target if controls is not None else None,
bias_fn=self.d_fn,
bias_matrix=D,
)
# transition (A) and emission (C)
A | |
from django.contrib import admin
from django import forms
from django.forms import ValidationError
from django.forms.utils import ErrorList
from django.db.models import Count
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.contrib.postgres.forms.ranges import RangeWidget
from .models import ConferenceSeries, Conference, ConferenceRegistration
from .models import RegistrationType, Speaker
from .models import ConferenceSession, Track, Room, ConferenceSessionScheduleSlot
from .models import RegistrationClass, RegistrationDay, AttendeeMail
from .models import ShirtSize, ConferenceAdditionalOption
from .models import ConferenceFeedbackQuestion
from .models import PrepaidVoucher, PrepaidBatch, BulkPayment, DiscountCode
from .models import PendingAdditionalOrder
from .models import VolunteerSlot
from .models import AccessToken
from .models import ConferenceNews
from postgresqleu.util.forms import ConcurrentProtectedModelForm
from postgresqleu.accounting.models import Object
from postgresqleu.confsponsor.models import Sponsor
#
# List filters
#
class TrackListFilter(admin.SimpleListFilter):
title = 'Track'
parameter_name = 'track'
def lookups(self, request, model_admin):
cid = int(request.GET.get('conference__id__exact', -1))
if cid >= 0:
return ((t.id, t.trackname) for t in Track.objects.filter(conference__id=cid))
def queryset(self, request, queryset):
if self.value():
return queryset.filter(track_id=self.value())
class RegtypeListFilter(admin.SimpleListFilter):
title = 'Registration type'
parameter_name = 'regtype'
def lookups(self, request, model_admin):
cid = int(request.GET.get('conference__id__exact', -1))
if cid >= 0:
return ((r.id, r.regtype) for r in RegistrationType.objects.filter(conference__id=cid))
def queryset(self, request, queryset):
if self.value():
return queryset.filter(regtype_id=self.value())
class AdditionalOptionListFilter(admin.SimpleListFilter):
title = 'Additional option'
parameter_name = 'addoption'
def lookups(self, request, model_admin):
cid = int(request.GET.get('conference__id__exact', -1))
if cid >= 0:
return ((ao.id, ao.name) for ao in ConferenceAdditionalOption.objects.filter(conference__id=cid))
def queryset(self, request, queryset):
if self.value():
return queryset.filter(additionaloptions__id=self.value())
#
# General admin classes
#
class ConferenceSeriesAdmin(admin.ModelAdmin):
autocomplete_fields = ('administrators', )
class ConferenceAdminForm(ConcurrentProtectedModelForm):
class Meta:
model = Conference
exclude = []
accounting_object = forms.ChoiceField(choices=[], required=False)
def __init__(self, *args, **kwargs):
super(ConferenceAdminForm, self).__init__(*args, **kwargs)
self.fields['volunteers'].queryset = ConferenceRegistration.objects.filter(conference=self.instance, payconfirmedat__isnull=False)
self.fields['checkinprocessors'].queryset = ConferenceRegistration.objects.filter(conference=self.instance, payconfirmedat__isnull=False)
self.fields['accounting_object'].choices = [('', '----'), ] + [(o.name, o.name) for o in Object.objects.filter(active=True)]
def clean(self):
data = super(ConferenceAdminForm, self).clean()
return data
class ConferenceAdmin(admin.ModelAdmin):
form = ConferenceAdminForm
list_display = ('conferencename', 'active', 'callforpapersopen', 'callforsponsorsopen', 'feedbackopen', 'startdate', 'enddate')
ordering = ('-startdate', )
autocomplete_fields = ('administrators', 'testers', 'talkvoters', 'staff', 'volunteers', 'checkinprocessors', )
class ConferenceRegistrationForm(ConcurrentProtectedModelForm):
class Meta:
model = ConferenceRegistration
exclude = []
def __init__(self, *args, **kwargs):
super(ConferenceRegistrationForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.fields['additionaloptions'].queryset = ConferenceAdditionalOption.objects.filter(conference=self.instance.conference)
self.fields['regtype'].queryset = RegistrationType.objects.filter(conference=self.instance.conference)
self.fields['payconfirmedat'].help_text = self.fields['payconfirmedby'].help_text = "Don't edit this field here - instead, go back to the list of registrations and chose to approve from there!"
self.fields['checkedinby'].queryset = ConferenceRegistration.objects.filter(conference=self.instance.conference, payconfirmedat__isnull=True)
class ConferenceRegistrationAdmin(admin.ModelAdmin):
form = ConferenceRegistrationForm
list_display = ['email', 'conference', 'firstname', 'lastname', 'created_short', 'short_regtype', 'payconfirmedat_short', 'has_invoice']
list_filter = ['conference', RegtypeListFilter, AdditionalOptionListFilter, ]
search_fields = ['email', 'firstname', 'lastname', ]
ordering = ['-payconfirmedat', '-created', 'lastname', 'firstname', ]
filter_horizontal = ('additionaloptions',)
exclude = ('invoice', 'bulkpayment', )
readonly_fields = ('invoice_link', 'bulkpayment_link', 'lastmodified', )
autocomplete_fields = ('attendee', 'registrator', )
def payconfirmedat_short(self, inst):
return inst.payconfirmedat
payconfirmedat_short.short_description = "Pay conf"
def created_short(self, inst):
return "<nobr>%s</nobr>" % inst.created.strftime("%Y-%m-%d %H:%M")
created_short.allow_tags = True
created_short.short_description = "Created"
def invoice_link(self, inst):
if inst.invoice:
url = reverse('admin:invoices_invoice_change', args=(inst.invoice.id,))
return mark_safe('<a href="%s">%s</a>' % (url, inst.invoice))
else:
return ""
invoice_link.short_description = 'Invoice'
def bulkpayment_link(self, inst):
if inst.bulkpayment:
url = reverse('admin:confreg_bulkpayment_change', args=(inst.bulkpayment.id,))
return mark_safe('<a href="%s">%s</a>' % (url, inst.bulkpayment))
else:
return ""
bulkpayment_link.short_description = 'Bulk payment'
class ConferenceSessionForm(ConcurrentProtectedModelForm):
class Meta:
model = ConferenceSession
exclude = []
def __init__(self, *args, **kwargs):
super(ConferenceSessionForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs and self.instance.conference_id:
self.fields['track'].queryset = Track.objects.filter(conference=self.instance.conference)
self.fields['room'].queryset = Room.objects.filter(conference=self.instance.conference)
self.fields['tentativeroom'].queryset = Room.objects.filter(conference=self.instance.conference)
self.fields['tentativescheduleslot'].queryset = ConferenceSessionScheduleSlot.objects.filter(conference=self.instance.conference)
def clean_track(self):
if not self.cleaned_data['track']:
return None
if self.cleaned_data['track'].conference != self.cleaned_data['conference']:
raise ValidationError("This track does not belong to this conference!")
return self.cleaned_data['track']
def clean_room(self):
if not self.cleaned_data['room']:
return None
if self.cleaned_data['room'].conference != self.cleaned_data['conference']:
raise ValidationError("This room does not belong to this conference!")
return self.cleaned_data['room']
class ConferenceSessionAdmin(admin.ModelAdmin):
form = ConferenceSessionForm
list_display = ['title', 'conference', 'speaker_list', 'status', 'starttime', 'track', 'initialsubmit', ]
list_filter = ['conference', TrackListFilter, 'status', ]
search_fields = ['title', ]
filter_horizontal = ('speaker',)
autocomplete_fields = ('speaker', )
class ConferenceSessionScheduleSlotAdmin(admin.ModelAdmin):
list_display = ['conference', 'starttime', 'endtime', ]
list_filter = ['conference']
ordering = ['starttime', ]
class RegistrationClassAdmin(admin.ModelAdmin):
list_display = ['regclass', 'conference', ]
list_filter = ['conference', ]
ordering = ['conference', 'regclass', ]
class RegistrationDayAdmin(admin.ModelAdmin):
list_display = ['day', 'conference', ]
list_filter = ['conference', ]
ordering = ['conference', 'day', ]
class RegistrationTypeAdminForm(ConcurrentProtectedModelForm):
class Meta:
model = RegistrationType
exclude = []
def __init__(self, *args, **kwargs):
super(RegistrationTypeAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['regclass'].queryset = RegistrationClass.objects.filter(conference=self.instance.conference)
self.fields['days'].queryset = RegistrationDay.objects.filter(conference=self.instance.conference)
self.fields['requires_option'].queryset = ConferenceAdditionalOption.objects.filter(conference=self.instance.conference)
if self.instance.conference.invoice_autocancel_hours:
self.fields['invoice_autocancel_hours'].help_text = "Automatically cancel invoices after this many hours. Conference settings currently override this to minimum value {0}.".format(self.instance.conference.invoice_autocancel_hours)
except Conference.DoesNotExist:
# If we don't have a conference yet, we can just ignore the fact
# that we couldn't list it.
pass
class RegistrationTypeAdmin(admin.ModelAdmin):
list_display = ['conference', 'regtype', 'cost', 'sortkey', 'active', 'activeuntil', ]
list_filter = ['conference', ]
ordering = ['conference', 'regtype', ]
filter_horizontal = ('requires_option', )
form = RegistrationTypeAdminForm
class ShirtsizeAdmin(admin.ModelAdmin):
list_display = ['shirtsize', 'sortkey', ]
class ConferenceAdditionalOptionAdminForm(ConcurrentProtectedModelForm):
class Meta:
model = ConferenceAdditionalOption
exclude = []
def __init__(self, *args, **kwargs):
super(ConferenceAdditionalOptionAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['requires_regtype'].queryset = RegistrationType.objects.filter(conference=self.instance.conference)
self.fields['mutually_exclusive'].queryset = ConferenceAdditionalOption.objects.filter(conference=self.instance.conference)
self.fields['additionaldays'].queryset = RegistrationDay.objects.filter(conference=self.instance.conference)
except Conference.DoesNotExist:
# If we don't have a conference yet, we can just ignore the fact
# that we couldn't list it.
pass
class ConferenceAdditionalOptionAdmin(admin.ModelAdmin):
list_display = ['conference', 'name', 'maxcount', 'cost', 'used_count', 'confirmed_count', 'unconfirmed_count']
list_filter = ['conference', ]
ordering = ['conference', 'name', ]
search_fields = ['name', ]
filter_horizontal = ('requires_regtype', 'mutually_exclusive', )
form = ConferenceAdditionalOptionAdminForm
def get_queryset(self, request):
return ConferenceAdditionalOption.objects.extra(select={
'confirmed_count': 'SELECT count(*) FROM confreg_conferenceregistration r INNER JOIN confreg_conferenceregistration_additionaloptions cao ON cao.conferenceregistration_id=r.id WHERE cao.conferenceadditionaloption_id=confreg_conferenceadditionaloption.id AND r.payconfirmedat IS NOT NULL',
'unconfirmed_count': 'SELECT count(*) FROM confreg_conferenceregistration r INNER JOIN confreg_conferenceregistration_additionaloptions cao ON cao.conferenceregistration_id=r.id WHERE cao.conferenceadditionaloption_id=confreg_conferenceadditionaloption.id AND r.payconfirmedat IS NULL',
})
return ConferenceAdditionalOption.objects.annotate(reg_count=Count('conferenceregistration'))
def confirmed_count(self, inst):
return inst.confirmed_count
confirmed_count.short_description = 'Confirmed'
def unconfirmed_count(self, inst):
return inst.unconfirmed_count
unconfirmed_count.short_description = 'Unconfirmed'
def used_count(self, inst):
return inst.confirmed_count + inst.unconfirmed_count
used_count.short_description = 'Total used'
class SpeakerAdminForm(ConcurrentProtectedModelForm):
exclude_fields_from_validation = ['photo', ]
class Meta:
model = Speaker
exclude = []
class SpeakerAdmin(admin.ModelAdmin):
list_display = ['user', 'email', 'fullname', 'has_abstract', 'has_photo']
search_fields = ['fullname', 'user__email']
autocomplete_fields = ('user', )
ordering = ['fullname']
form = SpeakerAdminForm
class TrackAdmin(admin.ModelAdmin):
list_filter = ['conference', ]
list_display = ['conference', 'trackname', 'sortkey', 'color', 'incfp', ]
class Meta:
model = Track
class RoomAdmin(admin.ModelAdmin):
list_filter = ['conference', ]
class Meta:
model = Room
class ConferenceFeedbackQuestionAdmin(admin.ModelAdmin):
list_display = ['conference', 'sortkey', 'newfieldset', 'question', ]
list_filter = ['conference', ]
class PrepaidVoucherInline(admin.TabularInline):
model = PrepaidVoucher
readonly_fields = ['user', 'usedate', ]
exclude = ['vouchervalue', 'conference', ]
extra = 0
can_delete = False
class PrepaidBatchAdminForm(ConcurrentProtectedModelForm):
class Meta:
model = PrepaidBatch
exclude = []
def __init__(self, *args, **kwargs):
super(PrepaidBatchAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['sponsor'].queryset = Sponsor.objects.filter(conference=self.instance.conference)
self.fields['regtype'].queryset = RegistrationType.objects.filter(conference=self.instance.conference)
except Conference.DoesNotExist:
pass
class PrepaidBatchAdmin(admin.ModelAdmin):
list_display = ['id', 'conference', 'buyer', 'buyername', 'total_num', 'used_num', ]
list_filter = ['conference', ]
autocomplete_fields = ('buyer', )
inlines = [PrepaidVoucherInline, ]
form = PrepaidBatchAdminForm
def get_queryset(self, request):
return PrepaidBatch.objects.extra(select={
'num': 'SELECT count(*) FROM confreg_prepaidvoucher WHERE batch_id=confreg_prepaidbatch.id',
'used': 'SELECT count(*) FROM confreg_prepaidvoucher WHERE batch_id=confreg_prepaidbatch.id AND usedate IS NOT NULL',
})
def total_num(self, inst):
return inst.num
total_num.short_description = 'Total vouchers'
def used_num(self, inst):
return inst.used
used_num.short_description = 'Used vouchers'
class PrepaidVoucherAdminForm(ConcurrentProtectedModelForm):
class Meta:
model = PrepaidVoucher
exclude = []
def __init__(self, *args, **kwargs):
super(PrepaidVoucherAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['batch'].queryset = PrepaidBatch.objects.filter(conference=self.instance.conference)
self.fields['user'].queryset = ConferenceRegistration.objects.filter(conference=self.instance.conference)
except Conference.DoesNotExist:
pass
class PrepaidVoucherAdmin(admin.ModelAdmin):
list_display = ['vouchervalue', 'conference', 'buyername', 'usedby', 'usedate', ]
list_filter = ['conference', ]
form = PrepaidVoucherAdminForm
def buyername(self, obj):
url = reverse('admin:confreg_prepaidbatch_change', args=(obj.batch.pk,))
return mark_safe('<a href="%s">%s</a>' % (url, obj.batch.buyername))
buyername.allow_tags = True
def usedby(self, obj):
if obj.user:
return "%s %s" % (obj.user.firstname, obj.user.lastname)
return None
class DiscountCodeAdminForm(ConcurrentProtectedModelForm):
class Meta:
model = DiscountCode
exclude = []
def __init__(self, *args, **kwargs):
super(DiscountCodeAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['registrations'].queryset = ConferenceRegistration.objects.filter(conference=self.instance.conference)
self.fields['requiresoption'].queryset = ConferenceAdditionalOption.objects.filter(conference=self.instance.conference)
self.fields['requiresregtype'].queryset = RegistrationType.objects.filter(conference=self.instance.conference)
self.fields['sponsor'].queryset = Sponsor.objects.filter(conference=self.instance.conference)
except Conference.DoesNotExist:
pass
def clean_discountpercentage(self):
if int(self.cleaned_data['discountpercentage']) < 0:
raise ValidationError('Discount percentage must be a positive number or zero!')
if int(self.cleaned_data['discountpercentage']) > 100:
raise ValidationError('Discount percentage cannot be higher than 100!')
return self.cleaned_data['discountpercentage']
def clean_maxuses(self):
if int(self.cleaned_data['maxuses']) < 0:
raise ValidationError('Max uses must be a positive number or zero!')
return self.cleaned_data['maxuses']
def clean(self):
cleaned_data = super(DiscountCodeAdminForm, self).clean()
if 'discountamount' in cleaned_data and 'discountpercentage' in cleaned_data:
if cleaned_data['discountamount'] > 0 and cleaned_data['discountpercentage'] > 0:
raise ValidationError('Cannot specify both discount amount and discount percentage at the same time!')
if 'discountamount' in cleaned_data and 'regonly' in cleaned_data:
if cleaned_data['discountamount'] > 0 and cleaned_data['regonly']:
raise ValidationError('Regonly field can only be set for percentage discounts!')
if cleaned_data.get('sponsor', None) and not cleaned_data.get('sponsor_rep', None):
self._errors['sponsor_rep'] = ErrorList(["Sponsor rep must be given if sponsor is given!"])
if cleaned_data.get('sponsor_rep', None) and not cleaned_data.get('sponsor', None):
self._errors['sponsor'] = ErrorList(["Sponsor must be given if sponsor rep is given!"])
| |
self._drop_collection_if_exists("mycoll9")
collection = self.schema.create_collection("mycoll9")
collection.add(
{
"_id": 1,
"name": "joy",
"age": 21,
"additionalinfo": {
"company": "xyz",
"vehicle": "bike",
"hobbies": [
"reading",
"music",
"playing",
{"a1": "x", "b1": "y", "c1": "z"},
],
},
}
).execute()
result = collection.find(
"'reading' IN $.additionalinfo.hobbies"
).execute()
result1 = (
collection.find()
.fields("'music' IN $.age as test")
.limit(1)
.execute()
)
result2 = (
collection.find()
.fields("'boxing' IN $.additionalinfo.hobbies as test1")
.limit(1)
.execute()
)
result3 = collection.find(
'{"a1":"x","b1":"y","c1":"z"} IN $.additionalinfo.hobbies'
).execute()
self.assertEqual(len(result.fetch_all()), 1)
self.assertFalse(result1.fetch_all()[0].test)
self.assertFalse(result2.fetch_all()[0].test1)
self.assertEqual(len(result3.fetch_all()), 1)
self.schema.drop_collection("mycoll9")
@tests.foreach_session()
def test_contains_operator10(self):
"""Test IN operator with array/list operand on LHS and array/list on
RHS."""
self._drop_collection_if_exists("mycoll10")
collection = self.schema.create_collection("mycoll10")
collection.add(
{
"_id": 1,
"name": "joy",
"age": 21,
"additionalinfo": {
"company": "xyz",
"vehicle": "bike",
"hobbies": ["reading", "music", "playing"],
},
},
{
"_id": 2,
"name": "happy",
"age": 24,
"additionalinfo": {
"company": "abc",
"vehicle": "car",
"hobbies": ["playing", "painting", "boxing"],
},
},
).execute()
result = collection.find(
'["playing","painting","boxing"] IN $.additionalinfo.hobbies'
).execute()
result1 = (
collection.find()
.fields('["happy","joy"] IN $.name as test')
.limit(1)
.execute()
)
result2 = (
collection.find()
.fields('["car","bike"] NOT IN $.additionalinfo.vehicle as test1')
.limit(1)
.execute()
)
self.assertEqual(len(result.fetch_all()), 1)
self.assertFalse(result1.fetch_all()[0].test)
self.assertTrue(result2.fetch_all()[0].test1)
self.schema.drop_collection("mycoll10")
@tests.foreach_session()
def test_contains_operator11(self):
"""Test IN operator with dict on LHS and dict on RHS."""
self._drop_collection_if_exists("mycoll11")
collection = self.schema.create_collection("mycoll11")
collection.add(
{
"_id": 1,
"name": "joy",
"age": 21,
"additionalinfo": [
{"company": "xyz", "vehicle": "bike"},
{"company": "abc", "vehicle": "car"},
{"company": "mno", "vehicle": "zeep"},
],
},
{
"_id": 2,
"name": "happy",
"age": 24,
"additionalinfo": [
{"company": "abc", "vehicle": "car"},
{"company": "pqr", "vehicle": "bicycle"},
],
},
{
"_id": 3,
"name": "nice",
"age": 25,
"additionalinfo": {"company": "def", "vehicle": "none"},
},
).execute()
result = collection.find(
'{"company":"abc","vehicle":"car"} IN $.additionalinfo'
).execute()
result1 = (
collection.find()
.fields('{"vehicle":"car"} NOT IN $.additionalinfo as test')
.limit(1)
.execute()
)
result2 = (
collection.find()
.fields('{"company":"mno"} IN $.additionalinfo as test1')
.limit(1)
.execute()
)
result3 = collection.find(
'{"company":"abc","vehicle":"car"} NOT IN $.additionalinfo'
).execute()
self.assertEqual(len(result.fetch_all()), 2)
self.assertFalse(result1.fetch_all()[0].test)
self.assertTrue(result2.fetch_all()[0].test1)
self.assertEqual(len(result3.fetch_all()), 1)
self.schema.drop_collection("mycoll11")
@tests.foreach_session()
def test_contains_operator12(self):
"""Test IN operator with operands having expressions."""
self._drop_collection_if_exists("mycoll12")
collection = self.schema.create_collection("mycoll12")
collection.add(
{"_id": 1, "name": "a", "age": 21},
{"_id": 2, "name": "b"},
{"_id": 3, "name": "c"},
).execute()
result = (
collection.find()
.fields("(1>5) IN (true, false) as test")
.limit(1)
.execute()
)
result1 = (
collection.find()
.fields("('a'>'b') in (true, false) as test1")
.limit(1)
.execute()
)
result2 = (
collection.find()
.fields(
"true IN [(1>5), !(false), (true || false), (false && true)] as test2"
)
.limit(1)
.execute()
)
self.assertTrue(result.fetch_all()[0].test)
self.assertTrue(result1.fetch_all()[0].test1)
self.assertTrue(result2.fetch_all()[0].test2)
self.schema.drop_collection("mycoll12")
@tests.foreach_session()
def test_contains_operator13(self):
"""Test IN operator with operands having expressions."""
self._drop_collection_if_exists("mycoll13")
collection = self.schema.create_collection("mycoll13")
collection.add(
{"_id": 1, "name": "a", "age": 21},
{"_id": 2, "name": "b"},
{"_id": 3, "name": "c"},
).execute()
result = collection.find("(1+5) IN (1,2,3,4,5,6)").execute()
result1 = collection.find("(2+3) IN (1,2,3,4)").limit(1).execute()
result2 = collection.find("(1+5) IN (1,2,3,4,5,6)").execute()
self.assertEqual(len(result.fetch_all()), 3)
self.assertEqual(len(result1.fetch_all()), 0)
self.assertEqual(len(result2.fetch_all()), 3)
self.schema.drop_collection("mycoll13")
@tests.foreach_session()
def test_contains_operator14(self):
"""Test IN operator: search for empty string in a field and field in
empty string."""
self._drop_collection_if_exists("mycoll14")
collection = self.schema.create_collection("mycoll14")
collection.add(
{"_id": 1, "name": "a", "age": 21},
{"_id": 2, "name": "b"},
{"_id": 3, "name": "c"},
).execute()
result = collection.find("'' IN $.name").execute()
result1 = collection.find("$.name IN ['', ' ']").execute()
result2 = collection.find("$.name IN ('', ' ')").execute()
self.assertEqual(len(result.fetch_all()), 0)
self.assertEqual(len(result1.fetch_all()), 0)
self.assertEqual(len(result2.fetch_all()), 0)
self.schema.drop_collection("mycoll14")
@tests.foreach_session()
def test_collection_s_s_lock(self):
"""Test shared-shared lock."""
config = tests.get_mysqlx_config()
self._drop_collection_if_exists("mycoll11")
collection = self.schema.create_collection("mycoll1")
collection.add(
{"name": "Joe", "age": 21}, {"name": "James", "age": 23}
).execute()
locking = threading.Event()
waiting = threading.Event()
def thread_a(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll1")
session1.start_transaction()
collection.find("name = 'James'").lock_shared().execute()
locking.set()
time.sleep(2)
locking.clear()
if waiting.is_set():
session1.commit()
self.fail(
"Collection_S_S_Lock_test IS NOT OK. Other thread is "
"waiting while it is not expected to!"
)
session1.commit()
def thread_b(locking, waiting):
session2 = mysqlx.get_session(config)
schema2 = session2.get_schema(config["schema"])
collection = schema2.get_collection("mycoll1")
if not locking.wait(2):
self.fail(
"Collection_S_S_Lock_test IS NOT OK. Other thread has not "
"set the lock!"
)
session2.start_transaction()
waiting.set()
collection.find("name = 'James'").lock_shared().execute()
waiting.clear()
session2.commit()
client1 = threading.Thread(
target=thread_a,
args=(
locking,
waiting,
),
)
client2 = threading.Thread(
target=thread_b,
args=(
locking,
waiting,
),
)
client1.start()
client2.start()
client1.join()
client2.join()
self.schema.drop_collection("mycoll1")
@tests.foreach_session()
def test_collection_s_x_lock(self):
config = tests.get_mysqlx_config()
"""Test shared-exclusive lock."""
self._drop_collection_if_exists("mycoll2")
collection = self.schema.create_collection("mycoll2")
collection.add(
{"name": "Joe", "age": 21}, {"name": "James", "age": 23}
).execute()
locking = threading.Event()
waiting = threading.Event()
def thread_a(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll2")
session1.start_transaction()
collection.find("name = 'James'").lock_shared().execute()
locking.set()
time.sleep(2)
locking.clear()
if not waiting.is_set():
session1.commit()
self.fail(
"Collection_S_X_Lock_test IS NOT OK. Other thread is not "
"waiting while it is expected to!"
)
session1.commit()
def thread_b(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll2")
if not locking.wait(2):
self.fail(
"Collection_S_X_Lock_test IS NOT OK. Other thread has not "
"set the lock!"
)
session1.start_transaction()
waiting.set()
collection.find("name = 'James'").lock_exclusive().execute()
waiting.clear()
session1.commit()
client1 = threading.Thread(
target=thread_a,
args=(
locking,
waiting,
),
)
client2 = threading.Thread(
target=thread_b,
args=(
locking,
waiting,
),
)
client1.start()
client2.start()
client1.join()
client2.join()
self.schema.drop_collection("mycoll2")
@tests.foreach_session()
def test_collection_x_x_lock(self):
"""Test exclusive-exclusive lock."""
config = tests.get_mysqlx_config()
self._drop_collection_if_exists("mycoll3")
collection = self.schema.create_collection("mycoll3")
collection.add(
{"name": "Joe", "age": 21}, {"name": "James", "age": 23}
).execute()
locking = threading.Event()
waiting = threading.Event()
def thread_a(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll3")
session1.start_transaction()
collection.find("name = 'James'").lock_exclusive().execute()
locking.set()
time.sleep(2)
locking.clear()
if not waiting.is_set():
session1.commit()
self.fail(
"Collection_X_X_Lock_test IS NOT OK. Other thread is not "
"waiting while it is expected to!"
)
session1.commit()
def thread_b(locking, waiting):
session2 = mysqlx.get_session(config)
schema2 = session2.get_schema(config["schema"])
collection = schema2.get_collection("mycoll3")
if not locking.wait(2):
self.fail(
"Collection_X_X_Lock_test IS NOT OK. Other thread has not "
"set the lock!"
)
session2.start_transaction()
waiting.set()
collection.find("name = 'James'").lock_exclusive().execute()
waiting.clear()
session2.commit()
client1 = threading.Thread(
target=thread_a,
args=(
locking,
waiting,
),
)
client2 = threading.Thread(
target=thread_b,
args=(
locking,
waiting,
),
)
client1.start()
client2.start()
client1.join()
client2.join()
self.schema.drop_collection("mycoll3")
@tests.foreach_session()
def test_collection_x_s_lock(self):
"""Test exclusive-exclusive lock."""
config = tests.get_mysqlx_config()
self._drop_collection_if_exists("mycoll4")
collection = self.schema.create_collection("mycoll4")
collection.add(
{"name": "Joe", "age": 21}, {"name": "James", "age": 23}
).execute()
locking = threading.Event()
waiting = threading.Event()
def thread_a(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll4")
session1.start_transaction()
collection.find("name = 'James'").lock_exclusive().execute()
locking.set()
time.sleep(2)
locking.clear()
if not waiting.is_set():
session1.commit()
self.fail(
"Collection_X_S_Lock_test IS NOT OK. Other thread is not "
"waiting while it is expected to!"
)
session1.commit()
def thread_b(locking, waiting):
session2 = mysqlx.get_session(config)
schema2 = session2.get_schema(config["schema"])
collection = schema2.get_collection("mycoll4")
if not locking.wait(2):
self.fail(
"Collection_X_S_Lock_test IS NOT OK. Other thread has not "
"set the lock!"
)
session2.start_transaction()
waiting.set()
collection.find("name = 'James'").lock_shared().execute()
waiting.clear()
session2.commit()
client1 = threading.Thread(
target=thread_a,
args=(
locking,
waiting,
),
)
client2 = threading.Thread(
target=thread_b,
args=(
locking,
waiting,
),
)
client1.start()
client2.start()
client1.join()
client2.join()
self.schema.drop_collection("mycoll4")
@tests.foreach_session()
def test_collection_multiple_lock_calls(self):
"""Test multiple lock calls."""
config = tests.get_mysqlx_config()
self._drop_collection_if_exists("mycoll5")
collection = self.schema.create_collection("mycoll5")
collection.add(
{"name": "Joe", "age": 21}, {"name": "James", "age": 23}
).execute()
locking = threading.Event()
waiting = threading.Event()
def thread_a(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll5")
session1.start_transaction()
collection.find(
"name = 'James'"
).lock_exclusive().lock_shared().lock_exclusive().execute()
locking.set()
time.sleep(2)
locking.clear()
if not waiting.is_set():
session1.commit()
self.fail(
"Collection_Multiple_Lock_calls_test IS NOT OK. Other "
"thread is not waiting while it is expected to!"
)
session1.commit()
def thread_b(locking, waiting):
session2 = mysqlx.get_session(config)
schema2 = session2.get_schema(config["schema"])
collection = schema2.get_collection("mycoll5")
if not locking.wait(2):
self.fail(
"Collection_Multiple_Lock_calls_test IS NOT OK. Other "
"thread has not set the lock!"
)
session2.start_transaction()
waiting.set()
collection.find(
"name = 'James'"
).lock_shared().lock_exclusive().lock_exclusive().lock_shared().execute()
waiting.clear()
session2.commit()
client1 = threading.Thread(
target=thread_a,
args=(
locking,
waiting,
),
)
client2 = threading.Thread(
target=thread_b,
args=(
locking,
waiting,
),
)
client1.start()
client2.start()
client1.join()
client2.join()
self.schema.drop_collection("mycoll5")
@tests.foreach_session()
def test_collection_x_lock_modify(self):
"""Test lock exclusive and modify - modify will be blocked until the
lock is released."""
config = tests.get_mysqlx_config()
self._drop_collection_if_exists("mycoll6")
collection = self.schema.create_collection("mycoll6")
collection.add(
{"name": "Joe", "age": 21}, {"name": "James", "age": 23}
).execute()
locking = threading.Event()
waiting = threading.Event()
def thread_a(locking, waiting):
session1 = mysqlx.get_session(config)
schema1 = session1.get_schema(config["schema"])
collection = schema1.get_collection("mycoll6")
session1.start_transaction()
collection.find(
"$.name = 'James'"
).lock_exclusive().lock_shared().lock_exclusive().execute()
locking.set()
time.sleep(2)
locking.clear()
if not waiting.is_set():
session1.commit()
self.fail(
"Collection_X_Lock_Modify_test IS NOT OK. Other thread is "
"not waiting while it is expected to!"
)
session1.commit()
def thread_b(locking, waiting):
session2 = mysqlx.get_session(config)
schema2 = session2.get_schema(config["schema"])
collection = schema2.get_collection("mycoll6")
if not locking.wait(2):
self.fail(
"Collection_X_Lock_Modify_test IS NOT OK. Other thread has "
"not set the lock!"
)
session2.start_transaction()
waiting.set()
collection.modify("$.name == 'James'").set("$.age", 30).execute()
waiting.clear()
session2.commit()
client1 = threading.Thread(
target=thread_a,
args=(
locking,
waiting,
),
)
client2 = threading.Thread(
target=thread_b,
args=(
locking,
waiting,
),
| |
request.method == 'POST':
post_data = request.json
stg_list = []
code_value = []
for x in post_data:
result = {}
c_code = FUND_ESSENTIAL.query.filter_by(wind_code_s=x[1]).first()
if c_code is not None:
result['wind_code'] = c_code.wind_code
else:
result['wind_code'] = x[1]
result['value'] = x[2]
code_value.append(result)
for i in code_value:
if i['wind_code'] != 'fh0000':
last_date = FUND_STG_PCT.query.filter_by(wind_code=i['wind_code']).order_by(
FUND_STG_PCT.trade_date.desc()).first().trade_date
stg = FUND_STG_PCT.query.filter(
and_(FUND_STG_PCT.wind_code == i['wind_code'], FUND_STG_PCT.trade_date == last_date)).all()
stg_pct = [{"stg_name": x.stg_code, "stg_pct": x.stg_pct, "name": x.wind_code} for x in stg]
stg_list.extend(stg_pct)
cash = [{"stg_name": "未投现金", 'value': float(i['value']), "name": "fh0000"} for i in code_value if
i['wind_code'] == 'fh0000']
stg_pct = []
for b in code_value:
pct_temp = [
{"stg_name": t['stg_name'], "value": float(b['value']) * (t['stg_pct'] / 100), "name": t['name']} for
t in stg_list if t['name'] == b['wind_code']]
stg_pct.extend(pct_temp)
stg_pct.extend(cash)
df = DataFrame(stg_pct)
dx = df.groupby(['stg_name'])['value'].sum()
stg_summary = [{"value": v, "name": k} for k, v in dx.items()]
stg_name = {t['stg_name'] for t in stg_pct}
stg_pie = []
for i in stg_name:
series = [{"name": code_get_name(x['name']), "value": x['value']} for x in stg_pct if x['stg_name'] == i]
series_obj = {"name": i, "data": series}
stg_pie.append(series_obj)
return jsonify(key=list(stg_name), stg_pie=stg_pie, stg_summary=stg_summary)
@f_app_blueprint.route("/add")
@login_required
def add():
"""
加载智能生成组合配比页面
:by hdhuang
:return:
"""
fof_list = cache.get(str(current_user.id))
query = db.session.query(strategy_index_val.index_name.distinct().label("title"))
exist_name = [row.title for row in query.all()]
exist_name = [STRATEGY_EN_CN_DIC.get(i) for i in exist_name]
strategy_list = list(STRATEGY_EN_CN_DIC.values())
sorted(strategy_list, key=lambda x: len(x))
chunk_list = [i for i in chunks(strategy_list, 4)]
not_exist = list(set(strategy_list) - set(exist_name))
return render_template('append.html', chunk_list=chunk_list, not_exist=not_exist,fof_list=fof_list)
@f_app_blueprint.route('/tab2', methods=['POST'])
def tab2():
"""
智能生成组合配比页面第二页
:by hdhuang
:return:
"""
data = request.get_json()
sub_view = {k: get_Value(STRATEGY_EN_CN_DIC, v) if get_Value(STRATEGY_EN_CN_DIC, v) is not None else v for i in
data['subjective_view'] for k, v in i.items()}
strategies = [get_Value(STRATEGY_EN_CN_DIC, i) for i in data['strategies']]
data["subjective_view"] = sub_view
data["strategies"] = strategies
pr_data = calc_portfolio_optim_fund(json.dumps(data), JSON_DB)
pr_data = pr_data['strategyWeight'].to_dict()['Weight']
legend = list(pr_data.keys())
trans_dict = STRATEGY_EN_CN_DIC
result = [{"name": trans_dict.get(k), "value": v} for k, v in pr_data.items()]
for i in result:
i['value'] = math.floor(i['value'] * 100)
result = [i for i in result if i['value'] != 0]
data['strategies'] = [{"strategy": get_Value(STRATEGY_EN_CN_DIC, i["name"]), "percent": i['value'], 'operator': ''}
for i in result]
mx = max([i['percent'] for i in data['strategies']])
for i in data['strategies']:
if i['percent'] == mx:
i['operator'] = 'largerorequal'
else:
i['operator'] = 'smallerorequal'
session['tab2'] = data
return json.dumps({'status': 'ok', 'legend': legend, 'result': result})
@f_app_blueprint.route("/tab3", methods=['POST', 'GET'])
@login_required
def tab3():
"""
智能生成组合配比页面第三页
:by hdhuang
:return:
"""
if request.method == "POST":
user_select = request.get_json()
expressions = []
if user_select.get('years'):
years = user_select['years']
start, end = range_years(years[1], years[0])
expressions.append(FoFModel.fund_setupdate.between(start, end))
if user_select.get('name'):
name = user_select.get('name')
expressions.append(FoFModel.strategy_type == name)
if user_select.get('rank'):
rank = user_select.get('rank')
expressions.append(FoFModel.rank == rank)
data = FoFModel.query.filter(*expressions).order_by(FoFModel.nav_date_latest)
data = [{'name': i.sec_name, 'code': i.wind_code,
'model': i.strategy_type, 'date': i.fund_setupdate.strftime("%Y-%m-%d")} for i in data]
return json.dumps(data)
@f_app_blueprint.route('/tab4', methods=['POST'])
def tab4():
"""
智能生成组合配比页面第四页
:by hdhuang
:return:
"""
if request.method == 'POST':
json_obj = request.get_json()
t4_data = []
for i in json_obj:
for x in i['fund']:
fund = FoFModel.query.filter_by(sec_name=x.split(" ")[0]).first()
t4_data.append({'fund': fund.wind_code, 'strategies': [
{'strategy': get_Value(STRATEGY_EN_CN_DIC, i['title']), 'percent': 100}]})
port_f = dict(session['tab2'])
port_f['funds'] = t4_data
raw_calc = c4(json.dumps(port_f), JSON_DB)
raw_calc_obj = {}
for k, v in raw_calc.items():
if k == 'fundWeightA':
for i in v.values:
if str(i[0]) != '0.0':
raw_calc_obj = v.to_json()
break
elif k == 'fundWeightB':
for i in v.values:
if str(i[0]) != '0.0':
raw_calc_obj = v.to_json()
break
elif k == 'fundWeightC':
for i in v.values:
if str(i[0]) != '0.0':
raw_calc_obj = v.to_json()
break
else:
raw_calc_obj = json.dumps("balance")
return json.dumps({'status': 'ok', "data": raw_calc_obj})
@f_app_blueprint.route('/manual_add', methods=['POST', 'GET'])
def manual_add():
"""
手动选择基金生成组合页面,用户可以自主选择基金,同时可以根绝用户添加的基金动态生成组合配置图形
:by hdhuang
:return:
"""
if request.method == 'GET':
fof_list = get_all_fof()
return render_template('manual_add.html', fof_list=fof_list)
elif request.method == 'POST':
post_data = request.json
stg_list = []
code_value = []
for x in post_data:
result = {}
c_code = FUND_ESSENTIAL.query.filter_by(wind_code_s=x[1]).first()
if c_code is not None:
result['wind_code'] = c_code.wind_code
else:
result['wind_code'] = x[1]
result['value'] = x[2]
code_value.append(result)
for i in code_value:
if i['wind_code'] != 'fh0000':
last_date = FUND_STG_PCT.query.filter_by(wind_code=i['wind_code']).order_by(
FUND_STG_PCT.trade_date.desc()).first().trade_date
stg = FUND_STG_PCT.query.filter(
and_(FUND_STG_PCT.wind_code == i['wind_code'], FUND_STG_PCT.trade_date == last_date)).all()
stg_pct = [{"stg_name": x.stg_code, "stg_pct": x.stg_pct, "name": x.wind_code} for x in stg]
stg_list.extend(stg_pct)
cash = [{"stg_name": "未投现金", 'value': float(i['value']), "name": "fh0000"} for i in code_value if
i['wind_code'] == 'fh0000']
stg_pct = []
for b in code_value:
pct_temp = [
{"stg_name": t['stg_name'], "value": float(b['value']) * (t['stg_pct'] / 100), "name": t['name']} for
t in stg_list if t['name'] == b['wind_code']]
stg_pct.extend(pct_temp)
stg_pct.extend(cash)
df = DataFrame(stg_pct)
dx = df.groupby(['stg_name'])['value'].sum()
stg_summary = [{"value": v, "name": k} for k, v in dx.items()]
stg_name = {t['stg_name'] for t in stg_pct}
stg_pie = []
for i in stg_name:
series = [{"name": code_get_name(x['name']), "value": x['value']} for x in stg_pct if x['stg_name'] == i]
series_obj = {"name": i, "data": series}
stg_pie.append(series_obj)
full_year = datetime.datetime.now() - datetime.timedelta(days=365)
wind_code_dict = {i[1]: int(i[2]) for i in post_data}
ret_dic = calc_index_by_wind_code_dic(wind_code_dict, full_year.strftime("%Y-%m-%d"),
datetime.date.today().strftime('%Y-%m-%d'))
data = [i for i in ret_dic]
time_line = [i.strftime("%Y-%m-%d") for i in ret_dic.index]
line_pie = {"time_line": time_line, 'data': data}
return jsonify(key=list(stg_name), stg_pie=stg_pie, stg_summary=stg_summary, line_pie=line_pie)
@f_app_blueprint.route('/save_scheme', methods=['POST', 'GET'])
@login_required
def save_scheme():
"""
保存用户手动配比的组合,立即执行压力测试,
:param scheme_name 组合名称 当前时间
:by hdhuang
:return:
"""
if request.method == 'POST':
scheme_name = datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S")
scheme = INFO_SCHEME(scheme_name=scheme_name,
scheme_setupdate=datetime.datetime.now(),
create_user=current_user.id)
db.session.add(scheme)
db.session.commit()
for i in request.json:
pct_scheme = PCT_SCHEME(scheme_id=scheme.scheme_id, wind_code=i[1], invest_scale=i[2])
db.session.add(pct_scheme)
db.session.commit()
scheme_id = scheme.scheme_id
task = run_scheme_testing.apply_async(kwargs={"user": current_user.email, 'sid': scheme_id},
task_id=scheme_name)
return jsonify(status='ok')
@f_app_blueprint.route('/testing_result', methods=['POST', 'GET'])
@login_required
def testing_result():
"""
压力测试结果查询,
:by hdhuang
:return: 所有的压力结果供用户选择
"""
if request.method == 'GET':
fof_list = get_all_fof()
result = INFO_SCHEME.query.all()
result = [{"scheme_id": i.scheme_id, "scheme_name": i.scheme_name,
"create_time": i.scheme_setupdate, 'task': run_scheme_testing.AsyncResult(i.scheme_name).state,
"user": UserModel.query.get(i.create_user).username} for i in result]
return render_template('testing_result.html', fof_list=fof_list, result=result)
@f_app_blueprint.route('/show_testing', methods=['POST', 'GET'])
@login_required
def show_testing():
"""
在页面展现压力测试结果
异步任务id和scheme_name相同,压力测试完成后在redis中保存3个key
:key_name:scheme_id_type
:by hdhuang
:return:
"""
if request.method == 'POST':
if request.json['schemeName'] == '':
return jsonify(status='del')
else:
scheme_name = request.json['schemeName']
task = run_scheme_testing.AsyncResult(scheme_name)
if task.state == 'PENDING':
return json.dumps({"status": 'pending'})
elif task.state == 'FAILURE':
return json.dumps({"status": 'error'})
else:
scheme = INFO_SCHEME.query.filter_by(scheme_name=scheme_name).first()
scheme_fund = PCT_SCHEME.query.filter_by(scheme_id=scheme.scheme_id)
pct_scheme = [
{"fund_name": code_get_name(i.wind_code), "scale": i.invest_scale, "wind_code": i.wind_code} for i
in scheme_fund]
r = get_redis()
copula = r.get('scheme_{0}_{1}'.format(scheme.scheme_id, 'copula'))
if copula is not None:
copula_obj = json.loads(copula.decode('utf-8'))
else:
copula_obj = ''
fhs = r.get('scheme_{0}_{1}'.format(scheme.scheme_id, 'fhs_garch'))
if fhs is not None:
fhs_obj = json.loads(fhs.decode('utf-8'))
else:
fhs_obj = ''
return json.dumps({"copula": copula_obj, 'fhs': fhs_obj, 'status': 'ok', "pct_scheme": pct_scheme})
@f_app_blueprint.route('/del_scheme', methods=['GET', 'POST'])
@login_required
def del_scheme():
"""
删除压力测试结果,pending状态的压力结果不能删除
:by hdhuang
:return:
"""
if request.method == 'POST':
logger.warning("删除scheme{}".format(request.json['name']))
scheme = INFO_SCHEME.query.filter_by(scheme_name=request.json['name']).first()
pct_scheme = PCT_SCHEME.query.filter_by(scheme_id=scheme.scheme_id).all()
db.session.delete(scheme)
[db.session.delete(i) for i in pct_scheme]
db.session.commit()
logger.info("scheme{} info pct 已删除".format(request.json['name']))
r = get_redis(host='127.0.0.1', db=0)
r.delete('celery-task-meta-' + request.json['name'])
logger.info("celery {} 已删除".format(request.json['name']))
return jsonify(status='ok')
@f_app_blueprint.route('/data_show', methods=['GET', 'POST'])
def data_show():
fof_list = get_all_fof()
return render_template('data_show.html', fof_list=fof_list)
@f_app_blueprint.route('/data_select', methods=['GET', 'POST'])
def data_select2():
if request.method == 'POST':
start = request.form['start']
end = request.form['end']
strategy_type_en = request.form['name']
if start == "" and end == "":
now = datetime.datetime.now()
last_year = int(now.year) - 1
last_months = now.month
last_day = now.day
date_from_str = "%s-%s-%s" % (last_year, last_months, last_day)
date_to_str = time.strftime("%Y-%m-%d", time.localtime())
else:
start_time = datetime.datetime.strptime(start, '%Y-%m-%d')
end_time = datetime.datetime.strptime(end, '%Y-%m-%d')
date_from_str = start_time.strftime('%Y-%m-%d')
date_to_str = end_time.strftime('%Y-%m-%d')
df_rr_df = get_strategy_index_quantile(strategy_type_en, date_from_str, date_to_str,
[0.95, 0.90, 0.75, 0.6, 0.50, 0.4, 0.25, 0.10, 0.05])
df_rr_df.index = [d.strftime('%Y-%m-%d') if type(d) in (datetime.date, datetime.datetime) else d for d in
df_rr_df.index]
fof_dict = {"min": df_rr_df.min().to_json(), "value": df_rr_df.to_json()}
return json.dumps(fof_dict)
@f_app_blueprint.route('/invest_corp')
@login_required
def invest_corp():
"""
数据库所有的投顾的表格,每种级别投顾的个数
:param 0,1,2,4
:by hdhuang
:return:
"""
fof_list = get_all_fof()
invest = Invest_corp.query.all()
all_invest = [{"id": index, "name": i.name, "alias": i.alias, "review_status": i.review_status,
'tot': i.fund_count_tot, 'existing': i.fund_count_existing, "active": i.fund_count_active,
'uid': i.mgrcomp_id} for index, i in
enumerate(invest)]
core_invest = query_invest(4)
observe_invest = query_invest(3)
archive_invest = query_invest(2)
all_data = {"core": core_invest, 'all': {"data": all_invest, 'length': len(all_invest)}, "observe": observe_invest,
"archive": archive_invest, }
return render_template("f_app/invest_corp.html", fof_list=fof_list, all_data=all_data)
@f_app_blueprint.route('/get_corp')
def get_corp():
"""
Datatables插件服务器端获取数据方式
:param 数据中每个列的名称,要和Datatables中列一致
:by hdhuang
:return:
"""
columns = ['mgrcomp_id', 'name', 'alias', 'fund_count_tot', 'fund_count_existing', 'fund_count_active',
'review_status', ]
index_column = "mgrcomp_id"
table = "fund_mgrcomp_info"
result = DataTablesServer(request, columns=columns, table=table, index=index_column).output_result()
return json.dumps(result)
@f_app_blueprint.route('/process/<uid>', methods=['GET', 'POST'])
@login_required
def process(uid):
"""
投顾评估报告
:param uid:投顾id
:by hdhuang
:return:
"""
if request.method == 'GET':
fof_list = get_all_fof()
corp = Invest_corp.query.get(uid)
return render_template("process.html", fof_list=fof_list, corp=corp)
if request.method == 'POST':
comments = request.form['comments']
file = request.files['file']
file_name = file.filename
f_content = file.read()
file_record = Invest_corp_file(mgrcomp_id=uid, file_type='report', upload_user_id=current_user.id,
upload_datetime=datetime.datetime.now(),
file_name=file_name, file_content=f_content, comments=comments)
db.session.add(file_record)
db.session.commit()
file.close()
return redirect(url_for('f_app.corp', uid=uid))
@f_app_blueprint.route('/corp_upload_file/<uid>', methods=['GET', 'POST'])
@login_required
def corp_upload_file(uid):
"""
| |
import random
import numpy as np
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.nn.functional as F
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils import (
remove_self_loops,
add_self_loops,
softmax,
dropout_adj,
is_undirected,
accuracy,
negative_sampling,
batched_negative_sampling,
to_undirected,
)
import torch_geometric.nn.inits as tgi
from cogdl.trainers.supergat_trainer import SuperGATTrainer
from .. import BaseModel, register_model
from typing import List
# borrowed from https://github.com/dongkwan-kim/SuperGAT
def np_sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
class SuperGATLayer(MessagePassing):
def __init__(
self,
in_channels,
out_channels,
heads=1,
concat=True,
negative_slope=0.2,
dropout=0,
bias=True,
is_super_gat=True,
attention_type="basic",
super_gat_criterion=None,
neg_sample_ratio=0.0,
edge_sample_ratio=1.0,
pretraining_noise_ratio=0.0,
use_pretraining=False,
to_undirected_at_neg=False,
scaling_factor=None,
cache_label=False,
cache_attention=False,
**kwargs,
):
super(SuperGATLayer, self).__init__(aggr="add", node_dim=0, **kwargs)
self.in_channels = in_channels
self.out_channels = out_channels
self.heads = heads
self.concat = concat
self.negative_slope = negative_slope
self.dropout = dropout
self.is_super_gat = is_super_gat
self.attention_type = attention_type
self.super_gat_criterion = super_gat_criterion
self.neg_sample_ratio = neg_sample_ratio
self.edge_sample_ratio = edge_sample_ratio
self.pretraining_noise_ratio = pretraining_noise_ratio
self.pretraining = None if not use_pretraining else True
self.to_undirected_at_neg = to_undirected_at_neg
self.cache_label = cache_label
self.cache_attention = cache_attention
self.weight = Parameter(torch.Tensor(in_channels, heads * out_channels))
if self.is_super_gat:
if self.attention_type == "gat_originated": # GO
self.att_mh_1 = Parameter(torch.Tensor(1, heads, 2 * out_channels))
elif self.attention_type == "dot_product": # DP
pass
elif self.attention_type == "scaled_dot_product": # SD
self.scaling_factor = scaling_factor or np.sqrt(self.out_channels)
elif self.attention_type.endswith("mask_only"): # MX
self.att_mh_1 = Parameter(torch.Tensor(1, heads, 2 * out_channels))
else:
raise ValueError
else:
if self.attention_type.endswith("gat_originated") or self.attention_type == "basic":
self.att_mh_1 = Parameter(torch.Tensor(1, heads, 2 * out_channels))
elif self.attention_type.endswith("dot_product"):
pass
else:
raise ValueError
self.cache = {
"num_updated": 0,
"att": None, # Use only when self.cache_attention == True for task_type == "Attention_Dist"
"att_with_negatives": None, # Use as X for supervision.
"att_label": None, # Use as Y for supervision.
}
if bias and concat:
self.bias = Parameter(torch.Tensor(heads * out_channels))
elif bias and not concat:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
tgi.glorot(self.weight)
tgi.zeros(self.bias)
for name, param in self.named_parameters():
if name.startswith("att_scaling"):
tgi.ones(param)
elif name.startswith("att_bias"):
tgi.zeros(param)
elif name.startswith("att_mh"):
tgi.glorot(param)
def forward(self, x, edge_index, size=None, batch=None, neg_edge_index=None, attention_edge_index=None):
"""
:param x: [N, F]
:param edge_index: [2, E]
:param size:
:param batch: None or [B]
:param neg_edge_index: When using explicitly given negative edges.
:param attention_edge_index: [2, E'], Use for link prediction
:return:
"""
if self.pretraining and self.pretraining_noise_ratio > 0.0:
edge_index, _ = dropout_adj(
edge_index,
p=self.pretraining_noise_ratio,
force_undirected=is_undirected(edge_index),
num_nodes=x.size(0),
training=self.training,
)
if size is None and torch.is_tensor(x):
edge_index, _ = remove_self_loops(edge_index)
edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))
# [N, F0] * [F0, heads * F] = [N, heads * F]
x = torch.matmul(x, self.weight)
x = x.view(-1, self.heads, self.out_channels)
propagated = self.propagate(edge_index, size=size, x=x)
if (self.is_super_gat and self.training) or (attention_edge_index is not None) or (neg_edge_index is not None):
device = next(self.parameters()).device
num_pos_samples = int(self.edge_sample_ratio * edge_index.size(1))
num_neg_samples = int(self.neg_sample_ratio * self.edge_sample_ratio * edge_index.size(1))
if attention_edge_index is not None:
neg_edge_index = None
elif neg_edge_index is not None:
pass
elif batch is None:
if self.to_undirected_at_neg:
edge_index_for_ns = to_undirected(edge_index, num_nodes=x.size(0))
else:
edge_index_for_ns = edge_index
neg_edge_index = negative_sampling(
edge_index=edge_index_for_ns,
num_nodes=x.size(0),
num_neg_samples=num_neg_samples,
)
else:
neg_edge_index = batched_negative_sampling(
edge_index=edge_index,
batch=batch,
num_neg_samples=num_neg_samples,
)
if self.edge_sample_ratio < 1.0:
pos_indices = random.sample(range(edge_index.size(1)), num_pos_samples)
pos_indices = torch.tensor(pos_indices).long().to(device)
pos_edge_index = edge_index[:, pos_indices]
else:
pos_edge_index = edge_index
att_with_negatives = self._get_attention_with_negatives(
x=x,
edge_index=pos_edge_index,
neg_edge_index=neg_edge_index,
total_edge_index=attention_edge_index,
) # [E + neg_E, heads]
# Labels
if self.training and (self.cache["att_label"] is None or not self.cache_label):
att_label = torch.zeros(att_with_negatives.size(0)).float().to(device)
att_label[: pos_edge_index.size(1)] = 1.0
elif self.training and self.cache["att_label"] is not None:
att_label = self.cache["att_label"]
else:
att_label = None
self._update_cache("att_label", att_label)
self._update_cache("att_with_negatives", att_with_negatives)
return propagated
def message(self, edge_index_i, x_i, x_j, size_i):
"""
:param edge_index_i: [E]
:param x_i: [E, heads * F]
:param x_j: [E, heads * F]
:param size_i: N
:return: [E, heads, F]
"""
x_j = x_j.view(-1, self.heads, self.out_channels) # [E, heads, F]
if x_i is not None:
x_i = x_i.view(-1, self.heads, self.out_channels) # [E, heads, F]
# Compute attention coefficients. [E, heads]
alpha = self._get_attention(edge_index_i, x_i, x_j, size_i)
if self.cache_attention:
self._update_cache("att", alpha)
# Sample attention coefficients stochastically.
alpha = F.dropout(alpha, p=self.dropout, training=self.training)
# [E, heads, F] * [E, heads, 1] = [E, heads, F]
return x_j * alpha.view(-1, self.heads, 1)
def update(self, aggr_out):
"""
:param aggr_out: [N, heads, F]
:return: [N, heads * F]
"""
if self.concat is True:
aggr_out = aggr_out.view(-1, self.heads * self.out_channels)
else:
aggr_out = aggr_out.mean(dim=1)
if self.bias is not None:
aggr_out = aggr_out + self.bias
return aggr_out
def _get_attention(
self, edge_index_i, x_i, x_j, size_i, normalize=True, with_negatives=False, **kwargs
) -> torch.Tensor:
"""
:param edge_index_i: [E]
:param x_i: [E, heads, F]
:param x_j: [E, heads, F]
:param size_i: N
:return: [E, heads]
"""
# Compute attention coefficients.
if self.attention_type == "basic" or self.attention_type.endswith("gat_originated"):
# [E, heads, 2F] * [1, heads, 2F] -> [E, heads]
alpha = torch.einsum("ehf,xhf->eh", torch.cat([x_i, x_j], dim=-1), self.att_mh_1)
elif self.attention_type == "scaled_dot_product":
alpha = torch.einsum("ehf,ehf->eh", x_i, x_j) / self.scaling_factor
elif self.attention_type == "dot_product":
# [E, heads, F] * [E, heads, F] -> [E, heads]
alpha = torch.einsum("ehf,ehf->eh", x_i, x_j)
elif "mask" in self.attention_type:
# [E, heads, F] * [E, heads, F] -> [E, heads]
logits = torch.einsum("ehf,ehf->eh", x_i, x_j)
if self.attention_type.endswith("scaling"):
logits = logits / self.att_scaling
if with_negatives:
return logits
# [E, heads, 2F] * [1, heads, 2F] -> [E, heads]
alpha = torch.einsum("ehf,xhf->eh", torch.cat([x_i, x_j], dim=-1), self.att_mh_1)
alpha = torch.einsum("eh,eh->eh", alpha, torch.sigmoid(logits))
else:
raise ValueError
if normalize:
alpha = F.leaky_relu(alpha, self.negative_slope)
alpha = softmax(alpha, edge_index_i, num_nodes=size_i)
return alpha
def _get_attention_with_negatives(self, x, edge_index, neg_edge_index, total_edge_index=None):
"""
:param x: [N, heads * F]
:param edge_index: [2, E]
:param neg_edge_index: [2, neg_E]
:param total_edge_index: [2, E + neg_E], if total_edge_index is given, use it.
:return: [E + neg_E, heads]
"""
if neg_edge_index is not None and neg_edge_index.size(1) <= 0:
neg_edge_index = torch.zeros((2, 0, self.heads))
if total_edge_index is None:
total_edge_index = torch.cat([edge_index, neg_edge_index], dim=-1) # [2, E + neg_E]
total_edge_index_j, total_edge_index_i = total_edge_index # [E + neg_E]
x_i = torch.index_select(x, 0, total_edge_index_i) # [E + neg_E, heads * F]
x_j = torch.index_select(x, 0, total_edge_index_j) # [E + neg_E, heads * F]
size_i = x.size(0) # N
x_j = x_j.view(-1, self.heads, self.out_channels) # [E + neg_E, heads, F]
if x_i is not None:
x_i = x_i.view(-1, self.heads, self.out_channels) # [E + neg_E, heads, F]
alpha = self._get_attention(total_edge_index_i, x_i, x_j, size_i, normalize=False, with_negatives=True)
return alpha
def __repr__(self):
return "{}({}, {}, heads={}, concat={}, att_type={}, nsr={}, pnr={})".format(
self.__class__.__name__,
self.in_channels,
self.out_channels,
self.heads,
self.concat,
self.attention_type,
self.neg_sample_ratio,
self.pretraining_noise_ratio,
)
def _update_cache(self, key, val):
self.cache[key] = val
self.cache["num_updated"] += 1
def get_attention_dist(self, edge_index: torch.Tensor, num_nodes: int):
"""
:param edge_index: tensor the shape of which is [2, E]
:param num_nodes: number of nodes
:return: Tensor list L the length of which is N.
L[i] = a_ji for e_{ji} in {E}
- a_ji = normalized attention coefficient of e_{ji} (shape: [heads, #neighbors])
"""
edge_index, _ = remove_self_loops(edge_index)
edge_index, _ = add_self_loops(edge_index, num_nodes=num_nodes) # [2, E]
att = self.cache["att"] # [E, heads]
att_dist_list = []
for node_idx in range(num_nodes):
att_neighbors = att[edge_index[1] == node_idx, :].t() # [heads, #neighbors]
att_dist_list.append(att_neighbors)
return att_dist_list
@register_model("supergat")
class SuperGAT(BaseModel):
@staticmethod
def add_args(parser):
"""Add model-specific arguments to the parser."""
# fmt: off
parser.add_argument('--num-features', type=int)
parser.add_argument("--num-classes", type=int)
parser.add_argument("--patience", type=int, default=100)
parser.add_argument('--hidden-size', type=int, default=16)
parser.add_argument("--heads", default=8, type=int)
parser.add_argument("--out-heads", default=None, type=int)
parser.add_argument('--dropout', type=float, default=0.5)
parser.add_argument("--attention-type", type=str, default="basic")
parser.add_argument("--super-gat-criterion", type=str, default=None)
parser.add_argument("--neg-sample-ratio", type=float, default=0.5)
parser.add_argument("--edge-sampling-ratio", type=float, default=0.8)
parser.add_argument("--scaling-factor", type=float, default=None)
parser.add_argument("--to-undirected-at-neg", action="store_true")
parser.add_argument("--to-undirected", action="store_true")
parser.add_argument("--pretraining-noise-ratio", type=float, default=0.0)
parser.add_argument("--val-interval", type=int, default=1)
parser.add_argument("--att-lambda", default=0., type=float)
parser.add_argument("--total-pretraining-epoch", default=0, type=int)
# fmt: on
@classmethod
def build_model_from_args(cls, args):
return cls(args)
def __init__(self, args):
super().__init__()
self.args = args
self.conv1 = SuperGATLayer(
args.num_features,
args.hidden_size,
heads=args.heads,
dropout=args.dropout,
concat=True,
is_super_gat=True,
attention_type=args.attention_type,
super_gat_criterion=args.super_gat_criterion,
neg_sample_ratio=args.neg_sample_ratio,
edge_sample_ratio=args.edge_sampling_ratio,
pretraining_noise_ratio=args.pretraining_noise_ratio,
use_pretraining=False,
to_undirected_at_neg=args.to_undirected_at_neg,
scaling_factor=args.scaling_factor,
)
self.conv2 = SuperGATLayer(
args.hidden_size * args.heads,
args.num_classes,
heads=(args.out_heads or args.heads),
dropout=args.dropout,
concat=False,
is_super_gat=True,
attention_type=args.attention_type,
super_gat_criterion=args.super_gat_criterion,
neg_sample_ratio=args.neg_sample_ratio,
edge_sample_ratio=args.edge_sampling_ratio,
pretraining_noise_ratio=args.pretraining_noise_ratio,
use_pretraining=False,
to_undirected_at_neg=args.to_undirected_at_neg,
scaling_factor=args.scaling_factor,
)
def forward_for_all_layers(self, x, edge_index, batch=None, **kwargs):
x1 = F.dropout(x, p=self.args.dropout, training=self.training)
x1 = self.conv1(x1, edge_index, batch=batch, **kwargs)
x2 = F.elu(x1)
x2 = F.dropout(x2, p=self.args.dropout, training=self.training)
x2 = self.conv2(x2, edge_index, batch=batch, **kwargs)
return x1, x2
def forward(self, x, edge_index, batch=None, **kwargs) -> torch.Tensor:
x = F.dropout(x, p=self.args.dropout, training=self.training)
x = self.conv1(x, edge_index, batch=batch, **kwargs)
x = F.elu(x)
x = F.dropout(x, p=self.args.dropout, training=self.training)
x = self.conv2(x, edge_index, batch=batch, **kwargs)
return x
def set_layer_attrs(self, name, value):
setattr(self.conv1, name, value)
setattr(self.conv2, name, value)
| |
# Import
import asyncio
import random
from itertools import cycle
import discord
from discord.ext import commands
# Framework
import Framework
# Cog Initialising
class CASINO(commands.Cog):
def __init__(self, client):
self.client = client
self.Uccount = Framework.Mongo.Uccount(client)
self.settings = \
{
"Get":
{
"Return": "CURRENCY",
"Type": "CLASS",
"Timestamp": True
}
}
@staticmethod
def win_calculator(colour, aspect):
rnum = random.randint(0, 36)
rcolor = random.choice(["Rot", "Schwarz"])
if aspect == "even" and (rnum % 2) == 0 and rcolor == colour:
return True, rnum, rcolor
elif aspect == "odd" and rcolor == colour and (rnum % 2) != 0:
return True, rnum, rcolor
else:
return False, rnum, rcolor
@commands.command(aliases=["rou"])
async def roulette(self, ctx, cred: int):
# CHECK
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in valid_reactions
valid_reactions = ['⚫', '🔴', '➖', '✖️']
schwarz = "⚫"
rot = "🔴"
gerade = "➖"
ungerade = "✖️"
data = self.Uccount.get(ctx.author, self.settings)
if cred > int(data.Balance):
raise Framework.CreditError(
"Du willst mehr Credits ausgeben als du hast!")
else:
embed = discord.Embed(
title="Roulette",
colour=Framework.Farbe.Red,
description="Wähle zwischen schwarz (⚫) / rot (🔴) und gerade (➖) / ungerade(✖️)"
)
await ctx.message.delete()
m1 = await ctx.send(embed=embed)
await m1.add_reaction("⚫")
await m1.add_reaction("🔴")
try:
reaction, user = await self.client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
erembed = discord.Embed(
title='Roulette',
colour=Framework.Farbe.Red,
description=f'{ctx.author.mention} hat nicht rechtzeitig reagiert.'
)
await m1.edit(embed=erembed)
await asyncio.sleep(9)
await m1.delete()
return
if str(reaction.emoji) == schwarz:
reaktionf = "Schwarz"
await m1.clear_reactions()
elif str(reaction.emoji) == rot:
reaktionf = "Rot"
await m1.clear_reactions()
await m1.add_reaction("➖")
await m1.add_reaction("✖️")
try:
reaction, user = await self.client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
erembed = discord.Embed(
title='Roulette',
colour=Framework.Farbe.Red,
description=f'{ctx.author.mention} hat nicht rechtzeitig reagiert.'
)
await m1.edit(embed=erembed)
await asyncio.sleep(9)
await m1.delete()
return
if str(reaction.emoji) == gerade:
reaktionz = "even"
await m1.clear_reactions()
elif str(reaction.emoji) == ungerade:
reaktionz = "odd"
await m1.clear_reactions()
await self.Roulette2(ctx, reaktionf, reaktionz, m1, cred)
async def Roulette2(self, ctx, reaktionf, reaktionz, m1, cred: int):
outcome, rnum, rcolor = CASINO.win_calculator(reaktionf, reaktionz)
new_cred = int(cred) * 2
if outcome is True:
embed = discord.Embed(
title="Roulette",
colour=Framework.Farbe.Lp_Green,
description=f"Du hast gewonnen! Es war die Zahl {rnum} mit der Farbe {rcolor}!\nEs wurden **{new_cred}**₹ auf dein Konto überwiesen."
)
embed.set_thumbnail(url=ctx.author.avatar_url)
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"], {"Type": "balance", "Attributes": "*", "Timestamp": False})
await Framework.Messaging.Universal_edit(m1, embed, 15)
else:
embed = discord.Embed(
title="Roulette",
colour=Framework.Farbe.Dp_Red,
description=f"Du hast verloren! Es war die Zahl {rnum} mit der Farbe {rcolor}!\nEs wurden **{cred}**₹ von deinem Konto abgebucht."
)
embed.set_thumbnail(url=ctx.author.avatar_url)
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"], {"Type": "balance", "Attributes": "-", "Timestamp": False})
await Framework.Messaging.Universal_edit(m1, embed, 15)
@commands.command(aliases=['bj'])
@commands.cooldown(1, 10, commands.BucketType.user)
async def bj_game(self, ctx, cred: int):
hit = '⬇'
stand = '⏹'
'❤️'
'♦️'
'♠️'
'♣️'
valid_reactions = ['⬇', '⏹']
myDeck = Framework.BlackJack_Bot.Deck()
hands = Framework.BlackJack_Bot.createPlayinghands(myDeck)
dealer = hands[0]
player = hands[1]
Framework.BlackJack_Bot.pointCount(player)
new_bal = cred * 2
chars = ["'", ","]
data = self.Uccount.get(ctx.author, self.settings)
if cred not in range(100, 20000) or cred > (int(data.Balance) - 100):
raise Framework.CreditError(
"Du willst mehr Credits ausgeben als du hast / Mehr setzten als erlaubt ist / Weniger als die Mindestangabe verwenden! (Du musst mind. 100 Credits in der Bank lassen und nicht mehr als 20000 / weniger als 250 setzten.)")
else:
for p in chars:
if Framework.BlackJack_Bot.pointCount(player) == 21:
embed = discord.Embed(
title='!!BLACKJACK!!',
colour=Framework.Farbe.Lp_Green,
description=f'{ctx.author.mention}, du hast einen BLACKJACK!\n**Du hast somit Gewonnen!**\nDir wurden: **{new_bal}**₹ überwiesen!'
)
embed.set_thumbnail(url=ctx.author.avatar_url)
embed.add_field(name='**Deine Hand:**',
value=f'{str(player).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(player))}')
embed.add_field(name='**Dealer Hand:**',
value=f'{str(dealer).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(dealer))}')
embed.set_thumbnail(url=ctx.author.avatar_url)
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"], {"Type": "balance", "Attributes": "*", "Timestamp": False})
await Framework.Messaging.Universal_send(ctx, embed, 10)
return
elif Framework.BlackJack_Bot.pointCount(dealer) == 21:
embed = discord.Embed(
title='!!BLACKJACK!!',
colour=Framework.Farbe.Dp_Red,
description=f'{ctx.author.mention}, der Dealer hat einen BLACKJACK!\n**Du hast somit Verloren!**\nDir wurden: **{cred}**₹ entzogen! '
)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.add_field(name='**Deine Hand:**',
value=f'{str(player).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(player))}')
embed.add_field(name='**Dealer Hand:**',
value=f'{str(dealer).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(dealer))}')
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"],
{"Type": "balance", "Attributes": "-", "Timestamp": False})
await Framework.Messaging.Universal_send(ctx, embed, 10)
return
elif Framework.BlackJack_Bot.pointCount(player) > 21 and Framework.BlackJack_Bot.pointCount(dealer) > 21:
embed = discord.Embed(
title='-BLACKJACK-',
colour=Framework.Farbe.Darker_Theme,
description=f'{ctx.author.mention}, ihr habt beide mehr als 21!\n**Keiner hat Gewonnen!**\nDir wurden: **{cred}**₹ entzogen!'
)
embed.add_field(name='**Deine Hand:**',
value=f'{str(player).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(player))}')
embed.add_field(name='**Dealer Hand:**',
value=f'{str(dealer).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(dealer))}')
embed.set_thumbnail(url=self.client.user.avatar_url)
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"], {"Type": "balance", "Attributes": "-", "Timestamp": False})
await Framework.Messaging.Universal_send(ctx, embed, 10)
return
elif Framework.BlackJack_Bot.pointCount(player) > 21 > Framework.BlackJack_Bot.pointCount(dealer):
embed = discord.Embed(
title='-BLACKJACK-',
colour=Framework.Farbe.Dp_Red,
description=f'{ctx.author.mention}, du hast mehr als 21!\n**Du hast somit Verloren!**\nDir wurden: **{cred}**₹ entzogen!'
)
embed.add_field(name='**Deine Hand:**',
value=f'{str(player).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(player))}')
embed.add_field(name='**Dealer Hand:**',
value=f'{str(dealer).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(dealer))}')
embed.set_thumbnail(url=self.client.user.avatar_url)
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"], {"Type": "balance", "Attributes": "-", "Timestamp": False})
await Framework.Messaging.Universal_send(ctx, embed, 10)
return
elif Framework.BlackJack_Bot.pointCount(dealer) > 21 > Framework.BlackJack_Bot.pointCount(player):
embed = discord.Embed(
title='-BLACKJACK-',
colour=Framework.Farbe.Lp_Green,
description=f'{ctx.author.mention}, der Dealer hat mehr als 21!\n**Du hast somit Gewonnen!**\nDir wurden: **{new_bal}**₹ überwiesen!'
)
embed.add_field(name='**Deine Hand:**',
value=f'{str(player).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(player))}')
embed.add_field(name='**Dealer Hand:**',
value=f'{str(dealer).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(dealer))}')
embed.set_thumbnail(url=ctx.author.avatar_url)
self.Uccount.refactor(ctx.author, cred, ["Currency", "Balance"], {"Type": "balance", "Attributes": "*", "Timestamp": False})
await Framework.Messaging.Universal_send(ctx, embed, 10)
return
else:
embed = discord.Embed(
title='-BLACKJACK-',
colour=Framework.Farbe.Red,
description=f'{ctx.author.mention} um eine Karte zu ziehen tippe (⬇), um zu halten tippe (⏹).'
)
embed.add_field(name='**Deine Hand:**',
value=f'{str(player).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Bot.pointCount(player))}')
embed.add_field(name='**Dealer Hand:**', value=f'{str(dealer[0]).replace(p, " ")}')
await ctx.message.delete()
m = await ctx.send(embed=embed)
await asyncio.sleep(2)
await m.add_reaction('⬇')
await m.add_reaction('⏹')
# CHECK
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in valid_reactions
try:
reaction, user = await self.client.wait_for('reaction_add', timeout=120.0, check=check)
except asyncio.TimeoutError:
erembed = discord.Embed(
title='Roulette',
colour=Framework.Farbe.Red,
description=f'{ctx.author.mention} hat nicht rechtzeitig reagiert.'
)
await m.clear_reactions()
await m.edit(embed=erembed)
await asyncio.sleep(9)
await m.delete()
return
avatar = self.client.user.avatar_url
if str(reaction.emoji) == hit:
player.append(myDeck.pop())
if "Ass" in dealer:
pass
elif Framework.BlackJack_Bot.pointCount(dealer) < 15:
while Framework.BlackJack_Bot.pointCount(dealer) < 15:
if Framework.BlackJack_Bot.pointCount(dealer) < 15:
dealer.append(myDeck.pop())
else:
break
await Framework.BlackJack_Bot.win_evaluation_bot(self, ctx, dealer, player, m, avatar, cred)
return
elif str(reaction.emoji) == stand:
if "Ass" in dealer:
pass
elif Framework.BlackJack_Bot.pointCount(dealer) < 15:
while Framework.BlackJack_Bot.pointCount(dealer) < 15:
if Framework.BlackJack_Bot.pointCount(dealer) < 15:
dealer.append(myDeck.pop())
else:
break
await Framework.BlackJack_Bot.win_evaluation_bot(self, ctx, dealer, player, m, avatar, cred)
return
@commands.command(aliases=["bjd"])
async def blackjack_d(self, ctx, user: discord.Member):
myDeck = Framework.BlackJack_Duell.Deck()
hands = Framework.BlackJack_Duell.createPlayinghands(myDeck)
pl1P = hands[0]
pl2P = hands[1]
Framework.BlackJack_Duell.pointCount(pl1P)
Framework.BlackJack_Duell.pointCount(pl2P)
pl1 = ctx.author
pl2 = user
ei = "1️⃣"
zw = "2️⃣"
dr = "3️⃣"
'❤️'
'♦️'
'♠️'
'♣️'
hit = "⬇"
stand = "⏹"
chars = ["'", ","]
valid_reactions = ['1️⃣', '2️⃣', '3️⃣', '⬇', '⏹']
auth = self.Uccount.get(ctx.author, self.settings)
us = self.Uccount.get(user, self.settings)
if (int(auth.Balance) - 100) < 1000:
raise Framework.CreditError(
f"{ctx.author.name}, du musst mind. 1000 Credits besitzen! (Du musst mind. 100 Credits in der Bank lassen.)")
if (int(us.Balance) - 100) < 1000:
raise Framework.CreditError(
f"{user.name}, du musst mind. 1000 Credits besitzen! (Du musst mind. 100 Credits in der Bank lassen.)")
else:
await ctx.message.delete()
embed = discord.Embed(
title="-BLACK-JACK-",
colour=Framework.Farbe.Red,
description=f"{ctx.author.mention}|{user.mention} bitte wählt euren Geldbetrag gemeinsam. **100**₹ (1️⃣), **500**₹ (2️⃣), **1000**₹ (3️⃣)\n**Der Command-Starter muss zuerst auswählen, die Auswahl kann nicht"
f" Rückgängig gemacht werden!**"
)
st = await ctx.send(embed=embed)
await st.add_reaction("1️⃣")
await st.add_reaction("2️⃣")
await st.add_reaction("3️⃣")
# CHECK
def check1(reaction, user_n):
return user_n == ctx.author and str(reaction.emoji) in valid_reactions
def check2(reaction, user_n):
return user_n == user and str(reaction.emoji) in valid_reactions
try:
reaction1, user1 = await self.client.wait_for('reaction_add', timeout=120.0, check=check1)
except asyncio.TimeoutError:
erembed = discord.Embed(
title='Roulette',
colour=Framework.Farbe.Red,
description=f'{ctx.author.mention} hat nicht rechtzeitig reagiert.'
)
await Framework.Messaging.Universal_edit(ctx, erembed, 15)
return
try:
reaction2, user2 = await self.client.wait_for('reaction_add', timeout=120.0, check=check2)
except asyncio.TimeoutError:
erembed = discord.Embed(
title='Roulette',
colour=Framework.Farbe.Red,
description=f'{user.mention} hat nicht rechtzeitig reagiert.'
)
await Framework.Messaging.Universal_edit(ctx, erembed, 15)
return
if not str(reaction1.emoji) == str(reaction2.emoji):
embed = discord.Embed(
title="-BLACK-JACK-",
colour=Framework.Farbe.Red,
description=f"**Ihr habt nicht den selben Betrag gewählt!**"
)
embed.set_thumbnail(url=self.client.user.avatar_url)
return await Framework.Messaging.Universal_edit(st, embed, 15)
else:
if str(reaction1.emoji) and str(reaction2.emoji) == ei:
cred = 100
elif str(reaction1.emoji) and str(reaction2.emoji) == zw:
cred = 500
elif str(reaction1.emoji) and str(reaction2.emoji) == dr:
cred = 1000
for p in chars:
embed = discord.Embed(
title="-BLACK-JACK-",
colour=Framework.Farbe.Red,
description=f"{ctx.author.mention}|{user.mention} **schaut in eure Privatnachrichten!**"
)
embed.set_thumbnail(url=self.client.user.avatar_url)
await st.edit(embed=embed)
pl1E = discord.Embed(
title='-BLACKJACK-',
colour=Framework.Farbe.Red,
description=f'{pl1.name} um eine Karte zu ziehen tippe (⬇), um zu halten tippe (⏹).'
)
pl1E.add_field(name=f'**Deine Hand:**',
value=f'{str(pl1P).replace(p, " ")}\n\nGezählt:\n{str(Framework.BlackJack_Duell.pointCount(pl1P))}')
pl1E.add_field(name=f'**{pl2.name}`s Hand:**', value=f'{str(pl2P[0]).replace(p, " ")}')
pl2E = discord.Embed(
title="-BLACK-JACK-",
colour=Framework.Farbe.Red,
description=f"{pl2.name}, bitte warte bis {pl1.name} seine Auswahl getroffen hat."
)
Embed_pl2 = await pl2.send(embed=pl2E)
Embed_pl1 = await pl1.send(embed=pl1E)
await asyncio.sleep(2)
await Embed_pl1.add_reaction("⬇")
await Embed_pl1.add_reaction("⏹")
try:
reaction1, user_new1 = await self.client.wait_for('reaction_add', timeout=60.0, check=check1)
except asyncio.TimeoutError:
erembed = discord.Embed(
title='-BLACK_JACK-',
colour=Framework.Farbe.Red,
description=f'{pl1.name} hat nicht rechtzeitig reagiert.'
)
await Embed_pl1.edit(embed=erembed)
await Embed_pl2.edit(embed=erembed)
| |
<filename>codes/orbitm_run_stk.py
# -*- coding: utf-8 -*-
###############################################################################
###############################################################################
## ##
## _____ ___ ____ ___ _____ ______ ##
## | _ | _ \| _ \|_ _||_ _| | | ##
## | |_| | <| _ < | | | | | \ / | _ ##
## |_____|_|\_|____/|___| |_| |_|\/|_| |_| ##
## v 1.0 ##
## ##
## FILE DESCRIPTION: ##
## ##
## This code is quite difficult to understand even with my comments. ##
## If the reader wants to understand the code, it is best to first go ##
## through the STK Object Model API, documentation, and tutorial. ##
## ##
## Important note, make sure you close any running instances of STK. ##
## (i.e. check your task manager) ##
## ##
## Written by <NAME>. ##
## First created 12-10-2020 10:18 AM (+8 GMT) ##
## Last modified 30-03-2021 08:33 PM (+8 GMT) ##
## ##
###############################################################################
###############################################################################
# Import basic utilities
import os
import datetime
import comtypes
import numpy as np
import matplotlib.pyplot as plt
# Needed to interact with COM
from comtypes.client import CreateObject
from comtypes.client import GetActiveObject
def orbm_run_stk(orbm_mode, tstart, tfinal,
sc_Cd, sc_area_d, sc_Ck, sc_area_a, sc_Cr, sc_area_r,
orb_a, orb_e, orb_i, orb_R, orb_w, orb_m,
maintenance_tolerance,
maintenance_margin,
maintenance_fro,
sc_mass, isp_min, isp_max):
# The parameters below are not used, but will be set to defaults.
thr_TankPressure = 0.1 # tank pressure (Pa)
thr_TankVolume = 0.1 # tank volume (m^3)
thr_FuelDensity = 0.1 # fuel density (kg/m^3)
thr_FuelMass = 0.1 # fuel mass (kg)
thr_MaximumFuelMass = 1.0 # max fuel mass (kg)
# For thruster sizing and plotting, what range of Isp is needed?
plot_Isp_Min = isp_min # s
plot_Isp_Max = isp_max # s
# Check below if you want the STK GUI to open up too (default True)
stk_gui = True
# User, check if you are using STK10 or STK11. By default, the comtypes GUID
# is using the STK10 GUID code that allows the Astrogator wrapper to load.
# Without successful loading, the AgStkGatorLib file cannot be recognised
# and created in the comtypes gen folder, and AstroGator cannot be run.
# GUID for STK10: 90E096F9-9615-4BA8-BA23-680F8D236959
# GUID for STK11: 090D317C-31A7-4AF7-89CD-25FE18F4017C
# Replace below where necessary.
if orbm_mode == 2:
comtypes.client.GetModule((comtypes.GUID("{90E096F9-9615-4BA8-BA23-680F8D236959}"),1,0))
elif orbm_mode == 3:
comtypes.client.GetModule((comtypes.GUID("{090D317C-31A7-4AF7-89CD-25FE18F4017C}"),1,0))
# As a rule of thumb, frozen repeat orbit maintenance generally takes about
# 02x as much Delta-V per thrust as regular altitude maintenance due to the
# need for the thrusts to bring the SC above the reference to maintain the
# eastward-to-westward ground track shift.
""" #######################################################################
TO THE USER: DO NOT CHANGE ANY OF THE CODE BELOW, AS THE CODE IS HIGHLY
DEPENDENT ON INTERFACING WITH THE RIGHT POINTERS TO THE RIGHT CLASSES.
EDIT THE CODE BELOW, AT YOUR RISK, AND ONLY IF YOU KNOW WHAT YOU ARE DOING!
####################################################################### """
# The program will now compute the total scenario time in seconds.
months_dict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4,
'May':5, 'Jun':6, 'Jul':7, 'Aug':8,
'Sep':9, 'Oct':10,'Nov':11,'Dec':12}
# Read the start epoch string as a datetime object
tstart_dt = datetime.datetime(int(tstart[6:10]),
int(months_dict[tstart[2:5]]),
int(tstart[0]),
int(tstart[11:13]),
int(tstart[14:16]),
int(tstart[17:19]))
# Read the final epoch string as a datetime object
tfinal_dt = datetime.datetime(int(tfinal[6:10]),
int(months_dict[tfinal[2:5]]),
int(tfinal[0]),
int(tfinal[11:13]),
int(tfinal[14:16]),
int(tfinal[17:19]))
# Read the time delta between start and final as a datetime-timedelta object
tdelta_dt = tfinal_dt - tstart_dt
# Compute the total scenario time in seconds
tdelta = (tdelta_dt.days*86400) + tdelta_dt.seconds # int
############################################################################
############################################################################
# The program will now compute what is the desired Delta-V per thrust
# using a first order Taylor expansion of the Vis-Visa equation.
GM = 398.6004415e12 # gravity constant x Earth mass (m**3/s**2)
velocity = ((398.6004415e12)/(orb_a*1000))**0.5
delta_v = (0.25*velocity*maintenance_tolerance)/(orb_a * 1000) # km/s
############################################################################
############################################################################
# First, try to close any existing STK applications.
print("Closing any pre-existing STK applications... \n")
print("Check if you need to save your existing scenarios? (Open the UI) \n")
# Check if the user is running in STK 10
if orbm_mode == 2:
try:
uiApp = GetActiveObject('STK10.Application')
uiApp.Quit()
except:
pass
# Check if the user is running in STK 11
elif orbm_mode == 3:
try:
uiApp = GetActiveObject('STK11.Application')
uiApp.Quit()
except:
pass
############################################################################
############################################################################
# Start STK10 Application
print("Creating a new STK application. \n")
if orbm_mode == 2:
uiApp = CreateObject("STK10.Application")
elif orbm_mode == 3:
uiApp = CreateObject("STK11.Application")
uiApp.Visible = stk_gui
uiApp.UserControl = stk_gui
stkRoot = uiApp.Personality2
from comtypes.gen import STKObjects
from comtypes.gen import STKUtil
from comtypes.gen import AgStkGatorLib
from comtypes.client import gen_dir
print("Creating the STK scenario object. \n")
stkRoot.NewScenario("Orbit_Maintenance")
# Get a reference to the scenario object (null if no scenario loaded)
scenario = stkRoot.CurrentScenario
scenario2 = scenario.QueryInterface(STKObjects.IAgScenario)
# Set the time period for the scenario.
scenario2.SetTimePeriod( tstart, tfinal )
#Reset STK to the new start time
stkRoot.Rewind()
############################################################################
############################################################################
# This segment will create the life-time test satellite and propagate it.
print("Creating the satellite (life-time) object. \n")
sat = scenario.Children.New(STKObjects.eSatellite, 'Lifetime')
sat2 = sat.QueryInterface(STKObjects.IAgSatellite)
# You can gain access to the initial orbit state through the satellite's
# propagator object. In the block below, get a pointer to the interface
# IAgVePropagtorTwoBody. Then use that pointer to convert the orbit state
# into the classical representation, and obtain a pointer to the interface
# IAgOrbitStateClassical.
sat2.SetPropagatorType(STKObjects.ePropagatorTwoBody)
sat2prop = sat2.Propagator.QueryInterface(STKObjects.IAgVePropagatorTwoBody)
sat2init = sat2prop.InitialState.Representation
sat2state = sat2init.ConvertTo(STKUtil.eOrbitStateClassical)
sat2state2 = sat2state.QueryInterface(STKObjects.IAgOrbitStateClassical)
# With the IAgOrbitStateClassical interface you will be able to set the values
# of the desired orbital elements.
# The SizeShape property only provides a pointer to the IAgClassicalSizeShape
# interface, which does not immediately provide access to the semimajor axis
# or eccentricity values. To access those, you "cast" to the interface
# IAgClassicalSizeShapeSemimajorAxis provided by the object
# AgClassicalSizeShapeSemimajorAxis.
sat2state2.SizeShapeType = STKObjects.eSizeShapeSemimajorAxis
sat2state2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeSemimajorAxis).SemiMajorAxis = orb_a
sat2state2.SizeShape.QueryInterface(STKObjects.IAgClassicalSizeShapeSemimajorAxis).Eccentricity = orb_e
# Set the inclination and argument of perigee
sat2state2.Orientation.Inclination = orb_i
sat2state2.Orientation.ArgOfPerigee = orb_w
# For the RAAN, much as in the case of the semi-major axis and eccentricity,
# you must first specify the AscNodeType, then provide the value for the
# AscNode through the approriate interface.
sat2state2.Orientation.AscNodeType = STKObjects.eAscNodeRAAN
sat2state2.Orientation.AscNode.QueryInterface(STKObjects.IAgOrientationAscNodeRAAN).Value = orb_R
# Set the mean anomaly
sat2state2.LocationType = STKObjects.eLocationMeanAnomaly
sat2state2.Location.QueryInterface(STKObjects.IAgClassicalLocationMeanAnomaly).Value = orb_m
# Propagate the orbit
sat2prop.InitialState.Representation.Assign(sat2state2)
sat2prop.Propagate()
# Prepare the STK Connect Command strings for the life-time computation.
setLifeTime = 'SetLifetime */Satellite/Lifetime '
setLifeTimeDragCoeff = setLifeTime + 'DragCoeff ' + str(sc_Cd)
setLifeTimeReflectCoeff = setLifeTime + 'ReflectCoeff ' + str(sc_Cr)
setLifeTimeDragArea = setLifeTime + 'DragArea ' + str(sc_area_d)
setLifeTimeSunArea = setLifeTime + 'SunArea ' + str(sc_area_r)
setLifeTimeMass = setLifeTime + 'Mass ' + str(sc_mass)
setLifeTimeLimitType = setLifeTime + 'LimitType Duration'
setLifeTimeDurationLimit = setLifeTime + 'DurationLimit 3650'
setLifeTimeDensityModel = setLifeTime + 'DensityModel Jacchia70Lifetime'
# Execute the STK Connect Command strings for life-time computation settings.
stkRoot.ExecuteCommand( setLifeTimeDragCoeff )
stkRoot.ExecuteCommand( setLifeTimeReflectCoeff )
stkRoot.ExecuteCommand( setLifeTimeDragArea )
stkRoot.ExecuteCommand( setLifeTimeSunArea )
stkRoot.ExecuteCommand( setLifeTimeMass )
stkRoot.ExecuteCommand( setLifeTimeLimitType )
stkRoot.ExecuteCommand( setLifeTimeDurationLimit )
stkRoot.ExecuteCommand( setLifeTimeDensityModel )
# Execute the STK Connect Command strings for life-time computation.
resultsLifeTime = stkRoot.ExecuteCommand('Lifetime */Satellite/Lifetime')
lifetime_str = resultsLifeTime.Item(0) + " \n"
print(lifetime_str)
# Finally, remove the test satellite used to compute the life time.
sat.Unload()
############################################################################
############################################################################
# This segment will create the test satellite and propagate it.
print("Creating the satellite object with orbit maintenance. \n")
satellite = scenario.Children.New(STKObjects.eSatellite, "Satellite")
#print("Querying the IAgStkObject interface of the satellite. \n")
satellite2 = satellite.QueryInterface(STKObjects.IAgSatellite)
satellite2.SetPropagatorType(STKObjects.ePropagatorAstrogator) # Astrogator
# For AstroGator, we need to access a special class called the IAgVADriverMCS.
# Acquire an interface to the DriverMCS interface of Astrogator through the
# propagator object. This is the central interface from which to control the
# satellite via Astrogator.
print("Creating the MCS interface object to Astrogator. \n")
astg = satellite2.Propagator.QueryInterface(AgStkGatorLib.IAgVADriverMCS)
mcs = astg.MainSequence
mcs.RemoveAll() # Clear all sequences
# Next, we set the initial states of the satellite.
# | |
<filename>src/pykeen/losses.py<gh_stars>10-100
# -*- coding: utf-8 -*-
r"""Loss functions integrated in PyKEEN.
Rather than re-using the built-in loss functions in PyTorch, we have elected to re-implement
some of the code from :mod:`pytorch.nn.modules.loss` in order to encode the three different
links of loss functions accepted by PyKEEN in a class hierarchy. This allows for PyKEEN to more
dynamically handle different kinds of loss functions as well as share code. Further, it gives
more insight to potential users.
Throughout the following explanations of pointwise loss functions, pairwise loss functions, and setwise
loss functions, we will assume the set of entities $\mathcal{E}$, set of relations $\mathcal{R}$, set of possible
triples $\mathcal{T} = \mathcal{E} \times \mathcal{R} \times \mathcal{E}$, set of possible subsets of possible triples
$2^{\mathcal{T}}$ (i.e., the power set of $\mathcal{T}$), set of positive triples $\mathcal{K}$, set of negative
triples $\mathcal{\bar{K}}$, scoring function (e.g., TransE) $f: \mathcal{T} \rightarrow \mathbb{R}$ and labeling
function $l:\mathcal{T} \rightarrow \{0,1\}$ where a value of 1 denotes the triple is positive (i.e., $(h,r,t) \in
\mathcal{K}$) and a value of 0 denotes the triple is negative (i.e., $(h,r,t) \notin \mathcal{K}$).
.. note::
In most realistic use cases of knowledge graph embedding models, you will have observed a subset of positive
triples $\mathcal{T_{obs}} \subset \mathcal{K}$ and no observations over negative triples. Depending on the training
assumption (sLCWA or LCWA), this will mean negative triples are generated in a variety of patterns.
.. note::
Following the open world assumption (OWA), triples $\mathcal{\bar{K}}$ are better named "not positive" rather
than negative. This is most relevant for pointwise loss functions. For pairwise and setwise loss functions,
triples are compared as being more/less positive and the binary classification is not relevant.
Pointwise Loss Functions
------------------------
A pointwise loss is applied to a single triple. It takes the form of $L: \mathcal{T} \rightarrow \mathbb{R}$ and
computes a real-value for the triple given its labeling. Typically, a pointwise loss function takes the form of
$g: \mathbb{R} \times \{0,1\} \rightarrow \mathbb{R}$ based on the scoring function and labeling function.
.. math::
L(k) = g(f(k), l(k))
Examples
~~~~~~~~
.. table::
:align: center
:widths: auto
============================= ============================================================
Pointwise Loss Formulation
============================= ============================================================
Square Error $g(s, l) = \frac{1}{2}(s - l)^2$
Binary Cross Entropy $g(s, l) = -(l*\log (\sigma(s))+(1-l)*(\log (1-\sigma(s))))$
Pointwise Hinge $g(s, l) = \max(0, \lambda -\hat{l}*s)$
Soft Pointwise Hinge $g(s, l) = \log(1+\exp(\lambda-\hat{l}*s))$
Pointwise Logistic (softplus) $g(s, l) = \log(1+\exp(-\hat{l}*s))$
============================= ============================================================
For the pointwise logistic and pointwise hinge losses, $\hat{l}$ has been rescaled from $\{0,1\}$ to $\{-1,1\}$.
The sigmoid logistic loss function is defined as $\sigma(z) = \frac{1}{1 + e^{-z}}$.
.. note::
The pointwise logistic loss can be considered as a special case of the pointwise soft hinge loss
where $\lambda = 0$.
Batching
~~~~~~~~
The pointwise loss of a set of triples (i.e., a batch) $\mathcal{L}_L: 2^{\mathcal{T}} \rightarrow \mathbb{R}$ is
defined as the arithmetic mean of the pointwise losses over each triple in the subset $\mathcal{B} \in 2^{\mathcal{T}}$:
.. math::
\mathcal{L}_L(\mathcal{B}) = \frac{1}{|\mathcal{B}|} \sum \limits_{k \in \mathcal{B}} L(k)
Pairwise Loss Functions
-----------------------
A pairwise loss is applied to a pair of triples - a positive and a negative one. It is defined as $L: \mathcal{K}
\times \mathcal{\bar{K}} \rightarrow \mathbb{R}$ and computes a real value for the pair.
All loss functions implemented in PyKEEN induce an auxillary loss function based on the chosen interaction
function $L{*}: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$ that simply passes the scores through.
Note that $L$ is often used interchangbly with $L^{*}$.
.. math::
L(k, \bar{k}) = L^{*}(f(k), f(\bar{k}))
Delta Pairwise Loss Functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Delta pairwise losses are computed on the differences between the scores of the positive and negative
triples (e.g., $\Delta := f(k) - f(\bar{k})$) with transfer function $g: \mathbb{R} \rightarrow \mathbb{R}$ that take
the form of:
.. math::
L^{*}(f(k), f(\bar{k})) = g(f(k) - f(\bar{k})) := g(\Delta)
The following table shows delta pairwise loss functions:
.. table::
:align: center
:widths: auto
========================================= =========== ====================== ==============================================
Pairwise Loss Activation Margin Formulation
========================================= =========== ====================== ==============================================
Pairwise Hinge (margin ranking) ReLU $\lambda \neq 0$ $g(\Delta) = \max(0, \Delta + \lambda)$
Soft Pairwise Hinge (soft margin ranking) softplus $\lambda \neq 0$ $g(\Delta) = \log(1 + \exp(\Delta + \lambda))$
Pairwise Logistic softplus $\lambda=0$ $g(\Delta) = \log(1 + \exp(\Delta))$
========================================= =========== ====================== ==============================================
.. note::
The pairwise logistic loss can be considered as a special case of the pairwise soft hinge loss
where $\lambda = 0$.
Inseparable Pairwise Loss Functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following pairwise loss function use the full generalized form of $L(k, \bar{k}) = \dots$
for their definitions:
.. table::
:align: center
:widths: auto
============== ===================================================
Pairwise Loss Formulation
============== ===================================================
Double Loss $h(\bar{\lambda} + f(\bar{k})) + h(\lambda - f(k))$
============== ===================================================
Batching
~~~~~~~~
The pairwise loss for a set of pairs of positive/negative triples $\mathcal{L}_L: 2^{\mathcal{K} \times
\mathcal{\bar{K}}} \rightarrow \mathbb{R}$ is defined as the arithmetic mean of the pairwise losses for each pair of
positive and negative triples in the subset $\mathcal{B} \in 2^{\mathcal{K} \times \mathcal{\bar{K}}}$.
.. math::
\mathcal{L}_L(\mathcal{B}) = \frac{1}{|\mathcal{B}|} \sum \limits_{(k, \bar{k}) \in \mathcal{B}} L(k, \bar{k})
Setwise Loss Functions
----------------------
A setwise loss is applied to a set of triples which can be either positive or negative. It is defined as
$L: 2^{\mathcal{T}} \rightarrow \mathbb{R}$. The two setwise loss functions implemented in PyKEEN,
:class:`pykeen.losses.NSSALoss` and :class:`pykeen.losses.CrossEntropyLoss` are both widely different
in their paradigms, but both share the notion that triples are not strictly positive or negative.
.. math::
L(k_1, ... k_n) = g(f(k_1), ..., f(k_n))
Batching
~~~~~~~~
The pairwise loss for a set of sets of triples triples $\mathcal{L}_L: 2^{2^{\mathcal{T}}} \rightarrow \mathbb{R}$
is defined as the arithmetic mean of the setwise losses for each set of
triples $\mathcal{b}$ in the subset $\mathcal{B} \in 2^{2^{\mathcal{T}}}$.
.. math::
\mathcal{L}_L(\mathcal{B}) = \frac{1}{|\mathcal{B}|} \sum \limits_{\mathcal{b} \in \mathcal{B}} L(\mathcal{b})
""" # noqa: E501
import logging
import math
from textwrap import dedent
from typing import Any, ClassVar, Mapping, Optional, Set, Tuple
import torch
from class_resolver import ClassResolver, Hint
from class_resolver.contrib.torch import margin_activation_resolver
from docdata import parse_docdata
from torch import nn
from torch.nn import functional
from torch.nn.modules.loss import _Loss
__all__ = [
# Base Classes
"Loss",
"PointwiseLoss",
"DeltaPointwiseLoss",
"MarginPairwiseLoss",
"PairwiseLoss",
"SetwiseLoss",
# Concrete Classes
"BCEAfterSigmoidLoss",
"BCEWithLogitsLoss",
"CrossEntropyLoss",
"FocalLoss",
"InfoNCELoss",
"MarginRankingLoss",
"MSELoss",
"NSSALoss",
"SoftplusLoss",
"SoftPointwiseHingeLoss",
"PointwiseHingeLoss",
"DoubleMarginLoss",
"SoftMarginRankingLoss",
"PairwiseLogisticLoss",
# Utils
"loss_resolver",
]
logger = logging.getLogger(__name__)
DEFAULT_MARGIN_HPO_STRATEGY = dict(type=float, low=0, high=3)
def apply_label_smoothing(
labels: torch.FloatTensor,
epsilon: Optional[float] = None,
num_classes: Optional[int] = None,
) -> torch.FloatTensor:
"""Apply label smoothing to a target tensor.
Redistributes epsilon probability mass from the true target uniformly to the remaining classes by replacing
* a hard one by (1 - epsilon)
* a hard zero by epsilon / (num_classes - 1)
:param labels:
The one-hot label tensor.
:param epsilon:
The smoothing parameter. Determines how much probability should be transferred from the true class to the
other classes.
:param num_classes:
The number of classes.
:returns: A smoothed label tensor
:raises ValueError: if epsilon is negative or if num_classes is None
..seealso:
https://www.deeplearningbook.org/contents/regularization.html, chapter 7.5.1
"""
if not epsilon: # either none or zero
return labels
if epsilon < 0.0:
raise ValueError(f"epsilon must be positive, but is {epsilon}")
if num_classes is None:
raise ValueError("must pass num_classes to perform label smoothing")
new_label_true = 1.0 - epsilon
new_label_false = epsilon / (num_classes - 1)
return new_label_true * labels + new_label_false * (1.0 - labels)
class UnsupportedLabelSmoothingError(RuntimeError):
"""Raised if a loss does not support label smoothing."""
def __init__(self, instance: object):
"""Initialize the error."""
self.instance = instance
def __str__(self) -> str:
return f"{self.instance.__class__.__name__} does not support label smoothing."
_REDUCTION_METHODS = dict(
mean=torch.mean,
sum=torch.sum,
)
class Loss(_Loss):
"""A loss function."""
#: synonyms of this loss
synonyms: ClassVar[Optional[Set[str]]] = None
#: The default strategy for optimizing the loss's hyper-parameters
hpo_default: ClassVar[Mapping[str, Any]] = {}
def __init__(self, reduction: str = "mean"):
"""
Initialize the loss.
:param reduction:
the reduction, cf. `_Loss.__init__`
"""
super().__init__(reduction=reduction)
self._reduction_method = _REDUCTION_METHODS[reduction]
def process_slcwa_scores(
self,
positive_scores: torch.FloatTensor,
negative_scores: torch.FloatTensor,
label_smoothing: Optional[float] = None,
batch_filter: Optional[torch.BoolTensor] = None,
num_entities: Optional[int] = None,
) -> torch.FloatTensor:
"""
Process scores from sLCWA training loop.
:param positive_scores: shape: (batch_size, 1)
The scores for positive triples.
:param negative_scores: shape: (batch_size, num_neg_per_pos) or (num_unfiltered_negatives,)
The scores for the negative triples, either in dense 2D shape, or in case they are already filtered, in
sparse shape. If they are given in sparse shape, batch_filter needs to be provided, too.
:param label_smoothing:
An optional label smoothing parameter.
:param batch_filter: shape: (batch_size, num_neg_per_pos)
An optional filter of | |
long, and supports both new lines, indents and embedded links. Indents of 5 spaces are
recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a
multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the
additional credits section is removed."""
description = description.strip()
async with self.bot.db.acquire() as conn:
if description.lower() == "remove":
await conn.execute("UPDATE settings SET value = '' WHERE key = 'additional_credits'")
self.bot.modules[self.bot.user.name.lower()].credits = None
await ctx.send("The additional credits section has been removed.")
return
if description.count("```") != 2 or description[:3] != "```" or description[-3:] != "```":
await ctx.send("Credits must be fully encased in a multi-line code block.")
return
description = description.strip("```").strip() # Remove code block.
description = description.replace(" ", "\u202F") # Prevent whitespace from disappearing.
if len(description) > 1024:
await ctx.send("Credits too long. Credits can be at most 1024 characters long.")
return
await conn.execute("UPDATE settings SET value = $1 WHERE key = 'additional_credits'", description)
self.bot.modules[self.bot.user.name.lower()].credits = description
await ctx.send("The additional credits section has been set.")
@commands.has_permissions(administrator=True)
@commands.group(
invoke_without_command=True, name="module", aliases=["modules"], usage="<list/load/unload/reload/error>"
)
async def module(self, ctx: commands.Context):
"""This command can load, unload, reload and list available modules. It can also show any errors that occur
during the loading process. Modules contain added functionality, such as commands. The intended purpose for
modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's
functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help
text for the subcommands for more info."""
raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.")
@commands.has_permissions(administrator=True)
@module.command(name="list")
async def module_list(self, ctx: commands.Context):
"""This command lists all currently loaded and available modules. For the bot to find new modules they need to
be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded,
unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload`
and `module reload` for more info on this."""
loaded_modules = [
f"`{clean(ctx, mod.replace('modules.', ''), False, True)}`, "
for mod in self.bot.extensions
if mod != "core_commands"
] or ["None, "]
available_modules = [
f"`{clean(ctx, mod, False, True).replace('.py', '')}`, "
for mod in listdir("modules")
if mod.endswith(".py")
]
available_modules = [mod for mod in available_modules if mod not in loaded_modules] or ["None, "]
loaded_modules[-1] = loaded_modules[-1][:-2]
available_modules[-1] = available_modules[-1][:-2]
paginator = commands.Paginator(prefix="", suffix="", linesep="")
paginator.add_line("Loaded modules: ")
for mod in loaded_modules:
paginator.add_line(mod)
paginator.add_line("\nAvailable Modules: ")
for mod in available_modules:
paginator.add_line(mod)
for page in paginator.pages:
await ctx.send(page)
@commands.has_permissions(administrator=True)
@module.command(name="load", aliases=["l"], usage="<MODULE NAME>")
async def module_load(self, ctx: commands.Context, *, mod: str):
"""This command loads modules. Modules should be located inside the module folder in the bot directory. The
`module list` command can be used to show all modules available for loading. Once a module is loaded the
functionality defined in the module file will be added to the bot. If an error is encountered during the
loading process the user will be informed and the `module error` command can then be used to see the error
details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the
`default` command."""
await self._module_operation(ctx, "load", mod)
@commands.has_permissions(administrator=True)
@module.command(name="unload", aliases=["ul"], usage="<MODULE NAME>")
async def module_unload(self, ctx: commands.Context, *, mod: str):
"""This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can
use the `module list` command to see all currently loaded modules. This will not prevent default modules from
being loaded when the bot starts. See the `default` command for removing modules starting with the bot."""
await self._module_operation(ctx, "unload", mod)
@commands.has_permissions(administrator=True)
@module.command(name="reload", aliases=["rl"], usage="<MODULE NAME>")
async def module_reload(self, ctx: commands.Context, *, mod: str):
"""This command reloads a module that is currently loaded. This will unload and load the module in one command.
If the module is no longer present or the loading process encounters an error the module will not be reloaded
and the functionality from before the reload will be retained and the user informed, the `module error` command
can then be used to see the error details. You can use the module list command to see all currently loaded
modules."""
await self._module_operation(ctx, "reload", mod)
@commands.has_permissions(administrator=True)
@module.command(name="error")
async def module_error(self, ctx: commands.Context):
"""This command will show the last error that was encountered during the module load or reloading process. This
information will also be logged to the console when the error first is encountered. This command retains this
information until another error replaces it, or the bot shuts down."""
if self.bot.last_module_error:
await ctx.send(self.bot.last_module_error[:1999])
else:
await ctx.send("There have not been any errors loading modules since the last restart.")
@commands.is_owner()
@commands.group(invoke_without_command=True, name="default", aliases=["defaults"], usage="<add/remove/list>")
async def default(self, ctx: commands.Context):
"""This command is used to add, remove or list default modules. Modules contain added functionality, such as
commands. Default modules are loaded automatically when the bot starts and as such any functionality in them
will be available as soon as the bot is online. For more info see the help text of the subcommands."""
raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.")
@commands.is_owner()
@default.command(name="list")
async def default_list(self, ctx: commands.Context):
"""This command lists all current default modules. For more information on modules see the help text for the
`module` command. All modules in this list start as soon as the bot is launched. For a list of all available or
loaded modules see the `module list` command."""
async with self.bot.db.acquire() as conn:
result = await conn.fetch("SELECT module FROM default_modules")
result = [f"`{clean(ctx, val['module'], False, True)}`, " for val in result] or ["None, "]
result[-1] = result[-1][:-2]
paginator = commands.Paginator(prefix="", suffix="", linesep="")
paginator.add_line("Default modules: ")
for mod in result:
paginator.add_line(mod)
for page in paginator.pages:
await ctx.send(page)
@commands.is_owner()
@default.command(name="add", usage="<MODULE NAME>")
async def default_add(self, ctx: commands.Context, *, mod: str):
"""This command adds a module to the list of default modules. Modules in this list are loaded automatically
once the bot starts. This command does not load modules if they are not already loaded until the bot is started
the next time. For that, see the `module load` command. For a list of existing default modules, see the
`default list` command. For more info on modules see the help text for the `module` command."""
if f"{mod}.py" in listdir("modules"): # Check if such a module even exists.
try:
async with self.bot.db.acquire() as conn:
await conn.execute("INSERT INTO default_modules VALUES ($1)", mod)
await ctx.send(f"The `{clean(ctx, mod, False, True)}` module is now a default module.")
except IntegrityConstraintViolationError:
await ctx.send(f"The `{clean(ctx, mod, False, True)}` module is already a default module.")
else:
await ctx.send(f"No `{clean(ctx, mod, False, True)}` module was found.")
@commands.is_owner()
@default.command(name="remove", usage="<MODULE NAME>")
async def default_remove(self, ctx: commands.Context, *, mod: str):
"""This command removes a module from the list of default modules. Once removed from this list the module will
no longer automatically be loaded when the bot starts. This command will not unload commands that are already
loaded. For that, see the `module unload` command. For a list of existing default modules, see the
`default list` command. For more info on modules see the help text for the `module` command."""
async with self.bot.db.acquire() as conn:
result = await conn.fetchval("SELECT module FROM default_modules WHERE module = $1", mod)
if result:
await conn.execute("DELETE FROM default_modules WHERE module = $1", mod)
await ctx.send(f"Removed `{clean(ctx, mod, False, True)}` module from default modules.")
else:
await ctx.send(f"No `{clean(ctx, mod, False, True)}` module in default modules.")
@commands.has_permissions(administrator=True)
@commands.group(
invoke_without_command=True, name="command", aliases=["commands"], usage="<enable/disable/show/hide>"
)
async def command(self, ctx: commands.Context):
"""This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in
the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show
up in the overall help command list and the specific help text for the command | |
0.10122213733079687,
0.10815111064556049,
0.15441507348973532,
0.21250258967874155,
0.24896898089962366,
0.3253959634471055,
0.42135517906718983,
0.5055255686061185,
0.551874739010259,
0.6575563227830395,
0.7177979465884874,
0.7330599486607571,
0.7352348966378153,
0.735446432018303,
0.7936409320282931,
0.8599860993127918,
0.8965196532241496,
0.9217321230237153,
0.9494990625721857,
0.9647891737357832,
0.9695797911945361,
0.9774937789812066,
0.9862095939016312,
0.9910090345739461,
0.9915990516603818,
0.9929241419894697,
0.9951849072551446,
0.9978379661773127,
1.0],
'KOR': [0.011635293943269955,
0.019447860022177913,
0.02325324116360027,
0.024517402124857222,
0.024835306692862425,
0.04537533446193729,
0.06632816168161684,
0.07701512309748056,
0.08064903665344815,
0.13129999000331036,
0.18296889162230343,
0.20932254558092575,
0.3030000872118299,
0.3985602960987863,
0.5140629829603046,
0.5852693278321308,
0.7030933088133973,
0.7518336651652883,
0.7607947623979741,
0.7617214987651966,
0.7617857540220871,
0.8344231553838621,
0.8945191188263324,
0.9315677279502026,
0.9481410301993259,
0.9685756072240316,
0.981173336146785,
0.983458633958041,
0.9876852292478516,
0.9928965435474181,
0.9961092709162223,
0.996309194938151,
0.9968091590118006,
0.9977556201718949,
0.9989776070720338,
1.0],
'KSA': [0.06343099770152492,
0.0902528140439361,
0.10008664774951846,
0.10255387456303272,
0.10302310874241193,
0.1631473563601831,
0.20963082962285684,
0.22759956413657617,
0.23223024822509064,
0.3300601099091065,
0.4056946823163944,
0.43493211782310287,
0.5543184164004782,
0.6466187783631067,
0.7437471877782379,
0.7832572824370448,
0.858349545558518,
0.8940293384658707,
0.901564055353502,
0.9024590781128086,
0.9025308565713966,
0.9330770422027577,
0.9621048416625628,
0.9739128297815889,
0.9831077927975665,
0.9905884848285206,
0.9936314961579158,
0.9950878129721178,
0.9968650236418533,
0.9983108984834719,
0.9988990544329117,
0.9990466252047818,
0.9992906480553775,
0.9995965308079682,
0.999858910987041,
1.0],
'MAR': [0.001434212545144189,
0.0028663365766151924,
0.0037861945817765238,
0.00418771725251694,
0.004320196538734628,
0.008892977405620022,
0.014999442822074674,
0.0190767123182352,
0.02089163310689366,
0.03842624460479098,
0.06184186451307851,
0.07747640696516364,
0.12790457245119288,
0.1952460562265638,
0.2919310184070792,
0.38461713758027705,
0.5137296831041736,
0.5586933992473367,
0.5656528254378727,
0.5662587341481394,
0.566293839935044,
0.6900663533776197,
0.7762744308061266,
0.8589169840846043,
0.8789317472098799,
0.9173056717254435,
0.9540924693884787,
0.9564158638713975,
0.9630977639230763,
0.975908843754436,
0.9881900635553995,
0.9883596586388999,
0.9890176809641097,
0.9909475001858615,
0.9947937877130215,
1.0],
'MEX': [0.0032361178889729705,
0.006251693952854025,
0.008154081750803994,
0.00897266864500674,
0.009239315305066803,
0.017133318660959126,
0.02756464177980576,
0.03445674057328825,
0.03749253480175009,
0.06261348132429767,
0.09580889541445795,
0.11774149886210589,
0.17769795495966217,
0.2569258369883309,
0.35232501908925656,
0.42822179933521665,
0.5542845394815891,
0.6066313399707234,
0.6162920939669481,
0.6172949865770639,
0.6173647990201927,
0.7176566031571591,
0.8009477493873196,
0.8672117328162016,
0.8902691670702833,
0.9269567986008417,
0.9561443979774672,
0.9593358852990139,
0.9669530453175853,
0.9790730217638451,
0.9887153181511961,
0.9889956399947967,
0.9899003437068421,
0.9921106956478292,
0.9957941344399901,
1.0],
'NGA': [0.005093315491884334,
0.008797457467689293,
0.01061926406987998,
0.011227842913847447,
0.011381473369255305,
0.023619545535853916,
0.03611894300743571,
0.04250209449672817,
0.04467524580410876,
0.08168182148029265,
0.11947861595428315,
0.13878055954681706,
0.22270840116072305,
0.308428393409775,
0.4353226452062578,
0.5312511882817724,
0.6608550726576276,
0.704630278417,
0.7112016474380024,
0.7117565363450759,
0.7117876806527358,
0.8097646309801881,
0.8759503194865905,
0.9259848685775288,
0.940888188009382,
0.9634211822127697,
0.9804555023215071,
0.982133424959317,
0.9859388142128038,
0.9916923521667166,
0.9960418676540983,
0.996160488027245,
0.9965232993120183,
0.9973618864082543,
0.9986783701380364,
1.0],
'PAN': [0.018062003111223468,
0.02741932437793211,
0.030975361763618064,
0.03189350367519459,
0.03207266830688902,
0.06244409533327857,
0.08642711515545877,
0.09589629879459614,
0.09838876886874368,
0.16827292537253524,
0.2234574614574047,
0.24524589803055716,
0.365847623280483,
0.46108165903207676,
0.5998329569982528,
0.6796490734236286,
0.7892150522162825,
0.8268161791767006,
0.8325513120234843,
0.8330433613363347,
0.8330714390974555,
0.8960988200860392,
0.939358608948406,
0.9642436254850983,
0.9741409605959845,
0.9855277636470671,
0.9920779755107397,
0.9932101729263216,
0.9951640487184016,
0.9974119668278147,
0.9987050725224323,
0.9987864575448935,
0.9989759073774332,
0.999309213228669,
0.9997076141798601,
1.0],
'PER': [0.0020312114850504436,
0.003987107626495772,
0.00522197438528585,
0.005752455383180205,
0.0059247951544930105,
0.011752161947654854,
0.0194202983670207,
0.02446548586191157,
0.026678445696960876,
0.047379141500232536,
0.07461884770536634,
0.09254098909601305,
0.14769267534851194,
0.22026587503769104,
0.3182242085932663,
0.4052191471437676,
0.5341209121741313,
0.5818698539654334,
0.5897310046354015,
0.5904590040263807,
0.5905039824176683,
0.704979195713388,
0.7897890552978026,
0.8651070834351126,
0.8860510999770677,
0.9232510678804491,
0.9562876539918213,
0.9588737438112076,
0.9657637158051461,
0.9780014227662855,
0.9888694982677882,
0.9890708964680667,
0.9897953490721592,
0.9917660935534336,
0.9954138520853437,
1.0],
'POL': [0.004814692104018708,
0.009777727112537264,
0.013464469182849857,
0.015348688459457107,
0.016080326574346014,
0.024969486962347118,
0.03904927435746903,
0.05019995701133514,
0.056087248732340715,
0.08058219903740563,
0.11938042940963833,
0.1501072253669581,
0.2007308977042386,
0.28091513474774477,
0.35066437337299255,
0.39871458451126157,
0.5091923358341788,
0.57269535303345,
0.5889183608140398,
0.5912496219272015,
0.5914783842626907,
0.6675864448204417,
0.7550808302641732,
0.8153556630343559,
0.848883725756733,
0.8950786527443427,
0.9269023118841587,
0.9333263297466454,
0.9466028365902668,
0.9648951927389049,
0.977496786569641,
0.9782951258641172,
0.9805385625125529,
0.9853283506738207,
0.9923641278018268,
1.0],
'POR': [0.0011882605393783374,
0.0025777257799803823,
0.003637619565135796,
0.004189220980528738,
0.004406561282993764,
0.007997289128740117,
0.013737641365193102,
0.018326076525711596,
0.020771192127803595,
0.03444020984146075,
0.0562923188771423,
0.07375936293657809,
0.11278530418361722,
0.17517450735937598,
0.2494555870059234,
0.32014803691416677,
0.43889821236406135,
0.48876776769735425,
0.498075721380485,
0.49905294838137576,
0.4991217825263242,
0.6121349598997761,
0.7070555253821338,
0.797390336784348,
0.8239651544616333,
0.874547051666449,
0.9226852619809721,
0.9264053248092546,
0.9370263479444281,
0.9572421592797026,
0.9764813146201138,
0.976811981840754,
0.9780887943463973,
0.9818214246648063,
0.9892661931776058,
1.0],
'SEN': [0.005399037234727417,
0.009234929668946608,
0.011081249915693803,
0.011684712330544007,
0.011833751079698545,
0.024680510730795295,
0.037515552426383714,
0.04392721964059165,
0.04606249261389665,
0.08452936599822469,
0.12296115247168163,
0.14215951825494194,
0.22854513541558572,
0.314851957390055,
0.44418358216525067,
0.5409975525735817,
0.6702112096848613,
0.7133252590148599,
0.7197188771205811,
0.7202522084505849,
0.7202817660252278,
0.817007429200557,
0.8815553277253476,
0.9298740459704891,
0.9442322871624341,
0.9657286279110932,
0.9818201762910469,
0.9834171228597015,
0.9870034090007013,
0.9923725923065487,
0.9963918099928089,
0.9965032743919908,
0.9968408135721585,
0.9976131703810569,
0.9988132618541538,
1.0],
'SRB': [0.006179274790668191,
0.011456836216235602,
0.014649164705647052,
0.015969706369658766,
0.016383680939180387,
0.028567946815973265,
0.044088607726357934,
0.05397393514497417,
0.05817133793761182,
0.09167754675448578,
0.13435869888115978,
0.16154292549445054,
0.23064840386091556,
0.3186769078037515,
0.41369545926801937,
0.4790196950289645,
0.60005700104194,
0.6561235943829266,
0.667666272118359,
0.6690029645811547,
0.6691073307130239,
0.7523191813676257,
0.8294095454129448,
0.8824083444704874,
0.9062147461704402,
0.9389480382129378,
0.9614518256698545,
0.965127672638007,
0.9727089888210594,
0.9831331360657419,
0.9902996255746304,
0.9906621609903253,
0.9916749189358957,
0.9938189837034439,
0.9969231172615338,
1.0],
'SWE': [0.002582558031937135,
0.005227255195395361,
0.007058334100136568,
0.007924443631960145,
0.008234781060803336,
0.014633972047330576,
0.023945028443667464,
0.030718991855471715,
0.03400444650574572,
0.054939396405236894,
0.0854005124399114,
0.10756153012881592,
0.15892803820189932,
0.23366818184792104,
0.31769093373060786,
0.38641103072352556,
0.5086672007616206,
0.5630420189240718,
0.5737903820601847,
0.5749854961613545,
0.5750749023974534,
0.6750651511663903,
0.7640087454755372,
0.8367534758118775,
0.8631259240123388,
0.9062646491235269,
0.9415467281719581,
0.945456543316535,
0.9550497619367073,
0.9707418667364395,
0.9835760448572208,
0.9839453581207959,
0.9851719336988864,
0.9882578866613325,
0.993562075041209,
1.0],
'SWI': [0.0028156598444871307,
0.005465738155424086,
0.007137405263991407,
0.007856094542355797,
0.00808992361741567,
0.015308018232518445,
0.024830234719638713,
0.031111158679672866,
0.033873121075374275,
0.057618259380893766,
0.08894319477155423,
0.10960535231731514,
0.16819057700755227,
0.24547706633671407,
0.34184004972147863,
0.4210906168730956,
0.5482140806213518,
0.5991928168505741,
0.6082787574730967,
0.6091896628180518,
0.6092508007080546,
0.7137993134922715,
0.7976508842288685,
0.8666118514386062,
0.8890291507629444,
0.9259018922049087,
0.9562266659828508,
0.9592232425799404,
0.9666165502534185,
0.9787773158434591,
0.9887785376420875,
0.9890322292691474,
0.9898782020894502,
0.992013078132162,
0.9956849641886234,
1.0],
'TUN': [0.006656062397392624,
0.011234874707662282,
0.0133994134965311,
0.014094645482868443,
0.014263418349127276,
0.029078126911864368,
0.04363193592233943,
0.0507806879823749,
0.05312164014498191,
0.09541004034118333,
0.1369537060304353,
0.1573597293239739,
0.24789351118581313,
0.33683291654997627,
0.4660466902275361,
0.5582564652122775,
0.6851946750098052,
0.7288812286025982,
0.7355634472553152,
0.7361383787589112,
0.7361712827100549,
0.826757165540197,
0.8891085258015662,
0.9336038201967323,
0.9479095523372576,
0.9683273190215056,
0.9828978838928913,
0.9845390186750242,
0.9880524676984479,
0.9930670158329015,
0.996645507056925,
0.9967638260151344,
0.997105516721839,
0.9978513135052007,
0.9989573251151735,
1.0],
'URU': [0.002417986988163627,
0.00502203778744765,
0.006927297028768902,
0.007881048544544952,
0.008242940938619797,
0.014125940035936736,
0.02319920462902034,
0.030195987138612282,
0.033792999363139065,
0.05301746048040372,
0.08266706937732532,
0.10553115129822067,
0.15264741365891563,
0.22531414502569425,
0.3022973927502368,
0.3651888460753015,
0.4839189978712178,
0.539955423332001,
0.5517097378414624,
0.5530966428501923,
0.5532070842002921,
0.6502036648936544,
0.7417615645806216,
0.8165597777621124,
0.845367834483169,
0.8924373101992614,
0.9308907117188513,
0.935422839120643,
0.9465304016376046,
0.9646790448876353,
0.9795055764202699,
0.9799615499709026,
0.9814756537139597,
0.9852866161205802,
0.9918494322369001,
1.0]},
'SEN': {'COL': [0.00020016160730299354,
0.0004601396420839692,
0.00066227917520768,
0.0007687166453957171,
0.0008110186638405478,
0.001849947058348566,
0.0035174829641145314,
0.004855725335637887,
0.005571708977028737,
0.011436406734116248,
0.020849561806309327,
0.02840387168579732,
0.05323331130151409,
0.09308589623241538,
0.16316635586456874,
0.2620665102431052,
0.37454941411497233,
0.40653218437188476,
0.4105738754816602,
0.41086117353710644,
0.4108746664172078,
0.5696147291431902,
0.6598852819467753,
0.787278447673307,
0.8043898026846152,
0.8526861654975064,
0.9208437912206864,
0.9224655740791569,
0.9293317351708404,
0.9487112996177564,
0.9760604626462108,
0.9761562814393041,
0.976702383425053,
0.9790515838805844,
0.9858953487585375,
1.0],
'JPN': [0.0036847644448752535,
0.00714518171073377,
0.009374394222505708,
0.010355294515633245,
0.010682227529152332,
0.01913310418832523,
0.030569647307083787,
0.03830816508353565,
0.041799001825291816,
0.06772081464927532,
0.10280071724803011,
0.12653747467881332,
0.18617096660940682,
0.266872771793855,
0.3583312250531094,
0.4284650408148185,
0.5522354597262209,
0.6068422012500004,
0.6175498260643643,
0.6187308604862283,
0.6188184691839856,
0.7137303274905716,
0.7974793744708408,
0.8617013246768332,
0.8863343649004862,
0.9241134666265836,
0.9530839167673733,
0.9567065649797348,
0.9650405177169971,
0.9778221007202675,
0.9876235040411099,
0.9879627818087637,
0.9890191568044725,
0.9915105446701298,
0.9955239679691519,
1.0]},
'SRB': {'BEL': [0.0011997876689572294,
0.0028774483642029737,
0.004476215043965367,
0.005524798322982975,
0.006047383963102704,
0.009014254557660297,
0.015047019661459118,
0.02118046121842729,
0.02533765996952242,
0.035722213065767366,
0.05683791984869643,
0.07830601138861372,
0.10556679162112954,
0.16099822297197133,
0.20870691311318043,
0.2504540512283803,
0.34746378315258475,
0.4038202695663179,
0.4183711742271354,
0.4204844618441592,
0.4206941945560148,
0.5055818463689523,
0.6042105035397054,
0.6905147839724146,
0.7287127700067172,
0.7955625029998725,
0.8540588697617617,
0.8614557368535984,
0.8808734591504398,
0.9148561290669477,
0.9445924142244037,
0.945522246247241,
0.9488419320595144,
0.9578478123510685,
0.9746626329646795,
1.0],
'COL': [0.0005704080872213189,
0.0012719076704040104,
0.0018128139677370608,
0.0020964064316540774,
0.0022088178505383035,
0.004381260037398929,
0.00786767494794317,
0.01066523821613545,
0.012161782266944164,
0.021903247895882202,
0.037536709271608425,
0.050081285411172786,
0.08284262418478879,
0.13541922239327028,
0.2088719148403744,
0.29121436831901437,
0.40909394353444184,
0.45128237023882156,
0.45799303555425264,
0.4585934627514161,
0.4586292531685946,
0.5907754429797869,
0.6853641761496178,
0.7914007025335784,
0.8139692141076585,
0.8645690369993545,
0.9212928060495816,
0.9239851865139382,
0.9330398803208155,
0.9533409932879964,
0.976099089613308,
0.9763013250957925,
0.9772192106556661,
0.9803688644199404,
0.9877176422989543,
1.0],
'ENG': [0.000350524479879678,
0.0008166031522666834,
0.0011993317464859957,
0.0014129219219086438,
0.0015030218010221468,
0.0029892923331123287,
0.0055268644747717656,
0.007693116255687563,
0.008925960490611028,
0.016204139484501986,
0.028630480354582478,
0.039238487353932434,
0.06596909678374113,
0.11160738964773882,
0.17705649727834474,
0.2571816006900498,
0.36892561272151353,
0.4078857004256368,
0.4139228658135159,
0.41444908750700993,
0.41447961294913954,
0.55128056935321,
0.6466731933089317,
0.7634562043517263,
0.7856289360449165,
0.8399182146662207,
0.9063810622306192,
0.9089579387769987,
0.9184220479405575,
0.9415946396803783,
0.9699633428863808,
0.970151668595941,
0.9710848199287048,
0.9745798194660183,
0.9834759438539521,
1.0],
'GER': [0.00033094243808964635,
0.0008751509231749459,
0.001450191879140561,
0.001866501688764086,
0.0020950886600954546,
0.003250623271236425,
0.00583184999385524,
0.008714814869733228,
0.01086146511751765,
0.01604707272742558,
0.027630653873898806,
0.04056832311834373,
0.058021625268278934,
0.09700871355884104,
0.13617066317684579,
0.18010671277674425,
0.2675864558231546,
0.3111310252209211,
0.320764389512563,
0.321963183328489,
0.3220641605234044,
0.4202082612886637,
0.517914140568326,
0.6275310110281996,
0.6599542158578853,
0.7327058306002628,
0.8143263470702664,
0.8197060858289686,
0.8378127790280351,
0.87844081610199,
0.9240216788894527,
0.9245945426760314,
0.927209209979711,
0.9362602495777788,
0.95772693006254,
1.0],
'JPN': [0.009504438619037731,
0.01762040652365194,
0.022781922779834495,
0.025037985936441038,
0.02578686098685272,
0.040933132386746215,
0.061427758858348176,
0.07529353820168687,
0.08154752993506661,
0.11845254586062823,
0.1683892264042124,
0.20217422826875273,
0.26961558881090236,
0.3608714138621893,
0.4430343574387541,
0.4930833870171734,
0.6042591869187155,
0.6659989378582483,
0.6812372535086818,
0.683352843893075,
0.6835529650362548,
0.7512749897771475,
0.8264917355856136,
0.8723095333894658,
0.9001564998264632,
0.9340821014713403,
0.9547476639047001,
0.9599024571053918,
0.9693224846558275,
0.9807987832638962,
0.9877894968810487,
0.9884067500183411,
0.9899394570205599,
0.9928297317912872,
0.9965756310855225,
1.0],
'KOR': [0.008572862666456365,
0.014864198418709933,
0.018152671002213783,
0.019325217264681463,
0.019641729905450236,
0.03602054250100648,
0.05395731072285008,
0.06377876915785978,
0.06736399493906274,
0.1103521617201938,
0.15742937072643792,
0.18320697156135402,
0.2678276883755748,
0.3604975431289496,
0.4715461758160202,
0.5444113043916953,
0.6660229031715148,
0.716765217248488,
0.7261750742165186,
0.7271566374935454,
0.7272253107171615,
0.8070213835455,
0.8736110416075646,
0.9173041864855879,
0.9358271638855816,
0.9601350566924779,
0.9760848049416919,
0.9786610360092917,
0.9837322576021847,
0.990387273597621,
0.9947539963968752,
0.9949814324771108,
0.995586866177639,
0.9968069765884499,
0.9984842971577432,
1.0],
'MEX': [0.0023262447499997436,
0.004662036301434971,
0.00622774561093459,
0.006943583115652195,
0.007191336128781231,
0.013313450622546984,
0.021908926135759132,
0.02794296873439601,
0.030766909463538845,
0.05148931305996526,
0.08058365830119919,
0.10100795225622299,
0.15361453261956873,
0.22747440142918113,
0.31650694004204066,
0.3918472575184968,
0.5168493309532953,
0.5686991203037375,
0.5782577196375585,
0.5792489259198333,
0.5793178461179832,
0.6850959812191735,
0.7728477100053378,
0.8471041920607937,
0.871369969033808,
0.912437905980081,
0.94719004779072,
0.950545126603691,
0.9590624408418111,
0.973477331593989,
0.9856753713508902,
0.9859697227431204,
0.9869801585946156,
0.9896059038034075,
0.994259864169104,
1.0],
'PAN': [0.018423134719953094,
0.02834807408648582,
0.03230219634008702,
0.03337378284179655,
0.0335933768697546,
0.06362642875649804,
0.08855049298568465,
0.09889258176246367,
0.10175350629663404,
0.16997346681895215,
0.2265883817527672,
0.25008039617510414,
0.36630142737142624,
0.4627518466376096,
0.5947496567498733,
0.6697077847886841,
0.7792511608583738,
0.8192726753848982,
0.8257712543343317,
0.8263648159469961,
0.8264009645359542,
0.8886078026816162,
0.9340621599567093,
0.9598745088862142,
0.9709456314877407,
0.9835196374472757,
0.9906600888522952,
0.992008361746313,
0.9943053092214665,
0.9969140628484328,
0.9983955062771194,
0.9984989947375971,
0.998736990945388,
0.9991508612787212,
0.9996404297801212,
1.0],
'POL': [0.004475890552234655,
0.009273657263408968,
0.012989351246648228,
0.014971729077073453,
0.01577570321022377,
0.02396358796483395,
0.03752032622036174,
0.04874331955972277,
0.05493731584020631,
0.07759199611885555,
0.1151015092598888,
0.1461538913454424,
0.19316553298819172,
0.27100303801103415,
0.3360402083370608,
0.3810272942610105,
0.4887097936383603,
0.5531478453258775,
0.5702857276467649,
0.5728495884254278,
0.5731122156792314,
0.6475976495889523,
0.7367429845875807,
0.7984060124407113,
0.8339695239215806,
0.883169042865196,
0.9172010121996257,
0.9242948402101963,
0.9390155291012479,
0.9593805263076671,
0.9734672689284412,
0.9743880402636592,
0.9769882349197373,
0.9825699682365786,
0.9908242252077428,
1.0],
'SEN': [0.0054167809813552474,
0.00951489272154191,
0.011635690735954492,
0.012382278068575144,
0.01258101682686356,
0.0249644997899471,
0.03831439035661925,
0.04551024868958634,
0.04809605651023376,
0.08459037244709662,
0.12393270654769328,
0.14513901241681515,
0.22580099780109125,
0.3127578483883399,
0.43161390800758764,
0.5191815697810608,
0.6473131619860153,
0.6941846456721029,
0.7018050613370687,
0.7025019624337755,
0.702544460027064,
0.7969459063196938,
0.8660114002186603,
0.9168956700601548,
0.9337387822328285,
0.9585572383498191,
0.9768423319155533,
0.9788961102326696,
0.9834354975960167,
0.9901243200012981,
0.9950523357871561,
0.9952101840809404,
0.9956811562633424,
0.9967437598258985,
0.9983746062854975,
1.0],
'SWE': [0.0019937446929601667,
0.004162347337758477,
0.005741729029778614,
0.006527656163320101,
0.006823931349491354,
0.012040583618692539,
0.020026988632745595,
0.02614035998251534,
0.029260104030425314,
0.047125843424256166,
0.07447729859351243,
0.0954140782975241,
0.14130337103024923,
0.21155733059273013,
0.290137050173658,
0.3574160597389311,
0.47771724794906667,
0.5314947038683966,
0.5421790529986769,
0.543373091733724,
0.5434628949452952,
0.6464633234969381,
0.7385505437234352,
0.8173945126698657,
0.8448379458292777,
0.8918314197658822,
0.9320666662053921,
0.9361559525456828,
0.9466595456968476,
0.9646456456181933,
0.9800451277632514,
0.9804334782346911,
0.9817838066189617,
0.985340715750997,
0.9917423994333582,
1.0],
'TUN': [0.008208837407462071,
0.01410328061131554,
0.017092646036986337,
0.018125690645487243,
0.018395828320987136,
0.034637828660201944,
0.051856630104236454,
0.060983804004524,
0.06420916606691274,
0.10758745757441551,
0.15357453877436886,
0.17795092110520955,
0.26484028824646416,
0.356955220468871,
0.47298502646683105,
0.5504566223759008,
0.6734645123735987,
0.7222918949263132,
0.7309060245185739,
0.7317608587104453,
0.7318176243576312,
0.8139483964085347,
0.87915121594075,
0.9226862924970326,
0.93994092016292,
0.962982302169826,
0.9783667339601965,
0.9806497807519177,
0.9852228629087431,
0.991329638144044,
0.9954070527296123,
0.9955982675270345,
0.9961158645310964,
0.9971760650804834,
0.998655814384217,
1.0]},
'SWE': {'BEL': [0.002554907900359596,
0.005562409381446626,
0.00803367090511873,
0.009429948506661427,
0.010029179790710642,
0.015539279456872168,
0.025181772002856605,
0.033618793847521,
0.03854029709770071,
0.055636830474211724,
0.08555519958422507,
0.1117332788032787,
0.15151814720899506,
0.2211403537547316,
0.28286186260107365,
0.3307386661061183,
0.438749269368466,
0.4996675510989233,
0.5149378092933489,
0.5170909263547484,
0.5172979815948258,
0.6010808074769125,
0.6955883027986802,
0.7688968927513117,
0.8044318868584338,
0.8595602193382847,
0.9023227569209189,
0.9090033688760554,
0.9245496355753573,
0.9486678261352307,
0.9673760834658632,
0.9681894999113294,
0.9707623158147956,
0.9769435346300519,
0.9871548039426505,
1.0],
'COL': [0.001178995221125947,
0.0024051048421700493,
0.003219698620396964,
0.003587474493858865,
0.0037129810095353818,
0.0076379076830108625,
0.013058845630115005,
0.01680242744336862,
0.018525918215540216,
0.034127442064260355,
0.05567558797886603,
0.0705562687655453,
0.11706813382415737,
0.18130829810308696,
0.27375027630160326,
0.36561414074228205,
0.49329097886215806,
0.5376538387623518,
0.5445046883761293,
0.545099790992408,
0.5451341893908526,
0.6720125619422419,
0.7601834087261685,
0.8478028525591921,
0.8682268698451061,
0.9088194489276987,
0.9491581700889111,
0.9515236939401086,
0.9585758849457233,
0.9725920609552485,
0.9865205825858728,
0.9866928426647239,
0.9873856619581951,
0.9894918454052851,
0.9938429825854116,
1.0],
'ENG': [0.0007407492191755913,
0.0015751748479258278,
0.002165543686534173,
0.0024492549015784626,
0.0025522893904698623,
0.005302510054192318,
0.009343614891480896,
0.01231256362373527,
0.013766729737486999,
0.025705285786554056,
0.04324749875750376,
0.05613554127509962,
0.09500400074549398,
0.15211633418682868,
0.236479252415383,
0.3280329449081194,
0.45199368792710104,
0.4939533986483182,
0.5002658534570102,
0.5008000322043756,
0.5008300814275154,
0.6353567666802036,
0.7264291604076704,
0.8252642185704611,
0.8458157319094227,
0.8904222242405241,
0.938830804311181,
0.9411496447590639,
0.9486991135219875,
0.9650850270517138,
0.9828676135247048,
0.9830319142453093,
0.9837533376004515,
0.9861471712498087,
0.9915424641054906,
1.0],
'JPN': [0.017525221010268998,
0.029943221318974814,
0.03675223940154328,
0.03931598222674016,
0.0400487881945108,
0.06405166175273767,
0.09200344733879369,
0.10827863029873266,
0.11459621311323037,
0.16644066614601816,
0.2268144806180003,
0.26196768660892983,
0.3459528593763283,
0.44375513025474933,
0.5344560485099636,
0.5834328875236979,
0.6890557669417837,
0.7460020342041469,
0.7596475514674211,
0.7614867866721626,
0.7616553828821193,
0.8186898083426271,
0.8801896964979823,
0.9133985126763602,
0.9355035028501756,
0.9593760846491123,
0.9722668427373471,
0.9762394563895065,
0.9826748728014363,
0.9896248874133405,
0.9933777683470544,
0.9938385703780572,
0.9948523072247552,
0.9965453216127224,
0.9984868923367585,
1.0],
'KOR': [0.015471699982887891,
0.024911948497869735,
0.02916436519162377,
0.030470189685773523,
0.030773676425429376,
0.056192948419876036,
0.0801501968635246,
0.0914398544334993,
0.09498662702015051,
0.1541276750891532,
0.20986714638936987,
0.23613391678209877,
0.3393330829737255,
0.4365966105905003,
0.5566493573755642,
0.6264787103757447,
0.7396264622744054,
0.7854611049055912,
0.7937131055168906,
0.7945487993169538,
0.7946054844857335,
0.8604185085113643,
0.9137384620424631,
0.9447523118441865,
0.9591517790552729,
0.975902840664845,
| |
<filename>utils/maketarget/maketarget.py
# You may use, modify and redistribute this module under the terms of the GNU GPL.
"""
Utility function for creating a morph target (part of the development functionality).
=========================== ===============================================================
Project Name: **MakeHuman**
Product Home Page: http://www.makehuman.org/
Authors:
Copyright(c): MakeHuman Team 2001-2011
Licensing: GPL3
=========================== ===============================================================
The MakeHuman application uses predefined morph target files to distort
the humanoid model when physiological changes or changes to the pose are
applied by the user. The morph target files contain extreme mesh
deformations for individual joints and features which can used
proportionately to apply less extreme deformations and which can be
combined to provide a very wide range of options to the user of the
application.
This module contains a set of functions used by 3d artists during the
development cycle to create these extreme morph target files from
hand-crafted models.
"""
import os.path
__docformat__ = 'restructuredtext'
import sys
sys.path.append("./")
sys.path.append("../../../utils/maketarget/" )
sys.path.append("../../../utils/svd_tools/fit/")
sys.path.append("../../../utils/")
sys.path.append("../../../core/")
sys.path.append("../../../utils/topology_translator/")
import os
import Blender
import maketargetlib
from Blender.BGL import *
from Blender import Draw
from Blender import Window
import bpy
from Blender.Mathutils import *
import blender2obj
from Blender import Types
from Blender import Scene
from Blender.Scene import Render
basePath = 'base.obj'
pairsPath = 'base.sym'
centersPath = 'base.sym.centers'
windowEditMode = Blender.Window.EditMode()
GUIswitch = 1
objToCOnvertPath = None
morphFactor = Draw.Create(1.0)
regulFactor = Draw.Create(0.005)
saveOnlySelectedVerts = Draw.Create(0)
rotationMode = Draw.Create(0)
fitVert1 = Draw.Create("head_vertices.dat")
fitVert2 = Draw.Create("verts_to_fit.verts")
fitVert3 = Draw.Create("head2_vertices.dat")
poseMode = False
loadedTraslTarget = ""
loadedRotTarget = ""
loadedPoseTarget = ""
targetBuffer = [] #Loaded target Data
message = ""
targetVertexList = None
targetVertexLookup = None
targetBasePath = None
regularise = maketargetlib.RegularisationTool(basePath)
#--------SOME BLENDER SPECIFICS SHORTCUTS------------
def startEditing():
global windowEditMode
windowEditMode = Blender.Window.EditMode()
Blender.Window.EditMode(0)
def endEditing():
global windowEditMode
Blender.Window.EditMode(windowEditMode)
Blender.Window.RedrawAll()
def redrawAll():
Blender.Window.RedrawAll()
def getVertices(n=0,name = None, copy = True):
if name:
obj = Blender.Object.Get(name).getData(mesh=True)
else:
obj = Blender.Object.GetSelected()[n].getData(mesh=True)
if copy:
vertices = [[v.co[0],v.co[1],v.co[2]] for v in obj.verts]
else:
vertices = obj.verts
return vertices
def getObjName(n=0):
obj = Blender.Object.GetSelected()[n]
return obj.getName()
def getVertGroups(n=0, name = None):
vertGroups = {}
if name:
obj = Blender.Object.Get(name).getData(mesh=True)
else:
obj = Blender.Object.GetSelected()[n].getData(mesh=True)
vertGroupNames = obj.getVertGroupNames()
for n in vertGroupNames:
vertGroups[n] = obj.getVertsFromGroup(n)
return vertGroups
def getSelectedVertices(n=0, name = None):
selectedVertices = []
if name:
obj = Blender.Object.Get(name).getData(mesh=True)
else:
obj = Blender.Object.GetSelected()[n].getData(mesh=True)
for i,v in enumerate(obj.verts):
if v.sel == 1:
selectedVertices.append(i)
return selectedVertices
def selectVert(vertsToSelect, n=0, name = None):
if name:
obj = Blender.Object.Get(name).getData(mesh=True)
else:
obj = Blender.Object.GetSelected()[n].getData(mesh=True)
for i in vertsToSelect:
obj.verts[i].sel = 1
obj.update()
obj.calcNormals()
def updateVertices(vertices, n=0, name = None):
if name:
obj = Blender.Object.Get(name).getData(mesh=True)
else:
obj = Blender.Object.GetSelected()[n].getData(mesh=True)
for i,v in enumerate(vertices):
obj.verts[i].co[0], obj.verts[i].co[1],obj.verts[i].co[2] = v[0],v[1],v[2]
obj.update()
obj.calcNormals()
def colorVertices(vertColors, n=0):
obj = Blender.Object.GetSelected()[n].getData(mesh=True)
obj.vertexColors = True
for f in obj.faces:
for i, v in enumerate(f):
col = f.col[i]
col2 = vertColors[v.index]
print col2
col.r = col2[0]
col.g = col2[1]
col.b = col2[2]
obj.update()
obj.calcNormals()
def createMesh(verts, faces, name):
"""
Create mesh on the Blender scene
"""
scn = bpy.data.scenes.active
mesh = bpy.data.meshes.new(name)
mesh.verts.extend(verts)
mesh.faces.extend(faces)
ob = scn.objects.new(mesh, name)
return ob
def applyTransforms():
objs = Blender.Object.Get()
for obj in objs:
if type(obj.getData(mesh=True)) == Types.MeshType:
mesh = obj.getData(mesh=True)
m = obj.getMatrix()
obj.setLocation(0,0,0)
obj.setSize(1,1,1)
obj.setEuler(0,0,0)
mesh.transform(m) # Convert verts to world space
mesh.update()
def render(path = "//myRenderdir/", imageName = "001.tga"):
scn = Scene.GetCurrent()
context = scn.getRenderingContext()
Render.EnableDispWin()
context.extensions = True
context.renderPath = path
context.sizePreset(Render.PC)
context.imageType = Render.TARGA
context.render()
context.saveRenderedImage(imageName)
Render.CloseRenderWindow()
#-------MAKETARGET CALLBACKS----------------------
def buildScan2Mesh(path):
global message
main_dir = os.path.dirname(path)
target_dir = os.path.join(main_dir,"target_db_scan2mesh")
if not os.path.isdir(target_dir):
message = "The build folder must contain a 'target_db_scan2mesh' folder with the db"
print message
return
head_mesh = os.path.join(main_dir,"base_mesh.obj")
head_mask = os.path.join(main_dir,"base_mask.obj")
prefix = os.path.join(main_dir,"fitdata")
maketargetlib.scan2meshBuild(target_dir, head_mesh ,head_mask,prefix)
def fitScan2Mesh(path):
global message, regulFactor,fitVert1
print "Fitting using a regul = %f"%(regulFactor.val)
main_dir = os.path.dirname(path)
#target_dir = os.path.join(main_dir,"targets_db")
head_mesh = os.path.join(main_dir,"base_mesh.obj")
head_mask = os.path.join(main_dir,"base_mask.obj")
scan_mesh = os.path.join(main_dir,"scan_mesh.obj")
scan_mask = os.path.join(main_dir,"scan_mask.obj")
fit_verts = os.path.join(main_dir,fitVert1.val)
output = os.path.join(main_dir,"result.target")
prefix = os.path.join(main_dir,"fitdata")
if os.path.isfile(fit_verts):
maketargetlib.scan2meshFit(head_mesh,head_mask,scan_mesh,scan_mask,fit_verts,prefix,output,regulFactor.val)
else:
message = "Error: head_vertices.dat not found!"
print message
def saveScanMask(path):
mainDir = os.path.dirname(path)
scanMask = Blender.Object.Get("scan_mask")
scanMaskPath = os.path.join(mainDir,"scan_mask.obj")
bExporter = blender2obj.Blender2obj(scanMask,1)
bExporter.write(scanMaskPath,1)
def saveBaseMask(path):
mainDir = os.path.dirname(path)
baseMask = Blender.Object.Get("base_mask")
baseMaskPath = os.path.join(mainDir,"base_mask.obj")
bExporter = blender2obj.Blender2obj(baseMask,1)
bExporter.write(baseMaskPath,1)
def saveBaseMesh(path):
mainDir = os.path.dirname(path)
baseMask = Blender.Object.Get("Base")
baseMaskPath = os.path.join(mainDir,"base_mesh.obj")
bExporter = blender2obj.Blender2obj(baseMask,1)
bExporter.write(baseMaskPath,1)
def saveScanMesh(path):
mainDir = os.path.dirname(path)
scanMesh = Blender.Object.Get("scan_mesh")
scanMeshPath = os.path.join(mainDir,"scan_mesh.obj")
bExporter = blender2obj.Blender2obj(scanMesh,1)
bExporter.write(scanMeshPath,1)
def buildSVDdb(path):
saveBaseMesh(path)
saveBaseMask(path)
buildScan2Mesh(path)
def buildRegulariseDb(path):
mainDir = os.path.dirname(path)
vPath = os.path.join(mainDir,fitVert3.val)
regularise.buildBaseDB(vPath)
def loadFitTarget(path):
mainDir = os.path.dirname(path)
tPath = os.path.join(mainDir,"result.target")
loadTarget(tPath)
applyTarget(1.0, meshName = "Base")
def scan2mh(path):
global loadedTraslTarget,objToCOnvertPath
saveScanMask(path)
saveScanMesh(path)
fitScan2Mesh(path)
loadFitTarget(path)
applyTransforms()
align()
loadSelVertsBase(path)
adapt(path)
loadedTraslTarget = objToCOnvertPath
def loadTarget(path):
global loadedTraslTarget,rotationMode,loadedRotTarget,loadedPoseTarget,poseMode
startEditing()
if os.path.splitext(path)[1] == ".rot":
loadedRotTarget = path
loadedTraslTarget = ""
loadedPoseTarget = ""
rotationMode.val = 1
poseMode = False
if os.path.splitext(path)[1] == ".target":
loadedTraslTarget = path
loadedRotTarget = ""
loadedPoseTarget = ""
rotationMode.val = 0
poseMode = False
if os.path.splitext(path)[1] == ".pose":
loadedPoseTarget = path
loadedTraslTarget = ""
loadedRotTarget = ""
poseMode = True
endEditing()
def applyTarget(mFactor, n=0, meshName = None):
global loadedTraslTarget,rotationMode,loadedRotTarget,loadedPoseTarget
startEditing()
vertices = getVertices(n, name = meshName)
if rotationMode.val and not poseMode:
maketargetlib.loadRotTarget(vertices,loadedRotTarget,mFactor)
if not rotationMode.val and not poseMode:
maketargetlib.loadTraslTarget(vertices,loadedTraslTarget,mFactor)
if not rotationMode.val and poseMode:
maketargetlib.loadPoseFromFile(vertices,loadedPoseTarget,mFactor)
if rotationMode.val and poseMode:
maketargetlib.loadPoseFromFile(vertices,loadedPoseTarget,mFactor,onlyRot = True)
updateVertices(vertices, n, name = meshName)
endEditing()
def applyPosesFromLibrary(path, n=0, meshName = None, onlyRot = False):
mainDir = os.path.dirname(path)
poseFiles = os.listdir(mainDir)
homedir = os.path.expanduser('~')
saveDir = os.path.join(homedir, "poseLibBlender")
if not os.path.isdir(saveDir):
os.mkdir(saveDir)
for poseFile in poseFiles:
blendFile = os.path.join(saveDir,poseFile+".blend")
startEditing()
vertices = getVertices(n, name = meshName)
pPath = os.path.join(mainDir,poseFile)
maketargetlib.loadPoseFromFile(vertices,pPath,1.00,onlyRot)
updateVertices(vertices, n, name = meshName)
endEditing()
Blender.Save(blendFile)
startEditing()
vertices = getVertices(n, name = meshName)
pPath = os.path.join(mainDir,poseFile)
maketargetlib.loadPoseFromFile(vertices,pPath,-1.00,onlyRot)
updateVertices(vertices, n, name = meshName)
endEditing()
def applyPoseFromFolder(path, n=0):
global morphFactor
startEditing()
vertices = getVertices(n)
maketargetlib.loadPoseFromFolder(vertices,path,morphFactor.val)
updateVertices(vertices)
endEditing()
def scanReg(scan):
global objToCOnvertPath
objToCOnvertPath = os.path.basename(scan)
print "wavefront ",objToCOnvertPath
startEditing()
(vertsM, facesM) = maketargetlib.scanRegistration(scan)
#name = scan.split('\\')[-1].split('/')[-1]
ob = createMesh(vertsM, facesM, "scan_mesh")
#apply rotation matrix as the base
#matrixR = RotationMatrix(90, 4, 'x')
#put scan on the left of base
matrixT = TranslationMatrix(Vector(-3, 7, 0))
ob.setMatrix(matrixT)
endEditing()
def saveTarget(path):
global saveOnlySelectedVerts,basePath, message
verticesTosave = []
vertices = getVertices()
if saveOnlySelectedVerts.val:
verticesTosave = getSelectedVertices()
else:
verticesTosave = xrange(len(vertices))
if os.path.splitext(path)[1] == ".rot":
maketargetlib.saveRotTargets(vertices, path, basePath,getSelectedVertices())
else:
maketargetlib.saveTraslTarget(vertices, path, basePath, verticesTosave)
message = "Saved in %s"%(path)
redrawAll()
def seekGroup():
vertSelect = getSelectedVertices()
vertices = getVertices()
vertGroups = getVertGroups()
maketargetlib.seekGroupName(vertices, vertSelect, vertGroups)
def saveGroups(path):
vertGroups = getVertGroups().keys()
vertGroups.sort()
maketargetlib.saveGroups(vertGroups, path, "joint")
def reset():
global basePath
startEditing()
vertices = getVertices()
maketargetlib.resetMesh(vertices, basePath)
updateVertices(vertices)
endEditing()
def regulariseMesh():
startEditing()
vertices = getVertices()
regularise.projectTarget(vertices)
updateVertices(vertices)
endEditing()
def symm(rightMirror, n=0):
global pairsPath, centersPath
startEditing()
vertices = getVertices(n)
maketargetlib.symmetrise(vertices, pairsPath, centersPath, rightMirror)
updateVertices(vertices)
endEditing()
def scaleRotTarget(path):
global morphFactor,basePath
maketargetlib.saveScaledRotTarget(path,morphFactor.val)
def processingTargetsSimple(path,mFactor):
"""
Load and then save all targets in a dir
"""
#reset()
targetDir = os.path.dirname(path)
targetsList = os.listdir(targetDir)
for targetName in targetsList:
blendFile = os.path.join(targetDir,targetName+".blend")
targetPath = os.path.join(targetDir,targetName)
if os.path.isfile(targetPath):
print "Processing %s"%(targetName)
loadTarget(targetPath)
applyTarget(mFactor)
#it should do something here
#saveTarget(targetPath)
Blender.Save(blendFile)
applyTarget(-mFactor)
#reset()
def processingTargetsSimple2(path,mFactor):
"""
Load and then save all targets in a dir
"""
#reset()
targetDir = os.path.dirname(path)
targetsList = os.listdir(targetDir)
targetToSubtract = "C:/Users/124578/Documents/mhsrc/data/targets/macrodetails/neutral-female-old.target"
for targetName in targetsList:
blendFile = os.path.join(targetDir,targetName+".blend")
targetPath = os.path.join(targetDir,targetName)
if os.path.isfile(targetPath):
print "Processing %s"%(targetName)
loadTarget(targetPath)
applyTarget(mFactor)
loadTarget(targetToSubtract)
applyTarget(-1)
#it should do something here
saveTarget(targetPath)
#Blender.Save(blendFile)
#applyTarget(-mFactor)
reset()
def processingTargetsRender(path,mFactor):
"""
This function is used to render all targets in a dir
"""
targetDir = os.path.dirname(path)
targetsList = os.listdir(targetDir)
for targetName in targetsList:
targetPath = os.path.join(targetDir,targetName)
if os.path.isfile(targetPath):
loadTarget(targetPath)
applyTarget(mFactor)
redrawAll()
imageName = os.path.splitext(targetName)[0] + ".tga"
render("//myRenderdir/", imageName)
applyTarget(-mFactor)
redrawAll()
def processingTargetsSymm(path,mFactor):
"""
This function is used to save the symmetric targets
"""
targetDir = os.path.dirname(path)
targetsList = os.listdir(targetDir)
for targetName in targetsList:
targetPath = os.path.join(targetDir,targetName)
targetNameNoExt = os.path.splitext(targetName)[0]
targetPathSym = os.path.join(targetDir,targetNameNoExt+"-symm.target")
if os.path.isfile(targetPath):
print "Processing %s"%(targetName)
loadTarget(targetPath)
applyTarget(mFactor)
symm(1,0)
#applyTarget(-mFactor)
saveTarget(targetPath)
reset()
def processingTargetsSaveSel(path):
"""
This function is used to save the symmetric targets
"""
global saveOnlySelectedVerts
saveOnlySelectedVerts.val = 1
targetDir = os.path.dirname(path)
targetsList = os.listdir(targetDir)
for targetName in targetsList:
targetPath = os.path.join(targetDir,targetName)
targetNameNoExt = os.path.splitext(targetName)[0]
targetPathSym = os.path.join(targetDir,targetNameNoExt+"-symm.target")
if os.path.isfile(targetPath):
print "Processing %s"%(targetName)
loadTarget(targetPath)
applyTarget(1)
saveTarget(targetPath)
reset()
def loadVerticesFromFolder(path):
"""
-
"""
#reset()
targetDir = os.path.dirname(path)
targetsList = os.listdir(targetDir)
for targetName in targetsList:
blendFile = os.path.join(targetDir,targetName+".blend")
targetPath = os.path.join(targetDir,targetName)
if os.path.isfile(targetPath):
print "Processing %s"%(targetName)
loadSelVerts(targetPath)
def processingTargets(path, processingType=3):
global morphFactor
startEditing()
if processingType == 1:
processingTargetsRender(path,morphFactor.val)
if processingType == 2:
processingTargetsSymm(path,morphFactor.val)
if processingType == 3:
processingTargetsSimple(path,morphFactor.val)
endEditing()
def adapt(path):
global fitVert2
mainDir = os.path.dirname(path)
path = os.path.join(mainDir,fitVert2.val)
startEditing()
base = getVertices(name="Base")
verticesToAdapt = maketargetlib.loadVertsIndex(path)
#print verticesToAdapt
scan = getVertices(name="scan_mesh")
maketargetlib.adaptMesh(base, | |
data without head status code
and headers
:type _return_http_data_only: bool, optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:type _request_auth: dict, optional
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: None
"""
local_var_params = locals()
all_params = [
'id',
'update_file_permissions_vm'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout',
'_request_auth'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method report_folders_update_permissions" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'id' is set
if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501
local_var_params['id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `id` when calling `report_folders_update_permissions`") # noqa: E501
if self.api_client.client_side_validation and 'id' in local_var_params and not re.search(r'^[A-Fa-f0-9]{24}$', local_var_params['id']): # noqa: E501
raise ApiValueError("Invalid value for parameter `id` when calling `report_folders_update_permissions`, must conform to the pattern `/^[A-Fa-f0-9]{24}$/`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'update_file_permissions_vm' in local_var_params:
body_params = local_var_params['update_file_permissions_vm']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'text/json', 'application/*+json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey', 'JWT'] # noqa: E501
response_types_map = {}
return self.api_client.call_api(
'/api/rp/v1/Reports/{id}/permissions', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_types_map=response_types_map,
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats,
_request_auth=local_var_params.get('_request_auth'))
def report_folders_update_tags(self, id, **kwargs): # noqa: E501
"""Update tags # noqa: E501
User with a Update Tags permission can access this method. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.report_folders_update_tags(id, async_req=True)
>>> result = thread.get()
:param id: (required)
:type id: str
:param folder_tags_update_vm:
:type folder_tags_update_vm: FolderTagsUpdateVM
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: FileVM
"""
kwargs['_return_http_data_only'] = True
return self.report_folders_update_tags_with_http_info(id, **kwargs) # noqa: E501
def report_folders_update_tags_with_http_info(self, id, **kwargs): # noqa: E501
"""Update tags # noqa: E501
User with a Update Tags permission can access this method. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.report_folders_update_tags_with_http_info(id, async_req=True)
>>> result = thread.get()
:param id: (required)
:type id: str
:param folder_tags_update_vm:
:type folder_tags_update_vm: FolderTagsUpdateVM
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _return_http_data_only: response data without head status code
and headers
:type _return_http_data_only: bool, optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:type _request_auth: dict, optional
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: tuple(FileVM, status_code(int), headers(HTTPHeaderDict))
"""
local_var_params = locals()
all_params = [
'id',
'folder_tags_update_vm'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout',
'_request_auth'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method report_folders_update_tags" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'id' is set
if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501
local_var_params['id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `id` when calling `report_folders_update_tags`") # noqa: E501
if self.api_client.client_side_validation and 'id' in local_var_params and not re.search(r'^[A-Fa-f0-9]{24}$', local_var_params['id']): # noqa: E501
raise ApiValueError("Invalid value for parameter `id` when calling `report_folders_update_tags`, must conform to the pattern `/^[A-Fa-f0-9]{24}$/`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'folder_tags_update_vm' in local_var_params:
body_params = local_var_params['folder_tags_update_vm']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'text/json', 'application/*+json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey', 'JWT'] # noqa: E501
response_types_map = {
200: "FileVM",
400: "ProblemDetails",
403: "ProblemDetails",
402: "ProblemDetails",
404: "ProblemDetails",
}
return self.api_client.call_api(
'/api/rp/v1/Reports/Folder/{id}/UpdateTags', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_types_map=response_types_map,
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats,
_request_auth=local_var_params.get('_request_auth'))
def reports_copy_file(self, id, folder_id, **kwargs): # noqa: E501
"""Copy file to a specified folder # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.reports_copy_file(id, folder_id, async_req=True)
>>> result = thread.get()
:param id: file id (required)
:type id: str
:param folder_id: folder id (required)
:type folder_id: str
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: ReportVM
"""
kwargs['_return_http_data_only'] = True
return self.reports_copy_file_with_http_info(id, folder_id, **kwargs) # noqa: E501
def reports_copy_file_with_http_info(self, id, folder_id, **kwargs): # noqa: E501
"""Copy file to a specified folder # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.reports_copy_file_with_http_info(id, folder_id, async_req=True)
>>> result = thread.get()
:param id: file id (required)
:type id: str
:param folder_id: folder id (required)
:type folder_id: str
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _return_http_data_only: response data without head status code
and headers
:type _return_http_data_only: bool, optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:type _request_auth: dict, optional
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: tuple(ReportVM, status_code(int), headers(HTTPHeaderDict))
"""
local_var_params = locals()
all_params = [
'id',
'folder_id'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout',
'_request_auth'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method reports_copy_file" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'id' is set
if self.api_client.client_side_validation | |
<reponame>sebastian-software/jasy<gh_stars>1-10
#
# Jasy - Web Tooling Framework
# Copyright 2013-2014 <NAME>
#
import re
import json
import jasy.style.tokenize.Tokenizer as Tokenizer
import jasy.style.parse.Node as Node
import jasy.style.Util as Util
import jasy.core.Console as Console
ascii_encoder = json.JSONEncoder(ensure_ascii=True)
RE_SELECTOR_SPLIT = re.compile(r"\s*,\s*")
def parseExpression(source, fileId=None, line=1):
# Convert source into expression statement to be friendly to the Tokenizer
if not source.endswith(";"):
source = source + ";"
tokenizer = Tokenizer.Tokenizer(source, fileId, line)
staticContext = StaticContext()
try:
return Expression(tokenizer, staticContext)
except Tokenizer.TokenizerError as ex:
raise ParseError("Unable to parse file: %s" % ex.message, tokenizer)
def parse(source, fileId=None, line=1):
tokenizer = Tokenizer.Tokenizer(source, fileId, line)
staticContext = StaticContext()
try:
node = Sheet(tokenizer, staticContext)
except Tokenizer.TokenizerError as ex:
raise ParseError("Unable to parse file: %s" % ex.message, tokenizer)
# store fileId on top-level node
node.fileId = tokenizer.fileId
# add missing comments e.g. empty file with only a comment etc.
# if there is something non-attached by an inner node it is attached to
# the top level node, which is not correct, but might be better than
# just ignoring the comment after all.
if len(node) > 0:
addComments(node[-1], None, tokenizer.getComments())
else:
addComments(node, None, tokenizer.getComments())
if not tokenizer.done():
raise ParseError("Unexpected end of file", tokenizer)
return node
class ParseError(Exception):
def __init__(self, message, tokenizer):
self.message = "Parse Error: %s" % message
self.fileId = tokenizer.fileId
self.line = tokenizer.line
Exception.__init__(self, self.message)
def __str__(self):
return "%s in %s at %s" % (self.message, self.fileId, self.line)
# Used as a status container during tree-building for every def body and the global body
class StaticContext(object):
def __init__(self):
self.blockId = 0
self.statementStack = []
def Sheet(tokenizer, staticContext):
"""Parses the toplevel and rule bodies."""
node = Statements(tokenizer, staticContext)
# change type from "block" to "sheet" for style root
node.type = "sheet"
return node
def Statements(tokenizer, staticContext):
"""Parses a list of Statements."""
node = Node.Node(tokenizer, "block")
staticContext.blockId += 1
staticContext.statementStack.append(node)
prevNode = None
while not tokenizer.done() and tokenizer.peek(True) != "right_curly":
comments = tokenizer.getComments()
childNode = Statement(tokenizer, staticContext)
# Ignore semicolons in AST
if childNode.type != "semicolon":
node.append(childNode)
prevNode = childNode
staticContext.statementStack.pop()
return node
def Block(tokenizer, staticContext):
tokenizer.mustMatch("left_curly")
node = Statements(tokenizer, staticContext)
tokenizer.mustMatch("right_curly")
return node
def Statement(tokenizer, staticContext):
"""Parses a Statement."""
tokenType = tokenizer.get(True)
tokenValue = getattr(tokenizer.token, "value", "")
if tokenType == "left_curly":
node = Statements(tokenizer, staticContext)
tokenizer.mustMatch("right_curly")
return node
elif tokenType == "command":
if tokenValue == "if" or tokenValue == "elif":
node = Node.Node(tokenizer, "if")
node.append(Expression(tokenizer, staticContext), "condition")
staticContext.statementStack.append(node)
thenPart = Statement(tokenizer, staticContext)
thenPart.noscope = True
node.append(thenPart, "thenPart")
if tokenizer.match("command"):
elseTokenValue = tokenizer.token.value
if elseTokenValue == "elif":
# Process like an "if" and append as elsePart
tokenizer.unget()
elsePart = Statement(tokenizer, staticContext)
elsePart.noscope = True
node.append(elsePart, "elsePart")
if elseTokenValue == "else":
comments = tokenizer.getComments()
elsePart = Statement(tokenizer, staticContext)
elsePart.noscope = True
addComments(elsePart, node, comments)
node.append(elsePart, "elsePart")
staticContext.statementStack.pop()
return node
elif tokenValue == "content":
node = Node.Node(tokenizer, "content")
return node
elif tokenValue == "include":
node = Node.Node(tokenizer, "include")
node.append(Expression(tokenizer, staticContext))
return node
elif tokenValue in ("require", "load", "break", "asset"):
node = Node.Node(tokenizer, "meta")
node.name = tokenValue
node.append(Expression(tokenizer, staticContext))
return node
elif tokenValue == "font-face":
return FontFace(tokenizer, staticContext)
elif tokenValue == "media":
return Media(tokenizer, staticContext)
elif tokenValue == "supports":
return Supports(tokenizer, staticContext)
elif tokenValue == "charset":
return Charset(tokenizer, staticContext)
elif tokenValue == "page":
return Page(tokenizer, staticContext)
elif tokenValue == "root":
return Root(tokenizer, staticContext)
# Special case: Support keyframe command with optional engine prefix
elif tokenValue == "keyframes" or tokenValue.endswith("-keyframes"):
return KeyFrames(tokenizer, staticContext)
else:
raise ParseError("Unknown system command: %s" % tokenValue, tokenizer)
elif tokenType == "identifier" or tokenType == "mul":
if tokenType == "identifier":
nextTokenType = tokenizer.peek()
# e.g. jasy.gradient() or gradient() - process them as expressions
# native calls in these places result in full property or multiple full properties
if nextTokenType == "left_paren":
tokenizer.unget()
node = Expression(tokenizer, staticContext)
return node
# It's hard to differentiate between selectors and properties.
# The strategy is to look for these next symbols as they define if the tokens
# until then are either a selector or property declaration.
nextRelevantTokenType = tokenizer.find(("semicolon", "left_curly", "right_curly"))
# e.g. background: xxx;
if nextRelevantTokenType == "right_curly" or nextRelevantTokenType == "semicolon":
node = Property(tokenizer, staticContext)
return node
# e.g. h1, #dad {...
elif nextRelevantTokenType == "left_curly":
node = Selector(tokenizer, staticContext)
return node
else:
raise ParseError("Warning: Unhandled: %s in Statement()" % nextTokenType, tokenizer)
# Declaration / Assignment
elif tokenType == "variable":
node = Variable(tokenizer, staticContext)
return node
# Vendor prefixed property
elif tokenType == "minus":
node = Property(tokenizer, staticContext)
return node
# Generated content or pseudo selector
elif tokenType == "colon":
nextTokenType = tokenizer.peek()
# e.g. ::after, ...
if nextTokenType == "colon":
node = Selector(tokenizer, staticContext)
return node
# e.g. :last-child, ...
elif nextTokenType == "identifier":
node = Selector(tokenizer, staticContext)
return node
else:
raise ParseError("Warning: Unhandled: %s in Statement()" % nextTokenType, tokenizer)
# Class selectors e.g. .message {...
elif tokenType == "dot":
nextTokenType = tokenizer.peek()
# The ampersand might be used to inject the current path inside the new selector
# e.g. header { &.-fullscreen {} } => .header-fullscreen{}
if nextTokenType == "identifier" or nextTokenType == "ampersand":
node = Selector(tokenizer, staticContext)
return node
else:
raise ParseError("Warning: Unhandled: %s in Statement()" % nextTokenType, tokenizer)
# Attribute selectors e.g. [hidden] {...
elif tokenType == "left_bracket":
nextTokenType = tokenizer.peek()
if nextTokenType == "identifier":
node = Selector(tokenizer, staticContext)
return node
else:
raise ParseError("Warning: Unhandled: %s in Statement()" % nextTokenType, tokenizer)
# Class selectors e.g. &.selected, &::after {...
elif tokenType == "ampersand":
nextTokenType = tokenizer.peek()
if nextTokenType in ("identifier", "colon", "left_curly", "left_bracket", "minus", "dot", "plus", "comma"):
node = Selector(tokenizer, staticContext)
return node
else:
raise ParseError("Warning: Unhandled: %s in Statement()" % nextTokenType, tokenizer)
# Child selectors e.g. > li {...
elif tokenType == "gt":
nextTokenType = tokenizer.peek()
if nextTokenType in ("identifier", "colon", "left_curly", "left_bracket", "minus", "dot", "mul"):
node = Selector(tokenizer, staticContext)
return node
else:
raise ParseError("Warning: Unhandled: %s in Statement()" % nextTokenType, tokenizer)
elif tokenType == "semicolon":
node = Node.Node(tokenizer, "semicolon")
return node
else:
raise ParseError("Warning: Unsupported token in Statement(): %s" % tokenType, tokenizer)
def Property(tokenizer, staticContext):
"""
Parses all CSS properties e.g.
- background: red
- font: 12px bold Arial;
"""
node = Node.Node(tokenizer, "property")
node.name = ""
# Start from the beginning to support mixed identifiers/variables easily
tokenizer.unget()
while tokenizer.match("variable") or tokenizer.match("identifier"):
token = tokenizer.token
if token.type == "variable":
node.name += "${%s}" % token.value
if hasattr(node, "dynamic"):
node.dynamic.add(token.value)
else:
node.dynamic = set([token.value])
else:
node.name += token.value
if not tokenizer.mustMatch("colon"):
raise ParseError("Invalid property definition", tokenizer)
# Add all values until we find a semicolon or right curly
while tokenizer.peek() not in ("semicolon", "right_curly"):
childNode = ValueExpression(tokenizer, staticContext)
node.append(childNode)
return node
def KeyFrames(tokenizer, staticContext):
"""
Supports e.g.:
@keyframes fade{
from, 10%{
background-color: #000000;
}
100%{
background-color: #FFFFFF;
}
}
"""
node = Node.Node(tokenizer, "keyframes")
node.vendor = Util.extractVendor(tokenizer.token.value)
# Use param as name on keyframes
tokenizer.get()
node.name = tokenizer.token.value
tokenizer.mustMatch("left_curly")
while tokenizer.get() != "right_curly":
# Parse frame as block
frameNode = Node.Node(tokenizer, "frame")
token = tokenizer.token
frameNode.value = "%s%s" % (token.value, getattr(token, "unit", ""))
node.append(frameNode)
# Process comma separated values for
while True:
if tokenizer.peek() != "comma":
break
else:
tokenizer.mustMatch("comma")
# Next one is our next value
tokenizer.get()
token = tokenizer.token
frameNode.value += ",%s%s" % (token.value, getattr(token, "unit", ""))
# Next process content of selector
blockNode = Block(tokenizer, staticContext)
frameNode.append(blockNode, "rules")
return node
def FontFace(tokenizer, staticContext):
# Like a selector but store as a different type
node = node = Node.Node(tokenizer, "fontface")
childNode = Block(tokenizer, staticContext)
node.append(childNode, "rules")
return node
def Supports(tokenizer, staticContext):
node = Node.Node(tokenizer, "supports")
tokenType = tokenizer.get()
test = ""
requiresSpace = False
while tokenType != "left_curly":
token = tokenizer.token
if tokenType == "identifier":
if requiresSpace :
test += " "
test += token.value
requiresSpace = True
elif tokenType == "colon":
test += ":"
requiresSpace = False
elif tokenType == "left_paren":
if requiresSpace:
test += " "
test += "("
requiresSpace = False
elif tokenType == "right_paren":
test += ")"
requiresSpace = True
elif tokenType == "string":
if requiresSpace:
test += " "
test += ascii_encoder.encode(token.value)
requiresSpace = True
elif tokenType == "number":
if requiresSpace:
test += " "
test += "%s%s" | |
<reponame>c64cryptoboy/ChiptuneSAK<filename>chiptunesak/emulator_6502.py
# 6502 instruction-level emulation
#
# This module emulates 6502 machine language program execution at an instruction-level
# of granularity (not a cycle-level).
#
# runcpu() can be called in a while loop. (Non-error) Exit conditions:
# - BRK
# - RTI or RTS if exit_on_empty_stack is True and stack is empty or has already wrapped
#
# Code references used during development:
# 1) C code: SIDDump: https://csdb.dk/release/?id=152422
# This started as a direct python adaptation of SIDDump. At this time, the original
# C code is still included in this file as reference. It made heavy use of macros
# (something python doesn't have) for register/value/address polymorphism.
# 2) python code: py65: https://github.com/eteran/pretendo/blob/master/doc/cpu/6502.txt
# If I had just imported this library, I would have been done. But then I wouldn't have
# learned nearly as much while getting bugs out of this emulator.
# 3) python code: The Pretendo NES emulator:
# Nice docs: https://github.com/eteran/pretendo/blob/master/doc/cpu/6502.txt
# 4) python code: pyc64, a C64 simulator in python, using py65
# https://github.com/irmen/pyc64
# TODOs:
# - throw an exception if the break flag ever appears on flags
from chiptunesak.errors import ChiptuneSAKNotImplemented, ChiptuneSAKValueError
from chiptunesak.byte_util import hexdump
# 6502 vector locations
NMI = 0xfffa # on C64, vector points to NMI routine at $FE43/65091
RESET = 0xfffc # on C64, vector points to power-on routine $FCE2/64738
IRQ = 0xfffe # on C64, vector points to IRQ handler routine at $FF48/65352
FN = 0b10000000 # Negative
FV = 0b01000000 # oVerflow
FU = 0b00100000 # Unused
FB = 0b00010000 # Break
FD = 0b00001000 # Decimal
FI = 0b00000100 # Interrupt
FZ = 0b00000010 # Zero
FC = 0b00000001 # Carry
# base cycle values for instructions (and pseudo-ops) 0 through 255:
cpucycles_table = [
7, 6, 0, 8, 3, 3, 5, 5, 3, 2, 2, 2, 4, 4, 6, 6,
2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7,
6, 6, 0, 8, 3, 3, 5, 5, 4, 2, 2, 2, 4, 4, 6, 6,
2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7,
6, 6, 0, 8, 3, 3, 5, 5, 3, 2, 2, 2, 3, 4, 6, 6,
2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7,
6, 6, 0, 8, 3, 3, 5, 5, 4, 2, 2, 2, 5, 4, 6, 6,
2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7,
2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4,
2, 6, 0, 6, 4, 4, 4, 4, 2, 5, 2, 5, 5, 5, 5, 5,
2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4,
2, 5, 0, 5, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 4, 4,
2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6,
2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7,
2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6,
2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7]
# A cutoff point for determining if an RTI or RTS should exit emulation when the
# stack has wrapped (i.e. 0 <= SP < STACK_WRAP_AREA).
STACK_WRAP_AREA = 0x0f
MEM_USAGE_READ = 0b00000001 # noqa:E221
MEM_USAGE_WRITE = 0b00000010
class Cpu6502Emulator:
def __init__(self):
self.memory = 0x10000 * [0x00] # 64K memory as integers
self.mem_usage = 0x10000 * [0x00] # monitor a program's memory r/w usage
self.a = 0 # accumulator (byte)
self.x = 0 # x register (byte)
self.y = 0 # y register (byte)
self.flags = FU # processor flags (byte)
self.sp = 0 # stack pointer (byte)
self.pc = 0 # program counter (16-bit)
self.cpucycles = 0 # count of cpu cycles processed
self.last_instruction = None # last instruction processed
self.exit_on_empty_stack = False # True = RTI/RTS exists on empty stack
self.debug = False
self.invocationCount = -1
def get_mem(self, loc):
return self.memory[loc]
def set_mem(self, loc, val):
if not (0 <= val <= 255):
exit("Error: POKE(%d),%d out of range" % (loc, val))
self.memory[loc] = val
# define LO() (MEM(pc))
def lo(self):
return self.get_mem(self.pc)
# define HI() (MEM(pc+1))
def hi(self):
return self.get_mem((self.pc + 1) & 0xffff)
# define FETCH() (MEM(pc++))
def fetch(self):
self.pc &= 0xffff
val = self.get_mem(self.pc)
self.pc = (self.pc + 1) & 0xffff
return val
# define PUSH(data) (MEM(0x100 + (sp--)) = (data))
def push(self, data):
self.set_mem(0x100 + self.sp, data)
self.sp -= 1
self.sp &= 0xff # this will wrap -1 to 255, as it should
# define POP() (MEM(0x100 + (++sp)))
def pop(self):
self.sp += 1
# If poping from an empty stack (sp == $FF), this must wrap to 0
# http://forum.6502.org/viewtopic.php?f=8&t=1446
self.sp &= 0xff
result = self.get_mem(0x100 + self.sp)
return result
# define IMMEDIATE() (LO())
def immediate(self):
return self.lo()
# define ABSOLUTE() (LO() | (HI() << 8))
def absolute(self):
return self.lo() | (self.hi() << 8)
# define ABSOLUTEX() (((LO() | (HI() << 8)) + x) & 0xffff)
def absolute_x(self):
return (self.absolute() + self.x) & 0xffff
# define ABSOLUTEY() (((LO() | (HI() << 8)) + y) & 0xffff)
def absolute_y(self):
return (self.absolute() + self.y) & 0xffff
# define ZEROPAGE() (LO() & 0xff)
def zeropage(self):
return self.lo() & 0xff
# define ZEROPAGEX() ((LO() + x) & 0xff)
def zeropage_x(self):
return (self.lo() + self.x) & 0xff
# define ZEROPAGEY() ((LO() + y) & 0xff)
def zeropage_y(self):
return (self.lo() + self.y) & 0xff
# define INDIRECTX() (MEM((LO() + x) & 0xff) | (MEM((LO() + x + 1) & 0xff) << 8))
def indirect_x(self):
return self.get_mem((self.lo() + self.x) & 0xff) | (self.get_mem((self.lo() + self.x + 1) & 0xff) << 8)
# define INDIRECTY() (((MEM(LO()) | (MEM((LO() + 1) & 0xff) << 8)) + y) & 0xffff)
def indirect_y(self):
zp_vec = self.get_mem(self.pc)
return ((self.get_mem(zp_vec) | (self.get_mem((zp_vec + 1) & 0xff) << 8)) + self.y) & 0xffff
# define INDIRECTZP() (((MEM(LO()) | (MEM((LO() + 1) & 0xff) << 8)) + 0) & 0xffff)
def indirect_zp(self):
zp_vec = self.get_mem(self.pc)
return ((self.get_mem(zp_vec) | (self.get_mem((zp_vec + 1) & 0xff) << 8)) + 0) & 0xffff
# define EVALPAGECROSSING(baseaddr, realaddr) ((((baseaddr) ^ (realaddr)) & 0xff00) ? 1 : 0)
def eval_page_crossing(self, baseaddr, realaddr):
if (baseaddr ^ realaddr) & 0xff00 != 0:
return 1
return 0
# define EVALPAGECROSSING_ABSOLUTEX() (EVALPAGECROSSING(ABSOLUTE(), ABSOLUTEX()))
def eval_page_crossing_absolute_x(self):
return self.eval_page_crossing(self.absolute(), self.absolute_x())
# define EVALPAGECROSSING_ABSOLUTEY() (EVALPAGECROSSING(ABSOLUTE(), ABSOLUTEY()))
def eval_page_crossing_absolute_y(self):
return self.eval_page_crossing(self.absolute(), self.absolute_y())
# define EVALPAGECROSSING_INDIRECTY() (EVALPAGECROSSING(INDIRECTZP(), INDIRECTY()))
def eval_page_crossing_indirect_y(self):
return self.eval_page_crossing(self.indirect_zp(), self.indirect_y())
# #define BRANCH() \
# { \
# ++cpucycles; \
# temp = FETCH(); \
# if (temp < 0x80) \
# { \
# cpucycles += EVALPAGECROSSING(pc, pc + temp); \
# SETPC(pc + temp); \
# } \
# else \
# { \
# cpucycles += EVALPAGECROSSING(pc, pc + temp - 0x100); \
# SETPC(pc + temp - 0x100); \
# } \
# }
def branch(self):
self.cpucycles += 1 # taking the branch adds a cycle
temp = self.fetch()
if temp < 0x80: # if branching forward
self.cpucycles += self.eval_page_crossing(self.pc, self.pc + temp)
self.pc = self.pc + temp
else:
self.cpucycles += self.eval_page_crossing(self.pc, self.pc + temp - 0x100)
self.pc = self.pc + temp - 0x100
# #define SETFLAGS(data) \
# { \
# if (!(data)) \
# flags = (flags & ~FN) | FZ; \
# else \
# flags = (flags & ~(FN|FZ)) | \
# ((data) & FN); \
# }
# a_byte from a register value (i.e., a,x,y)
def set_flags(self, a_byte):
assert 0 <= a_byte <= 255, "Error: can't set flags using non-byte value"
if a_byte == 0:
self.flags = (self.flags & ~FN & 0xff) | FZ
else:
# turn off flag's N and Z, then add in a_byte's N
self.flags = (self.flags & ~(FN | FZ) & 0xff) | (a_byte & FN)
self.flags |= FU # might not need this here, but | |
<filename>data_dl.py<gh_stars>0
#!/usr/bin/env python3
"""
Open source data downloader
Created: 10/15/2020 <NAME> (<EMAIL>)
"""
__doc__ = """
This python library takes in a list of subjects, the data source,
and the data type you want, and downloads them. It then can delete them.
"""
import pkg_resources as pkgrf
import argparse
import configparser
import os
import re
import sys
import threading
from cryptography.fernet import Fernet
from datetime import datetime
from functools import partial
from getpass import getpass
from glob import glob
from multiprocessing.dummy import Pool
from pandas import read_csv
from subprocess import call, check_call
class RepeatTimer(threading.Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
def stop(self):
self.cancel()
HOME = os.path.expanduser("~")
NDA_CREDENTIALS = os.path.join(HOME, ".data_dl", "config.ini")
HERE = os.path.dirname(os.path.abspath(sys.argv[0]))
NDA_AWS_TOKEN_MAKER = pkgrf.resource_filename('data_dl', 'data/nda_aws_token_maker.py')
def download_abcd(subjects,where,log,data,cores=1):
"""
subjects: subject list, strings in a list
where: where should we put your data?
log: where should I keep the log? we use this to show what downloaded, and use it to delete things
cores: how many cores?
"""
date_stamp = "{:%Y:%m:%d %H:%M}".format(datetime.now())
print('Data downloader called at %s with:' % date_stamp)
make_nda_token(NDA_CREDENTIALS)
# start an hourly thread ( 60 * 60 = 3600 seconds) to update the NDA download token
t = RepeatTimer(3600, make_nda_token, [NDA_CREDENTIALS])
t.start()
s3_file = pkgrf.resource_filename('data_dl', 'data/abcd_datastructure_manifest.txt')
if os.path.exists(s3_file) == False:
print ('downloading a big file (1.7GB) you need, hang tight')
os.system('wget https://www.dropbox.com/s/nzc87lnowohud0m/datastructure_manifest.txt?dl=0 -O %s'%(s3_file))
if data == 'dwi': basenames_file = pkgrf.resource_filename('data_dl', 'data/abcd_data_subsets_dwi.txt')
if data == 'all': basenames_file = pkgrf.resource_filename('data_dl', 'data/abcd_data_subsets.txt')
if data == 'anat': basenames_file = pkgrf.resource_filename('data_dl', 'data/abcd_data_subsets_anat.txt')
if data == 'jsons': basenames_file = pkgrf.resource_filename('data_dl', 'data/abcd_data_subsets.txt')
manifest_df = read_csv(s3_file, sep='\t',low_memory=False)
subject_list = get_subject_list(manifest_df, subjects)
print('\tData Subsets:\t%s' % basenames_file)
manifest_names = generate_manifest_list(basenames_file, subject_list)
print('\nReading in S3 links...')
s3_links_arr = manifest_df[manifest_df['manifest_name'].isin(manifest_names)]['associated_file'].values
if data == 'jsons':
bad = download_s3_jsons(s3_links_arr, where, log, cores)
else:
bad = download_s3_files(s3_links_arr, where, log, cores)
print('\nProblematic commands:')
for baddy in bad:
print(baddy)
t.stop()
def delete(where,log):
df = read_csv('%s/successful_downloads.txt'%(log),skiprows=1,header=None)
for f in df.iterrows():
f = f[1][0]
f = '/'.join(f.split('/')[4:])
f = '/%s/%s'%(where,f)
os.system('rm -f %s'%(f))
os.system('rm -f /%s/successful_downloads.txt'%(log))
def delete_scary(where):
os.system('rm -f -r %s'%(where))
os.system('rm /%s/successful_downloads.txt'%(log))
def get_subject_list(manifest_df, subjects):
"""
If a list of subject is provided then use that, else collect all unique
subject ids from the s3 spreadsheet and use that instead
:param manifest_df: pandas dataframe created from the s3 csv
:param subjects: array of subjects
:return: subject_list
"""
if subjects!= 'all': return subjects
# Otherwise get all subjects from the S3 spreadsheet
subject_list = set()
if subjects == 'all':
print('\tSubjects:\tAll subjects')
for manifest_name in manifest_df['manifest_name'].values:
subject_id = manifest_name.split('.')[0]
subject_list.add(subject_id)
return list(subject_list)
def generate_manifest_list(basenames_file, subject_list):
"""
Take the list of subjects and list of basenames and concatenate them to
match the ${SUBJECT}.${BASENAME}.manifest.json to match the manifest name
in the s3 file.
:param args: argparse namespace containing all CLI arguments. The specific
arguments used by this function are
:return: manifest_names: list of manifest_name
"""
# if a subject list is not provided
basenames = [line.rstrip('\n') for line in open(basenames_file)]
manifest_names = []
for sub in subject_list:
for base in basenames:
manifest = sub + '.' + base + '.manifest.json'
manifest_names += [manifest]
return manifest_names
def download_s3_jsons(s3_links_arr, output_dir, log_dir, pool_size=1):
"""
"""
bad_download = []
commands = []
success_log = os.path.join(log_dir, 'successful_downloads.txt')
failed_log = os.path.join(log_dir, 'failed_downloads.txt')
only_one_needed = [
"CHANGES",
"dataset_description.json",
"README",
"task-MID_bold.json",
"task-nback_bold.json",
"task-rest_bold.json",
"task-SST_bold.json",
"Gordon2014FreeSurferSubcortical_dparc.dlabel.nii",
"HCP2016FreeSurferSubcortical_dparc.dlabel.nii",
"Markov2012FreeSurferSubcortical_dparc.dlabel.nii",
"Power2011FreeSurferSubcortical_dparc.dlabel.nii",
"Yeo2011FreeSurferSubcortical_dparc.dlabel.nii"
]
only_one_tuple = list(zip([0]*len(only_one_needed), only_one_needed))
if os.path.isfile(success_log):
with open(success_log) as f:
success_set = set(f.readlines())
else:
success_set = set()
download_set = set()
print('Creating unique download list...')
for s3_link in s3_links_arr:
if s3_link.endswith('.json'):
if s3_link[:4] != 's3:/':
s3_path = 's3:/' + s3_link
else:
s3_path = s3_link
dest = os.path.join(output_dir, '/'.join(s3_path.split('/')[4:]))
skip = False
for i, only_one_pair in enumerate(only_one_tuple):
only_one_count = only_one_pair[0]
only_one = only_one_pair[1]
if only_one in s3_path:
if only_one_count == 0:
only_one_tuple[i] = (1, only_one)
else:
skip = True
break
if not skip and s3_path not in success_set:
# Check if the filename already in the success log
dest = os.path.join(output_dir, '/'.join(s3_path.split('/')[4:]))
if not os.path.isfile(dest):
download_set.add( (s3_path, dest) )
# make unique s3 downloads
print('Creating download commands...')
for s3_path, dest in sorted(download_set, key=lambda x: x[1]):
commands.append( ' ; '.join( [
"mkdir -p " + os.path.dirname(dest),
"aws s3 cp " + s3_path + " " + dest + " --profile NDA"
] )
)
if pool_size == 1:
print('\nDownloading files serially...')
elif pool_size > 1:
print('\nParallel downloading with %d core(s)...' % pool_size)
elif pool_size < 1:
print('\nCannot download with less than 1 core. Try changing your "-p" argument. Quitting...')
sys.exit()
pool = Pool(pool_size) # pool_size concurrent commands at a time
for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
s3_path = re.search('.+aws\ s3\ cp\ (s3://.+)\ ' + output_dir + '.+', commands[i]).group(1)
if returncode == 0:
with open(success_log, 'a+') as s:
s.write(s3_path + '\n')
else:
print( "Command failed: {}".format(commands[i]) )
bad_download.append(s3_path)
with open(failed_log, 'a+') as f:
f.write(s3_path + '\n')
bad_download.append(commands[i])
pool.close()
return bad_download
def download_s3_files(s3_links_arr, output_dir, log_dir, pool_size=1):
"""
"""
bad_download = []
commands = []
success_log = os.path.join(log_dir, 'successful_downloads.txt')
failed_log = os.path.join(log_dir, 'failed_downloads.txt')
only_one_needed = [
"CHANGES",
"dataset_description.json",
"README",
"task-MID_bold.json",
"task-nback_bold.json",
"task-rest_bold.json",
"task-SST_bold.json",
"Gordon2014FreeSurferSubcortical_dparc.dlabel.nii",
"HCP2016FreeSurferSubcortical_dparc.dlabel.nii",
"Markov2012FreeSurferSubcortical_dparc.dlabel.nii",
"Power2011FreeSurferSubcortical_dparc.dlabel.nii",
"Yeo2011FreeSurferSubcortical_dparc.dlabel.nii"
]
only_one_tuple = list(zip([0]*len(only_one_needed), only_one_needed))
if os.path.isfile(success_log):
with open(success_log) as f:
success_set = set(f.readlines())
else:
success_set = set()
download_set = set()
print('Creating unique download list...')
for s3_link in s3_links_arr:
if s3_link[:4] != 's3:/':
s3_path = 's3:/' + s3_link
else:
s3_path = s3_link
dest = os.path.join(output_dir, '/'.join(s3_path.split('/')[4:]))
skip = False
for i, only_one_pair in enumerate(only_one_tuple):
only_one_count = only_one_pair[0]
only_one = only_one_pair[1]
if only_one in s3_path:
if only_one_count == 0:
only_one_tuple[i] = (1, only_one)
else:
skip = True
break
if not skip and s3_path not in success_set:
# Check if the filename already in the success log
dest = os.path.join(output_dir, '/'.join(s3_path.split('/')[4:]))
if not os.path.isfile(dest):
download_set.add( (s3_path, dest) )
# make unique s3 downloads
print('Creating download commands...')
for s3_path, dest in sorted(download_set, key=lambda x: x[1]):
commands.append( ' ; '.join( [
"mkdir -p " + os.path.dirname(dest),
"aws s3 cp " + s3_path + " " + dest + " --profile NDA"
] )
)
if pool_size == 1:
print('\nDownloading files serially...')
elif pool_size > 1:
print('\nParallel downloading with %d core(s)...' % pool_size)
elif pool_size < 1:
print('\nCannot download with less than 1 core. Try changing your "-p" argument. Quitting...')
sys.exit()
pool = Pool(pool_size) # pool_size concurrent commands at a time
for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
s3_path = re.search('.+aws\ s3\ cp\ (s3://.+)\ ' + output_dir + '.+', commands[i]).group(1)
if returncode == 0:
with open(success_log, 'a+') as s:
s.write(s3_path + '\n')
else:
print( "Command failed: {}".format(commands[i]) )
bad_download.append(s3_path)
with open(failed_log, 'a+') as f:
f.write(s3_path + '\n')
bad_download.append(commands[i])
pool.close()
return bad_download
def make_nda_token(credentials):
"""
Create NDA token by getting credentials from config file. If no config file
exists yet, or user specified to make a new one by entering their NDA
credentials as CLI args, then create one to store NDA credentials.
:param args: argparse namespace containing all CLI arguments. The specific
arguments used by this function are --username, --password, and --config.
:return: N/A
"""
# If config file with NDA credentials exists, then get credentials from it,
# unless user entered other credentials to make a new config file
# First make sure ~/.aws directory exists
os.makedirs(os.path.join(HOME, '.aws'), exist_ok=True)
if os.path.exists(credentials):
username, password = get_nda_credentials_from(credentials)
# Otherwise get NDA credentials from user & save them in a new config file,
# overwriting the existing config file if user gave credentials as cli args
else:
# If NDA username was a CLI arg, use it; otherwise prompt user for it
username = input("\nEnter your NIMH Data Archives username: ")
# If NDA password was a CLI arg, use it; otherwise prompt user for it
password = getpass("Enter your NIMH Data Archives password: ")
make_config_file(credentials, username, password)
# Try to make NDA token
token_call_exit_code = call((
"python3",
NDA_AWS_TOKEN_MAKER,
username,
password
))
# If NDA credentials are invalid, tell user so without printing password.
# Manually catch error instead of using try-except to avoid trying to
# catch another file's exception.
if token_call_exit_code != 0:
print("Failed to create NDA token using the username and | |
<filename>finetune/nn/group_target_blocks.py
import math
import functools
import tensorflow as tf
from tensorflow_addons.text.crf import crf_log_likelihood
from scipy.optimize import linear_sum_assignment
from finetune.base_models.gpt.featurizer import attn, dropout, norm
from finetune.util.shapes import shape_list, merge_leading_dims
from finetune.optimizers.recompute_grads import recompute_grad
from finetune.errors import FinetuneError
from finetune.nn.activations import act_fns
from finetune.nn.nn_utils import norm
from finetune.nn.target_blocks import sequence_labeler
from tensorflow.python.framework import function
from finetune.nn.target_blocks import class_reweighted_grad
from finetune.base_models.bert.modeling import (
attention_layer,
dropout,
create_initializer,
layer_norm,
gelu,
)
def multi_crf_group_labeler(
hidden,
targets,
n_targets,
config,
train=False,
reuse=None,
lengths=None,
use_crf=False,
**kwargs
):
"""
Multi CRF group tagging model. Takes two sets of targets - one for normal
tagging and one for group tagging. Learns a CRF for each set of targets.
:param hidden: The output of the featurizer. [batch_size, sequence_length, embed_dim]
:param targets: The placeholder representing the NER and group targets. [batch_size, 2, sequence_length]
:param n_targets: A python int containing the number of NER classes.
:param config: A config object, containing all parameters for the featurizer.
:param train: If this flag is true, dropout and losses are added to the graph.
:param reuse: Should reuse be set within this scope.
:param lengths: The number of non-padding tokens in the input.
:param kwargs: Spare arguments.
:return: dict containing:
"logits": Un-normalized log probabilties for NER and group predictions, has
shape of [2, batch_size, sequence_length]
"losses": The negative log likelihood for the sequence targets.
"predict_params": A dictionary of params to be fed to the viterbi decode function.
"""
with tf.compat.v1.variable_scope("multi-crf-group", reuse=reuse):
if targets is not None:
targets = tf.cast(targets, dtype=tf.int32)
nx = config.n_embed
def seq_lab_internal(hidden):
flat_logits = tf.compat.v1.layers.dense(hidden, n_targets)
logits = tf.reshape(
flat_logits, tf.concat([tf.shape(input=hidden)[:2], [n_targets]], 0)
)
return logits
def group_seq_lab_internal(hidden):
flat_logits = tf.compat.v1.layers.dense(hidden, 3)
logits = tf.reshape(
flat_logits, tf.concat([tf.shape(input=hidden)[:2], [3]], 0)
)
return logits
with tf.compat.v1.variable_scope("seq_lab_attn"):
if config.low_memory_mode and train:
seq_lab_internal = recompute_grad(
seq_lab_internal, use_entire_scope=True
)
logits = seq_lab_internal(hidden)
logits = tf.cast(logits, tf.float32) # always run the crf in float32
with tf.compat.v1.variable_scope("group_seq_lab_attn"):
if config.low_memory_mode and train:
group_seq_lab_internal = recompute_grad(
group_seq_lab_internal, use_entire_scope=True
)
group_logits = group_seq_lab_internal(hidden)
group_logits = tf.cast(group_logits, tf.float32)
loss = 0.0
default_lengths = tf.shape(input=hidden)[1] * tf.ones(
tf.shape(input=hidden)[0], dtype=tf.int32
)
if lengths is None:
lengths = default_lengths
class_weights = kwargs.get("class_weights")
with tf.device("CPU:0" if train else logits.device):
if class_weights is not None and train:
class_weights = tf.reshape(class_weights, [1, 1, -1])
one_hot_class_weights = class_weights * tf.one_hot(
targets[:, 0, :], depth=n_targets
)
per_token_weights = tf.reduce_sum(
input_tensor=one_hot_class_weights, axis=-1, keepdims=True
)
logits = class_reweighted_grad(logits, per_token_weights)
transition_params = tf.cast(
tf.compat.v1.get_variable(
"Transition_matrix", shape=[n_targets, n_targets]
),
tf.float32,
)
group_transition_params = tf.cast(
tf.compat.v1.get_variable(
"Group_transition_matrix", shape=[3, 3]
),
tf.float32,
)
if targets is not None:
if use_crf:
ner_loss, _ = crf_log_likelihood(
logits,
targets[:, 0, :],
lengths,
transition_params=transition_params,
)
group_loss, _ = crf_log_likelihood(
group_logits,
targets[:, 1, :],
lengths,
transition_params=group_transition_params,
)
ner_loss = tf.reduce_mean(ner_loss * -1)
group_loss = tf.reduce_mean(group_loss * -1)
else:
weights = tf.math.divide_no_nan(
tf.sequence_mask(
lengths,
maxlen=tf.shape(input=targets)[2],
dtype=tf.float32,
),
tf.expand_dims(tf.cast(lengths, tf.float32), -1),
)
ner_loss = tf.compat.v1.losses.sparse_softmax_cross_entropy(
targets[:, 0, :], logits, weights=weights
)
ner_loss = tf.reduce_mean(ner_loss)
group_loss = tf.compat.v1.losses.sparse_softmax_cross_entropy(
targets[:, 1, :], group_logits, weights=weights
)
group_loss = tf.reduce_mean(group_loss)
scaled_ner_loss = config.seq_loss_weight * ner_loss
scaled_group_loss = config.group_loss_weight * group_loss
loss = scaled_ner_loss + scaled_group_loss
tf.compat.v1.summary.scalar("Sequence Loss", ner_loss)
tf.compat.v1.summary.scalar("Group Loss", group_loss)
tf.compat.v1.summary.scalar("Scaled Sequence Loss", scaled_ner_loss)
tf.compat.v1.summary.scalar("Scaled Group Loss", scaled_group_loss)
return {
"logits": [logits, group_logits],
"losses": loss,
"predict_params": {
"transition_matrix": transition_params,
"group_transition_matrix": group_transition_params,
"sequence_length": lengths,
},
}
def multi_logit_group_labeler (
hidden,
targets,
n_targets,
config,
train=False,
reuse=None,
lengths=None,
use_crf=False,
**kwargs
):
"""
Mult-logit CRF group tagging model. Produces a set of logits for NER tags
and group tags, then broadcasts them to create the final predictions.
:param hidden: The output of the featurizer. [batch_size, sequence_length, embed_dim]
:param targets: The placeholder representing the sequence labeling targets. [batch_size, sequence_length]
:param n_targets: A python int containing the number of total number of classes (NER Classes * 3)
:param config: A config object, containing all parameters for the featurizer.
:param train: If this flag is true, dropout and losses are added to the graph.
:param reuse: Should reuse be set within this scope.
:param lengths: The number of non-padding tokens in the input.
:param kwargs: Spare arguments.
:return: dict containing:
"logits": The un-normalised log probabilities of each class being in each location. For usable predictions,
sampling from this distribution is not sufficient and a viterbi decoding method should be used.
"losses": The negative log likelihood for the sequence targets.
"predict_params": A dictionary of params to be fed to the viterbi decode function.
"""
assert n_targets % 3 == 0, f"{n_targets} classes not divisible by 3!"
with tf.compat.v1.variable_scope("multi-logit-group", reuse=reuse):
if targets is not None:
targets = tf.cast(targets, dtype=tf.int32)
nx = config.n_embed
def seq_lab_internal(hidden):
flat_logits = tf.compat.v1.layers.dense(hidden, n_targets // 3)
logits = tf.reshape(
flat_logits, tf.concat([tf.shape(input=hidden)[:2], [n_targets // 3]], 0)
)
return logits
def group_seq_lab_internal(hidden):
# Produce 3 outputs: start group, in group, outside of group
flat_logits = tf.compat.v1.layers.dense(hidden, 3)
logits = tf.reshape(
flat_logits, tf.concat([tf.shape(input=hidden)[:2], [3]], 0)
)
return logits
with tf.compat.v1.variable_scope("seq_lab_attn"):
if config.low_memory_mode and train:
seq_lab_internal = recompute_grad(
seq_lab_internal, use_entire_scope=True
)
ner_logits = seq_lab_internal(hidden)
ner_logits = tf.cast(ner_logits, tf.float32) # always run the crf in float32
with tf.compat.v1.variable_scope("group_seq_lab_attn"):
if config.low_memory_mode and train:
group_seq_lab_internal = recompute_grad(
group_seq_lab_internal, use_entire_scope=True
)
group_logits = group_seq_lab_internal(hidden)
group_logits = tf.cast(group_logits, tf.float32)
# Broadcast probabilities to make [batch, seq_len, n_classes] matrix
# [batch, seq_len, n_classes / 3, 1] * [batch, seq_len, 1, 3] =
# [batch, seq_len, n_classes / 3, 3]
logits = tf.expand_dims(ner_logits, 3) + tf.expand_dims(group_logits, 2)
# Reshape down to [batch, seq_len, n_classes]
final_shape = tf.concat((tf.shape(hidden)[:2], [n_targets]), 0)
logits = tf.reshape(logits, final_shape)
# Note, in order for loss to work correctly the targets must be in the
# form [AA-TAG1, BB-TAG1, CC-TAG1, AA-TAG2, BB-TAG2, CC-TAG2, AA-TAG3 ...]
# where tags are grouped together and always in the same order of
# prefixes, as this is the form the logits will be produced in via broadcasting
loss = 0.0
default_lengths = tf.shape(input=hidden)[1] * tf.ones(
tf.shape(input=hidden)[0], dtype=tf.int32
)
if lengths is None:
lengths = default_lengths
class_weights = kwargs.get("class_weights")
with tf.device("CPU:0" if train else logits.device):
if class_weights is not None and train:
class_weights = tf.reshape(class_weights, [1, 1, -1])
one_hot_class_weights = class_weights * tf.one_hot(
targets, depth=n_targets
)
per_token_weights = tf.reduce_sum(
input_tensor=one_hot_class_weights, axis=-1, keepdims=True
)
logits = class_reweighted_grad(logits, per_token_weights)
transition_params = tf.cast(
tf.compat.v1.get_variable(
"Transition_matrix", shape=[n_targets, n_targets]
),
tf.float32,
)
if targets is not None:
if use_crf:
log_likelihood, _ = crf_log_likelihood(
logits,
targets,
lengths,
transition_params=transition_params,
)
loss = -log_likelihood
else:
weights = tf.math.divide_no_nan(
tf.sequence_mask(
lengths,
maxlen=tf.shape(input=targets)[1],
dtype=tf.float32,
),
tf.expand_dims(tf.cast(lengths, tf.float32), -1),
)
loss = tf.compat.v1.losses.sparse_softmax_cross_entropy(
targets, logits, weights=weights
)
return {
"logits": logits,
"losses": loss,
"predict_params": {
"transition_matrix": transition_params,
"sequence_length": lengths,
},
}
def bros_decoder(
hidden,
targets,
n_targets,
config,
train=False,
reuse=None,
lengths=None,
**kwargs
):
"""
A BROS decoder.
:param hidden: The output of the featurizer. [batch_size, sequence_length, embed_dim]
:param targets: The targets. Contains start token and next token labels. [batch_size, 2, sequence_length]
:param n_targets: A python int containing the number of classes that the model should be learning to predict over.
:param config: A config object, containing all parameters for the featurizer.
:param train: If this flag is true, dropout and losses are added to the graph.
:param reuse: Should reuse be set within this scope.
:param lengths: The number of non-padding tokens in the input.
:param kwargs: Spare arguments.
:return: dict containing:
"logits": Dictionary containing "start_token_logits" and "next_token_logits"
"losses": Combined start token and next token loss
"""
with tf.compat.v1.variable_scope("bros-decoder", reuse=reuse):
if targets is not None:
targets = tf.cast(targets, dtype=tf.int32)
nx = config.n_embed
hidden_size = config.relation_hidden_size
def get_out_logits(hidden):
flat_logits = tf.compat.v1.layers.dense(hidden, 2)
logits_shape = tf.concat([tf.shape(hidden)[:2], [2]], 0)
logits = tf.reshape(flat_logits, logits_shape)
return logits
def get_out_hidden(hidden):
flat_logits = tf.compat.v1.layers.dense(hidden, hidden_size)
logits_shape = tf.concat([tf.shape(hidden)[:2], [hidden_size]], 0)
logits = tf.reshape(flat_logits, logits_shape)
return logits
with tf.compat.v1.variable_scope("start_token_logits"):
# [batch_size, seq_len, 2]
if config.low_memory_mode and train:
get_out_logits = recompute_grad(get_out_logits, use_entire_scope=True)
start_token_logits = get_out_logits(hidden)
start_token_logits = tf.cast(start_token_logits, tf.float32)
with tf.compat.v1.variable_scope("start_token_hidden"):
if config.low_memory_mode and train:
get_out_hidden = recompute_grad(get_out_hidden, use_entire_scope=True)
# [batch_size, seq_len, hidden_size]
start_token_hidden = get_out_hidden(hidden)
start_token_hidden = tf.cast(start_token_hidden, tf.float32)
with tf.compat.v1.variable_scope("next_token_hidden"):
if config.low_memory_mode and train:
get_out_hidden = recompute_grad(get_out_hidden, use_entire_scope=True)
# [batch_size, seq_len, hidden_size]
next_token_hidden = get_out_hidden(hidden)
next_token_hidden = tf.cast(next_token_hidden, tf.float32)
# [hidden_size]
no_next_hidden = tf.cast(
tf.compat.v1.get_variable(
"no_next_hidden", shape=[hidden_size]
| |
import IPython
import bisect
import threading
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import numpy as np
from basic_sweep_ui import Ui_SweepDialog
import kid_readout.roach.baseband
import kid_readout.utils.sweeps
import kid_readout.roach.hardware_tools
from kid_readout.measurement.io.data_block import SweepData
from kid_readout.measurement.io import data_file
import logging
logger = logging.getLogger('kid_readout')
logger.addHandler(logging.StreamHandler())
#from kid_readout.utils.PeakFind01 import peakdetect
import socket
if socket.gethostname() == 'detectors':
at_a_time = 16
else:
at_a_time = 32
class SweepDialog(QDialog,Ui_SweepDialog):
def __init__(self, qApp, parent=None):
super(SweepDialog, self).__init__(parent)
self.__app = qApp
self.setupUi(self)
self.dpi = 72
self.fig = Figure((9.1, 5.2), dpi=self.dpi)
# self.fig = Figure(dpi=self.dpi)
self.plot_layout = QVBoxLayout(self.plot_group_box)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.plot_group_box)
self.canvas.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
self.plot_layout.addWidget(self.canvas)
self.axes = self.fig.add_subplot(211)
self.axes.set_xlabel('MHz')
self.axes.set_ylabel('dB')
self.axes.grid(True)
self.axes2 = self.fig.add_subplot(212)
# Use matplotlib event handler
#self.canvas.mpl_connect('pick_event', self.onclick_plot)
self.canvas.mpl_connect('button_release_event', self.onclick_plot)
self.mpl_toolbar = NavigationToolbar(self.canvas,self.plot_group_box) #self.adc_plot_box)
self.plot_layout.addWidget(self.mpl_toolbar)
self.cal_freq=np.arange(256)
self.cal_mag = np.ones((256,))
self.cal_phase = np.zeros((256,))
try:
cdata = np.load('lbcal1.npz')
self.cal_freq = cdata['freq']
self.cal_mag = cdata['mag']
self.cal_phase = cdata['phase']
except Exception, e:
print "cal data could not be loaded",e
self.line = None
self.phline = None
self.line2 = None
self.phline2 = None
self.peakline = None
self.psd_text = None
self.selection_line = None
self.sweep_data = None
self.fine_sweep_data = None
self.selected_sweep = 'coarse'
self.selected_idx = 0
self.progress_value = 0
self.total_subsweeps = 1
self.current_subsweep = 0
self.line_dac_gain.setText("-2.0")
self.ri = kid_readout.roach.baseband.RoachBaseband(adc_valon=kid_readout.roach.hardware_tools.roach1_valon)
#self.ri.set_adc_attenuator(31)
self.ri.set_dac_attenuator(36)
self.abort_requested = False
self.sweep_thread = None
self.reslist = np.array([92.94,
96.31,
101.546,
117.195,
121.35,
130.585,
133.436,
148.238,
148.696,
148.867,
149.202,
159.572,
167.97,
172.93,
176.645,
178.764])
self.setup_freq_table()
self.push_abort.clicked.connect(self.onclick_abort)
self.push_start_sweep.clicked.connect(self.onclick_start_sweep)
self.push_start_fine_sweep.clicked.connect(self.onclick_start_fine_sweep)
self.push_save.clicked.connect(self.onclick_save)
self.line_npoints.textEdited.connect(self.recalc_spacing)
self.line_span_hz.textEdited.connect(self.recalc_spacing)
self.tableview_freqs.itemChanged.connect(self.freq_table_item_changed)
self.spin_subsweeps.valueChanged.connect(self.onspin_subsweeps_changed)
self.push_add_resonator.clicked.connect(self.onclick_add_resonator)
self.push_clear_all.clicked.connect(self.onclick_clear_all)
self.check_use_cal.stateChanged.connect(self.oncheck_use_cal)
self.push_save_res.clicked.connect(self.onclick_save_res)
self.push_load_res.clicked.connect(self.onclick_load_res)
self.logfile = None
self.fresh = False
self.fine_sweep_data = None
self.recalc_spacing('')
self.onspin_subsweeps_changed(1)
QTimer.singleShot(1000, self.update_plot)
def onclick_plot(self,event):
print event.xdata,event.ydata,event.inaxes
if event.inaxes == self.axes:
if event.button != 1 and self.fine_sweep_data is not None:
sweep_data = self.fine_sweep_data
self.selected_sweep = 'fine'
else:
sweep_data = self.sweep_data
self.selected_sweep = 'coarse'
idx = (np.abs(sweep_data.freqs - event.xdata)).argmin()
self.selected_idx = idx
self.axes2.cla()
NFFT = sweep_data.blocks[idx].data.shape[0]/2
pxx,fr = plt.mlab.psd(sweep_data.blocks[idx].data,Fs=256e6/2**14,NFFT=NFFT,detrend=plt.mlab.detrend_mean)
self.axes2.semilogx(fr[fr>0],10*np.log10(pxx[fr>0]))
self.axes2.semilogx(-fr[fr<0],10*np.log10(pxx[fr<0]))
self.axes2.semilogx(fr[fr>0][0],10*np.log10(np.abs(sweep_data.blocks[idx].data.mean())**2*NFFT/(256e6/2**14)), 'o', mew=2)
blk = sweep_data.blocks[idx]
freq = blk.fs*blk.tone/float(blk.nsamp)
self.axes2.text(0.95,0.95,('%.6f MHz' % freq), ha='right', va='top',
transform = self.axes2.transAxes)
self.axes2.set_xlim(10,fr[-1])
self.axes2.set_ylim(-140,-20)
self.axes2.grid(True)
self.axes2.set_ylabel('dB/Hz')
self.axes2.set_xlabel('Hz')
#self.axes2.semilogx(fr[fr>0][0],10*np.log10(pxx[fr==0]), 'o', mew=2)
#self.canvas.draw()
self.fresh = True
print idx
def update_plot(self):
if self.fresh and (self.sweep_data is not None or self.fine_sweep_data is not None):
x = self.sweep_data.freqs
y = self.sweep_data.data
if self.check_use_cal.isChecked():
cal = np.interp(x,self.cal_freq,self.cal_mag)
cal *= 10**(-(self.ri.adc_atten+self.ri.dac_atten-31)/20.0)
else:
cal = 1.0
ph = self.sweep_data.data[:]
if len(x) >0 and len(x) == len(y) and len(x) == len(ph):
y = 20*np.log10(np.abs(y/cal))
if len(self.reslist):
resy = np.interp(self.reslist, x, y)
else:
resy = np.zeros((0,))
ph = np.angle(ph*np.exp(-1j*x*398.15))
if self.line:
self.line.set_xdata(x)
self.line.set_ydata(y)
# self.phline.set_xdata(x)
# self.phline.set_ydata(ph)
self.peakline.set_data(self.reslist,resy)
else:
self.line, = self.axes.plot(x,y,'b.-',alpha=0.5)
# self.phline, = self.axes.plot(x,ph,'g',alpha=0)
self.peakline, = self.axes.plot(self.reslist,resy,'ro')
if self.selected_sweep == 'coarse':
if self.selected_idx >= len(x):
self.selected_idx = 0
if self.selection_line:
self.selection_line.set_data([x[self.selected_idx]],[y[self.selected_idx]])
else:
self.selection_line, = self.axes.plot([x[self.selected_idx]],[y[self.selected_idx]],'mx',mew=2,markersize=20)
if self.fine_sweep_data is not None:
x = self.fine_sweep_data.freqs
y = self.fine_sweep_data.data
ph = self.fine_sweep_data.data[:]
if len(x) == len(y) and len(x) == len(ph):
if self.check_use_cal.isChecked():
cal = np.interp(x,self.cal_freq,self.cal_mag)
cal *= 10**(-(self.ri.adc_atten+self.ri.dac_atten-31)/20.0)
else:
cal = 1.0
y = 20*np.log10(np.abs(y/cal))
ph = np.angle(ph*np.exp(-1j*x*398.15))
if self.line2:
self.line2.set_xdata(x)
self.line2.set_ydata(y)
# self.phline2.set_xdata(x)
# self.phline2.set_ydata(ph)
else:
self.line2, = self.axes.plot(x,y,'r.',alpha=0.5)
# self.phline2, = self.axes.plot(x,ph,'k.',alpha=0)
if self.selected_sweep == 'fine':
if self.selected_idx >= len(x):
self.selected_idx = 0
if self.selection_line:
self.selection_line.set_data([x[self.selected_idx]],[y[self.selected_idx]])
else:
self.selection_line, = self.axes.plot([x[self.selected_idx]],[y[self.selected_idx]],'mx',mew=2,markersize=20)
self.canvas.draw()
self.fresh = False
self.line_dac_atten.setText(str(self.ri.dac_atten))
self.progress_sweep.setValue(int(self.progress_value*100))
QTimer.singleShot(1000, self.update_plot)
@pyqtSlot(int)
def oncheck_use_cal(self,val):
self.fresh = True
@pyqtSlot(int)
def onspin_subsweeps_changed(self, val):
step = 0.0625*2**self.combo_step_size.currentIndex()
substep = step/float(val)
nsamp = np.ceil(np.log2(self.ri.fs/substep))
if nsamp < 18:
nsamp = 18
self.label_coarse_info.setText("Spacing: %.3f kHz using 2**%d samples" % (substep*1000,nsamp))
@pyqtSlot()
def onclick_add_resonator(self):
if self.selected_idx is not None:
if self.selected_sweep == 'coarse':
freq = self.sweep_data.freqs[self.selected_idx]
else:
freq = self.fine_sweep_data.freqs[self.selected_idx]
reslist = self.reslist.tolist()
bisect.insort(reslist,freq)
self.reslist = np.array(reslist)
self.refresh_freq_table()
@pyqtSlot()
def onclick_save_res(self):
fname = str(QFileDialog.getSaveFileName(self, "Save resonators as:",".", "Numpy (*.npy)"))
np.save(fname,self.reslist)
@pyqtSlot()
def onclick_load_res(self):
fname = str(QFileDialog.getOpenFileName(self, "Load resonators from:",".", "Numpy (*.npy)"))
if fname:
reslist = np.load(fname)
self.reslist = reslist
self.refresh_freq_table()
@pyqtSlot()
def onclick_clear_all(self):
self.reslist = np.array([])
self.refresh_freq_table()
@pyqtSlot()
def onclick_save(self):
if self.logfile:
self.logfile.close()
self.logfile = None
self.push_save.setText("Start Logging")
self.line_filename.setText('')
else:
self.logfile = data_file.DataFile()
self.line_filename.setText(self.logfile.filename)
self.push_save.setText("Close Log File")
@pyqtSlot()
def onclick_abort(self):
self.abort_requested = True
@pyqtSlot(str)
def recalc_spacing(self,txt):
msg = None
span = None
npoint = None
try:
span = float(self.line_span_hz.text())
if span <= 0:
raise Exception()
except:
msg = "span invalid"
try:
npoint = int(self.line_npoints.text())
if npoint <=0:
raise Exception()
except:
msg = "invalid number of points"
if msg:
self.label_spacing.setText(msg)
else:
spacing = span/npoint
samps = np.ceil(np.log2(self.ri.fs*1e6/spacing))
self.label_spacing.setText("Spacing: %.3f Hz requires 2**%d samples" % (spacing,samps))
def sweep_callback(self,block):
self.sweep_data.add_block(block)
self.fresh = True
self.progress_value = (block.progress + self.current_subsweep)/float(self.total_subsweeps)
# print "currently have freqs", self.sweep_data.freqs
return self.abort_requested
def fine_sweep_callback(self,block):
self.fine_sweep_data.add_block(block)
self.fresh = True
self.progress_value = (block.progress + self.current_subsweep)/float(self.total_subsweeps)
return self.abort_requested
@pyqtSlot()
def onclick_start_sweep(self):
if self.sweep_thread:
if self.sweep_thread.is_alive():
print "sweep already running"
return
self.sweep_thread = threading.Thread(target=self.do_sweep)
self.sweep_thread.daemon = True
self.sweep_thread.start()
@pyqtSlot()
def onclick_start_fine_sweep(self):
if np.mod(self.reslist.shape[0],4) != 0:
print "Number of resonators must be divisible by 4! Add some dummy resonators."
if self.sweep_thread:
if self.sweep_thread.is_alive():
print "sweep already running"
return
self.sweep_thread = threading.Thread(target=self.do_fine_sweep)
self.sweep_thread.daemon = True
self.sweep_thread.start()
def do_sweep(self):
self.abort_requested = False
self.sweep_data = SweepData(sweep_id=1)
start = self.spin_start_freq.value()
stop = self.spin_stop_freq.value()
step = 0.0625*2**self.combo_step_size.currentIndex()
nsubstep = self.spin_subsweeps.value()
substepspace = step/nsubstep
nsamp = np.ceil(np.log2(self.ri.fs/substepspace))
if nsamp < 18:
nsamp = 18
self.total_subsweeps = nsubstep
base_freqs = np.arange(start,stop+1e-3,step)
ntones = base_freqs.shape[0]
ntones_corr = kid_readout.roach.tools.ntone_power_correction(ntones)
try:
dac_gain = float(self.line_dac_gain.text())
except:
print "Could not parse DAC gain! Aborting sweep!"
return
desired_level = self.spin_dbm_per_tone.value()
total_level = desired_level + ntones_corr
atten_val = -(total_level - dac_gain) #atten should be positive
print "Requested %.2f dBm per tone" % desired_level
print "%d tones requires a correction of %.1f dB" % (ntones,ntones_corr)
print "requiring %.1f dB of attenuation" % atten_val
if atten_val < 0:
print "Warning! requested attenuation is less than 0, can't reach desired level. Setting to 0 dB"
atten_val = 0
if atten_val > 63:
print "Warning! requested attenuation is greater than 63, can't reach desired level. Setting to 63 dB"
atten_val = 63
self.ri.set_dac_attenuator(atten_val)
for k in range(nsubstep):
self.current_subsweep = k
print "subsweep",k,"of",nsubstep
if self.logfile:
self.logfile.log_hw_state(self.ri)
kid_readout.utils.sweeps.coarse_sweep(self.ri, freqs = base_freqs + k*substepspace,
nsamp = 2**nsamp, nchan_per_step=at_a_time, callback=self.sweep_callback, sweep_id=1)
if self.logfile:
self.logfile.log_adc_snap(self.ri)
if self.abort_requested:
break
if self.logfile:
self.logfile.log_hw_state(self.ri)
name = self.logfile.add_sweep(self.sweep_data)
self.label_status.setText("saved %s" % name)
#self.find_resonances()
self.refresh_freq_table()
self.abort_requested = False
def do_fine_sweep(self):
self.abort_requested = False
self.fine_sweep_data = SweepData(sweep_id=2)
try:
width = float(self.line_span_hz.text())/1e6
npts = int(self.line_npoints.text())
except:
print "npoint or span is invalid"
return
spacing = width/npts
samps = np.ceil(np.log2(self.ri.fs/spacing))
print samps
flist = self.reslist
offsets = np.linspace(-width/2,width/2,npts)
self.total_subsweeps = len(offsets)
ntones = flist.shape[0]
ntones_corr = kid_readout.roach.baseband.ntone_power_correction(ntones)
try:
dac_gain = float(self.line_dac_gain.text())
except:
print "Could not parse DAC gain! Aborting sweep!"
return
desired_level = self.spin_dbm_per_tone.value()
total_level = desired_level + ntones_corr
atten_val = -(total_level - dac_gain) #atten should be positive
print "Requested %.2f dBm per tone" % desired_level
print "%d tones requires a correction of %.1f dB" % (ntones,ntones_corr)
print "requiring %.1f dB of attenuation" % atten_val
if atten_val < 0:
print "Warning! requested attenuation is less than 0, can't reach desired level. Setting to 0 dB"
atten_val = 0
if atten_val > 63:
print "Warning! requested attenuation is greater than 63, can't reach desired level. Setting to 63 dB"
atten_val = 63
self.ri.set_dac_attenuator(atten_val)
for k,offs in enumerate(offsets):
self.current_subsweep = k
if self.logfile:
self.logfile.log_hw_state(self.ri)
kid_readout.utils.sweeps.coarse_sweep(self.ri, freqs = flist+offs,
nsamp = 2**samps, nchan_per_step=8, reads_per_step = 8,
callback=self.fine_sweep_callback, sweep_id=2)
if self.abort_requested:
break
if self.logfile:
self.logfile.log_adc_snap(self.ri)
if self.logfile:
self.logfile.log_hw_state(self.ri)
name = self.logfile.add_sweep(self.fine_sweep_data)
self.label_status.setText("saved %s" % name)
self.abort_requested = False
def find_resonances(self):
x = self.sweep_data.freqs
y = np.abs(self.sweep_data.data)
mx,mn = peakdetect(y,x,lookahead=20)
res = np.array(mn)
if len(res) == 0:
self.reslist=np.array([])
return
self.reslist = np.array(mn)[:,0]
self.fresh = True
def setup_freq_table(self):
self.tableview_freqs.clear()
self.tableview_freqs.setSortingEnabled(False)
self.tableview_freqs.setAlternatingRowColors(True)
self.tableview_freqs.setSelectionBehavior(QTableWidget.SelectRows)
self.tableview_freqs.setColumnCount(1)
# self.tableview_freqs.setColumnWidth(0, 80)
self.tableview_freqs.setRowCount(64)#self.reslist.shape[0])
headers = ['f0']
self.tableview_freqs.setHorizontalHeaderLabels(headers)
self.refresh_freq_table()
def refresh_freq_table(self):
self.tableview_freqs.clear()
self.tableview_freqs.blockSignals(True)
for row,f0 in enumerate(self.reslist):
# Current frequency
item = QTableWidgetItem(QString.number(float(f0), 'f', 6))
item.setTextAlignment(Qt.AlignRight)
self.tableview_freqs.setItem(row, 0, item)
for row in range(self.reslist.shape[0],64):
item = QTableWidgetItem('')
item.setTextAlignment(Qt.AlignRight)
self.tableview_freqs.setItem(row, 0, item)
self.tableview_freqs.blockSignals(False)
self.fresh = True
@pyqtSlot(QTableWidgetItem)
def freq_table_item_changed(self,item):
| |
<reponame>egiltane/tsd-file-api
# -*- coding: utf-8 -*-
"""
Run this as: python -m tsdfileapi.tests.test_file_api test-config.yaml
-------------------------------------------------------------------------------
Exploring Transfer-Encoding: chunked with a minimal python client.
From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
Data is sent in a series of chunks. The Content-Length header is omitted in this
case and at the beginning of each chunk you need to add the length of the current
chunk in hexadecimal format, followed by '\r\n' and then the chunk itself, followed
by another '\r\n'.
The terminating chunk is a regular chunk, with the exception that its length is zero.
It is followed by the trailer, which consists of a (possibly empty) sequence of
entity header fields.
E.g.
HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked
7\r\n
Mozilla\r\n
9\r\n
Developer\r\n
7\r\n
Network\r\n
0\r\n
\r\n
tornado
so with tornado it _just works_ - but not the naive impl
the async method write data to the file, while waiting for the rest
this is _exactly what the video streaming needs.
behind nginx you need to set the following:
proxy_http_version 1.1;
proxy_request_buffering off;
From bdarnell:
sending an error requires a little-used feature of HTTP called "100-continue".
If the client supports 100-continue (curl-based clients do by default for large POSTS;
most others don't. I don't know if curl uses 100-continue with chunked requests)
and the tornado service uses @stream_request_body, then sending an error response
from prepare() will be received by the client before the body is uploaded
On 100-continue:
https://tools.ietf.org/html/rfc7231#page-50
So the HTTP Client should implement this...
Some background on python2.7 and requests
https://github.com/kennethreitz/requests/issues/713
"""
# pylint tends to be too pedantic regarding docstrings - we can decide in code review
# pylint: disable=missing-docstring
# test names are verbose...
# pylint: disable=too-many-public-methods
# method names are verbose in tests
# pylint: disable=invalid-name
import base64
import json
import logging
import os
import random
import sys
import time
import unittest
import pwd
import uuid
import shutil
import sqlite3
from datetime import datetime
from typing import Union, Callable
import psycopg2
import psycopg2.pool
import pretty_bad_protocol._parsers
import requests
import yaml
from pretty_bad_protocol import gnupg
from sqlalchemy.exc import OperationalError
from termcolor import colored
from tsdapiclient import fileapi
from tornado.escape import url_escape
pretty_bad_protocol._parsers.Verify.TRUST_LEVELS["ENCRYPTION_COMPLIANCE_MODE"] = 23
# pylint: disable=relative-import
from auth import process_access_token
from tokens import gen_test_tokens, get_test_token_for_p12, gen_test_token_for_user
from db import session_scope, sqlite_init, postgres_init, SqliteBackend, \
sqlite_session, PostgresBackend, postgres_session
from resumables import SerialResumable
from utils import sns_dir, md5sum, IllegalFilenameException
from pgp import _import_keys
from squril import SqliteQueryGenerator, PostgresQueryGenerator
def project_import_dir(
config: dict,
tenant: str,
*,
backend: str,
tenant_pattern: str,
) -> str:
folder = config['backends']['disk'][backend]['import_path'].replace(tenant_pattern, tenant)
return os.path.normpath(folder)
def lazy_file_reader(filename: str) -> bytes:
with open(filename, 'rb') as f:
while True:
data = f.read(10)
if not data:
break
else:
yield data
class TestFileApi(unittest.TestCase):
@classmethod
def pgp_encrypt_and_base64_encode(cls, string):
gpg = _import_keys(cls.config)
encrypted = gpg.encrypt(string, cls.config['public_key_id'], armor=False)
encoded = base64.b64encode(encrypted.data)
return encoded
@classmethod
def setUpClass(cls):
try:
with open(sys.argv[1]) as f:
cls.config = yaml.load(f, Loader=yaml.Loader)
except Exception as e:
print(e)
print("Missing config file?")
sys.exit(1)
# includes p19 - a random project number for integration testing
cls.test_project = cls.config['test_project']
cls.maintenance_url = f"http://localhost:{str(cls.config['port'])}/v1/admin"
cls.base_url = f"http://localhost:{str(cls.config['port'])}/v1/{cls.test_project}"
cls.data_folder = cls.config['data_folder']
cls.example_csv = os.path.normpath(cls.data_folder + '/example.csv')
cls.an_empty_file = os.path.normpath(cls.data_folder + '/an-empty-file')
cls.example_codebook = json.loads(
open(os.path.normpath(cls.data_folder + '/example-ns.json')).read())
cls.test_user = cls.config['test_user']
cls.test_group = cls.config['test_group']
cls.uploads_folder = project_import_dir(
cls.config,
cls.config['test_project'],
backend='files_import',
tenant_pattern=cls.config['tenant_string_pattern']
)
cls.uploads_folder_p12 = project_import_dir(
cls.config,
'p12',
backend='files_import',
tenant_pattern=cls.config['tenant_string_pattern']
)
cls.uploads_folder_survey = project_import_dir(
cls.config,
cls.config['test_project'],
backend='survey',
tenant_pattern=cls.config['tenant_string_pattern']
)
cls.test_sns_url = '/v1/{0}/sns/{1}/{2}'.format(
cls.config['test_project'],
cls.config['test_keyid'],
cls.config['test_formid']
)
cls.test_sns_dir = cls.config['backends']['disk']['sns']['import_path']
cls.test_formid = cls.config['test_formid']
cls.test_keyid = cls.config['test_keyid']
cls.sns_uploads_folder = sns_dir(
cls.test_sns_dir,
cls.config['test_project'],
cls.test_sns_url,
cls.config['tenant_string_pattern'],
test=True
)
cls.publication_import_folder = cls.config['backends']['disk']['publication']['import_path'].replace('pXX', cls.config['test_project'])
cls.apps_import_folder = cls.config['backends']['disk']['apps_files']['import_path'].replace('pXX', cls.config['test_project'])
cls.verbose = cls.config.get('verbose')
# endpoints
cls.upload = cls.base_url + '/files/upload'
cls.sns_upload = cls.base_url + '/sns/' + cls.config['test_keyid'] + '/' + cls.config['test_formid']
cls.upload_sns_wrong = cls.base_url + '/sns/' + 'WRONG' + '/' + cls.config['test_formid']
cls.stream = cls.base_url + '/files/stream'
cls.export = cls.base_url + '/files/export'
cls.resumables = cls.base_url + '/files/resumables'
cls.publication_import = cls.base_url + '/publication/import'
cls.publication_export = cls.base_url + '/publication/export'
cls.publication_tables = cls.base_url + '/publication/tables'
cls.survey = cls.base_url + '/survey'
cls.apps = cls.base_url + '/apps'
cls.logs = cls.base_url + '/logs'
cls.test_project = cls.test_project
cls.tenant_string_pattern = cls.config['tenant_string_pattern']
# auth tokens
global TEST_TOKENS
TEST_TOKENS = gen_test_tokens(cls.config)
global P12_TOKEN
P12_TOKEN = get_test_token_for_p12(cls.config)
# example data
cls.example_tar = os.path.normpath(cls.data_folder + '/example.tar')
cls.example_tar_gz = os.path.normpath(cls.data_folder + '/example.tar.gz')
cls.enc_symmetric_secret = cls.pgp_encrypt_and_base64_encode('tOg1qbyhRMdZLg==')
cls.enc_hex_aes_key = cls.pgp_encrypt_and_base64_encode('<KEY>')
cls.hex_aes_iv = 'a53c9b54b5f84e543b592050c52531ef'
cls.example_aes = os.path.normpath(cls.data_folder + '/example.csv.aes')
# tar -cf - totar3 | openssl enc -aes-256-cbc -a -pass file:<( echo $PW ) > example.tar.aes
cls.example_tar_aes = os.path.normpath(cls.data_folder + '/example.tar.aes')
# tar -cf - totar3 | gzip -9 | openssl enc -aes-256-cbc -a -pass file:<( echo $PW ) > example.tar.gz.aes
cls.example_tar_gz_aes = os.path.normpath(cls.data_folder + '/example.tar.gz.aes')
cls.example_gz = os.path.normpath(cls.data_folder + '/example.csv.gz')
cls.example_gz_aes = os.path.normpath(cls.data_folder + '/example.csv.gz.aes')
# openssl enc -aes-256-cbc -a -iv ${hex_aes_iv} -K ${hex_aes_key}
cls.example_aes_with_key_and_iv = os.path.normpath(cls.data_folder + '/example.csv.aes-with-key-and-iv')
cls.example_tar_aes_with_key_and_iv = os.path.normpath(cls.data_folder + '/example.tar.aes-with-key-and-iv')
cls.example_tar_gz_aes_with_key_and_iv = os.path.normpath(cls.data_folder + '/example.tar.gz.aes-with-key-and-iv')
cls.example_gz_aes_with_key_and_iv = os.path.normpath(cls.data_folder + '/example.csv.gz.aes-with-key-and-iv')
# openssl enc -aes-256-cbc -iv ${hex_aes_iv} -K ${hex_aes_key}
cls.example_binary_aes_with_key_and_iv = os.path.normpath(cls.data_folder + '/example.csv.binary-aes-with-key-and-iv')
# resumables
cls.resume_file1 = os.path.normpath(cls.data_folder + '/resume-file1')
cls.resume_file2 = os.path.normpath(cls.data_folder + '/resume-file2')
# filename tests
cls.so_sweet = os.path.normpath(cls.data_folder + '/så_søt(1).txt')
cls.red = os.path.normpath(cls.data_folder + '/rød_fil_(1).txt')
cls.test_upload_id = '96c68dad-8dc5-4076-9569-92394001d42a'
# TODO: make this configurable
# do not dist with package
cls.large_file = os.path.normpath(cls.data_folder + '/large-file')
@classmethod
def tearDownClass(cls):
uploaded_files = os.listdir(cls.uploads_folder)
test_files = os.listdir(cls.config['data_folder'])
today = datetime.fromtimestamp(time.time()).isoformat()[:10]
file_list = ['streamed-example.csv', 'uploaded-example.csv',
'uploaded-example-2.csv', 'uploaded-example-3.csv',
'streamed-not-chunked', 'streamed-put-example.csv']
for _file in uploaded_files:
# TODO: eventually remove - still want to inspect them
# manually while the data pipelines are in alpha
if _file in ['totar', 'totar2', 'decrypted-aes.csv',
'totar3', 'totar4', 'ungz1', 'ungz-aes1',
'uploaded-example-2.csv', 'uploaded-example-3.csv']:
continue
if (_file in test_files) or (today in _file) or (_file in file_list):
try:
os.remove(os.path.normpath(cls.uploads_folder + '/' + _file))
except OSError as e:
logging.error(e)
continue
sqlite_path = cls.uploads_folder + '/api-data.db'
try:
#os.remove(sqlite_path)
pass
except OSError:
print('no tables to cleanup')
return
# Import Auth
#------------
def check_endpoints(self, headers: dict) -> None:
files = {'file': ('example.csv', open(self.example_csv))}
for url in [self.upload, self.stream, self.upload]:
resp = requests.put(url, headers=headers, files=files)
self.assertEqual(resp.status_code, 401)
resp = requests.post(url, headers=headers, files=files)
self.assertEqual(resp.status_code, 401)
resp = requests.patch(url, headers=headers, files=files)
self.assertEqual(resp.status_code, 401)
def test_D_timed_out_token_rejected(self) -> None:
headers = {'Authorization': 'Bearer ' + TEST_TOKENS['TIMED_OUT']}
self.check_endpoints(headers)
def test_E_unauthenticated_request_rejected(self) -> None:
headers = {}
self.check_endpoints(headers)
# uploading files and streams
#----------------------------
# multipart formdata endpoint
def remove(self, target_uploads_folder: str, newfilename: str) -> None:
try:
_file = os.path.normpath(target_uploads_folder + '/' + newfilename)
os.remove(_file)
except OSError:
pass
def mp_fd(
self,
newfilename: str,
target_uploads_folder: str,
url: str,
method: str,
) -> requests.Response:
headers = {'Authorization': 'Bearer ' + TEST_TOKENS['VALID']}
f = open(self.example_csv)
files = {'file': (newfilename, f)}
if method == 'POST':
self.remove(target_uploads_folder, newfilename)
resp = requests.post(url, files=files, headers=headers)
elif method == 'PATCH':
# not going to remove here, since we need to test non-idempotent uploads
resp = requests.patch(url, files=files, headers=headers)
elif method == 'PUT':
# not going to remove, need to check that it is idempotent
resp = requests.put(url, files=files, headers=headers)
f.close()
return resp
def check_copied_sns_file_exists(self, filename: str) -> None:
file = (self.sns_uploads_folder + '/' + filename)
hidden_file = file.replace(self.config['public_key_id'], '.tsd/' + self.config['public_key_id'])
self.assertTrue(os.path.lexists(hidden_file))
def t_post_mp(self, uploads_folder: str, newfilename: str, url: str) -> None:
target = os.path.normpath(uploads_folder + '/' + newfilename)
resp = self.mp_fd(newfilename, uploads_folder, url, 'POST')
self.assertEqual(resp.status_code, 201)
uploaded_file = os.path.normpath(uploads_folder + '/' + newfilename)
self.assertEqual(md5sum(self.example_csv), md5sum(uploaded_file))
def test_F_post_file_multi_part_form_data(self) -> None:
self.t_post_mp(self.uploads_folder, 'uploaded-example.csv', self.upload)
def test_F1_post_file_multi_part_form_data_sns(self) -> None:
filename = 'sns-uploaded-example.csv'
self.t_post_mp(self.sns_uploads_folder, filename, self.sns_upload)
self.check_copied_sns_file_exists(filename)
def test_FA_post_multiple_files_multi_part_form_data(self) -> None:
newfilename1 = 'n1'
newfilename2 = 'n2'
try:
os.remove(os.path.normpath(self.uploads_folder + '/' + newfilename1))
os.remove(os.path.normpath(self.uploads_folder + '/' + newfilename2))
except OSError:
pass
files = [('file', (newfilename1, open(self.example_csv, 'rb'), 'text/html')),
('file', (newfilename2, open(self.example_csv, 'rb'), 'text/html'))]
headers = {'Authorization': 'Bearer ' + TEST_TOKENS['VALID']}
resp = requests.post(self.upload, files=files, headers=headers)
self.assertEqual(resp.status_code, 201)
uploaded_file1 = os.path.normpath(self.uploads_folder + '/' + newfilename1)
uploaded_file2 = os.path.normpath(self.uploads_folder + '/' + newfilename2)
self.assertEqual(md5sum(self.example_csv), md5sum(uploaded_file1))
self.assertEqual(md5sum(self.example_csv), md5sum(uploaded_file2))
files = [('file', (newfilename1, open(self.example_csv, 'rb'), 'text/html')),
('file', (newfilename2, open(self.example_csv, 'rb'), 'text/html'))]
resp2 = requests.post(self.upload, files=files, headers=headers)
self.assertEqual(resp2.status_code, 201)
self.assertNotEqual(md5sum(self.example_csv), md5sum(uploaded_file1))
self.assertNotEqual(md5sum(self.example_csv), md5sum(uploaded_file2))
def t_patch_mp(self, uploads_folder: str, newfilename: str, url: str) -> None:
target = os.path.normpath(uploads_folder + '/' + newfilename)
# need to get rid of previous round's file, if present
self.remove(uploads_folder, newfilename)
# first request - create a new file
resp = self.mp_fd(newfilename, target, url, 'PATCH')
self.assertEqual(resp.status_code, 201)
uploaded_file = os.path.normpath(uploads_folder + '/' + newfilename)
self.assertEqual(md5sum(self.example_csv), md5sum(uploaded_file))
# second request - PATCH should not be idempotent
resp2 = self.mp_fd(newfilename, target, url, 'PATCH')
self.assertEqual(resp2.status_code, 201)
self.assertNotEqual(md5sum(self.example_csv), md5sum(uploaded_file))
def test_G_patch_file_multi_part_form_data(self) -> None:
self.t_patch_mp(self.uploads_folder, 'uploaded-example-2.csv', self.upload)
def test_G1_patch_file_multi_part_form_data_sns(self) -> None:
filename = | |
0.18 34.13 0.02
1 1.33e+06 2821.26 | 1578.01 0.0 244 0 | 1.60 0.18 34.10 0.02
1 1.34e+06 2821.26 | 2315.74 907.4 361 142 | 1.64 0.19 34.61 0.02
1 1.36e+06 2821.26 | 1068.61 0.0 185 0 | 1.65 0.18 34.59 0.02
1 1.37e+06 2821.26 | 780.38 0.0 119 0 | 1.68 0.19 35.22 0.02
1 1.38e+06 2821.26 | 2128.08 909.8 340 138 | 1.68 0.19 34.24 0.02
1 1.40e+06 5116.59 |
1 1.40e+06 5116.59 | 5116.59 2166.1 734 297 | 1.77 0.19 32.93 0.02
1 1.41e+06 5116.59 | 2901.13 2543.3 403 345 | 1.71 0.19 35.32 0.02
1 1.43e+06 5116.59 | 1638.18 0.0 244 0 | 1.73 0.19 34.84 0.02
1 1.44e+06 5116.59 | 1007.29 0.0 169 0 | 1.72 0.18 34.59 0.02
1 1.46e+06 5116.59 | 3304.17 2510.8 469 341 | 1.76 0.19 35.45 0.02
1 1.47e+06 5116.59 | 3501.58 0.0 483 0 | 1.74 0.19 35.97 0.02
1 1.49e+06 5305.27 |
1 1.49e+06 5305.27 | 5305.27 2807.9 730 378 | 1.77 0.19 35.58 0.02
1 1.50e+06 5305.27 | 5014.42 2359.4 688 315 | 1.72 0.19 35.65 0.02
1 1.52e+06 5305.27 | 4736.14 0.0 639 0 | 1.72 0.19 36.84 0.02
1 1.53e+06 5305.27 | 4393.27 2047.5 598 265 | 1.76 0.19 37.57 0.02
1 1.55e+06 5305.27 | 1213.84 0.0 175 0 | 1.84 0.19 37.64 0.02
1 1.56e+06 5305.27 | 3804.35 2176.2 529 286 | 1.82 0.18 36.11 0.02
1 1.58e+06 5305.27 | 4753.45 0.0 649 0 | 1.82 0.19 35.78 0.02
1 1.59e+06 5305.27 | 3659.95 0.0 478 0 | 1.81 0.20 36.94 0.02
1 1.61e+06 5305.27 | 4564.50 0.0 606 0 | 1.85 0.19 36.93 0.02
1 1.62e+06 6495.10 |
1 1.62e+06 6495.10 | 6495.10 2253.1 837 283 | 1.83 0.19 37.61 0.02
1 1.63e+06 6495.10 | 6440.03 2628.1 819 314 | 1.85 0.19 37.76 0.02
1 1.64e+06 6495.10 | 5980.08 2214.3 784 282 | 1.91 0.19 37.79 0.02
1 1.66e+06 6495.10 | 1143.72 0.0 158 0 | 1.87 0.19 38.26 0.02
1 1.67e+06 6495.10 | 3229.25 0.0 447 0 | 1.87 0.19 38.75 0.02
1 1.68e+06 7820.89 |
1 1.68e+06 7820.89 | 7820.89 49.0 1000 0 | 1.86 0.19 38.04 0.02
1 1.69e+06 7820.89 | 6616.72 2186.4 843 272 | 1.89 0.19 38.41 0.02
1 1.70e+06 7820.89 | 2205.00 0.0 297 0 | 1.85 0.19 38.45 0.02
1 1.71e+06 8201.97 |
1 1.71e+06 8201.97 | 8201.97 60.7 1000 0 | 1.89 0.19 38.49 0.02
1 1.72e+06 8201.97 | 8053.00 0.0 1000 0 | 1.93 0.19 37.79 0.02
1 1.73e+06 8201.97 | 7974.46 0.0 1000 0 | 1.92 0.19 38.88 0.02
1 1.74e+06 8201.97 | 1736.69 0.0 237 0 | 1.88 0.19 38.00 0.02
1 1.75e+06 8201.97 | 7027.53 1871.2 873 220 | 1.94 0.19 37.89 0.02
1 1.76e+06 8201.97 | 4689.30 0.0 579 0 | 1.92 0.19 38.55 0.02
1 1.77e+06 8201.97 | 7855.02 0.0 1000 0 | 1.91 0.19 38.86 0.02
1 1.78e+06 8201.97 | 5215.32 0.0 673 0 | 1.92 0.19 38.98 0.02
1 1.79e+06 8201.97 | 8026.47 0.0 1000 0 | 1.92 0.19 39.59 0.02
1 1.80e+06 8201.97 | 2568.57 0.0 322 0 | 1.89 0.19 39.10 0.02
1 1.81e+06 8201.97 | 3905.44 0.0 516 0 | 1.91 0.20 39.09 0.02
1 1.82e+06 8201.97 | 6868.42 0.0 841 0 | 1.89 0.19 38.71 0.02
1 1.83e+06 8201.97 | 2328.69 0.0 302 0 | 1.93 0.19 39.10 0.02
1 1.84e+06 8201.97 | 7570.05 1112.7 922 135 | 1.97 0.19 39.31 0.02
1 1.85e+06 8201.97 | 5452.10 3047.4 648 353 | 1.81 0.19 39.20 0.02
1 1.85e+06 8201.97 | 5185.33 3187.5 621 365 | 1.95 0.19 39.28 0.02
1 1.87e+06 8201.97 | 3431.44 0.0 414 0 | 2.01 0.19 39.72 0.02
1 1.88e+06 8201.97 | 7174.34 2007.4 852 236 | 1.92 0.20 40.53 0.02
1 1.88e+06 8201.97 | 7000.72 2664.7 823 307 | 1.98 0.19 39.93 0.02
1 1.89e+06 8201.97 | 7756.40 1533.1 900 172 | 1.95 0.20 40.53 0.02
1 1.90e+06 8201.97 | 1015.23 0.0 138 0 | 1.97 0.20 40.52 0.02
1 1.91e+06 8201.97 | 7223.27 0.0 829 0 | 1.96 0.20 39.91 0.02
1 1.92e+06 8201.97 | 2276.04 0.0 271 0 | 1.93 0.20 41.08 0.02
1 1.93e+06 8201.97 | 4279.54 2531.4 512 290 | 1.92 0.20 41.14 0.02
1 1.94e+06 8601.43 |
1 1.94e+06 8601.43 | 8601.43 36.4 1000 0 | 2.01 0.19 41.16 0.02
1 1.95e+06 8605.06 |
1 1.95e+06 8605.06 | 8605.06 53.1 999 2 | 2.01 0.19 39.77 0.02
1 1.96e+06 8605.06 | 8604.10 0.0 1000 0 | 2.02 0.19 41.39 0.02
1 1.97e+06 8605.06 | 4942.93 2670.4 565 286 | 1.99 0.19 40.93 0.02
1 1.98e+06 8605.06 | 8122.71 1366.2 914 148 | 1.93 0.20 41.49 0.02
1 1.99e+06 8605.06 | 1545.50 0.0 194 0 | 1.96 0.19 40.50 0.02
1 2.00e+06 8605.06 | 8586.34 0.0 1000 0 | 1.98 0.20 40.69 0.02
| UsedTime: 17168 | SavedDir: ./Humanoid-v3_ReliableSAC_1
| Learner: Save in ./Humanoid-v3_ReliableSAC_1
"""
elif env_name == 'Humanoid-v3.backup.best.5684':
from elegantrl.envs.CustomGymEnv import HumanoidEnv
env_func = HumanoidEnv
env_args = {
'env_num': 1,
'env_name': 'Humanoid-v3',
'max_step': 1000,
'state_dim': 376,
'action_dim': 17,
'if_discrete': False,
'target_return': 3000.,
}
args = Arguments(agent, env_func=env_func, env_args=env_args)
args.eval_times = 2 ** 2
args.reward_scale = 2 ** -5 # todo
args.max_memo = 2 ** 21
args.learning_rate = 2 ** -14
args.lambda_a_log_std = 2 ** -6
args.target_step = args.max_step
args.worker_num = 4
args.net_dim = 2 ** 8
args.num_layer = 4
args.batch_size = args.net_dim
args.repeat_times = 2 ** 1
args.gamma = 0.99
args.if_act_target = False # todo
# import numpy as np
# args.target_entropy = np.log(env_args['action_dim']) * 1.5 # ???
args.if_allow_break = False
args.break_step = int(2e6)
"""
| Arguments Remove cwd: ./Humanoid-v3_ReliableSAC_2
################################################################################
ID Step maxR | avgR stdR avgS stdS | expR objC etc.
2 8.07e+03 61.53 |
2 8.07e+03 61.53 | 61.53 0.2 13 0 | 0.30 0.54 0.06 0.00
2 8.94e+04 280.97 |
2 8.94e+04 280.97 | 280.97 31.6 65 7 | 0.27 0.07 7.21 0.00
2 1.30e+05 482.54 |
2 1.30e+05 482.54 | 482.54 81.2 104 18 | 0.29 0.14 12.59 0.00
2 1.63e+05 482.54 | 214.11 0.0 45 0 | 0.33 0.19 14.43 0.00
2 1.92e+05 482.54 | 316.52 0.0 68 0 | 0.28 0.21 14.28 0.00
2 2.17e+05 482.54 | 420.99 62.4 85 13 | 0.32 0.21 14.13 0.01
2 2.37e+05 482.54 | 431.52 86.9 93 20 | 0.31 0.17 12.33 0.01
2 2.58e+05 482.54 | 327.86 0.0 66 0 | 0.31 0.16 11.73 0.02
2 2.79e+05 482.54 | 242.40 0.0 52 0 | 0.29 0.15 11.19 0.02
2 2.96e+05 482.54 | 320.37 0.0 69 0 | 0.30 0.14 11.86 0.02
2 3.13e+05 482.54 | 322.18 0.0 63 0 | 0.31 0.13 11.78 0.02
2 3.30e+05 482.54 | 329.25 0.0 65 0 | 0.30 0.13 12.85 0.02
2 3.46e+05 482.54 | 325.96 0.0 64 0 | 0.31 0.13 13.95 0.02
2 3.63e+05 482.54 | 404.71 0.0 86 0 | 0.30 0.13 13.56 0.02
2 3.76e+05 482.54 | 470.03 0.0 90 0 | 0.31 0.14 13.65 0.02
2 3.88e+05 482.54 | 476.55 0.0 105 0 | 0.31 0.14 14.21 0.02
2 4.01e+05 482.54 | 442.83 129.8 88 23 | 0.31 0.14 14.80 0.02
2 4.13e+05 634.66 |
2 4.13e+05 634.66 | 634.66 120.2 129 21 | 0.30 0.15 13.76 0.02
2 4.26e+05 634.66 | 559.63 50.0 121 16 | 0.30 0.15 15.50 0.02
2 4.39e+05 634.66 | 523.28 170.8 112 31 | 0.29 0.15 15.04 0.02
2 4.51e+05 634.66 | 357.70 0.0 77 0 | 0.30 0.16 15.47 0.02
2 4.64e+05 634.66 | 324.52 0.0 73 0 | 0.30 0.17 15.74 0.02
2 4.77e+05 634.66 | 605.87 211.2 128 35 | 0.31 0.18 15.78 0.02
2 4.90e+05 634.66 | 525.32 0.0 102 0 | 0.30 0.18 16.98 0.02
2 5.03e+05 634.66 | 606.06 0.0 119 0 | 0.30 0.20 17.79 0.02
2 5.16e+05 754.18 |
2 5.16e+05 754.18 | 754.18 187.2 152 40 | 0.30 0.20 18.10 0.02
2 5.28e+05 754.18 | 588.85 0.0 121 0 | 0.30 0.20 18.44 0.02
2 5.41e+05 754.18 | 645.80 0.0 137 0 | 0.29 0.21 18.65 0.02
2 5.54e+05 754.18 | 599.06 180.4 127 37 | 0.29 0.21 17.64 0.02
2 5.68e+05 754.18 | 598.60 125.8 116 27 | 0.30 0.22 18.42 | |
#! /usr/bin/env python
import mock
import errno
import socket
import ssl
from collections import deque
from nsq import connection
from nsq import constants
from nsq import exceptions
from nsq import response
from nsq import util
from nsq import json
from common import MockedSocketTest, HttpClientIntegrationTest
class TestConnection(MockedSocketTest):
'''Tests about our connection'''
def test_alive(self):
self.assertTrue(self.connection.alive())
def test_close(self):
'''Should mark the connection as closed'''
self.connection.close()
self.assertFalse(self.connection.alive())
def test_blocking(self):
'''Sets blocking on the socket'''
self.connection.setblocking(0)
self.socket.setblocking.assert_called_with(0)
def test_pending(self):
'''Appends to pending'''
self.connection.nop()
self.assertEqual(
list(self.connection.pending()), [constants.NOP + constants.NL])
def test_flush_partial(self):
'''Keeps its place when flushing out partial messages'''
# We'll tell the connection it has only sent one byte when flushing
with mock.patch.object(self.socket, 'send'):
self.socket.send.return_value = 1
self.connection.nop()
self.connection.flush()
# We expect all but the first byte to remain
message = constants.NOP + constants.NL
self.assertEqual(list(self.connection.pending()), [message[1:]])
def test_flush_full(self):
'''Pops off messages it has flushed completely'''
# We'll tell the connection it has only sent one byte when flushing
self.connection.nop()
self.connection.flush()
# The nop message was sent, so we expect it to be popped
self.assertEqual(list(self.connection.pending()), [])
def test_flush_count(self):
'''Returns how many bytes were sent'''
message = constants.NOP + constants.NL
# Ensure this doesn't invoke our normal flush
self.connection.nop()
self.assertEqual(self.connection.flush(), len(message))
def test_flush_empty(self):
'''Returns 0 if there are no pending messages'''
self.assertEqual(self.connection.flush(), 0)
def test_flush_multiple(self):
'''Flushes as many messages as possible'''
pending = deque([b'hello'] * 5)
with mock.patch.object(self.connection, '_pending', pending):
self.connection.flush()
self.assertEqual(len(self.connection.pending()), 0)
def test_flush_would_block(self):
'''Honors EAGAIN / EWOULDBLOCK'''
pending = deque([b'1', b'2', b'3'])
with mock.patch.object(self.connection, '_socket') as mock_socket:
with mock.patch.object(self.connection, '_pending', pending):
mock_socket.send.side_effect = socket.error(errno.EAGAIN)
self.assertEqual(self.connection.flush(), 0)
def test_flush_would_block_ssl_write(self):
'''Honors ssl.SSL_ERROR_WANT_WRITE'''
pending = deque([b'1', b'2', b'3'])
with mock.patch.object(self.connection, '_socket') as mock_socket:
with mock.patch.object(self.connection, '_pending', pending):
mock_socket.send.side_effect = ssl.SSLError(
ssl.SSL_ERROR_WANT_WRITE)
self.assertEqual(self.connection.flush(), 0)
def test_flush_would_block_ssl_read(self):
'''Honors ssl.SSL_ERROR_WANT_READ'''
pending = deque([b'1', b'2', b'3'])
with mock.patch.object(self.connection, '_socket') as mock_socket:
with mock.patch.object(self.connection, '_pending', pending):
mock_socket.send.side_effect = ssl.SSLError(
ssl.SSL_ERROR_WANT_READ)
self.assertEqual(self.connection.flush(), 0)
def test_flush_would_block_ssl_write_buffer(self):
'''ssl.SSL_ERROR_WANT_WRITE usesthe same buffer on next send'''
pending = deque([b'1', b'2', b'3'])
with mock.patch.object(self.connection, '_pending', pending):
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.send.side_effect = ssl.SSLError(
ssl.SSL_ERROR_WANT_WRITE)
self.assertFalse(self.connection._out_buffer)
self.connection.flush()
self.assertEqual(self.connection._out_buffer, b'123')
# With some more pending items, make sure we still only get '123' sent
pending = deque([b'4', b'5', b'6'])
with mock.patch.object(self.connection, '_pending', pending):
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.send.return_value = 3
# The first flush should see the existing buffer
self.connection.flush()
mock_socket.send.assert_called_with(b'123')
# The second flush should see the pending requests
self.connection.flush()
mock_socket.send.assert_called_with(b'456')
def test_flush_socket_error(self):
'''Re-raises socket non-EAGAIN errors'''
pending = deque([b'1', b'2', b'3'])
with mock.patch.object(self.connection, '_socket') as mock_socket:
with mock.patch.object(self.connection, '_pending', pending):
mock_socket.send.side_effect = socket.error('foo')
self.assertRaises(socket.error, self.connection.flush)
def test_eager_flush(self):
'''Sending on a non-blocking connection does not eagerly flushes'''
with mock.patch.object(self.connection, 'flush') as mock_flush:
self.connection.send(b'foo')
mock_flush.assert_not_called()
def test_close_flush(self):
'''Closing the connection flushes all remaining messages'''
def fake_flush():
self.connection._pending = False
self.connection._fake_flush_called = True
with mock.patch.object(self.connection, 'flush', fake_flush):
self.connection.send(b'foo')
self.connection.close()
self.assertTrue(self.connection._fake_flush_called)
def test_magic(self):
'''Sends the NSQ magic bytes'''
self.assertTrue(self.socket.read().startswith(constants.MAGIC_V2))
def test_identify(self):
'''The connection sends the identify commands'''
expected = b''.join([
constants.MAGIC_V2,
constants.IDENTIFY,
constants.NL,
util.pack(json.dumps(self.connection._identify_options).encode())])
self.assertEqual(self.socket.read(), expected)
def test_read_timeout(self):
'''Returns no results after a socket timeout'''
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.recv.side_effect = socket.timeout
self.assertEqual(self.connection.read(), [])
def test_read_socket_error(self):
'''Re-raises socket non-errno socket errors'''
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.recv.side_effect = socket.error('foo')
self.assertRaises(socket.error, self.connection.read)
def test_read_would_block(self):
'''Returns no results if it would block'''
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.recv.side_effect = socket.error(errno.EAGAIN)
self.assertEqual(self.connection.read(), [])
def test_read_would_block_ssl_write(self):
'''Returns no results if it would block on a SSL socket'''
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.recv.side_effect = ssl.SSLError(ssl.SSL_ERROR_WANT_WRITE)
self.assertEqual(self.connection.read(), [])
def test_read_would_block_ssl_read(self):
'''Returns no results if it would block on a SSL socket'''
with mock.patch.object(self.connection, '_socket') as mock_socket:
mock_socket.recv.side_effect = ssl.SSLError(ssl.SSL_ERROR_WANT_READ)
self.assertEqual(self.connection.read(), [])
def test_read_partial(self):
'''Returns nothing if it has only read partial results'''
self.socket.write(b'f')
self.assertEqual(self.connection.read(), [])
def test_read_size_partial(self):
'''Returns one response size is complete, but content is partial'''
self.socket.write(response.Response.pack(b'hello')[:-1])
self.assertEqual(self.connection.read(), [])
def test_read_whole(self):
'''Returns a single message if it has read a complete one'''
self.socket.write(response.Response.pack(b'hello'))
expected = response.Response(
self.connection, constants.FRAME_TYPE_RESPONSE, b'hello')
self.assertEqual(self.connection.read(), [expected])
def test_read_multiple(self):
'''Returns multiple responses if available'''
self.socket.write(response.Response.pack(b'hello') * 10)
expected = response.Response(
self.connection, constants.FRAME_TYPE_RESPONSE, b'hello')
self.assertEqual(self.connection.read(), [expected] * 10)
def test_fileno(self):
'''Returns the connection's file descriptor appropriately'''
self.assertEqual(
self.connection.fileno(), self.socket.fileno())
def test_fileno_closed(self):
'''Raises an exception if the connection's closed'''
with mock.patch.object(self.connection, '_socket', None):
self.assertRaises(exceptions.ConnectionClosedException,
self.connection.fileno)
def test_str_alive(self):
'''Sane str representation for an alive connection'''
with mock.patch.object(self.connection, 'alive', return_value=True):
with mock.patch.object(
self.connection, 'fileno', return_value=7):
with mock.patch.object(self.connection, 'host', 'host'):
with mock.patch.object(self.connection, 'port', 'port'):
self.assertEqual(str(self.connection),
'<Connection host:port (alive on FD 7)>')
def test_str_dead(self):
'''Sane str representation for an alive connection'''
with mock.patch.object(self.connection, 'alive', return_value=False):
with mock.patch.object(
self.connection, 'fileno', return_value=7):
with mock.patch.object(self.connection, 'host', 'host'):
with mock.patch.object(self.connection, 'port', 'port'):
self.assertEqual(str(self.connection),
'<Connection host:port (dead on FD 7)>')
def test_send_no_message(self):
'''Appropriately sends packed data without message'''
self.socket.read()
self.connection.nop()
self.connection.flush()
expected = constants.NOP + constants.NL
self.assertEqual(self.socket.read(), expected)
def test_send_message(self):
'''Appropriately sends packed data with message'''
self.socket.read()
self.connection.identify({})
self.connection.flush()
expected = b''.join(
(constants.IDENTIFY, constants.NL, util.pack(b'{}')))
self.assertEqual(self.socket.read(), expected)
def assertSent(self, expected, function, *args, **kwargs):
'''Assert that the connection sends the expected payload'''
self.socket.read()
function(*args, **kwargs)
self.connection.flush()
self.assertEqual(self.socket.read(), expected)
def test_auth(self):
'''Appropriately send auth'''
expected = b''.join((constants.AUTH, constants.NL, util.pack(b'hello')))
self.assertSent(expected, self.connection.auth, b'hello')
def test_sub(self):
'''Appropriately sends sub'''
expected = b''.join((constants.SUB, b' foo bar', constants.NL))
self.assertSent(expected, self.connection.sub, b'foo', b'bar')
def test_pub(self):
'''Appropriately sends pub'''
expected = b''.join(
(constants.PUB, b' foo', constants.NL, util.pack(b'hello')))
self.assertSent(expected, self.connection.pub, b'foo', b'hello')
def test_mpub(self):
'''Appropriately sends mpub'''
expected = b''.join((
constants.MPUB, b' foo', constants.NL,
util.pack([b'hello', b'howdy'])))
self.assertSent(expected, self.connection.mpub, b'foo', b'hello', b'howdy')
def test_ready(self):
'''Appropriately sends ready'''
expected = b''.join((constants.RDY, b' 5', constants.NL))
self.assertSent(expected, self.connection.rdy, 5)
def test_fin(self):
'''Appropriately sends fin'''
expected = b''.join((constants.FIN, b' message_id', constants.NL))
self.assertSent(expected, self.connection.fin, b'message_id')
def test_req(self):
'''Appropriately sends req'''
expected = b''.join((constants.REQ, b' message_id 10', constants.NL))
self.assertSent(expected, self.connection.req, b'message_id', 10)
def test_touch(self):
'''Appropriately sends touch'''
expected = b''.join((constants.TOUCH, b' message_id', constants.NL))
self.assertSent(expected, self.connection.touch, b'message_id')
def test_cls(self):
'''Appropriately sends cls'''
expected = b''.join((constants.CLS, constants.NL))
self.assertSent(expected, self.connection.cls)
def test_nop(self):
'''Appropriately sends nop'''
expected = b''.join((constants.NOP, constants.NL))
self.assertSent(expected, self.connection.nop)
# Some tests very closely aimed at identification
def test_calls_identified(self):
'''Upon getting an identification response, we call 'identified'''
with mock.patch.object(
connection.Connection, 'identified') as mock_identified:
self.connect({'foo': 'bar'})
self.assertTrue(mock_identified.called)
def test_identified_tolerates_ok(self):
'''The identified handler tolerates OK responses'''
res = mock.Mock(data='OK')
self.assertEqual(self.connection.identified(res).data, 'OK')
def test_identify_defaults(self):
'''Identify provides default options'''
self.assertEqual(self.connection._identify_options, {
'feature_negotiation': True,
'long_id': socket.getfqdn(),
'short_id': socket.gethostname(),
'user_agent': self.connection.USER_AGENT
})
def test_identify_override_defaults(self):
'''Identify allows us to override defaults'''
with mock.patch('nsq.connection.Connection.connect'):
conn = connection.Connection('host', 0, long_id='not-your-fqdn')
self.assertEqual(conn._identify_options['long_id'], 'not-your-fqdn')
def test_identify_tls_unsupported(self):
'''Raises an exception about the lack of TLS support'''
with mock.patch('nsq.connection.TLSSocket', None):
self.assertRaises(exceptions.UnsupportedException,
connection.Connection, 'host', 0, tls_v1=True)
def test_identify_snappy_unsupported(self):
'''Raises an exception about the lack of snappy support'''
with mock.patch('nsq.connection.SnappySocket', None):
self.assertRaises(exceptions.UnsupportedException,
connection.Connection, 'host', 0, snappy=True)
def test_identify_deflate_unsupported(self):
'''Raises an exception about the lack of deflate support'''
with mock.patch('nsq.connection.DeflateSocket', None):
self.assertRaises(exceptions.UnsupportedException,
connection.Connection, 'host', 0, deflate=True)
def test_identify_no_deflate_level(self):
'''Raises an exception about the lack of deflate_level support'''
with mock.patch('nsq.connection.DeflateSocket', None):
self.assertRaises(exceptions.UnsupportedException,
connection.Connection, 'host', 0, deflate_level=True)
def test_identify_no_snappy_and_deflate(self):
'''We should yell early about incompatible snappy and deflate options'''
self.assertRaises(exceptions.UnsupportedException,
connection.Connection, 'host', 0, snappy=True, deflate=True)
def test_identify_saves_identify_response(self):
'''Saves the identify response from the server'''
expected = {'foo': 'bar'}
conn = self.connect(expected)
self.assertEqual(conn._identify_response, expected)
def test_identify_saves_max_rdy_count(self):
'''Saves the max ready count if it's provided'''
conn = self.connect({'max_rdy_count': 100})
self.assertEqual(conn.max_rdy_count, 100)
def test_ready_to_reconnect(self):
'''Alias for the reconnection attempt's ready method'''
with mock.patch.object(
self.connection, '_reconnnection_counter') as ctr:
self.connection.ready_to_reconnect()
ctr.ready.assert_called_with()
def test_reconnect_living_socket(self):
'''Don't reconnect a living connection'''
before = self.connection._socket
self.connection.connect()
self.assertEqual(self.connection._socket, before)
def test_connect_socket_error_return_value(self):
'''Socket errors has connect return False'''
self.connection.close()
with mock.patch('nsq.connection.socket') as mock_socket:
mock_socket.socket = mock.Mock(side_effect=socket.error)
self.assertFalse(self.connection.connect())
def test_connect_socket_error_reset(self):
'''Invokes reset if the socket raises an error'''
self.connection.close()
with mock.patch('nsq.connection.socket') as mock_socket:
with mock.patch.object(self.connection, '_reset') as mock_reset:
mock_socket.socket = mock.Mock(side_effect=socket.error)
self.connection.connect()
mock_reset.assert_called_with()
def test_connect_timeout(self):
'''Times out when connection instantiation is too slow'''
socket = self.connection._socket
self.connection.close()
with mock.patch.object(self.connection, '_read', return_value=[]):
with mock.patch.object(self.connection, '_timeout', 0.05):
with mock.patch(
'nsq.connection.socket.socket', return_value=socket):
self.assertFalse(self.connection.connect())
def test_connect_resets_state(self):
'''Upon connection, makes a call to reset its state'''
socket = self.connection._socket
self.connection.close()
with mock.patch.object(self.connection, '_read', return_value=[]):
with mock.patch.object(self.connection, '_reset') as mock_reset:
with mock.patch.object(self.connection, '_timeout', 0.05):
with mock.patch(
'nsq.connection.socket.socket', return_value=socket):
self.connection.connect()
mock_reset.assert_called_with()
def test_close_resets_state(self):
'''On closing a connection, reset its state'''
with mock.patch.object(self.connection, '_reset') as mock_reset:
self.connection.close()
mock_reset.assert_called_with()
def | |
<reponame>lycantropos/symba
import math
from collections import defaultdict
from functools import reduce
from numbers import Real
from typing import (Any,
DefaultDict,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union)
from reprit.base import generate_repr
from .constant import (Constant,
Finite,
NaN,
One,
Zero,
to_expression)
from .expression import Expression
from .hints import SqrtEvaluator
from .term import Term
from .utils import (BASE,
digits_count,
lcm,
positiveness_to_sign,
to_square_free,
transpose)
class Form(Expression):
"""Represents sum of square roots."""
is_finite = True
@classmethod
def from_components(cls,
terms: List[Term],
tail: Finite = Zero) -> Expression:
queue = sorted(terms,
key=abs,
reverse=True)
arguments_scales = (defaultdict
(Finite)) # type: Dict[Expression, Finite]
while queue:
min_term = queue.pop()
min_term_argument = min_term.argument
arguments_scales[min_term_argument] += min_term.scale
next_queue = []
for term in queue:
arguments_ratio = term.argument / min_term_argument
arguments_ratio_sqrt = arguments_ratio.perfect_sqrt()
if arguments_ratio_sqrt.square() == arguments_ratio:
arguments_scales[min_term_argument] += (
term.scale * arguments_ratio_sqrt)
else:
next_queue.append(term)
queue = next_queue
terms = [Term(scale, argument)
for argument, scale in arguments_scales.items()
if scale]
return ((cls(terms, tail) if tail or len(terms) > 1 else terms[0])
if terms
else tail)
__slots__ = 'tail', 'terms'
def __init__(self, terms: List[Term], tail: Finite = Zero) -> None:
self.tail, self.terms = tail, terms
@property
def degree(self) -> int:
return max(term.degree for term in self.terms)
def evaluate(self, sqrt_evaluator: Optional[SqrtEvaluator] = None) -> Real:
return sum([term.evaluate(sqrt_evaluator) for term in self.terms],
self.tail.evaluate(sqrt_evaluator))
def extract_common_denominator(self) -> Tuple[int, 'Form']:
terms_common_denominators, _ = transpose(
[term.extract_common_denominator() for term in self.terms])
tail_denominator, _ = self.tail.extract_common_denominator()
common_denominator = reduce(lcm, terms_common_denominators,
tail_denominator)
return common_denominator, self._scale(Finite(common_denominator))
def extract_common_numerator(self) -> Tuple[int, 'Form']:
terms_common_numerators, _ = transpose(
[term.extract_common_numerator() for term in self.terms])
tail_numerator, _ = self.tail.extract_common_numerator()
common_numerator = reduce(math.gcd, terms_common_numerators,
tail_numerator)
return common_numerator, self / common_numerator
def inverse(self) -> Expression:
common_denominator, integer_form = self.extract_common_denominator()
numerator, denominator = (Factorization(tail=One * common_denominator),
Factorization.from_form(integer_form))
while denominator.factors:
max_factor = max(denominator.factors)
max_factorization = denominator.factors.pop(max_factor)
numerator = numerator.multiply(
denominator
- max_factorization.multiply_by_factor(max_factor))
denominator = (denominator.square()
- max_factorization.square() * max_factor.square())
return numerator.scale_non_zero(denominator.tail.inverse()).express()
def is_positive(self) -> bool:
components = (*self.terms, self.tail) if self.tail else self.terms
positive, negative = [], []
for component in components:
if component.is_positive():
positive.append(component)
else:
negative.append(component)
if not (positive and negative):
return not negative
positive_squares_sum, negative_squares_sum = (
sum(component.square() for component in positive),
sum(component.square() for component in negative))
return ((len(positive) * positive_squares_sum
- negative_squares_sum).is_positive()
and ((positive_squares_sum
- len(negative) * negative_squares_sum).is_positive()
or self.lower_bound() >= 0))
def lower_bound(self) -> Real:
common_denominator, form = self.extract_common_denominator()
scale = BASE ** form.significant_digits_count()
return (sum([(scale * term).lower_bound() for term in form.terms],
(scale * form.tail).lower_bound())
/ (common_denominator * scale))
def perfect_sqrt(self) -> Expression:
if self.degree != 1:
raise ValueError('Unsupported value: {!r}.'.format(self))
denominator, integer_form = self.extract_common_denominator()
if not self.tail:
arguments_gcd = form_arguments_gcd(integer_form)
if arguments_gcd != 1:
common_term = Term(One, Finite(arguments_gcd))
normalized_form = integer_form / common_term
normalized_sqrt = normalized_form.perfect_sqrt()
if normalized_sqrt.square() == normalized_form:
return (Term(One / denominator, common_term)
* normalized_sqrt)
elif len(self.terms) == 1:
term, = integer_form.terms
discriminant = integer_form.tail.square() - term.square()
if discriminant.is_positive():
# checking if the form can be represented as
# ``(a * sqrt(x) + b * sqrt(y)) ** 2``,
# where
# ``a, b, x, y`` are rational,
# ``x, y`` are non-equal
discriminant_sqrt = discriminant.perfect_sqrt()
if discriminant_sqrt.square() == discriminant:
scale = One / denominator
return (positiveness_to_sign(term.is_positive())
* Term.from_components(scale,
(integer_form.tail
- discriminant_sqrt) / 2)
+ Term.from_components(scale,
(integer_form.tail
+ discriminant_sqrt) / 2))
else:
# checking if the form can be represented as
# ``((sqrt(a) + b * sqrt(c)) * sqrt(sqrt(x))) ** 2``,
# where
# ``a, b, c, x`` are non-zero rational,
# ``a, c, x`` are positive,
# ``a, c`` are non-equal,
# ``a * c`` is a perfect square
discriminant /= -term.argument
discriminant_sqrt = discriminant.perfect_sqrt()
if discriminant_sqrt.square() == discriminant:
scale = One / denominator
sub_term = Term(One, term.argument)
return (positiveness_to_sign(self.tail.is_positive())
* Term(scale,
(term.scale - discriminant_sqrt) / 2
* sub_term)
+ Term(scale,
(term.scale + discriminant_sqrt) / 2
* sub_term))
else:
lesser_part, greater_part = split_form(integer_form)
discriminant = greater_part.square() - lesser_part.square()
if discriminant.is_positive():
discriminant_is_constant = not discriminant.degree
discriminant_sqrt = (Term.from_components(One, discriminant)
if discriminant_is_constant
else discriminant.perfect_sqrt())
if (discriminant_is_constant
or discriminant_sqrt.square() == discriminant):
addend = greater_part + discriminant_sqrt
if (addend.degree < self.degree
or (len(addend.terms) + bool(addend.tail)
< len(self.terms) + bool(self.tail))):
return ((addend + lesser_part)
/ Term.from_components(Finite(denominator),
2 * addend))
common_denominator, integer_form = self.extract_common_denominator()
common_numerator, _ = integer_form.extract_common_numerator()
return (Finite(common_numerator) / common_denominator).perfect_sqrt()
def significant_digits_count(self) -> int:
return (max(max(term.significant_digits_count()
for term in self.terms),
self.tail.significant_digits_count())
+ digits_count(len(self.terms) + bool(self.tail)) + 1)
def square(self) -> Expression:
terms = ([(2 * self.tail) * term for term in self.terms]
if self.tail
else [])
tail = (self.tail.square()
+ _sift_components([2 * (self.terms[step] * self.terms[index])
for step in range(1, len(self.terms))
for index in range(step)]
+ [term.square() for term in self.terms],
terms))
return Form.from_components(terms, tail)
def upper_bound(self) -> Real:
common_denominator, form = self.extract_common_denominator()
scale = BASE ** form.significant_digits_count()
return (sum([(scale * term).upper_bound() for term in form.terms],
(scale * form.tail).upper_bound())
/ (common_denominator * scale))
def __add__(self, other: Union[Real, Expression]) -> Expression:
return (self._add_constant(other)
if isinstance(other, (Real, Constant))
else (self._add_term(other)
if isinstance(other, Term)
else (Form.from_components(self.terms + other.terms,
self.tail + other.tail)
if isinstance(other, Form)
else NotImplemented)))
def __eq__(self, other: Any) -> Any:
return (self is other
or (self.tail == other.tail
and len(self.terms) == len(other.terms)
and set(self.terms) == set(other.terms))
if isinstance(other, Form)
else (False
if isinstance(other, (Real, Expression))
else NotImplemented))
def __hash__(self) -> int:
return hash((frozenset(self.terms), self.tail))
def __mul__(self, other: Union[Real, Expression]) -> Expression:
return (self._multiply_by_constant(other)
if isinstance(other, (Real, Constant))
else (self._multiply_by_term(other)
if isinstance(other, Term)
else (self._multiply_by_form(other)
if isinstance(other, Form)
else NotImplemented)))
def __neg__(self) -> 'Form':
return Form([-term for term in self.terms],
tail=-self.tail)
def __radd__(self, other: Union[Real, Expression]) -> Expression:
return (self._add_constant(other)
if isinstance(other, (Real, Constant))
else (self._add_term(other)
if isinstance(other, Term)
else NotImplemented))
__repr__ = generate_repr(__init__)
def __rmul__(self, other: Union[Real, Expression]) -> Expression:
return (self._multiply_by_constant(other)
if isinstance(other, (Real, Constant))
else (self._multiply_by_term(other)
if isinstance(other, Term)
else NotImplemented))
def __str__(self) -> str:
return (str(self.terms[0])
+ (' ' + ' '.join(map(_to_signed_value, self.terms[1:]))
if len(self.terms) > 1
else '')
+ (' ' + _to_signed_value(self.tail)
if self.tail
else ''))
def _add_constant(self, other: Union[Real, Constant]) -> 'Form':
tail = self.tail + other
return ((Form(self.terms, tail)
if tail or len(self.terms) > 1
else self.terms[0])
if tail.is_finite
else tail)
def _add_term(self, other: Term) -> Expression:
return Form.from_components(self.terms + [other], self.tail)
def _multiply_by_constant(self,
other: Union[Real, Constant]) -> Expression:
other = to_expression(other)
return ((self._scale(other) if other else other)
if other.is_finite
else (other if other is NaN or self.is_positive() else -other))
def _multiply_by_form(self, other: 'Form') -> Expression:
if self == other:
return self.square()
tail, other_tail = self.tail, other.tail
terms = (([term * other_tail for term in self.terms]
if other_tail
else [])
+ ([other_term * tail for other_term in other.terms]
if tail
else []))
tail = (tail * other_tail
+ _sift_components([term * other_term
for term in self.terms
for other_term in other.terms],
terms))
return Form.from_components(terms, tail)
def _multiply_by_term(self, other: Term) -> Expression:
terms = [other * self.tail] if self.tail else []
return Form(terms,
_sift_components([term * other for term in self.terms],
terms))
def _scale(self, other: Finite) -> 'Form':
return (self
if other == One
else Form([term * other for term in self.terms],
self.tail * other))
def form_arguments_gcd(integer_form: Form) -> int:
result, _, coprime_indices = _split_integers(
[term.argument.value.numerator
for term in sorted(integer_form.terms,
key=_term_key)])
return 1 if coprime_indices else result
def split_form(integer_form: Form) -> Tuple[Form, Form]:
terms = integer_form.terms
if len(terms) == 3:
return Form(terms[1:]), Form([terms[0]], integer_form.tail)
surds, terms = zip(*sorted(
[(to_square_free(term.argument.value.numerator), term)
for term in terms]))
cocomposite_indices, coprime_indices = split_integers(surds)
return ((Form([terms[index] for index in cocomposite_indices]),
Form([terms[index] for index in coprime_indices],
integer_form.tail)))
def split_integers(values: Sequence[int]) -> Tuple[List[int], List[int]]:
gcd, cocomposite_indices, coprime_indices = _split_integers(values)
if not coprime_indices:
_, cocomposite_indices, coprime_indices = _split_integers(
value // gcd for value in values)
return cocomposite_indices, coprime_indices
def _split_integers(integers: Iterable[int]
) -> Tuple[int, List[int], List[int]]:
iterator = iter(integers)
gcd = next(iterator)
cocomposite_indices, coprime_indices, gcd, start = (
([1], [0], next(iterator), 2) if gcd == 1 else ([0], [], gcd, 1))
for index, value in enumerate(iterator,
start=start):
value_gcd = math.gcd(gcd, value)
if value_gcd == 1:
coprime_indices.append(index)
else:
gcd = value_gcd
cocomposite_indices.append(index)
return gcd, cocomposite_indices, coprime_indices
class Factor:
__slots__ = 'argument', 'degree', '_term'
def __init__(self, argument: Expression, degree: int) -> None:
self.argument, self.degree = argument, degree
term = argument
for _ in range(degree):
term = | |
ave will average the outputs, used in the output layer
def __init__(self,
adjancy,
input_dim, output_dim,
activation_func,
name,
total_nodes,
attention_head = 1,
dropout_prob = None,
bias = False,
sparse = False,
row = None,
col = None,
indices = None,
num_nodes = None,
aggregate_mode = 'concate'):
super(GraphAttentionLayer, self).__init__(
input_dim, output_dim,
activation_func,
name,
dropout_prob,
bias,
sparse
)
self.adjancy = adjancy
self.attention_head = attention_head
self.aggregate_mode = aggregate_mode
self.total_nodes = total_nodes
self.row = row
self.col = col
self.num_nodes = num_nodes
self.indices = indices
#Define layer's variables
#The number of weights and attention is equal to the number of attention heads
self.weights = []
self.att_i_weights = []
self.att_j_weights = []
with tf.variable_scope(self.name + '_var'):
#Add weights and attention
for i in range(self.attention_head):
tmp_weight = glort_init([self.input_dim, self.output_dim], name = 'weights_' + str(i))
self.weights.append(tmp_weight)
tmp_i = tf.zeros([output_dim, 1], name = 'attention_' + str(i))
tmp_j = tf.zeros([output_dim, 1], name = 'attention_' + str(i))
self.att_i_weights.append(tmp_i)
self.att_j_weights.append(tmp_j)
self.weight_decay_vars.append(tmp_weight)
self.weight_decay_vars.append(tmp_i)
self.weight_decay_vars.append(tmp_j)
#if bias is used
if self.bias:
if aggregate_mode == 'concate':
self.bias = tf.zeros([output_dim*attention_head], name = 'bias')
elif aggregate_mode == 'ave':
self.bias = tf.zeros([output_dim], name = 'bias')
else:
raise "Invalid value for aggregate_mode"
def run(self, inputs, num_features_nonzero):
#
#Inputs are features or the output passed by the previous layer
#This will connect each layers into one compution graph
#
#Note, sparse drop is not implemented
#Since we assume that no dropout is implemented and the output of a layer is dense matrix
#Drop out to input can be implemented befor it is feeded to the train function
def lrelu(x, alpha):
return tf.nn.relu(x) - alpha * tf.nn.relu(-x)
if not self.dropout_prob:
pass
else:
if self.sparse:
inputs = sparse_dropout(inputs, 1 - self.dropout_prob, num_features_nonzero)
else:
inputs = tf.nn.dropout(inputs, 1 - self.dropout_prob)
#Do the calculation
trans_feature = []
if self.sparse:
for i in range(self.attention_head):
tmp_value = tf.sparse_tensor_dense_matmul(inputs, self.weights[i])
trans_feature.append(tmp_value)
else:
#Directly compute WX_T
for i in range(self.attention_head):
trans_feature.append(tf.matmul(inputs, self.weights[i]))
#Compute a_T[Wh_i||Wh_j]
#Note the concatention is calculted later
#AWX_T_1 is the front part of the multiplication
#AWX_T_2 is the back part of the multiplicationh
#each of them is a #NODE vector
att_i_list = []
att_j_list = []
for i in range(self.attention_head):
tmp_i = tf.matmul(trans_feature[i], self.att_i_weights[i])
tmp_j = tf.matmul(trans_feature[i], self.att_j_weights[i])
tmp_i = tf.contrib.layers.bias_add(tmp_i)
tmp_j = tf.contrib.layers.bias_add(tmp_j)
att_i_list.append(tmp_i)
att_j_list.append(tmp_j)
att_coffe_list = []
for i in range(self.attention_head):
att_coffe = tf.gather(att_i_list[i], self.row) + \
tf.gather(att_j_list[i], self.col)
att_coffe = tf.squeeze(att_coffe)
att_coffe_list.append(att_coffe)
att_coffe_mat_list = []
for i in range(self.attention_head):
att_coffe_mat = tf.SparseTensor(
indices=self.indices,
values=lrelu(att_coffe_list[i], alpha=0.2),
dense_shape=(self.num_nodes, self.num_nodes)
)
att_coffe_mat = tf.sparse_softmax(att_coffe_mat)
att_coffe_mat_list.append(att_coffe_mat)
output = []
for i in range(self.attention_head):
cur_output = tf.sparse_tensor_dense_matmul(att_coffe_mat_list[i], trans_feature[i])
if self.bias != None:
cur_output = tf.contrib.layers.bias_add(cur_output)
output.append(cur_output)
if self.aggregate_mode == 'concate':
#Concate the matrix
output = tf.concat(output, axis = 1)
elif self.aggregate_mode == 'ave':
#Ave over output_matrix
len_output = len(output)
output = tf.add_n(output)
output = output/len_output
else:
raise "aggregate_mode has a invalid value"
#acitvation
return self.activation_func(output)
class DiffusionLayer(BaseLayer):
'''
First Cheb Layer
Note that the adjancy matrix is not normalized
'''
def __init__(self,
adjancy,
input_dim, output_dim,
activation_func,
name,
dropout_prob = None,
bias = False,
sparse = False,
num_nodes = False,
hops = 3):
super(DiffusionLayer, self).__init__(
input_dim, output_dim,
activation_func,
name,
dropout_prob,
bias,
sparse
)
self.adjancy = adjancy
self.hops = hops
self.num_nodes = num_nodes
#Define layer's variables
with tf.variable_scope(self.name + '_var'):
self.weight_c = glort_init([self.hops, input_dim], name = 'weight_c')
self.weight_d = glort_init([self.hops * input_dim, output_dim], name = 'weight_d')
self.weight_decay_vars.append(self.weight_c)
self.weight_decay_vars.append(self.weight_d)
#if bias is used
if self.bias:
self.bias = tf.zeros([output_dim], name = 'bias')
self.weight_decay_vars.append(self.bias)
def run(self, inputs, num_features_nonzero):
'''
Inputs are features or the output passed by the previous layer
This will connect each layers into one compution graph
'''
#Note, sparse drop is not implemented
#Since we assume that no dropout is implemented and the output of a layer is dense matrix
#Drop out to input can be implemented befor it is feeded to the train function
if not self.dropout_prob:
pass
else:
if self.sparse:
inputs = sparse_dropout(inputs, 1 - self.dropout_prob, num_features_nonzero)
inputs = tf.sparse_to_dense(inputs.indices, inputs.dense_shape, inputs.values)
else:
inputs = tf.nn.dropout(inputs, 1 - self.dropout_prob)
#Shape Nt * H * Nt
pt_series = create_power_series(self.adjancy, self.hops, sparse=True)
#compute P_X
#dim (Nt*H*Nt) * (Nt*F)
pt_series.set_shape((self.num_nodes, self.hops, self.num_nodes))
inputs.set_shape((self.num_nodes, self.input_dim))
P_X = tf.einsum('ijk,kl->ijl', pt_series , inputs)
#compute W_c (element-wise product) P_X
WPX = P_X * self.weight_c
WPX = tf.nn.tanh(WPX)
#flatten, let Z be a two-dim matrix Nt*(H*F)
Z = tf.contrib.layers.flatten(WPX)
print(Z)
print(self.weight_d)
print(self.bias)
output = tf.matmul(Z, self.weight_d)
#bias
if self.bias != None:
output += self.bias
#acitvation
return self.activation_func(output)
'''
class SpectralCNNLayer(BaseLayer):
#Dense Layer
def __init__(self,
eigenvalue_matrix,
input_dim, output_dim,
activation_func,
name,
dropout_prob = None,
bias = False,
sparse = False,
total_nodes = None):
super(SpectralCNNLayer, self).__init__(
input_dim, output_dim,
activation_func,
name,
dropout_prob,
bias,
sparse
)
self.ei_mat = eigenvalue_matrix
self.total_nodes = total_nodes
#Define layer's variables
with tf.variable_scope(self.name + '_var'):
self.weights_list = []
for i in range(output_dim):
self.weights_list.append(glort_init([total_nodes, input_dim], name = 'weights' + str(i)))
#Stack self.weights as a single three-dim vector
self.weights = tf.stack(self.weights_list, axis=0)
#if bias is used
if self.bias:
self.bias = tf.zeros([output_dim], name = 'bias')
def run(self, inputs, num_features_nonzero):
#Inputs are features or the output passed by the previous layer
#This will connect each layers into one compution graph
#Note, sparse drop is not implemented
#Since we assume that no dropout is implemented and the output of a layer is dense matrix
#Drop out to input can be implemented befor it is feeded to the train function
if not self.dropout_prob:
pass
else:
if self.sparse:
inputs = sparse_dropout(inputs, 1 - self.dropout_prob, num_features_nonzero)
else:
inputs = tf.nn.dropout(inputs, 1 - self.dropout_prob)
#Do the calculation
if self.sparse:
X_TV = tf.sparse_tensor_dense_matmul(tf.sparse.transpose(inputs), self.ei_mat)
V_TX = tf.transpose(X_TV)
else:
V_TX = tf.matmul(tf.transpose(self.ei_mat), inputs)
WV_TX = V_TX * self.weights
output = tf.einsum('jk,ikl->ijl', self.ei_mat , WV_TX)
#Output shape is output_dim, total_nodes, input_dim
#Add over input features
#output_dim, total_nodes
#Add over total_nodes
output = tf.reduce_sum(output, 2)
output = tf.transpose(output)
#bias
if self.bias != None:
output += self.bias
#acitvation
return self.activation_func(output)
'''
class SpectralCNNLayer(BaseLayer):
'''
Dense Layer
'''
def __init__(self,
eigenvalue_matrix,
input_dim, output_dim,
activation_func,
name,
dropout_prob = None,
bias = False,
sparse = False,
total_nodes = None):
super(SpectralCNNLayer, self).__init__(
input_dim, output_dim,
activation_func,
name,
dropout_prob,
bias,
sparse
)
self.ei_mat = eigenvalue_matrix
self.total_nodes = total_nodes
#Define layer's variables
with tf.variable_scope(self.name + '_var'):
self.weights=glort_init([input_dim, output_dim], name = 'weights')
self.weight_decay_vars.append(self.weights)
#if bias is used
if self.bias:
self.bias = tf.zeros([output_dim], name = 'bias')
self.weight_decay_vars.append(self.bias)
def run(self, inputs, num_features_nonzero):
'''
Inputs are features or the output passed by the previous layer
This will connect each layers into one compution graph
'''
#Note, sparse drop is not implemented
#Since we assume that no dropout is implemented and the output of a layer is dense matrix
#Drop out to input can be implemented befor it is feeded to the train function
if not self.dropout_prob:
pass
else:
if self.sparse:
inputs = sparse_dropout(inputs, 1 - self.dropout_prob, num_features_nonzero)
else:
inputs = tf.nn.dropout(inputs, 1 - self.dropout_prob)
if self.sparse:
XW = tf.sparse_tensor_dense_matmul(inputs, self.weights)
else:
XW = tf.matmul(inputs, self.weights)
V_TXW = tf.matmul(tf.transpose(self.ei_mat), XW)
'''
#Do the calculation
if self.sparse:
X_TV = tf.sparse_tensor_dense_matmul(tf.sparse.transpose(inputs), self.ei_mat)
V_TX = tf.transpose(X_TV)
else:
V_TX = tf.matmul(tf.transpose(self.ei_mat), inputs)
V_TXW = tf.matmul(V_TX, self.weights)
'''
output = tf.matmul(self.ei_mat , V_TXW)
#Output shape is output_dim, total_nodes, input_dim
#Add over input features
#output_dim, total_nodes
#Add over total_nodes
#bias
if self.bias != None:
output += self.bias
#acitvation
return self.activation_func(output)
class ChebLayer(BaseLayer):
'''
ChebLayer: Compute cheblayer
'''
def __init__(self,
adjancy,
input_dim, output_dim,
activation_func,
name,
dropout_prob = None,
bias = False,
sparse = False,
poly_order = None,
):
super(ChebLayer, self).__init__(
input_dim, output_dim,
activation_func,
name,
dropout_prob,
bias,
sparse
)
self.adjancy = adjancy
self.poly_order = poly_order
#Compute the cheb polynimials
self.series = self.adjancy
#Define layer's variables
self.weights_list = []
with tf.variable_scope(self.name + '_var'):
for i in range(self.poly_order):
tmp = glort_init([self.input_dim, self.output_dim], name = 'weights' + str(i))
self.weights_list.append(tmp)
self.weight_decay_vars.append(tmp)
#if bias is used
if self.bias:
self.bias = tf.zeros([output_dim], name = 'bias')
self.weight_decay_vars.append(self.bias)
def run(self, inputs, num_features_nonzero):
'''
Inputs are features or the output passed by the previous layer
This will connect each layers | |
""" Bifurcation point classes. Each class locates and processes bifurcation points.
* _BranchPointFold is a version based on BranchPoint location algorithms
* BranchPoint: Branch process is broken (can't find alternate branch -- see MATCONT notes)
<NAME>, March 2006
"""
from __future__ import absolute_import, print_function
from .misc import *
from PyDSTool.common import args
from .TestFunc import DiscreteMap, FixedPointMap
from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, \
subtract, divide, transpose, eye, real, imag, \
conjugate, average
from scipy import optimize, linalg
from numpy import dot as matrixmultiply
from numpy import array, float, complex, int, float64, complex64, int32, \
zeros, divide, subtract, reshape, argsort, nonzero
#####
_classes = ['BifPoint', 'BPoint', 'BranchPoint', 'FoldPoint', 'HopfPoint',
'BTPoint', 'ZHPoint', 'CPPoint',
'BranchPointFold', '_BranchPointFold', 'DHPoint',
'GHPoint', 'LPCPoint', 'PDPoint', 'NSPoint', 'SPoint']
__all__ = _classes
#####
class BifPoint(object):
def __init__(self, testfuncs, flagfuncs, label='Bifurcation', stop=False):
self.testfuncs = []
self.flagfuncs = []
self.found = []
self.label = label
self.stop = stop
self.data = args()
if not isinstance(testfuncs, list):
testfuncs = [testfuncs]
if not isinstance(flagfuncs, list):
flagfuncs = [flagfuncs]
self.testfuncs.extend(testfuncs)
self.flagfuncs.extend(flagfuncs)
self.tflen = len(self.testfuncs)
def locate(self, P1, P2, C):
pointlist = []
for i, testfunc in enumerate(self.testfuncs):
if self.flagfuncs[i] == iszero:
for ind in range(testfunc.m):
X, V = testfunc.findzero(P1, P2, ind)
pointlist.append((X,V))
X = average([point[0] for point in pointlist], axis=0)
V = average([point[1] for point in pointlist], axis=0)
C.Corrector(X,V)
return X, V
def process(self, X, V, C):
data = args()
data.X = todict(C, X)
data.V = todict(C, V)
self.found.append(data)
def info(self, C, ind=None, strlist=None):
if ind is None:
ind = list(range(len(self.found)))
elif isinstance(ind, int):
ind = [ind]
if C.verbosity >= 1:
print(self.label + ' Point found ')
if C.verbosity >= 2:
print('========================== ')
for n, i in enumerate(ind):
print(n, ': ')
Xd = self.found[i].X
for k, j in Xd.items():
print(k, ' = ', j)
print('')
if hasattr(self.found[i], 'eigs'):
print('Eigenvalues = \n')
for x in self.found[i].eigs:
print(' (%f,%f)' % (x.real, x.imag))
print('\n')
if strlist is not None:
for string in strlist:
print(string)
print('')
class SPoint(BifPoint):
"""Special point that represents user-selected free parameter values."""
def __init__(self, testfuncs, flagfuncs, stop=False):
BifPoint.__init__(self, testfuncs, flagfuncs, 'S', stop=stop)
def process(self, X, V, C):
BifPoint.process(self, X, V, C)
self.info(C, -1)
return True
class BPoint(BifPoint):
"""Special point that represents boundary of computational domain."""
def __init__(self, testfuncs, flagfuncs, stop=False):
BifPoint.__init__(self, testfuncs, flagfuncs, 'B', stop=stop)
def locate(self, P1, P2, C):
# Find location that triggered testfunc and initialize testfunc to that index
val1 = (P1[0]-self.testfuncs[0].lower)*(self.testfuncs[0].upper-P1[0])
val2 = (P2[0]-self.testfuncs[0].lower)*(self.testfuncs[0].upper-P2[0])
ind = nonzero(val1*val2 < 0)
self.testfuncs[0].ind = ind
self.testfuncs[0].func = self.testfuncs[0].one
X, V = BifPoint.locate(self, P1, P2, C)
# Set testfunc back to monitoring all
self.testfuncs[0].ind = None
self.testfuncs[0].func = self.testfuncs[0].all
return X, V
def process(self, X, V, C):
BifPoint.process(self, X, V, C)
self.info(C, -1)
return True
def info(self, C, ind=None):
if ind is None:
ind = list(range(len(self.found)))
elif isinstance(ind, int):
ind = [ind]
BifPoint.info(self, C, ind)
class BranchPoint(BifPoint):
"""May only work for EquilibriumCurve ... (needs fixing)"""
def __init__(self, testfuncs, flagfuncs, stop=False):
BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop)
def __locate_newton(self, X, C):
"""x[0:self.dim] = (x,alpha)
x[self.dim] = beta
x[self.dim+1:2*self.dim] = p
"""
J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords)
J_params = C.CorrFunc.jac(X[0:C.dim], C.params)
return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \
matrixmultiply(transpose(J_coords),X[C.dim+1:]), \
matrixmultiply(transpose(X[C.dim+1:]),J_params), \
matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1]
def locate(self, P1, P2, C):
# Initiliaze p vector to eigenvector with smallest eigenvalue
X, V = P1
X2, V2 = P2
J_coords = C.CorrFunc.jac(X, C.coords)
W, VL = linalg.eig(J_coords, left=1, right=0)
ind = argsort([abs(eig) for eig in W])[0]
p = real(VL[:,ind])
initpoint = zeros(2*C.dim, float)
initpoint[0:C.dim] = X
initpoint[C.dim+1:] = p
X = optimize.fsolve(self.__locate_newton, initpoint, C)
self.data.psi = X[C.dim+1:]
X = X[0:C.dim]
V = 0.5*(V+V2)
return X, V
def process(self, X, V, C):
BifPoint.process(self, X, V, C)
# Finds the new branch
J_coords = C.CorrFunc.jac(X, C.coords)
J_params = C.CorrFunc.jac(X, C.params)
singular = True
perpvec = r_[1,zeros(C.dim-1)]
d = 1
while singular and d <= C.dim:
try:
v0 = linalg.solve(r_[c_[J_coords, J_params],
[perpvec]], \
r_[zeros(C.dim-1),1])
except:
perpvec = r_[0., perpvec[0:(C.dim-1)]]
d += 1
else:
singular = False
if singular:
raise PyDSTool_ExistError("Problem in _compute: Failed to compute tangent vector.")
v0 /= linalg.norm(v0)
V = sign([x for x in v0 if abs(x) > 1e-8][0])*v0
A = r_[c_[J_coords, J_params], [V]]
W, VR = linalg.eig(A)
W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5]
V1 = real(VR[:,W0[0]])
H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params)
c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])])
c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])])
c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])])
beta = 1
alpha = -1*c22/(2*c12)
V1 = alpha*V + beta*V1
V1 /= linalg.norm(V1)
self.found[-1].eigs = W
self.found[-1].branch = todict(C, V1)
self.info(C, -1)
return True
def info(self, C, ind=None):
if ind is None:
ind = list(range(len(self.found)))
elif isinstance(ind, int):
ind = [ind]
strlist = []
for n, i in enumerate(ind):
strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \
tocoords(C, self.found[i].branch))))
X = tocoords(C, self.found[-1].X)
V = tocoords(C, self.found[-1].V)
C._preTestFunc(X, V)
strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0]))
BifPoint.info(self, C, ind, strlist)
class FoldPoint(BifPoint):
def __init__(self, testfuncs, flagfuncs, stop=False):
BifPoint.__init__(self, testfuncs, flagfuncs, 'LP', stop=stop)
def process(self, X, V, C):
BifPoint.process(self, X, V, C)
# Compute normal form coefficient
# NOTE: These are for free when using bordering technique!)
# NOTE: Does not agree with MATCONT output! (if |p| = |q| = 1, then it does)
J_coords = C.CorrFunc.jac(X, C.coords)
W, VL, VR = linalg.eig(J_coords, left=1, right=1)
minW = min(abs(W))
ind = [(abs(eig) < minW+1e-8) and (abs(eig) > minW-1e-8) for eig in W].index(True)
p, q = real(VL[:,ind]), real(VR[:,ind])
p /= matrixmultiply(p,q)
B = C.CorrFunc.hess(X, C.coords, C.coords)
self.found[-1].a = abs(0.5*matrixmultiply(p,[bilinearform(B[i,:,:], q, q) for i in range(B.shape[0])]))
self.found[-1].eigs = W
numzero = len([eig for eig in W if abs(eig) < 1e-4])
if numzero > 1:
if C.verbosity >= 2:
print('Fold-Fold!\n')
del self.found[-1]
return False
elif numzero == 0:
if C.verbosity >= 2:
print('False positive!\n')
del self.found[-1]
return False
if C.verbosity >= 2:
print('\nChecking...')
print(' |q| = %f' % linalg.norm(q))
print(' <p,q> = %f' % matrixmultiply(p,q))
print(' |Aq| = %f' % linalg.norm(matrixmultiply(J_coords,q)))
print(' |transpose(A)p| = %f\n' % linalg.norm(matrixmultiply(transpose(J_coords),p)))
self.info(C, -1)
return True
def info(self, C, ind=None):
if ind is None:
ind = list(range(len(self.found)))
elif isinstance(ind, int):
ind = [ind]
strlist = []
for n, i in enumerate(ind):
strlist.append('a = ' + repr(self.found[i].a))
BifPoint.info(self, C, ind, strlist)
class HopfPoint(BifPoint):
def __init__(self, testfuncs, flagfuncs, stop=False):
BifPoint.__init__(self, testfuncs, flagfuncs, 'H', stop=stop)
def process(self, X, V, C):
"""Tolerance for eigenvalues a possible problem when checking for neutral saddles."""
BifPoint.process(self, X, V, C)
J_coords = C.CorrFunc.jac(X, C.coords)
eigs, LV, RV = linalg.eig(J_coords,left=1,right=1)
# Check for neutral saddles
found = False
for i in range(len(eigs)):
if abs(imag(eigs[i])) < 1e-5:
for j in range(i+1,len(eigs)):
if C.verbosity >= 2:
if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5:
print('Fold-Fold point found in Hopf!\n')
elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5:
print('Neutral saddle found!\n')
elif abs(real(eigs[i])) < 1e-5:
for j in range(i+1, len(eigs)):
if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5:
found = True
w = abs(imag(eigs[i]))
if imag(eigs[i]) > 0:
p = conjugate(LV[:,j])/linalg.norm(LV[:,j])
q = RV[:,i]/linalg.norm(RV[:,i])
else:
p = conjugate(LV[:,i])/linalg.norm(LV[:,i])
q = RV[:,j]/linalg.norm(RV[:,j])
if not found:
del self.found[-1]
return False
direc = conjugate(1/matrixmultiply(conjugate(p),q))
p = direc*p
# Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4])
#print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \
# w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q))))
self.found[-1].w = w
self.found[-1].l1 = firstlyapunov(X, C.CorrFunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2))
self.found[-1].eigs = eigs
self.info(C, -1)
return True
def info(self, C, ind=None):
if ind is None:
ind = list(range(len(self.found)))
elif isinstance(ind, int):
ind = [ind]
strlist = []
for n, i in enumerate(ind):
strlist.append('w = ' + repr(self.found[i].w))
strlist.append('l1 = ' + repr(self.found[i].l1))
BifPoint.info(self, C, ind, strlist)
# Codimension-2 bifurcations
class BTPoint(BifPoint):
def __init__(self, testfuncs, flagfuncs, stop=False):
BifPoint.__init__(self, testfuncs, flagfuncs, 'BT', stop=stop)
def process(self, X, V, C):
BifPoint.process(self, X, V, C)
J_coords = C.CorrFunc.sysfunc.jac(X, C.coords)
W, VL, VR = linalg.eig(J_coords, left=1, right=1)
self.found[-1].eigs = W
if C.verbosity >= 2:
if C.CorrFunc.testfunc.data.B.shape[1] == 2:
b = matrixmultiply(transpose(J_coords), C.CorrFunc.testfunc.data.w[:,0])
c = matrixmultiply(J_coords, C.CorrFunc.testfunc.data.v[:,0])
else:
b = C.CorrFunc.testfunc.data.w[:,0]
c = C.CorrFunc.testfunc.data.v[:,0]
print('\nChecking...')
print(' <b,c> = | |
<gh_stars>0
import math
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from easydict import EasyDict as edict
from tensorflow.python.keras import initializers
from visualdet3d.networks.heads.losses import SigmoidFocalLoss, ModifiedSmoothL1Loss
from visualdet3d.networks.heads.anchors import Anchors
from visualdet3d.networks.backbones.resnet import BasicBlock
from visualdet3d.networks.utils import calc_iou, BackProjection, ClipBoxes
from visualdet3d.networks.lib.common import conv3x3, conv_bn_relu
from visualdet3d.networks.lib.blocks import AnchorFlatten
from visualdet3d.networks.lib.fast_utils.hill_climbing import post_opt
# from visualdet3d.networks.lib.ops.deform_conv import deform_conv2d
class AnchorBasedDetection3DHead(layers.Layer):
def __init__(self,
# num_features_in: int=1024,
num_classes: int=3,
num_regression_loss_terms=12,
preprocessed_path: str='',
anchors_cfg: edict=edict(),
layer_cfg: edict=edict(),
loss_cfg: edict=edict(),
test_cfg: edict=edict(),
read_precompute_anchor:bool=True,
name=None):
super(AnchorBasedDetection3DHead, self).__init__(name=name)
self.anchors = Anchors(preprocessed_path=preprocessed_path,
read_config_file=read_precompute_anchor,
**anchors_cfg)
self.num_classes = num_classes
self.num_regression_loss_terms=num_regression_loss_terms
self.decode_before_loss = getattr(loss_cfg, 'decode_before_loss', False)
self.loss_cfg = loss_cfg
self.test_cfg = test_cfg
self.build_loss(**loss_cfg)
self.backprojector = BackProjection()
self.clipper = ClipBoxes()
if getattr(layer_cfg, 'num_anchors', None) is None:
layer_cfg['num_anchors'] = self.anchors.num_anchors
self.init_layers(**layer_cfg)
def init_layers(self,
# num_features_in,
num_anchors: int,
num_cls_output: int,
num_reg_output: int,
cls_feature_size: int=1024,
reg_feature_size: int=1024,
**kwargs):
self.cls_feature_extraction = keras.Sequential([
conv3x3(cls_feature_size, padding=1),
layers.Dropout(0.3),
layers.ReLU(),
conv3x3(cls_feature_size, padding=1),
layers.Dropout(0.3),
layers.ReLU(),
conv3x3(num_anchors*num_cls_output,
padding=1,
kernel_initializer=keras.initializers.Zeros(),
bias_initializer=keras.initializers.Zeros()),
AnchorFlatten(num_cls_output),
])
# self.cls_feature_extraction[-2].weight.data.fill_(0)
# self.cls_feature_extraction[-2].bias.data.fill_(0)
self.reg_feature_extraction = keras.Sequential([
# TODO: ModulatedDeformConvPack
# deform_conv2d(reg_feature_size, 3, padding=1),
conv3x3(reg_feature_size, padding=1),
layers.BatchNormalization(),
layers.ReLU(),
conv3x3(reg_feature_size, padding=1),
layers.BatchNormalization(),
layers.ReLU(),
conv3x3(num_anchors*num_reg_output,
padding=1,
kernel_initializer=keras.initializers.Zeros(),
bias_initializer=keras.initializers.Zeros()),
AnchorFlatten(num_reg_output),
])
# TODO:
# self.reg_feature_extraction[-2].weight.data.fill_(0)
# self.reg_feature_extraction[-2].bias.data.fill_(0)
def call(self, inputs):
with tf.name_scope('cls_feature_extraction'):
cls_preds = self.cls_feature_extraction(inputs['features'])
with tf.name_scope('reg_feature_extraction'):
reg_preds = self.reg_feature_extraction(inputs['features'])
return cls_preds, reg_preds
def build_loss(self, focal_loss_gamma=0.0, balance_weight=[0], L1_regression_alpha=9, **kwargs):
self.focal_loss_gamma = focal_loss_gamma
self.balance_weights = tf.constant(balance_weight, dtype=tf.float32)
self.loss_cls = SigmoidFocalLoss(
gamma=focal_loss_gamma,
balance_weights=self.balance_weights,
reduction=tf.keras.losses.Reduction.NONE
)
self.loss_bbox = ModifiedSmoothL1Loss(
L1_regression_alpha,
reduction=tf.keras.losses.Reduction.NONE
)
regression_weight = kwargs.get("regression_weight",
[1 for _ in range(self.num_regression_loss_terms)]) #default 12 only use in 3D
self.regression_weight = tf.constant(regression_weight, dtype=tf.float32)
self.alpha_loss = keras.losses.BinaryCrossentropy(
from_logits=True,
reduction=tf.keras.losses.Reduction.NONE
)
def _assign(self, anchor, annotation,
bg_iou_threshold=0.0,
fg_iou_threshold=0.5,
min_iou_threshold=0.0,
match_low_quality=True,
gt_max_assign_all=True,
**kwargs):
"""
anchor: [N, 4]
annotation: [num_gt, 4]:
"""
N = anchor.shape[0]
num_gt = annotation.shape[0]
assigned_gt_inds = tf.fill((N,), -1)
max_overlaps = tf.zeros((N,), dtype=anchor.dtype)
assigned_labels = tf.fill((N,), -1)
if num_gt == 0:
assigned_gt_inds = tf.fill((N,), 0)
return_dict = dict(
num_gt=num_gt,
assigned_gt_inds=assigned_gt_inds,
max_overlaps=max_overlaps,
labels=assigned_labels
)
return return_dict
IoU = calc_iou(anchor, annotation[:, :4]) # num_anchors x num_annotations
# max for anchor
max_overlaps = tf.reduce_max(IoU, axis=1)
argmax_overlaps = tf.argmax(IoU, axis=1)
# max for gt
gt_max_overlaps = tf.reduce_max(IoU, axis=0)
gt_argmax_overlaps = tf.argmax(IoU, axis=0)
# assign negative
indices = tf.where((max_overlaps >=0) & (max_overlaps < bg_iou_threshold))
updates = tf.zeros(indices.shape[0], dtype=assigned_gt_inds.dtype)
assigned_gt_inds = tf.tensor_scatter_nd_update(assigned_gt_inds, indices, updates)
# assign positive
pos_inds = max_overlaps >= fg_iou_threshold
indices = tf.where(pos_inds)
updates = tf.cast(argmax_overlaps[pos_inds] + 1, dtype=assigned_gt_inds.dtype)
assigned_gt_inds = tf.tensor_scatter_nd_update(assigned_gt_inds, indices, updates)
if match_low_quality:
for i in range(num_gt):
if gt_max_overlaps[i] >= min_iou_threshold:
if gt_max_assign_all:
max_iou_inds = IoU[:, i] == gt_max_overlaps[i]
indices = tf.where(max_iou_inds)
updates = tf.cast(tf.fill(indices.shape[0], i+1), dtype=assigned_gt_inds.dtype)
assigned_gt_inds = tf.tensor_scatter_nd_update(assigned_gt_inds, indices, updates)
else:
indices = tf.reshape(gt_argmax_overlaps, (-1, 1))
updates = tf.cast(tf.fill(indices.shape[0], i+1), dtype=assigned_gt_inds.dtype)
assigned_gt_inds = tf.tensor_scatter_nd_update(assigned_gt_inds, indices, updates)
assigned_labels = tf.cast(tf.fill(N, -1), dtype=assigned_gt_inds.dtype)
pos_inds = tf.cast(tf.squeeze(tf.where(assigned_gt_inds > 0), axis=1), dtype=tf.int32)
if tf.size(pos_inds) > 0:
# assigned_labels[pos_inds] = annotation[assigned_gt_inds[pos_inds] - 1, 4].long()
indices = tf.reshape(pos_inds, (-1, 1))
ann_inds = tf.gather(assigned_gt_inds, pos_inds) - 1
updates = tf.cast(
tf.gather_nd(annotation, tf.stack([ann_inds, tf.fill(ann_inds.shape[0], 4)], axis=1)),
tf.int32
)
# assigned_labels[pos_inds] = tf.cast(annotation[assigned_gt_inds[pos_inds] - 1, 4], tf.int32)
assigned_labels = tf.tensor_scatter_nd_update(assigned_labels, indices, updates)
return_dict = dict(
num_gt=num_gt,
assigned_gt_inds=assigned_gt_inds,
max_overlaps=max_overlaps,
labels=assigned_labels
)
return return_dict
def _encode(self, sampled_anchors, sampled_gt_bboxes, selected_anchors_3d):
assert sampled_anchors.shape[0] == sampled_gt_bboxes.shape[0]
# sampled_anchors = sampled_anchors.float()
sampled_anchors = tf.cast(sampled_anchors, tf.float32)
# sampled_gt_bboxes = sampled_gt_bboxes.float()
sampled_gt_bboxes = tf.cast(sampled_gt_bboxes, tf.float32)
px = (sampled_anchors[..., 0] + sampled_anchors[..., 2]) * 0.5
py = (sampled_anchors[..., 1] + sampled_anchors[..., 3]) * 0.5
pw = sampled_anchors[..., 2] - sampled_anchors[..., 0]
ph = sampled_anchors[..., 3] - sampled_anchors[..., 1]
gx = (sampled_gt_bboxes[..., 0] + sampled_gt_bboxes[..., 2]) * 0.5
gy = (sampled_gt_bboxes[..., 1] + sampled_gt_bboxes[..., 3]) * 0.5
gw = sampled_gt_bboxes[..., 2] - sampled_gt_bboxes[..., 0]
gh = sampled_gt_bboxes[..., 3] - sampled_gt_bboxes[..., 1]
targets_dx = (gx - px) / pw
targets_dy = (gy - py) / ph
# targets_dw = torch.log(gw / pw)
# targets_dh = torch.log(gh / ph)
targets_dw = tf.math.log(gw / pw)
targets_dh = tf.math.log(gh / ph)
targets_cdx = (sampled_gt_bboxes[:, 5] - px) / pw
targets_cdy = (sampled_gt_bboxes[:, 6] - py) / ph
targets_cdz = (sampled_gt_bboxes[:, 7] - selected_anchors_3d[:, 0, 0]) / selected_anchors_3d[:, 0, 1]
targets_cd_sin = (tf.math.sin(sampled_gt_bboxes[:, 11] * 2) - selected_anchors_3d[:, 1, 0]) / selected_anchors_3d[:, 1, 1]
targets_cd_cos = (tf.math.cos(sampled_gt_bboxes[:, 11] * 2) - selected_anchors_3d[:, 2, 0]) / selected_anchors_3d[:, 2, 1]
targets_w3d = (sampled_gt_bboxes[:, 8] - selected_anchors_3d[:, 3, 0]) / selected_anchors_3d[:, 3, 1]
targets_h3d = (sampled_gt_bboxes[:, 9] - selected_anchors_3d[:, 4, 0]) / selected_anchors_3d[:, 4, 1]
targets_l3d = (sampled_gt_bboxes[:, 10] - selected_anchors_3d[:, 5, 0]) / selected_anchors_3d[:, 5, 1]
targets = tf.stack((targets_dx, targets_dy, targets_dw, targets_dh,
targets_cdx, targets_cdy, targets_cdz,
targets_cd_sin, targets_cd_cos,
targets_w3d, targets_h3d, targets_l3d), axis=1)
# stds = targets.new([0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 1, 1, 1, 1, 1, 1])
stds = tf.constant([0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 1, 1, 1, 1, 1, 1])
# targets = targets.div_(stds)
targets = tf.truediv(targets, stds)
targets_alpha_cls = tf.cast(tf.math.cos(sampled_gt_bboxes[:, 11:12]) > 0, tf.float32)
return targets, targets_alpha_cls #[N, 4]
def _decode(self, boxes, deltas, anchors_3d_mean_std, label_index, alpha_score):
std = tf.constant([0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 1, 1, 1, 1, 1, 1], dtype=tf.float32)
widths = boxes[..., 2] - boxes[..., 0]
heights = boxes[..., 3] - boxes[..., 1]
ctr_x = boxes[..., 0] + 0.5 * widths
ctr_y = boxes[..., 1] + 0.5 * heights
dx = deltas[..., 0] * std[0]
dy = deltas[..., 1] * std[1]
dw = deltas[..., 2] * std[2]
dh = deltas[..., 3] * std[3]
pred_ctr_x = ctr_x + dx * widths
pred_ctr_y = ctr_y + dy * heights
pred_w = tf.exp(dw) * widths
pred_h = tf.exp(dh) * heights
pred_boxes_x1 = pred_ctr_x - 0.5 * pred_w
pred_boxes_y1 = pred_ctr_y - 0.5 * pred_h
pred_boxes_x2 = pred_ctr_x + 0.5 * pred_w
pred_boxes_y2 = pred_ctr_y + 0.5 * pred_h
one_hot_mask = tf.cast(tf.one_hot(label_index, anchors_3d_mean_std.shape[1]), tf.bool)
selected_mean_std = anchors_3d_mean_std[one_hot_mask] #[N]
mask = selected_mean_std[:, 0, 0] > 0
cdx = deltas[..., 4] * std[4]
cdy = deltas[..., 5] * std[5]
pred_cx1 = ctr_x + cdx * widths
pred_cy1 = ctr_y + cdy * heights
pred_z = deltas[...,6] * selected_mean_std[:, 0, 1] + selected_mean_std[:,0, 0] #[N, 6]
pred_sin = deltas[...,7] * selected_mean_std[:, 1, 1] + selected_mean_std[:,1, 0]
pred_cos = deltas[...,8] * selected_mean_std[:, 2, 1] + selected_mean_std[:,2, 0]
pred_alpha = tf.math.atan2(pred_sin, pred_cos) / 2.0
pred_w = deltas[...,9] * selected_mean_std[:, 3, 1] + selected_mean_std[:,3, 0]
pred_h = deltas[...,10] * selected_mean_std[:,4, 1] + selected_mean_std[:,4, 0]
pred_l = deltas[...,11] * selected_mean_std[:,5, 1] + selected_mean_std[:,5, 0]
pred_boxes = tf.stack([pred_boxes_x1, pred_boxes_y1, pred_boxes_x2, pred_boxes_y2,
pred_cx1, pred_cy1, pred_z,
pred_w, pred_h, pred_l, pred_alpha], axis=1)
alpha_score_mask = alpha_score[:, 0] < 0.5
alpha_score_inds = tf.cast(tf.squeeze(tf.where(alpha_score_mask), 1), tf.int32)
inds = tf.stack([
alpha_score_inds,
tf.fill(alpha_score_inds.shape[0], pred_boxes.shape[-1]-1)
], axis=1)
# pred_boxes[alpha_score[:, 0] < 0.5, -1] += np.pi
updates = tf.fill(alpha_score_inds.shape[0], tf.constant(math.pi))
pred_boxes = tf.tensor_scatter_nd_add(pred_boxes, inds, updates)
return pred_boxes, mask
def _sample(self, assignment_result, anchors, gt_bboxes):
"""
Pseudo sampling
"""
# pos_inds = torch.nonzero(
# assignment_result['assigned_gt_inds'] > 0, as_tuple=False
# ).unsqueeze(-1).unique()
pos_inds = tf.unique(
tf.squeeze(tf.where(assignment_result['assigned_gt_inds'] > 0), 1))[0]
pos_inds = tf.cast(pos_inds, dtype=tf.int32)
# neg_inds = torch.nonzero(
# assignment_result['assigned_gt_inds'] == 0, as_tuple=False
# ).unsqueeze(-1).unique()
neg_inds = tf.unique(
tf.squeeze(tf.where(assignment_result['assigned_gt_inds'] == 0), 1))[0]
neg_inds = tf.cast(neg_inds, dtype=tf.int32)
# gt_flags = anchors.new_zeros(anchors.shape[0], dtype=torch.uint8) #
gt_flags = tf.zeros(anchors.shape[0], dtype=tf.uint8)
pos_assigned_gt_inds = assignment_result['assigned_gt_inds'] - 1
# if gt_bboxes.numel() == 0:
if tf.size(gt_bboxes) == 0:
# pos_gt_bboxes = gt_bboxes.new_zeros([0, 4])
pos_gt_bboxes = tf.zeros((0, 4), dtype=gt_bboxes.dtype)
else:
gt_inds = tf.gather(pos_assigned_gt_inds, pos_inds)
pos_gt_bboxes = tf.gather(
gt_bboxes,
gt_inds
)
# pos_gt_bboxes = gt_bboxes[pos_assigned_gt_inds[pos_inds], :]
return_dict = dict(
pos_inds=pos_inds,
neg_inds=neg_inds,
# pos_bboxes=anchors[pos_inds],
pos_bboxes=tf.gather(anchors, pos_inds),
# neg_bboxes=anchors[neg_inds],
neg_bboxes=tf.gather(anchors, neg_inds),
pos_gt_bboxes=pos_gt_bboxes,
# pos_assigned_gt_inds=pos_assigned_gt_inds[pos_inds],
pos_assigned_gt_inds=tf.gather(pos_assigned_gt_inds, pos_inds),
)
return return_dict
def _post_process(self, scores, bboxes, labels, P2s):
N = len(scores)
bbox2d = bboxes[:, 0:4]
bbox3d = bboxes[:, 4:] #[cx, cy, z, w, h, l, alpha]
bbox3d_state_3d = self.backprojector(bbox3d, P2s[0]) #[x, y, z, w, h, l, alpha]
for i in range(N):
if bbox3d_state_3d[i, 2] > 3 and labels[i] == 0:
bbox3d[i] = post_opt(
bbox2d[i], bbox3d_state_3d[i], P2s[0],
bbox3d[i, 0], bbox3d[i, 1]
)
bboxes = tf.concat([bbox2d, bbox3d], axis=-1)
return scores, bboxes, labels
def get_anchor(self, img_batch, P2, training=False):
is_filtering = getattr(self.loss_cfg, 'filter_anchor', True)
if not training:
is_filtering = getattr(self.test_cfg, 'filter_anchor', is_filtering)
anchors, useful_mask, anchor_mean_std = self.anchors(img_batch, | |
import os
import re
import itertools
import time
from pycparser import CParser, c_ast
from srcgen.python import PythonModule
from collections import OrderedDict
include_pattern = re.compile(r'^\s*#\s*include\s*[<"](.+?)[">]\s*$', re.IGNORECASE)
define_pattern = re.compile(r'^\s*#\s*define\s+(\w+)(?:\((.*?)\))?\s*(.*)\s*$', re.IGNORECASE)
undef_pattern = re.compile(r'^\s*#\s*undef\s+(\w+)\s*$', re.IGNORECASE)
if_pattern = re.compile(r'^\s*#\s*if\s+(.+)\s*$', re.IGNORECASE)
elif_pattern = re.compile(r'^\s*#\s*if\s+(.+)\s*$', re.IGNORECASE)
else_pattern = re.compile(r'^\s*#\s*else\s*$', re.IGNORECASE)
endif_pattern = re.compile(r'^\s*#\s*endif\s*$', re.IGNORECASE)
ifdef_pattern = re.compile(r'^\s*#\s*ifdef\s+(\w+)\s*$', re.IGNORECASE)
ifndef_pattern = re.compile(r'^\s*#\s*ifndef\s+(\w+)\s*$', re.IGNORECASE)
ml_comment_pattern = re.compile(r'/\*.*?\*/', re.DOTALL)
sl_comment_pattern = re.compile(r'//.*?\n')
delimiters = re.compile(r'''([!%^&*()[\]{}<>;,:+\-/?:\s"'|=])''')
identifier_pattern = re.compile(r'[a-zA-Z_][a-zA-Z_0-9]*')
def strip_comments(text):
text = text.replace("\\\n", " ")
return sl_comment_pattern.sub("\n", ml_comment_pattern.sub("", text))
def autorepr(cls):
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, ", ".join("%s = %r" % (k, v)
for k, v in sorted(self.__dict__.items()) if not k.startswith("_") and v))
cls.__repr__ = __repr__
return cls
@autorepr
class CFunc(object):
def __init__(self, name, args, type): # @ReservedAssignment
self.name = name
self.args = args
self.type = type
@autorepr
class CEnum(object):
def __init__(self, name, members):
self.name = name
self.members = members
def get_ctype(self):
return "ctypes.c_int"
@autorepr
class CStruct(object):
def __init__(self, name, members, packed = False):
self.name = name
self.members = members
self.packed = packed
def get_ctype(self):
return self.name
@autorepr
class CUnion(object):
def __init__(self, name, members, packed = False):
self.name = name
self.members = members
self.packed = packed
def get_ctype(self):
return self.name
@autorepr
class CTypedef(object):
def __init__(self, name, type): # @ReservedAssignment
self.name = name
self.type = type
def get_ctype(self):
return self.name
@autorepr
class CType(object):
builtin_ctypes = {
# Misc
"_Bool" : "c_bool", "bool" : "c_bool", "wchar_t" : "c_wchar", "wchar" : "c_wchar",
"float" : "c_float", "double" : "c_double", "long double" : "c_longdouble", "size_t" : "c_size_t",
"ssize_t" : "c_ssize_t",
# 8
"char" : "c_char", "signed char" : "c_byte", "int8" : "c_byte", "int8_t" : "c_byte", "__int8" : "c_byte",
"unsigned char" : "c_ubyte", "uchar" : "c_ubyte", "uchar_t" : "c_ubyte", "uint8" : "c_ubyte",
"uint8_t" : "c_ubyte", "unsigned __int8" : "c_byte",
# 16
"short" : "c_short", "signed short" : "c_short", "int16" : "c_short", "int16_t" : "c_short", "__int16" : "c_short",
"unsigned short" : "c_ushort", "ushort" : "c_ushort", "ushort_t" : "c_ushort", "uint16" : "c_ushort",
"uint16_t" : "c_ushort", "unsigned __int16" : "c_ushort",
"short int" : "c_short",
# 32
"int" : "c_int", "signed int" : "c_int", "int32" : "c_int", "int32_t" : "c_int", "__int32" : "c_int",
"unsigned int" : "c_uint", "uint" : "c_uint", "uint_t" : "c_uint", "uint32" : "c_uint",
"uint32_t" : "c_uint", "unsigned __int32" : "c_uint", "long" : "c_long", "signed long" : "c_long",
"unsigned long" : "c_ulong", "ulong" : "c_ulong", "ulong_t" : "c_ulong",
"long int" : "c_long",
# 64
"long long" : "c_longlong", "signed long long" : "c_longlong", "int64" : "c_longlong", "int64_t" : "c_longlong",
"__int64" : "c_longlong", "unsigned long long" : "c_ulonglong", "ulonglong" : "c_ulonglong",
"ulonglong_t" : "c_ulonglong", "unsigned __int64" : "c_longlong", "uint64" : "c_ulonglong",
"uint64_t" : "c_ulonglong", "unsigned __int64" : "c_ulonglong",
# Windows
'ARRAY' : 'wintypes.ARRAY', 'ATOM' : 'wintypes.ATOM', 'BOOL' : 'wintypes.BOOL', 'BOOLEAN' : 'wintypes.BOOLEAN',
'BYTE' : 'wintypes.BYTE', 'COLORREF' : 'wintypes.COLORREF', 'DOUBLE' : 'wintypes.DOUBLE',
'DWORD' : 'wintypes.DWORD', 'FILETIME' : 'wintypes.FILETIME', 'FLOAT' : 'wintypes.FLOAT',
'HACCEL' : 'wintypes.HACCEL', 'HANDLE' : 'wintypes.HANDLE', 'HBITMAP' : 'wintypes.HBITMAP',
'HBRUSH' : 'wintypes.HBRUSH', 'HCOLORSPACE' : 'wintypes.HCOLORSPACE', 'HDC' : 'wintypes.HDC',
'HDESK' : 'wintypes.HDESK', 'HDWP' : 'wintypes.HDWP', 'HENHMETAFILE' : 'wintypes.HENHMETAFILE',
'HFONT' : 'wintypes.HFONT', 'HGDIOBJ' : 'wintypes.HGDIOBJ', 'HGLOBAL' : 'wintypes.HGLOBAL',
'HHOOK' : 'wintypes.HHOOK', 'HICON' : 'wintypes.HICON', 'HINSTANCE' : 'wintypes.HINSTANCE',
'HKEY' : 'wintypes.HKEY', 'HKL' : 'wintypes.HKL', 'HLOCAL' : 'wintypes.HLOCAL', 'HMENU' : 'wintypes.HMENU',
'HMETAFILE' : 'wintypes.HMETAFILE', 'HMODULE' : 'wintypes.HMODULE', 'HMONITOR' : 'wintypes.HMONITOR',
'HPALETTE' : 'wintypes.HPALETTE', 'HPEN' : 'wintypes.HPEN', 'HRESULT' : 'wintypes.HRESULT',
'HRGN' : 'wintypes.HRGN', 'HRSRC' : 'wintypes.HRSRC', 'HSTR' : 'wintypes.HSTR', 'HTASK' : 'wintypes.HTASK',
'HWINSTA' : 'wintypes.HWINSTA', 'HWND' : 'wintypes.HWND', 'INT' : 'wintypes.INT', 'LANGID' : 'wintypes.LANGID',
'LARGE_INTEGER' : 'wintypes.LARGE_INTEGER', 'LCID' : 'wintypes.LCID', 'LCTYPE' : 'wintypes.LCTYPE',
'LGRPID' : 'wintypes.LGRPID', 'LONG' : 'wintypes.LONG', 'LPARAM' : 'wintypes.LPARAM',
'LPCOLESTR' : 'wintypes.LPCOLESTR', 'LPCSTR' : 'wintypes.LPCSTR', 'LPCVOID' : 'wintypes.LPCVOID',
'LPCWSTR' : 'wintypes.LPCWSTR', 'LPOLESTR' : 'wintypes.LPOLESTR', 'LPSTR' : 'wintypes.LPSTR',
'LPVOID' : 'wintypes.LPVOID', 'LPWSTR' : 'wintypes.LPWSTR', 'MSG' : 'wintypes.MSG',
'OLESTR' : 'wintypes.OLESTR', 'POINT' : 'wintypes.POINT', 'POINTL' : 'wintypes.POINTL',
'RECT' : 'wintypes.RECT', 'RECTL' : 'wintypes.RECTL', 'RGB' : 'wintypes.RGB',
'RTLD_GLOBAL' : 'wintypes.RTLD_GLOBAL', 'RTLD_LOCAL' : 'wintypes.RTLD_LOCAL',
'SC_HANDLE' : 'wintypes.SC_HANDLE', 'SERVICE_STATUS_HANDLE' : 'wintypes.SERVICE_STATUS_HANDLE',
'SHORT' : 'wintypes.SHORT', 'SIZE' : 'wintypes.SIZE', 'SIZEL' : 'wintypes.SIZEL',
'SMALL_RECT' : 'wintypes.SMALL_RECT', 'UINT' : 'wintypes.UINT', 'ULARGE_INTEGER' : 'wintypes.ULARGE_INTEGER',
'ULONG' : 'wintypes.ULONG', 'USHORT' : 'wintypes.USHORT', 'VARIANT_BOOL' : 'wintypes.VARIANT_BOOL',
'WCHAR' : 'wintypes.WCHAR', 'WIN32_FIND_DATAA' : 'wintypes.WIN32_FIND_DATAA',
'WIN32_FIND_DATAW' : 'wintypes.WIN32_FIND_DATAW', 'WORD' : 'wintypes.WORD', 'WPARAM' : 'wintypes.WPARAM',
'_COORD' : 'wintypes._COORD', '_FILETIME' : 'wintypes._FILETIME', '_LARGE_INTEGER' : 'wintypes._LARGE_INTEGER',
'_POINTL' : 'wintypes._POINTL', '_RECTL' : 'wintypes._RECTL', '_SMALL_RECT' : 'wintypes._SMALL_RECT',
'_ULARGE_INTEGER' : 'wintypes._ULARGE_INTEGER',
}
def __init__(self, name, indir_levels = 0, subscripts = None, quals = None, calling_convention = "auto"):
self.name = name
self.indir_levels = indir_levels
self.subscripts = subscripts
self.quals = None
self.calling_convention = calling_convention
def get_ctype(self):
if self.indir_levels == 1 and not self.quals:
if self.name == "char":
return "ctypes.c_char_p"
elif self.name == "wchar":
return "ctypes.c_wchar_p"
elif self.name == "void":
return "ctypes.c_void_p"
if isinstance(self.name, tuple):
restype, argtypes = self.name
restype = restype.get_ctype()
if restype == "void":
restype = None
if self.calling_convention == "auto":
callingconv = "_get_calling_conv"
elif self.calling_convention == "stdcall":
callingconv = "ctypes.WINFUNCTYPE"
elif self.calling_convention == "cdecl":
callingconv = "ctypes.CFUNCTYPE"
else:
raise ValueError("Unknown calling convention %r" % (self.calling_convention))
tp = "%s(%s, %s)" % (callingconv, restype, ", ".join(a.get_ctype() for _, a in argtypes))
for _ in range(self.indir_levels - 1):
tp = "ctypes.POINTER(%s)" % (tp)
else:
key = (self.quals if self.quals else "") + self.name
if key in self.builtin_ctypes:
tp = "ctypes." + self.builtin_ctypes[key]
else:
tp = self.name
for _ in range(self.indir_levels):
tp = "ctypes.POINTER(%s)" % (tp)
if self.subscripts:
for subs in self.subscripts:
tp = "(%s * %s)" % (tp, subs)
return tp
def as_pretty_type(self, argname):
return ("%s %s%s %s%s" % (self.quals if self.quals else "", self.name, "*" * self.indir_levels, argname,
("".join("[%s]" % (subs,) for subs in self.subscripts) if self.subscripts else ""))).strip()
class CtypesGenVisitor(c_ast.NodeVisitor):
def __init__(self, module):
self.module = module
self.counter = itertools.count(0)
def eval_const(self, node):
if isinstance(node, c_ast.UnaryOp):
expr = "(%s%s)" % (node.op, self.eval_const(node.expr))
try:
return eval(expr)
except Exception:
return expr
elif isinstance(node, c_ast.BinaryOp):
expr = "(%s %s %s)" % (self.eval_const(node.left), node.op, self.eval_const(node.right))
try:
return eval(expr)
except Exception:
return expr
elif isinstance(node, c_ast.ID):
return node.name
elif isinstance(node.value, c_ast.ID):
return node.value.name
elif node.value.startswith("0x"):
return int(node.value, 16)
elif node.value.startswith("0"):
return int(node.value, 8)
elif node.value.isdigit():
return int(node.value)
else:
raise TypeError(node.value)
def type_to_ctype(self, node, quals = None, indir_levels = 0, subscripts = None):
if isinstance(node, c_ast.TypeDecl):
return self.type_to_ctype(node.type, node.quals, indir_levels, subscripts)
elif isinstance(node, c_ast.PtrDecl):
return self.type_to_ctype(node.type, node.quals, indir_levels + 1, subscripts)
elif isinstance(node, c_ast.IdentifierType):
return CType(" ".join(node.names), indir_levels = indir_levels, quals = quals if quals else None,
subscripts = subscripts if subscripts else None)
elif isinstance(node, c_ast.FuncDecl):
rettype = self.type_to_ctype(node.type)
args = [(a.name, self.type_to_ctype(a.type)) for a in node.args.params]
return CType((rettype, args), indir_levels = indir_levels, quals = quals if quals else None,
subscripts = subscripts if subscripts else None)
elif isinstance(node, c_ast.ArrayDecl):
if subscripts:
subscripts.append(self.eval_const(node.dim))
else:
subscripts = [self.eval_const(node.dim)]
return self.type_to_ctype(node.type, quals, indir_levels, subscripts)
elif isinstance(node, (c_ast.Struct, c_ast.Union)):
return CType(node.name, indir_levels = indir_levels, quals = quals if quals else None,
subscripts = subscripts if subscripts else None)
else:
node.show(showcoord = True)
raise TypeError(node)
def visit_Decl(self, node):
if isinstance(node.type, c_ast.FuncDecl):
if node.type.args:
args = [(a.name, self.type_to_ctype(a.type)) for a in node.type.args.params]
else:
args = []
self.module.funcs[node.name] = CFunc(node.name, args, self.type_to_ctype(node.type.type))
else:
self.generic_visit(node)
def create_enum(self, node):
members = []
for e in node.values.enumerators:
if e.value is None:
v = members[-1][1] + 1 if members else 0
else:
v = self.eval_const(e.value)
members.append((e.name, v))
enum = CEnum(node.name, members)
if not enum.name:
enum.name = "_anon_enum_%d" % (self.counter.next(),)
self.module.types[enum.name] = enum
return enum.name
def create_struct(self, node):
members = []
if node.decls:
for m in node.decls:
members.append((m.name, self.type_to_ctype(m.type)))
struct = CStruct(node.name, members, packed = node.coord.line in self.module.packed_lines)
if not struct.name:
struct.name = "_anon_struct_%d" % (self.counter.next(),)
self.module.types[struct.name] = struct
return struct.name
def create_union(self, node):
members = []
for m in node.decls:
members.append((m.name, self.type_to_ctype(m.type)))
union = CUnion(node.name, members, packed = node.coord.line in self.module.packed_lines)
if not union.name:
union.name = "_anon_union_%d" % (self.counter.next(),)
self.module.types[union.name] = union
return union.name
def _resolve_typedef(self, node, realname, newname):
if realname.startswith("_anon_"):
obj | |
<reponame>remanevy/Package
# Copyright 2013-2016 The Salish Sea MEOPAR contributors
# and The University of British Columbia
# 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.
"""Salish Sea NEMO model geographic places information.
It is recommended that library code that uses the :py:data:`PLACES` data
structure from this module should use :kbd:`try...except` to catch
:py:exc:`KeyError` exceptions and produce an error message that is more
informative than the default, for example:
.. code-block:: python
try:
max_tide_ssh = max(ttide.pred_all) + PLACES[site_name]['mean sea lvl']
max_historic_ssh = PLACES[site_name]['hist max sea lvl']
except KeyError as e:
raise KeyError(
'place name or info key not found in '
'salishsea_tools.places.PLACES: {}'.format(e))
"""
#: Information about geographic places used in the analysis and
#: presentation of Salish Sea NEMO model results.
PLACES = {
# Tide gauge stations
'Campbell River': {
# deg E, deg N
'lon lat': (-125.24, 50.04),
# Canadian Hydrographic Service (CHS) or NOAA
'stn number': 8074,
# m above chart datum
'mean sea lvl': 2.916,
# m above chart datum
'hist max sea lvl': 5.35,
# indices of nearest weather forcing grid point
# j is the latitude (y) direction, i is the longitude (x) direction
'wind grid ji': (190, 102),
# indices of nearest NEMO model grid point
# j is the latitude (y) direction, i is the longitude (x) direction
'NEMO grid ji': (747, 125),
# indices of nearest wave model grid point
# j is the latitude (y) direction, i is the longitude (x) direction
'ww3 grid ji': (453, 109)
},
'Cherry Point': {
'lon lat': (-122.766667, 48.866667),
'stn number': 9449424,
'mean sea lvl': 3.543,
'hist max sea lvl': 5.846,
'wind grid ji': (122, 166),
'NEMO grid ji': (343, 342),
'ww3 grid ji': (193, 462),
},
'Friday Harbor': {
'lon lat': (-123.016667, 48.55),
'stn number': 9449880,
'mean sea lvl': 2.561,
'hist max sea lvl': 4.572,
'wind grid ji': (108, 155),
'NEMO grid ji': (300, 267),
'ww3 grid ji': (124, 427),
},
'Halfmoon Bay': {
'lon lat': (-123.912, 49.511),
'stn number': 7830,
'NEMO grid ji': (549, 254),
'wind grid ji': (158, 136),
'ww3 grid ji': (331, 297),
'mean sea lvl': 3.14,
'hist max sea lvl': 5.61, # copied from Point Atkinson
},
'Nanaimo': {
'lon lat': (-123.93, 49.16),
'stn number': 7917,
'mean sea lvl': 3.08,
'hist max sea lvl': 5.47,
'wind grid ji': (142, 133),
'NEMO grid ji': (484, 208), # current a little different
'ww3 grid ji': (261, 298),
},
'Neah Bay': {
'lon lat': (-124.6, 48.4),
'stn number': 9443090,
'mean sea lvl': 1.925,
'hist max sea lvl': 4.359,
'wind grid ji': (111, 105),
'NEMO grid ji': (384, 15),
'ww3 grid ji': (89, 200),
},
'New Westminster': {
'lon lat': (-122.90535, 49.203683),
'stn number': 7654,
'mean sea lvl': 1.3, # from <NAME> via 20mar18 email from <NAME>
'hist max sea lvl': 4.66,
'NEMO grid ji': (423, 363),
'wind grid ji': (138, 164),
# no nearby waves
},
'Patricia Bay': {
'lon lat': (-123.4515, 48.6536),
'stn number': 7277,
'mean sea lvl': 2.256,
'hist max sea lvl': 4.38,
'NEMO grid ji': (351, 214),
'wind grid ji': (115, 143),
'ww3 grid ji': (145, 363),
},
'Point Atkinson': {
'lon lat': (-123.25, 49.33),
'stn number': 7795,
'mean sea lvl': 3.09,
'hist max sea lvl': 5.61,
'wind grid ji': (146, 155),
'NEMO grid ji': (468, 329),
'ww3 grid ji': (296, 393),
},
'<NAME>': {
'lon lat': (-124.421, 48.555),
'stn number': 8525,
'mean sea lvl': 1.937,
'hist max sea lvl': 4.359, # from Neah Bay
'NEMO grid ji': (401, 61),
'wind grid ji': (117, 112),
'ww3 grid ji': (123, 226),
},
'<NAME>': {
'lon lat': (-123.23, 49.34),
'stn number': 7786,
'NEMO grid ji': (468, 333),
'wind grid ji': (146, 155),
'ww3 grid ji': (294, 396),
'mean sea lvl': 3.1, # from <NAME> via 20mar18 email from <NAME>
'hist max sea lvl': 5.61, # from Pt. Atkinson
},
'Squamish': {
'lon lat': (-123.155, 49.694),
'stn number': 7811,
'NEMO grid ji': (532, 389),
'wind grid ji': (162, 160),
'ww3 grid ji': (370, 404),
'mean sea lvl': 3.14,
'hist max sea lvl': 5.61 # from Pt. Atkkinson
},
'Victoria': {
'lon lat': (-123.3707, 48.424666),
'stn number': 7120,
'mean sea lvl': 1.8810,
'hist max sea lvl': 3.76,
'wind grid ji': (104, 144),
'NEMO grid ji': (302, 196),
'ww3 grid ji': (90, 374),
},
'Woodwards Landing': {
'lon lat': (-123.0754, 49.1251),
'stn number': 7610,
'hist max sea lvl': 4.66, # based on New West
'mean sea lvl': 1.84, # from <NAME> via 20mar18 email from <NAME>
'NEMO grid ji': (414, 329),
'wind grid ji': (135, 138),
},
'Boundary Bay': {
'lon lat': (-122.925, 49.0),
'stn number': None,
'hist max sea lvl': 5.61, # based on Point Atk
'mean sea lvl': 3.09, # based on Point Atk
'NEMO grid ji': (380, 335),
'wind grid ji': (129, 162),
'ww3 grid ji': (222, 439),
},
# VHFR FVCOM model tide guage stations
'Calamity Point': {
'lon lat': (-123.1276, 49.31262),
'stn number': 7724,
'mean sea lvl': 3.001, # same as Vancouver Harbour; from <NAME> via 20mar18 email from <NAME>
'NEMO grid ji': None,
# 'wind grid ji': TODO
'ww3 grid ji': None,
},
'Vancouver Harbour': {
'lon lat': (-123.1069, 49.28937),
'stn number': 7735,
'mean sea lvl': 3.001, # from <NAME> via 20mar18 email from <NAME>
'NEMO grid ji': None,
# 'wind grid ji': TODO
'ww3 grid ji': None,
},
'Port Moody': {
'lon lat': (-122.8658, 49.28814),
'stn number': 7755,
'mean sea lvl': 3.143, # from <NAME> via 20mar18 email from <NAME>
'NEMO grid ji': None,
# 'wind grid ji': TODO
'ww3 grid ji': None,
},
'Indian Arm Head': {
'lon lat': (-122.8864, 49.4615),
'stn number': 7774,
'mean sea lvl': 3.052, # from <NAME> via 20mar18 email from <NAME>
'NEMO grid ji': None,
# 'wind grid ji': TODO
'ww3 grid ji': None,
},
# VHFR FVCOM model HADCP station
'2nd Narrows Rail Bridge': {
'lon lat': (-123.0247222, 49.2938889),
'stn number': 3160171 # AIS MMSI (Maritime Mobile Service Identity)
},
# Ferry terminals
'Tsawwassen': {
'lon lat': (-123.132722, 49.006165),
'in berth radius': 0.0015,
},
'Duke Pt.': {
'lon lat': (-123.89095676900132, 49.16340592936349),
'in berth radius': 0.002,
},
'Horseshoe Bay': {
'lon lat': (-123.2728, 49.3742),
},
'Departure Bay': {
'lon lat': (-123.8909, 49.1632),
},
'Swartz Bay': {
'lon lat': (-123.4102, 48.6882),
},
# Cities
'Vancouver': {
'lon lat': (-123.1207, 49.2827),
},
# Provinces and states
'British Columbia': {
'lon lat': (-123.6, 49.9),
},
'Washington State': {
'lon lat': (-123.8, 47.8),
},
# Bodies of water
'Pacific Ocean': {
'lon lat': (-125.6, 48.1),
},
'<NAME>': {
'lon lat': (-124.7, 48.47),
},
'Puget Sound': {
'lon lat': (-122.67, 48),
},
'Strait of Georgia': {
'lon lat': (-123.8, 49.3),
},
'Central SJDF': {
'lon lat': (-123.9534, 48.281677),
'NEMO grid ji': (315,95),
'GEM2.5 grid ji': (101, 124),
},
# if you have a better location in mind for Baynes Sound, please update!
# if not, I will after I hear from Debbie/Evie -EO
'Baynes Sound': {
'lon lat': (-124.86022, 49.60356),
'NEMO grid ji': (635, 126),
},
# STRATOGEM STATION S3(lat,lon)=(49 7.5 N, 123 33.5 W)
'S3': {
'lon lat': (-123.558, 49.125),
'NEMO grid ji': (450, 258),
'GEM2.5 grid ji': (138, 144),
},
# Tereza's cluster stations, aligned with Vector Stations where possible.
'Cluster_1': {
'NEMO grid ji': (241, 212),
'lon lat': (48.215, -123.099),
'Vector Stn': '64'
},
'Cluster_2': {
'NEMO grid ji': (294, 127),
'lon lat': (48.261, -123.717),
'Vector Stn': '69'
},
'Cluster_3': {
'NEMO grid ji': (376, 291),
'lon lat': (48.899, -123.138),
'Vector Stn': '45'
},
'Cluster_4': {
| |
import json
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.views.generic import CreateView, DetailView, ListView, TemplateView, View
from cases.models import Case
from cases.forms import CaseForm, CaseCommentForm, CaseAttachmentForm
from common.models import User, Comment, Attachments
from accounts.models import Account
from contacts.models import Contact
from common.utils import PRIORITY_CHOICE, STATUS_CHOICE, CASE_TYPE
from django.urls import reverse
from django.core.exceptions import PermissionDenied
from common.tasks import send_email_user_mentions
from cases.tasks import send_email_to_assigned_user
from common.access_decorators_mixins import (
sales_access_required,
marketing_access_required,
SalesAccessRequiredMixin,
MarketingAccessRequiredMixin,
)
from teams.models import Teams
@login_required
def get_teams_and_users(request):
data = {}
teams = Teams.objects.all()
teams_data = [
{"team": team.id, "users": [user.id for user in team.users.all()]}
for team in teams
]
users = User.objects.all().values_list("id", flat=True)
data["teams"] = teams_data
data["users"] = list(users)
return JsonResponse(data)
class CasesListView(SalesAccessRequiredMixin, LoginRequiredMixin, TemplateView):
model = Case
context_object_name = "cases"
template_name = "cases.html"
def get_queryset(self):
queryset = self.model.objects.all().select_related("account")
if self.request.user.role != "ADMIN" and not self.request.user.is_superuser:
queryset = queryset.filter(
Q(assigned_to__in=[self.request.user]) | Q(created_by=self.request.user)
)
request_post = self.request.POST
if request_post:
if request_post.get("name"):
queryset = queryset.filter(name__icontains=request_post.get("name"))
if request_post.get("account"):
queryset = queryset.filter(account_id=request_post.get("account"))
if request_post.get("status"):
queryset = queryset.filter(status=request_post.get("status"))
if request_post.get("priority"):
queryset = queryset.filter(priority=request_post.get("priority"))
return queryset.filter(company=self.request.company)
def get_context_data(self, **kwargs):
context = super(CasesListView, self).get_context_data(**kwargs)
context["cases"] = self.get_queryset()
context["accounts"] = Account.objects.filter(
status="open", company=self.request.company
)
context["per_page"] = self.request.POST.get("per_page")
context["acc"] = (
int(self.request.POST.get("account"))
if self.request.POST.get("account")
else None
)
context["case_priority"] = PRIORITY_CHOICE
context["case_status"] = STATUS_CHOICE
search = False
if (
self.request.POST.get("name")
or self.request.POST.get("account")
or self.request.POST.get("status")
or self.request.POST.get("priority")
):
search = True
context["search"] = search
return context
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
@login_required
@sales_access_required
def create_case(request):
users = []
if request.user.role == "ADMIN" or request.user.is_superuser:
users = User.objects.filter(is_active=True, company=request.company).order_by(
"email"
)
elif request.user.google.all():
users = []
else:
users = User.objects.filter(role="ADMIN", company=request.company).order_by(
"email"
)
accounts = Account.objects.filter(status="open", company=request.company)
contacts = Contact.objects.filter(company=request.company)
if request.user.role != "ADMIN" and not request.user.is_superuser:
accounts = Account.objects.filter(created_by=request.user).filter(
company=request.company
)
contacts = Contact.objects.filter(
Q(assigned_to__in=[request.user]) | Q(created_by=request.user)
).filter(company=request.company)
kwargs_data = {
"assigned_to": users,
"account": accounts,
"contacts": contacts,
"request_obj": request,
}
form = CaseForm(**kwargs_data)
template_name = "create_cases.html"
if request.POST:
form = CaseForm(request.POST, request.FILES, **kwargs_data)
if form.is_valid():
case = form.save(commit=False)
case.created_by = request.user
case.company = request.company
case.save()
if request.POST.getlist("assigned_to", []):
case.assigned_to.add(*request.POST.getlist("assigned_to"))
assigned_to_list = request.POST.getlist("assigned_to")
# current_site = get_current_site(request)
# recipients = assigned_to_list
# send_email_to_assigned_user.delay(recipients, case.id, domain=current_site.domain,
# protocol=request.scheme)
# for assigned_to_user in assigned_to_list:
# user = get_object_or_404(User, pk=assigned_to_user)
# mail_subject = 'Assigned to case.'
# message = render_to_string(
# 'assigned_to/cases_assigned.html', {
# 'user': user,
# 'domain': current_site.domain,
# 'protocol': request.scheme,
# 'case': case
# })
# email = EmailMessage(
# mail_subject, message, to=[user.email])
# email.content_subtype = "html"
# email.send()
if request.POST.getlist("contacts", []):
case.contacts.add(*request.POST.getlist("contacts"))
if request.POST.getlist("teams", []):
user_ids = Teams.objects.filter(
id__in=request.POST.getlist("teams")
).values_list("users", flat=True)
assinged_to_users_ids = case.assigned_to.all().values_list(
"id", flat=True
)
for user_id in user_ids:
if user_id not in assinged_to_users_ids:
case.assigned_to.add(user_id)
if request.POST.getlist("teams", []):
case.teams.add(*request.POST.getlist("teams"))
current_site = get_current_site(request)
recipients = list(case.assigned_to.all().values_list("id", flat=True))
send_email_to_assigned_user.delay(
recipients, case.id, domain=current_site.domain, protocol=request.scheme
)
if request.FILES.get("case_attachment"):
attachment = Attachments()
attachment.created_by = request.user
attachment.file_name = request.FILES.get("case_attachment").name
attachment.case = case
attachment.attachment = request.FILES.get("case_attachment")
attachment.save()
success_url = reverse("cases:list")
if request.POST.get("savenewform"):
success_url = reverse("cases:add_case")
if request.POST.get("from_account"):
from_account = request.POST.get("from_account")
success_url = reverse(
"accounts:view_account", kwargs={"pk": from_account}
)
return JsonResponse({"error": False, "success_url": success_url})
return JsonResponse({"error": True, "errors": form.errors})
context = {}
context["case_form"] = form
context["accounts"] = accounts
if request.GET.get("view_account"):
context["account"] = get_object_or_404(
Account, id=request.GET.get("view_account")
)
context["contacts"] = contacts
context["users"] = users
context["case_types"] = CASE_TYPE
context["case_priority"] = PRIORITY_CHOICE
context["case_status"] = STATUS_CHOICE
context["teams"] = Teams.objects.filter(company=request.company)
context["assignedto_list"] = [
int(i) for i in request.POST.getlist("assigned_to", []) if i
]
context["contacts_list"] = [
int(i) for i in request.POST.getlist("contacts", []) if i
]
return render(request, template_name, context)
class CaseDetailView(SalesAccessRequiredMixin, LoginRequiredMixin, DetailView):
model = Case
context_object_name = "case_record"
template_name = "view_case.html"
def dispatch(self, request, *args, **kwargs):
case = self.get_object()
if case.company != request.company:
raise PermissionDenied
return super(CaseDetailView, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
queryset = super(CaseDetailView, self).get_queryset()
return queryset.prefetch_related("contacts", "account")
def get_context_data(self, **kwargs):
context = super(CaseDetailView, self).get_context_data(**kwargs)
user_assgn_list = [
assigned_to.id for assigned_to in context["object"].assigned_to.all()
]
user_assigned_accounts = set(
self.request.user.account_assigned_users.values_list("id", flat=True)
)
if context["object"].account:
case_account = set([context["object"].account.id])
else:
case_account = set()
if user_assigned_accounts.intersection(case_account):
user_assgn_list.append(self.request.user.id)
if self.request.user == context["object"].created_by:
user_assgn_list.append(self.request.user.id)
if self.request.user.role != "ADMIN" and not self.request.user.is_superuser:
if self.request.user.id not in user_assgn_list:
raise PermissionDenied
assigned_data = []
for each in context["case_record"].assigned_to.all():
assigned_dict = {}
assigned_dict["id"] = each.id
assigned_dict["name"] = each.email
assigned_data.append(assigned_dict)
if self.request.user.is_superuser or self.request.user.role == "ADMIN":
users_mention = list(
User.objects.filter(
is_active=True, company=self.request.company
).values("username")
)
elif self.request.user != context["object"].created_by:
users_mention = [{"username": context["object"].created_by.username}]
else:
users_mention = list(context["object"].assigned_to.all().values("username"))
context.update(
{
"comments": context["case_record"].cases.all(),
"attachments": context["case_record"].case_attachment.all(),
"users_mention": users_mention,
"assigned_data": json.dumps(assigned_data),
}
)
return context
@login_required
@sales_access_required
def update_case(request, pk):
case_object = Case.objects.filter(pk=pk).first()
if case_object.company != request.company:
raise PermissionDenied
accounts = Account.objects.filter(status="open", company=request.company)
contacts = Contact.objects.filter(company=request.company)
if request.user.role != "ADMIN" and not request.user.is_superuser:
accounts = Account.objects.filter(
created_by=request.user, company=request.company
)
contacts = Contact.objects.filter(
Q(assigned_to__in=[request.user]) | Q(created_by=request.user)
).filter(company=request.company)
users = []
if request.user.role == "ADMIN" or request.user.is_superuser:
users = User.objects.filter(is_active=True, company=request.company).order_by(
"email"
)
elif request.user.google.all():
users = []
else:
users = User.objects.filter(role="ADMIN", company=request.company).order_by(
"email"
)
kwargs_data = {
"assigned_to": users,
"account": accounts,
"contacts": contacts,
"request_obj": request,
}
form = CaseForm(instance=case_object, **kwargs_data)
if request.POST:
form = CaseForm(
request.POST, request.FILES, instance=case_object, **kwargs_data
)
if form.is_valid():
assigned_to_ids = case_object.assigned_to.all().values_list("id", flat=True)
case_obj = form.save(commit=False)
case_obj.contacts.clear()
case_obj.save()
previous_assigned_to_users = list(
case_obj.assigned_to.all().values_list("id", flat=True)
)
all_members_list = []
if request.POST.getlist("assigned_to", []):
current_site = get_current_site(request)
assigned_form_users = form.cleaned_data.get("assigned_to").values_list(
"id", flat=True
)
all_members_list = list(
set(list(assigned_form_users)) - set(list(assigned_to_ids))
)
# recipients = all_members_list
# send_email_to_assigned_user.delay(recipients, case_obj.id, domain=current_site.domain,
# protocol=request.scheme)
# if all_members_list:
# for assigned_to_user in all_members_list:
# user = get_object_or_404(User, pk=assigned_to_user)
# mail_subject = 'Assigned to case.'
# message = render_to_string(
# 'assigned_to/cases_assigned.html', {
# 'user': user,
# 'domain': current_site.domain,
# 'protocol': request.scheme,
# 'case': case_obj
# })
# email = EmailMessage(
# mail_subject, message, to=[user.email])
# email.content_subtype = "html"
# email.send()
case_obj.assigned_to.clear()
case_obj.assigned_to.add(*request.POST.getlist("assigned_to"))
else:
case_obj.assigned_to.clear()
if request.POST.getlist("teams", []):
user_ids = Teams.objects.filter(
id__in=request.POST.getlist("teams")
).values_list("users", flat=True)
assinged_to_users_ids = case_obj.assigned_to.all().values_list(
"id", flat=True
)
for user_id in user_ids:
if user_id not in assinged_to_users_ids:
case_obj.assigned_to.add(user_id)
if request.POST.getlist("teams", []):
case_obj.teams.clear()
case_obj.teams.add(*request.POST.getlist("teams"))
else:
case_obj.teams.clear()
current_site = get_current_site(request)
assigned_to_list = list(
case_obj.assigned_to.all().values_list("id", flat=True)
)
recipients = list(set(assigned_to_list) - set(previous_assigned_to_users))
send_email_to_assigned_user.delay(
recipients,
case_obj.id,
domain=current_site.domain,
protocol=request.scheme,
)
if request.POST.getlist("contacts", []):
case_obj.contacts.add(*request.POST.getlist("contacts"))
success_url = reverse("cases:list")
if request.POST.get("from_account"):
from_account = request.POST.get("from_account")
success_url = reverse(
"accounts:view_account", kwargs={"pk": from_account}
)
if request.FILES.get("case_attachment"):
attachment = Attachments()
attachment.created_by = request.user
attachment.file_name = request.FILES.get("case_attachment").name
attachment.case = case_obj
attachment.attachment = request.FILES.get("case_attachment")
attachment.save()
return JsonResponse({"error": False, "success_url": success_url})
return JsonResponse({"error": True, "errors": form.errors})
context = {}
context["case_obj"] = case_object
user_assgn_list = [
assgined_to.id for assgined_to in context["case_obj"].assigned_to.all()
]
if request.user == case_object.created_by:
user_assgn_list.append(request.user.id)
if request.user.role != "ADMIN" and not request.user.is_superuser:
if request.user.id not in user_assgn_list:
raise PermissionDenied
context["case_form"] = form
context["accounts"] = accounts
if request.GET.get("view_account"):
context["account"] = get_object_or_404(
Account, id=request.GET.get("view_account")
)
context["contacts"] = contacts
context["users"] = kwargs_data["assigned_to"]
context["case_types"] = CASE_TYPE
context["case_priority"] = PRIORITY_CHOICE
context["case_status"] = STATUS_CHOICE
context["teams"] = Teams.objects.filter(company=request.company)
context["assignedto_list"] = [
int(i) for i in request.POST.getlist("assigned_to", []) if i
]
context["contacts_list"] = [
int(i) for i in request.POST.getlist("contacts", []) if i
]
return render(request, "create_cases.html", context)
class RemoveCaseView(SalesAccessRequiredMixin, LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
case_id = kwargs.get("case_id")
self.object = get_object_or_404(Case, id=case_id)
if self.object.company != request.company:
raise PermissionDenied
if (
self.request.user.role == "ADMIN"
or self.request.user.is_superuser
or self.request.user == self.object.created_by
):
self.object.delete()
if request.GET.get("view_account"):
account = request.GET.get("view_account")
return redirect("accounts:view_account", pk=account)
return redirect("cases:list")
raise PermissionDenied
def post(self, request, *args, **kwargs):
case_id = kwargs.get("case_id")
self.object = get_object_or_404(Case, id=case_id)
if (
self.request.user.role == "ADMIN"
or self.request.user.is_superuser
or self.request.user == self.object.created_by
):
self.object.delete()
if request.is_ajax():
return JsonResponse({"error": False})
count = (
Case.objects.filter(
Q(assigned_to__in=[request.user]) | Q(created_by=request.user)
)
.distinct()
.count()
)
data = {"case_id": case_id, "count": count}
return JsonResponse(data)
raise PermissionDenied
class CloseCaseView(SalesAccessRequiredMixin, LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
case_id = request.POST.get("case_id")
self.object = get_object_or_404(Case, id=case_id)
if (
self.request.user.role == "ADMIN"
or self.request.user.is_superuser
or self.request.user == self.object.created_by
):
self.object.status = "Closed"
self.object.save()
data = {"status": "Closed", "cid": case_id}
return JsonResponse(data)
raise PermissionDenied
def select_contact(request):
contact_account = request.GET.get("account")
if contact_account:
account = get_object_or_404(Account, id=contact_account)
contacts = account.contacts.all()
else:
contacts = Contact.objects.all()
data = {contact.pk: contact.first_name for contact in contacts.distinct()}
return JsonResponse(data)
class GetCasesView(LoginRequiredMixin, ListView):
model = Case
| |
np.isclose(integrals, quantpoints)
assert(type(quantiles) is np.ndarray)
self.quantiles = (quantpoints, quantiles)
if vb:
print("Resulting "+str(len(quantiles))+" quantiles: "+str(self.quantiles))
self.limits = (min(limits[0], np.min(quantiles)), max(limits[-1], np.max(quantiles)))
self.last = 'quantiles'
return self.quantiles
def histogramize(self, binends=None, N=10, binrange=None, vb=True):
"""
Computes integrated histogram bin values from the truth via the CDF.
Parameters
----------
binends: ndarray, float, optional
array of N+1 endpoints of N bins
N: int, optional
number of regular bins if no binends provided
binrange: tuple, float, optional
pair of values of endpoints of total bin range
vb: boolean
report on progress to stdout?
Returns
-------
self.histogram: tuple of ndarrays of floats
Pair of arrays of lengths (N+1, N) containing endpoints
of bins and values in bins
Comments
--------
A histogram representation of a PDF is a popular approximate way
to store it. This method computes some histogram bin heights
from a truth distribution (other representations forthcoming)
and stores them in the `self.histogram` attribute.
Uses the `.cdf` method of the `rvs_continuous` distribution
object stored in `self.truth`. This calculates the CDF.
See `the Scipy docs <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.cdf.html#scipy.stats.rv_continuous.cdf>`_ for details.
"""
if binends is None:
if binrange is None:
binrange = self.limits
binends = np.linspace(binrange[0], binrange[-1], N+1)
else:
N = len(binends) - 1
histogram = np.zeros(N)
if vb: print 'Calculating histogram: ', binends
if self.mixmod is not None:
cdf = self.mixmod.cdf(binends)
heights = cdf[1:] - cdf[:-1]
histogram = qp.utils.normalize_histogram((binends, heights), vb=vb)
# for b in range(N):
# histogram[b] = (cdf[b+1]-cdf[b])/(binends[b+1]-binends[b])
else:
print 'New histograms can only be computed from a mixmod format in this version.'
return
if vb: print 'Result: ', histogram
self.histogram = histogram
self.last = 'histogram'
return self.histogram
def mix_mod_fit(self, n_components=5, using=None, vb=True):
"""
Fits the parameters of a given functional form to an approximation
Parameters
----------
n_components: int, optional
number of components to consider
using: string, optional
which existing approximation to use, defaults to first approximation
vb: boolean
Report progress on stdout?
Returns
-------
self.mix_mod: qp.composite object
the qp.composite object approximating the PDF
Notes
-----
Currently only supports mixture of Gaussians
TO DO: change syntax n_components --> N
"""
comp_range = range(n_components)
if using == None:
using = self.first
if using == 'gridded':
if self.gridded is not None:
(x, y) = self.gridded
ival_weights = np.ones(n_components) / n_components
ival_means = min(x) + (max(x) - min(x)) * np.arange(n_components) / n_components
ival_stdevs = np.sqrt((max(x) - min(x)) * np.ones(n_components) / n_components)
ivals = np.array([ival_weights, ival_means, ival_stdevs]).T.flatten()
def gmm(x, *args):
y = 0.
args = np.array(args).reshape((n_components, 3))
for c in comp_range:
# index = c * n_components
y += args[c][0] * sps.norm(loc = args[c][1], scale = args[c][2]).pdf(x)
return y
low_bounds = np.array([np.zeros(n_components), min(x) * np.ones(n_components), np.ones(n_components) * (max(x) - min(x)) / len(x)]).T.flatten()
high_bounds = np.array([np.ones(n_components), max(x) * np.ones(n_components), np.ones(n_components) * (max(x) - min(x))]).T.flatten()
popt, pcov = spo.curve_fit(gmm, self.gridded[0], self.gridded[1], ivals, bounds = (low_bounds, high_bounds))
popt = popt.reshape((n_components, 3)).T
weights = popt[0]
means = popt[1]
stdevs = popt[2]
else:
print('No gridded parametrization available. Try using a different format.')
return
else:
if self.samples is None:
self.samples = self.sample(using=using, vb=vb)
estimator = skl.mixture.GaussianMixture(n_components=n_components)
estimator.fit(self.samples.reshape(-1, 1))
weights = estimator.weights_
means = estimator.means_[:, 0]
stdevs = np.sqrt(estimator.covariances_[:, 0, 0])
if vb:
print('weights, means, stds = '+str((weights, means, stdevs)))
components = []
for i in comp_range:
mix_mod_dict = {}
function = sps.norm(loc = means[i], scale = stdevs[i])
coefficient = weights[i]
mix_mod_dict['function'] = function
mix_mod_dict['coefficient'] = coefficient
components.append(mix_mod_dict)
if vb:
statement = ''
for c in comp_range:
statement += str(weights[c])+r'$\cdot\mathcal{N}($'+str(means[c])+r','+str(stdevs[c])+r')\n'
print(statement)
self.mix_mod = qp.composite(components)
return self.mix_mod
def sample(self, N=1000, infty=default_infty, using=None, vb=True):
"""
Samples the pdf in given representation
Parameters
----------
N: int, optional
number of samples to produce
infty: float, optional
approximate value at which CDF=1.
using: string, optional
Parametrization on which to interpolate, defaults to initialization
vb: boolean
report on progress to stdout?
Returns
-------
samples: ndarray
array of sampled values
Notes
-----
TO DO: all formats should use rejection sampling
TO DO: change infty to upper and lower bounds to use for quantiles
TO DO: check for existence of parametrization before using it
"""
if using is None:
using = self.first
if vb: print 'Sampling from '+using+' parametrization.'
# if using == 'truth':
# samples = self.truth.rvs(size=N)
if using == 'mix_mod':
samples = self.mix_mod.rvs(size=N)
elif using == 'gridded':
interpolator = self.interpolate(using = 'gridded', vb=vb)[0]
# (xlims, ylims) = self.evaluate(self.limits, using='gridded', vb=vb)
(xmin, xmax) = (min(self.gridded[0]), max(self.gridded[0]))
(ymin, ymax) = (min(self.gridded[1]), max(self.gridded[1]))
(xran, yran) = (xmax - xmin, ymax - ymin)
samples = []
while len(samples) < N:
(x, y) = (xmin + xran * np.random.uniform(), ymin + yran * np.random.uniform())
if y < interpolator(x):
samples.append(x)
else:
if using == 'quantiles':
# First find the quantiles if none exist:
if self.quantiles is None:
self.quantiles = self.quantize(vb=vb)
# (x, y) = qp.utils.evaluate_quantiles(self.quantiles, vb=vb)
(endpoints, weights) = qp.utils.normalize_quantiles(self.quantiles, vb=vb)
# endpoints = np.insert(self.quantiles[1], [0, -1], self.limits)
# weights = qp.utils.evaluate_quantiles(self.quantiles)[1]# self.evaluate((endpoints[1:]+endpoints[:-1])/2.)
# interpolator = self.interpolate(using='quantiles', vb=False)
if using == 'histogram':
# First find the histogram if none exists:
if self.histogram is None:
self.histogram = self.histogramize(vb=vb)
endpoints = self.histogram[0]
weights = self.histogram[1]
ncats = len(weights)
cats = range(ncats)
sampbins = [0]*ncats
for item in range(N):
sampbins[qp.utils.choice(cats, weights)] += 1
samples = []*N
for c in cats:
for n in range(sampbins[c]):
samples.append(np.random.uniform(low=endpoints[c], high=endpoints[c+1]))
if vb: print 'Sampled values: ', samples
self.samples = np.array(samples)
self.limits = (min(self.limits[0], np.min(self.samples)), max(self.limits[-1], np.max(self.samples)))
self.last = 'samples'
return self.samples
def interpolate(self, using=None, vb=True):
"""
Constructs an `interpolator` function based on the parametrization.
Parameters
----------
using: string, optional
parametrization on which to interpolate, defaults to initialization
vb: boolean
report on progress to stdout?
Returns
-------
interpolator
an interpolator object
Notes
-----
The `interpolator` object is a function that is used by the
`approximate` method. It employs
[`scipy.interpolate.interp1d`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html)
to carry out the interpolation for the gridded format, using the internal
`self.scheme` attribute to choose the interpolation scheme. For quantile interpolation, it uses a `scipy.interpolate.InterpolatedUnivariateSpline` object, with self.scheme being the integer order of the spline.
TO DO: store the interpolators separately with using tags
"""
if using is None:
using = self.last
if using == 'truth' or using == 'mix_mod':
interpolator = self.mix_mod.pdf
print 'A functional form needs no interpolation. Try converting to an approximate parametrization first.'
# return
if using == 'quantiles':
# First find the quantiles if none exist:
if self.quantiles is None:
self.quantiles = self.quantize(vb=vb)
if type(self.scheme) != int:
order = min(5, len(self.quantiles[0]))
else:
order = self.scheme
if vb: print('input quantiles are '+str(self.quantiles[1]))
# (x, y) = qp.utils.evaluate_quantiles(self.quantiles, vb=vb)
# if vb: print('evaluated quantile PDF: '+str((x, y)))
# [x_crit_lo, x_crit_hi] = [x[0], x[-1]]
# [y_crit_lo, y_crit_hi] = [y[0], y[-1]]
(x, y) = qp.utils.normalize_quantiles(self.quantiles, vb=vb)
if vb: print('complete evaluated quantile PDF: '+str((x, y)))
z = np.insert(self.quantiles[1], 0, min(x))
z = np.append(z, max(x))
q = np.insert(self.quantiles[0], 0, 0.)
q = np.append(q, 1.)
# knots, coeffs, degree = spi.splrep(z, q, k=order, s=0)
#
# def inside(xi):
# yi = spi.splev(xi, (knots, coeffs, degree), der=1)
# coeffs[yi<0]
[x_crit_lo, x_crit_hi] = [self.quantiles[1][0], self.quantiles[1][-1]]
[y_crit_lo, y_crit_hi] = [-1., -1.]
try:
while (order>0) and ((y_crit_lo <= 0.) or (y_crit_hi <= 0.)):
if vb: print('order is '+str(order))
inside = spi.InterpolatedUnivariateSpline(z, q, k=order, ext=1).derivative()
[y_crit_lo, y_crit_hi] = inside([x_crit_lo, x_crit_hi])
order -= 1
assert((y_crit_lo > 0.) and (y_crit_hi > 0.))
except AssertionError:
print('ERROR: spline tangents '+str((y_crit_lo, y_crit_hi))+'<0')
if type(self.scheme) == str:
scheme = self.scheme
else:
scheme = 'linear'
if vb: print('defaulting to '+scheme+' interpolation')
inside_int = spi.interp1d(z, q, kind=scheme, bounds_error=False, fill_value=default_eps)
derivative = (q[1:] - q[:-1]) / (z[1:] - z[:-1])
derivative = np.insert(derivative, 0, default_eps)
derivative = np.append(derivative, default_eps)
def inside(xf):
nx = len(xf)
yf = np.ones(nx) * default_eps
for n in range(nx):
i = bisect.bisect_left(z, xf[n])
yf[n] = derivative[i]
return(yf)
[y_crit_lo, y_crit_hi] = inside([x_crit_lo, x_crit_hi])
assert((y_crit_lo > 0.) and (y_crit_hi > 0.))
def quantile_interpolator(xf):
yf = np.ones(np.shape(xf)) * default_eps
in_inds = ((xf >= self.quantiles[1][0]) & (xf <= self.quantiles[1][-1])).nonzero()[0]
lo_inds = ((xf < self.quantiles[1][0]) & (xf >= z[0])).nonzero()[0]
hi_inds = ((xf > self.quantiles[1][-1]) & (xf | |
1, 0, 0, 0, 0...
# ses-2 - ses-1: -1, 0, 0, 0, etc.
contrast_one.update({
"contrasts": "{0}_{1} - {2}_{3}".format(condition_type,
conditions[0],
condition_type,
conditions[1])})
contrast_two.update({
"contrasts": "{0}_{1} - {2}_{3}".format(condition_type,
conditions[1],
condition_type,
conditions[0])})
contrast_one.update({condition_type: 1})
contrast_two.update({condition_type: -1})
contrasts = [contrast_one, contrast_two]
contrasts_df = create_contrasts_template_df(design_df, contrasts)
# create design and contrasts matrix file paths
design_mat_path = os.path.join(output_dir, model_name,
"design_matrix_{0}.csv".format(model_name))
contrasts_mat_path = os.path.join(output_dir, model_name,
"contrasts_matrix_{0}.csv"
"".format(model_name))
# start group config yaml dictionary
group_config.update({"pheno_file": design_mat_path,
"ev_selections": {"demean": [],
"categorical": []},
"design_formula": design_formula,
"group_sep": "Off",
"grouping_var": None,
"custom_contrasts": contrasts_mat_path,
"model_name": model_name,
"output_dir": os.path.join(output_dir, model_name)})
return design_df, contrasts_df, group_config
def preset_tripled_two_group(group_list, conditions, condition_type="session",
output_dir=None,
model_name="tripled_T-test"):
"""Set up the design matrix and contrasts matrix for running a tripled
two-group difference ('tripled' T-test).
group_list: a list of strings- sub_ses unique IDs
conditions: a three-item list of strings- session or series/scan names of
the three sessions or three scans (per participant) you wish
to compare
condition_type: a string, either "session" or "scan", depending on what
is in "conditions"
output_dir: (optional) string of the output directory path
model_name: (optional) name/label of the model to run
Sets up the model described here:
https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FEAT/UserGuide
#Tripled_Two-Group_Difference_.28.22Tripled.22_T-Test.29
"""
import os
if not output_dir:
output_dir = os.getcwd()
if len(conditions) != 3:
# TODO: msg
raise Exception('Three conditions are required for the tripled '
't-test.\n')
design_df = create_design_matrix_df(group_list)
# make the "condition" EVs (the 1's, -1's, and 0's delineating the three
# conditions, with the "conditions" being the three sessions or three
# scans)
condition_ev_one = []
condition_ev_two = []
if condition_type == "session":
# note: the participant_id column in design_df should be in order, so
# the condition_ev's should come out in order:
# 1,1,1,-1,-1,-1, 0, 0, 0 (this is checked further down)
# 1,1,1, 0, 0, 0,-1,-1,-1
for sub_ses_id in design_df["participant_session_id"]:
if sub_ses_id.split("_")[-1] == conditions[0]:
condition_ev_one.append(1)
condition_ev_two.append(1)
elif sub_ses_id.split("_")[-1] == conditions[1]:
condition_ev_one.append(-1)
condition_ev_two.append(0)
elif sub_ses_id.split("_")[-1] == conditions[2]:
condition_ev_one.append(0)
condition_ev_two.append(-1)
group_config = {"sessions_list": conditions, "series_list": []}
elif condition_type == "scan":
# TODO: re-visit later, when session/scan difference in how to run
# TODO: group-level analysis repeated measures is streamlined and
# TODO: simplified
# the information needed in this part is not encoded in the group
# sublist! user inputs the two scan names, and we have a list of
# sub_ses (which needs to be doubled), with each scan paired to each
# half of this list (will need to ensure these scans exist for each
# selected derivative in the output directory later on)
for sub_ses_id in design_df["participant_session_id"]:
condition_ev_one.append(1)
condition_ev_two.append(1)
for sub_ses_id in design_df["participant_session_id"]:
condition_ev_one.append(-1)
condition_ev_two.append(0)
for sub_ses_id in design_df["participant_session_id"]:
condition_ev_one.append(0)
condition_ev_two.append(-1)
# NOTE: there is only one iteration of the sub_ses list in
# design_df["participant_id"] at this point! so use append
# (twice) triple that column:
design_df_double = design_df.append(design_df)
design_df = design_df_double.append(design_df)
group_config = {"sessions_list": [], "series_list": conditions}
else:
# TODO: msg
raise Exception
# let's check to make sure it came out right
# first third
for val in condition_ev_one[0:(len(condition_ev_one) / 3) - 1]:
if val != 1:
# TODO: msg
raise Exception
# second third
for val in condition_ev_one[(len(condition_ev_one) / 3):(len(condition_ev_one)/3)*2]:
if val != -1:
# TODO: msg
raise Exception
# third... third
for val in condition_ev_one[((len(condition_ev_one)/3)*2 + 1):]:
if val != 0:
# TODO: msg
raise Exception
# first third
for val in condition_ev_two[0:(len(condition_ev_two) / 3) - 1]:
if val != 1:
# TODO: msg
raise Exception
# second third
for val in condition_ev_two[(len(condition_ev_two) / 3):(len(condition_ev_two)/3)*2]:
if val != 0:
# TODO: msg
raise Exception
# third... third
for val in condition_ev_two[((len(condition_ev_two)/3)*2 + 1):]:
if val != -1:
# TODO: msg
raise Exception
# label the two covariate columns which encode the three conditions
column_one = "{0}_column_one".format(condition_type)
column_two = "{0}_column_two".format(condition_type)
design_df[column_one] = condition_ev_one
design_df[column_two] = condition_ev_two
# initalize the contrast dct's
contrast_one = {}
contrast_two = {}
contrast_three = {}
design_formula = "{0} + {1}".format(column_one, column_two)
# create the participant identity columns
for sub_ses_id in design_df["participant_session_id"]:
new_part_col = []
sub_id = sub_ses_id.split("_")[0]
new_part_label = "participant_{0}".format(sub_id)
for moving_sub_ses_id in design_df["participant_id"]:
moving_sub_id = moving_sub_ses_id.split("_")[0]
if moving_sub_id == sub_id:
new_part_col.append(1)
else:
new_part_col.append(0)
design_df[new_part_label] = new_part_col
contrast_one.update({new_part_label: 0})
contrast_two.update({new_part_label: 0})
contrast_three.update({new_part_label: 0})
if new_part_label not in design_formula:
design_formula = "{0} + {1}".format(design_formula,
new_part_label)
# finish the contrasts
# should be something like
# ses,ses,sub,sub,sub, etc.
# ses-1 - ses-2: 2, 1, 0, 0, 0...
# ses-1 - ses-3: 1, 2, 0, 0, 0...
# ses-2 - ses-3: -1, 1, 0, 0, 0, etc.
contrast_one.update({
"contrasts": "{0}_{1} - {2}_{3}".format(condition_type,
conditions[0],
condition_type,
conditions[1])})
contrast_two.update({
"contrasts": "{0}_{1} - {2}_{3}".format(condition_type,
conditions[0],
condition_type,
conditions[2])})
contrast_three.update({
"contrasts": "{0}_{1} - {2}_{3}".format(condition_type,
conditions[1],
condition_type,
conditions[2])})
contrast_one.update({column_one: 2, column_two: 1})
contrast_two.update({column_one: 1, column_two: 2})
contrast_three.update({column_one: -1, column_two: 1})
contrasts = [contrast_one, contrast_two, contrast_three]
contrasts_df = create_contrasts_template_df(design_df, contrasts)
# create design and contrasts matrix file paths
design_mat_path = os.path.join(output_dir, model_name,
"design_matrix_{0}.csv".format(model_name))
contrasts_mat_path = os.path.join(output_dir, model_name,
"contrasts_matrix_{0}.csv"
"".format(model_name))
# start group config yaml dictionary
group_config.update({"pheno_file": design_mat_path,
"ev_selections": {"demean": [],
"categorical": []},
"design_formula": design_formula,
"group_sep": "Off",
"grouping_var": None,
"custom_contrasts": contrasts_mat_path,
"model_name": model_name,
"output_dir": os.path.join(output_dir, model_name)})
return design_df, contrasts_df, group_config
def run(group_list_text_file, derivative_list, z_thresh, p_thresh,
preset=None, pheno_file=None, pheno_sub_label=None, output_dir=None,
model_name=None, covariate=None, condition_type=None, run=False):
# FSL FEAT presets: run regular group analysis with no changes to its
# original flow- use the generated pheno as the pheno, use the
# contrasts DF as a custom contrasts matrix, and auto-generate the
# group analysis config YAML as well
# NOTE: the input parameters above may come in as a dictionary instead
# or something
import os
import pandas as pd
import pkg_resources as p
# make life easy
keys_csv = p.resource_filename('CPAC', 'resources/cpac_outputs.csv')
try:
keys = pd.read_csv(keys_csv)
except Exception as e:
err = "\n[!] Could not access or read the cpac_outputs.csv " \
"resource file:\n{0}\n\nError details {1}\n".format(keys_csv, e)
raise Exception(err)
if derivative_list == 'all':
derivative_list = ['alff', 'falff', 'reho', 'sca_roi', 'sca_tempreg',
'vmhc', 'centrality', 'dr_tempreg']
if pheno_file and not pheno_sub_label:
# TODO: message
raise Exception("pheno file provided, but no pheno sub label")
if pheno_sub_label and not pheno_file:
# TODO: message
raise Exception("pheno sub label provided, but no pheno file")
if isinstance(group_list_text_file, list):
group_list = group_list_text_file
# write out a group analysis sublist text file so that it can be
# linked in the group analysis config yaml
group_list_text_file = os.path.join(output_dir, model_name,
"gpa_participant_list_"
"{0}.txt".format(model_name))
elif os.path.isfile(group_list_text_file):
group_list = read_group_list_text_file(group_list_text_file)
# write out a group analysis sublist text file so that it can be
# linked in the group analysis config yaml
group_list_text_file = os.path.join(output_dir, model_name,
"gpa_participant_list_"
"{0}.txt".format(model_name))
group_config = {"participant_list": group_list_text_file,
"participant_id_label": "participant_id",
"mean_mask": ["Group Mask"],
"custom_roi_mask": None,
"derivative_list": derivative_list,
"coding_scheme": ["Treatment"],
"z_threshold": [float(z_thresh)],
"p_threshold": [float(p_thresh)],
"contrasts": [],
"f_tests": []}
if not preset:
# TODO: this
pass
elif preset == "single_grp":
design_df, contrasts_df, group_config_update = \
preset_single_group_avg(group_list, pheno_df=None, covariate=None,
pheno_sub_label=None,
output_dir=output_dir,
model_name=model_name)
group_config.update(group_config_update)
elif preset == "single_grp_cov":
if not pheno_file:
# TODO: message
raise Exception("pheno file not provided")
if not covariate:
# TODO: message
raise Exception("covariate not provided")
pheno_df = read_pheno_csv_into_df(pheno_file, pheno_sub_label)
design_df, contrasts_df, group_config_update = \
preset_single_group_avg(group_list, pheno_df, covariate=covariate,
pheno_sub_label=pheno_sub_label,
output_dir=output_dir,
model_name=model_name)
group_config.update(group_config_update)
elif preset == "unpaired_two":
if not pheno_file:
# TODO: message
raise Exception("pheno file not provided")
if not covariate:
# TODO: message
raise Exception("the two groups were not provided")
# we're assuming covariate will be coming in as a string of either one
# covariate name, or a string with two covariates separated by a comma
# either way, it needs to be in list form in this case, not string
covariate = covariate.split(",")
pheno_df = read_pheno_csv_into_df(pheno_file, pheno_sub_label)
# in this case, "covariate" gets sent in as a list of two covariates
design_df, contrasts_df, group_config_update = \
preset_unpaired_two_group(group_list, pheno_df,
groups=covariate,
pheno_sub_label=pheno_sub_label,
output_dir=output_dir,
model_name=model_name)
group_config.update(group_config_update)
elif preset == "paired_two":
# run a two-sample paired T-test
# we need it as repeated measures- either session or scan
# and the list of subs
# also: the two session or scan names (in a list together), and
# whether they are sessions or scans
if | |
is NOT visible
# then we need to use the data of the refering node
def _resolve(node):
if node.visible and node.reference_node and not node.reference_node.visible:
node.children = node.reference_node.children
for referent in node.reference_node.referents:
referent.reference_node = node
node.reference_node = None
node.walk(_resolve)
# are we viewing all analysis?
if 'prune' not in session:
session['prune'] = True
# we only display the tree if we're looking at the alert
display_tree = None
if alert is analysis:
display_tree = TreeNode(analysis)
_recurse(display_tree)
_sort(display_tree)
if session['prune']:
_prune(display_tree)
# root node is visible
display_tree.visible = True
# if the show_root_observables config option is True then
# also all observables in the root node
if saq.CONFIG['gui'].getboolean('show_root_observables'):
for child in display_tree.children:
child.visible = True
_resolve_references(display_tree)
try:
# go ahead and get the list of all the users, we'll end up using it
all_users = db.session.query(User).order_by('username').all()
except Exception as e:
logging.error(f"idk why it breaks specifically right here {e}")
db.session.rollback()
all_users = db.session.query(User).order_by('username').all()
open_events = db.session.query(Event).filter(or_(Event.status == 'OPEN', Event.status == 'COMPLETED')).order_by(Event.creation_date.desc()).all()
malware = db.session.query(Malware).order_by(Malware.name.asc()).all()
companies = db.session.query(Company).order_by(Company.name.asc()).all()
campaigns = db.session.query(Campaign).order_by(Campaign.name.asc()).all()
# get list of domains that appear in the alert
domains = find_all_url_domains(analysis)
#domain_list = list(domains)
domain_list = sorted(domains, key=lambda k: domains[k])
domain_summary_str = create_histogram_string(domains)
return render_template(
'analysis/index.html',
alert=alert,
alert_tags=alert_tags,
observable=observable,
analysis=analysis,
ace_config=saq.CONFIG,
User=User,
db=db,
current_time=datetime.datetime.now(),
observable_types=VALID_OBSERVABLE_TYPES,
display_tree=display_tree,
prune_display_tree=session['prune'],
open_events=open_events,
malware=malware,
companies=companies,
campaigns=campaigns,
all_users=all_users,
disposition_css_mapping=DISPOSITION_CSS_MAPPING,
domains=domains,
domain_list=domain_list,
domain_summary_str=domain_summary_str,
tip=tip_factory(),
tip_indicator_summaries=alert.all_ioc_tip_summaries,
remediation_targets=get_remediation_targets([alert.uuid]),
)
@analysis.route('/file', methods=['GET'])
@login_required
@use_db
def file(db, c):
# get the list of available nodes (for all companies)
sql = """
SELECT
nodes.id,
nodes.name,
nodes.location,
company.id,
company.name
FROM
nodes LEFT JOIN node_modes ON nodes.id = node_modes.node_id
JOIN company ON company.id = nodes.company_id OR company.id = %s
WHERE
nodes.is_local = 0
AND ( nodes.any_mode OR node_modes.analysis_mode = %s )
ORDER BY
company.name,
nodes.location
"""
# get the available nodes for the default/primary company id
c.execute(sql, (None, ANALYSIS_MODE_CORRELATION,))
available_nodes = c.fetchall()
secondary_companies = saq.CONFIG['global'].get('secondary_company_ids', None)
if secondary_companies is not None:
secondary_companies = secondary_companies.split(',')
for secondary_company_id in secondary_companies:
c.execute(sql, (secondary_company_id, ANALYSIS_MODE_CORRELATION,))
more_nodes = c.fetchall()
for node in more_nodes:
if node not in available_nodes:
available_nodes = (node,) + available_nodes
logging.debug("Available Nodes: {}".format(available_nodes))
date = datetime.datetime.now().strftime("%m-%d-%Y %H:%M:%S")
return render_template('analysis/analyze_file.html',
observable_types=VALID_OBSERVABLE_TYPES,
date=date,
available_nodes=available_nodes,
queue=current_user.queue,
timezones=pytz.common_timezones)
@analysis.route('/upload_file', methods=['POST'])
@login_required
def upload_file():
downloadfile = request.files['file_path']
comment = request.form.get("comment", "")
alert_uuid = request.form.get("alert_uuid","")
if not downloadfile:
flash("No file specified for upload.")
return redirect(url_for('analysis.file'))
file_name = downloadfile.filename
if not alert_uuid:
alert = Alert()
alert.tool = 'Manual File Upload - '+file_name
alert.tool_instance = saq.CONFIG['global']['instance_name']
alert.alert_type = 'manual_upload'
alert.description = 'Manual File upload {0}'.format(file_name)
alert.event_time = datetime.datetime.now()
alert.details = {'user': current_user.username, 'comment': comment}
# XXX database.Alert does not automatically create this
alert.uuid = str(uuidlib.uuid4())
# we use a temporary directory while we process the file
alert.storage_dir = os.path.join(
saq.CONFIG['global']['data_dir'],
alert.uuid[0:3],
alert.uuid)
dest_path = os.path.join(SAQ_HOME, alert.storage_dir)
if not os.path.isdir(dest_path):
try:
os.makedirs(dest_path)
except Exception as e:
logging.error("unable to create directory {0}: {1}".format(dest_path, str(e)))
report_exception()
return
# XXX fix this!! we should not need to do this
# we need to do this here so that the proper subdirectories get created
alert.save()
alert.lock_uuid = acquire_lock(alert.uuid)
if alert.lock_uuid is None:
flash("unable to lock alert {}".format(alert))
return redirect(url_for('analysis.index'))
else:
alert = get_current_alert()
alert.lock_uuid = acquire_lock(alert.uuid)
if alert.lock_uuid is None:
flash("unable to lock alert {}".format(alert))
return redirect(url_for('analysis.index'))
if not alert.load():
flash("unable to load alert {}".format(alert))
return redirect(url_for('analysis.index'))
dest_path = os.path.join(SAQ_HOME, alert.storage_dir, os.path.basename(downloadfile.filename))
try:
downloadfile.save(dest_path)
except Exception as e:
flash("unable to save {} to {}: {}".format(file_name, dest_path, str(e)))
report_exception()
release_lock(alert.uuid, alert.lock_uuid)
return redirect(url_for('analysis.file'))
alert.add_observable(F_FILE, os.path.relpath(dest_path, start=os.path.join(SAQ_HOME, alert.storage_dir)))
alert.sync()
alert.schedule()
release_lock(alert.uuid, alert.lock_uuid)
return redirect(url_for('analysis.index', direct=alert.uuid))
@analysis.route('/analyze_alert', methods=['POST'])
@login_required
def analyze_alert():
alert = get_current_alert()
try:
result = ace_api.resubmit_alert(
remote_host = alert.node_location,
ssl_verification = abs_path(saq.CONFIG['SSL']['ca_chain_path']),
uuid = alert.uuid)
if 'error' in result:
e_msg = result['error']
logging.error(f"failed to resubmit alert: {e_msg}")
flash(f"failed to resubmit alert: {e_msg}")
else:
flash("successfully submitted alert for re-analysis")
except Exception as e:
logging.error(f"unable to submit alert: {e}")
flash(f"unable to submit alert: {e}")
return redirect(url_for('analysis.index', direct=alert.uuid))
@analysis.route('/observable_action_whitelist', methods=['POST'])
@login_required
def observable_action_whitelist():
alert = get_current_alert()
if alert is None:
return "operation failed: unable to find alert", 200
try:
alert.load()
except Exception as e:
return f"operation failed: unable to load alert {alert}: {e}", 200
observable = alert.get_observable(request.form.get('id'))
if not observable:
return "operation failed: unable to find observable in alert", 200
try:
if add_observable_tag_mapping(observable.tag_mapping_type,
observable.tag_mapping_value,
observable.tag_mapping_md5_hex,
'whitelisted'):
return "whitelisting added", 200
else:
return "operation failed", 200
except Exception as e:
return f"operation failed: {e}", 200
@analysis.route('/observable_action_un_whitelist', methods=['POST'])
@login_required
def observable_action_un_whitelist():
alert = get_current_alert()
if alert is None:
return "operation failed: unable to find alert", 200
try:
alert.load()
except Exception as e:
return f"operation failed: unable to load alert {alert}: {e}", 200
observable = alert.get_observable(request.form.get('id'))
if not observable:
return "operation failed: unable to find observable in alert", 200
try:
if remove_observable_tag_mapping(observable.tag_mapping_type,
observable.tag_mapping_value,
observable.tag_mapping_md5_hex,
'whitelisted'):
return "removed whitelisting", 200
else:
return "operation failed", 200
except Exception as e:
return f"operation failed: {e}", 200
@analysis.route('/observable_action', methods=['POST'])
@login_required
def observable_action():
from saq.crits import submit_indicator
alert = get_current_alert()
observable_uuid = request.form.get('observable_uuid')
action_id = request.form.get('action_id')
logging.debug("alert {} observable {} action {}".format(alert, observable_uuid, action_id))
lock_uuid = acquire_lock(alert.uuid)
if lock_uuid is None:
return "Unable to lock alert.", 500
try:
if not alert.load():
return "Unable to load alert.", 500
observable = alert.observable_store[observable_uuid]
if action_id == 'mark_as_suspect':
if not observable.is_suspect:
observable.is_suspect = True
alert.sync()
return "Observable marked as suspect.", 200
elif action_id == ACTION_UPLOAD_TO_CRITS:
try:
indicator_id = submit_indicator(observable)
if indicator_id is None:
return "submission failed", 500
return indicator_id, 200
except Exception as e:
logging.error("unable to submit {} to crits: {}".format(observable, str(e)))
report_exception()
return "unable to submit to crits: {}".format(str(e)), 500
elif action_id == ACTION_COLLECT_FILE:
try:
logging.info("user {} added directive {} to {}".format(current_user, DIRECTIVE_COLLECT_FILE, observable))
observable.add_directive(DIRECTIVE_COLLECT_FILE)
alert.sync()
return "File collection requested.", 200
except Exception as e:
logging.error("unable to mark observable {} for file collection".format(observable))
report_exception()
return "request failed - check logs", 500
elif action_id in [ACTION_SET_CBC_IOC_IGNORE, ACTION_SET_CBC_IOC_ACTIVE]:
from saq.carbon_black import CBC_API
from cbinterface.psc.intel import ignore_ioc, activate_ioc
if not CBC_API:
return "Unavailable", 400
try:
report_id, ioc_id = observable.value[len('cbc:'):].split('/', 1)
result = None
if action_id == ACTION_SET_CBC_IOC_IGNORE:
result = ignore_ioc(CBC_API, report_id, ioc_id)
if result:
return "Ignored", 200
if action_id == ACTION_SET_CBC_IOC_ACTIVE:
result = activate_ioc(CBC_API, report_id, ioc_id)
if result:
return "Activated", 200
return f"Unexpected Result: {result}", 400
except Exception as e:
logging.error(f"unable to execute cbc ioc update action: {e}")
return f"Error: {e}", 400
elif action_id in [ ACTION_SET_SIP_INDICATOR_STATUS_ANALYZED,
ACTION_SET_SIP_INDICATOR_STATUS_INFORMATIONAL,
ACTION_SET_SIP_INDICATOR_STATUS_NEW ]:
if action_id == ACTION_SET_SIP_INDICATOR_STATUS_ANALYZED:
status = saq.intel.SIP_STATUS_ANALYZED
elif action_id == ACTION_SET_SIP_INDICATOR_STATUS_INFORMATIONAL:
status = saq.intel.SIP_STATUS_INFORMATIONAL
else:
status = saq.intel.SIP_STATUS_NEW
sip_id = int(observable.value[len('sip:'):])
logging.info(f"{current_user.username} set sip indicator {sip_id} status to {status}")
result = saq.intel.set_sip_indicator_status(sip_id, status)
return "OK", 200
elif action_id == ACTION_FILE_SEND_TO:
host = request.form.get('hostname')
try:
# data is validated by the uploader
logging.info(f"attempting to send file '{observable}' to {host}")
uploader = FileUploader(host, alert.storage_dir, observable.value, alert.uuid)
uploader.uploadFile()
except Exception as error:
logging.error(f"unable to send file '{observable}' to {host} due to error: {error}")
return f"Error: {error}", 400
else:
return "File uploaded", 200
elif action_id in [ACTION_URL_CRAWL, ACTION_FILE_RENDER]:
from saq.modules.url import CrawlphishAnalyzer
from saq.modules.render import RenderAnalyzer
# make sure alert is locked before starting new analysis
if alert.is_locked():
try:
# crawlphish only works for URL observables, so we want to limit these actions to the URL observable action only
if action_id == ACTION_URL_CRAWL:
observable.add_directive(DIRECTIVE_CRAWL)
observable.remove_analysis_exclusion(CrawlphishAnalyzer)
logging.info(f"user {current_user} added directive {DIRECTIVE_CRAWL} to {observable}")
# both URLs and files can be rendered, so we can do that in either case (ACTION_URL_CRAWL or ACTION_FILE_RENDER)
observable.remove_analysis_exclusion(RenderAnalyzer)
logging.info(f"user {current_user} removed analysis exclusion for RenderAnalyzer for {observable}")
alert.analysis_mode = ANALYSIS_MODE_CORRELATION
alert.sync()
add_workload(alert)
except Exception as e:
logging.error(f"unable to mark observable {observable} for crawl/render")
report_exception()
return "Error: Crawl/Render Request failed - Check logs", 500
else:
return "URL crawl/render successfully requested.", 200
else:
return "Alert wasn't locked for crawl/render, try again later", 500
return "invalid action_id", 500
except Exception as e:
traceback.print_exc()
return "Unable to load alert: {}".format(str(e)), 500
finally:
release_lock(alert.uuid, lock_uuid)
@analysis.route('/mark_suspect', methods=['POST'])
@login_required
def mark_suspect():
alert = get_current_alert()
observable_uuid = request.form.get("observable_uuid")
lock_uuid = acquire_lock(alert.uuid)
if lock_uuid is None:
flash("unable to lock alert")
return "", 400
try:
if not alert.load():
flash("unable to load alert")
return "", 400
observable = alert.observable_store[observable_uuid]
observable.is_suspect = True
alert.sync()
except Exception as e:
| |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from ECAgent.Core import Model
# Can be used to customize CSS of Visualizer
external_stylesheets = ['https://rawgit.com/BrandonGower-Winter/ABMECS/master/Assets/VisualizerCustom.css',
'https://rawgit.com/BrandonGower-Winter/ABMECS/master/Assets/VisualizerBase.css']
class VisualInterface:
"""
Ths is the base class for Visual Interfaces.
VisualInterface's utilize the dash package to create a WebApp to allow individuals to view the results of their
model once a run has been completed or in real-time.
There are a few things to note about the VisualInterface class:
* By calling the VisualInterface.__init__() method, your WebApp will have features setup for you: Namely, play,
stop, restart and step. It'll also include a banner with your System's name as a title on it.
* A frameFreq of 0.0 means that your system is static and will only ever be constructed once.
If you want a dynamic WebApp, you must set the frameFreq to some non-zero positive number. If your frameFreq is 0.0,
the play, stop, restart and step buttons will not be added to your WebApp.
* The server/WebApp will start once you call the VisualInterface.app.run_server().
* The frameFreq property determines how frequently (in milliseconds) the SystemManager.executeSystems() method is
called and how often your your graphs will update.
"""
def __init__(self, name, model: Model, frameFreq: float = 0.0):
self.name = name
self.model = model
self.frameFreq = frameFreq
self.running = False # Is used to determine whether a dynamic model is running or not.
# Create app
self.app = dash.Dash(
self.name, meta_tags=[{"name": "viewport", "content": "width=device-width"}],
external_stylesheets=external_stylesheets
)
# Create parameter lists
self.displays = []
self.parameters = []
self.createBaseLayout()
def isStatic(self) -> bool:
return self.frameFreq == 0.0
def execute(self):
self.render()
def render(self):
pass
def createBaseLayout(self):
"""Creates the base layout"""
# Create banner
banner = html.Div(
className="app-banner row",
children=[
html.H2(className="h2-title", children=self.name),
html.H2(className="h2-title-mobile", children=self.name),
],
)
# Add parameter header
self.addParameter(createLabel('parameter-heading', 'Parameters:'))
# If framerate > 0, create the play, stop, and restart buttons and Timestep label
if not self.isStatic():
# Add Play/Restart/Step Buttons
banner.children.append(
html.Div(
className='div-play-buttons',
id='dynamic-button',
children=[
html.Button("Play", id='play-stop-button', n_clicks=0),
html.Button('Restart', id='restart-button', n_clicks=0),
html.Button('Step', id='step-button', n_clicks=0),
dcc.Interval(
id='interval-component',
interval=self.frameFreq,
n_intervals=0
)
]
)
)
# Add Timestep label
self.parameters.append(createLabel('timestep-label', 'Timestep: 0'))
# Apply Play/Stop Callback
self.app.callback(
dash.dependencies.Output('play-stop-button', 'children'),
[dash.dependencies.Input('play-stop-button', 'n_clicks')]
)(self.play_button_callback)
# Apply executeSystems() on interval callback and Step button callback
self.app.callback(
dash.dependencies.Output('timestep-label', 'children'),
[dash.dependencies.Input('interval-component', 'n_intervals'),
dash.dependencies.Input('step-button', 'n_clicks')]
)(self.execute_system_on_play_callback)
self.app.layout = html.Div(
children=[
# Error Message
html.Div(id="error-message"),
# Top Banner
banner,
# Body of the App
html.Div(
className="row app-body",
children=[
# User Controls
html.Div(
className="four columns card",
children=html.Div(
className="bg-white user-control",
children=self.parameters)
),
# Graph
html.Div(
className="eight columns card-left",
children=self.displays,
style={'margin-left': 0}
),
dcc.Store(id="error", storage_type="memory"),
],
),
]
)
def addDisplay(self, content, add_break=True):
self.displays.append(content)
if add_break:
self.displays.append(html.Br())
def addParameter(self, content):
self.parameters.append(content)
# #################################### Class Callbacks ###########################################
def play_button_callback(self, n_clicks):
if n_clicks % 2 == 0:
self.running = False
return 'Play'
else:
self.running = True
return 'Stop'
def execute_system_on_play_callback(self, n_intervals, n_clicks):
context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
if context == 'step-button':
if not self.running:
self.model.systemManager.executeSystems()
elif self.running:
self.model.systemManager.executeSystems()
return "Timestep: {}".format(self.model.systemManager.timestep)
# ############################## Graph and Parameter Functionality ##############################
def createScatterPlot(title, data: [[[float], [float], dict]], layout_kwargs: dict = {}):
"""Creates a Scatter plot Figure. This function supports multiple traces supplied to the 'data' parameter
Data should be supplied in the following format:
[[xdata_1,ydata_1, fig_layout_1], [xdata_2, ydata_2, fig_layout_2], ..., [xdata_n,ydata_n, fig_layout_n]]
The 'fig_layout' property is optional. If it is supplied, the trace in question will be updated to include all of
the properties specified..
"""
traces = []
for data_packet in data:
scatter = go.Scatter(x=data_packet[0], y=data_packet[1])
traces.append(scatter)
if len(data_packet) > 2:
scatter.update(data_packet[2])
return go.Figure(data=traces, layout=go.Layout(title=title, **layout_kwargs))
def createScatterGLPlot(title, data: [[[float], [float], dict]], layout_kwargs: dict = {}):
"""Creates a Scatter plot Figure that will be rendered using WebGL.
This function supports multiple traces supplied to the 'data' parameter Data should be supplied in the
following format:
[[xdata_1,ydata_1, fig_layout_1], [xdata_2, ydata_2, fig_layout_2], ..., [xdata_n,ydata_n, fig_layout_n]]
The 'fig_layout' property is optional. If it is supplied, the trace in question will be updated to include all of
the properties specified..
"""
traces = []
for data_packet in data:
scatter = go.Scattergl(x=data_packet[0], y=data_packet[1])
traces.append(scatter)
if len(data_packet) > 2:
scatter.update(data_packet[2])
return go.Figure(data=traces, layout=go.Layout(title=title, **layout_kwargs))
def createBarGraph(title: str, data: [[[float], [float], dict]], layout_kwargs: dict = {}):
"""Creates a Bar Graph Figure. This function supports multiple traces supplied to the 'data' parameter
Data should be supplied in the following format:
[[xdata_1,ydata_1, fig_layout_1], [xdata_2, ydata_2, fig_layout_2], ..., [xdata_n,ydata_n, fig_layout_n]]
The 'fig_layout' property is optional. If it is supplied, the trace in question will be updated to include all of
the properties specified..
"""
traces = []
for data_packet in data:
bar = go.Bar(x=data_packet[0], y=data_packet[1])
traces.append(bar)
if len(data_packet) > 2:
bar.update(data_packet[2])
return go.Figure(data=traces, layout=go.Layout(title=title, **layout_kwargs))
def createHeatMap(title: str, data: [[float]], heatmap_kwargs: dict = {}, layout_kwargs: dict = {}):
"""Creates a HeatMap Figure object using Plotly graph objects. The data object determines the dimensions of the
heatmap. The len(data) will be the height. The len(data[i]) will be the width of the heatmap. The Heatmap is
constructed in a bottom-up and left-to-right manner.
Discrete X and Y categories can be specified, this is done by supplying xData and yData with the X and Y category
name respectively. The len(xData) must be equal to the width of your Heatmap, while len(yData) must be equal to the
height of your Heatmap.
A custom color scale can be supplied, ensure that it follows the correct format and that the threshold values are
normalized and that the color scales are in rgb like so 'rgb(r_val, g_val, b_val)'"""
return go.Figure(data=go.Heatmap(
z=data,
**heatmap_kwargs
), layout=go.Layout(title=title, **layout_kwargs))
def createHeatMapGL(title: str, data: [[float]], heatmap_kwargs: dict = {}, layout_kwargs: dict = {}):
"""Creates a HeatMap Figure object using Plotly graph objects that will be rendered by WebGL.
The data object determines the dimensions of the heatmap. The len(data) will be the height.
The len(data[i]) will be the width of the heatmap.
The Heatmap is constructed in a bottom-up and left-to-right manner.
Discrete X and Y categories can be specified, this is done by supplying xData and yData with the X and Y category
name respectively. The len(xData) must be equal to the width of your Heatmap, while len(yData) must be equal to the
height of your Heatmap.
A custom color scale can be supplied, ensure that it follows the correct format and that the threshold values are
normalized and that the color scales are in rgb like so 'rgb(r_val, g_val, b_val)'"""
return go.Figure(data=go.Heatmapgl(
z=data,
**heatmap_kwargs
), layout=go.Layout(title=title, **layout_kwargs))
def createContourMap(title: str, data: [[float]], contour_kwargs: dict = {}, layout_kwargs: dict = {}):
"""Creates a Contour Figure object using Plotly graph objects. The data object determines the dimensions of the
Contour plot. The len(data) will be the height. The len(data[i]) will be the width of the contour plot.
The contour plot is constructed in a bottom-up and left-to-right manner.
The contour plot can be customized using the contour_kwargs dict. The dict will be supplied to the contour plot
graph object when it is created. See the plotly api for a list of customizable properties. This can be similarly be
applied to layout_kwargs which can change the layout of contour plot."""
return go.Figure(data=go.Contour(
z=data,
**contour_kwargs
), layout=go.Layout(title=title, **layout_kwargs))
def createTable(title: str, headers: [str], cells: [[]], header_kwargs: dict = {}, cell_kwargs: dict = {},
layout_kwargs: dict = {}):
"""Creates a Table figure using Plotly graph objects. Table headers and cells need to be supplied separately.
The data format for the headers and cells are as follows:
Headers: [hdr1, hdr2,...,hdrN]
Cells: [column1_data, column2_data,..., columnN_data].
The Table headers and cells are customized separately using the header_kwargs and cell_kwargs parameters. The
layout of the Table can also be customized using the layout_kwargs."""
return go.Figure(data=go.Table(
header=dict(values=headers, **header_kwargs),
cells=dict(values=cells, **cell_kwargs)
), layout=go.Layout(title=title, **layout_kwargs))
def createPieChart(title: str, labels: [str], values: [float], pie_kwargs: dict = {}, layout_kwargs: dict = {}):
""" Creates a Pie Chart Figure using Plotly graph objects. Chart labels and values need to be supplied separately.
The data format for the labels and | |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import os.path
import yaml
from reno import defaults
LOG = logging.getLogger(__name__)
_TEMPLATE = """\
---
prelude: >
Replace this text with content to appear at the top of the section for this
release. All of the prelude content is merged together and then rendered
separately from the items listed in other parts of the file, so the text
needs to be worded so that both the prelude and the other items make sense
when read independently. This may mean repeating some details. Not every
release note requires a prelude. Usually only notes describing major
features or adding release theme details should have a prelude.
features:
- |
List new features here, or remove this section. All of the list items in
this section are combined when the release notes are rendered, so the text
needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
issues:
- |
List known issues here, or remove this section. All of the list items in
this section are combined when the release notes are rendered, so the text
needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
upgrade:
- |
List upgrade notes here, or remove this section. All of the list items in
this section are combined when the release notes are rendered, so the text
needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
deprecations:
- |
List deprecations notes here, or remove this section. All of the list
items in this section are combined when the release notes are rendered, so
the text needs to be worded so that it does not depend on any information
only available in another section, such as the prelude. This may mean
repeating some details.
critical:
- |
Add critical notes here, or remove this section. All of the list items in
this section are combined when the release notes are rendered, so the text
needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
security:
- |
Add security notes here, or remove this section. All of the list items in
this section are combined when the release notes are rendered, so the text
needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
fixes:
- |
Add normal bug fixes here, or remove this section. All of the list items
in this section are combined when the release notes are rendered, so the
text needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
other:
- |
Add other notes here, or remove this section. All of the list items in
this section are combined when the release notes are rendered, so the text
needs to be worded so that it does not depend on any information only
available in another section, such as the prelude. This may mean repeating
some details.
"""
class Config(object):
_OPTS = {
# The notes subdirectory within the relnotesdir where the
# notes live.
'notesdir': defaults.NOTES_SUBDIR,
# Should pre-release versions be merged into the final release
# of the same number (1.0.0.0a1 notes appear under 1.0.0).
'collapse_pre_releases': True,
# Should the scanner stop at the base of a branch (True) or go
# ahead and scan the entire history (False)?
'stop_at_branch_base': True,
# The git branch to scan. Defaults to the "current" branch
# checked out.
'branch': None,
# The earliest version to be included. This is usually the
# lowest version number, and is meant to be the oldest
# version.
'earliest_version': None,
# The template used by reno new to create a note.
'template': _TEMPLATE,
# The RE pattern used to match the repo tags representing a valid
# release version. The pattern is compiled with the verbose and unicode
# flags enabled.
'release_tag_re': '''
((?:[\d.ab]|rc)+) # digits, a, b, and rc cover regular and
# pre-releases
''',
# The RE pattern used to check if a valid release version tag is also a
# valid pre-release version. The pattern is compiled with the verbose
# and unicode flags enabled. The pattern must define a group called
# 'pre_release' that matches the pre-release part of the tag and any
# separator, e.g for pre-release version '12.0.0.0rc1' the default RE
# pattern will identify '.0rc1' as the value of the group
# 'pre_release'.
'pre_release_tag_re': '''
(?P<pre_release>\.\d+(?:[ab]|rc)+\d*)$
''',
# The pattern for names for branches that are relevant when
# scanning history to determine where to stop, to find the
# "base" of a branch. Other branches are ignored.
'branch_name_re': 'stable/.+',
# The identifiers and names of permitted sections in the
# release notes, in the order in which the final report will
# be generated. A prelude section will always be automatically
# inserted before the first element of this list.
'sections': [
['features', 'New Features'],
['issues', 'Known Issues'],
['upgrade', 'Upgrade Notes'],
['deprecations', 'Deprecation Notes'],
['critical', 'Critical Issues'],
['security', 'Security Issues'],
['fixes', 'Bug Fixes'],
['other', 'Other Notes'],
],
# When this option is set to True, any merge commits with no
# changes and in which the second or later parent is tagged
# are considered "null-merges" that bring the tag information
# into the current branch but nothing else.
#
# OpenStack used to use null-merges to bring final release
# tags from stable branches back into the master branch. This
# confuses the regular traversal because it makes that stable
# branch appear to be part of master and/or the later stable
# branch. This option allows us to ignore those.
'ignore_null_merges': True,
# Note files to be ignored. It's useful to be able to ignore a
# file if it is edited on the wrong branch. Notes should be
# specified by their filename or UID. Setting the value in the
# configuration file makes it apply to all branches.
'ignore_notes': [],
}
@classmethod
def get_default(cls, opt):
"Return the default for an option."
try:
return cls._OPTS[opt]
except KeyError:
raise ValueError('unknown option name %r' % (opt,))
def __init__(self, reporoot, relnotesdir=None):
"""Instantiate a Config object
:param str reporoot:
The root directory of the repository.
:param str relnotesdir:
The directory containing release notes. Defaults to
'releasenotes'.
"""
self.reporoot = reporoot
if relnotesdir is None:
relnotesdir = defaults.RELEASE_NOTES_SUBDIR
self.relnotesdir = relnotesdir
# Initialize attributes from the defaults.
self.override(**self._OPTS)
self._contents = {}
self._load_file()
def _load_file(self):
filenames = [
os.path.join(self.reporoot, self.relnotesdir, 'config.yaml'),
os.path.join(self.reporoot, 'reno.yaml')]
for filename in filenames:
if os.path.isfile(filename):
break
else:
LOG.info('no configuration file in: %s', ', '.join(filenames))
return
try:
with open(filename, 'r') as fd:
self._contents = yaml.safe_load(fd)
except IOError as err:
LOG.warning('did not load config file %s: %s', filename, err)
else:
self.override(**self._contents)
def override(self, **kwds):
"""Set the values of the named configuration options.
Take the values of the keyword arguments as the current value
of the same option, regardless of whether a value is | |
# Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import, unicode_literals, print_function
import pytest
import six
from thriftrw.errors import ThriftCompilerError
from thriftrw.spec.struct import StructTypeSpec
from thriftrw.spec.field import FieldSpec
from thriftrw.idl import Parser
from thriftrw.spec import primitive as prim_spec
from thriftrw.spec.reference import TypeReference
from thriftrw.wire import ttype
from ..util.value import vstruct, vbinary, vi64, vi32
@pytest.fixture
def parse():
return Parser(start='struct', silent=True).parse
def test_compile_missing_field_id(parse):
struct_ast = parse('struct Foo { required string param }')
with pytest.raises(ThriftCompilerError) as exc_info:
StructTypeSpec.compile(struct_ast)
assert 'Please specify the numeric ID for the field' in str(exc_info)
def test_compile_missing_requiredness(parse):
struct_ast = parse('struct Foo { 1: string param }')
with pytest.raises(ThriftCompilerError) as exc_info:
StructTypeSpec.compile(struct_ast)
assert (
'Please specify whether the field is optional or required'
in str(exc_info)
)
def test_compile_non_strict_missing_requiredness(parse):
struct_ast = parse('struct Foo { 1: string param }')
assert StructTypeSpec.compile(struct_ast, require_requiredness=False)
def test_compile_duplicate_fields(parse):
struct_ast = parse(
'struct Foo { 1: required string x; 2: optional i32 x }'
)
with pytest.raises(ThriftCompilerError) as exc_info:
StructTypeSpec.compile(struct_ast)
assert 'Field "x" of struct "Foo"' in str(exc_info)
assert 'has duplicates' in str(exc_info)
def test_compile_duplicate_field_ids(parse):
struct_ast = parse(
'struct Foo { 1: required string x; 1: optional i32 y; }'
)
with pytest.raises(ThriftCompilerError) as exc_info:
StructTypeSpec.compile(struct_ast)
assert 'Field ID "1" of struct "Foo"' in str(exc_info)
assert 'has already been used' in str(exc_info)
def test_compile_primitives(parse):
struct_ast = parse('''struct PrimitiveStruct {
1: required string x;
2: optional i32 y;
3: required double z;
}''')
spec = StructTypeSpec.compile(struct_ast)
assert spec.name == 'PrimitiveStruct'
assert spec.fields == [
FieldSpec(id=1, name='x', spec=prim_spec.TextTypeSpec, required=True),
FieldSpec(id=2, name='y', spec=prim_spec.I32TypeSpec, required=False),
FieldSpec(
id=3, name='z', spec=prim_spec.DoubleTypeSpec, required=True
),
]
def test_compile_reference(parse):
struct_ast = parse('''struct RefStruct {
1: optional string x;
2: required SomeCustomType y;
3: optional AnotherCustomType z;
}''')
spec = StructTypeSpec.compile(struct_ast)
assert spec.name == 'RefStruct'
assert spec.fields == [
FieldSpec(id=1, name='x', spec=prim_spec.TextTypeSpec, required=False),
FieldSpec(
id=2, name='y', spec=TypeReference('SomeCustomType', 3),
required=True,
),
FieldSpec(
id=3, name='z', spec=TypeReference('AnotherCustomType', 4),
required=False,
),
]
def test_link_simple(scope):
spec = StructTypeSpec('SimpleStruct', fields=[
FieldSpec(1, 'a', spec=prim_spec.TextTypeSpec, required=True),
FieldSpec(2, 'b', spec=prim_spec.BinaryTypeSpec, required=False),
FieldSpec(3, 'c', spec=prim_spec.I32TypeSpec, required=True),
FieldSpec(4, 'd', spec=prim_spec.I64TypeSpec, required=False),
])
spec = spec.link(scope)
SimpleStruct = spec.surface
assert SimpleStruct.type_spec is spec
assert 'SimpleStruct(a, c, b=None, d=None)' in SimpleStruct.__doc__
def test_load_simple(loads):
SimpleStruct = loads('''
struct SimpleStruct {
1: required string a
2: optional binary b
3: required i32 c
4: optional i64 d
}
''').SimpleStruct
obj = SimpleStruct('hello', 42)
assert obj.a == 'hello'
assert obj.c == 42
assert obj.b is None
assert obj.d is None
obj = SimpleStruct(c=42, a='hello', b=b'world', d=2)
assert obj.a == 'hello'
assert obj.b == b'world'
assert obj.c == 42
assert obj.d == 2
assert SimpleStruct('hello', 42) == SimpleStruct('hello', 42)
assert SimpleStruct('hello', 42) != SimpleStruct('world', 42)
assert 'SimpleStruct(a, c, b=None, d=None)' in SimpleStruct.__doc__
def test_simple_convert(loads):
SimpleStruct = loads('''struct SimpleStruct {
1: required string a;
2: optional binary b
}''').SimpleStruct
spec = SimpleStruct.type_spec
cases = [
(
SimpleStruct('hello', b'world'),
vstruct(
(1, ttype.BINARY, vbinary(b'hello')),
(2, ttype.BINARY, vbinary(b'world')),
),
{'a': 'hello', 'b': b'world'},
),
(
SimpleStruct('hello'),
vstruct((1, ttype.BINARY, vbinary(b'hello'))),
{'a': 'hello'},
),
]
for value, wire_value, prim_value in cases:
assert spec.to_wire(value) == wire_value
assert value.to_primitive() == prim_value
assert spec.from_wire(wire_value) == value
assert SimpleStruct.from_primitive(prim_value) == value
assert 'SimpleStruct(a, b=None)' in SimpleStruct.__doc__
def test_required_field_missing(loads):
X = loads('struct X { 1: required string foo }').X
spec = X.type_spec
x = X('foo')
x.foo = None
with pytest.raises(TypeError) as exc_info:
spec.validate(x)
assert 'Field "foo" of "X" is required' in str(exc_info)
def test_int_field_too_large(loads):
X = loads('struct X { 1: optional i16 foo }').X
spec = X.type_spec
x = X()
x.foo = 1000000000000
with pytest.raises(ValueError) as exc_info:
spec.validate(x)
assert 'Field 1 of X is invalid' in str(exc_info)
def test_empty(loads):
S = loads('struct S {}').S
spec = S.type_spec
assert spec.to_wire(S()) == vstruct()
def test_simple_round_trip(loads):
RoundTripStruct = loads('''struct RoundTripStruct {
1: required string a;
2: optional binary b;
}''').RoundTripStruct
spec = RoundTripStruct.type_spec
assert RoundTripStruct('hello', b'world') == (
spec.from_wire(spec.to_wire(RoundTripStruct('hello', b'world')))
)
assert RoundTripStruct('hello') == (
spec.from_wire(spec.to_wire(RoundTripStruct('hello')))
)
def test_default_values(loads):
Struct = loads('''struct DefaultStruct {
1: optional i32 optionalField;
2: optional i64 optionalFieldWithDefault = 42;
3: required string requiredFieldWithDefault = "";
4: required string requiredField;
}''').DefaultStruct
spec = Struct.type_spec
# We should end up with this signature:
#
# Struct(
# requiredField,
# optionalField,
# optionalFieldWithDefault,
# requiredFieldWithDefault,
# )
#
cases = [
(
Struct('hello'),
vstruct(
(2, ttype.I64, vi64(42)),
(3, ttype.BINARY, vbinary(b'')),
(4, ttype.BINARY, vbinary(b'hello')),
),
{
'optionalFieldWithDefault': 42,
'requiredFieldWithDefault': '',
'requiredField': 'hello',
},
),
(
Struct('hello', 10, 100, u'world'),
vstruct(
(1, ttype.I32, vi32(10)),
(2, ttype.I64, vi64(100)),
(3, ttype.BINARY, vbinary(b'world')),
(4, ttype.BINARY, vbinary(b'hello')),
),
{
'optionalField': 10,
'optionalFieldWithDefault': 100,
'requiredFieldWithDefault': 'world',
'requiredField': 'hello',
},
)
]
for value, wire_value, prim_value in cases:
assert spec.to_wire(value) == wire_value
assert value.to_primitive() == prim_value
assert spec.from_wire(wire_value) == value
assert Struct.from_primitive(prim_value) == value
assert (
'DefaultStruct(requiredField, optionalField=None, '
'optionalFieldWithDefault=None, requiredFieldWithDefault=None)'
) in Struct.__doc__
def test_default_binary_value(loads):
Struct = loads('''struct Struct {
1: optional binary field = "";
}''').Struct
assert isinstance(Struct().field, six.binary_type)
def test_constructor_behavior(loads):
Struct = loads('''struct ConstructorStruct {
1: optional i32 optionalField;
2: optional i64 optionalFieldWithDefault = 42;
3: required binary requiredFieldWithDefault = "";
4: required string requiredField;
}''').ConstructorStruct
assert (
'ConstructorStruct(requiredField, optionalField=None, '
'optionalFieldWithDefault=None, requiredFieldWithDefault=None)'
) in Struct.__doc__
with pytest.raises(TypeError) as exc_info:
Struct()
assert 'takes at least 2 arguments (1 given)' in str(exc_info)
with pytest.raises(TypeError) as exc_info:
Struct(1, 2, 3, 4, 5)
assert 'at most 5 arguments (6 given)' in str(exc_info)
with pytest.raises(TypeError) as exc_info:
Struct('hello', requiredField='world')
assert 'multiple values for argument "requiredField"' in str(exc_info)
with pytest.raises(TypeError) as exc_info:
Struct('hello', unknown='world')
assert 'unexpected keyword argument "unknown"' in str(exc_info)
with pytest.raises(TypeError) as exc_info:
Struct(optionalField=10)
assert 'is required' in str(exc_info)
def test_constructor_behavior_with_nested_types(loads):
Struct = loads('''struct Struct {
1: optional list<string> strings;
}''').Struct
with pytest.raises(TypeError):
Struct(strings=[1])
def test_validate_with_nested_primitives(loads):
Struct = loads('''struct Struct {
1: optional list<string> strings;
2: optional map<string, i32> values
}''').Struct
with pytest.raises(TypeError):
s = Struct(strings=[1])
Struct.type_spec.validate(s)
with pytest.raises(TypeError):
Struct.type_spec.validate(
Struct(values={1: 1})
)
Struct.type_spec.validate(Struct(strings=['foo']))
Struct.type_spec.validate(Struct(values={'a': 1}))
def test_mutable_default(loads):
"""Mutating default values should have no effect.
"""
m = loads('''
struct X {
1: required list<string> foo = []
2: required map<string, string> bar = {}
}
struct Y {
1: required X x = {"foo": ["x", "y"], "bar": {"a": "b"}}
}
''')
X = m.X
Y = m.Y
# mutable collections
assert [] == X().foo
X().foo.append('hello')
assert [] == X().foo
assert {} == X().bar
X().bar['x'] = 'y'
assert {} == X().bar
# mutable structs
assert X(foo=['x', 'y'], bar={'a': 'b'}) == Y().x
y = Y()
y.x.foo = ["a", "b"]
assert X(foo=['x', 'y'], bar={'a': 'b'}) == Y().x
Y().x.foo.append('z')
assert X(foo=['x', 'y'], bar={'a': 'b'}) == Y().x
def test_self_referential(loads):
Cons = loads('''struct Cons {
1: required i32 value
2: optional Cons next
}''').Cons
spec = Cons.type_spec
c = Cons(1, Cons(2, Cons(3, Cons(4, Cons(5)))))
assert spec.to_wire(c) == vstruct(
(1, ttype.I32, vi32(1)),
(2, ttype.STRUCT, vstruct(
(1, ttype.I32, vi32(2)),
(2, ttype.STRUCT, vstruct(
(1, ttype.I32, vi32(3)),
(2, ttype.STRUCT, vstruct(
(1, ttype.I32, vi32(4)),
(2, ttype.STRUCT, vstruct(
(1, ttype.I32, vi32(5)),
)),
)),
)),
)),
)
assert c.to_primitive() == {
'value': 1,
'next': {
'value': 2,
'next': {
'value': 3,
'next': {
'value': 4,
'next': {'value': 5},
},
},
},
}
assert spec.from_wire(spec.to_wire(c)) == c
assert Cons.from_primitive(c.to_primitive()) == c
@pytest.mark.parametrize('expr', [
'struct Foo { 1: optional list<string> foo = {} }',
'struct Bar { 1: optional list<string> | |
import asyncio
from telethon.errors.rpcerrorlist import YouBlockedUserError
from dragons import BOTLOG, BOTLOG_CHATID, drgub
from ..core.logger import logging
from ..core.managers import edit_delete, edit_or_reply
from ..helpers.utils import _format, get_user_from_event, reply_id
from ..sql_helper.global_collectionjson import add_collection, get_collection
LOGS = logging.getLogger(__name__)
FBAN_GROUP_ID = Config.FBAN_GROUP_ID
plugin_category = "admin"
rose = "@MissRose_bot"
fbanresults = [
"New FedBan",
"FedBan Reason update",
"has already been fbanned, with the exact same reason.",
]
unfbanresults = ["I'll give", "Un-FedBan", "un-FedBan"]
@drgub.drg_cmd(
pattern="fban(?:\s|$)([\s\S]*)",
command=("fban", plugin_category),
info={
"header": "Ban the person in your database federations",
"description": "Will fban the person in the all feds of given category which you stored in database.",
"usage": "{tr}fban <userid/username/reply> <category> <reason>",
},
)
async def group_fban(event):
"fban a person."
if FBAN_GROUP_ID == 0:
return await edit_delete(
event,
"__For working of this cmd you need to set FBAN_GROUP_ID in heroku vars__",
)
user, reason = await get_user_from_event(event)
if not user:
return
if user.id == event.client.uid:
return await edit_delete(event, "__You can't fban yourself.__")
if not reason:
return await edit_delete(
event, "__You haven't mentioned category name and reason for fban__"
)
reasons = reason.split(" ", 1)
fedgroup = reasons[0]
reason = "Not Mentioned" if len(reasons) == 1 else reasons[1]
if get_collection("fedids") is not None:
feds = get_collection("fedids").json
else:
feds = {}
if fedgroup in feds:
fedids = feds[fedgroup]
else:
return await edit_delete(
event, f"__There is no such '{fedgroup}' named fedgroup in your database.__"
)
drgevent = await edit_or_reply(
event, f"Fbanning {_format.mentionuser(user.first_name ,user.id)}.."
)
fedchat = FBAN_GROUP_ID
success = 0
errors = []
total = 0
for i in fedids:
total += 1
try:
async with event.client.conversation(fedchat) as conv:
await conv.send_message(f"/joinfed {i}")
reply = await conv.get_response()
await event.client.send_read_acknowledge(
conv.chat_id, message=reply, clear_mentions=True
)
if (
"All new federation bans will now also remove the members from this chat."
not in reply.text
):
return await edit_delete(
drgevent,
"__You must be owner of the group(FBAN_GROUP_ID) to perform this action__",
10,
)
await conv.send_message(f"/fban {user.id} {reason}")
reply = await conv.get_response()
await event.client.send_read_acknowledge(
conv.chat_id, message=reply, clear_mentions=True
)
check = False
for txt in fbanresults:
if txt in reply.text:
success += 1
check = True
if not check:
errors.append(reply.text)
except Exception as e:
errors.append(str(e))
success_report = f"{_format.mentionuser(user.first_name ,user.id)} is succesfully banned in {success} feds of {total}\
\n**Reason:** __{reason}__.\n"
if errors != []:
success_report += "\n**Error:**"
for txt in errors:
success_report += f"\n☞ __{txt}__"
await edit_or_reply(drgevent, success_report)
@drgub.drg_cmd(
pattern="unfban(?:\s|$)([\s\S]*)",
command=("unfban", plugin_category),
info={
"header": "UnBan the person in your database federations",
"description": "Will unfban the person in the all feds of given category which you stored in database.",
"usage": "{tr}unfban <userid/username/reply> <category> <reason>",
},
)
async def group_unfban(event):
"unfban a person."
if FBAN_GROUP_ID == 0:
return await edit_delete(
event,
"__For working of this cmd you need to set FBAN_GROUP_ID in heroku vars__",
)
user, reason = await get_user_from_event(event)
if not user:
return
if user.id == event.client.uid:
return await edit_delete(event, "__You can't unfban yourself.__")
if not reason:
return await edit_delete(
event, "__You haven't mentioned category name and reason for unfban__"
)
reasons = reason.split(" ", 1)
fedgroup = reasons[0]
reason = "Not Mentioned" if len(reasons) == 1 else reasons[1]
if get_collection("fedids") is not None:
feds = get_collection("fedids").json
else:
feds = {}
if fedgroup in feds:
fedids = feds[fedgroup]
else:
return await edit_delete(
event, f"__There is no such '{fedgroup}' named fedgroup in your database.__"
)
drgevent = await edit_or_reply(
event, f"Unfbanning {_format.mentionuser(user.first_name ,user.id)}.."
)
fedchat = FBAN_GROUP_ID
success = 0
errors = []
total = 0
for i in fedids:
total += 1
try:
async with event.client.conversation(fedchat) as conv:
await conv.send_message(f"/joinfed {i}")
reply = await conv.get_response()
await event.client.send_read_acknowledge(
conv.chat_id, message=reply, clear_mentions=True
)
if (
"All new federation bans will now also remove the members from this chat."
not in reply.text
):
return await edit_delete(
drgevent,
"__You must be owner of the group(FBAN_GROUP_ID) to perform this action__",
10,
)
await conv.send_message(f"/unfban {user.id} {reason}")
reply = await conv.get_response()
await event.client.send_read_acknowledge(
conv.chat_id, message=reply, clear_mentions=True
)
check = False
for txt in unfbanresults:
if txt in reply.text:
success += 1
check = True
if not check:
errors.append(reply.text)
except Exception as e:
errors.append(str(e))
success_report = f"{_format.mentionuser(user.first_name ,user.id)} is succesfully unbanned in {success} feds of {total}\
\n**Reason:** __{reason}__.\n"
if errors != []:
success_report += "\n**Error:**"
for txt in errors:
success_report += f"\n☞ __{txt}__"
await edit_or_reply(drgevent, success_report)
@drgub.drg_cmd(
pattern="addfedto (\w+|-all) ([-\w]+)",
command=("addfedto", plugin_category),
info={
"header": "Add the federation to given category in database.",
"description": "You can add multiple federations to one category like a group of feds under one category. And you can access all thoose feds by that name.",
"flags": {
"-all": "If you want to add all your feds to database then use this as {tr}addfedto -all <category name>"
},
"usage": [
"{tr}addfedto <category name> <fedid>",
"{tr}addfedto -all <category name>",
],
},
)
async def quote_search(event): # sourcery no-metrics
"Add the federation to database."
fedgroup = event.pattern_match.group(1)
fedid = event.pattern_match.group(2)
if get_collection("fedids") is not None:
feds = get_collection("fedids").json
else:
feds = {}
if fedgroup == "-all":
drgevent = await edit_or_reply(event, "`Adding all your feds to database...`")
fedidstoadd = []
async with event.client.conversation("@MissRose_bot") as conv:
try:
await conv.send_message("/myfeds")
await asyncio.sleep(2)
try:
response = await conv.get_response()
except asyncio.exceptions.TimeoutError:
return await edit_or_reply(
drgevent,
"__Rose bot is not responding try again later.__",
)
if "can only" in response.text:
return await edit_delete(drgevent, f"__{response.text}__")
if "make a file" in response.text or "Looks like" in response.text:
await response.click(0)
await asyncio.sleep(2)
response_result = await conv.get_response()
await asyncio.sleep(2)
if response_result.media:
fed_file = await event.client.download_media(
response_result,
"fedlist",
)
await asyncio.sleep(5)
fedfile = open(fed_file, errors="ignore")
lines = fedfile.readlines()
for line in lines:
try:
fedidstoadd.append(line[:36])
except Exception:
pass
else:
text_lines = response.text.split("`")
for fed_id in text_lines:
if len(fed_id) == 36 and fed_id.count("-") == 4:
fedidstoadd.append(fed_id)
except YouBlockedUserError:
await edit_delete(
drgevent,
"**Error while fecthing myfeds:**\n__Unblock__ @MissRose_Bot __and try again!__",
10,
)
except Exception as e:
await edit_delete(
drgevent, f"**Error while fecthing myfeds:**\n__{e}__", 10
)
await event.client.send_read_acknowledge(conv.chat_id)
conv.cancel()
if not fedidstoadd:
return await edit_or_reply(
drgevent,
"__I have failed to fetch your feds or you are not admin of any fed.__",
)
feds[fedid] = fedidstoadd
add_collection("fedids", feds)
await edit_or_reply(
drgevent,
f"__Successfully added all your feds to database group__ **{fedid}**.",
)
if BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
f"#ADDFEDID\
\n**Fed Group:** `{fedid}`\
\nSuccessfully added all your feds to above database category.",
)
return
if fedgroup in feds:
fed_ids = feds[fedgroup]
if fedid in fed_ids:
return await edit_delete(
event, "__This fed is already part of this fed category.__"
)
fed_ids.append(fedid)
feds[fedgroup] = fed_ids
else:
feds[fedgroup] = [fedid]
add_collection("fedids", feds)
await edit_or_reply(
event, "__The given fed is succesfully added to fed category.__"
)
if BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
f"#ADDFEDID\
\n**Fedid:** `{fedid}`\
\n**Fed Group:** `{fedgroup}`\
\nThe above fedid is sucessfully added to that fed category.",
)
@drgub.drg_cmd(
pattern="rmfedfrom (\w+|-all) ([-\w]+)",
command=("rmfedfrom", plugin_category),
info={
"header": "Remove the federation from given category in database.",
"description": "To remove given fed from the given category name",
"flags": {
"-all": "If you want to delete compelete category then use this flag as {tr}rmfedfrom -all <category name>"
},
"usage": [
"{tr}rmfedfrom <category name> <fedid>",
"{tr}rmfedfrom -all <category name>",
],
},
)
async def quote_search(event):
"To remove the federation from database."
fedgroup = event.pattern_match.group(1)
fedid = event.pattern_match.group(2)
if get_collection("fedids") is not None:
feds = get_collection("fedids").json
else:
feds = {}
if fedgroup == "-all":
if fedid not in feds:
return await edit_delete(
event, "__There is no such fedgroup in your database.__"
)
feds[fedid] = []
add_collection("fedids", feds)
await edit_or_reply(
event, f"__Succesfully removed all feds in the category {fedid}__"
)
if BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
f"#REMOVEFEDID\
\n**Fed Group:** `{fedid}`\
\nDeleted this Fed category in your database.",
)
return
if fedgroup not in feds:
return await edit_delete(
event, "__There is no such fedgroup in your database.__"
)
fed_ids = feds[fedgroup]
if fedid not in fed_ids:
return await edit_delete(
event, "__This fed is not part of given fed category.__"
)
fed_ids.remove(fedid)
feds[fedgroup] = fed_ids
add_collection("fedids", feds)
await edit_or_reply(
event, "__The given fed is succesfully removed from fed category.__"
)
if BOTLOG:
await event.client.send_message(
BOTLOG_CHATID,
f"#REMOVEFEDID\
\n**Fedid:** `{fedid}`\
\n**Fed Group:** `{fedgroup}`\
\nThe above fedid is sucessfully removed that fed category.",
)
@drgub.drg_cmd(
pattern="listfed(s)?(?:\s|$)([\s\S]*)",
command=("listfed", plugin_category),
info={
| |
<filename>app/baremetal_service/repository/service_model.py
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
import uuid
from django.db import models
from django.db.models.fields.related import ManyToManyField
from common.lark_common import random_object_id
from account.repository.auth_models import BmContract, BmProject
ORDER_TYPE_INCREASE = "increase"
ORDER_TYPE_ALTERATION = "alteration"
ORDER_STATUS_DELIVERED = "delivered"
ORDER_STATUS_DELIVERING = "delivering"
ORDER_TYPE_DICT = {"increase": "新购", "alteration": "变更"}
FLAVOR_ACTIVE = "active"
VOLUME_ACTIVE = "active"
VOLUME_BACKUP_ACTIVE = "active"
FLOATINGIP_ACTIVE = "active"
LB_ERROR = "ERROR"
resource_type_volume = "volume"
resource_type_volume_backup = "volume_backup"
resource_type_flaoting_ip = "flaoting_ip"
resource_type_ecbm = "ECBM"
resource_contract_info = "contract_info"
FLOATINGIP_AATTACH_ECBM = "ECBM"
FLOATINGIP_AATTACH_SLB = "LoadBalance"
class BmServiceOrder(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_bm_service_order_code)
account_id = models.CharField(max_length=64, blank=True, null=True,
help_text="客户id 示例:3f4cb35aeec544d3af33150f38b55286")
contract_number = models.CharField(max_length=64, blank=True, null=True, help_text="合同编码 示例:ding11")
project = models.ForeignKey(BmProject, models.DO_NOTHING, blank=True, null=True, help_text="项目 示例:test")
# contract_number = models.CharField(max_length=64, blank=True, null=True)
# project_id = models.CharField(max_length=64, blank=True, null=True)
# project_name = models.CharField(max_length=64, blank=True, null=True)
region = models.CharField(max_length=64, blank=True, null=True, help_text="可用区 示例:华北区")
order_type = models.CharField(max_length=64, blank=True, null=True, default=ORDER_TYPE_INCREASE,
help_text="订单类型 示例:increase")
order_price = models.FloatField(blank=True, null=True, help_text="订单价格 示例:1300")
product_type = models.CharField(max_length=64, blank=True, null=True, help_text="产品类型 示例:ECBM")
product_info = models.TextField(blank=True, null=True, help_text="产品详细信息")
billing_model = models.CharField(max_length=64, blank=True, null=True, help_text="绑定的合同类型 示例:框架合同 ")
service_count = models.IntegerField(blank=True, null=True, help_text="所购买的服务数量 示例:3")
delivery_status = models.CharField(max_length=64, blank=True, null=True, help_text="")
create_at = models.DateTimeField(blank=True, null=True, help_text="")
update_at = models.DateTimeField(blank=True, null=True, help_text="")
deleted = models.CharField(max_length=11, blank=True, null=True, help_text="")
class Meta:
managed = False
db_table = 'bm_service_order'
class BmServiceMachine(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_random_object_id)
order = models.ForeignKey('BmServiceOrder', models.DO_NOTHING, blank=True, null=True)
uuid = models.CharField(max_length=64, blank=True, null=True)
flavor_name = models.CharField(max_length=255, blank=True, null=True, help_text="机器名称 示例:戴尔")
flavor_id = models.CharField(max_length=64, blank=True, null=True,
help_text="机器id 示例:11a2c533-73cc-4f95-8e7b-0055b7ec18a7")
image_name = models.CharField(max_length=255, blank=True, null=True, help_text="镜像名称 示例:Windows2016")
image_id = models.CharField(max_length=64, blank=True, null=True,
help_text="镜像id 示例:198e0048-c8b2-4db9-9f08-395ea005af21")
monitoring = models.CharField(max_length=11, blank=True, null=True, help_text="是否携带监控 示例:True/False")
vulnerability_scanning = models.CharField(max_length=11, blank=True, null=True, help_text="是否携带扫描 示例:True/False")
disk_info = models.TextField(blank=True, null=True, help_text="磁盘信息")
network_path_type = models.CharField(max_length=64, blank=True, null=True, help_text="网络类型")
network = models.CharField(max_length=64, blank=True, null=True, help_text="网络名称")
network_id = models.CharField(max_length=64, blank=True, null=True, help_text="网络id")
floating_ip_info = models.TextField(blank=True, null=True, help_text="弹性公网IP信息")
floating_ip_allocation = models.BooleanField(max_length=64, blank=True, null=True, help_text="弹性公网IP可用量")
floating_ip_bandwidth = models.CharField(max_length=64, blank=True, null=True, help_text="弹性公网IP带宽")
floating_ip_line = models.CharField(max_length=64, blank=True, null=True, help_text="弹性公网IP类型")
firewall_id = models.CharField(max_length=64, blank=True, null=True, help_text="防火墙id")
firewall_name = models.CharField(max_length=64, blank=True, null=True, help_text="防火墙名称")
service_name = models.CharField(max_length=64, blank=True, null=True, help_text="所生成的服务器名称")
login_method = models.CharField(max_length=64, blank=True, null=True,
help_text="登陆方式(user_password-密码登陆)(keypair-密钥登陆)")
service_username = models.CharField(max_length=64, blank=True, null=True, help_text="所生成服务器的登录名")
service_password = models.CharField(max_length=64, blank=True, null=True, help_text="所生成服务器的密码")
public_key = models.TextField(blank=True, null=True, help_text="公钥信息")
create_at = models.DateTimeField(blank=True, null=True, help_text="服务创建时间")
update_at = models.DateTimeField(blank=True, null=True, help_text="服务更新时间")
deleted = models.CharField(max_length=11, blank=True, null=True, help_text="服务删除时间")
status = models.CharField(max_length=64, blank=True, null=True, help_text="状态(active-激活)(DELETED-删除)")
job_model = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_machine'
class BmRequestLog(models.Model):
account_id = models.CharField(max_length=64, blank=True, null=True)
account_name = models.CharField(max_length=255, blank=True, null=True)
project_id = models.CharField(max_length=64, blank=True, null=True)
project_name = models.CharField(max_length=255, blank=True, null=True)
object_id = models.CharField(max_length=64, blank=True, null=True)
object_name = models.CharField(max_length=255, blank=True, null=True)
object_type = models.CharField(max_length=255, blank=True, null=True)
action = models.CharField(max_length=255, blank=True, null=True)
uri = models.CharField(max_length=255, blank=True, null=True)
create_at = models.DateTimeField(blank=True, null=True)
update_at = models.DateTimeField(blank=True, null=True)
request_info = models.TextField(blank=True, null=True)
extra = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_request_log'
class BmServiceInstance(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_random_object_id)
account_id = models.CharField(max_length=64, blank=True, null=True,
help_text="客户id 示例:3f4cb35aeec544d3af33150f38b55286")
project_id = models.CharField(max_length=64, blank=True, null=True,
help_text="项目id 示例:7ae5a60714014778baddea703b85cd93")
region = models.CharField(max_length=64, blank=True, null=True, help_text="区域 示例:regionOne")
monitoring = models.CharField(max_length=11, blank=True, null=True,help_text="是否带监控 示例:True")
contract_number = models.CharField(max_length=64, blank=True, null=True, help_text="合同编号 示例:ding111")
product_type = models.CharField(max_length=64, blank=True, null=True, help_text="产品类型 示例:ECBM")
billing_model = models.CharField(max_length=64, blank=True, null=True, help_text="绑定合同类型 示例:标准合同")
uuid = models.CharField(unique=True, max_length=64, help_text="对应机器id 示例:c4130c54-bc4b-4249-928d-c014827653db")
name = models.CharField(max_length=255, help_text="机器名称", blank=True, null=True)
status = models.CharField(max_length=64, blank=True, null=True, help_text="状态 示例:active/DELETED")
task = models.CharField(max_length=64, blank=True, null=True, help_text="实例创建结果 示例:success/instance_build")
create_at = models.DateTimeField(blank=True, null=True, help_text="实例创建时间")
update_at = models.DateTimeField(blank=True, null=True, help_text="实例更新时间")
deleted = models.NullBooleanField(blank=True, null=True, default=False, help_text="实例删除时间")
class Meta:
managed = False
db_table = 'bm_service_instance'
class BmServiceFloatingIp(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_random_object_id, help_text="")
order_id = models.CharField(max_length=64, blank=True, null=True)
account_id = models.CharField(max_length=64, blank=True, null=True)
project_id = models.CharField(max_length=64, blank=True, null=True)
contract_number = models.CharField(max_length=64, blank=True, null=True)
external_line_type = models.CharField(max_length=64, blank=True, null=True, help_text="进出网络类型 "
"示例:three_line_ip")
external_name = models.CharField(max_length=255, blank=True, null=True)
external_name_id = models.CharField(max_length=255, blank=True, null=True)
floating_ip = models.CharField(max_length=64, blank=True, null=True)
floating_ip_id = models.CharField(max_length=64, blank=True, null=True)
attached = models.NullBooleanField(blank=True, null=True, default=False)
instance_uuid = models.CharField(max_length=64, blank=True, null=True)
instance_name = models.CharField(max_length=255, blank=True, null=True)
fixed_address = models.CharField(max_length=255, blank=True, null=True)
shared_qos_policy_type = models.BooleanField(default=False)
qos_policy_name = models.CharField(max_length=64, blank=True, null=True, help_text="带宽大小 示例:100M")
qos_policy_id = models.CharField(max_length=64, blank=True, null=True)
create_at = models.DateTimeField(blank=True, null=True)
update_at = models.DateTimeField(blank=True, null=True)
first_create_at = models.DateTimeField(blank=True, null=True)
status = models.CharField(max_length=64, blank=True, null=True)
is_measure_end = models.NullBooleanField(blank=True, null=True, default=False)
attached_type = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_floating_ip'
class BmContractFloatingIpMaterial(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_random_object_id)
material_number = models.CharField(max_length=64, blank=True, null=True)
floating_ip_type_name = models.CharField(max_length=255, blank=True, null=True)
floating_ip_type = models.CharField(max_length=255, blank=True, null=True)
external_line_type = models.CharField(max_length=255, blank=True, null=True)
charge_type = models.CharField(max_length=255, blank=True, null=True)
base_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
floating_ip_available = models.IntegerField(blank=True, null=True)
floating_ip_capacity = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_material_floating_ip'
class BmContractBandWidthaterial(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_random_object_id)
material_number = models.CharField(max_length=64, blank=True, null=True)
band_width_type_name = models.CharField(max_length=255, blank=True, null=True)
band_width_type = models.CharField(max_length=255, blank=True, null=True)
external_line_type = models.CharField(max_length=255, blank=True, null=True)
charge_type = models.CharField(max_length=255, blank=True, null=True)
base_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
band_width_available = models.IntegerField(blank=True, null=True)
band_width_capacity = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_material_band_width'
class BmServiceLoadbalanceFlavor(models.Model):
id = models.CharField(primary_key=True, max_length=64)
type = models.CharField(max_length=255, blank=True, null=True)
max_connect = models.CharField(max_length=255, blank=True, null=True)
new_connetc = models.CharField(max_length=255, blank=True, null=True)
second_query = models.CharField(max_length=255, blank=True, null=True)
openstack_name = models.CharField(max_length=255, blank=True, null=True)
memory = models.CharField(max_length=255, blank=True, null=True)
disk = models.CharField(max_length=255, blank=True, null=True)
vcpus = models.CharField(max_length=255, blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_loadbalance_flavor'
class BmServiceMaterialVolume(models.Model):
id = models.CharField(primary_key=True, max_length=64)
material_number = models.CharField(max_length=64, blank=True, null=True)
volume_type_name = models.CharField(max_length=255, blank=True, null=True)
volume_type = models.CharField(max_length=255, blank=True, null=True)
openstack_volume_type = models.CharField(max_length=255, blank=True, null=True)
base_price = models.FloatField(blank=True, null=True)
volume_available = models.IntegerField(blank=True, null=True)
volume_capacity = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_material_volume'
class BmServiceMaterialNat(models.Model):
id = models.CharField(primary_key=True, max_length=64)
material_number = models.CharField(max_length=64, blank=True, null=True)
nat_getway_type_name = models.CharField(max_length=255, blank=True, null=True)
charge_type = models.CharField(max_length=255, blank=True, null=True)
base_price = models.FloatField(blank=True, null=True)
nat_getway_available = models.IntegerField(blank=True, null=True)
nat_getway_capacity = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
nat_getway_type = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_material_nat'
class BmServiceMaterialLb(models.Model):
id = models.CharField(primary_key=True, max_length=64)
material_number = models.CharField(max_length=64, blank=True, null=True)
lb_type_name = models.CharField(max_length=255, blank=True, null=True)
charge_type = models.CharField(max_length=255, blank=True, null=True)
base_price = models.FloatField(blank=True, null=True)
lb_available = models.IntegerField(blank=True, null=True)
lb_capacity = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
lb_type = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_material_lb'
class BmServiceMaterialBandWidth(models.Model):
id = models.CharField(primary_key=True, max_length=64)
material_number = models.CharField(max_length=64, blank=True, null=True)
band_width_type_name = models.CharField(max_length=255, blank=True, null=True)
band_width_type = models.CharField(max_length=255, blank=True, null=True)
external_line_type = models.CharField(max_length=255, blank=True, null=True)
charge_type = models.CharField(max_length=255, blank=True, null=True)
base_price = models.FloatField(blank=True, null=True)
band_width_available = models.IntegerField(blank=True, null=True)
band_width_capacity = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'bm_service_material_band_width'
class BmMaterialFloatingIpSeasonal(models.Model):
id = models.CharField(primary_key=True, max_length=64, default=random_object_id.gen_random_object_id)
account_id = models.CharField(max_length=255, blank=True, null=True)
identity_name = models.CharField(max_length=255, blank=True, null=True)
user_account = models.CharField(max_length=255, blank=True, null=True)
contract_number = models.CharField(max_length=255, blank=True, null=True)
date = models.DateTimeField(blank=True, null=True)
band_material_number = models.CharField(max_length=255, blank=True, null=True)
band_width_type_name = models.CharField(max_length=255, blank=True, null=True)
material_band_base_price = models.CharField(max_length=255, blank=True, null=True)
material_number = models.CharField(max_length=255, blank=True, null=True)
floating_ip_type_name = models.CharField(max_length=255, blank=True, null=True)
base_price = models.CharField(max_length=255, blank=True, null=True)
region = models.CharField(max_length=255, blank=True, null=True)
sales = models.CharField(max_length=255, blank=True, null=True)
enterprise_number = models.CharField(max_length=255, blank=True, null=True)
location = models.CharField(max_length=255, blank=True, null=True)
customer_service_name = models.CharField(max_length=255, blank=True, null=True)
service_expired_time = models.CharField(max_length=255, blank=True, null=True)
service_start_time = models.CharField(max_length=255, blank=True, null=True)
contract_start_date = models.CharField(max_length=255, blank=True, null=True)
contract_expire_date = models.CharField(max_length=255, blank=True, null=True)
contract_customer_name = models.CharField(max_length=255, blank=True, null=True)
contract_authorizer = models.CharField(max_length=255, blank=True, null=True)
contract_type = models.CharField(max_length=255, blank=True, null=True)
contract_authorizer_account = models.CharField(max_length=255, blank=True, null=True)
external_line_type = models.CharField(max_length=255, blank=True, null=True)
external_name = models.CharField(max_length=255, blank=True, null=True)
external_name_id = models.CharField(max_length=255, blank=True, null=True)
floating_ip = models.CharField(max_length=255, blank=True, null=True)
floating_ip_id = models.CharField(max_length=255, blank=True, null=True)
order_id = models.CharField(max_length=255, blank=True, null=True)
project_id = models.CharField(max_length=255, blank=True, null=True)
project_name = models.CharField(max_length=255, blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
| |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) <NAME> <<EMAIL>>
# This program is published under a GPLv2 license
"""
Implementation of the configuration object.
"""
from __future__ import absolute_import
from __future__ import print_function
import functools
import os
import re
import time
import socket
import sys
from scapy import VERSION, base_classes
from scapy.consts import DARWIN, WINDOWS, LINUX, BSD, SOLARIS
from scapy.error import log_scapy, warning, ScapyInvalidPlatformException
from scapy.modules import six
from scapy.themes import NoTheme, apply_ipython_style
############
# Config #
############
class ConfClass(object):
def configure(self, cnf):
self.__dict__ = cnf.__dict__.copy()
def __repr__(self):
return str(self)
def __str__(self):
s = ""
keys = self.__class__.__dict__.copy()
keys.update(self.__dict__)
keys = sorted(keys)
for i in keys:
if i[0] != "_":
r = repr(getattr(self, i))
r = " ".join(r.split())
wlen = 76 - max(len(i), 10)
if len(r) > wlen:
r = r[:wlen - 3] + "..."
s += "%-10s = %s\n" % (i, r)
return s[:-1]
class Interceptor(object):
def __init__(self, name=None, default=None,
hook=None, args=None, kargs=None):
self.name = name
self.intname = "_intercepted_%s" % name
self.default = default
self.hook = hook
self.args = args if args is not None else []
self.kargs = kargs if kargs is not None else {}
def __get__(self, obj, typ=None):
if not hasattr(obj, self.intname):
setattr(obj, self.intname, self.default)
return getattr(obj, self.intname)
@staticmethod
def set_from_hook(obj, name, val):
int_name = "_intercepted_%s" % name
setattr(obj, int_name, val)
def __set__(self, obj, val):
setattr(obj, self.intname, val)
self.hook(self.name, val, *self.args, **self.kargs)
def _readonly(name):
default = Conf.__dict__[name].default
Interceptor.set_from_hook(conf, name, default)
raise ValueError("Read-only value !")
ReadOnlyAttribute = functools.partial(
Interceptor,
hook=(lambda name, *args, **kwargs: _readonly(name))
)
ReadOnlyAttribute.__doc__ = "Read-only class attribute"
class ProgPath(ConfClass):
universal_open = "open" if DARWIN else "xdg-open"
pdfreader = universal_open
psreader = universal_open
svgreader = universal_open
dot = "dot"
display = "display"
tcpdump = "tcpdump"
tcpreplay = "tcpreplay"
hexedit = "hexer"
tshark = "tshark"
wireshark = "wireshark"
ifconfig = "ifconfig"
class ConfigFieldList:
def __init__(self):
self.fields = set()
self.layers = set()
@staticmethod
def _is_field(f):
return hasattr(f, "owners")
def _recalc_layer_list(self):
self.layers = {owner for f in self.fields for owner in f.owners}
def add(self, *flds):
self.fields |= {f for f in flds if self._is_field(f)}
self._recalc_layer_list()
def remove(self, *flds):
self.fields -= set(flds)
self._recalc_layer_list()
def __contains__(self, elt):
if isinstance(elt, base_classes.Packet_metaclass):
return elt in self.layers
return elt in self.fields
def __repr__(self):
return "<%s [%s]>" % (self.__class__.__name__, " ".join(str(x) for x in self.fields)) # noqa: E501
class Emphasize(ConfigFieldList):
pass
class Resolve(ConfigFieldList):
pass
class Num2Layer:
def __init__(self):
self.num2layer = {}
self.layer2num = {}
def register(self, num, layer):
self.register_num2layer(num, layer)
self.register_layer2num(num, layer)
def register_num2layer(self, num, layer):
self.num2layer[num] = layer
def register_layer2num(self, num, layer):
self.layer2num[layer] = num
def __getitem__(self, item):
if isinstance(item, base_classes.Packet_metaclass):
return self.layer2num[item]
return self.num2layer[item]
def __contains__(self, item):
if isinstance(item, base_classes.Packet_metaclass):
return item in self.layer2num
return item in self.num2layer
def get(self, item, default=None):
return self[item] if item in self else default
def __repr__(self):
lst = []
for num, layer in six.iteritems(self.num2layer):
if layer in self.layer2num and self.layer2num[layer] == num:
dir = "<->"
else:
dir = " ->"
lst.append((num, "%#6x %s %-20s (%s)" % (num, dir, layer.__name__,
layer._name)))
for layer, num in six.iteritems(self.layer2num):
if num not in self.num2layer or self.num2layer[num] != layer:
lst.append((num, "%#6x <- %-20s (%s)" % (num, layer.__name__,
layer._name)))
lst.sort()
return "\n".join(y for x, y in lst)
class LayersList(list):
def __init__(self):
list.__init__(self)
self.ldict = {}
def __repr__(self):
return "\n".join("%-20s: %s" % (l.__name__, l.name) for l in self)
def register(self, layer):
self.append(layer)
if layer.__module__ not in self.ldict:
self.ldict[layer.__module__] = []
self.ldict[layer.__module__].append(layer)
def layers(self):
result = []
# This import may feel useless, but it is required for the eval below
import scapy # noqa: F401
for lay in self.ldict:
doc = eval(lay).__doc__
result.append((lay, doc.strip().split("\n")[0] if doc else lay))
return result
class CommandsList(list):
def __repr__(self):
s = []
for l in sorted(self, key=lambda x: x.__name__):
doc = l.__doc__.split("\n")[0] if l.__doc__ else "--"
s.append("%-20s: %s" % (l.__name__, doc))
return "\n".join(s)
def register(self, cmd):
self.append(cmd)
return cmd # return cmd so that method can be used as a decorator
def lsc():
"""Displays Scapy's default commands"""
print(repr(conf.commands))
class CacheInstance(dict, object):
__slots__ = ["timeout", "name", "_timetable", "__dict__"]
def __init__(self, name="noname", timeout=None):
self.timeout = timeout
self.name = name
self._timetable = {}
def flush(self):
self.__init__(name=self.name, timeout=self.timeout)
def __getitem__(self, item):
if item in self.__slots__:
return object.__getattribute__(self, item)
val = dict.__getitem__(self, item)
if self.timeout is not None:
t = self._timetable[item]
if time.time() - t > self.timeout:
raise KeyError(item)
return val
def get(self, item, default=None):
# overloading this method is needed to force the dict to go through
# the timetable check
try:
return self[item]
except KeyError:
return default
def __setitem__(self, item, v):
if item in self.__slots__:
return object.__setattr__(self, item, v)
self._timetable[item] = time.time()
dict.__setitem__(self, item, v)
def update(self, other):
for key, value in six.iteritems(other):
# We only update an element from `other` either if it does
# not exist in `self` or if the entry in `self` is older.
if key not in self or self._timetable[key] < other._timetable[key]:
dict.__setitem__(self, key, value)
self._timetable[key] = other._timetable[key]
def iteritems(self):
if self.timeout is None:
return six.iteritems(self.__dict__)
t0 = time.time()
return ((k, v) for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa: E501
def iterkeys(self):
if self.timeout is None:
return six.iterkeys(self.__dict__)
t0 = time.time()
return (k for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa: E501
def __iter__(self):
return six.iterkeys(self.__dict__)
def itervalues(self):
if self.timeout is None:
return six.itervalues(self.__dict__)
t0 = time.time()
return (v for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa: E501
def items(self):
if self.timeout is None:
return dict.items(self)
t0 = time.time()
return [(k, v) for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa: E501
def keys(self):
if self.timeout is None:
return dict.keys(self)
t0 = time.time()
return [k for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa: E501
def values(self):
if self.timeout is None:
return list(six.itervalues(self))
t0 = time.time()
return [v for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa: E501
def __len__(self):
if self.timeout is None:
return dict.__len__(self)
return len(self.keys())
def summary(self):
return "%s: %i valid items. Timeout=%rs" % (self.name, len(self), self.timeout) # noqa: E501
def __repr__(self):
s = []
if self:
mk = max(len(k) for k in six.iterkeys(self.__dict__))
fmt = "%%-%is %%s" % (mk + 1)
for item in six.iteritems(self.__dict__):
s.append(fmt % item)
return "\n".join(s)
class NetCache:
def __init__(self):
self._caches_list = []
def add_cache(self, cache):
self._caches_list.append(cache)
setattr(self, cache.name, cache)
def new_cache(self, name, timeout=None):
c = CacheInstance(name=name, timeout=timeout)
self.add_cache(c)
def __delattr__(self, attr):
raise AttributeError("Cannot delete attributes")
def update(self, other):
for co in other._caches_list:
if hasattr(self, co.name):
getattr(self, co.name).update(co)
else:
self.add_cache(co.copy())
def flush(self):
for c in self._caches_list:
c.flush()
def __repr__(self):
return "\n".join(c.summary() for c in self._caches_list)
def _version_checker(module, minver):
"""Checks that module has a higher version that minver.
params:
- module: a module to test
- minver: a tuple of versions
"""
# We could use LooseVersion, but distutils imports imp which is deprecated
version_regexp = r'[a-z]?((?:\d|\.)+\d+)(?:\.dev[0-9]+)?'
version_tags = re.match(version_regexp, module.__version__)
if not version_tags:
return False
version_tags = version_tags.group(1).split(".")
version_tags = tuple(int(x) for x in version_tags)
return version_tags >= minver
def isCryptographyValid():
"""
Check if the cryptography library is present, and if it is recent enough
for most usages in scapy (v1.7 or later).
"""
try:
import cryptography
except ImportError:
return False
return _version_checker(cryptography, (1, 7))
def isCryptographyRecent():
"""
Check if the cryptography library is recent (2.0 and later)
"""
try:
import cryptography
except ImportError:
return False
return _version_checker(cryptography, (2, 0))
def isCryptographyAdvanced():
"""
Check if the cryptography library is present, and if it supports X25519,
ChaCha20Poly1305 and such (v2.0 or later).
"""
try:
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501
X25519PrivateKey.generate()
except Exception:
return False
else:
return True
def isPyPy():
"""Returns either scapy is running under PyPy or not"""
try:
import __pypy__ # noqa: F401
return True
except ImportError:
return False
def _prompt_changer(attr, val):
"""Change the current prompt theme"""
try:
sys.ps1 = conf.color_theme.prompt(conf.prompt)
except Exception:
pass
try:
apply_ipython_style(get_ipython())
except NameError:
pass
def _set_conf_sockets():
"""Populate the conf.L2Socket and conf.L3Socket
according to the various use_* parameters
"""
from scapy.main import _load
if conf.use_bpf and not BSD:
Interceptor.set_from_hook(conf, "use_bpf", False)
raise ScapyInvalidPlatformException("BSD-like (OSX, *BSD...) only !")
if not conf.use_pcap and SOLARIS:
| |
import datetime
import getpass
import json
import sys
import mgear
import mgear.core.icon as ico
import pymel.core as pm
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
from mgear import shifter
from mgear.core import transform, node, attribute, applyop, pyqt, utils, curve
from mgear.vendor.Qt import QtCore, QtWidgets
from pymel import versions
from pymel.core import datatypes
from mgear.core import string
from mgear.simpleRig import simpleRigUI as srUI
CTL_TAG_ATTR = "is_simple_rig_ctl"
RIG_ROOT = "rig"
if sys.version_info[0] == 2:
string_types = (basestring, )
else:
string_types = (str, )
# driven attr ===========================================
def _driven_attr(dagNode):
"""message attribute to store a list of object affected
by the root or pivot
Args:
dagNode (PyNode): dagNode
Returns:
Attr: Attribute
"""
if not dagNode.hasAttr("drivenElements"):
dagNode.addAttr("drivenElements", attributeType='message', multi=True)
return dagNode.attr("drivenElements")
def _add_to_driven_attr(dagNode, driven):
"""add one or more elements to the driven list
should check is not in another driven attr and remove from others
Args:
dagNode (PyNode): dagNode with the attribute
driven (PyNode): driven elements
"""
d_attr = _driven_attr(dagNode)
if not isinstance(driven, list):
driven = [driven]
for d in driven:
if not _is_valid_ctl(d):
_remove_from_driven_attr(d)
ni = _get_driven_attr_next_available_index(d_attr)
pm.connectAttr(d.message,
d_attr.attr("drivenElements[{}]".format(str(ni))))
else:
pm.displayWarning("{} is a simple rig control and can't be "
" driven by another control".format(d))
def _remove_from_driven_attr(driven):
"""Remove one or more elements to the driven attr
Args:
driven (list of dagNode): Driven elements
"""
if not isinstance(driven, list):
driven = [driven]
for x in driven:
for o in x.message.connections(p=True):
if "drivenElements" in o.name():
pm.disconnectAttr(x.message, o)
def _get_from_driven_attr(dagNode):
"""Return a list of all elements in the driven attr as PyNodes
Args:
dagNode (PyNode): Driver dagNode
Returns:
TYPE: Description
"""
d_attr = _driven_attr(dagNode)
return d_attr.inputs()
def _get_driven_attr_next_available_index(d_attr):
"""Get the next available index for the drivenElements attr
Args:
d_attr (attr): driven attribute
Returns:
int: next available index
"""
return attribute.get_next_available_index(d_attr)
# creators ===========================================
def _create_control(name,
t,
radio,
parent=None,
icon="circle",
side="C",
indx=0,
color=17,
driven=None,
sets_config=None):
"""Crete control
Args:
name (str): Name of the control
t (matrix): transform matrix
radio (double): Size Radio
parent (dagNode, optional): Parent Control
icon (str, optional): Icon shape
side (str, optional): Side. Can be C, L or R
indx (int, optional): Index
color (int, optional): Colort
driven (None, optional): Driven elements
sets_config (None, optional): Groups/sets where the new control will be
added
Returns:
dagNode: New control
"""
name = _validate_name(name)
def _set_name(extension):
if side:
fullName = "{}_{}{}_{}".format(name, side, str(indx), extension)
i = 0
while pm.ls(fullName):
i += 1
fullName = "{}_{}{}_{}".format(name, side, str(i), extension)
else:
fullName = "{}_{}".format(name, extension)
return fullName
npo = pm.createNode('transform', n=_set_name("npo"))
npo.setTransformation(t)
if parent:
pm.parent(npo, parent)
ctl = ico.create(npo,
_set_name("ctl"),
t,
color,
icon=icon,
w=radio * 2,
h=radio * 2,
d=radio * 2)
attribute.addAttribute(ctl, "conf_icon", "string", icon)
attribute.addAttribute(ctl, "conf_sets", "string", sets_config)
attribute.addAttribute(ctl, "conf_radio", "float", radio, keyable=False)
attribute.addAttribute(ctl, "conf_color", "long", color, keyable=False)
attribute.addAttribute(ctl, CTL_TAG_ATTR, "bool", True, keyable=False)
attribute.addAttribute(ctl, "edit_mode", "bool", False, keyable=False)
pm.parent(ctl, npo)
attribute.setKeyableAttributes(ctl)
if driven:
if not isinstance(driven, list):
driven = [driven]
_add_to_driven_attr(ctl, driven)
_update_driven(ctl)
grp = _get_sets_grp()
grp.add(ctl)
if sets_config:
for ef in _extra_sets(sets_config):
ef.add(ctl)
return ctl
def _create_base_structure(rigName):
"""Create base structure
Args:
rigName (str): Rig name
Returns:
dagNode: rig root
"""
rig = pm.createNode('transform', n=rigName)
attribute.addAttribute(rig, "is_rig", "bool", True, keyable=False)
attribute.addAttribute(rig, "is_simple_rig", "bool", True, keyable=False)
attribute.addAttribute(rig, "geoUnselectable", "bool", True)
attribute.addAttribute(rig, "rig_name", "string", rigName)
attribute.addAttribute(rig, "user", "string", getpass.getuser())
attribute.addAttribute(rig, "date", "string", str(datetime.datetime.now()))
attribute.addAttribute(rig,
"maya_version",
"string",
str(pm.mel.eval("getApplicationVersionAsFloat")))
attribute.addAttribute(rig, "gear_version", "string", mgear.getVersion())
attribute.addAttribute(rig, "ctl_vis", "bool", True)
attribute.addAttribute(rig, "jnt_vis", "bool", False)
attribute.addAttribute(rig, "quickselA", "string", "")
attribute.addAttribute(rig, "quickselB", "string", "")
attribute.addAttribute(rig, "quickselC", "string", "")
attribute.addAttribute(rig, "quickselD", "string", "")
attribute.addAttribute(rig, "quickselE", "string", "")
attribute.addAttribute(rig, "quickselF", "string", "")
attribute.addAttribute(rig, "synoptic", "string", "")
attribute.addAttribute(rig, "comments", "string", "")
rig.addAttr("rigGroups", at='message', m=1)
rig.addAttr("rigPoses", at='message', m=1)
rig.addAttr("rigCtlTags", at='message', m=1)
# Create sets
meshList = []
ctlList = []
ctlSet = pm.sets(ctlList, n="{}_controllers_grp".format(rigName))
deformersSet = pm.sets(meshList, n="{}_deformers_grp".format(rigName))
compGroup = pm.sets(meshList, n="{}_componentsRoots_grp".format(rigName))
rigSets = pm.sets([ctlSet, deformersSet, compGroup],
n="rig_sets_grp")
pm.connectAttr(rigSets.attr("message"),
"{}.rigGroups[0]".format(rigName))
pm.connectAttr(ctlSet.attr("message"),
"{}.rigGroups[2]".format(rigName))
pm.connectAttr(deformersSet.attr("message"),
"{}.rigGroups[3]".format(rigName))
pm.connectAttr(compGroup.attr("message"),
"{}.rigGroups[4]".format(rigName))
return rig
@utils.one_undo
def _create_simple_rig_root(rigName=RIG_ROOT,
selection=None,
world_ctl=True,
sets_config=None,
ctl_wcm=False,
fix_radio=False,
radio_val=100,
gl_shape="square",
w_shape="circle"):
"""Create the simple rig root
create the simple rig root
have the attr: is_simple_rig and is_rig
should not create if there is a another simple rig root
should have synoptic attr. (synoptic configuration in UI)
use World_ctl should be optional
Args:
rigName (str, optional): Rig Name
selection (dagNode list, optional): Elements selected to be included
in the rig
world_ctl (bool, optional): if True, will create world_ctl
sets_config (None, optional): Groups to include the ctl
ctl_wcm (bool, optional): If True, the world_ctl will ve placed in the
scene world center
fix_radio (bool, optional): If True, will use a fix radio value,
instead of the bbox radio
radio_val (int, optional): Fix value for Radio
gl_shape (str, optional): Global and local control shape
w_shape (str, optional): World control shape
Returns:
dagNode: local control
"""
# check if there is another rig root in the scene
rig_models = _get_simple_rig_root()
if rig_models:
pm.displayWarning("Simple rig root already exist in the "
"scene: {}".format(str(rig_models)))
return
if not selection:
if pm.selected():
selection = pm.selected()
else:
pm.displayWarning("Selection is needed to create the root")
return
volCenter, radio, bb = _get_branch_bbox_data(selection)
if fix_radio:
radio = radio_val
rig = _create_base_structure(rigName)
if ctl_wcm:
t = datatypes.Matrix()
else:
t = transform.getTransformFromPos(volCenter)
# configure selectable geo
connect_selectable(rig, selection)
ctt = None
# create world ctl
if world_ctl:
world_ctl = _create_control("world",
t,
radio * 1.5,
parent=rig,
icon=w_shape,
side=None,
indx=0,
color=13,
driven=None,
sets_config=sets_config)
if versions.current() >= 201650:
ctt = node.add_controller_tag(world_ctl, None)
_connect_tag_to_rig(rig, ctt)
else:
world_ctl = rig
# create global ctl
global_ctl = _create_control("global",
t,
radio * 1.1,
parent=world_ctl,
icon=gl_shape,
side="C",
indx=0,
color=17,
driven=None,
sets_config=sets_config)
if versions.current() >= 201650:
ctt = node.add_controller_tag(global_ctl, ctt)
_connect_tag_to_rig(rig, ctt)
# create local ctl
local_ctl = _create_control("local",
t,
radio,
parent=global_ctl,
icon=gl_shape,
side="C",
indx=0,
color=17,
driven=selection,
sets_config=sets_config)
if versions.current() >= 201650:
ctt = node.add_controller_tag(local_ctl, ctt)
_connect_tag_to_rig(rig, ctt)
return local_ctl
@utils.one_undo
def _create_custom_pivot(name,
side,
icon,
yZero,
selection=None,
parent=None,
sets_config=None):
"""Create a custom pivot control
Args:
name (str): Custompivot control name
side (str): Side. can be C, L or R
icon (str): Control shape
yZero (bool): If True, the control will be placed in the lowest
position of the bbox
selection (list of dagNode, optional): Elements affected by the
custom pivot
parent (dagNode, optional): Parent of the custom pivot. Should be
another ctl
sets_config (str, optional): Sets to add the controls
Returns:
TYPE: Description
"""
# should have an options in UI and store as attr for rebuild
# -side
# -Control Shape
# -Place in base or place in BBOX center
if not selection:
if pm.selected():
selection = pm.selected()
else:
pm.displayWarning("Selection is needed to create the root")
return
if not parent:
if selection and _is_valid_ctl(selection[-1]):
parent = selection[-1]
selection = selection[:-1]
else:
pm.displayWarning("The latest selected element should be a CTL. "
"PARENT is needed!")
return
# handle the 3rd stat for yZero
# this state will trigger to put it in world center
wolrd_center = False
if yZero > 1:
yZero = True
wolrd_center = True
volCenter, radio, bb = _get_branch_bbox_data(selection, yZero)
if volCenter:
if wolrd_center:
t = datatypes.Matrix()
else:
t = transform.getTransformFromPos(volCenter)
ctl = _create_control(name,
t,
radio,
parent,
icon,
side,
indx=0,
color=14,
driven=selection,
sets_config=sets_config)
# add ctl tag
if versions.current() >= 201650:
parentTag = pm.PyNode(pm.controller(parent, q=True)[0])
ctt = node.add_controller_tag(ctl, parentTag)
_connect_tag_to_rig(ctl.getParent(-1), ctt)
return ctl
# Getters ===========================================
def _get_simple_rig_root():
"""get the root from the scene.
If there is more than one It will return none and print warning
Returns:
dagNode: Rig root
"""
rig_models = [item for item in pm.ls(transforms=True)
if _is_simple_rig_root(item)]
if rig_models:
return rig_models[0]
def connect_selectable(rig, selection):
"""Configure selectable geo
Args:
rig (dagNode): rig root with geo Unselectable attr
selection (list): List of object to connect
"""
# configure selectable geo
for e in selection:
pm.connectAttr(rig.geoUnselectable,
e.attr("overrideEnabled"),
force=True)
e.attr("overrideDisplayType").set(2)
def _get_children(dagNode):
"""Get all children node
Args:
dagNode (PyNode): dagNode to get the childrens
Returns:
list of dagNode: children dagNodes
"""
children = dagNode.listRelatives(allDescendents=True,
type="transform")
return children
def _get_bbox_data(obj=None, yZero=True, *args):
"""Calculate the bounding box data
Args:
obj (None, optional): The object to calculate the bounding box
yZero (bool, optional): If true, sets the hight to the lowest point
*args: Maya dummy
Returns:
mutiy: volumen center vector position, radio and bounding box (bbox)
"""
volCenter = False
if not obj:
obj = | |
"Behavior_CloakOn_Banshee_quick", cmd_quick, 392, 3676),
Function.ability(28, "Behavior_CloakOn_Ghost_quick", cmd_quick, 382, 3676),
Function.ability(29, "Behavior_GenerateCreepOff_quick", cmd_quick, 1693),
Function.ability(30, "Behavior_GenerateCreepOn_quick", cmd_quick, 1692),
Function.ability(31, "Behavior_HoldFireOff_quick", cmd_quick, 3689),
Function.ability(32, "Behavior_HoldFireOff_Ghost_quick", cmd_quick, 38, 3689),
Function.ability(33, "Behavior_HoldFireOff_Lurker_quick", cmd_quick, 2552, 3689),
Function.ability(34, "Behavior_HoldFireOn_quick", cmd_quick, 3688),
Function.ability(35, "Behavior_HoldFireOn_Ghost_quick", cmd_quick, 36, 3688),
Function.ability(36, "Behavior_HoldFireOn_Lurker_quick", cmd_quick, 2550, 3688),
Function.ability(37, "Behavior_PulsarBeamOff_quick", cmd_quick, 2376),
Function.ability(38, "Behavior_PulsarBeamOn_quick", cmd_quick, 2375),
Function.ability(39, "Build_Armory_screen", cmd_screen, 331),
Function.ability(40, "Build_Assimilator_screen", cmd_screen, 882),
Function.ability(41, "Build_BanelingNest_screen", cmd_screen, 1162),
Function.ability(42, "Build_Barracks_screen", cmd_screen, 321),
Function.ability(43, "Build_Bunker_screen", cmd_screen, 324),
Function.ability(44, "Build_CommandCenter_screen", cmd_screen, 318),
Function.ability(45, "Build_CreepTumor_screen", cmd_screen, 3691),
Function.ability(46, "Build_CreepTumor_Queen_screen", cmd_screen, 1694, 3691),
Function.ability(47, "Build_CreepTumor_Tumor_screen", cmd_screen, 1733, 3691),
Function.ability(48, "Build_CyberneticsCore_screen", cmd_screen, 894),
Function.ability(49, "Build_DarkShrine_screen", cmd_screen, 891),
Function.ability(50, "Build_EngineeringBay_screen", cmd_screen, 322),
Function.ability(51, "Build_EvolutionChamber_screen", cmd_screen, 1156),
Function.ability(52, "Build_Extractor_screen", cmd_screen, 1154),
Function.ability(53, "Build_Factory_screen", cmd_screen, 328),
Function.ability(54, "Build_FleetBeacon_screen", cmd_screen, 885),
Function.ability(55, "Build_Forge_screen", cmd_screen, 884),
Function.ability(56, "Build_FusionCore_screen", cmd_screen, 333),
Function.ability(57, "Build_Gateway_screen", cmd_screen, 883),
Function.ability(58, "Build_GhostAcademy_screen", cmd_screen, 327),
Function.ability(59, "Build_Hatchery_screen", cmd_screen, 1152),
Function.ability(60, "Build_HydraliskDen_screen", cmd_screen, 1157),
Function.ability(61, "Build_InfestationPit_screen", cmd_screen, 1160),
Function.ability(62, "Build_Interceptors_quick", cmd_quick, 1042),
Function.ability(63, "Build_Interceptors_autocast", autocast, 1042),
Function.ability(64, "Build_MissileTurret_screen", cmd_screen, 323),
Function.ability(65, "Build_Nexus_screen", cmd_screen, 880),
Function.ability(66, "Build_Nuke_quick", cmd_quick, 710),
Function.ability(67, "Build_NydusNetwork_screen", cmd_screen, 1161),
Function.ability(68, "Build_NydusWorm_screen", cmd_screen, 1768),
Function.ability(69, "Build_PhotonCannon_screen", cmd_screen, 887),
Function.ability(70, "Build_Pylon_screen", cmd_screen, 881),
Function.ability(71, "Build_Reactor_quick", cmd_quick, 3683),
Function.ability(72, "Build_Reactor_screen", cmd_screen, 3683),
Function.ability(73, "Build_Reactor_Barracks_quick", cmd_quick, 422, 3683),
Function.ability(74, "Build_Reactor_Barracks_screen", cmd_screen, 422, 3683),
Function.ability(75, "Build_Reactor_Factory_quick", cmd_quick, 455, 3683),
Function.ability(76, "Build_Reactor_Factory_screen", cmd_screen, 455, 3683),
Function.ability(77, "Build_Reactor_Starport_quick", cmd_quick, 488, 3683),
Function.ability(78, "Build_Reactor_Starport_screen", cmd_screen, 488, 3683),
Function.ability(79, "Build_Refinery_screen", cmd_screen, 320),
Function.ability(80, "Build_RoachWarren_screen", cmd_screen, 1165),
Function.ability(81, "Build_RoboticsBay_screen", cmd_screen, 892),
Function.ability(82, "Build_RoboticsFacility_screen", cmd_screen, 893),
Function.ability(83, "Build_SensorTower_screen", cmd_screen, 326),
Function.ability(84, "Build_SpawningPool_screen", cmd_screen, 1155),
Function.ability(85, "Build_SpineCrawler_screen", cmd_screen, 1166),
Function.ability(86, "Build_Spire_screen", cmd_screen, 1158),
Function.ability(87, "Build_SporeCrawler_screen", cmd_screen, 1167),
Function.ability(88, "Build_Stargate_screen", cmd_screen, 889),
Function.ability(89, "Build_Starport_screen", cmd_screen, 329),
Function.ability(90, "Build_StasisTrap_screen", cmd_screen, 2505),
Function.ability(91, "Build_SupplyDepot_screen", cmd_screen, 319),
Function.ability(92, "Build_TechLab_quick", cmd_quick, 3682),
Function.ability(93, "Build_TechLab_screen", cmd_screen, 3682),
Function.ability(94, "Build_TechLab_Barracks_quick", cmd_quick, 421, 3682),
Function.ability(95, "Build_TechLab_Barracks_screen", cmd_screen, 421, 3682),
Function.ability(96, "Build_TechLab_Factory_quick", cmd_quick, 454, 3682),
Function.ability(97, "Build_TechLab_Factory_screen", cmd_screen, 454, 3682),
Function.ability(98, "Build_TechLab_Starport_quick", cmd_quick, 487, 3682),
Function.ability(99, "Build_TechLab_Starport_screen", cmd_screen, 487, 3682),
Function.ability(100, "Build_TemplarArchive_screen", cmd_screen, 890),
Function.ability(101, "Build_TwilightCouncil_screen", cmd_screen, 886),
Function.ability(102, "Build_UltraliskCavern_screen", cmd_screen, 1159),
Function.ability(103, "BurrowDown_quick", cmd_quick, 3661),
Function.ability(104, "BurrowDown_Baneling_quick", cmd_quick, 1374, 3661),
Function.ability(105, "BurrowDown_Drone_quick", cmd_quick, 1378, 3661),
Function.ability(106, "BurrowDown_Hydralisk_quick", cmd_quick, 1382, 3661),
Function.ability(107, "BurrowDown_Infestor_quick", cmd_quick, 1444, 3661),
Function.ability(108, "BurrowDown_InfestorTerran_quick", cmd_quick, 1394, 3661),
Function.ability(109, "BurrowDown_Lurker_quick", cmd_quick, 2108, 3661),
Function.ability(110, "BurrowDown_Queen_quick", cmd_quick, 1433, 3661),
Function.ability(111, "BurrowDown_Ravager_quick", cmd_quick, 2340, 3661),
Function.ability(112, "BurrowDown_Roach_quick", cmd_quick, 1386, 3661),
Function.ability(113, "BurrowDown_SwarmHost_quick", cmd_quick, 2014, 3661),
Function.ability(114, "BurrowDown_Ultralisk_quick", cmd_quick, 1512, 3661),
Function.ability(115, "BurrowDown_WidowMine_quick", cmd_quick, 2095, 3661),
Function.ability(116, "BurrowDown_Zergling_quick", cmd_quick, 1390, 3661),
Function.ability(117, "BurrowUp_quick", cmd_quick, 3662),
Function.ability(118, "BurrowUp_autocast", autocast, 3662),
Function.ability(119, "BurrowUp_Baneling_quick", cmd_quick, 1376, 3662),
Function.ability(120, "BurrowUp_Baneling_autocast", autocast, 1376, 3662),
Function.ability(121, "BurrowUp_Drone_quick", cmd_quick, 1380, 3662),
Function.ability(122, "BurrowUp_Hydralisk_quick", cmd_quick, 1384, 3662),
Function.ability(123, "BurrowUp_Hydralisk_autocast", autocast, 1384, 3662),
Function.ability(124, "BurrowUp_Infestor_quick", cmd_quick, 1446, 3662),
Function.ability(125, "BurrowUp_InfestorTerran_quick", cmd_quick, 1396, 3662),
Function.ability(126, "BurrowUp_InfestorTerran_autocast", autocast, 1396, 3662),
Function.ability(127, "BurrowUp_Lurker_quick", cmd_quick, 2110, 3662),
Function.ability(128, "BurrowUp_Queen_quick", cmd_quick, 1435, 3662),
Function.ability(129, "BurrowUp_Queen_autocast", autocast, 1435, 3662),
Function.ability(130, "BurrowUp_Ravager_quick", cmd_quick, 2342, 3662),
Function.ability(131, "BurrowUp_Ravager_autocast", autocast, 2342, 3662),
Function.ability(132, "BurrowUp_Roach_quick", cmd_quick, 1388, 3662),
Function.ability(133, "BurrowUp_Roach_autocast", autocast, 1388, 3662),
Function.ability(134, "BurrowUp_SwarmHost_quick", cmd_quick, 2016, 3662),
Function.ability(135, "BurrowUp_Ultralisk_quick", cmd_quick, 1514, 3662),
Function.ability(136, "BurrowUp_Ultralisk_autocast", autocast, 1514, 3662),
Function.ability(137, "BurrowUp_WidowMine_quick", cmd_quick, 2097, 3662),
Function.ability(138, "BurrowUp_Zergling_quick", cmd_quick, 1392, 3662),
Function.ability(139, "BurrowUp_Zergling_autocast", autocast, 1392, 3662),
Function.ability(140, "Cancel_quick", cmd_quick, 3659),
Function.ability(141, "Cancel_AdeptPhaseShift_quick", cmd_quick, 2594, 3659),
Function.ability(142, "Cancel_AdeptShadePhaseShift_quick", cmd_quick, 2596, 3659),
Function.ability(143, "Cancel_BarracksAddOn_quick", cmd_quick, 451, 3659),
Function.ability(144, "Cancel_BuildInProgress_quick", cmd_quick, 314, 3659),
Function.ability(145, "Cancel_CreepTumor_quick", cmd_quick, 1763, 3659),
Function.ability(146, "Cancel_FactoryAddOn_quick", cmd_quick, 484, 3659),
Function.ability(147, "Cancel_GravitonBeam_quick", cmd_quick, 174, 3659),
Function.ability(148, "Cancel_LockOn_quick", cmd_quick, 2354, 3659),
Function.ability(149, "Cancel_MorphBroodlord_quick", cmd_quick, 1373, 3659),
Function.ability(150, "Cancel_MorphGreaterSpire_quick", cmd_quick, 1221, 3659),
Function.ability(151, "Cancel_MorphHive_quick", cmd_quick, 1219, 3659),
Function.ability(152, "Cancel_MorphLair_quick", cmd_quick, 1217, 3659),
Function.ability(153, "Cancel_MorphLurker_quick", cmd_quick, 2333, 3659),
Function.ability(154, "Cancel_MorphLurkerDen_quick", cmd_quick, 2113, 3659),
Function.ability(155, "Cancel_MorphMothership_quick", cmd_quick, 1848, 3659),
Function.ability(156, "Cancel_MorphOrbital_quick", cmd_quick, 1517, 3659),
Function.ability(157, "Cancel_MorphOverlordTransport_quick", cmd_quick, 2709, 3659),
Function.ability(158, "Cancel_MorphOverseer_quick", cmd_quick, 1449, 3659),
Function.ability(159, "Cancel_MorphPlanetaryFortress_quick", cmd_quick, 1451, 3659),
Function.ability(160, "Cancel_MorphRavager_quick", cmd_quick, 2331, 3659),
Function.ability(161, "Cancel_MorphThorExplosiveMode_quick", cmd_quick, 2365, 3659),
Function.ability(162, "Cancel_NeuralParasite_quick", cmd_quick, 250, 3659),
Function.ability(163, "Cancel_Nuke_quick", cmd_quick, 1623, 3659),
Function.ability(164, "Cancel_SpineCrawlerRoot_quick", cmd_quick, 1730, 3659),
Function.ability(165, "Cancel_SporeCrawlerRoot_quick", cmd_quick, 1732, 3659),
Function.ability(166, "Cancel_StarportAddOn_quick", cmd_quick, 517, 3659),
Function.ability(167, "Cancel_StasisTrap_quick", cmd_quick, 2535, 3659),
Function.ability(168, "Cancel_Last_quick", cmd_quick, 3671),
Function.ability(169, "Cancel_HangarQueue5_quick", cmd_quick, 1038, 3671),
Function.ability(170, "Cancel_Queue1_quick", cmd_quick, 304, 3671),
Function.ability(171, "Cancel_Queue5_quick", cmd_quick, 306, 3671),
Function.ability(172, "Cancel_QueueAddOn_quick", cmd_quick, 312, 3671),
Function.ability(173, "Cancel_QueueCancelToSelection_quick", cmd_quick, 308, 3671),
Function.ability(174, "Cancel_QueuePasive_quick", cmd_quick, 1831, 3671),
Function.ability(175, "Cancel_QueuePassiveCancelToSelection_quick", cmd_quick, 1833, 3671),
Function.ability(176, "Effect_Abduct_screen", cmd_screen, 2067),
Function.ability(177, "Effect_AdeptPhaseShift_screen", cmd_screen, 2544),
Function.ability(178, "Effect_AutoTurret_screen", cmd_screen, 1764),
Function.ability(179, "Effect_BlindingCloud_screen", cmd_screen, 2063),
Function.ability(180, "Effect_Blink_screen", cmd_screen, 3687),
Function.ability(181, "Effect_Blink_Stalker_screen", cmd_screen, 1442, 3687),
Function.ability(182, "Effect_ShadowStride_screen", cmd_screen, 2700, 3687),
Function.ability(183, "Effect_CalldownMULE_screen", cmd_screen, 171),
Function.ability(184, "Effect_CausticSpray_screen", cmd_screen, 2324),
Function.ability(185, "Effect_Charge_screen", cmd_screen, 1819),
Function.ability(186, "Effect_Charge_autocast", autocast, 1819),
Function.ability(187, "Effect_ChronoBoost_screen", cmd_screen, 261),
Function.ability(188, "Effect_Contaminate_screen", cmd_screen, 1825),
Function.ability(189, "Effect_CorrosiveBile_screen", cmd_screen, 2338),
Function.ability(190, "Effect_EMP_screen", cmd_screen, 1628),
Function.ability(191, "Effect_Explode_quick", cmd_quick, 42),
Function.ability(192, "Effect_Feedback_screen", cmd_screen, 140),
Function.ability(193, "Effect_ForceField_screen", cmd_screen, 1526),
Function.ability(194, "Effect_FungalGrowth_screen", cmd_screen, 74),
Function.ability(195, "Effect_GhostSnipe_screen", cmd_screen, 2714),
Function.ability(196, "Effect_GravitonBeam_screen", cmd_screen, 173),
Function.ability(197, "Effect_GuardianShield_quick", cmd_quick, 76),
Function.ability(198, "Effect_Heal_screen", cmd_screen, 386),
Function.ability(199, "Effect_Heal_autocast", autocast, 386),
Function.ability(200, "Effect_HunterSeekerMissile_screen", cmd_screen, 169),
Function.ability(201, "Effect_ImmortalBarrier_quick", cmd_quick, 2328),
Function.ability(202, "Effect_ImmortalBarrier_autocast", autocast, 2328),
Function.ability(203, "Effect_InfestedTerrans_screen", cmd_screen, 247),
Function.ability(204, "Effect_InjectLarva_screen", cmd_screen, 251),
Function.ability(205, "Effect_KD8Charge_screen", cmd_screen, 2588),
Function.ability(206, "Effect_LockOn_screen", cmd_screen, 2350),
Function.ability(207, "Effect_LocustSwoop_screen", cmd_screen, 2387),
Function.ability(208, "Effect_MassRecall_screen", cmd_screen, 3686),
Function.ability(209, "Effect_MassRecall_Mothership_screen", cmd_screen, 2368, 3686),
Function.ability(210, "Effect_MassRecall_MothershipCore_screen", cmd_screen, 1974, 3686),
Function.ability(211, "Effect_MedivacIgniteAfterburners_quick", cmd_quick, 2116),
Function.ability(212, "Effect_NeuralParasite_screen", cmd_screen, 249),
Function.ability(213, "Effect_NukeCalldown_screen", cmd_screen, 1622),
Function.ability(214, "Effect_OracleRevelation_screen", cmd_screen, 2146),
Function.ability(215, "Effect_ParasiticBomb_screen", cmd_screen, 2542),
Function.ability(216, "Effect_PhotonOvercharge_screen", cmd_screen, 2162),
Function.ability(217, "Effect_PointDefenseDrone_screen", cmd_screen, 144),
Function.ability(218, "Effect_PsiStorm_screen", cmd_screen, 1036),
Function.ability(219, "Effect_PurificationNova_screen", cmd_screen, 2346),
Function.ability(220, "Effect_Repair_screen", cmd_screen, 3685),
Function.ability(221, "Effect_Repair_autocast", autocast, 3685),
Function.ability(222, "Effect_Repair_Mule_screen", cmd_screen, 78, 3685),
Function.ability(223, "Effect_Repair_Mule_autocast", autocast, 78, 3685),
Function.ability(224, "Effect_Repair_SCV_screen", cmd_screen, 316, 3685),
Function.ability(225, "Effect_Repair_SCV_autocast", autocast, 316, 3685),
Function.ability(226, "Effect_Salvage_quick", cmd_quick, 32),
Function.ability(227, "Effect_Scan_screen", cmd_screen, 399),
Function.ability(228, "Effect_SpawnChangeling_quick", cmd_quick, 181),
Function.ability(229, "Effect_SpawnLocusts_screen", cmd_screen, 2704),
Function.ability(230, "Effect_Spray_screen", cmd_screen, 3684),
Function.ability(231, "Effect_Spray_Protoss_screen", cmd_screen, 30, 3684),
Function.ability(232, "Effect_Spray_Terran_screen", cmd_screen, 26, 3684),
Function.ability(233, "Effect_Spray_Zerg_screen", cmd_screen, 28, 3684),
Function.ability(234, "Effect_Stim_quick", cmd_quick, 3675),
Function.ability(235, "Effect_Stim_Marauder_quick", cmd_quick, 253, 3675),
Function.ability(236, "Effect_Stim_Marauder_Redirect_quick", cmd_quick, 1684, 3675),
Function.ability(237, "Effect_Stim_Marine_quick", cmd_quick, 380, 3675),
Function.ability(238, "Effect_Stim_Marine_Redirect_quick", cmd_quick, 1683, 3675),
Function.ability(239, "Effect_SupplyDrop_screen", cmd_screen, 255),
Function.ability(240, "Effect_TacticalJump_screen", cmd_screen, 2358),
Function.ability(241, "Effect_TimeWarp_screen", cmd_screen, 2244),
Function.ability(242, "Effect_Transfusion_screen", cmd_screen, 1664),
Function.ability(243, "Effect_ViperConsume_screen", cmd_screen, 2073),
Function.ability(244, "Effect_VoidRayPrismaticAlignment_quick", cmd_quick, 2393),
Function.ability(245, "Effect_WidowMineAttack_screen", cmd_screen, 2099),
Function.ability(246, "Effect_WidowMineAttack_autocast", autocast, 2099),
Function.ability(247, "Effect_YamatoGun_screen", cmd_screen, 401),
Function.ability(248, "Hallucination_Adept_quick", cmd_quick, 2391),
Function.ability(249, "Hallucination_Archon_quick", cmd_quick, 146),
Function.ability(250, "Hallucination_Colossus_quick", cmd_quick, 148),
Function.ability(251, "Hallucination_Disruptor_quick", cmd_quick, 2389),
Function.ability(252, "Hallucination_HighTemplar_quick", cmd_quick, 150),
Function.ability(253, "Hallucination_Immortal_quick", cmd_quick, 152),
Function.ability(254, "Hallucination_Oracle_quick", cmd_quick, 2114),
Function.ability(255, "Hallucination_Phoenix_quick", cmd_quick, 154),
Function.ability(256, "Hallucination_Probe_quick", cmd_quick, 156),
Function.ability(257, "Hallucination_Stalker_quick", cmd_quick, 158),
Function.ability(258, "Hallucination_VoidRay_quick", cmd_quick, 160),
Function.ability(259, "Hallucination_WarpPrism_quick", cmd_quick, 162),
Function.ability(260, "Hallucination_Zealot_quick", cmd_quick, 164),
Function.ability(261, "Halt_quick", cmd_quick, 3660),
Function.ability(262, "Halt_Building_quick", cmd_quick, 315, 3660),
Function.ability(263, "Halt_TerranBuild_quick", cmd_quick, 348, 3660),
Function.ability(264, "Harvest_Gather_screen", cmd_screen, 3666),
Function.ability(265, "Harvest_Gather_Drone_screen", cmd_screen, 1183, 3666),
Function.ability(266, "Harvest_Gather_Mule_screen", cmd_screen, 166, 3666),
Function.ability(267, "Harvest_Gather_Probe_screen", cmd_screen, 298, 3666),
Function.ability(268, "Harvest_Gather_SCV_screen", cmd_screen, 295, 3666),
Function.ability(269, "Harvest_Return_quick", cmd_quick, 3667),
Function.ability(270, "Harvest_Return_Drone_quick", cmd_quick, 1184, 3667),
Function.ability(271, "Harvest_Return_Mule_quick", cmd_quick, 167, 3667),
Function.ability(272, "Harvest_Return_Probe_quick", cmd_quick, 299, 3667),
Function.ability(273, "Harvest_Return_SCV_quick", cmd_quick, 296, 3667),
Function.ability(274, "HoldPosition_quick", cmd_quick, 18),
Function.ability(275, "Land_screen", cmd_screen, 3678),
Function.ability(276, "Land_Barracks_screen", cmd_screen, 554, 3678),
Function.ability(277, "Land_CommandCenter_screen", cmd_screen, 419, 3678),
Function.ability(278, "Land_Factory_screen", cmd_screen, 520, 3678),
Function.ability(279, "Land_OrbitalCommand_screen", cmd_screen, 1524, 3678),
Function.ability(280, "Land_Starport_screen", cmd_screen, 522, 3678),
Function.ability(281, "Lift_quick", cmd_quick, 3679),
Function.ability(282, "Lift_Barracks_quick", cmd_quick, 452, 3679),
Function.ability(283, "Lift_CommandCenter_quick", cmd_quick, 417, 3679),
Function.ability(284, "Lift_Factory_quick", cmd_quick, 485, 3679),
Function.ability(285, "Lift_OrbitalCommand_quick", cmd_quick, 1522, 3679),
Function.ability(286, "Lift_Starport_quick", cmd_quick, 518, 3679),
Function.ability(287, "Load_screen", cmd_screen, 3668),
Function.ability(288, "Load_Bunker_screen", cmd_screen, 407, 3668),
Function.ability(289, "Load_Medivac_screen", cmd_screen, 394, 3668),
Function.ability(290, "Load_NydusNetwork_screen", cmd_screen, 1437, 3668),
Function.ability(291, "Load_NydusWorm_screen", cmd_screen, 2370, 3668),
Function.ability(292, "Load_Overlord_screen", cmd_screen, 1406, 3668),
Function.ability(293, "Load_WarpPrism_screen", cmd_screen, 911, 3668),
Function.ability(294, "LoadAll_quick", cmd_quick, 3663),
Function.ability(295, "LoadAll_CommandCenter_quick", cmd_quick, 416, 3663),
Function.ability(296, "Morph_Archon_quick", cmd_quick, 1766),
Function.ability(297, "Morph_BroodLord_quick", cmd_quick, 1372),
Function.ability(298, "Morph_Gateway_quick", cmd_quick, 1520),
Function.ability(299, "Morph_GreaterSpire_quick", cmd_quick, 1220),
Function.ability(300, "Morph_Hellbat_quick", cmd_quick, 1998),
Function.ability(301, "Morph_Hellion_quick", cmd_quick, 1978),
Function.ability(302, "Morph_Hive_quick", cmd_quick, 1218),
Function.ability(303, "Morph_Lair_quick", cmd_quick, 1216),
Function.ability(304, "Morph_LiberatorAAMode_quick", cmd_quick, 2560),
Function.ability(305, "Morph_LiberatorAGMode_screen", cmd_screen, 2558),
Function.ability(306, "Morph_Lurker_quick", cmd_quick, 2332),
Function.ability(307, "Morph_LurkerDen_quick", cmd_quick, 2112),
Function.ability(308, "Morph_Mothership_quick", cmd_quick, 1847),
Function.ability(309, "Morph_OrbitalCommand_quick", cmd_quick, 1516),
Function.ability(310, "Morph_OverlordTransport_quick", cmd_quick, 2708),
Function.ability(311, "Morph_Overseer_quick", cmd_quick, 1448),
Function.ability(312, "Morph_PlanetaryFortress_quick", cmd_quick, 1450),
Function.ability(313, "Morph_Ravager_quick", cmd_quick, 2330),
Function.ability(314, "Morph_Root_screen", cmd_screen, | |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENCE BLOCK #####
bl_info = {
"name": "My Big Button",
"author": "Hokuss",
"version": (0, 3, 6),
"blender": (2, 80, 0),
"location": "PROPERTIES WINDOW > Render & 3D View > UI > Render Tab & 3D View header",
"description": "Render Button & Camera Manager for Blender 2.80",
"warning": "",
"wiki_url": "https://blenderartists.org/t/big-render-button-for-blender-2-80/1159414",
"category": "Render",
}
import bpy
import os, platform, subprocess
import aud
from bl_ui.utils import PresetPanel
import time, datetime
from bpy.utils import register_class, unregister_class
from bpy.types import (
Operator,
Panel,Scene, PropertyGroup,Object,Menu, Panel, UIList
)
from bpy.props import (IntProperty,
FloatProperty,
StringProperty,
EnumProperty,
PointerProperty,
)
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#SETTINGS//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class MYBIGBUTTON_Settings(PropertyGroup):
### Render Button[ -------------------------------------------
switchStillAnim_prop : bpy.props.BoolProperty(
name="Animation",
description="Activate Animation Rendering",
default = False)
### ]Render Button
### Render button panel Quick Settings[ -----------------------------
mbbOptions : bpy.props.BoolProperty(
name="Render Quick Settings",
#description="Toggle Quick Settings",
default = False)
## Sound alarm[---
playAfterRender: bpy.props.BoolProperty(
name="Play sound",
description="Play Sound when render is done",
default = False)
soundToPlay: bpy.props.StringProperty(
name="Choose Audio File",
description="Specify location of audio file to play after render",
default="",
subtype="FILE_PATH")
loopSoundToPlay: bpy.props.BoolProperty(
name="loop sound",
description="Play loop Sound",
default = False)
repeatSoundToPlay: bpy.props.IntProperty(
name='Repeat Sound',
description='Repeat sound after render',
min=0, max=100,step=1,default = 0)
alarmInProgress: bpy.props.BoolProperty(
name="Alarm In Progress",
description="Alarm In Progress",
default = False)
abortAlarm: bpy.props.BoolProperty(
name="Abort Alarm",
description="Abort Alarm",
default = False)
## ]Sound alarm
## Power off[---
poweroffAfterRender: bpy.props.BoolProperty(
name="Power Off",
description="Power Off after render",
default = False)
timeoutPowerOff: bpy.props.IntProperty(
name='Timeout Delay',
description='Delay in secondes before Power Off',
min=15, max=1200,step=1,default = 60)
countDownAfterRender : bpy.props.IntProperty(
name="Countdown after render",
description="Countdown after render",
default = 0)
saveAtPowerOff: bpy.props.BoolProperty(
name="Save Blender File",
description="Save Blender file before Power Off",
default = False)
## ]Power off
## Auto save render[---
saveInBlendFolder: bpy.props.BoolProperty(
name="Save in blend folder",
description="Save Camera Output in blend folder",
default = False)
storeRenderInSlots: bpy.props.BoolProperty(
name="Store in Slots",
description="Store Cameras Output in Render Slots",
default = False)
## ]Auto save render
### ]Render button panel Quick Settings
### Dimensions settings[ -------------------------------------
switchRenderRotation_prop : bpy.props.BoolProperty(
name="Rotation",
description="Toggle Landscape / Portrait",
default = False)
Default_HRes_prop : bpy.props.IntProperty(
name="DHres",
description="Horizontal Default Dimension",
default = 1920,max=65536,min=4,step=1
)
Default_VRes_prop : bpy.props.IntProperty(
name="DVres",
description="Vertical Default Dimension",
default = 1080,max=65536,min=4,step=1
)
Default_HPixRes_prop : bpy.props.IntProperty(
name="DHPix",
description="Horizontal Default Pixel Aspect",
default = 1)
Default_VPixRes_prop : bpy.props.IntProperty(
name="DVPix",
description="Vertical Default Pixel Aspect",
default = 1)
### ]Dimensions settings
### Camera Manager panel Quick Settings[ -----------------------------------------
## Cameras Manager quick settings UI[---
cmOptions : bpy.props.BoolProperty(
name="Camera Manager Quick Settings",
#description="Toggle Quick Settings",
default = False)
cmBut_Render : bpy.props.BoolProperty(
name="Toggle Render Camera",
default = True)
cmBut_AlignV : bpy.props.BoolProperty(
name="Toggle Align Camera To View",
default = True)
cmBut_AlignO : bpy.props.BoolProperty(
name="Toggle Aligne Camera To Object",
default = True)
cmBut_Trackto : bpy.props.BoolProperty(
name="Toggle Track To",
default = True)
cmBut_Marker : bpy.props.BoolProperty(
name="Toggle Marker",
default = True)
cmBut_AnimData : bpy.props.BoolProperty(
name="Toggle AnimData",
default = True)
Manager_ShowSelect : bpy.props.BoolProperty(
name="Hilighlight Selected Camera",
default = True)
Manager_ShowSelect_Color : bpy.props.BoolProperty(
name="Selected Camera Hilighlight with red",
description="Selected Camera Hilighlight with red",
default = True)
Manager_ShowSelect_Gray : bpy.props.BoolProperty(
name="Not selected Camera Grayed out",
description="Not selected Camera Grayed out",
default = True)
Manager_ShowSelect_Pointer : bpy.props.BoolProperty(
name="Add a pointer before Selected Camera",
description="Add a pointer before Selected Camera",
default = False)
## ]Cameras Manager quick settings UI
## Default settings for new cameras[---
NewCam_lensPersp : bpy.props.IntProperty(
name='Focal Length',
description='New camera Focal Length ',
min=1, max=5000,step=1,default = 50)
NewCam_lensOrtho : bpy.props.FloatProperty(
name='Orthographic Scale',
description='New camera Orthographic Scale',
min=0.001, max=100000,step=0.1,default = 35.000, precision= 3)
NewCam_ClipStart : bpy.props.FloatProperty(
name='Clip Start',
description='New camera Clip start',
min=0.001, max=100000,step=0.1,default = 0.1, precision= 3)
NewCam_ClipEnd : bpy.props.FloatProperty(
name='Clip End',
description='New camera clip end',
min=0.001, max=100000,step=0.1,default = 1000, precision= 3)
NewCam_ClipStartOrtho : bpy.props.FloatProperty(
name='Ortho Clip Start',
description='New camera Orthographic clip start',
min=0.001, max=100000,step=0.1,default = 0.1, precision= 3)
NewCam_ClipEndOrtho : bpy.props.FloatProperty(
name='Ortho Clip End',
description='New camera Orthographic clip end',
min=0.001, max=100000,step=0.1,default = 1000, precision= 3)
## ]Default settings for new cameras
### ]Camera Manager panel Quick Settings
### Batch Render Property[ -----------------------------------------
switchRenderSelection: bpy.props.BoolProperty(
name="Cameras Listing ",
description="Toglle to Cameras listing for Batch Rendering",
default = False)
### ]Batch Render Property
class MYBIGBUTTON_obj_Settings(PropertyGroup):
### Cameras Properties[ -------------------------------------------------
Custom_Camtrack_prop : bpy.props.BoolProperty(
name="Track",
description="Camera Track To property",
default = False)
Custom_CamMarker_prop : bpy.props.BoolProperty(
name="Marker",
description="Camera Marker property",
default = False)
Custom_CamRes_prop : bpy.props.BoolProperty(
name="Custom Resolution",
description="Camera custom resolution property",
default = False)
Custom_CamRender_prop : bpy.props.BoolProperty(
name="Add This Camera",
description="Add in batch rendering list",
default = False)
### ]Cameras Properties
## Cameras Custom resolution[------------------------------------------
Custom_CamHRes_prop : bpy.props.IntProperty(
name="Custom Horizontal Resolution",
description="Custom Horizontal Resolution",
default = 1920)
Custom_CamVRes_prop : bpy.props.IntProperty(
name="Custom Vertical Resolution",
description="Custom Vertical Resolution",
default = 1080)
Custom_CamHPixRes_prop : bpy.props.IntProperty(
name="Custom Horizontal Pixel Aspect",
description="Custom Horizontal Pixel Aspect",
default = 1)
Custom_CamVPixRes_prop : bpy.props.IntProperty(
name="Custom Vertical Pixel Aspect",
description="Custom Vertical Pixel Aspect",
default = 1)
## ]Cameras Custom resolution
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Function /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
def ShowMessageBox(message = "", title = "Message Box", icon = 'INFO'):
def draw(self, context):
self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
def visualAlarm(self, context):
scene = context.scene
rd = scene.render
rs = scene.RBTab_Settings
layout = self.layout
row = layout.row(align=True)
row.scale_y = 3
row.alert = True
if rs.countDownAfterRender == 0 and rs.playAfterRender == True:
row.prop(rs,"abortAlarm", text="RENDER IS DONE",icon='BLANK1',emboss=False)
elif rs.countDownAfterRender == 0:
row.prop(rs,"abortAlarm", text="RENDER IS DONE".format(rs.countDownAfterRender),icon='BLANK1',emboss=False)
else:
if rs.countDownAfterRender%2 == 0 :
row.alert = False
else : row.alert = True
row.prop(rs,"abortAlarm", text="POWER OFF IN {0} SEC".format(rs.countDownAfterRender),icon='BLANK1',emboss=False)
row = layout.row(align=True)
row.alert = False
row.prop(rs,"abortAlarm", text="Click or ESC to Abort",icon='BLANK1',emboss=False)
def SetCameraDimension(self, context):
scene = context.scene
render = scene.render
chosen_camera = context.active_object
previousSceneCamera = scene.camera
scene.camera = chosen_camera
cs = chosen_camera.RBTab_obj_Settings
rs = scene.RBTab_Settings
if cs.Custom_CamRes_prop == True:
render.resolution_x = cs.Custom_CamHRes_prop
render.resolution_y = cs.Custom_CamVRes_prop
render.pixel_aspect_x = cs.Custom_CamHPixRes_prop
render.pixel_aspect_y = cs.Custom_CamVPixRes_prop
else :
render.resolution_x = rs.Default_HRes_prop
render.resolution_y = rs.Default_VRes_prop
render.pixel_aspect_x = rs.Default_HPixRes_prop
render.pixel_aspect_y = rs.Default_VPixRes_prop
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#OPERATOR /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# ADD CAMERA ##################################################################################
class SCENECAMERA_OT_Add(Operator):
bl_idname = "cameramanager.add_scene_camera"
bl_label = "add Camera"
bl_description = "Add Camera"
#bl_options = {'UNDO'}
def execute(self, context):
scene = context.scene
rd = scene.render
sp = scene.RBTab_Settings
#Store active collection before add Camera
Active_Coll = bpy.context.view_layer.active_layer_collection
# Make Master Collection active before add camera
context.view_layer.active_layer_collection = context.view_layer.layer_collection
bpy.ops.object.camera_add()
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
if context.area.spaces[0].region_3d.is_perspective:
bpy.context.object.data.type = 'PERSP'
bpy.context.object.data.lens = sp.NewCam_lensPersp
bpy.context.object.data.clip_start = sp.NewCam_ClipStart
bpy.context.object.data.clip_end = sp.NewCam_ClipEnd
else:
bpy.context.object.data.type = 'ORTHO'
bpy.context.object.data.ortho_scale = sp.NewCam_lensOrtho
bpy.context.object.data.clip_start = sp.NewCam_ClipStartOrtho
bpy.context.object.data.clip_end = sp.NewCam_ClipEndOrtho
break
bpy.context.object.show_name = True
bpy.context.object.data.show_name = True
#Restore collection active before adding camera
bpy.context.view_layer.active_layer_collection = Active_Coll
###Align to view last camera added
chosen_camera = context.active_object
scene.camera = chosen_camera
bpy.context.space_data.camera = bpy.data.objects[chosen_camera.name]
bpy.ops.object.select_all(action='DESELECT')
chosen_camera.select_set(state = True)
if rd.resolution_x != sp.Default_HRes_prop or rd.resolution_y != sp.Default_VRes_prop:
chosen_camera.RBTab_obj_Settings.Custom_CamRes_prop = True
chosen_camera.RBTab_obj_Settings.Custom_CamHRes_prop = rd.resolution_x
chosen_camera.RBTab_obj_Settings.Custom_CamVRes_prop = rd.resolution_y
chosen_camera.RBTab_obj_Settings.Custom_CamHPixRes_prop | |
CHRM_SIZE = clr.chromsizes[chr1]
CHUNK_SIZE = max(2 * distance_in_bp / res, 2000)
start = 0
end = min(CHUNK_SIZE * res, CHRM_SIZE) # CHUNK_SIZE*res
result = []
val = []
###########################
if chr1 == chr2:
# try:
# normVec = clr.bins()['weight'].fetch(chr1)
# result = clr.matrix(balance=True,sparse=True).fetch(chr1)#as_pixels=True, join=True
while start < CHRM_SIZE:
print(int(start), int(end))
if not cooler_balance:
temp = clr.matrix(balance=True, sparse=True).fetch((chr1, int(start), int(end)))
else:
temp = clr.matrix(balance=cooler_balance, sparse=True).fetch((chr1, int(start), int(end)))
temp = sparse.triu(temp)
np.nan_to_num(temp, copy=False, nan=0, posinf=0, neginf=0)
start_in_px = int(start / res)
if len(temp.row) == 0:
start = min(start + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE)
if end == CHRM_SIZE - 1:
break
else:
end = min(end + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE - 1)
continue
if result == []:
result += [list(start_in_px + temp.row), list(start_in_px + temp.col), list(temp.data)]
prev_block = set(
[(x, y, v) for x, y, v in zip(start_in_px + temp.row, start_in_px + temp.col, temp.data)])
else:
cur_block = set(
[(x, y, v) for x, y, v in zip(start_in_px + temp.row, start_in_px + temp.col, temp.data)])
to_add_list = list(cur_block - prev_block)
del prev_block
result[0] += [x[0] for x in to_add_list]
result[1] += [x[1] for x in to_add_list]
result[2] += [x[2] for x in to_add_list]
prev_block = cur_block
del cur_block
start = min(start + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE)
if end == CHRM_SIZE - 1:
break
else:
end = min(end + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE - 1)
# except:
# raise NameError('Reading from the file failed!')
if len(result) == 0:
print(f'There is no contact in chrmosome {chr1} to work on.')
return [], [], [], res
x = np.array(result[0])
y = np.array(result[1])
val = np.array(result[2])
else:
result = clr.matrix(balance=True, sparse=True).fetch(chr1, chr2)
result = sparse.triu(result)
np.nan_to_num(result, copy=False, nan=0, posinf=0, neginf=0)
x = result.row
y = result.col
val = result.data
##########################
if len(val) == 0:
print(f'There is no contact in chrmosome {chr1} to work on.')
return [], [], [], res
else:
val[np.isnan(val)] = 0
if (chr1 == chr2):
dist_f = np.logical_and(np.abs(x - y) <= distance_in_bp / res, val > 0)
x = x[dist_f]
y = y[dist_f]
val = val[dist_f]
# return np.array(x),np.array(y),np.array(val), res, normVec
if len(val > 0):
return np.array(x), np.array(y), np.array(val), res
else:
print(f'There is no contact in chrmosome {chr1} to work on.')
return [], [], [], res
def read_mcooler(f, distance_in_bp, chr1, chr2, res, cooler_balance):
"""
:param f: .cool file path
:param chr: Which chromosome to read the file for
:param res: Resolution to extract information from
:return: Numpy matrix of contact counts
"""
uri = '%s::/resolutions/%s' % (f, res)
# uri = '%s::/7' % (f)
clr = cooler.Cooler(uri)
# print(clr.bins()[:100])
if chr1 not in clr.chromnames or chr2 not in clr.chromnames:
raise NameError('wrong chromosome name!')
CHRM_SIZE = clr.chromsizes[chr1]
CHUNK_SIZE = max(2 * distance_in_bp / res, 2000)
start = 0
end = min(CHRM_SIZE, CHUNK_SIZE * res) # CHUNK_SIZE*res
result = []
val = []
if chr1 == chr2:
try:
# result = clr.matrix(balance=True,sparse=True).fetch(chr1)#as_pixels=True, join=True
while start < CHRM_SIZE:
print(int(start), int(end))
if not cooler_balance:
temp = clr.matrix(balance=True, sparse=True).fetch((chr1, int(start), int(end)))
else:
temp = clr.matrix(balance=cooler_balance, sparse=True).fetch((chr1, int(start), int(end)))
temp = sparse.triu(temp)
np.nan_to_num(temp, copy=False, nan=0, posinf=0, neginf=0)
start_in_px = int(start / res)
if len(temp.row) == 0:
start = min(start + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE)
if end == CHRM_SIZE - 1:
break
else:
end = min(end + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE - 1)
continue
if result == []:
result += [list(start_in_px + temp.row), list(start_in_px + temp.col), list(temp.data)]
prev_block = set(
[(x, y, v) for x, y, v in zip(start_in_px + temp.row, start_in_px + temp.col, temp.data)])
# print('result==[]')
else:
cur_block = set(
[(x, y, v) for x, y, v in zip(start_in_px + temp.row, start_in_px + temp.col, temp.data)])
to_add_list = list(cur_block - prev_block)
del prev_block
result[0] += [x[0] for x in to_add_list]
result[1] += [x[1] for x in to_add_list]
result[2] += [x[2] for x in to_add_list]
prev_block = cur_block
del cur_block
start = min(start + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE)
if end == CHRM_SIZE - 1:
break
else:
end = min(end + CHUNK_SIZE * res - distance_in_bp, CHRM_SIZE - 1)
except:
raise NameError('Reading from the file failed!')
if len(result) == 0:
print(f'There is no contact in chrmosome {chr1} to work on.')
return [], [], []
x = np.array(result[0])
y = np.array(result[1])
val = np.array(result[2])
else:
result = clr.matrix(balance=True, sparse=True).fetch(chr1, chr2)
result = sparse.triu(result)
np.nan_to_num(result, copy=False, nan=0, posinf=0, neginf=0)
x = result.row
y = result.col
val = result.data
if len(val) == 0:
print(f'There is no contact in chrmosome {chr1} to work on.')
return [], [], []
else:
val[np.isnan(val)] = 0
if (chr1 == chr2):
dist_f = np.logical_and(np.abs(x - y) <= distance_in_bp / res, val > 0)
x = x[dist_f]
y = y[dist_f]
val = val[dist_f]
if len(val > 0):
return np.array(x), np.array(y), np.array(val)
else:
print(f'There is no contact in chrmosome {chr1} to work on.')
return [], [], []
def get_diags(map):
"""
:param map: Contact map, numpy matrix
:return: 2 Dictionaries where keys are the diagonal number and values are the mean of that diagonal in one dictionary and the std. in the other dictionary.
"""
means = {}
stds = {}
for i in range(len(map)):
diag = map.diagonal(i)
diag = diag[diag != 0]
if len(diag) > 0:
mean = np.mean(diag)
std = np.std(diag) if np.std(diag) != 0 else 1
if math.isnan(mean):
means[i] = 0
else:
means[i] = mean
if math.isnan(std):
stds[i] = 1
else:
stds[i] = std
else:
means[i] = 0
stds[i] = 1
return means, stds
def normalize_sparse(x, y, v, resolution, distance_in_px):
n = max(max(x), max(y)) + 1
# distance_in_px = min(distance_in_px, n)
pval_weights = []
distances = np.abs(y - x)
if (n - distance_in_px) * resolution > 2000000:
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=RuntimeWarning)
filter_size = int(2000000 / resolution)
for d in range(2 + distance_in_px):
indices = distances == d
vals = np.zeros(n - d)
vals[x[indices]] = v[indices] + 0.001
if vals.size == 0:
continue
std = np.std(v[indices])
mean = np.mean(v[indices])
if math.isnan(mean):
mean = 0
if math.isnan(std):
std = 1
kernel = np.ones(filter_size)
counts = np.convolve(vals != 0, kernel, mode='same')
s = np.convolve(vals, kernel, mode='same')
s2 = np.convolve(vals ** 2, kernel, mode='same')
local_var = (s2 - s ** 2 / counts) / (counts - 1)
std2 = std ** 2
np.nan_to_num(local_var, copy=False,
neginf=std2, posinf=std2, nan=std2)
local_mean = s / counts
local_mean[counts < 30] = mean
local_var[counts < 30] = std2
np.nan_to_num(local_mean, copy=False,
neginf=mean, posinf=mean, nan=mean)
local_std = np.sqrt(local_var)
vals[x[indices]] -= local_mean[x[indices]]
vals[x[indices]] /= local_std[x[indices]]
np.nan_to_num(vals, copy=False, nan=0, posinf=0, neginf=0)
vals = vals * (1 + math.log(1 + mean, 30))
pval_weights += [1 + math.log(1 + mean, 30)]
v[indices] = vals[x[indices]]
else:
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=RuntimeWarning)
np.nan_to_num(v, copy=False, neginf=0, posinf=0, nan=0)
distance_in_px = min(distance_in_px, n)
for d in range(distance_in_px):
indices = distances == d
std = np.std(v[indices])
mean = np.mean(v[indices])
if math.isnan(mean):
mean = 0
if math.isnan(std):
std = 1
# print(std)
v[indices] = (v[indices] - mean) / std
np.nan_to_num(v, copy=False, nan=0, posinf=0, neginf=0)
return pval_weights
def inter_nrmalize_map(vals):
m = np.mean(vals)
s = np.std(vals)
cmap -= m
cmap /= s
np.nan_to_num(cmap, copy=False, nan=0, posinf=0, neginf=0)
def mustache(c, chromosome, chromosome2, res, pval_weights, start, end, mask_size, distance_in_px, octave_values, st,
pt):
nz = np.logical_and(c != 0, np.triu(c, 4))
nz_temp = np.logical_and.reduce((c != 0, np.triu(c, 4) > 0, np.tril(c, distance_in_px) > 0))
if np.sum(nz) < 50:
return []
c[np.tril_indices_from(c, 4)] = 2
if chromosome == chromosome2:
c[np.triu_indices_from(c, k=(distance_in_px + 1))] = 2
pAll = np.ones_like(c[nz]) * 2
Scales = np.ones_like(pAll)
vAll = np.zeros_like(pAll)
s = 10
# curr_filter = 1
scales = {}
for o in octave_values:
scales[o] = {}
sigma = o
w = 2 * math.ceil(2 * sigma) + 1
t = (((w - 1) / 2) - 0.5) / sigma
Gp = gaussian_filter(c, o, truncate=t, order=0)
scales[o][1] = sigma
sigma = o * 2 ** ((2 - 1) / s)
w = 2 * math.ceil(2 * sigma) + 1
t = (((w - 1) / 2) - 0.5) / sigma
Gc | |
"""
Written by <NAME> and contributed to by <NAME>.
Using the NOAA rubrics Dr Habermann created, and his work
conceptualizing the documentation language so that rubrics using
recommendations from other earth science communities can be applied
to multiple metadata dialects as a part of the USGeo BEDI and
NSF DIBBs projects. This python module as an outcome of DIBBs allows
a user to initiate an evaluation of valid XML and assess the degree
to which the collection of records is likely to meet a community information need.
The basic workflow is to retrieve records, evaluate for xpaths that contain
text, run occurrence functions on csv output of evaluation, create reports with
the outputs, if you want to compare between collections, combine csv outputs with
appropriate combination functions, create organizationSpreadsheet. Finally run
WriteToGoogle on any outputs you want to share to get a viewable/downloadable link.
"""
import pandas as pd
import csv
import gzip
import os
import requests
import xlsxwriter
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from lxml import etree
import sys
import logging
from IPython.core.display import display, HTML
import itertools
from plotly import tools
import plotly.plotly
from _plotly_future_ import v4
import plotly.graph_objs as go
import plotly.io as pio
from plotly.offline import iplot, init_notebook_mode
pio.orca.config.use_xvfb = True
init_notebook_mode(connected=True)
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
lggr = logging.getLogger(__name__)
csv.field_size_limit(sys.maxsize)
# function to download metadata
def get_records(urls, xml_files, well_formed=True):
"""Download metadata records. Metadata records are download from the
supplied ``urls`` and stored in files whose names are found on
``xml_files``. When ``well_formed`` is ``True`` downloaded XML will
be saved to a file only if well-formed.
"""
""" if we used a function
like this to collect xml, it would be the root of any processing steps
"""
if len(urls) != len(xml_files):
raise ValueError('Different number of URLs and record file names')
for url, fname in zip(urls, xml_files):
try:
r = requests.get(url)
r.raise_for_status()
except Exception:
print('There was an error downloading from {}'.format(url))
if well_formed:
try:
etree.fromstring(r.text)
except Exception:
print('Metadata record from {} not well-formed'.format(url))
if fname[-4:] != '.xml':
fname += '.xml'
with open(fname, 'wt') as f:
f.write(r.text)
def recordXpathContent(EvaluatedMetadataDF):
"""requires a dataframe with elements. Creates a vertical view of
concept content for each record in the collection. Useful in the
creation of json.
"""
EvaluatedMetadataDF = EvaluatedMetadataDF.applymap(str)
group_name = EvaluatedMetadataDF.groupby([
'Collection', 'Record', 'XPath'], as_index=False)
occurrenceMatrix = group_name['Content'].apply(
lambda x: '%s' % ', '.join(x)).unstack().reset_index()
occurrenceMatrix.columns.names = ['']
#FILLvalues = 'No Content'
#occurrenceMatrix = occurrenceMatrix.fillna(value=FILLvalues)
occurrenceMatrix.reset_index()
return(occurrenceMatrix)
def applyRecommendation(recElements, recommendationName, collection):
# places for all the evaluated and analyzed data
XpathEvaluated = os.path.join("..","data", recommendationName, collection + "_XpathEvaluated.csv.gz")
EvaluatedDF = pd.read_csv(XpathEvaluated)
# Use above dataframe and apply the xpathCounts and xpathOccurrence functions from MDeval for each recommendation
RecommendationEvaluated = os.path.join("..","data", recommendationName, collection + '_' + recommendationName + 'Evaluated.csv.gz')
#RecommendationCounts = os.path.join("../data/", collection + '_' + recommendationName + 'Counts.csv')
RecommendationOccurrence = os.path.join("..","data", recommendationName, collection + '_' + recommendationName + 'Occurrence.csv')
# Use the output of the evaluation transform and the piped string
# of all root paths to create a dataframe of just recommendation elements
recElementsPattern = '|'.join(recElements)
RecommendationDF = EvaluatedDF[EvaluatedDF['XPath'].str.contains(recElementsPattern)]
RecommendationDF.to_csv(RecommendationEvaluated, index=False, compression='gzip')
#XpathCounts(RecommendationDF, RecommendationCounts)
# change order of rows to be meaningful for recommendation
#RecommendationCountsDF = pd.read_csv(RecommendationCounts)
CollectionRecRows = []
CollectionRecRows.append(["Number of Records"])
CollectionRecColumns = []
CollectionRecColumns.append(["Collection","Record"])
XpathOccurrence(RecommendationDF, collection, RecommendationOccurrence)
RecommendationOccurrenceDF = pd.read_csv(RecommendationOccurrence)
for element in recElements:
# find the rows that match each element
CollectionElements = list(RecommendationOccurrenceDF['XPath'])[1:]
matchingElements = [CollectionElement for CollectionElement in CollectionElements if element in CollectionElement]
#append the list to a master list that will be used to order the chart
CollectionRecRows.append(matchingElements)
CollectionRecColumns.append(matchingElements)
CollectionRecRows = [item for sublist in CollectionRecRows for item in sublist]
CollectionRecColumns = [item for sublist in CollectionRecColumns for item in sublist]
from collections import OrderedDict
CollectionRecRows = list(OrderedDict.fromkeys(CollectionRecRows))
CollectionRecColumns = list(OrderedDict.fromkeys(CollectionRecColumns))
#RecommendationCountsDF = RecommendationCountsDF[CollectionRecColumns]
# write over the previous csv
#RecommendationCountsDF.to_csv(RecommendationCounts, index=False, mode='w')
# change order of rows to be meaningful for recommendation
RecommendationOccurrenceDF = RecommendationOccurrenceDF.set_index('XPath')
RecommendationOccurrenceDF = RecommendationOccurrenceDF.loc[CollectionRecRows]
RecommendationOccurrenceDF = RecommendationOccurrenceDF.reset_index()
def XpathCounts(EvaluatedMetadataDF,
DataDestination, to_csv=True):
"""XpathCounts requires a dataframe with xpath.The DF
can created be localAllNodesEval, XMLeval(not accurate), or
a simpleXpath. It is required for combineXpathCounts"""
group_name = EvaluatedMetadataDF.groupby(
['Collection', 'Record', 'XPath'], as_index=False)
XpathCountsDF = group_name.size().unstack().reset_index()
XpathCountsDF = XpathCountsDF.fillna(0)
pd.options.display.float_format = '{:,.0f}'.format
if to_csv:
lggr.info('Saving Xpath counts report to %s' % DataDestination)
XpathCountsDF.to_csv(DataDestination, mode='w', index=False)
return XpathCountsDF
def XpathOccurrence(EvaluatedMetadataDF, Collection,
DataDestination, to_csv=True):
# xpath occurrence data product
"""requires a list of xpathOccurrence csv.
It is required for CombinationSpreadsheet
"""
DataDestinationDirectory = DataDestination[:DataDestination.rfind('/') + 1]
os.makedirs(DataDestinationDirectory, exist_ok=True)
group_name = EvaluatedMetadataDF.groupby(
['Record', 'XPath'], as_index=False)
occurrenceMatrix = group_name.size().unstack().reset_index()
occurrenceMatrix = occurrenceMatrix.fillna(0)
occurrenceSum = occurrenceMatrix.sum()
occurrenceCount = occurrenceMatrix[occurrenceMatrix != 0].count()
result = pd.concat([occurrenceSum, occurrenceCount], axis=1).reset_index()
result.insert(
1, 'Collection', Collection)
result.insert(4, 'CollectionOccurrence%', Collection)
result.insert(4, 'AverageOccurrencePerRecord', Collection)
result.columns = [
'XPath', 'Collection', 'XPathCount', 'RecordCount',
'AverageOccurrencePerRecord', 'CollectionOccurrence%'
]
NumberOfRecords = result.at[0, 'XPathCount'].count('.xml')
result['CollectionOccurrence%'] = result['RecordCount'] / NumberOfRecords
result.at[0, 'XPathCount'] = NumberOfRecords
result.at[0, 'XPath'] = 'Number of Records'
result.at[0, 'CollectionOccurrence%'] = NumberOfRecords
result['AverageOccurrencePerRecord'] = (
result['XPathCount'] / NumberOfRecords)
result[['AverageOccurrencePerRecord', 'CollectionOccurrence%']] = (
result[['AverageOccurrencePerRecord',
'CollectionOccurrence%']].astype(float)
)
result[["XPathCount", "RecordCount"]] = (
result[["XPathCount", "RecordCount"]].astype(int)
)
result['AverageOccurrencePerRecord'] = (pd.Series([
"{0:.2f}".format(val) for val in result['AverageOccurrencePerRecord']
], index=result.index))
result.at[0, 'AverageOccurrencePerRecord'] = NumberOfRecords
if to_csv:
lggr.info('Saving XPath occurrence report to %s' % DataDestination)
result.to_csv(DataDestination, mode='w', index=False)
return result
def CombineXPathOccurrence(CollectionComparisons,
DataDestination, to_csv=True):
"""Using xpath occurrence data products, combine them and produce a
collection occurrence% table with collections for columns and
concepts for rows requires a list of xpathOccurrence csv.
It is required for CombinationSpreadsheet
"""
DataDestinationDirectory = DataDestination[:DataDestination.rfind('/') + 1]
os.makedirs(DataDestinationDirectory, exist_ok=True)
CombinedDF = pd.concat((pd.read_csv(f) for f in CollectionComparisons))
CombinedPivotDF = CombinedDF.pivot(
index='XPath', columns='Collection', values='CollectionOccurrence%')
ConceptCountsDF = CombinedPivotDF.fillna(0)
ConceptCountsDF.columns.names = ['']
ConceptCountsDF = ConceptCountsDF.reset_index()
line = ConceptCountsDF[ConceptCountsDF['XPath'] == 'Number of Records']
ConceptCountsDF = pd.concat(
[ConceptCountsDF[0:0], line,
ConceptCountsDF[0:]]).reset_index(drop=True)
ConceptCountsDF.drop(
ConceptCountsDF.tail(1).index, inplace=True)
if to_csv:
lggr.info('Saving concept count report to %s' % DataDestination)
ConceptCountsDF.to_csv(DataDestination, mode='w', index=False)
return ConceptCountsDF
def CombinationSpreadsheet(xpathOccurrence, recommendationOccurrence,
RecommendationConcept, RecommendationGraph,
RecGraphLink,
DataDestination, AVGxpathOccurrence=None,
AVGrecommendationOccurrence=None,
recommendationCounts=None, xpathCounts=None,
recommendationOccurrence2=None,
RecommendationConcept2=None, RecommendationGraph2=None,
RecGraphLink2=None, AVGrecommendationOccurrence2=None,
recommendationCounts2=None):
# create spreadsheet for an organization
"""requires each xpath and concept occurrence,
csv for a organization
(or any group of collections you want to compare)
"""
lggr.info('Saving spreadsheet %s' % DataDestination)
workbook = xlsxwriter.Workbook(DataDestination,
{'strings_to_numbers': True})
workbook.use_zip64()
cell_format11 = workbook.add_format()
cell_format11.set_num_format('0%')
cell_format04 = workbook.add_format()
cell_format04.set_num_format('0')
cell_format05 = workbook.add_format()
cell_format05.set_num_format('0.00')
formatGreen = workbook.add_format(
{'bg_color': '#C6EFCE', 'font_color': '#006100'})
formatRed = workbook.add_format(
{'bg_color': '#FFC7CE', 'font_color': '#9C0006'})
formatYellow = workbook.add_format(
{'bg_color': '#FFEB9C', 'font_color': '#9C6500'})
RecommendationConceptWS = workbook.add_worksheet(
'BestPractices2004_Concepts')
# RecommendationGraphWS = workbook.add_worksheet(
# 'RecommendationGraph')
# Insert an image with scaling.
RecommendationConceptWS.write('A29', "Full Image")
RecommendationConceptWS.write('B29', RecGraphLink)
RecommendationConceptWS.insert_image('A30', RecommendationGraph, {'x_scale': .07, 'y_scale': .07})
Reader = csv.reader(
open(RecommendationConcept, 'r'), delimiter=',', quotechar='"')
row_count = 0
RecommendationConceptWS.set_row(0, None, cell_format04)
RecommendationConceptWS.set_row(2, None, cell_format04)
for row in Reader:
for col in range(len(row)):
RecommendationConceptWS.write(row_count, col, row[col])
RecommendationConceptWS.set_column(col, col, 7, cell_format11)
row_count += 1
RecommendationConceptWS.set_column(0, 0, 20)
RecommendationConceptWS.set_column(1, 1, 15)
RecommendationConceptWS.set_column(2, 2, 20)
RecommendationAnalysisWS = workbook.add_worksheet(
'BestPractices2004_Elements')
RecommendationAnalysisWS.set_column(2, 4, 12)
recommendationoccurrenceWS = workbook.add_worksheet(
'BestPractices2004_Occurrence')
avgRecommendationOccurWS = workbook.add_worksheet(
'BestPractices2004_AVGoccurrence')
if recommendationCounts is not None:
recommendationcounts = workbook.add_worksheet('BestPractices2004_Counts')
###################################################################
# if a second recommendation
if recommendationOccurrence2 is not None:
RecommendationConcept2WS = workbook.add_worksheet(
'BestPractices2011_Concepts')
# RecommendationGraphWS = workbook.add_worksheet(
# 'RecommendationGraph')
# Insert an image with scaling.
RecommendationConcept2WS.write('A31', "Full Image")
RecommendationConcept2WS.write('B31', RecGraphLink2)
RecommendationConcept2WS.insert_image('A33', RecommendationGraph2, {'x_scale': .07, 'y_scale': .07})
Reader = csv.reader(
open(RecommendationConcept2, 'r'), delimiter=',', quotechar='"')
row_count = 0
RecommendationConcept2WS.set_row(0, None, cell_format04)
RecommendationConcept2WS.set_row(2, None, cell_format04)
for row in Reader:
for col in range(len(row)):
RecommendationConcept2WS.write(row_count, col, row[col])
RecommendationConcept2WS.set_column(col, col, 7, cell_format11)
row_count += 1
RecommendationConcept2WS.set_column(0, 0, 20)
RecommendationConcept2WS.set_column(1, 1, 15)
RecommendationConcept2WS.set_column(2, 2, 20)
RecommendationAnalysis2WS = workbook.add_worksheet(
'BestPractices2011_Elements')
RecommendationAnalysis2WS.set_column(2, 4, 12)
recommendationoccurrence2WS = workbook.add_worksheet(
'BestPractices2011_Occurrence')
avgRecommendationOccur2WS = workbook.add_worksheet(
'BestPractices2011_AVGoccurrence')
if recommendationCounts2 is not None:
recommendationCounts2 = workbook.add_worksheet('BestPractices2011_Counts')
#######################################################################
RecommendationAnalysis2WS.set_column('A:A', 70)
RecommendationAnalysis2WS.set_column('B:B', 20)
recommendationoccurrence2WS.set_column('A:A', 70)
recommendationoccurrence2WS.hide()
Reader = csv.reader(
open(recommendationOccurrence2, 'r'), delimiter=',', quotechar='"')
row_count = 0
recommendationoccurrence2WS.set_row(1, None, cell_format04)
for row in Reader:
for col in range(len(row)):
recommendationoccurrence2WS.write(
row_count, col, row[col])
recommendationoccurrence2WS.set_column(
col, col, 15, cell_format11)
row_count += 1
Reader = csv.reader(
open(recommendationOccurrence2, 'r'), delimiter=',', quotechar='"')
row_count = 0
for row in Reader:
if Reader.line_num != 2:
for col in range(1, len(row)):
RecommendationAnalysis2WS.write(
row_count + 9, col + 4, row[col], cell_format11
)
for col in range(0, 1):
RecommendationAnalysis2WS.write(
row_count | |
'__file__'):
pkgdir = []
else:
pkgdir = getattr(self.module, '__path__',
[path.dirname(self.module.__file__)])
if self.is_package():
for (_, root, _) in pkgutil.iter_modules(pkgdir):
# Ignore if this module was already doc'd.
if root in self.doc:
continue
# Ignore if it isn't exported, unless we've specifically
# requested to document all submodules.
if not self._allsubmodules \
and not self.__is_exported(root, self.module):
continue
fullname = '%s.%s' % (self.name, root)
m = _safe_import(fullname)
if m is None:
continue
self.doc[root] = self.__new_submodule(root, m)
# Now see if we can grab inheritance relationships between classes.
for docobj in self.doc.values():
if isinstance(docobj, Class):
docobj._fill_inheritance()
# Build the reference name dictionary.
for basename, docobj in self.doc.items():
self.refdoc[docobj.refname] = docobj
if isinstance(docobj, Class):
for v in docobj.class_variables():
self.refdoc[v.refname] = v
for v in docobj.instance_variables():
self.refdoc[v.refname] = v
for f in docobj.methods():
self.refdoc[f.refname] = f
for f in docobj.functions():
self.refdoc[f.refname] = f
# Finally look for more docstrings in the __budoc__ override.
for name, docstring in getattr(self.module, '__budoc__', {}).items():
refname = '%s.%s' % (self.refname, name)
if docstring is None:
self.doc.pop(name, None)
self.refdoc.pop(refname, None)
continue
dobj = self.find_ident(refname)
if isinstance(dobj, External):
continue
dobj.docstring = inspect.cleandoc(docstring)
def is_package(self):
"""
Returns `True` if this module is a package.
Works by checking if `__package__` is not `None` and whether it
has the `__path__` attribute.
"""
return hasattr(self.module, '__path__')
@property
def source(self):
return _source(self.module)
@property
def refname(self):
return self.name
def mro(self, cls):
"""
Returns a method resolution list of documentation objects
for `cls`, which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
"""
ups = inspect.getmro(cls.cls)
return list(map(lambda c: self.find_class(c), ups))
def descendents(self, cls):
"""
Returns a descendent list of documentation objects for `cls`,
which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
"""
if cls.cls == type or not hasattr(cls.cls, '__subclasses__'):
# Is this right?
return []
downs = cls.cls.__subclasses__()
return list(map(lambda c: self.find_class(c), downs))
def is_public(self, name):
"""
Returns `True` if and only if an identifier with name `name` is
part of the public interface of this module. While the names
of sub-modules are included, identifiers only exported by
sub-modules are not checked.
`name` should be a fully qualified name, e.g.,
<code>pydoc.Module.is_public</code>.
"""
return name in self.refdoc
def find_class(self, cls):
"""
Given a Python `cls` object, try to find it in this module
or in any of the exported identifiers of the submodules.
"""
for doc_cls in self.classes():
if cls is doc_cls.cls:
return doc_cls
for module in self.submodules():
doc_cls = module.find_class(cls)
if not isinstance(doc_cls, External):
return doc_cls
return External('%s.%s' % (cls.__module__, cls.__name__))
def find_ident(self, name):
"""
Searches this module and **all** of its sub-modules for an
identifier with name `name` in its list of exported
identifiers according to `pydoc`. Note that unexported
sub-modules are searched.
A bare identifier (without `.` separators) will only be checked
for in this module.
The documentation object corresponding to the identifier is
returned. If one cannot be found, then an instance of
`External` is returned populated with the given identifier.
"""
if name in self.refdoc:
return self.refdoc[name]
for module in self.submodules():
o = module.find_ident(name)
if not isinstance(o, External):
return o
return External(name)
def variables(self):
"""
Returns all documented module level variables in the module
sorted alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
def classes(self):
"""
Returns all documented module level classes in the module
sorted alphabetically as a list of `pydoc.Class`.
"""
p = lambda o: isinstance(o, Class) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
def functions(self):
"""
Returns all documented module level functions in the module
sorted alphabetically as a list of `pydoc.Function`.
"""
p = lambda o: isinstance(o, Function) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
def submodules(self):
"""
Returns all documented sub-modules in the module sorted
alphabetically as a list of `pydoc.Module`.
"""
p = lambda o: isinstance(o, Module) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
def is_submodule(self, name):
"""
Returns `True` if and only if `name` starts with the full
import path of `self` and has length at least one greater than
`len(self.name)`.
"""
return self.name != name and name.startswith(self.name)
def __is_exported(self, name, module):
"""
Returns `True` if and only if `pydoc` considers `name` to be
a public identifier for this module where `name` was defined
in the Python module `module`.
If this module has an `__all__` attribute, then `name` is
considered to be exported if and only if it is a member of
this module's `__all__` list.
If `__all__` is not set, then whether `name` is exported or
not is heuristically determined. Firstly, if `name` starts
with an underscore, it will not be considered exported.
Secondly, if `name` was defined in a module other than this
one, it will not be considered exported. In all other cases,
`name` will be considered exported.
"""
if hasattr(self.module, '__all__'):
return name in self.module.__all__
if not _is_exported(name):
return False
if module is None:
return False
if module is not None and self.module.__name__ != module.__name__:
return name in self._declared_variables
return True
def __public_objs(self):
"""
Returns a dictionary mapping a public identifier name to a
Python object.
"""
members = dict(inspect.getmembers(self.module))
return dict([(name, obj)
for name, obj in members.items()
if self.__is_exported(name, inspect.getmodule(obj))])
def __new_submodule(self, name, obj):
"""
Create a new submodule documentation object for this `obj`,
which must by a Python module object and pass along any
settings in this module.
"""
# Forcefully set the module name so that it is always the absolute
# import path. We can't rely on `obj.__name__`, since it doesn't
# necessarily correspond to the public exported name of the module.
obj.__dict__['__budoc_module_name'] = '%s.%s' % (self.refname, name)
return Module(obj,
docfilter=self._docfilter,
allsubmodules=self._allsubmodules)
class Class (Doc):
"""
Representation of a class's documentation.
"""
def __init__(self, name, module, class_obj):
"""
Same as `pydoc.Doc.__init__`, except `class_obj` must be a
Python class object. The docstring is gathered automatically.
"""
super(Class, self).__init__(name, module, inspect.getdoc(class_obj))
self.cls = class_obj
"""The class Python object."""
self.doc = {}
"""A mapping from identifier name to a `pydoc.Doc` objects."""
self.doc_init = {}
"""
A special version of `pydoc.Class.doc` that contains
documentation for instance variables found in the `__init__`
method.
"""
public = self.__public_objs()
try:
# First try and find docstrings for class variables.
# Then move on to finding docstrings for instance variables.
# This must be optional, since not all modules have source
# code available.
cls_ast = ast.parse(inspect.getsource(self.cls)).body[0]
self.doc = _var_docstrings(cls_ast, self.module, cls=self)
for n in (cls_ast.body if '__init__' in public else []):
if isinstance(n, ast.FunctionDef) and n.name == '__init__':
self.doc_init = _var_docstrings(n, self.module,
cls=self, init=True)
break
except:
pass
# Convert the public Python objects to documentation objects.
for name, obj in public.items():
# Skip any identifiers that already have doco.
if name in self.doc and not self.doc[name].is_empty():
continue
if name in self.doc_init:
# Let instance members override class members.
continue
if inspect.ismethod(obj):
self.doc[name] = Function(name, self.module, obj.__func__,
cls=self, method=True)
elif inspect.isfunction(obj):
self.doc[name] = Function(name, self.module, obj,
cls=self, method=False)
elif isinstance(obj, property):
docstring = getattr(obj, '__doc__', '')
self.doc_init[name] = Variable(name, self.module, docstring,
cls=self)
elif not inspect.isbuiltin(obj) \
and not inspect.isroutine(obj):
if name in getattr(self.cls, '__slots__', []):
self.doc_init[name] = Variable(name, self.module,
'', cls=self)
else:
self.doc[name] = Variable(name, self.module, '', cls=self)
@property
def source(self):
return _source(self.cls)
@property
def refname(self):
return '%s.%s' % (self.module.refname, self.cls.__name__)
def class_variables(self):
"""
Returns all documented class variables in the class, sorted
alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self.module._docfilter(o)
return filter(p, self.doc.values())
def instance_variables(self):
"""
Returns all instance variables in the class, sorted
alphabetically as a list of `pydoc.Variable`. Instance variables
are attributes of `self` defined in a class's `__init__`
method.
"""
p = | |
there's only one possible letter left, select it
keyboard.set_selected_key(self.possible_alphabet[0])
keyboard.render_keys()
elif input in [B.KEY_RIGHT, B.KEY_LEFT, B.KEY_UP, B.KEY_DOWN] and ret_val in self.possible_alphabet:
# Live joystick movement; haven't locked this new letter in yet.
# Replace the last letter w/the currently selected one. But don't
# call `calc_possible_alphabet()` because we want to still be able
# to freely float to a different letter; only update the active
# keyboard keys when a selection has been locked in (KEY_PRESS) or
# removed ("del").
self.letters = self.letters[:-1]
self.letters.append(ret_val)
self.calc_possible_words() # live update our matches as we move
# Update the right-hand possible matches area
render_possible_matches()
# Render the text entry display and cursor block
text_entry_display.render(f"{num_word}: " + "".join(self.letters))
View.DispShowImage()
def draw_passphrase_keyboard_entry(self, existing_passphrase = ""):
def render_right_panel(button1_text="ABC", button2_text="123"):
# Render the up/down arrow buttons for KEY1 and KEY3
row_height = 28
right_button_left_margin = 10
right_button_width = right_panel_buttons_width - right_button_left_margin
font_padding_right = 2
font_padding_top = 1
key_x = View.canvas_width - right_button_width
key_y = int(View.canvas_height - row_height) / 2 - 1 - 60
background_color = "#111"
font_color = View.color
font = View.ROBOTOCONDENSED_BOLD_24
tw, th = font.getsize(button1_text)
if button1_is_active:
background_color = View.color
font_color = "#111"
View.draw.rounded_rectangle((key_x, key_y, 250, key_y + row_height), outline=View.color, fill=background_color, radius=5, width=1)
View.draw.text((View.canvas_width - tw - font_padding_right, key_y + font_padding_top), font=font, text=button1_text, fill=font_color)
background_color = "#111"
font_color = View.color
tw, th = font.getsize(button2_text)
if button2_is_active:
background_color = View.color
font_color = "#111"
key_y = int(View.canvas_height - row_height) / 2 - 1
View.draw.rounded_rectangle((key_x, key_y, 250, key_y + row_height), outline=View.color, fill=background_color, radius=5, width=1)
View.draw.text((View.canvas_width - tw - font_padding_right, key_y + font_padding_top), font=font, text=button2_text, fill=font_color)
background_color = "#111"
font_color = View.color
button3_text = "Save"
tw, th = font.getsize(button3_text)
if button3_is_active:
background_color = View.color
font_color = "#111"
key_y = int(View.canvas_height - row_height) / 2 - 1 + 60
View.draw.rounded_rectangle((key_x, key_y, 250, key_y + row_height), outline=View.color, fill=background_color, radius=5, width=1)
View.draw.text((View.canvas_width - tw - font_padding_right, key_y + font_padding_top), font=font, text=button3_text, fill=font_color)
# Clear the screen
View.draw.rectangle((0,0, View.canvas_width,View.canvas_height), fill="black")
self.render_previous_button()
previous_button_is_active = False
# Have to ensure that we don't carry any effects from a previous run
# TODO: This shouldn't be a member var
if existing_passphrase:
self.passphrase = existing_passphrase
else:
self.passphrase = ""
# Set up the keyboard params
right_panel_buttons_width = 60
# render top title banner
font = View.ROBOTOCONDENSED_REGULAR_20
title = "Enter Passphrase"
title_top_padding = 0
title_bottom_padding = 10
tw, th = font.getsize(title)
View.draw.text((int(View.canvas_width - tw) / 2, title_top_padding), text=title, font=font, fill=View.color)
title_height = th + title_top_padding + title_bottom_padding
# Render the live text entry display
font = View.ROBOTOCONDENSED_REGULAR_28
tw, th = font.getsize("!\"#$%&'()*+,=./;:<>?@[]|-_`~ ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890") # All possible chars for max range
text_entry_side_padding = 0
text_entry_top_padding = 1
text_entry_bottom_padding = 10
text_entry_top_y = title_height + text_entry_top_padding
text_entry_bottom_y = text_entry_top_y + 3 + th + 3
text_entry_display = TextEntryDisplay(
View.draw,
rect=(text_entry_side_padding,text_entry_top_y, View.canvas_width - right_panel_buttons_width - 1, text_entry_bottom_y),
font=font,
font_color=View.color,
cursor_mode=TextEntryDisplay.CURSOR_MODE__BAR,
is_centered=False,
has_outline=True,
cur_text=''.join(self.passphrase)
)
text_entry_display.render()
cursor_position = len(self.passphrase)
keyboard_start_y = text_entry_bottom_y + text_entry_bottom_padding
keyboard_abc = Keyboard(
View.draw,
charset="".join(SeedToolsView.ALPHABET),
rows=4,
cols=9,
rect=(0, keyboard_start_y, View.canvas_width - right_panel_buttons_width, View.canvas_height),
additional_keys=[Keyboard.KEY_SPACE_5, Keyboard.KEY_CURSOR_LEFT, Keyboard.KEY_CURSOR_RIGHT, Keyboard.KEY_BACKSPACE],
auto_wrap=[Keyboard.WRAP_LEFT, Keyboard.WRAP_RIGHT]
)
keyboard_ABC = Keyboard(
View.draw,
charset="".join(SeedToolsView.ALPHABET).upper(),
rows=4,
cols=9,
rect=(0, keyboard_start_y, View.canvas_width - right_panel_buttons_width, View.canvas_height),
additional_keys=[Keyboard.KEY_SPACE_5, Keyboard.KEY_CURSOR_LEFT, Keyboard.KEY_CURSOR_RIGHT, Keyboard.KEY_BACKSPACE],
auto_wrap=[Keyboard.WRAP_LEFT, Keyboard.WRAP_RIGHT],
render_now=False
)
keyboard_digits = Keyboard(
View.draw,
charset="1234567890",
rows=3,
cols=5,
rect=(0, keyboard_start_y, View.canvas_width - right_panel_buttons_width, View.canvas_height),
additional_keys=[Keyboard.KEY_CURSOR_LEFT, Keyboard.KEY_CURSOR_RIGHT, Keyboard.KEY_BACKSPACE],
auto_wrap=[Keyboard.WRAP_LEFT, Keyboard.WRAP_RIGHT],
render_now=False
)
keyboard_symbols = Keyboard(
View.draw,
charset="!@#$%^&*()-+_=[]{}\\|;:'\",.<>/?`~",
rows=4,
cols=10,
rect=(0, keyboard_start_y, View.canvas_width - right_panel_buttons_width, View.canvas_height),
additional_keys=[Keyboard.KEY_SPACE_4, Keyboard.KEY_CURSOR_LEFT, Keyboard.KEY_CURSOR_RIGHT, Keyboard.KEY_BACKSPACE],
auto_wrap=[Keyboard.WRAP_LEFT, Keyboard.WRAP_RIGHT],
render_now=False
)
button1_is_active = False
button2_is_active = False
button3_is_active = False
KEYBOARD__LOWERCASE = 0
KEYBOARD__UPPERCASE = 1
KEYBOARD__DIGITS = 2
KEYBOARD__SYMBOLS = 3
KEYBOARD__LOWERCASE_BUTTON_TEXT = "abc"
KEYBOARD__UPPERCASE_BUTTON_TEXT = "ABC"
KEYBOARD__DIGITS_BUTTON_TEXT = "123"
KEYBOARD__SYMBOLS_BUTTON_TEXT = "!@#"
cur_keyboard = keyboard_abc
cur_button1_text = KEYBOARD__UPPERCASE_BUTTON_TEXT
cur_button2_text = KEYBOARD__DIGITS_BUTTON_TEXT
render_right_panel()
View.DispShowImage()
# Start the interactive update loop
while True:
input = View.buttons.wait_for(
[B.KEY_UP, B.KEY_DOWN, B.KEY_RIGHT, B.KEY_LEFT, B.KEY_PRESS, B.KEY1, B.KEY2, B.KEY3],
check_release=True,
release_keys=[B.KEY_PRESS, B.KEY1, B.KEY2, B.KEY3]
)
keyboard_swap = False
# Check our two possible exit conditions
if input == B.KEY3:
# Save!
if len(self.passphrase) > 0:
return self.passphrase.strip()
elif input == B.KEY_PRESS and previous_button_is_active:
# Prev button clicked; return empty string to signal cancel.
return ""
# Check for keyboard swaps
if input == B.KEY1:
# Return to the same button2 keyboard, if applicable
if cur_keyboard == keyboard_digits:
cur_button2_text = KEYBOARD__DIGITS_BUTTON_TEXT
elif cur_keyboard == keyboard_symbols:
cur_button2_text = KEYBOARD__SYMBOLS_BUTTON_TEXT
if cur_button1_text == KEYBOARD__LOWERCASE_BUTTON_TEXT:
keyboard_abc.set_selected_key_indices(x=cur_keyboard.selected_key["x"], y=cur_keyboard.selected_key["y"])
cur_keyboard = keyboard_abc
cur_button1_text = KEYBOARD__UPPERCASE_BUTTON_TEXT
render_right_panel(button1_text=cur_button1_text, button2_text=cur_button2_text)
else:
keyboard_ABC.set_selected_key_indices(x=cur_keyboard.selected_key["x"], y=cur_keyboard.selected_key["y"])
cur_keyboard = keyboard_ABC
cur_button1_text = KEYBOARD__LOWERCASE_BUTTON_TEXT
render_right_panel(button1_text=cur_button1_text, button2_text=cur_button2_text)
cur_keyboard.render_keys()
keyboard_swap = True
ret_val = None
elif input == B.KEY2:
# Return to the same button1 keyboard, if applicable
if cur_keyboard == keyboard_abc:
cur_button1_text = KEYBOARD__LOWERCASE_BUTTON_TEXT
elif cur_keyboard == keyboard_ABC:
cur_button1_text = KEYBOARD__UPPERCASE_BUTTON_TEXT
if cur_button2_text == KEYBOARD__DIGITS_BUTTON_TEXT:
keyboard_digits.set_selected_key_indices(x=cur_keyboard.selected_key["x"], y=cur_keyboard.selected_key["y"])
cur_keyboard = keyboard_digits
cur_keyboard.render_keys()
cur_button2_text = KEYBOARD__SYMBOLS_BUTTON_TEXT
render_right_panel(button1_text=cur_button1_text, button2_text=cur_button2_text)
else:
keyboard_symbols.set_selected_key_indices(x=cur_keyboard.selected_key["x"], y=cur_keyboard.selected_key["y"])
cur_keyboard = keyboard_symbols
cur_keyboard.render_keys()
cur_button2_text = KEYBOARD__DIGITS_BUTTON_TEXT
render_right_panel(button1_text=cur_button1_text, button2_text=cur_button2_text)
cur_keyboard.render_keys()
keyboard_swap = True
ret_val = None
else:
# Process normal input
if input in [B.KEY_UP, B.KEY_DOWN] and previous_button_is_active:
# We're navigating off the previous button
previous_button_is_active = False
self.render_previous_button(highlight=False)
# Override the actual input w/an ENTER signal for the Keyboard
if input == B.KEY_DOWN:
input = Keyboard.ENTER_TOP
else:
input = Keyboard.ENTER_BOTTOM
elif input in [B.KEY_LEFT, B.KEY_RIGHT] and previous_button_is_active:
# ignore
continue
ret_val = cur_keyboard.update_from_input(input)
# Now process the result from the keyboard
if ret_val in Keyboard.EXIT_DIRECTIONS:
self.render_previous_button(highlight=True)
previous_button_is_active = True
elif ret_val in Keyboard.ADDITIONAL_KEYS and input == B.KEY_PRESS:
if ret_val == Keyboard.KEY_BACKSPACE["code"]:
if cursor_position == 0:
pass
elif cursor_position == len(self.passphrase):
self.passphrase = self.passphrase[:-1]
else:
self.passphrase = self.passphrase[:cursor_position - 1] + self.passphrase[cursor_position:]
cursor_position -= 1
elif ret_val == Keyboard.KEY_CURSOR_LEFT["code"]:
cursor_position -= 1
if cursor_position < 0:
cursor_position = 0
elif ret_val == Keyboard.KEY_CURSOR_RIGHT["code"]:
cursor_position += 1
if cursor_position > len(self.passphrase):
cursor_position = len(self.passphrase)
elif ret_val == Keyboard.KEY_SPACE["code"]:
if cursor_position == len(self.passphrase):
self.passphrase += " "
else:
self.passphrase = self.passphrase[:cursor_position] + " " + self.passphrase[cursor_position:]
cursor_position += 1
# Update the text entry display and cursor
text_entry_display.render(self.passphrase, cursor_position)
elif input == B.KEY_PRESS and ret_val not in Keyboard.ADDITIONAL_KEYS:
# User has locked in the current letter
if cursor_position == len(self.passphrase):
self.passphrase += ret_val
else:
self.passphrase = self.passphrase[:cursor_position] + ret_val + self.passphrase[cursor_position:]
cursor_position += 1
# Update the text entry display and cursor
text_entry_display.render(self.passphrase, cursor_position)
elif input in [B.KEY_RIGHT, B.KEY_LEFT, B.KEY_UP, B.KEY_DOWN] or keyboard_swap:
# Live joystick movement; haven't locked this new letter in yet.
# Leave current spot blank for now. Only update the active keyboard keys
# when a selection has been locked in (KEY_PRESS) or removed ("del").
pass
View.DispShowImage()
###
### Display Last Word
###
def display_last_word(self, partial_seed_phrase) -> list:
finalseed = mnemonic_generation.calculate_checksum(partial_seed_phrase, wordlist=self.controller.settings.wordlist)
last_word = finalseed[-1]
self.draw.rectangle((0, 0, View.canvas_width, View.canvas_height), outline=0, fill=0)
tw, th = self.draw.textsize("The final word is :", font=View.ASSISTANT23)
self.draw.text(((240 - tw) / 2, 60), "The final word is :", fill=View.color, font=View.ASSISTANT23)
tw, th = self.draw.textsize(last_word, font=View.ASSISTANT50)
self.draw.text(((240 - tw) / 2, 90), last_word, fill=View.color, font=View.ASSISTANT50)
tw, th = View.draw.textsize("Right to Continue", font=View.ASSISTANT18)
View.draw.text(((240 - tw) / 2, 210), "Right to Continue", fill=View.color, font=View.ASSISTANT18)
View.DispShowImage()
input = self.buttons.wait_for([B.KEY_RIGHT])
return finalseed
###
### Display Seed from Dice
###
def display_generate_seed_from_dice(self):
self.roll_number = 1
self.dice_selected = 5
self.roll_data = ""
self.draw_dice(self.dice_selected)
time.sleep(1) # pause for 1 second before accepting input
# Wait for Button Input (specifically menu selection/press)
while True:
input = self.buttons.wait_for([B.KEY_UP, B.KEY_DOWN, B.KEY_PRESS, B.KEY_RIGHT, B.KEY_LEFT])
if input == B.KEY_UP:
ret_val = self.dice_arrow_up()
elif input == B.KEY_DOWN:
ret_val = self.dice_arrow_down()
elif input == B.KEY_RIGHT:
ret_val = self.dice_arrow_right()
elif input == B.KEY_LEFT:
ret_val = self.dice_arrow_left()
elif input == B.KEY_PRESS:
ret_val = self.dice_arrow_press()
if ret_val == False:
return []
if self.roll_number >= 100:
self.dice_seed_phrase = mnemonic_generation.generate_mnemonic_from_dice(self.roll_data)
return self.dice_seed_phrase[:]
def dice_arrow_up(self):
new_selection = 0
if self.dice_selected == 4:
new_selection = 1
elif self.dice_selected == 5:
new_selection = 2
elif self.dice_selected == 6:
new_selection = 3
if self.dice_selected != new_selection and new_selection != 0:
self.draw_dice(new_selection)
return True
def dice_arrow_down(self):
new_selection = 0
if self.dice_selected == 1:
new_selection = 4
elif | |
#walks chronologicly through the booking
#intervals of each resource, and reduces
#the effort for each free interval
#until it becomes 0
alloc_effort = effort
effort -= task.performed_effort
while effort > 0:
date = next_date
interval_resource = []
interval_end = to_start(sys.maxint)
factor = 0
for r in resource:
max_load = _calc_maxload(task, r)
book_load = _calc_load(task, r)
end, load = r.end_of_booking_interval(date, task)
interval_end = to_start(min(end, interval_end))
if book_load <= 0:
#variable book_load ==> calc the maxmimal possible book_load >= (the given book_load)
book_load = - book_load
diff_load = max_load - load
if diff_load and diff_load >= book_load:
book_load = diff_load
else:
book_load = max_load
if book_load + load <= max_load:
resource_factor = book_load * r.efficiency
interval_resource.append((r, book_load, resource_factor))
factor += resource_factor
next_date = interval_end
if factor:
factor *= task.efficiency
length = to_delta(effort / factor).round()
end = date + length
if interval_end >= end:
next_date = interval_end = end
effort = 0
book_end = end
else:
book_end = interval_end
length = book_end - date
minus_effort = length * factor
effort -= minus_effort
book_end = to_end(book_end)
intervals.append((date, book_end, length, interval_resource))
return next_date, alloc_effort, resource, intervals
#@-node:test_allocation_effort
#@+node:allocate
def allocate(self, task, state):
if task.__dict__.has_key("effort"): self.allocate_effort(task, state)
else: self.allocate_length(task, state)
#@-node:allocate
#@+node:allocate_length
def allocate_length(self, task, state):
# now really book the resource
neg_sum_effort, end, resource, intervals = state
cal = task.root.calendar
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
task.start = to_start(task.performed_start or task.start)
task.end = to_end(end)
task._unfreeze("length")
task._unfreeze("duration")
effort = 0
for r, load, s, e in intervals:
work_time = to_delta((e - s) * load).round()
effort += work_time
r.book_task(task, s, e, load, work_time, False)
#see comment at StrictAllocator.allocate
task.booked_resource = resource
task.done = task.done
task.todo = task.todo
task.effort = to_delta(effort + task.performed_effort).round()
#@-node:allocate_length
#@+node:allocate_effort
def allocate_effort(self, task, state):
# now really book the resource
end, effort, resource, intervals = state
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
task.start = task.performed_start \
and to_start(task.performed_start) \
or to_start(intervals[0][0])
task.end = to_end(end)
task._unfreeze("length")
task._unfreeze("duration")
for start, end, length, resources in intervals:
for r, load, factor in resources:
work_time = to_delta(length * load)
r.book_task(task, start, end, load, work_time, False)
task.booked_resource = resource
task.done = task.done
task.todo = task.todo
task.effort = to_delta(effort)
task.length = task.end - task.start
#@-node:allocate_effort
#@-others
#@-node:class SloppyAllocator
#@-others
_smart_allocator = SmartAllocator()
_sloppy_allocator = SloppyAllocator()
_strict_allocator = StrictAllocator()
_allocators = { SMART: _smart_allocator,
SLOPPY: _sloppy_allocator,
STRICT: _strict_allocator }
_allocator_strings = { SMART: "SMART",
SLOPPY: "SLOPPY",
STRICT: "STRICT" }
#@-node:Resource Allocators
#@+node:Load Calculators
#@+node:YearlyMax
def YearlyMax(value):
"""
Calculates a load parameter with a maximal yearly workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / \
(cal.working_days_per_year \
* cal.working_hours_per_day \
* 60)
#@nonl
#@-node:YearlyMax
#@+node:WeeklyMax
def WeeklyMax(value):
"""
Calculates a load parameter with a maximal weekly workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / \
(cal.working_days_per_week \
* cal.working_hours_per_day \
* 60)
#@-node:WeeklyMax
#@+node:MonthlyMax
def MonthlyMax(value):
"""
Calculates a load parameter with a maximal monthly workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / \
(cal.working_days_per_month \
* cal.working_hours_per_day \
* 60)
#@-node:MonthlyMax
#@+node:DailyMax
def DailyMax(value):
"""
Calculates a load parameter with a maximal daily workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / (cal.working_hours_per_day * 60)
#@-node:DailyMax
#@-node:Load Calculators
#@+node:Task
#@+node:class _TaskProperty
class _TaskProperty(object):
#@ @+others
#@+node:__init__
def __init__(self, method):
self.method = method
#@-node:__init__
#@+node:__get__
def __get__(self, instance, owner):
if not instance:
return None
return instance._wrap_attrib(self.method)
#@-node:__get__
#@-others
#@-node:class _TaskProperty
#@+node:class _RoundingTaskProperty
class _RoundingTaskProperty(object):
#@ @+others
#@+node:__init__
def __init__(self, method, name):
self.method = method
self.name = name
#@-node:__init__
#@+node:__get__
def __get__(self, instance, owner):
if not instance:
return None
result = instance._wrap_attrib(self.method).round()
if instance._is_frozen:
#correct the attrib to the rounded value
setattr(instance, self.name, result)
return result
#@-node:__get__
#@-others
#@-node:class _RoundingTaskProperty
#@+node:class Task
class Task(object):
#@ << description >>
#@+node:<< description >>
"""
This class represents a single task in the project tree. A task
can have other child tasks, or is a leaf of the tree. Resources
will be allocated only to leafes. You will never create task
objects by your self, they are created indirectly by Projects.
@var root:
Returns the root project task.
@var up:
Returns the parent task.
@var title:
Specifies an alternative more descriptive name for the task.
@var start:
The start date of the task. Valid values are expressions and
strings specifing a datatime
@var end:
The end date of the task. Valid values are expressions and
strings.
@var effort:
Specifies the effort needed to complete the task. Valid values
are expressions and strings. (Todo: What happens, in case of
specified performance data...)
@var length:
Specifies the time the task occupies the resources. This is
working time, not calendar time. 7d means 7 working days, not one
week. Whether a day is considered a working day or not depends on
the defined working hours and global vacations.
@var duration:
Specifies the time the task occupies the resources. This is
calendar time, not working time. 7d means one week.
@var buffer:
Specifies the time a task can be delayed, without moving dependend
milestones. A Task with a buffer S{<=} 0d is part of the critical
chain. This attribute is readonly.
@var complete:
Specifies what percentage of the task is already completed.
@var todo:
Specifies the effort, which needs to be done to complete a
task. This is another (indirect) way to specify the ME{complete}
attribute.
@var done:
Specifies the work effort, which has been already done. This
attribute is readonly.
@var estimated_effort:
Specifies the estimated_effort given by setting the effort property.
@var performed:
Specifies a list of actual working times performed on the task.
The format is: C{[ (resource, from, to, time), ... ]}
@var performed_work_time:
Specifies the sum of all working times. This attribute is
readonly.
@var performed_effort:
Specifies the complete effort of all working times. This attribute is
readonly.
@var performed_start:
The start date of the performed data.
@var performed_end:
The end date of the performed data.
@var performed_resource:
The resources who have already performed on the task. This attribute is readonly.
@var balance:
Specifies the resource allocation type. Possible values are
CO{STRICT}, CO{SLOPPY}, CO{SMART}.
@var resource:
Specifies the possible resources, that may be allocated for the
task.
@var booked_resource:
Specifies the allocated resources of a task. This attribute is
readonly.
@var load:
Specifies the daily load of a resource for an allocation of the
specified task. A load of 1.0 (default) means the resource is
allocated for as many hours as specified by
ME{working_hours_per_day}. A load of 0.5 means half that many
hours.
@var max_load:
Specify the maximal allowed load sum of all simultaneously
allocated tasks of a resource. A ME{max_load} of 1.0 (default)
means the resource may be fully allocated. A ME{max_load} of 1.3
means the resource may be allocated with 30% overtime.
@var efficiency:
The efficiency of a resource can be used for two purposes. First
you can use it as a crude way to model a team. A team of 5 people
should have an efficiency of 5.0. Keep in mind that you cannot
track the member of the team individually if you use this
feature. The other use is to model performance variations between
your resources.
@var milestone:
Specified if the task is a milestone. The possible values are
C{True} or "later". If the start date of the milestone is not
a valid working date, the milestone will appear at the | |
#!/usr/bin/env python
"""
Variant of pyscroll.data.TileMapData.
ScrollTest was copied and modified from pyscroll/apps/demo.py.
Source copied and modified from https://github.com/bitcraft/pyscroll
"""
from typing import List, Optional
import collections
import pygame
import pyscroll
from GameInfo import GameInfo
from Point import Point
class LegacyMapData(pyscroll.data.PyscrollDataAdapter):
BASE_MAP_LAYER = 0
DECORATION_LAYER = 1
CHARACTER_LAYER = 2
OVERLAY_MAP_LAYER = 3
def __init__(self,
game_info: GameInfo,
map_name: str,
image_pad_tiles: Point = Point(0, 0)):
super(LegacyMapData, self).__init__()
self.game_info = game_info
self.map_name = map_name
self.image_pad_tiles = Point(image_pad_tiles)
self.map_size_tiles = self.game_info.maps[self.map_name].size + 2 * self.image_pad_tiles
# Load up the images for the base map and overlay
self.base_map_images = self.get_map_images_from_game_info(self.game_info.maps[map_name].dat)
self.overlay_images = None
if self.game_info.maps[map_name].overlay_dat is not None:
self.overlay_images = self.get_map_images_from_game_info(self.game_info.maps[map_name].overlay_dat)
self.layers_to_render = self.all_tile_layers
self.layers_changed = False
def get_map_images_from_game_info(self, dat: List[str]) -> List[List[Optional[pygame.Surface]]]:
def pad_row(row_to_pad: str) -> str:
return row_to_pad[0] * self.image_pad_tiles.w + row_to_pad + row_to_pad[-1] * self.image_pad_tiles.w
# Pad dat to generate padded_dat
padded_dat: List[str] = []
# Top padding
padded_row = pad_row(dat[0])
for i in range(self.image_pad_tiles.h):
padded_dat.append(padded_row)
# Middle
for row in dat:
padded_dat.append(pad_row(row))
# Bottom padding
padded_row = pad_row(dat[-1])
for i in range(self.image_pad_tiles.h + 1):
padded_dat.append(padded_row)
# Generate map_images from padded_dat
map_images: List[List[Optional[pygame.Surface]]] = []
for y, row_data in enumerate(padded_dat):
map_images_row: List[Optional[pygame.Surface]] = []
for x, tile_symbol in enumerate(row_data):
if tile_symbol not in self.game_info.tile_symbols:
map_images_row.append(None)
continue
# Determine which image to use
image_idx = 0
# TODO: Fix hardcoded exception for the bridge tile_symbol of 'b'
if y > 0 and padded_dat[y-1][x] != tile_symbol and padded_dat[y-1][x] != 'b':
image_idx += 8
if y < len(padded_dat)-1 and padded_dat[y+1][x] != tile_symbol and padded_dat[y+1][x] != 'b':
image_idx += 2
if x > 0 and row_data[x-1] != tile_symbol and row_data[x-1] != 'b':
image_idx += 1
if x < len(row_data)-1 and row_data[x+1] != tile_symbol and row_data[x+1] != 'b':
image_idx += 4
map_images_row.append(self.game_info.random_tile_image(tile_symbol, image_idx))
map_images.append(map_images_row)
return map_images
def set_tile_layers_to_render(self, layers_to_render):
if self.layers_to_render != layers_to_render:
self.layers_to_render = layers_to_render
self.layers_changed = True
def have_layers_changed(self) -> bool:
ret_val = self.layers_changed
self.layers_changed = False
return ret_val
def decrement_layers_to_render(self):
self.layers_to_render = self.base_tile_layers
def increment_layers_to_render(self):
self.layers_to_render = self.all_tile_layers
@property
def all_tile_layers(self):
return self.base_tile_layers + self.overlay_tile_layers
@property
def base_tile_layers(self):
return [LegacyMapData.BASE_MAP_LAYER]
@property
def decoration_layer(self):
return LegacyMapData.DECORATION_LAYER
@property
def character_layer(self):
return LegacyMapData.CHARACTER_LAYER
@property
def overlay_tile_layers(self):
if self.overlay_images is not None:
return[LegacyMapData.OVERLAY_MAP_LAYER]
return []
def get_animations(self):
return None
def convert_surfaces(self, parent, alpha=False):
""" Convert all images in the data to match the parent
:param parent: pygame.Surface
:param alpha: preserve alpha channel or not
:return: None
"""
def convert_surfaces_helper(map_images: List[List[Optional[pygame.Surface]]],
parent: pygame.Surface,
alpha=False) -> List[List[Optional[pygame.Surface]]]:
converted_map_images: List[List[Optional[pygame.Surface]]] = []
for map_images_row in map_images:
converted_images_row: List[Optional[pygame.Surface]] = []
for image in map_images_row:
if image is None:
converted_images_row.append(None)
elif alpha:
converted_images_row.append(image.convert_alpha(parent))
else:
converted_images_row.append(image.convert(parent))
converted_map_images.append(converted_images_row)
return converted_map_images
self.base_map_images = convert_surfaces_helper(self.base_map_images, parent, alpha)
if self.overlay_images is not None:
self.overlay_images = convert_surfaces_helper(self.overlay_images, parent, alpha)
@property
def tile_size(self):
""" This is the pixel size of tiles to be rendered
:return: (int, int)
"""
return self.game_info.tile_size_pixels, self.game_info.tile_size_pixels
@property
def map_size(self):
""" This is the size of the map in tiles
:return: (int, int)
"""
# This size INCLUDES the padding
return self.map_size_tiles.w, self.map_size_tiles.h
@property
def visible_tile_layers(self):
return self.layers_to_render
@property
def visible_object_layers(self):
return []
def _get_tile_image(self, x, y, l, image_indexing=True, limit_to_visible=True):
if l not in self.all_tile_layers or (limit_to_visible and l not in self.layers_to_render):
return None
if not image_indexing:
# With image_indexing, coord (0,0) is where the pad starts.
# Without image_indexing, coord (0,0) is where the Tiled map starts.
x = x + self.image_pad_tiles[0]
y = y + self.image_pad_tiles[1]
if l == LegacyMapData.BASE_MAP_LAYER:
return self.base_map_images[y][x]
elif l == LegacyMapData.OVERLAY_MAP_LAYER:
return self.overlay_images[y][x]
return None
def _get_tile_image_by_id(self, id):
""" Return Image by a custom ID
Used for animations. Not required for static maps.
:param id:
:return:
"""
return None
def get_tile_images_by_rect(self, rect):
x1, y1, x2, y2 = pyscroll.rect_to_bb(rect)
x1 = min(max(x1, 0), self.map_size_tiles.w - 1)
x2 = min(max(x2, 0), self.map_size_tiles.w - 1)
y1 = min(max(y1, 0), self.map_size_tiles.h - 1)
y2 = min(max(y2, 0), self.map_size_tiles.h - 1)
for l in self.visible_tile_layers:
for y in range(y1, y2+1):
for x in range(x1, x2+1):
tile_image = self._get_tile_image(x, y, l)
if tile_image is not None:
yield x, y, l, tile_image
class ScrollTest:
SCROLL_SPEED = 5000
""" Test and demo of pyscroll
For normal use, please see the quest demo, not this.
"""
def __init__(self, screen: pygame.Surface, game_info: GameInfo, map_name: str):
self.screen = screen
# create new data source
map_data = LegacyMapData(game_info, map_name, (100, 100))
# create new renderer
self.map_layer = pyscroll.orthographic.BufferedRenderer(map_data, self.screen.get_size())
# create a font and pre-render some text to be displayed over the map
f = pygame.font.Font(pygame.font.get_default_font(), 20)
t = ["scroll demo. press escape to quit",
"arrow keys move"]
# save the rendered text
self.text_overlay = [f.render(i, 1, (180, 180, 0)) for i in t]
# set our initial viewpoint in the center of the map
self.center = [self.map_layer.map_rect.width / 2,
self.map_layer.map_rect.height / 2]
# the camera vector is used to handle camera movement
self.camera_acc = [0, 0, 0]
self.camera_vel = [0, 0, 0]
self.last_update_time = 0
# true when running
self.running = False
def draw(self, surface):
# tell the map_layer (BufferedRenderer) to draw to the surface
# the draw function requires a rect to draw to.
self.map_layer.draw(surface, surface.get_rect())
# blit our text over the map
self.draw_text(surface)
def draw_text(self, surface):
y = 0
for text in self.text_overlay:
surface.blit(text, (0, y))
y += text.get_height()
def handle_input(self):
""" Simply handle pygame input events
"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
break
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
break
elif event.key == pygame.K_EQUALS:
self.map_layer.zoom *= 2.0
elif event.key == pygame.K_MINUS:
self.map_layer.zoom *= 0.5
elif event.key == pygame.K_LEFTBRACKET:
self.map_layer.data.decrement_layers_to_render()
self.map_layer.redraw_tiles(self.map_layer._buffer)
elif event.key == pygame.K_RIGHTBRACKET:
self.map_layer.data.increment_layers_to_render()
self.map_layer.redraw_tiles(self.map_layer._buffer)
# this will be handled if the window is resized
elif event.type == pygame.VIDEORESIZE:
self.screen = pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)
self.map_layer.set_size((event.w, event.h))
# these keys will change the camera vector
# the camera vector changes the center of the viewport,
# which causes the map to scroll
# using get_pressed is slightly less accurate than testing for events
# but is much easier to use.
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
self.camera_acc[1] = -ScrollTest.SCROLL_SPEED * self.last_update_time
elif pressed[pygame.K_DOWN]:
self.camera_acc[1] = ScrollTest.SCROLL_SPEED * self.last_update_time
else:
self.camera_acc[1] = 0
if pressed[pygame.K_LEFT]:
self.camera_acc[0] = -ScrollTest.SCROLL_SPEED * self.last_update_time
elif pressed[pygame.K_RIGHT]:
self.camera_acc[0] = ScrollTest.SCROLL_SPEED * self.last_update_time
else:
self.camera_acc[0] = 0
def update(self, td):
self.last_update_time = td
friction = pow(.0001, self.last_update_time)
# update the camera vector
self.camera_vel[0] += self.camera_acc[0] * td
self.camera_vel[1] += self.camera_acc[1] * td
self.camera_vel[0] *= friction
self.camera_vel[1] *= friction
# make sure the movement vector stops when scrolling off the screen if
# the camera is clamped
if self.map_layer.clamp_camera:
if self.center[0] < 0:
self.center[0] -= self.camera_vel[0]
self.camera_acc[0] = 0
self.camera_vel[0] = 0
if self.center[0] >= self.map_layer.map_rect.width:
self.center[0] -= self.camera_vel[0]
self.camera_acc[0] = 0
self.camera_vel[0] = 0
if self.center[1] < 0:
self.center[1] -= self.camera_vel[1]
self.camera_acc[1] = 0
self.camera_vel[1] = 0
if self.center[1] >= self.map_layer.map_rect.height:
self.center[1] -= self.camera_vel[1]
self.camera_acc[1] = 0
self.camera_vel[1] = 0
self.center[0] += self.camera_vel[0]
self.center[1] += self.camera_vel[1]
# set the center somewhere else
# in a game, you would set center to a playable character
self.map_layer.center(self.center)
def run(self):
clock = pygame.time.Clock()
self.running = True
fps = 60.
fps_log = collections.deque(maxlen=20)
try:
while self.running:
# somewhat smoother way to get fps and limit the framerate
clock.tick(fps*2)
try:
fps_log.append(clock.get_fps())
fps = sum(fps_log)/len(fps_log)
dt = 1/fps
except ZeroDivisionError:
continue
self.handle_input()
self.update(dt)
self.draw(self.screen)
pygame.display.flip()
except KeyboardInterrupt:
self.running = False
from AudioPlayer import AudioPlayer
class MapViewer:
def __init__(self) -> None:
# Initialize pygame
pygame.init()
self.audio_player = AudioPlayer()
# Setup to draw maps
self.tile_size_pixels = 20
desired_win_size_pixels = Point(2560, 1340)
if desired_win_size_pixels is None:
self.screen = pygame.display.set_mode(
(0, 0),
pygame.FULLSCREEN | pygame.NOFRAME | pygame.SRCALPHA | pygame.DOUBLEBUF | pygame.HWSURFACE)
self.win_size_pixels = Point(self.screen.get_size())
self.win_size_tiles = (self.win_size_pixels / self.tile_size_pixels).floor()
else:
self.win_size_tiles = (desired_win_size_pixels / self.tile_size_pixels).floor()
self.win_size_pixels = self.win_size_tiles * self.tile_size_pixels
self.screen = pygame.display.set_mode(self.win_size_pixels.getAsIntTuple(),
pygame.SRCALPHA | pygame.DOUBLEBUF | pygame.HWSURFACE)
self.image_pad_tiles = self.win_size_tiles // 2 * 4
# Initialize GameInfo
import os
base_path = os.path.split(os.path.abspath(__file__))[0]
game_xml_path = os.path.join(base_path, 'game.xml')
self.game_info = GameInfo(base_path, game_xml_path, self.tile_size_pixels)
self.is_running = True
def | |
import argparse
import os
import sys
import random
import numpy as np
import scipy
import torch
import torch.optim as optim
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.utils.data
from params import Params
import pickle
import time as t
from model import ActorCriticNet, Shared_obs_stats, ActorCriticNetWithContact
import statistics
import matplotlib.pyplot as plt
from operator import add, sub
import pickle
import threading
import torch.multiprocessing as mp
import queue
from utils import TrafficLight
from utils import Counter
from radam import RAdam
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# try:
# mp.set_start_method('spawn')
# except RuntimeError:
# pass
import sys
sys.path.append('/home/zhaoming/Documents/dev/gym/gym/envs/mujoco')
class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.sample_index = 0
def push(self, events):
for event in zip(*events):
self.memory.append(event)
if len(self.memory)>self.capacity:
del self.memory[0]
def push_half(self, events):
temp_memory = []
for event in zip(*events):
temp_memory.append(event)
self.memory = self.memory + temp_memory[len(temp_memory)//4:3*len(temp_memory)//2]
while len(self.memory)>self.capacity:
del self.memory[0]
def push_half(self, events):
temp_memory = []
for event in zip(*events):
temp_memory.append(event)
self.memory = self.memory + temp_memory[2*len(temp_memory)//4:len(temp_memory)]
while len(self.memory)>self.capacity:
del self.memory[0]
def clear(self):
self.memory = []
self.sample_index = 0
def sample(self, batch_size):
#print(len(self.memory), batch_size)
samples = zip(*random.sample(self.memory, batch_size))
return map(lambda x: np.concatenate(x, 0), samples)
def clean_memory(self):
while len(self.memory) > self.capacity:
del self.memory[0]
def shuffle(self):
random.shuffle(self.memory)
def sample_one_at_a_time(self):
samples = zip(*self.memory[self.sample_index:self.sample_index+1])
self.sample_index += 1
return map(lambda x: np.concatenate(x, 0), samples)
def normal(x, mu, log_std):
a = (x - mu)/(log_std.exp())
a = -0.5 * a.pow(2)
a = torch.sum(a, dim=1)
b = torch.sum(log_std, dim=1)
#print(a-b)
return a-b
class RL(object):
def __init__(self, env, hidden_layer=[64, 64], contact=False):
self.env = env
#self.env.env.disableViewer = False
self.num_inputs = env.observation_space.shape[0]
self.num_outputs = env.action_space.shape[0]
self.hidden_layer = hidden_layer
self.num_contact = 2
self.params = Params()
if contact:
self.Net = ActorCriticNetWithContact
else:
self.Net = ActorCriticNet
self.model = self.Net(self.num_inputs, self.num_outputs, self.hidden_layer, num_contact=self.num_contact)
self.model.share_memory()
self.shared_obs_stats = Shared_obs_stats(self.num_inputs)
self.memory = ReplayMemory(10000000)
self.value_memory = ReplayMemory(10000000)
self.test_mean = []
self.test_std = []
self.noisy_test_mean = []
self.noisy_test_std = []
self.fig = plt.figure()
#self.fig2 = plt.figure()
self.lr = self.params.lr
plt.show(block=False)
self.test_list = []
self.noisy_test_list = []
self.queue = mp.Queue()
self.value_queue = mp.Queue()
self.mpdone = [mp.Event(), mp.Event(), mp.Event(), mp.Event()]
self.process = []
self.traffic_light = TrafficLight()
self.counter = Counter()
self.best_trajectory = ReplayMemory(5000)
self.best_score_queue = mp.Queue()
self.best_score = mp.Value("f", 0)
self.max_reward = mp.Value("f", 1)
self.expert_trajectory = ReplayMemory(1e7)
self.validation_trajectory = ReplayMemory(6000*9)
self.best_validation = 1.0
self.current_best_validation = 1.0
self.return_obs_stats = Shared_obs_stats(1)
self.gpu_model = self.Net(self.num_inputs, self.num_outputs,self.hidden_layer, num_contact=self.num_contact)
self.base_controller = None
def normalize_data(self, num_iter=1000, file='shared_obs_stats.pkl'):
state = self.env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
#model_old = ActorCriticNet(self.num_inputs, self.num_outputs,self.hidden_layer)
#model_old.load_state_dict(self.model.state_dict())
for i in range(num_iter):
print(i)
self.shared_obs_stats.observes(state)
state = self.shared_obs_stats.normalize(state)#.to(device)
#mu = self.model.sample_actions(state)
#action = mu#(mu + log_std.exp()*Variable(eps))
#env_action = action.cpu().data.squeeze().numpy()
env_action = np.random.randn(self.num_outputs)
state, reward, done, _ = self.env.step(env_action*0)
if done:
state = self.env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
with open(file, 'wb') as output:
pickle.dump(self.shared_obs_stats, output, pickle.HIGHEST_PROTOCOL)
def run_test(self, num_test=1):
state = self.env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
ave_test_reward = 0
total_rewards = []
for i in range(num_test):
total_reward = 0
while True:
state = self.shared_obs_stats.normalize(state)
mu = self.model.sample_best_actions(state)
action = mu.cpu().data.squeeze().numpy()
if self.base_controller is not None:
base_action = self.base_controller.sample_best_actions(state)
action += base_action.cpu().data.squeeze().numpy()
state, reward, done, _ = self.env.step(action)
total_reward += reward
#print(state)
#print("done", done, "state", state)
if done:
state = self.env.reset()
#print(self.env.position)
#print(self.env.time)
state = Variable(torch.Tensor(state).unsqueeze(0))
ave_test_reward += total_reward / num_test
total_rewards.append(total_reward)
break
state = Variable(torch.Tensor(state).unsqueeze(0))
#print("avg test reward is", ave_test_reward)
reward_mean = statistics.mean(total_rewards)
reward_std = statistics.stdev(total_rewards)
self.test_mean.append(reward_mean)
self.test_std.append(reward_std)
self.test_list.append((reward_mean, reward_std))
#print(self.model.state_dict())
def run_test_with_noise(self, num_test=10):
state = self.env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
ave_test_reward = 0
total_rewards = []
for i in range(num_test):
total_reward = 0
while True:
state = self.shared_obs_stats.normalize(state)
mu = self.model.sample_actions(state)
eps = torch.randn(mu.size())
action = (mu + 0.0*Variable(eps))
action = action.cpu().data.squeeze().numpy()
if self.base_controller is not None:
base_action = self.base_controller.sample_best_actions(state)
action += base_action.cpu().data.squeeze().numpy()
state, reward, done, _ = self.env.step(action)
total_reward += reward
if done:
state = self.env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
ave_test_reward += total_reward / num_test
total_rewards.append(total_reward)
break
state = Variable(torch.Tensor(state).unsqueeze(0))
#print("avg test reward is", ave_test_reward)
reward_mean = statistics.mean(total_rewards)
reward_std = statistics.stdev(total_rewards)
self.noisy_test_mean.append(reward_mean)
self.noisy_test_std.append(reward_std)
self.noisy_test_list.append((reward_mean, reward_std))
def plot_statistics(self):
ax = self.fig.add_subplot(121)
ax2 = self.fig.add_subplot(122)
low = []
high = []
index = []
noisy_low = []
noisy_high = []
for i in range(len(self.test_mean)):
low.append(self.test_mean[i] - self.test_std[i])
high.append(self.test_mean[i] + self.test_std[i])
noisy_low.append(self.noisy_test_mean[i]-self.noisy_test_std[i])
noisy_high.append(self.noisy_test_mean[i]+self.noisy_test_std[i])
index.append(i)
plt.xlabel('iterations')
plt.ylabel('average rewards')
ax.plot(self.test_mean, 'b')
ax2.plot(self.noisy_test_mean, 'g')
ax.fill_between(index, low, high, color='cyan')
ax2.fill_between(index, noisy_low, noisy_high, color='r')
#ax.plot(map(sub, test_mean, test_std))
self.fig.canvas.draw()
def collect_samples(self, num_samples, start_state=None, noise=-2.0, env_index=0, random_seed=1):
random.seed(random_seed)
torch.manual_seed(random_seed+1)
np.random.seed(random_seed+2)
env.seed(random_seed + 3)
#env.seed(random_seed+3)
#print(noise)
if start_state == None:
start_state = self.env.reset()
samples = 0
done = False
states = []
next_states = []
actions = []
rewards = []
values = []
q_values = []
real_rewards = []
log_probs = []
noise = self.base_noise * self.explore_noise.value
self.model.set_noise(noise)
state = start_state
state = Variable(torch.Tensor(state).unsqueeze(0))
total_reward = 0
#q_value = Variable(torch.zeros(1, 1))
while True:
noise = self.base_noise * self.explore_noise.value
self.model.set_noise(noise)
#print("local", self.model.p_fcs[1].bias.data[0])
#self.model.load_state_dict(torch.load(self.model_name))
signal_init = self.traffic_light.get()
score = 0
while samples < num_samples and not done:
#self.shared_obs_stats.observes(state)
states.append(state.cpu().data.numpy())
#self.shared_obs_stats.observes(state)
#print("samples", samples)
state = self.shared_obs_stats.normalize(state)
action = self.model.sample_actions(state)
log_prob = self.model.calculate_prob(state, action)
actions.append(action.cpu().data.numpy())
log_probs.append(log_prob.data.numpy())
env_action = action.data.squeeze().numpy()
if self.base_controller is not None:
base_action = self.base_controller.sample_best_actions(state)
env_action += base_action.cpu().data.squeeze().numpy()
state, reward, done, _ = self.env.step(env_action)
score += reward
if reward > self.max_reward.value:
self.max_reward.value = reward
if self.max_reward.value > 50:
self.max_reward.value = 50
#print(self.max_reward.value)
#reward *= 0.3
rewards.append(Variable(reward * torch.ones(1)).data.numpy())
real_rewards.append(Variable(reward * torch.ones(1)).data.numpy())
state = Variable(torch.Tensor(state).unsqueeze(0))
next_states.append(state.cpu().data.numpy())
next_state = self.shared_obs_stats.normalize(state)
samples += 1
state = self.shared_obs_stats.normalize(state)
v = (self.model.get_value(state))*self.max_reward.value# / self.return_obs_stats.std) + self.return_obs_stats.mean
if self.base_controller is not None:
v += self.base_controller.get_value(state)*self.max_reward.value
if done:
R = torch.zeros(1, 1)
else:
R = v.data
R = Variable(R)
for i in reversed(range(len(real_rewards))):
reward = Variable(torch.from_numpy(real_rewards[i]).unsqueeze(0))
R = self.params.gamma * R + reward#self.return_obs_stats.normalize(reward)# Variable(torch.from_numpy(real_rewards[i]))
q_values.insert(0, R.cpu().data.numpy())
#self.return_obs_stats.observes(R)
#mirror
# mirror_states = np.array(states)
# mirror_actions = np.array(actions)
# (
# negation_obs_indices,
# right_obs_indices,
# left_obs_indices,
# negation_action_indices,
# right_action_indices,
# left_action_indices,
# ) = self.env.get_mirror_indices()
# mirror_states[:, :, negation_obs_indices] *= -1
# rl = np.concatenate((right_obs_indices, left_obs_indices))
# lr = np.concatenate((left_obs_indices, right_obs_indices))
# mirror_states[:, :, rl] = mirror_states[:, :,lr]
# #mirror_actions = self.model.sample_best_actions(batch_states)
# mirror_actions[:, :, negation_action_indices] = mirror_actions[:, :, negation_action_indices] * -1
# rl = np.concatenate((right_action_indices, left_action_indices))
# lr = np.concatenate((left_action_indices, right_action_indices))
# mirror_actions[:, :, rl] = mirror_actions[:, :, lr]
# mirror_states = list(mirror_states)
# mirror_actions = list(mirror_actions)
# #self.queue.put([mirror_states, mirror_actions, np.copy(next_states), np.copy(rewards), np.copy(q_values), np.copy(log_probs)])
# value_states = states + mirror_states
# value_actions = actions + mirror_actions
# value_next_states = next_states + next_states
# value_rewards = rewards + rewards
# value_q_values = q_values + q_values
# value_log_probs = log_probs + log_probs
self.queue.put([states, actions, next_states, rewards, q_values, log_probs])
#self.value_queue.put([value_states, value_actions, value_next_states, value_rewards, value_q_values, value_log_probs])
self.counter.increment()
self.env.reset()
while self.traffic_light.get() == signal_init:
pass
start_state = self.env.reset()
state = start_state
state = Variable(torch.Tensor(state).unsqueeze(0))
total_reward = 0
samples = 0
done = False
states = []
next_states = []
actions = []
rewards = []
values = []
q_values = []
real_rewards = []
log_probs = []
#print("child", self.model.noise)
#if self.model.noise[0] > -2:
# self.model.noise *= 1.001
def collect_expert_samples(self, num_samples, filename, noise=-2.0,validation=False, difficulty=[0, 0]):
import gym
expert_env = gym.make("mocca_envs:Walker3DStepperEnv-v0")
expert_env.set_difficulty(difficulty)
start_state = expert_env.reset()
samples = 0
done = False
states = []
next_states = []
actions = []
rewards = []
q_values = []
model_expert = self.Net(self.num_inputs, self.num_outputs,self.hidden_layer)
model_expert.load_state_dict(torch.load(filename))
policy_noise = noise * np.ones(self.num_outputs)
model_expert.set_noise(policy_noise)
state = start_state
state = Variable(torch.Tensor(state).unsqueeze(0))
total_reward = 0
total_sample = 0
#q_value = Variable(torch.zeros(1, 1))
if validation:
max_sample = 300
else:
max_sample = 50000
while total_sample < max_sample:
score = 0
while samples < num_samples and not done:
state = self.shared_obs_stats.normalize(state)
states.append(state.data.numpy())
mu = model_expert.sample_best_actions(state)
actions.append(mu.data.numpy())
eps = torch.randn(mu.size())
if validation:
weight = 0.1
else:
weight = 0.1
env_action = model_expert.sample_actions(state)
env_action = env_action.data.squeeze().numpy()
state, reward, done, _ = expert_env.step(env_action)
reward = 1
rewards.append(Variable(reward * torch.ones(1)).data.numpy())
state = Variable(torch.Tensor(state).unsqueeze(0))
next_state = self.shared_obs_stats.normalize(state)
next_states.append(next_state.data.numpy())
samples += 1
#total_sample += 1
score += reward
print("expert score", score)
state = self.shared_obs_stats.normalize(state)
#print(state)
v = model_expert.get_value(state)
if done:
R = torch.zeros(1, 1)
else:
R = v.data
R = torch.ones(1, 1) * 100
R = Variable(R)
for i in reversed(range(len(rewards))):
R = self.params.gamma * R + Variable(torch.from_numpy(rewards[i]))
q_values.insert(0, R.data.numpy())
if not validation and score >= num_samples:
self.expert_trajectory.push([states, actions, | |
+ " : " + str(e.args) + " : " + str(e)
else: ERROR_MESSAGE += "Error: You do not have permission to access this form type from a different project. Your action has been logged and sent to the admin"
else: ERROR_MESSAGE += "Error: You do not have permission to access this tool. Your action has been logged and sent to the admin"
#If anything goes wrong in the process, return an error in the json HTTP Response
SECURITY_log_security_issues(request.user, 'admin.py - ' + str(sys._getframe().f_code.co_name), ERROR_MESSAGE, request.META)
return HttpResponse('{"ERROR":"'+ ERROR_MESSAGE +'","row_index":"0","is_complete":"False", "row_total":"0", "row_timer":"0"}',content_type="application/json")
#=======================================================#
# ACCESS LEVEL : 2 BULK_EDIT_FORMTYPE()
#=======================================================#
def bulk_edit_formtype(self, request):
#***************#
ACCESS_LEVEL = 2
#***************#
#----------------------------------------------------------------------------------------------------------------------------
# This Endpoint works in the formtype viewer--it recieves a list of edits based on the form query and processes those edits
# --in bulk. E.g. you can edit the rtype of multiple forms, compared to one at a time in an individual form editor
ERROR_MESSAGE = ""
#Check our user's session and access level
if SECURITY_check_user_permissions(ACCESS_LEVEL, request.user.permissions.access_level):
try:
print >> sys.stderr, request.POST
#This will receive post data containing a series of FRAV or FRRVs that need to be edited
#Just an extra bit of security to ensure this only processes POST data
if request.method == 'POST':
counter = 0;
print >> sys.stderr, request.POST
for key in request.POST:
print >>sys.stderr, key
splitkey = key.split('__')
if len(splitkey) > 1:
if splitkey[0] == 'frav':
currentFRAV = FormRecordAttributeValue.objects.get(pk=splitkey[1])
currentFRAV.record_value = request.POST[key]
#Add the user information
currentFRAV.modified_by = request.user
currentFRAV.save()
else:
#Sometimes, if
currentFRRV = FormRecordReferenceValue.objects.get(pk=key.splitkey[1])
#set our external key to this key value
new_external_key = ""
#Empty our list of references, and then add them all new here
currentFRAV.record_reference.clear()
for reference in post_data.getlist(key):
#make sure we add a null check here--the user might not have chosen a referenced form
if reference != '' or reference != None:
currentFRAV.record_reference.add(Form.objects.get(pk=reference))
new_external_key += str(reference) + ","
#remove the trailing comma
external_key_reference[:-1]
counter += 1
return HttpResponse('{"message":"Succesfully updated:'+ str(counter) +' field(s) in the database"}', content_type="application/json")
except Exception as e:
ERROR_MESSAGE += '"Something happened and the fields did not update in the database. See Error| '+str(e)+'"'
else: ERROR_MESSAGE += "Error: You do not have permission to access modifying user information"
#If anything goes wrong in the process, return an error in the json HTTP Response
SECURITY_log_security_issues(request.user, 'admin.py - ' + str(sys._getframe().f_code.co_name), ERROR_MESSAGE, request.META)
return HttpResponse('{"ERROR":"'+ ERROR_MESSAGE +'"}',content_type="application/json")
#=======================================================#
# ACCESS LEVEL : 5 MODIFY_PROJECT_USER()
#=======================================================#
def modify_project_user(self, request):
#***************#
ACCESS_LEVEL = 5
#***************#
#------------------------------------------------------------------------------------------------------------------------------------
# :::This function is an admin API Endpoint that accepts json data in POST (and ONLY post) and returns a string of JSON through AJAX
#
# !!!!!! It is ESSENTIAL that we create tight security here.!!!!!!!
# -----------------------------------------------------------------
# This view HAS to make sure that ONLY users with proper
# --access rights can manipulate user accounts. Because User accounts and their OneToOne Permission Model
# --control access, only project 'Admins' or (level 5) can actually edit users and create new ones.
#
# Because Django requires high-level permissions on all of its users to access admin functions, I had to implement
# --another layer of control. This should work perfectly find and secure. Essentially, ANY user outside a 'Master Admin'
# --can ONLY edit members of their own project. This view handles that by automatically forcing this new user to be part
# --of the project of the current user's session.
#
# Additionally, If the user doesn't ahve the correct access level of 5 to do this action, nothing will happen and it will
# --return an error explaining what occured. This SHOULDN'T happen--because the javascript allowing this is only installed
# --on the client IF they already have the permission level--HOWEVER--if this jscript is downloaded off the GIT or some other
# --source and inserted into the page(which should only happen if they already HAVE access to some project on this database)--this
# --ensuress that no attack is possible.
#
# Finally, SQL injection should be a Null issue here--I do not allow any raw() SQL to be used in any form to date--so any insertions
# --should be automatically cleaned by Django's built-in ORM functions
#-------------------------------------------------------------------------------------------------------------------------------------
# POST json will contain a list of 'users' that contain several keys
# JSON KEYS : "is_new_user" , "username" , "password" , "access_level", "name" , "title", "email"
ERROR_MESSAGE = ""
#Check our user's session and access level
if SECURITY_check_user_permissions(ACCESS_LEVEL, request.user.permissions.access_level):
#Make sure we only take POST requests
if request.method == 'POST':
#Make sure we have the right key in the POST data
if 'user_change_list' in request.POST:
#Let's grab our json Data and convert it to a python Dictionary
userJSON = json.loads(request.POST['user_change_list'])
print >>sys.stderr, userJSON
PROGRESS_MESSAGE = ""
DELETE_KEYS = ""
#Now loop through each 'user' in the dictionary and continue making edits/or create them
for aUser in userJSON['userlist']:
#We also now need to make sure that there are the bare mininum of keys needed(username, pass, access_level, and edit/create
if 'is_new_user' in aUser and 'username' in aUser and 'password' in aUser and 'access_level' in aUser:
#NOW *sigh of exhaustion* let's make sure that the user/pass/access_level isn't blank
# --We have to do this, because if someone hacks the jscript--they can force submit a blank input.
# --This shouldn't have deleterious side-effects--but we're not playing around anyway!
if aUser['is_new_user'] != "" and aUser['username'] != "" and aUser['password'] != "" and aUser['access_level'] != "":
#OKAY! We are all set to create/edit a user
#----CREATING A NEW USER -------------------------------------------------------------
if aUser['is_new_user'] == "T":
#We need to make sure there isn't already a username in the database with the submitted name
if User.objects.all().filter(username=aUser['username']).exists() != True:
newUser = User.objects.create_user(username=aUser['username'],password=aUser['password'])
#ADD ALL STATIC INFORMATION
newUser.is_staff = True
newUser.is_active = True
#newUser.save()
#ADD USER SUBMITTED INFORMATION
#--SECURITY NEEDS: Make sure to ONLY use the project from the user's own Session data that's already been authorized
#--Also make sure the access level is set, and MAKE sure the access_level is an Integer and not a string
isInt = True
try:
newUser.permissions.access_level = int(aUser['access_level'])
except Exception as inst:
isInt = False
if isInt:
newUser.permissions.project = request.user.permissions.project
newUser.permissions.title = aUser['title']
newUser.email = aUser['email']
#figure out names--if there's more than one space first in list is first name--rest is last name
splitName = aUser['name'].split(' ')
newUser.first_name = splitName[0]
lastName = ""
if len(splitName) > 1:
#start at index 1--we don't need the first name
for i in range(1, len(splitName)):
lastName += splitName[i]
newUser.last_name = lastName
#If all goes well, save the new User to the database
newUser.save()
PROGRESS_MESSAGE += " Made a new user: " + newUser.username + " --- "
else:
#Delete the user and add an error message
newUser.delete()
ERROR_MESSAGE += " Uh Oh! Something happened with: the access level submitted when creating a new user!" + str(inst) +" --You probably tried submitting a non-int for an integer access level?"
else:
ERROR_MESSAGE += "That username already exists!"
#----EDITING AN EXISTING USER -------------------------------------------------------------
elif aUser['is_new_user'] == "F":
#--SECURITY NEEDS: We have to be mindful here of how access is given to PK lookups, e.g. a user
# --might have injected a different user PK than is part of this project. We'll filter by the
# --user's own Project PK to ensure ONLY User PKs attached this project can be modified
# --This also ensures no SQL injection can be performed
userToEdit = Permissions.objects.all().filter(user__pk=aUser['user_id'], project__pk = request.user.permissions.project.pk)[0].user
#We can only modify a small subset of the user's fields
isInt = True
try:
userToEdit.permissions.access_level = int(aUser['access_level'])
except:
isInt = False
if isInt:
#First try and edit the user's name--if it's the same as the current name than skip, and if | |
<reponame>The-Ludwig/dnn_reco
from __future__ import division, print_function
import numpy as np
import tensorflow as tf
# Check and allow for newer TFScripts versions
try:
from tfscripts.compat.v1 import layers as tfs
except ImportError:
from tfscripts import layers as tfs
from dnn_reco.modules.models.utils.model_utils import preprocess_icecube_data
"""
All defined models must have the following signature:
Parameters
----------
is_training : bool
True if model is in training mode, false if in inference mode.
config : dict
Dictionary containing all settings as read in from config file.
data_handler : :obj: of class DataHandler
An instance of the DataHandler class. The object is used to obtain
meta data.
data_transformer : :obj: of class DataTransformer
An instance of the DataTransformer class. The object is used to
transform data.
shared_objects : dict
A dictionary containg settings and objects that are shared and passed
on to sub modules.
*args
Variable length argument list.
**kwargs
Arbitrary keyword arguments.
Returns
-------
tf.Tensor
The label prediction tensor y_pred.
tf.Tensor
The uncertainty estimate for each label.
list of tf.Tensor
The trainable parameters of the prediction network.
list of tf.Tensor
The trainable parameters of the uncertainty sub network.
Can optionally be an empty list.
"""
def general_model_IC86(is_training, config, data_handler,
data_transformer, shared_objects, *args, **kwargs):
"""A general NN model for the IceCube IC86 configuration.
Very similar to general_model_IC86_opt4, but uncertainty fc layers get
network prediction as input as well.
Parameters
----------
is_training : bool
True if model is in training mode, false if in inference mode.
config : dict
Dictionary containing all settings as read in from config file.
data_handler : :obj: of class DataHandler
An instance of the DataHandler class. The object is used to obtain
meta data.
data_transformer : :obj: of class DataTransformer
An instance of the DataTransformer class. The object is used to
transform data.
shared_objects : dict
A dictionary containg settings and objects that are shared and passed
on to sub modules.
*args
Variable length argument list.
**kwargs
Arbitrary keyword arguments.
Returns
-------
tf.Tensor
The label prediction tensor y_pred.
tf.Tensor
The uncertainty estimate for each label.
list of tf.Tensor
The trainable parameters of the prediction network.
list of tf.Tensor
The trainable parameters of the uncertainty sub network.
"""
keep_prob_list = shared_objects['keep_prob_list']
num_labels = data_handler.label_shape[-1]
with tf.compat.v1.variable_scope('model_pred'):
# apply DOM dropout, split and reshape DeepCore input
X_IC78, X_DeepCore_upper, X_DeepCore_lower = preprocess_icecube_data(
is_training, shared_objects)
# -----------------------------------
# convolutional layers over DeepCore_1 : upper part
# -----------------------------------
conv2d_1_layers, kernels, biases = tfs.new_conv_nd_layers(
X_DeepCore_upper,
is_training=is_training,
name='Upper DeepCore',
method_list='convolution',
keep_prob=keep_prob_list[1],
**config['conv_upper_DeepCore_settings']
)
# -----------------------------------
# convolutional layers over DeepCore_2 : lower part
# -----------------------------------
conv2d_2_layers, kernels, biases = tfs.new_conv_nd_layers(
X_DeepCore_lower,
is_training=is_training,
name='Lower DeepCore',
method_list='convolution',
keep_prob=keep_prob_list[1],
**config['conv_lower_DeepCore_settings']
)
# -----------------------------------
# convolutional hex3d layers over X_IC78 data
# -----------------------------------
conv_hex3d_layers, kernels, biases = tfs.new_conv_nd_layers(
X_IC78,
name='IC78',
is_training=is_training,
method_list='hex_convolution',
keep_prob=keep_prob_list[1],
**config['conv_IC78_settings']
)
# -----------------------------------
# combine results of convolution and flatten
# -----------------------------------
# flatten layer
layer_flat_IC78, num_features_IC78 = tfs.flatten_layer(
conv_hex3d_layers[-1])
layer_flat_DeepCore_1, num_features_DeepCore_1 = tfs.flatten_layer(
conv2d_1_layers[-1])
layer_flat_DeepCore_2, num_features_DeepCore_2 = tfs.flatten_layer(
conv2d_2_layers[-1])
# combine layers
num_features = (num_features_DeepCore_1 + num_features_DeepCore_2
+ num_features_IC78)
layer_flat = tf.concat([layer_flat_IC78, layer_flat_DeepCore_1,
layer_flat_DeepCore_2], axis=1)
# dropout
layer_flat = tf.nn.dropout(layer_flat, rate=1 - (keep_prob_list[2]))
# -----------------------------------
# fully connected layers
# -----------------------------------
fc_settings = dict(config['fc_settings'])
fc_settings['fc_sizes'][-1] = num_labels
layers, weights, biases = tfs.new_fc_layers(
input=layer_flat,
keep_prob=keep_prob_list[3],
is_training=is_training,
**fc_settings)
y_pred_trafo_orig = layers[-1]
# -----------------------------------
# Enforce Normalisation
# -----------------------------------
assert len(y_pred_trafo_orig.get_shape().as_list()) == 2
# transform back
y_pred = data_transformer.inverse_transform(y_pred_trafo_orig,
data_type='label')
y_pred_list = tf.unstack(y_pred, axis=1)
if 'model_enforce_direction_norm' not in config:
# backward compatibility
enforce_direction_norm = True
else:
enforce_direction_norm = config['model_enforce_direction_norm']
if enforce_direction_norm:
index_dir_x = \
data_handler.get_label_index(config['label_dir_x_key'])
index_dir_y = \
data_handler.get_label_index(config['label_dir_y_key'])
index_dir_z = \
data_handler.get_label_index(config['label_dir_z_key'])
index_zenith = \
data_handler.get_label_index(config['label_zenith_key'])
index_azimuth = \
data_handler.get_label_index(config['label_azimuth_key'])
trafo_indices = [index_dir_x, index_dir_y, index_dir_z,
index_azimuth, index_zenith]
norm = tf.sqrt(y_pred_list[index_dir_x]**2 +
y_pred_list[index_dir_y]**2 +
y_pred_list[index_dir_z]**2)
y_pred_list[index_dir_x] /= norm
y_pred_list[index_dir_y] /= norm
y_pred_list[index_dir_z] /= norm
# calculate zenith
y_pred_list[index_zenith] = tf.acos(tf.clip_by_value(
-y_pred_list[index_dir_z],
-1, 1))
# calculate azimuth
y_pred_list[index_azimuth] = (tf.atan2(-y_pred_list[index_dir_y],
-y_pred_list[index_dir_x])
+ 2 * np.pi) % (2 * np.pi)
else:
trafo_indices = []
# limit PID variables to range 0 to 1
# safety check
for k in data_handler.label_names:
if k[0:2] == 'p_' and k not in config['label_pid_keys']:
raise ValueError('Did you forget about {!r}?'.format(k))
logit_tensors = {}
for pid_key in config['label_pid_keys']:
if pid_key in data_handler.label_names:
index_pid = data_handler.get_label_index(pid_key)
trafo_indices.append(index_pid)
logit_tensors[pid_key] = y_pred_list[index_pid]
y_pred_list[index_pid] = tf.sigmoid(y_pred_list[index_pid])
# save logit tensors. These will be needed if we want to use
# cross entropy as a loss function. Tensorflow's cross entropy
# functions use logits as input as opposed to sigmoid(logits) due
# to numerical stability.
shared_objects['logit_tensors'] = logit_tensors
# put it back together
y_pred = tf.stack(y_pred_list, axis=1)
# transform
y_pred_trafo = data_transformer.transform(y_pred, data_type='label')
# Only do inv_trafo(trafo(y)) if necessary (numerical problems ...)
y_pred_trafo_orig_list = tf.unstack(y_pred_trafo_orig, axis=1)
y_pred_trafo_list = tf.unstack(y_pred_trafo, axis=1)
y_pred_trafo_final_list = []
for i in range(len(y_pred_trafo_orig_list)):
if i in trafo_indices:
y_pred_trafo_final_list.append(y_pred_trafo_list[i])
else:
y_pred_trafo_final_list.append(y_pred_trafo_orig_list[i])
# # zero out labels with weights == 0 if they are nan
# for i, non_zero in enumerate(shared_objects['non_zero_mask']):
# if not non_zero:
# y_pred_trafo_final_list[i] = tf.where(
# tf.is_finite(y_pred_trafo_final_list[i]),
# y_pred_trafo_final_list[i],
# tf.zeros_like(y_pred_trafo_final_list[i]))
# put it back together
y_pred_trafo = tf.stack(y_pred_trafo_final_list, axis=1)
with tf.compat.v1.variable_scope('model_unc'):
# -----------------------------------
# Uncertainty estimate
# -----------------------------------
fc_unc_settings = dict(config['fc_unc_settings'])
fc_unc_settings['fc_sizes'][-1] = num_labels
unc_input = tf.stop_gradient(tf.concat((y_pred_trafo, layer_flat),
axis=-1))
uncertainty_layers, weights, biases = tfs.new_fc_layers(
input=unc_input,
is_training=is_training,
keep_prob=keep_prob_list[3],
**fc_unc_settings
)
y_unc_pred_trafo = uncertainty_layers[-1]
y_unc_pred_trafo = tf.abs(y_unc_pred_trafo) + 1e-3
# -----------------------------------
# print architecture
# -----------------------------------
print('flat IC78:', layer_flat_IC78)
print('layer_flat:', layer_flat)
print('unc_input:', unc_input)
print('y_pred_trafo:', y_pred_trafo)
print('y_unc_pred_trafo:', y_unc_pred_trafo)
# -----------------------------------
# collect model variables that need to be saved
# -----------------------------------
model_vars_pred = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES,
'model_pred')
model_vars_unc = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES,
'model_unc')
return y_pred_trafo, y_unc_pred_trafo, model_vars_pred, model_vars_unc
def general_model_IC86_opt4(is_training, config, data_handler,
data_transformer, shared_objects, *args, **kwargs):
"""A general NN model for the IceCube IC86 configuration.
Parameters
----------
is_training : bool
True if model is in training mode, false if in inference mode.
config : dict
Dictionary containing all settings as read in from config file.
data_handler : :obj: of class DataHandler
An instance of the DataHandler class. The object is used to obtain
meta data.
data_transformer : :obj: of class DataTransformer
An instance of the DataTransformer class. The object is used to
transform data.
shared_objects : dict
A dictionary containg settings and objects that are shared and passed
on to sub modules.
*args
Variable length argument list.
**kwargs
Arbitrary keyword arguments.
Returns
-------
tf.Tensor
The label prediction tensor y_pred.
tf.Tensor
The uncertainty estimate for each label.
list of tf.Tensor
The trainable parameters of the prediction network.
list of tf.Tensor
The trainable parameters of the uncertainty sub network.
"""
keep_prob_list = shared_objects['keep_prob_list']
num_labels = data_handler.label_shape[-1]
with tf.compat.v1.variable_scope('model_pred'):
# apply DOM dropout, split and reshape DeepCore input
X_IC78, X_DeepCore_upper, X_DeepCore_lower = preprocess_icecube_data(
is_training, shared_objects)
# -----------------------------------
# convolutional layers over DeepCore_1 : upper part
# -----------------------------------
conv2d_1_layers, kernels, biases = tfs.new_conv_nd_layers(
X_DeepCore_upper,
is_training=is_training,
name='Upper DeepCore',
method_list='convolution',
keep_prob=keep_prob_list[1],
**config['conv_upper_DeepCore_settings']
)
# -----------------------------------
# convolutional layers over DeepCore_2 : lower part
# -----------------------------------
conv2d_2_layers, kernels, biases = tfs.new_conv_nd_layers(
X_DeepCore_lower,
is_training=is_training,
name='Lower DeepCore',
method_list='convolution',
keep_prob=keep_prob_list[1],
**config['conv_lower_DeepCore_settings']
)
# -----------------------------------
# convolutional hex3d layers over X_IC78 data
# -----------------------------------
conv_hex3d_layers, kernels, biases = tfs.new_conv_nd_layers(
X_IC78,
name='IC78',
is_training=is_training,
method_list='hex_convolution',
keep_prob=keep_prob_list[1],
**config['conv_IC78_settings']
)
# -----------------------------------
# combine results of convolution and flatten
# -----------------------------------
# flatten layer
layer_flat_IC78, num_features_IC78 = tfs.flatten_layer(
conv_hex3d_layers[-1])
layer_flat_DeepCore_1, num_features_DeepCore_1 = tfs.flatten_layer(
conv2d_1_layers[-1])
layer_flat_DeepCore_2, num_features_DeepCore_2 = tfs.flatten_layer(
conv2d_2_layers[-1])
# combine layers
num_features = (num_features_DeepCore_1 + num_features_DeepCore_2
+ num_features_IC78)
layer_flat = tf.concat([layer_flat_IC78, layer_flat_DeepCore_1,
layer_flat_DeepCore_2], axis=1)
# dropout
layer_flat = tf.nn.dropout(layer_flat, rate=1 - (keep_prob_list[2]))
# -----------------------------------
# fully connected layers
# -----------------------------------
fc_settings = dict(config['fc_settings'])
fc_settings['fc_sizes'][-1] = num_labels
layers, weights, biases = tfs.new_fc_layers(
input=layer_flat,
keep_prob=keep_prob_list[3],
is_training=is_training,
**fc_settings)
y_pred_trafo_orig = layers[-1]
# -----------------------------------
# Enforce Normalisation
# -----------------------------------
assert len(y_pred_trafo_orig.get_shape().as_list()) == 2
# transform back
y_pred = data_transformer.inverse_transform(y_pred_trafo_orig,
data_type='label')
y_pred_list = tf.unstack(y_pred, axis=1)
if 'model_enforce_direction_norm' not in config:
# backward compatibility
enforce_direction_norm = True
else:
enforce_direction_norm = config['model_enforce_direction_norm']
if enforce_direction_norm:
index_dir_x = \
data_handler.get_label_index(config['label_dir_x_key'])
index_dir_y = \
data_handler.get_label_index(config['label_dir_y_key'])
index_dir_z = \
data_handler.get_label_index(config['label_dir_z_key'])
index_zenith = \
data_handler.get_label_index(config['label_zenith_key'])
index_azimuth = \
data_handler.get_label_index(config['label_azimuth_key'])
trafo_indices = [index_dir_x, index_dir_y, | |
<filename>solnml/components/models/object_detection/nn_utils/retinanet_utils.py
"""
RetinaNet code borrowed from
https://github.com/yhenon/pytorch-retinanet/tree/master/retinanet
"""
import numpy as np
import torch
import torch.nn as nn
class Anchors(nn.Module):
def __init__(self, pyramid_levels=None, strides=None, sizes=None, ratios=None, scales=None):
super(Anchors, self).__init__()
if pyramid_levels is None:
self.pyramid_levels = [3, 4, 5, 6, 7]
if strides is None:
self.strides = [2 ** x for x in self.pyramid_levels]
if sizes is None:
self.sizes = [2 ** (x + 2) for x in self.pyramid_levels]
if ratios is None:
self.ratios = np.array([0.5, 1, 2])
if scales is None:
self.scales = np.array([2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)])
def forward(self, image):
image_shape = image.shape[2:]
image_shape = np.array(image_shape)
image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in self.pyramid_levels]
# compute anchors over all pyramid levels
all_anchors = np.zeros((0, 4)).astype(np.float32)
for idx, p in enumerate(self.pyramid_levels):
anchors = generate_anchors(base_size=self.sizes[idx], ratios=self.ratios, scales=self.scales)
shifted_anchors = shift(image_shapes[idx], self.strides[idx], anchors)
all_anchors = np.append(all_anchors, shifted_anchors, axis=0)
all_anchors = np.expand_dims(all_anchors, axis=0)
if torch.cuda.is_available():
return torch.from_numpy(all_anchors.astype(np.float32)).cuda()
else:
return torch.from_numpy(all_anchors.astype(np.float32))
def generate_anchors(base_size=16, ratios=None, scales=None):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales w.r.t. a reference window.
"""
if ratios is None:
ratios = np.array([0.5, 1, 2])
if scales is None:
scales = np.array([2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)])
num_anchors = len(ratios) * len(scales)
# initialize output anchors
anchors = np.zeros((num_anchors, 4))
# scale base_size
anchors[:, 2:] = base_size * np.tile(scales, (2, len(ratios))).T
# compute areas of anchors
areas = anchors[:, 2] * anchors[:, 3]
# correct for ratios
anchors[:, 2] = np.sqrt(areas / np.repeat(ratios, len(scales)))
anchors[:, 3] = anchors[:, 2] * np.repeat(ratios, len(scales))
# transform from (x_ctr, y_ctr, w, h) -> (x1, y1, x2, y2)
anchors[:, 0::2] -= np.tile(anchors[:, 2] * 0.5, (2, 1)).T
anchors[:, 1::2] -= np.tile(anchors[:, 3] * 0.5, (2, 1)).T
return anchors
def compute_shape(image_shape, pyramid_levels):
"""Compute shapes based on pyramid levels.
:param image_shape:
:param pyramid_levels:
:return:
"""
image_shape = np.array(image_shape[:2])
image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in pyramid_levels]
return image_shapes
def anchors_for_shape(
image_shape,
pyramid_levels=None,
ratios=None,
scales=None,
strides=None,
sizes=None,
shapes_callback=None,
):
image_shapes = compute_shape(image_shape, pyramid_levels)
# compute anchors over all pyramid levels
all_anchors = np.zeros((0, 4))
for idx, p in enumerate(pyramid_levels):
anchors = generate_anchors(base_size=sizes[idx], ratios=ratios, scales=scales)
shifted_anchors = shift(image_shapes[idx], strides[idx], anchors)
all_anchors = np.append(all_anchors, shifted_anchors, axis=0)
return all_anchors
def shift(shape, stride, anchors):
shift_x = (np.arange(0, shape[1]) + 0.5) * stride
shift_y = (np.arange(0, shape[0]) + 0.5) * stride
shift_x, shift_y = np.meshgrid(shift_x, shift_y)
shifts = np.vstack((
shift_x.ravel(), shift_y.ravel(),
shift_x.ravel(), shift_y.ravel()
)).transpose()
# add A anchors (1, A, 4) to
# cell K shifts (K, 1, 4) to get
# shift anchors (K, A, 4)
# reshape to (K*A, 4) shifted anchors
A = anchors.shape[0]
K = shifts.shape[0]
all_anchors = (anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)))
all_anchors = all_anchors.reshape((K * A, 4))
return all_anchors
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class BBoxTransform(nn.Module):
def __init__(self, mean=None, std=None):
super(BBoxTransform, self).__init__()
if mean is None:
if torch.cuda.is_available():
self.mean = torch.from_numpy(np.array([0, 0, 0, 0]).astype(np.float32)).cuda()
else:
self.mean = torch.from_numpy(np.array([0, 0, 0, 0]).astype(np.float32))
else:
self.mean = mean
if std is None:
if torch.cuda.is_available():
self.std = torch.from_numpy(np.array([0.1, 0.1, 0.2, 0.2]).astype(np.float32)).cuda()
else:
self.std = torch.from_numpy(np.array([0.1, 0.1, 0.2, 0.2]).astype(np.float32))
else:
self.std = std
def forward(self, boxes, deltas):
widths = boxes[:, :, 2] - boxes[:, :, 0]
heights = boxes[:, :, 3] - boxes[:, :, 1]
ctr_x = boxes[:, :, 0] + 0.5 * widths
ctr_y = boxes[:, :, 1] + 0.5 * heights
dx = deltas[:, :, 0] * self.std[0] + self.mean[0]
dy = deltas[:, :, 1] * self.std[1] + self.mean[1]
dw = deltas[:, :, 2] * self.std[2] + self.mean[2]
dh = deltas[:, :, 3] * self.std[3] + self.mean[3]
pred_ctr_x = ctr_x + dx * widths
pred_ctr_y = ctr_y + dy * heights
pred_w = torch.exp(dw) * widths
pred_h = torch.exp(dh) * heights
pred_boxes_x1 = pred_ctr_x - 0.5 * pred_w
pred_boxes_y1 = pred_ctr_y - 0.5 * pred_h
pred_boxes_x2 = pred_ctr_x + 0.5 * pred_w
pred_boxes_y2 = pred_ctr_y + 0.5 * pred_h
pred_boxes = torch.stack([pred_boxes_x1, pred_boxes_y1, pred_boxes_x2, pred_boxes_y2], dim=2)
return pred_boxes
class ClipBoxes(nn.Module):
def __init__(self, width=None, height=None):
super(ClipBoxes, self).__init__()
def forward(self, boxes, img):
batch_size, num_channels, height, width = img.shape
boxes[:, :, 0] = torch.clamp(boxes[:, :, 0], min=0)
boxes[:, :, 1] = torch.clamp(boxes[:, :, 1], min=0)
boxes[:, :, 2] = torch.clamp(boxes[:, :, 2], max=width)
boxes[:, :, 3] = torch.clamp(boxes[:, :, 3], max=height)
return boxes
def calc_iou(a, b):
area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], 1), b[:, 0])
ih = torch.min(torch.unsqueeze(a[:, 3], dim=1), b[:, 3]) - torch.max(torch.unsqueeze(a[:, 1], 1), b[:, 1])
iw = torch.clamp(iw, min=0)
ih = torch.clamp(ih, min=0)
ua = torch.unsqueeze((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), dim=1) + area - iw * ih
ua = torch.clamp(ua, min=1e-8)
intersection = iw * ih
IoU = intersection / ua
return IoU
class FocalLoss(nn.Module):
# def __init__(self):
def forward(self, classifications, regressions, anchors, annotations):
alpha = 0.25
gamma = 2.0
batch_size = classifications.shape[0]
classification_losses = []
regression_losses = []
anchor = anchors[0, :, :]
anchor_widths = anchor[:, 2] - anchor[:, 0]
anchor_heights = anchor[:, 3] - anchor[:, 1]
anchor_ctr_x = anchor[:, 0] + 0.5 * anchor_widths
anchor_ctr_y = anchor[:, 1] + 0.5 * anchor_heights
for j in range(batch_size):
classification = classifications[j, :, :]
regression = regressions[j, :, :]
bbox_annotation = annotations[j, :, :]
bbox_annotation = bbox_annotation[bbox_annotation[:, 4] != -1]
if bbox_annotation.shape[0] == 0:
if torch.cuda.is_available():
regression_losses.append(torch.tensor(0).float().cuda())
classification_losses.append(torch.tensor(0).float().cuda())
else:
regression_losses.append(torch.tensor(0).float())
classification_losses.append(torch.tensor(0).float())
continue
classification = torch.clamp(classification, 1e-4, 1.0 - 1e-4)
IoU = calc_iou(anchors[0, :, :], bbox_annotation[:, :4]) # num_anchors x num_annotations
IoU_max, IoU_argmax = torch.max(IoU, dim=1) # num_anchors x 1
# import pdb
# pdb.set_trace()
# compute the loss for classification
targets = torch.ones(classification.shape) * -1
if torch.cuda.is_available():
targets = targets.cuda()
targets[torch.lt(IoU_max, 0.4), :] = 0
positive_indices = torch.ge(IoU_max, 0.5)
num_positive_anchors = positive_indices.sum()
assigned_annotations = bbox_annotation[IoU_argmax, :]
targets[positive_indices, :] = 0
targets[positive_indices, assigned_annotations[positive_indices, 4].long()] = 1
if torch.cuda.is_available():
alpha_factor = torch.ones(targets.shape).cuda() * alpha
else:
alpha_factor = torch.ones(targets.shape) * alpha
alpha_factor = torch.where(torch.eq(targets, 1.), alpha_factor, 1. - alpha_factor)
focal_weight = torch.where(torch.eq(targets, 1.), 1. - classification, classification)
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(targets * torch.log(classification) + (1.0 - targets) * torch.log(1.0 - classification))
# cls_loss = focal_weight * torch.pow(bce, gamma)
cls_loss = focal_weight * bce
if torch.cuda.is_available():
cls_loss = torch.where(torch.ne(targets, -1.0), cls_loss, torch.zeros(cls_loss.shape).cuda())
else:
cls_loss = torch.where(torch.ne(targets, -1.0), cls_loss, torch.zeros(cls_loss.shape))
classification_losses.append(cls_loss.sum() / torch.clamp(num_positive_anchors.float(), min=1.0))
# compute the loss for regression
if positive_indices.sum() > 0:
assigned_annotations = assigned_annotations[positive_indices, :]
anchor_widths_pi = anchor_widths[positive_indices]
anchor_heights_pi = anchor_heights[positive_indices]
anchor_ctr_x_pi = anchor_ctr_x[positive_indices]
anchor_ctr_y_pi = anchor_ctr_y[positive_indices]
gt_widths = assigned_annotations[:, 2] - assigned_annotations[:, 0]
gt_heights = assigned_annotations[:, 3] - assigned_annotations[:, 1]
gt_ctr_x = assigned_annotations[:, 0] + 0.5 * gt_widths
gt_ctr_y = assigned_annotations[:, 1] + 0.5 * gt_heights
# clip widths to | |
from __future__ import print_function
import numpy, os, spacy, pickle, sys, re, random
from itertools import *
import multiprocessing
# load spacy model for nlp tools
encoder = spacy.load('en_core_web_md')
pos_tag_idxs = {'#': 1, '$': 2, "''": 3, '(': 4, ')': 5, ',': 6, '-LRB-': 7, '-PRB-': 8, '.': 9, ':': 10, 'ADD': 11,
'AFX': 12, 'BES': 13, 'CC': 14, 'CD': 15, 'DT': 16, 'EX': 17,
'FW': 18, 'GW': 19, 'HVS': 20, 'HYPH': 21, 'IN': 22, 'JJ': 23, 'JJR': 24, 'JJS': 25, 'LS': 26, 'MD': 27,
'NFP': 28, 'NIL': 29, 'NN': 30, 'NNP': 31, 'NNPS': 32, 'NNS': 33,
'PDT': 34, 'POS': 35, 'PRP': 36, 'PRP$': 37, 'RB': 38, 'RBR': 39, 'RBS': 40, 'RP': 41, 'SP': 42,
'SYM': 43, 'TO': 44, 'UH': 45, 'VB': 46, 'VBD': 47, 'VBG': 48, 'VBN': 49,
'VBP': 50, 'VBZ': 51, 'WDT': 52, 'WP': 53, 'WP$': 54, 'WRB': 55, 'XX': 56, '``': 57, '""': 58,
'-RRB-': 59}
rng = numpy.random.RandomState(0)
def segment(seq, clauses=False):
if clauses:
seq = segment_into_clauses(seq) # segment into clauses rather than just sentences
else:
seq = [sent.string.strip() for sent in encoder(seq).sents]
return seq
def tokenize(seq, lowercase=True, recognize_ents=False, lemmatize=False, include_tags=[], include_pos=[],
prepend_start=False):
seq = encoder(seq) # 用spacy
if recognize_ents: # merge named entities into single tokens
ent_start_idxs = {ent.start: ent for ent in seq.ents if ent.string.strip()}
# combine each ent into a single token; this is pretty hard to read, but it works
seq = [ent_start_idxs[word_idx] if word_idx in ent_start_idxs else word
for word_idx, word in enumerate(seq)
if (not word.ent_type_ or word_idx in ent_start_idxs)]
# Don't apply POS filtering to phrases (words with underscores)
if include_tags:
# fine-grained POS tags
seq = [word for word in seq if ("_" in word.string or word.tag_ in include_tags)]
if include_pos:
# coarse-grained POS tags
seq = [word for word in seq if ("_" in word.string or word.pos_ in include_pos)]
if lemmatize:
seq = [word.lemma_ if not word.string.startswith('ENT_') else word.string.strip() for word in seq]
elif lowercase:
# don't lowercase if token is an entity (entities will be of type span instead of token;
# or will be prefixed with 'ENT_' if already transformed to types)
seq = [word.string.strip().lower() if (type(word) == spacy.tokens.token.Token and not word.string.startswith('ENT_'))
else word.string.strip() for word in seq]
else:
seq = [word.string.strip() for word in seq]
seq = [word for word in seq if word] # some words may be empty strings, so filter
if prepend_start:
seq.insert(0, u"<START>")
return seq
def get_pos_num_seq(seq): # get part-of-speech (PTB fine-grained) tags for this sequence, converted to indices
seq = encoder(seq)
pos_num_seq = [pos_tag_idxs[word.tag_] if not word.string.startswith('ENT_') else 'NNP' for word in
seq] # if token is an entity, assume POS is proper noun
assert (numpy.all(numpy.array(pos_num_seq) > 0))
assert (len(seq) == len(pos_num_seq))
return pos_num_seq
def ent_counts_to_probs(ent_counts):
sum_ent_counts = {ent_type: sum(counts.values()) for ent_type, counts in ent_counts.items()}
ent_probs = {ent_type: {ent: count * 1. / sum_ent_counts[ent_type] for ent, count in ent_counts[ent_type].items()}
for ent_type in ent_counts}
return ent_probs
def get_ents(seq, include_ent_types=('PERSON', 'NORP', 'ORG', 'GPE'), recognize_gender=False,
gender_filenames={'FEMALE': 'female_names.pkl', 'MALE': 'male_names.pkl'}):
'''return dict of all entities in seq mapped to their entity types, optionally labeled with gender for PERSON entities'''
if recognize_gender:
names_gender = {}
for gender, filename in gender_filenames.items():
with open(filename) as f:
names_gender[gender] = pickle.load(f)
ents = {}
ent_counts = {}
for ent in encoder(seq).ents:
ent_type = ent.label_
if ent_type in include_ent_types:
ent = ent.string.strip()
if ent: # not sure why, but whitespace can be detected as an ent, so need to check for this
ents[ent] = [ent_type]
if ent in ent_counts:
ent_counts[ent] += 1
else:
ent_counts[ent] = 1
if recognize_gender and ent_type == 'PERSON': # append gender to entity type
detected_gender = None
for gender, names in names_gender.items():
if ent.split()[0] in names: # person may have multiple tokens in name, just check first name
if detected_gender: # name is associated with both genders, so omit it
detected_gender = None
else:
detected_gender = gender
if detected_gender:
ents[ent].append(detected_gender)
ents[ent] = "_".join(ents[ent])
return ents, ent_counts
def number_ents(ents, ent_counts):
'''return dict of all entities in seq mapped to their entity types,
with numerical suffixes to distinguish entities of the same type'''
ent_counts = sorted([(count, ent, ents[ent]) for ent, count in ent_counts.items()])[::-1]
ent_type_counts = {}
num_ents = {}
for count, ent, ent_type in ent_counts:
coref_ent = [num_ent for num_ent in num_ents if
(tokenize(num_ent, lowercase=False)[0] == tokenize(ent, lowercase=False)[0]
or tokenize(num_ent, lowercase=False)[-1] == tokenize(ent, lowercase=False)[-1])
and ents[num_ent] == ent_type] # treat ents with same first or last word as co-referring
if coref_ent:
num_ents[ent] = num_ents[coref_ent[0]]
else:
ent_type = ent_type.split("_")
if ent_type[0] in ent_type_counts:
ent_type_counts[ent_type[0]] += 1
else:
ent_type_counts[ent_type[0]] = 1
num_ents[ent] = ent_type
num_ents[ent].insert(1, str(
ent_type_counts[ent_type[0]] - 1)) # insert number id after entity type (and before tag, if it exists)
num_ents[ent] = "_".join(num_ents[ent])
return num_ents
def adapt_tok_seq_ents(seq, ents={}, sub_ent_probs={}):
ents = {ent_type: ent for ent, ent_type in ents.items()} # reverse ents so that types map to names
adapted_seq_ents = {"_".join(token.split("_")[1:]): None for token in seq if token.startswith('ENT_')}
if not adapted_seq_ents:
return seq
for seq_ent_type in {ent_type: adapted_ent for ent_type, adapted_ent in adapted_seq_ents.items() if
not adapted_ent}:
if seq_ent_type in ents:
adapted_seq_ents[seq_ent_type] = ents[seq_ent_type]
del ents[seq_ent_type]
if ents:
for seq_ent_type in {ent_type: adapted_ent for ent_type, adapted_ent in adapted_seq_ents.items() if
not adapted_ent}:
for ent_type, ent in ents.items():
if seq_ent_type.split("_")[0] in ent_type.split("_")[0]:
# import pdb;pdb.set_trace()
adapted_seq_ents[seq_ent_type] = ents[ent_type]
del ents[ent_type]
break
for seq_ent_type in {ent_type: adapted_ent for ent_type, adapted_ent in adapted_seq_ents.items() if
not adapted_ent}:
if seq_ent_type.split("_")[0] in sub_ent_probs:
sub_ents, sub_probs = zip(*sub_ent_probs[seq_ent_type.split("_")[0]].items())
rand_ent_idx = rng.choice(len(sub_ents), p=numpy.array(sub_probs))
adapted_seq_ents[seq_ent_type] = sub_ents[rand_ent_idx]
for seq_ent_type in {ent_type: adapted_ent for ent_type, adapted_ent in adapted_seq_ents.items() if
not adapted_ent}:
adapted_seq_ents[seq_ent_type] = u'<UNK>' # as last resort, replace entity with UNK token
seq = [adapted_seq_ents["_".join(token.split("_")[1:])] if "_".join(
token.split("_")[1:]) in adapted_seq_ents else token for token in seq]
return seq
def detokenize_tok_seq(seq, ents=[]):
'''use simple rules for transforming list of tokens back into string
ents is optional list of words (named entities) that should be capitalized'''
# if type(seq) in (str, unicode):
# seq = tokenize(seq, lowercase=False)
seq = [sent.split() for sent in segment(" ".join(seq))] # split sequence into sentences
detok_seq = []
for sent_idx, sent in enumerate(seq):
assert (type(sent) in (list, tuple))
if ents:
token_idx = 0
while token_idx < len(sent): # capitalize all tokens that appear in cap_ents
for ent in ents:
ent = ent.split()
if sent[token_idx:token_idx + len(ent)] == [token.lower() for token in ent]:
# import pdb;pdb.set_trace()
sent[token_idx:token_idx + len(ent)] = list(ent)
token_idx += len(ent) - 1
break
token_idx += 1
detok_sent = " ".join(sent)
detok_sent = re.sub("\'", "'", detok_sent)
# capitalize first-person "I" pronoun
detok_sent = re.sub(" i ", " I ", detok_sent)
# rules for contractions
detok_sent = re.sub(" n\'\s*t ", "n\'t ", detok_sent)
detok_sent = re.sub(" \'\s*d ", "\'d ", detok_sent)
detok_sent = re.sub(" \'\s*s ", "\'s ", detok_sent)
detok_sent = re.sub(" \'\s*ve ", "\'ve ", detok_sent)
detok_sent = re.sub(" \'\s*ll ", "\'ll ", detok_sent)
detok_sent = re.sub(" \'\s*m ", "\'m ", detok_sent)
detok_sent = re.sub(" \'\s*re ", "\'re ", detok_sent)
# rules for formatting punctuation
detok_sent = re.sub(" \.", ".", detok_sent)
detok_sent = re.sub(" \!", "!", detok_sent)
detok_sent = re.sub(" \?", "?", detok_sent)
detok_sent = re.sub(" ,", ",", detok_sent)
detok_sent = re.sub(" \- ", "-", detok_sent)
detok_sent = re.sub(" :", ":", detok_sent)
detok_sent = re.sub(" ;", ";", detok_sent)
detok_sent = re.sub("\$ ", "$", detok_sent)
detok_sent = re.sub("\' \'", "\'\'", detok_sent)
detok_sent = re.sub("\` \`", "\`\`", detok_sent)
# replace repeated single quotes with double quotation mark.
detok_sent = re.sub("\'\'", "\"", detok_sent)
detok_sent = re.sub("\`\`", "\"", detok_sent)
# filter repetitive characters
detok_sent = re.sub("([\"\']\s*){2,}", "\" ", detok_sent)
punc_pairs = {"\'": "\'", "\'": "\'", "`": "\'", "\"": "\"", "(": ")",
"[": "]"} # map each opening puncutation mark to closing mark
open_punc = []
char_idx = 0
while char_idx < len(detok_sent): # check for quotes and parenthesis
char = detok_sent[char_idx]
if open_punc and char == punc_pairs[open_punc[-1]]: # end quote/parenthesis
if char_idx > 0 and detok_sent[char_idx - 1] == " ":
detok_sent = detok_sent[:char_idx - 1] + detok_sent[char_idx:]
open_punc.pop()
elif char in punc_pairs:
if char_idx | |
<reponame>sloebrich/sage<filename>src/sage/manifolds/continuous_map.py<gh_stars>1-10
r"""
Continuous Maps Between Topological Manifolds
:class:`ContinuousMap` implements continuous maps from a topological
manifold `M` to some topological manifold `N` over the same topological
field `K` as `M`.
AUTHORS:
- <NAME>, <NAME> (2013-2015): initial version
- <NAME> (2016): review tweaks
REFERENCES:
- Chap. 1 of [KN1963]_
- [Lee2011]_
"""
#*****************************************************************************
# Copyright (C) 2015 <NAME> <<EMAIL>>
# Copyright (C) 2015 <NAME> <<EMAIL>>
# Copyright (C) 2016 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.categories.homset import Hom
from sage.categories.morphism import Morphism
class ContinuousMap(Morphism):
r"""
Continuous map between two topological manifolds.
This class implements continuous maps of the type
.. MATH::
\Phi: M \longrightarrow N,
where `M` and `N` are topological manifolds over the same
topological field `K`.
Continuous maps are the morphisms of the category of topological
manifolds. The set of all continuous maps from `M` to `N` is
therefore the homset between `M` and `N`, which is denoted
by `\mathrm{Hom}(M,N)`.
The class :class:`ContinuousMap` is a Sage *element* class,
whose *parent* class is
:class:`~sage.manifolds.manifold_homset.TopologicalManifoldHomset`.
INPUT:
- ``parent`` -- homset `\mathrm{Hom}(M,N)` to which the continuous
map belongs
- ``coord_functions`` -- a dictionary of the coordinate expressions
(as lists or tuples of the coordinates of the image expressed in
terms of the coordinates of the considered point) with the pairs
of charts ``(chart1, chart2)`` as keys (``chart1`` being a chart
on `M` and ``chart2`` a chart on `N`)
- ``name`` -- (default: ``None``) name given to ``self``
- ``latex_name`` -- (default: ``None``) LaTeX symbol to denote the
continuous map; if ``None``, the LaTeX symbol is set to
``name``
- ``is_isomorphism`` -- (default: ``False``) determines whether the
constructed object is a isomorphism (i.e. a homeomorphism); if set to
``True``, then the manifolds `M` and `N` must have the same dimension
- ``is_identity`` -- (default: ``False``) determines whether the
constructed object is the identity map; if set to ``True``,
then `N` must be `M` and the entry ``coord_functions`` is not used
.. NOTE::
If the information passed by means of the argument
``coord_functions`` is not sufficient to fully specify the
continuous map, further coordinate expressions, in other charts,
can be subsequently added by means of the method :meth:`add_expr`.
EXAMPLES:
The standard embedding of the sphere `S^2` into `\RR^3`::
sage: M = Manifold(2, 'S^2', structure='topological') # the 2-dimensional sphere S^2
sage: U = M.open_subset('U') # complement of the North pole
sage: c_xy.<x,y> = U.chart() # stereographic coordinates from the North pole
sage: V = M.open_subset('V') # complement of the South pole
sage: c_uv.<u,v> = V.chart() # stereographic coordinates from the South pole
sage: M.declare_union(U,V) # S^2 is the union of U and V
sage: xy_to_uv = c_xy.transition_map(c_uv, (x/(x^2+y^2), y/(x^2+y^2)),
....: intersection_name='W',
....: restrictions1=x^2+y^2!=0,
....: restrictions2=u^2+v^2!=0)
sage: uv_to_xy = xy_to_uv.inverse()
sage: N = Manifold(3, 'R^3', latex_name=r'\RR^3', structure='topological') # R^3
sage: c_cart.<X,Y,Z> = N.chart() # Cartesian coordinates on R^3
sage: Phi = M.continuous_map(N,
....: {(c_xy, c_cart): [2*x/(1+x^2+y^2), 2*y/(1+x^2+y^2), (x^2+y^2-1)/(1+x^2+y^2)],
....: (c_uv, c_cart): [2*u/(1+u^2+v^2), 2*v/(1+u^2+v^2), (1-u^2-v^2)/(1+u^2+v^2)]},
....: name='Phi', latex_name=r'\Phi')
sage: Phi
Continuous map Phi from the 2-dimensional topological manifold S^2
to the 3-dimensional topological manifold R^3
sage: Phi.parent()
Set of Morphisms from 2-dimensional topological manifold S^2
to 3-dimensional topological manifold R^3
in Category of manifolds over Real Field with 53 bits of precision
sage: Phi.parent() is Hom(M, N)
True
sage: type(Phi)
<class 'sage.manifolds.manifold_homset.TopologicalManifoldHomset_with_category.element_class'>
sage: Phi.display()
Phi: S^2 --> R^3
on U: (x, y) |--> (X, Y, Z) = (2*x/(x^2 + y^2 + 1), 2*y/(x^2 + y^2 + 1), (x^2 + y^2 - 1)/(x^2 + y^2 + 1))
on V: (u, v) |--> (X, Y, Z) = (2*u/(u^2 + v^2 + 1), 2*v/(u^2 + v^2 + 1), -(u^2 + v^2 - 1)/(u^2 + v^2 + 1))
It is possible to create the map using
:meth:`~sage.manifolds.manifold.TopologicalManifold.continuous_map`
with only in a single pair of charts. The argument ``coord_functions``
is then a mere list of coordinate expressions (and not a dictionary)
and the arguments ``chart1`` and ``chart2`` have to be provided if
the charts differ from the default ones on the domain and/or codomain::
sage: Phi1 = M.continuous_map(N, [2*x/(1+x^2+y^2), 2*y/(1+x^2+y^2), (x^2+y^2-1)/(1+x^2+y^2)],
....: chart1=c_xy, chart2=c_cart,
....: name='Phi', latex_name=r'\Phi')
Since ``c_xy`` and ``c_cart`` are the default charts on respectively
``M`` and ``N``, they can be omitted, so that the above declaration
is equivalent to::
sage: Phi1 = M.continuous_map(N, [2*x/(1+x^2+y^2), 2*y/(1+x^2+y^2), (x^2+y^2-1)/(1+x^2+y^2)],
....: name='Phi', latex_name=r'\Phi')
With such a declaration, the continuous map ``Phi1`` is only partially
defined on the manifold `S^2` as it is known in only one chart::
sage: Phi1.display()
Phi: S^2 --> R^3
on U: (x, y) |--> (X, Y, Z) = (2*x/(x^2 + y^2 + 1), 2*y/(x^2 + y^2 + 1), (x^2 + y^2 - 1)/(x^2 + y^2 + 1))
The definition can be completed by using :meth:`add_expr`::
sage: Phi1.add_expr(c_uv, c_cart, [2*u/(1+u^2+v^2), 2*v/(1+u^2+v^2), (1-u^2-v^2)/(1+u^2+v^2)])
sage: Phi1.display()
Phi: S^2 --> R^3
on U: (x, y) |--> (X, Y, Z) = (2*x/(x^2 + y^2 + 1), 2*y/(x^2 + y^2 + 1), (x^2 + y^2 - 1)/(x^2 + y^2 + 1))
on V: (u, v) |--> (X, Y, Z) = (2*u/(u^2 + v^2 + 1), 2*v/(u^2 + v^2 + 1), -(u^2 + v^2 - 1)/(u^2 + v^2 + 1))
At this stage, ``Phi1`` and ``Phi`` are fully equivalent::
sage: Phi1 == Phi
True
The map acts on points::
sage: np = M.point((0,0), chart=c_uv) # the North pole
sage: Phi(np)
Point on the 3-dimensional topological manifold R^3
sage: Phi(np).coord() # Cartesian coordinates
(0, 0, 1)
sage: sp = M.point((0,0), chart=c_xy) # the South pole
sage: Phi(sp).coord() # Cartesian coordinates
(0, 0, -1)
The test suite is passed::
sage: TestSuite(Phi).run()
sage: TestSuite(Phi1).run()
Continuous maps can be composed by means of the operator ``*``.
Let us introduce the map `\RR^3 \to \RR^2` corresponding to
the projection from the point `(X, Y, Z) = (0, 0, 1)` onto the
equatorial plane `Z = 0`::
sage: P = Manifold(2, 'R^2', latex_name=r'\RR^2', structure='topological') # R^2 (equatorial plane)
sage: cP.<xP, yP> = P.chart()
sage: Psi = N.continuous_map(P, (X/(1-Z), Y/(1-Z)), name='Psi',
....: latex_name=r'\Psi')
sage: Psi
Continuous map Psi from the 3-dimensional topological manifold R^3
to the 2-dimensional topological manifold R^2
sage: Psi.display()
Psi: R^3 --> R^2
(X, Y, Z) |--> (xP, yP) = (-X/(Z - 1), -Y/(Z - 1))
Then we compose ``Psi`` with ``Phi``, thereby getting a map
`S^2 \to \RR^2`::
sage: ster = Psi * Phi ; ster
Continuous map from the 2-dimensional topological manifold S^2
to the 2-dimensional topological manifold R^2
Let us test on the South pole (``sp``) that ``ster`` is indeed the
composite of ``Psi`` and ``Phi``::
sage: ster(sp) == Psi(Phi(sp))
True
Actually ``ster`` is the stereographic projection from the North pole,
as its coordinate expression reveals::
sage: ster.display()
S^2 --> R^2
on U: (x, y) |--> (xP, yP) = (x, y)
on V: (u, v) |--> (xP, yP) = (u/(u^2 + v^2), v/(u^2 + v^2))
If the codomain of a continuous map is 1-dimensional, the map can
be defined by a single symbolic expression for each pair of charts
and not by a list/tuple with a single element::
sage: N = Manifold(1, 'N', structure='topological')
sage: c_N = N.chart('X')
sage: Phi = M.continuous_map(N, {(c_xy, c_N): x^2+y^2,
....: (c_uv, c_N): 1/(u^2+v^2)})
sage: Psi = M.continuous_map(N, {(c_xy, c_N): [x^2+y^2],
....: (c_uv, c_N): [1/(u^2+v^2)]})
sage: Phi == Psi
True
Next we construct an example of continuous map `\RR \to \RR^2`::
sage: R = Manifold(1, 'R', structure='topological') # field R
sage: T.<t> = R.chart() # canonical chart on R
sage: R2 = Manifold(2, 'R^2', structure='topological') # R^2
sage: c_xy.<x,y> = R2.chart() # Cartesian coordinates on R^2
sage: Phi = R.continuous_map(R2, [cos(t), sin(t)], name='Phi'); Phi
Continuous map Phi from the 1-dimensional topological manifold R
to the 2-dimensional topological manifold R^2
sage: Phi.parent()
Set of Morphisms from 1-dimensional topological manifold R
to 2-dimensional topological manifold | |
# from: https://github.com/ericPrince/optical-flow/blob/master/optical_flow.py
import numpy as np
import scipy.ndimage
from functools import partial
import skimage
def poly_exp(f, c, sigma):
"""
Calculates the local polynomial expansion of a 2D signal, as described by Farneback
Uses separable normalized correlation
$f ~ x^T A x + B^T x + C$
If f[i, j] and c[i, j] are the signal value and certainty of pixel (i, j) then
A[i, j] is a 2x2 array representing the quadratic term of the polynomial, B[i, j]
is a 2-element array representing the linear term, and C[i, j] is a scalar
representing the constant term.
Parameters
----------
f
Input signal
c
Certainty of signal
sigma
Standard deviation of applicability Gaussian kernel
Returns
-------
A
Quadratic term of polynomial expansion
B
Linear term of polynomial expansion
C
Constant term of polynomial expansion
"""
# Calculate applicability kernel (1D because it is separable)
n = int(4*sigma + 1)
x = np.arange(-n, n + 1, dtype=np.int)
a = np.exp(-x**2 / (2 * sigma**2)) # a: applicability kernel [n]
# b: calculate b from the paper. Calculate separately for X and Y dimensions
# [n, 6]
bx = np.stack([
np.ones(a.shape),
x,
np.ones(a.shape),
x**2,
np.ones(a.shape),
x
], axis=-1)
by = np.stack([
np.ones(a.shape),
np.ones(a.shape),
x,
np.ones(a.shape),
x**2,
x,
], axis=-1)
# Pre-calculate product of certainty and signal
cf = c * f
# G and v are used to calculate "r" from the paper: v = G*r
# r is the parametrization of the 2nd order polynomial for f
G = np.empty(list(f.shape) + [bx.shape[-1]]*2)
v = np.empty(list(f.shape) + [bx.shape[-1]])
# Apply separable cross-correlations
# Pre-calculate quantities recommended in paper
ab = np.einsum('i,ij->ij', a, bx)
abb = np.einsum('ij,ik->ijk', ab, bx)
# Calculate G and v for each pixel with cross-correlation
for i in range(bx.shape[-1]):
for j in range(bx.shape[-1]):
G[..., i, j] = scipy.ndimage.correlate1d(c, abb[..., i, j], axis=0, mode='constant', cval=0)
v[..., i] = scipy.ndimage.correlate1d(cf, ab[..., i], axis=0, mode='constant', cval=0)
# Pre-calculate quantities recommended in paper
ab = np.einsum('i,ij->ij', a, by)
abb = np.einsum('ij,ik->ijk', ab, by)
# Calculate G and v for each pixel with cross-correlation
for i in range(bx.shape[-1]):
for j in range(bx.shape[-1]):
G[..., i, j] = scipy.ndimage.correlate1d(G[..., i, j], abb[..., i, j], axis=1, mode='constant', cval=0)
v[..., i] = scipy.ndimage.correlate1d(v[..., i], ab[..., i], axis=1, mode='constant', cval=0)
# Solve r for each pixel
r = np.linalg.solve(G, v)
# Quadratic term
A = np.empty(list(f.shape) + [2, 2])
A[..., 0, 0] = r[..., 3]
A[..., 0, 1] = r[..., 5] / 2
A[..., 1, 0] = A[..., 0, 1]
A[..., 1, 1] = r[..., 4]
# Linear term
B = np.empty(list(f.shape) + [2])
B[..., 0] = r[..., 1]
B[..., 1] = r[..., 2]
# constant term
C = r[..., 0]
# b: [n, n, 6]
# r: [f, f, 6]
# f: [f, f]
# e = b*r - f
return A, B, C
def flow_iterative(
f1, f2, sigma, c1, c2, sigma_flow, num_iter=1, d=None, model='constant', mu=None, l_coef=0.95
):
"""
Calculates optical flow with an algorithm described by <NAME>
Parameters
----------
f1
First image
f2
Second image
sigma
Polynomial expansion applicability Gaussian kernel sigma
c1
Certainty of first image
c2
Certainty of second image
sigma_flow
Applicability window Gaussian kernel sigma for polynomial matching
num_iter
Number of iterations to run (defaults to 1)
d: (optional)
Initial displacement field
p: (optional)
Initial global displacement model parameters
model: ['constant', 'affine', 'eight_param']
Optical flow parametrization to use
mu: (optional)
Weighting term for usage of global parametrization. Defaults to
using value recommended in Farneback's thesis
l_coef:
Regularization coef for getting closer to optimal
Returns
-------
d
Optical flow field. d[i, j] is the (y, x) displacement for pixel (i, j)
"""
# TODO: add initial warp parameters as optional input?
# Calculate the polynomial expansion at each point in the images
A1, B1, C1 = poly_exp(f1, c1, sigma)
A2, B2, C2 = poly_exp(f2, c2, sigma)
# Pixel coordinates of each point in the images
x = np.stack(np.broadcast_arrays(
np.arange(f1.shape[0])[:, None],
np.arange(f1.shape[1])
), axis=-1).astype(np.int)
# Initialize displacement field
if d is None:
d = np.zeros(list(f1.shape) + [2])
# Set up applicability convolution window
n_flow = int(4*sigma_flow + 1)
xw = np.arange(-n_flow, n_flow + 1)
w = np.exp(-xw**2 / (2 * sigma_flow**2))
# Evaluate warp parametrization model at pixel coordinates
if model == 'constant':
S = np.eye(2)
elif model in ('affine', 'eight_param'):
S = np.empty(list(x.shape) + [6 if model == 'affine' else 8])
S[..., 0, 0] = 1
S[..., 0, 1] = x[..., 0]
S[..., 0, 2] = x[..., 1]
S[..., 0, 3] = 0
S[..., 0, 4] = 0
S[..., 0, 5] = 0
S[..., 1, 0] = 0
S[..., 1, 1] = 0
S[..., 1, 2] = 0
S[..., 1, 3] = 1
S[..., 1, 4] = x[..., 0]
S[..., 1, 5] = x[..., 1]
if model == 'eight_param':
S[..., 0, 6] = x[..., 0] ** 2
S[..., 0, 7] = x[..., 0] * x[..., 1]
S[..., 1, 6] = x[..., 0] * x[..., 1]
S[..., 1, 7] = x[..., 1] ** 2
else:
raise ValueError('Invalid parametrization model')
S_T = S.swapaxes(-1, -2)
# Iterate convolutions to estimate the optical flow
for _ in range(num_iter):
# Set d~ as displacement field fit to nearest pixel (and constrain to not
# being off image). Note we are setting certainty to 0 for points that
# would have been off-image had we not constrained them
# print(d.shape, x.shape)
d_ = d.astype(np.int)
x_ = x + d_
# x_ = np.maximum(np.minimum(x_, np.array(f1.shape) - 1), 0)
# Constrain d~ to be on-image, and find points that would have
# been off-image
x_2 = np.maximum(np.minimum(x_, np.array(f1.shape) - 1), 0)
off_f = np.any(x_ != x_2, axis=-1)
x_ = x_2
# Set certainty to 0 for off-image points
c_ = c1[x_[..., 0], x_[..., 1]]
c_[off_f] = 0
# Calculate A and delB for each point, according to paper
A = (A1 + A2[x_[..., 0], x_[..., 1]]) / 2
A *= c_[..., None, None] # recommendation in paper: add in certainty by applying to A and delB
delB = -1/2 * (B2[x_[..., 0], x_[..., 1]] - B1) + (A @ d_[..., None])[..., 0]
delB *= c_[..., None] # recommendation in paper: add in certainty by applying to A and delB
# Pre-calculate quantities recommended by paper
A_T = A.swapaxes(-1, -2)
ATA = S_T @ A_T @ A @ S
ATb = (S_T @ A_T @ delB[..., None])[..., 0]
# btb = delB.swapaxes(-1, -2) @ delB
# If mu is 0, it means the global/average parametrized warp should not be
# calculated, and the parametrization should apply to the local calculations
if mu == 0:
# Apply separable cross-correlation to calculate linear equation
# for each pixel: G*d = h
G = scipy.ndimage.correlate1d(ATA, w, axis=0, mode='constant', cval=0)
G = scipy.ndimage.correlate1d(G, w, axis=1, mode='constant', cval=0)
h = scipy.ndimage.correlate1d(ATb, w, axis=0, mode='constant', cval=0)
h = scipy.ndimage.correlate1d(h, w, axis=1, mode='constant', cval=0)
d = (S @ np.linalg.solve(G, h)[..., None])[..., 0]
# if mu is not 0, it should be used to regularize the least squares problem
# and "force" the background warp onto uncertain pixels
else:
# Calculate global parametrized warp
G_avg = np.mean(ATA, axis=(0, 1))
h_avg = np.mean(ATb, axis=(0, 1))
p_avg = np.linalg.solve(G_avg, h_avg)
d_avg = (S @ p_avg[..., None])[..., 0]
# Default value for mu is to set mu to 1/2 the trace of G_avg
if mu is None:
mu = 1/2 * np.trace(G_avg)
# Apply separable cross-correlation to calculate linear equation
G = scipy.ndimage.correlate1d(A_T @ A, w, axis=0, mode='constant', cval=0)
G = scipy.ndimage.correlate1d(G, w, axis=1, mode='constant', cval=0)
h = scipy.ndimage.correlate1d((A_T @ delB[..., None])[..., 0], w, axis=0, mode='constant', cval=0)
h = scipy.ndimage.correlate1d(h, w, axis=1, mode='constant', cval=0)
# Refine estimate of displacement field
d = np.linalg.solve(G + mu*np.eye(2), h + mu*d_avg)
if l_coef > 0:
d[..., 0] = l_coef * 0 + (1 - l_coef) * d[..., 0]
d[..., 1] = l_coef * | |
'subscribe_to_exploration', self._null_fn
):
# User B starts a feedback thread.
feedback_services.create_thread(
'exploration', self.EXP_ID_1, self.user_b_id, 'subject', 'text')
# User C adds to that thread.
thread_id = feedback_services.get_all_threads(
'exploration', self.EXP_ID_1, False)[0].id
feedback_services.create_message(
thread_id, self.user_c_id, None, None, 'more text')
self._run_one_off_job()
# Both users are subscribed to the feedback thread.
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id)
user_c_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_c_id)
self.assertEqual(user_b_subscriptions_model.exploration_ids, [])
self.assertEqual(user_c_subscriptions_model.exploration_ids, [])
self.assertEqual(
user_b_subscriptions_model.general_feedback_thread_ids, [thread_id])
self.assertEqual(
user_c_subscriptions_model.general_feedback_thread_ids, [thread_id])
def test_exploration_subscription(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
):
# User A adds user B as an editor to the exploration.
rights_manager.assign_role_for_exploration(
self.user_a, self.EXP_ID_1, self.user_b_id,
rights_domain.ROLE_EDITOR)
# User A adds user C as a viewer of the exploration.
rights_manager.assign_role_for_exploration(
self.user_a, self.EXP_ID_1, self.user_c_id,
rights_domain.ROLE_VIEWER)
self._run_one_off_job()
# Users A and B are subscribed to the exploration. User C is not.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id)
user_c_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_c_id, strict=False)
self.assertEqual(
user_a_subscriptions_model.exploration_ids, [self.EXP_ID_1])
self.assertEqual(
user_b_subscriptions_model.exploration_ids, [self.EXP_ID_1])
self.assertEqual(user_c_subscriptions_model, None)
def test_two_explorations(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
):
# User A creates and saves another valid exploration.
self.save_new_valid_exploration(self.EXP_ID_2, self.user_a_id)
self._run_one_off_job()
# User A is subscribed to two explorations.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
self.assertEqual(
sorted(user_a_subscriptions_model.exploration_ids),
sorted([self.EXP_ID_1, self.EXP_ID_2]))
def test_community_owned_exploration(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
):
# User A adds user B as an editor to the exploration.
rights_manager.assign_role_for_exploration(
self.user_a, self.EXP_ID_1, self.user_b_id,
rights_domain.ROLE_EDITOR)
# The exploration becomes community-owned.
rights_manager.publish_exploration(self.user_a, self.EXP_ID_1)
rights_manager.release_ownership_of_exploration(
self.user_a, self.EXP_ID_1)
# User C edits the exploration.
exp_services.update_exploration(
self.user_c_id, self.EXP_ID_1, [], 'Update exploration')
self._run_one_off_job()
# User A and user B are subscribed to the exploration; user C is not.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id)
user_c_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_c_id, strict=False)
self.assertEqual(
user_a_subscriptions_model.exploration_ids, [self.EXP_ID_1])
self.assertEqual(
user_b_subscriptions_model.exploration_ids, [self.EXP_ID_1])
self.assertEqual(user_c_subscriptions_model, None)
def test_deleted_exploration(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
):
# User A deletes the exploration.
exp_services.delete_exploration(self.user_a_id, self.EXP_ID_1)
self.process_and_flush_pending_mapreduce_tasks()
self._run_one_off_job()
# User A is not subscribed to the exploration.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id, strict=False)
self.assertEqual(user_a_subscriptions_model, None)
def test_collection_subscription(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_collection', self._null_fn
):
# User A creates and saves a new valid collection.
self.save_new_valid_collection(
self.COLLECTION_ID_1, self.user_a_id,
exploration_id=self.EXP_ID_FOR_COLLECTION_1)
# User A adds user B as an editor to the collection.
rights_manager.assign_role_for_collection(
self.user_a, self.COLLECTION_ID_1, self.user_b_id,
rights_domain.ROLE_EDITOR)
# User A adds user C as a viewer of the collection.
rights_manager.assign_role_for_collection(
self.user_a, self.COLLECTION_ID_1, self.user_c_id,
rights_domain.ROLE_VIEWER)
self._run_one_off_job()
# Users A and B are subscribed to the collection. User C is not.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id)
user_c_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_c_id, strict=False)
self.assertEqual(
user_a_subscriptions_model.collection_ids, [self.COLLECTION_ID_1])
# User A is also subscribed to the exploration within the collection
# because they created both.
self.assertEqual(
sorted(user_a_subscriptions_model.exploration_ids), [
self.EXP_ID_1, self.EXP_ID_FOR_COLLECTION_1])
self.assertEqual(
user_b_subscriptions_model.collection_ids, [self.COLLECTION_ID_1])
self.assertEqual(user_c_subscriptions_model, None)
def test_two_collections(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_collection', self._null_fn
):
# User A creates and saves a new valid collection.
self.save_new_valid_collection(
self.COLLECTION_ID_1, self.user_a_id,
exploration_id=self.EXP_ID_FOR_COLLECTION_1)
# User A creates and saves another valid collection.
self.save_new_valid_collection(
self.COLLECTION_ID_2, self.user_a_id,
exploration_id=self.EXP_ID_FOR_COLLECTION_1)
self._run_one_off_job()
# User A is subscribed to two collections.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
self.assertEqual(
sorted(user_a_subscriptions_model.collection_ids),
sorted([self.COLLECTION_ID_1, self.COLLECTION_ID_2]))
def test_deleted_collection(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_exploration', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_collection', self._null_fn
):
# User A creates and saves a new collection.
self.save_new_default_collection(
self.COLLECTION_ID_1, self.user_a_id)
# User A deletes the collection.
collection_services.delete_collection(
self.user_a_id, self.COLLECTION_ID_1)
# User A deletes the exploration from earlier.
exp_services.delete_exploration(self.user_a_id, self.EXP_ID_1)
self.process_and_flush_pending_mapreduce_tasks()
self._run_one_off_job()
# User A is not subscribed to the collection.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id, strict=False)
self.assertEqual(user_a_subscriptions_model, None)
def test_adding_exploration_to_collection(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_collection', self._null_fn
):
# User B creates and saves a new collection.
self.save_new_default_collection(
self.COLLECTION_ID_1, self.user_b_id)
# User B adds the exploration created by user A to the collection.
collection_services.update_collection(
self.user_b_id, self.COLLECTION_ID_1, [{
'cmd': collection_domain.CMD_ADD_COLLECTION_NODE,
'exploration_id': self.EXP_ID_1
}], 'Add new exploration to collection.')
# Users A and B have no subscriptions (to either explorations or
# collections).
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id, strict=False)
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id, strict=False)
self.assertEqual(user_a_subscriptions_model, None)
self.assertEqual(user_b_subscriptions_model, None)
self._run_one_off_job()
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id)
# User B should be subscribed to the collection and user A to the
# exploration.
self.assertEqual(
user_a_subscriptions_model.exploration_ids, [self.EXP_ID_1])
self.assertEqual(
user_a_subscriptions_model.collection_ids, [])
self.assertEqual(
user_b_subscriptions_model.exploration_ids, [])
self.assertEqual(
user_b_subscriptions_model.collection_ids, [self.COLLECTION_ID_1])
def test_community_owned_collection(self):
with self.swap(
subscription_services, 'subscribe_to_thread', self._null_fn
), self.swap(
subscription_services, 'subscribe_to_collection', self._null_fn
):
rights_manager.publish_exploration(self.user_a, self.EXP_ID_1)
# User A creates and saves a new valid collection.
self.save_new_valid_collection(
self.COLLECTION_ID_1, self.user_a_id,
exploration_id=self.EXP_ID_1)
# User A adds user B as an editor to the collection.
rights_manager.assign_role_for_collection(
self.user_a, self.COLLECTION_ID_1, self.user_b_id,
rights_domain.ROLE_EDITOR)
# The collection becomes community-owned.
rights_manager.publish_collection(self.user_a, self.COLLECTION_ID_1)
rights_manager.release_ownership_of_collection(
self.user_a, self.COLLECTION_ID_1)
# User C edits the collection.
collection_services.update_collection(
self.user_c_id, self.COLLECTION_ID_1, [{
'cmd': collection_domain.CMD_EDIT_COLLECTION_PROPERTY,
'property_name': (
collection_domain.COLLECTION_PROPERTY_TITLE),
'new_value': 'New title'
}], 'Changed title.')
self._run_one_off_job()
# User A and user B are subscribed to the collection; user C is not.
user_a_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_a_id)
user_b_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_b_id)
user_c_subscriptions_model = user_models.UserSubscriptionsModel.get(
self.user_c_id, strict=False)
self.assertEqual(
user_a_subscriptions_model.collection_ids, [self.COLLECTION_ID_1])
self.assertEqual(
user_b_subscriptions_model.collection_ids, [self.COLLECTION_ID_1])
self.assertEqual(user_c_subscriptions_model, None)
class MockUserStatsAggregator(
user_jobs_continuous.UserStatsAggregator):
"""A modified UserStatsAggregator that does not start a new
batch job when the previous one has finished.
"""
@classmethod
def _get_batch_job_manager_class(cls):
return MockUserStatsMRJobManager
@classmethod
def _kickoff_batch_job_after_previous_one_ends(cls):
pass
class MockUserStatsMRJobManager(
user_jobs_continuous.UserStatsMRJobManager):
@classmethod
def _get_continuous_computation_class(cls):
return MockUserStatsAggregator
class DashboardStatsOneOffJobTests(test_utils.GenericTestBase):
"""Tests for the one-off dashboard stats job."""
CURRENT_DATE_AS_STRING = user_services.get_current_date_as_string()
DATE_AFTER_ONE_WEEK = (
(datetime.datetime.utcnow() + datetime.timedelta(7)).strftime(
feconf.DASHBOARD_STATS_DATETIME_STRING_FORMAT))
USER_SESSION_ID = 'session1'
EXP_ID_1 = 'exp_id_1'
EXP_ID_2 = 'exp_id_2'
EXP_VERSION = 1
def _run_one_off_job(self):
"""Runs the one-off MapReduce job."""
job_id = user_jobs_one_off.DashboardStatsOneOffJob.create_new()
user_jobs_one_off.DashboardStatsOneOffJob.enqueue(job_id)
self.assertEqual(
self.count_jobs_in_mapreduce_taskqueue(
taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1)
self.process_and_flush_pending_mapreduce_tasks()
def setUp(self):
super(DashboardStatsOneOffJobTests, self).setUp()
self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME)
self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL)
def mock_get_current_date_as_string(self):
return self.CURRENT_DATE_AS_STRING
def _rate_exploration(self, user_id, exp_id, rating):
"""Assigns rating to the exploration corresponding to the given
exploration id.
Args:
user_id: str. The user id.
exp_id: str. The exploration id.
rating: int. The rating to be assigned to the given exploration.
"""
rating_services.assign_rating_to_exploration(user_id, exp_id, rating)
def _record_play(self, exp_id, state):
"""Calls StartExplorationEventHandler and records the 'play' event
corresponding to the given exploration id.
Args:
exp_id: str. The exploration id.
state: dict(str, *). The state of the exploration corresponding to
the given id.
"""
event_services.StartExplorationEventHandler.record(
exp_id, self.EXP_VERSION, state, self.USER_SESSION_ID, {},
feconf.PLAY_TYPE_NORMAL)
def test_weekly_stats_if_continuous_stats_job_has_not_been_run(self):
exploration = self.save_new_valid_exploration(
self.EXP_ID_1, self.owner_id)
exp_id = exploration.id
init_state_name = exploration.init_state_name
self._record_play(exp_id, init_state_name)
self._rate_exploration('user1', exp_id, 5)
weekly_stats = user_services.get_weekly_dashboard_stats(self.owner_id)
self.assertEqual(weekly_stats, None)
self.assertEqual(
user_services.get_last_week_dashboard_stats(self.owner_id), None)
with self.swap(
user_services,
'get_current_date_as_string',
self.mock_get_current_date_as_string):
self._run_one_off_job()
weekly_stats = user_services.get_weekly_dashboard_stats(self.owner_id)
expected_results_list = [{
self.mock_get_current_date_as_string(): {
'num_ratings': 0,
'average_ratings': None,
'total_plays': 0
}
}]
self.assertEqual(weekly_stats, expected_results_list)
self.assertEqual(
user_services.get_last_week_dashboard_stats(self.owner_id),
expected_results_list[0])
def test_weekly_stats_if_no_explorations(self):
MockUserStatsAggregator.start_computation()
self.process_and_flush_pending_mapreduce_tasks()
with self.swap(
user_services,
'get_current_date_as_string',
self.mock_get_current_date_as_string):
self._run_one_off_job()
weekly_stats = user_services.get_weekly_dashboard_stats(self.owner_id)
self.assertEqual(
weekly_stats, [{
self.mock_get_current_date_as_string(): {
'num_ratings': 0,
'average_ratings': None,
'total_plays': 0
}
}])
def test_weekly_stats_for_single_exploration(self):
exploration = self.save_new_valid_exploration(
self.EXP_ID_1, self.owner_id)
exp_id = exploration.id
init_state_name = exploration.init_state_name
self._record_play(exp_id, init_state_name)
self._rate_exploration('user1', exp_id, 5)
event_services.StatsEventsHandler.record(
self.EXP_ID_1, 1, {
'num_starts': 1,
'num_actual_starts': 0,
'num_completions': 0,
'state_stats_mapping': {}
})
self.process_and_flush_pending_tasks()
MockUserStatsAggregator.start_computation()
self.process_and_flush_pending_mapreduce_tasks()
with self.swap(
user_services,
'get_current_date_as_string',
self.mock_get_current_date_as_string):
self._run_one_off_job()
weekly_stats = user_services.get_weekly_dashboard_stats(self.owner_id)
self.assertEqual(
weekly_stats, [{
self.mock_get_current_date_as_string(): {
'num_ratings': 1,
'average_ratings': 5.0,
'total_plays': 1
}
}])
def test_weekly_stats_for_multiple_explorations(self):
exploration_1 = self.save_new_valid_exploration(
self.EXP_ID_1, self.owner_id)
exp_id_1 = exploration_1.id
exploration_2 = self.save_new_valid_exploration(
self.EXP_ID_2, self.owner_id)
exp_id_2 = exploration_2.id
init_state_name_1 = exploration_1.init_state_name
self._record_play(exp_id_1, init_state_name_1)
self._rate_exploration('user1', exp_id_1, 5)
self._rate_exploration('user2', exp_id_2, 4)
event_services.StatsEventsHandler.record(
self.EXP_ID_1, 1, {
'num_starts': 1,
'num_actual_starts': 0,
'num_completions': 0,
'state_stats_mapping': {}
})
self.process_and_flush_pending_tasks()
MockUserStatsAggregator.start_computation()
self.process_and_flush_pending_mapreduce_tasks()
with self.swap(
user_services,
'get_current_date_as_string',
self.mock_get_current_date_as_string):
self._run_one_off_job()
weekly_stats = user_services.get_weekly_dashboard_stats(self.owner_id)
self.assertEqual(
weekly_stats, [{
self.mock_get_current_date_as_string(): {
'num_ratings': 2,
'average_ratings': 4.5,
'total_plays': 1
}
}])
def test_stats_for_multiple_weeks(self):
exploration = self.save_new_valid_exploration(
self.EXP_ID_1, self.owner_id)
exp_id = exploration.id
init_state_name = exploration.init_state_name
self._rate_exploration('user1', exp_id, 4)
self._record_play(exp_id, init_state_name)
self._record_play(exp_id, init_state_name)
event_services.StatsEventsHandler.record(
self.EXP_ID_1, 1, {
'num_starts': 2,
'num_actual_starts': 0,
'num_completions': 0,
'state_stats_mapping': {}
})
self.process_and_flush_pending_tasks()
MockUserStatsAggregator.start_computation()
self.process_and_flush_pending_mapreduce_tasks()
with self.swap(
user_services,
'get_current_date_as_string',
self.mock_get_current_date_as_string):
self._run_one_off_job()
weekly_stats = user_services.get_weekly_dashboard_stats(self.owner_id)
self.assertEqual(
weekly_stats, [{
self.mock_get_current_date_as_string(): {
'num_ratings': 1,
'average_ratings': 4.0,
'total_plays': 2
}
}])
MockUserStatsAggregator.stop_computation(self.owner_id)
self.process_and_flush_pending_mapreduce_tasks()
self._rate_exploration('user2', exp_id, 2)
MockUserStatsAggregator.start_computation()
self.process_and_flush_pending_mapreduce_tasks()
def _mock_get_date_after_one_week():
"""Returns the date of the next week."""
return self.DATE_AFTER_ONE_WEEK
with self.swap(
user_services,
'get_current_date_as_string',
_mock_get_date_after_one_week):
self._run_one_off_job()
expected_results_list = [
{
self.mock_get_current_date_as_string(): {
'num_ratings': 1,
'average_ratings': 4.0,
'total_plays': 2
}
},
{
| |
from PyQt5 import QtWidgets as Qtw
from PyQt5 import QtCore as Qtc
from PyQt5 import QtGui as Qtg
from datetime import datetime, timedelta
from bu_data_model import BU366
import sys
import socket
import time
import pandas as pd
from openpyxl.chart import ScatterChart, Reference, Series
class CheckingThread(Qtc.QThread):
answer_thread = Qtc.pyqtSignal(str, list)
running_state = Qtc.pyqtSignal(str)
remaining_time = Qtc.pyqtSignal(str)
error_threads = Qtc.pyqtSignal(str)
running_threads = {}
def __init__(self, threadid_, n366, total_time, polling_interval, poll_rest):
Qtc.QThread.__init__(self)
self.threadid = threadid_
self.name = n366.name
self.n366 = n366
self.total_time = total_time
self.polling_inteval = polling_interval
self.poll_rest = timedelta(seconds=poll_rest)
self.next_poll = datetime.now()
self.end = datetime.now() + timedelta(minutes=total_time)
self.poll_rest_flag = False
if poll_rest > 0:
self.poll_rest_flag = True
def run(self): # we run iterating over time until the test is over
time_ = datetime.now() # get the time now for the loop
self.running_threads[f'{self.name}'] = self # we add the object to the queue to be able to stop it later
while time_ < self.end: # main loop until end time is bigger than current time
self.remaining_time.emit(f'{self.end - time_}') # we update the remaining time of the test via signal
self.running_state.emit('°R') # we update the status to °R via a signal
try: # we check if the conection is active
self.n366.check_active() # here we poll the DN and get the values to the dataframes
except: # try to reconnect
self.running_state.emit('°RC')
while not self.n366.connection_state and datetime.now() < self.end: # while there is no connection we try to reconnect
for tu_name_disconnect in self.n366.tus: # updates display to show the disconnection status
tu_item = self.n366.tus[tu_name_disconnect]
self.answer_thread.emit(tu_name_disconnect, [ # emit list with values
-1, # set local sector
-100, # set RSSI
0, # set SNR
0, # set RXMCS
0, # set TXMCS
0, # set RX PER
0, # set TX PER
0, # set RX MCS DR
0, # set TX MCS DR
tu_item.get_availability(),
tu_item.get_disconnection_counter(),
tu_item.get_disconnection_ldt(),
tu_item.get_disconnection_lds(),
tu_item.get_disconnection_tdt(),
False,
0,
])
self.n366.connect(self.n366.username, self.n366.password, 22, 1)
# mini loop to fill in the disconnection time for each TU. We get disconnection start from object
# and disconnection end at that time
except_disconnection_start = self.n366.disconnection_start
except_disconnection_end = datetime.now()
while except_disconnection_start < except_disconnection_end: # while there is time between both events
for tu_name_reconnect in self.n366.tus: # updates display to show the disconnection status
except_tu_item = self.n366.tus[tu_name_reconnect] # get each TU
# create a record with the disconnection parameters
record = {'Local Sector': 0, 'RSSI': -100, 'SNR': 0, 'MCS-RX': 0, 'MCS-TX': 0,
'MCS-DR-RX': 0, 'MCS-DR-TX': 0, 'Power Index': 0}
record_series = pd.Series(record, name=except_disconnection_start)
# add the record of the disconnection
except_tu_item.parameters_df = except_tu_item.parameters_df.append(record_series)
# add the time for the next event
except_disconnection_start = except_disconnection_start + self.poll_rest
continue # jump over the loop to try to parse the active connection as we had no
# conection extablished
tu_counter = len(self.n366.tus)
for tu_name in self.n366.tus:
tu_item = self.n366.tus[tu_name]
self.answer_thread.emit(tu_name, [ # emit list with values
tu_item.get_local_sector(),
tu_item.get_rssi(),
tu_item.get_snr(),
tu_item.get_rxmcs(),
tu_item.get_txmcs(),
tu_item.get_rxspeednum(),
tu_item.get_txspeednum(),
tu_item.get_rxmcsdr(),
tu_item.get_txmcsdr(),
tu_item.get_availability(),
tu_item.get_disconnection_counter(),
tu_item.get_disconnection_ldt(),
tu_item.get_disconnection_lds(),
tu_item.get_disconnection_tdt(),
tu_item.get_connection_status(),
tu_item.get_power_index(),
])
if self.poll_rest_flag and self.next_poll < time_ and tu_counter >= 0:
if tu_item.connection_state:
record = {'Local Sector': tu_item.get_local_sector(),
'RSSI': tu_item.get_rssi(), 'SNR': tu_item.get_snr(),
'MCS-RX': tu_item.get_rxmcs(), 'MCS-TX': tu_item.get_txmcs(),
'MCS-DR-RX': tu_item.get_rxmcsdr(), 'MCS-DR-TX': tu_item.get_txmcsdr(),
'Power Index': tu_item.get_power_index()}
else:
record = {'Local Sector': 0, 'RSSI': -100, 'SNR': 0, 'MCS-RX': 0, 'MCS-TX': 0,
'MCS-DR-RX': 0, 'MCS-DR-TX': 0, 'Power Index': 0}
record_series = pd.Series(record, name=time_)
tu_item.parameters_df = tu_item.parameters_df.append(record_series)
tu_counter -= 1
if tu_counter <= 0:
self.next_poll = self.next_poll + self.poll_rest
time.sleep(self.polling_inteval)
time_ = datetime.now()
# create the end
test_end = datetime.now()
self.n366.availability = self.n366.calculate_availability(self.n366.disconnection_total_time,
self.n366.first_connection, test_end)
self.n366.create_end(test_end)
# we write the dataframe to excel
# Show mesage box
try:
with pd.ExcelWriter(f'{self.n366.name}.xlsx', mode='w') as writer:
self.n366.disconnections.to_excel(writer, sheet_name=f'{self.n366.name}')
for tu_ in self.n366.tus:
tu__ = self.n366.tus[tu_]
tu__.availability = tu__.calculate_availability(tu__.disconnection_total_time, tu__.first_connection if tu__.first_connection != -1 else self.n366.first_connection, test_end) # use start time if there is one, else use the time of the N366
tu__.create_end(test_end)
tu__.disconnections.to_excel(writer, sheet_name=f'{tu__.name}')
tu__.parameters_df = tu__.parameters_df.dropna(axis=0)
tu__.parameters_df = tu__.parameters_df.astype(int)
tu__.parameters_df.to_excel(writer, sheet_name=f'{tu__.name}-Parameters')
# We create the chart
worksheet = writer.sheets[f'{tu__.name}-Parameters'] # where do we want to create the chart
# we create the chart
chart = ScatterChart('smoothMarker')
chart.title = 'Performance metrics'
chart.style = 10
chart.x_axis.title = 'Time'
chart.y_axis.title = 'Metrics'
# we define the range of the data that will work for the X series (dates in this case)
# they are on the column 1 and go from row 1 to the end
x_values = Reference(worksheet, min_col=1, min_row=2, max_row=tu__.parameters_df.shape[0] + 1)
for i_ in range(2, 7): # we walk through columns 1 to 5
values = Reference(worksheet, min_col=i_, min_row=1, max_row=tu__.parameters_df.shape[0] + 1)
series = Series(values, x_values, title_from_data=True)
chart.series.append(series)
worksheet.add_chart(chart, 'J2')
# end creating the chart
self.n366.append_end_summary(tu_, tu__.disconnections.loc['Total'])
self.n366.disconnections_summary.to_excel(writer, sheet_name=f'Summary')
self.running_state.emit('°D')
except PermissionError as e:
self.error_threads.emit('Could not write to the Excel file.')
del (self.running_threads[self.name])
# show message box
def stop_thread(self):
self.end = datetime.now()
class Tu(Qtw.QWidget):
def __init__(self, name, parent=None):
super(Tu, self).__init__()
self.setParent(parent)
# name of the widget
self.name = name
self.group = Qtw.QGroupBox(parent=self)
# title of the widget name of the remote unit
self.group.setTitle(self.name)
# set shape, min max size
self.group.setMinimumSize(300, 161)
self.group.setMaximumSize(300, 161)
# add push button that will show disconnection events
self.btn_node = Qtw.QPushButton('Show Drop Table', parent=self.group)
self.btn_node.setGeometry(Qtc.QRect(10, 20, 131, 23))
# label that will whos Dic.
self.lbl_disconnect_counter = Qtw.QLabel('Disc.', parent=self.group)
self.lbl_disconnect_counter.setGeometry(Qtc.QRect(10, 50, 31, 16))
# text line that will desplay the amount of disconnections
self.txt_disconnect_counter = Qtw.QLineEdit(f'-', parent=self.group)
self.txt_disconnect_counter.setGeometry(Qtc.QRect(40, 50, 101, 20))
self.txt_disconnect_counter.setReadOnly(True)
# state last disconection total time
self.lbl_last_disc_time = Qtw.QLabel('L. drop time:', parent=self.group)
self.lbl_last_disc_time.setGeometry(Qtc.QRect(10, 76, 72, 16))
self.lbl_last_disc_time_value = Qtw.QLabel(f'0 s', parent=self.group)
self.lbl_last_disc_time_value.setGeometry(Qtc.QRect(86, 76, 59, 16))
# state the start time of last disconnection
self.lbl_disc_time_start = Qtw.QLabel('Start disc. event:', parent=self.group)
self.lbl_disc_time_start.setGeometry(Qtc.QRect(10, 96, 131, 16))
self.lbl_disc_time_start_value = Qtw.QLabel('-', parent=self.group)
self.lbl_disc_time_start_value.setGeometry(Qtc.QRect(10, 117, 131, 16))
# state total disconection time
self.lbl_total_disc_time = Qtw.QLabel('Tot. downtime:', parent=self.group)
self.lbl_total_disc_time.setGeometry(Qtc.QRect(10, 135, 75, 16))
self.lbl_total_disc_time_value = Qtw.QLabel(f'0 s', parent=self.group)
self.lbl_total_disc_time_value.setGeometry(Qtc.QRect(91, 135, 59, 16))
# Division
self.line_Vertical = Qtw.QFrame(parent=self.group)
self.line_Vertical.setGeometry(Qtc.QRect(150, 7, 2, 151))
self.line_Vertical.setFrameShape(Qtw.QFrame.VLine)
self.line_Vertical.setFrameShadow(Qtw.QFrame.Sunken)
# TU parameters
self.lbl_ls = Qtw.QLabel('L.S.:', parent=self.group)
self.lbl_ls.setGeometry(Qtc.QRect(160, 10, 24, 16))
self.lbl_ls_text = Qtw.QLabel('-', parent=self.group)
self.lbl_ls_text.setGeometry(Qtc.QRect(190, 10, 10, 16))
self.lbl_av = Qtw.QLabel('Av.:', parent=self.group)
self.lbl_av.setGeometry(Qtc.QRect(210, 10, 24, 16))
self.lbl_av_text = Qtw.QLabel('-', parent=self.group)
self.lbl_av_text.setGeometry(Qtc.QRect(240, 10, 45, 16))
self.lbl_rssi = Qtw.QLabel('RSSI:', parent=self.group)
self.lbl_rssi.setGeometry(Qtc.QRect(160, 30, 28, 16))
self.lbl_rssi_text = Qtw.QLabel('-128', parent=self.group)
self.lbl_rssi_text.setGeometry(Qtc.QRect(190, 30, 25, 16))
self.lbl_snr = Qtw.QLabel('SNR:', parent=self.group)
self.lbl_snr.setGeometry(Qtc.QRect(230, 30, 26, 16))
self.lbl_snr_text = Qtw.QLabel('-128', parent=self.group)
self.lbl_snr_text.setGeometry(Qtc.QRect(260, 30, 25, 16))
self.lbl_rx_mcs = Qtw.QLabel('RxMCS:', parent=self.group)
self.lbl_rx_mcs.setGeometry(Qtc.QRect(160, 50, 40, 16))
self.lbl_rx_mcs_v = Qtw.QLabel('-', parent=self.group)
self.lbl_rx_mcs_v.setGeometry(Qtc.QRect(200, 50, 15, 16))
self.lbl_tx_mcs = Qtw.QLabel('TxMCS:', parent=self.group)
self.lbl_tx_mcs.setGeometry(Qtc.QRect(230, 50, 40, 16))
self.lbl_tx_mcs_v = Qtw.QLabel('-', parent=self.group)
self.lbl_tx_mcs_v.setGeometry(Qtc.QRect(270, 50, 15, 16))
# self.lbl_rx_mbps = Qtw.QLabel('RxMbps:', parent=self.group)
# self.lbl_rx_mbps.setGeometry(Qtc.QRect(160, 90, 40, 16))
# self.lbl_rx_mbps_v = Qtw.QLabel('-', parent=self.group)
# self.lbl_rx_mbps_v.setGeometry(Qtc.QRect(210, 90, 41, 16))
self.lbl_tx_dr = Qtw.QLabel('Tx DR:', parent=self.group)
self.lbl_tx_dr.setGeometry(Qtc.QRect(160, 70, 40, 16))
self.lbl_tx_dr_v = Qtw.QLabel('-', parent=self.group)
self.lbl_tx_dr_v.setGeometry(Qtc.QRect(210, 70, 41, 16))
self.lbl_rx_dr = Qtw.QLabel('Rx DR:', parent=self.group)
self.lbl_rx_dr.setGeometry(Qtc.QRect(160, 90, 40, 16))
self.lbl_rx_dr_v = Qtw.QLabel('-', parent=self.group)
self.lbl_rx_dr_v.setGeometry(Qtc.QRect(210, 90, 41, 16))
self.lbl_tx_index = Qtw.QLabel('Tx Index:', parent=self.group)
self.lbl_tx_index.setGeometry(Qtc.QRect(160, 110, 50, 16))
self.lbl_tx_index_v = Qtw.QLabel('-', parent=self.group)
self.lbl_tx_index_v.setGeometry(Qtc.QRect(210, 110, 41, 16))
# create the layout
widget_layout = Qtw.QGridLayout()
widget_layout.addWidget(self.group, 0, 0, 1, 1)
self.setLayout(widget_layout)
@Qtc.pyqtSlot(int)
def update_ls(self, ls):
self.lbl_ls_text.setText(f'{ls}')
@Qtc.pyqtSlot(int)
def update_rssi(self, rssi):
self.lbl_rssi_text.setText(f'{rssi}')
@Qtc.pyqtSlot(int)
def update_snr(self, snr):
self.lbl_snr_text.setText(f'{snr}')
@Qtc.pyqtSlot(int)
def update_rxmcs(self, rxmcs):
self.lbl_rx_mcs_v.setText(f'{rxmcs}')
@Qtc.pyqtSlot(int)
def update_txmcs(self, txmcs):
self.lbl_tx_mcs_v.setText(f'{txmcs}')
@Qtc.pyqtSlot(int)
def update_tx_power_index(self, txpower):
self.lbl_tx_index_v.setText(f'{txpower}')
# @Qtc.pyqtSlot(float)
# def update_rxmcs_v(self, rxsp):
# self.lbl_rx_mbps_v.setText(f'{rxsp}')
#
# @Qtc.pyqtSlot(float)
# def update_txmcs_v(self, txsp):
# self.lbl_tx_mbps_v.setText(f'{txsp}')
@Qtc.pyqtSlot(int)
def update_rx_dr(self, dr):
self.lbl_rx_dr_v.setText(f'{dr}')
@Qtc.pyqtSlot(int)
def update_tx_dr(self, dr):
self.lbl_tx_dr_v.setText(f'{dr}')
@Qtc.pyqtSlot(float)
def update_av(self, av):
self.lbl_av_text.setText(f'{av:.2f}%')
@Qtc.pyqtSlot(int)
def update_d_counter(self, counter_):
self.txt_disconnect_counter.setText(f'{counter_}')
@Qtc.pyqtSlot(timedelta)
def update_d_ldt(self, time_):
self.lbl_last_disc_time_value.setText(f'{time_}')
@Qtc.pyqtSlot(datetime)
def update_d_lds(self, time_):
self.lbl_disc_time_start_value.setText(f'{time_}')
@Qtc.pyqtSlot(timedelta)
def update_d_tdt(self, time_):
self.lbl_total_disc_time_value.setText(f'{time_}')
@Qtc.pyqtSlot(bool)
def update_connection_status(self, status):
if status:
self.setStyleSheet('background-color: rgb(85, 170, 0);')
else:
self.setStyleSheet('background-color: rgb(255, 41, 41);')
class N366Widget(Qtw.QWidget):
def __init__(self, n366_node, run_time, poll_time, poll_rest, parent=None):
super(N366Widget, self).__init__(parent)
self.n366 = n366_node # N366 BU datanode
self.tu_items = {} # TU widget dictionary
# Variables to fit the nodes inside the widget to add 60
self.columns = 5
self.rows = 60 / self.columns
# The x,y coordinates to add new nodes
self.current_row = 1
self.current_column = 0
# | |
#-----------------------------------------------------------------------------
# Do NOT modify or remove this copyright
#
# Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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.
#
#****************************************************************************
# \file tcgapi.py
# \brief Implementation of TCG API methods
#
#-----------------------------------------------------------------------------
import sys
import logging
from . import pysed
import struct
from . import pysedSupport
import warnings
from .pysedSupport import *
from . import tcgSupport
from .tcgSupport import locking_table as locking_table
from .tcgSupport import portlocking_table as portlocking_table
from .tcgSupport import c_tls_psk_table as c_tls_psk_table
import io
StatusCode = pysed.StatusCode
class PskCipherSuites(object):
'''
This is a class dealing with PskCipherSuites.
Used optionally to provide support for TLS Secure Messaging.
'''
DHE_PSK_WITH_AES_128_GCM_SHA256 = 0x00AA
PSK_WITH_AES_128_GCM_SHA256 = 0x00A8
PSK_WITH_AES_256_GCM_SHA384 = 0x00A9
DHE_PSK_WITH_AES_256_GCM_SHA384 = 0x00AB
PSK_WITH_AES_128_CBC_SHA256 = 0x00AE
PSK_WITH_AES_256_CBC_SHA384 = 0x00AF
PSK_WITH_NULL_SHA256 = 0x00B0
PSK_WITH_NULL_SHA384 = 0x00B1
DHE_PSK_WITH_AES_128_CBC_SHA256 = 0x00B2
DHE_PSK_WITH_AES_256_CBC_SHA384 = 0x00B3
DHE_PSK_WITH_NULL_SHA256 = 0x00B4
DHE_PSK_WITH_NULL_SHA384 = 0x00B5
PSK_WITH_AES_128_CCM = 0x0CA4
PSK_WITH_AES_256_CCM = 0x0CA5
DHE_PSK_WITH_AES_128_CCM = 0x0CA6
DHE_PSK_WITH_AES_256_CCM = 0x0CA7
ECDHE_PSK_WITH_AES_128_CBC_SHA256 = 0x0C37
ECDHE_PSK_WITH_AES_256_CBC_SHA384 = 0x0C38
ECDHE_PSK_WITH_NULL_SHA256 = 0x0C3A
ECDHE_PSK_WITH_NULL_SHA384 = 0x0C3B
byValue = {'\xff\xff':None}
@classmethod
def _init(cls):
for k, v in vars(cls).items():
if isinstance(v, int):
cls.byValue[v] = k
cls.byValue[struct.pack('>H', v)] = k
@classmethod
def Name(cls, value):
try:
return cls.byValue[value]
except KeyError:
if value in vars(cls):
return value
if len(cls.byValue) == 1:
cls._init()
try:
return cls.byValue[value]
except KeyError:
pass
raise ValueError('Invalid CipherSuite value - ' + str(value))
@classmethod
def Value(cls, name):
try:
return getattr(cls, cls.Name(name))
except KeyError:
raise ValueError('Invalid CipherSuite name - ' + str(name))
@classmethod
def StringValue(cls, name):
try:
return struct.pack('>H', cls.Value(name))
except KeyError:
raise ValueError('Invalid CipherSuite name - ' + str(name))
except ValueError:
if name is None:
return '\xff\xff'
raise
class SedCallbacksStub(object):
'''
classdocs
Hooks to provide mechanism that caches and gathers credentials to use in Sed methods.
Overridable Attributes:
logger - (class or instance) A Python logger instance to use for logging.
If not supplied, will use the logger sed.xxxxx where xxxxx is the last
five digits of the drive wwn or base device name.
'''
def __init__(self, **kwargs):
self.dataStore = None
def getAuth(self, op, defAuth):
'''
Override the default authority used in an Sed call. Example usage would be to
provide any cached BandMaster credentials to a WriteData call.
op - The operation to be performed
defAuth- The default authority (number) to be used for this request.
Returns the name or authority id to use for this request. If None, defAuth will be used.
'''
return defAuth
def getCred(self, auth):
'''
Override the credentials used in an SED call.
auth - The authority as a number to be used for this request.
Returns a Key object or a string containing the plain text credentials to be used.
if None, the mSID will be used.
'''
return None
def setCred(self, auth, key):
'''
Notification of a successful ChangePIN request.
auth - The authority id as a number that has been modified.
key - The new Key now in effect.
'''
return
def failedCred(self, auth, cred):
'''
Notification of an unsuccessful request due to authentication failure.
auth - The Authority attempted as an integer.
cred - The Key/plainText credentials used.
May return a new credential to use on retry.
Returns None to stop authentication attempts.
'''
return None
def fail(self, msg=None, op=None, status=None):
'''
Sets return code or raises an exception for failed operations.
'''
return False
def configureTls(self, sed, cipherSuites):
'''
Used optionally to provide support for TLS Secure Messaging.
Callback to solicit information regarding Tls configuration.
Routine should invoke sed.usePsk to configure the chosen cipher suite.
If usePsk is not invoked, TLS will not be configured.
Parameters:
sed - The Sed instance for this device.
cipherSuites - list of available cipher suites to utilize listed in preferential order by the drive.
'''
pass
currentFuncName = lambda n = 0: sys._getframe(n + 1).f_code.co_name
class SedObject(object):
def __init__(self, d):
self.__dict__ = d
def __repr__(self, *args, **kwargs):
out = io.StringIO()
keys = list(vars(self).keys())
klen = max(len(k) for k in keys)
for k in sorted(keys):
v = str(getattr(self, k))
if len(v) == 8 and v[0] == '\x00': # UIDs
v = "0x%016x" % (struct.unpack('>Q', v)[0])
out.write('%*s: %s\n' % (klen, k, v))
result = out.getvalue()
out.close()
return result
class Sed(pysed.Sed):
'''
classdocs
Establishes communications to the SED functionality of a drive.
All methods return False on error. Methods may return an object upon success or otherwise True
Many methods have an optional parameter authAs. This parameter provides the authority to
authenticate as and credentials. The parameter may take many forms:
string - Converted to Authority, if not a valid authority string, assumed to be plaintext credentials.
object - Assumed to be a container for the credential. Object has a plainText property
that extracts the credentials.
tuple - Assumed to be (auth, cred). if auth is not a valid authority string, assumed to be
plaintext credential. cred is either a string or a Credential message. In the string
form, assumed to be a plaintext credential.
If authority or credentials are not provided, the callbacks class methods provided at construction
will be consulted.
Caller must have CAP_SYS_RAWIO priveleges to communicate. Access to /dev/sdxx requires
the caller to either have CAP_DAC_OVERRIDE or be in the 'disk' (EL) supplimental group.
Full reset logic also requires CAP_SYSADM for rights to reset the drive.
'''
def __init__(self, dev, **kwargs):
'''
Constructor
dev - the device name of the storage device
- May also be the wwn in numeric or string form.
Named Parameters:
callbacks - A class that handles the methods in the SedCallbacksStub class
'''
self.callbacks = kwargs.get('callbacks', SedCallbacksStub)
if isinstance(self.callbacks, type):
self.callbacks = self.callbacks(**kwargs)
if hasattr(self.callbacks, 'logger'):
kwargs['logger'] = self.callbacks.logger
else:
warnings.warn("Logger not initialized and passed into the TCGAPI")
if isinstance(dev, int):
dev = hex(dev)
if '/' not in dev:
if dev[0].isdigit():
if dev[1] != 'x':
dev = '0x' + dev
dev = "/dev/disk/by-id/wwn-" + dev
super(Sed, self).__init__(dev, pysedSupport.getUidTables, PskCipherSuites, kwargs)
self.token = {}
if hasattr(tcgSupport, 'configureTls'):
cipherSuites = self._cipherSuites()
if cipherSuites is not None:
tcgSupport.configureTls(self, [PskCipherSuites.Name(s) for s in cipherSuites])
def close(self, authAs=None):
'''
Shutdown communication to the SED drive.
authAs - authority to use to write dirty DataStore data if necessary
Support provided only for Enterprise drives.
'''
if self.callbacks.dataStore is not None:
self.writeData(authAs=authAs)
def _getAuthAs(self, authAs, defAuth=None):
'''
Normalize the authAs parameter into a (auth, cred) tuple.
Parameters:
authAs - The authAs parameter to the function being performed.
Optional named parameters:
defAuth - The authority to utilize in case no authority was supplied.
Returns a tuple containing the authority and credential to be used to authenticate.
'''
if authAs is None:
authAs = (None, None)
elif isinstance(authAs, tuple):
auth, cred = authAs[:]
authAs = (auth, cred)
else:
tcgSupport.fail(msg='Unknown authAs parameter type: ' + str(authAs))
if not isinstance(authAs, tuple):
tcgSupport.fail(msg='authAs parameter normalization error: ' + str(authAs))
auth, cred = authAs[:]
if auth is None:
if defAuth:
auth = defAuth
else:
if hasattr(self.callbacks,'logger'):
tcgSupport.getAuth(self.callbacks.logger,currentFuncName(1), defAuth)
if auth == 'Anybody':
return auth
if cred is None:
if hasattr(self.callbacks,'keymanager'):
cred = tcgSupport.getCred(self.callbacks.keymanager,auth)
else:
print ("Credentials not provided for the method"+' '+currentFuncName(1))
return (auth, cred)
def _failedCredentials(self, auth, cred):
'''
Callback from the base class to alert us of a failed authentication and a chance to
provide the correct credentials.
Parameters:
auth - The authority being authenticated. A string.
cred - The credentials supplied to invoke() or returned from a
previous callback of this method.
'''
if hasattr(self.callbacks,'logger'):
return tcgSupport.failedCred(self.callbacks.logger,auth, cred)
def fail(self, msg, status):
'''
Callback for a failed operation.
msg - message to be displayed.
status - Status of the operation being performed
'''
if | |
Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 0.406823,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime Dynamic': 5.69904,
'Subthreshold Leakage': 6.21877,
'Subthreshold Leakage with power gating': 2.58311},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.062991,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.252165,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.341456,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.226777,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.365783,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.184635,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.777196,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.207018,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 4.82891,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0645084,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00951206,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0923147,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0703475,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.156823,
'Execution Unit/Register Files/Runtime Dynamic': 0.0798596,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.210233,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.531139,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 2.04574,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00133648,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00133648,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00117179,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.00045784,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.00101055,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00485529,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0125382,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0676269,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 4.30165,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.202357,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.229691,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 6.72893,
'Instruction Fetch Unit/Runtime Dynamic': 0.517068,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0383021,
'L2/Runtime Dynamic': 0.00845272,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 4.13942,
'Load Store Unit/Data Cache/Runtime Dynamic': 1.39524,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0938962,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0938963,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 4.58282,
'Load Store Unit/Runtime Dynamic': 1.9522,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.231532,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.463064,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0821715,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0827465,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.267461,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.033174,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.564726,
'Memory Management Unit/Runtime Dynamic': 0.11592,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 20.3332,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.169692,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.0122967,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.112803,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': | |
# SRE test harness for the Python regression suite
# this is based on test_re.py, but uses a test function instead
# of all those asserts
import sys
sys.path=['.']+sys.path
from test_support import verbose, TestFailed, have_unicode
import sre
import sys, os, string, traceback
#
# test support
def test(expression, result, exception=None):
try:
r = eval(expression)
except:
if exception:
if not isinstance(sys.exc_value, exception):
print expression, "FAILED"
# display name, not actual value
if exception is sre.error:
print "expected", "sre.error"
else:
print "expected", exception.__name__
print "got", sys.exc_type.__name__, str(sys.exc_value)
else:
print expression, "FAILED"
traceback.print_exc(file=sys.stdout)
else:
if exception:
print expression, "FAILED"
if exception is sre.error:
print "expected", "sre.error"
else:
print "expected", exception.__name__
print "got result", repr(r)
else:
if r != result:
print expression, "FAILED"
print "expected", repr(result)
print "got result", repr(r)
if verbose:
print 'Running tests on character literals'
for i in [0, 8, 16, 32, 64, 127, 128, 255]:
test(r"""sre.match(r"\%03o" % i, chr(i)) is not None""", 1)
test(r"""sre.match(r"\%03o0" % i, chr(i)+"0") is not None""", 1)
test(r"""sre.match(r"\%03o8" % i, chr(i)+"8") is not None""", 1)
test(r"""sre.match(r"\x%02x" % i, chr(i)) is not None""", 1)
test(r"""sre.match(r"\x%02x0" % i, chr(i)+"0") is not None""", 1)
test(r"""sre.match(r"\x%02xz" % i, chr(i)+"z") is not None""", 1)
test(r"""sre.match("\911", "")""", None, sre.error)
#
# Misc tests from <NAME>' re.doc
if verbose:
print 'Running tests on sre.search and sre.match'
test(r"""sre.search(r'x*', 'axx').span(0)""", (0, 0))
test(r"""sre.search(r'x*', 'axx').span()""", (0, 0))
test(r"""sre.search(r'x+', 'axx').span(0)""", (1, 3))
test(r"""sre.search(r'x+', 'axx').span()""", (1, 3))
test(r"""sre.search(r'x', 'aaa')""", None)
test(r"""sre.match(r'a*', 'xxx').span(0)""", (0, 0))
test(r"""sre.match(r'a*', 'xxx').span()""", (0, 0))
test(r"""sre.match(r'x*', 'xxxa').span(0)""", (0, 3))
test(r"""sre.match(r'x*', 'xxxa').span()""", (0, 3))
test(r"""sre.match(r'a+', 'xxx')""", None)
# bug 113254
test(r"""sre.match(r'(a)|(b)', 'b').start(1)""", -1)
test(r"""sre.match(r'(a)|(b)', 'b').end(1)""", -1)
test(r"""sre.match(r'(a)|(b)', 'b').span(1)""", (-1, -1))
# bug 612074
pat=u"["+sre.escape(u"\u2039")+u"]"
test(r"""sre.compile(pat) and 1""", 1, None)
if verbose:
print 'Running tests on sre.sub'
test(r"""sre.sub(r"(?i)b+", "x", "bbbb BBBB")""", 'x x')
def bump_num(matchobj):
int_value = int(matchobj.group(0))
return str(int_value + 1)
test(r"""sre.sub(r'\d+', bump_num, '08.2 -2 23x99y')""", '9.3 -3 24x100y')
test(r"""sre.sub(r'\d+', bump_num, '08.2 -2 23x99y', 3)""", '9.3 -3 23x99y')
test(r"""sre.sub(r'.', lambda m: r"\n", 'x')""", '\\n')
test(r"""sre.sub(r'.', r"\n", 'x')""", '\n')
s = r"\1\1"
test(r"""sre.sub(r'(.)', s, 'x')""", 'xx')
test(r"""sre.sub(r'(.)', sre.escape(s), 'x')""", s)
test(r"""sre.sub(r'(.)', lambda m: s, 'x')""", s)
test(r"""sre.sub(r'(?P<a>x)', '\g<a>\g<a>', 'xx')""", 'xxxx')
test(r"""sre.sub(r'(?P<a>x)', '\g<a>\g<1>', 'xx')""", 'xxxx')
test(r"""sre.sub(r'(?P<unk>x)', '\g<unk>\g<unk>', 'xx')""", 'xxxx')
test(r"""sre.sub(r'(?P<unk>x)', '\g<1>\g<1>', 'xx')""", 'xxxx')
# bug 449964: fails for group followed by other escape
test(r"""sre.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx')""", 'xx\bxx\b')
test(r"""sre.sub(r'a', r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D', 'a')""", '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D')
test(r"""sre.sub(r'a', '\t\n\v\r\f\a', 'a')""", '\t\n\v\r\f\a')
test(r"""sre.sub(r'a', '\t\n\v\r\f\a', 'a')""", (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)))
test(r"""sre.sub(r'^\s*', 'X', 'test')""", 'Xtest')
# qualified sub
test(r"""sre.sub(r'a', 'b', 'aaaaa')""", 'bbbbb')
test(r"""sre.sub(r'a', 'b', 'aaaaa', 1)""", 'baaaa')
# bug 114660
test(r"""sre.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there')""", 'hello there')
# Test for sub() on escaped characters, see SF bug #449000
test(r"""sre.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
test(r"""sre.sub('\r\n', r'\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
test(r"""sre.sub(r'\r\n', '\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
test(r"""sre.sub('\r\n', '\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
# Test for empty sub() behaviour, see SF bug #462270
test(r"""sre.sub('x*', '-', 'abxd')""", '-a-b-d-')
test(r"""sre.sub('x+', '-', 'abxd')""", 'ab-d')
if verbose:
print 'Running tests on symbolic references'
test(r"""sre.sub(r'(?P<a>x)', '\g<a', 'xx')""", None, sre.error)
test(r"""sre.sub(r'(?P<a>x)', '\g<', 'xx')""", None, sre.error)
test(r"""sre.sub(r'(?P<a>x)', '\g', 'xx')""", None, sre.error)
test(r"""sre.sub(r'(?P<a>x)', '\g<a a>', 'xx')""", None, sre.error)
test(r"""sre.sub(r'(?P<a>x)', '\g<1a1>', 'xx')""", None, sre.error)
test(r"""sre.sub(r'(?P<a>x)', '\g<ab>', 'xx')""", None, IndexError)
test(r"""sre.sub(r'(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')""", None, sre.error)
test(r"""sre.sub(r'(?P<a>x)|(?P<b>y)', '\\2', 'xx')""", None, sre.error)
if verbose:
print 'Running tests on sre.subn'
test(r"""sre.subn(r"(?i)b+", "x", "bbbb BBBB")""", ('x x', 2))
test(r"""sre.subn(r"b+", "x", "bbbb BBBB")""", ('x BBBB', 1))
test(r"""sre.subn(r"b+", "x", "xyz")""", ('xyz', 0))
test(r"""sre.subn(r"b*", "x", "xyz")""", ('xxxyxzx', 4))
test(r"""sre.subn(r"b*", "x", "xyz", 2)""", ('xxxyz', 2))
if verbose:
print 'Running tests on sre.split'
test(r"""sre.split(r":", ":a:b::c")""", ['', 'a', 'b', '', 'c'])
test(r"""sre.split(r":+", ":a:b:::")""", ['', 'a', 'b', ''])
test(r"""sre.split(r":*", ":a:b::c")""", ['', 'a', 'b', 'c'])
test(r"""sre.split(r"(:*)", ":a:b::c")""", ['', ':', 'a', ':', 'b', '::', 'c'])
test(r"""sre.split(r"(?::*)", ":a:b::c")""", ['', 'a', 'b', 'c'])
test(r"""sre.split(r"(:)*", ":a:b::c")""", ['', ':', 'a', ':', 'b', ':', 'c'])
test(r"""sre.split(r"([b:]+)", ":a:b::c")""", ['', ':', 'a', ':b::', 'c'])
test(r"""sre.split(r"(b)|(:+)", ":a:b::c")""",
['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c'])
test(r"""sre.split(r"(?:b)|(?::+)", ":a:b::c")""", ['', 'a', '', '', 'c'])
test(r"""sre.split(r":", ":a:b::c", 2)""", ['', 'a', 'b::c'])
test(r"""sre.split(r':', 'a:b:c:d', 2)""", ['a', 'b', 'c:d'])
test(r"""sre.split(r"(:)", ":a:b::c", 2)""", ['', ':', 'a', ':', 'b::c'])
test(r"""sre.split(r"(:*)", ":a:b::c", 2)""", ['', ':', 'a', ':', 'b::c'])
if verbose:
print "Running tests on sre.findall"
test(r"""sre.findall(r":+", "abc")""", [])
test(r"""sre.findall(r":+", "a:b::c:::d")""", [":", "::", ":::"])
test(r"""sre.findall(r"(:+)", "a:b::c:::d")""", [":", "::", ":::"])
test(r"""sre.findall(r"(:)(:*)", "a:b::c:::d")""",
[(":", ""), (":", ":"), (":", "::")])
test(r"""sre.findall(r"(a)|(b)", "abc")""", [("a", ""), ("", "b")])
# bug 117612
test(r"""sre.findall(r"(a|(b))", "aba")""", [("a", ""),("b", "b"),("a", "")])
if sys.hexversion >= 0x02020000:
if verbose:
print "Running tests on sre.finditer"
def fixup(seq):
# convert iterator to list
if not hasattr(seq, "next") or not hasattr(seq, "__iter__"):
print "finditer returned", type(seq)
return map(lambda item: item.group(0), seq)
# sanity
test(r"""fixup(sre.finditer(r":+", "a:b::c:::d"))""", [":", "::", ":::"])
if verbose:
print "Running tests on sre.match"
test(r"""sre.match(r'a', 'a').groups()""", ())
test(r"""sre.match(r'(a)', 'a').groups()""", ('a',))
test(r"""sre.match(r'(a)', 'a').group(0)""", 'a')
test(r"""sre.match(r'(a)', 'a').group(1)""", 'a')
test(r"""sre.match(r'(a)', 'a').group(1, 1)""", ('a', 'a'))
pat = sre.compile(r'((a)|(b))(c)?')
test(r"""pat.match('a').groups()""", ('a', 'a', None, None))
test(r"""pat.match('b').groups()""", ('b', None, 'b', None))
test(r"""pat.match('ac').groups()""", ('a', 'a', None, 'c'))
test(r"""pat.match('bc').groups()""", ('b', None, 'b', 'c'))
test(r"""pat.match('bc').groups("")""", ('b', "", 'b', 'c'))
pat = sre.compile(r'(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
test(r"""pat.match('a').group(1, 2, 3)""", ('a', None, None))
test(r"""pat.match('b').group('a1', 'b2', 'c3')""", (None, 'b', None))
test(r"""pat.match('ac').group(1, 'b2', 3)""", ('a', None, 'c'))
# bug 448951 (similar to 429357, but with single char match)
# (Also test greedy matches.)
for op in '','?','*':
test(r"""sre.match(r'((.%s):)?z', 'z').groups()"""%op, (None, None))
test(r"""sre.match(r'((.%s):)?z', 'a:z').groups()"""%op, ('a:', 'a'))
if verbose:
print "Running tests on sre.escape"
p = ""
for i in range(0, 256):
p = p + chr(i)
test(r"""sre.match(sre.escape(chr(i)), chr(i)) is not None""", 1)
test(r"""sre.match(sre.escape(chr(i)), chr(i)).span()""", (0,1))
pat = sre.compile(sre.escape(p))
test(r"""pat.match(p) is not None""", 1)
test(r"""pat.match(p).span()""", (0,256))
if verbose:
print 'Running tests on sre.Scanner'
def s_ident(scanner, token): return token
def s_operator(scanner, token): return "op%s" % token
def s_float(scanner, token): return float(token)
def s_int(scanner, token): return int(token)
scanner = sre.Scanner([
(r"[a-zA-Z_]\w*", s_ident),
(r"\d+\.\d*", s_float),
(r"\d+", s_int),
(r"=|\+|-|\*|/", s_operator),
(r"\s+", None),
])
# sanity check
test('scanner.scan("sum = 3*foo + 312.50 + bar")',
(['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], ''))
if verbose:
print 'Pickling a SRE_Pattern instance'
try:
import pickle
pat = sre.compile(r'a(?:b|(c|e){1,2}?|d)+?(.)')
s = pickle.dumps(pat)
pat = pickle.loads(s)
except:
print TestFailed, 're module pickle'
try:
import cPickle
pat = sre.compile(r'a(?:b|(c|e){1,2}?|d)+?(.)')
s = cPickle.dumps(pat)
pat = cPickle.loads(s)
except:
print TestFailed, 're module cPickle'
# constants
test(r"""sre.I""", sre.IGNORECASE)
test(r"""sre.L""", sre.LOCALE)
test(r"""sre.M""", sre.MULTILINE)
test(r"""sre.S""", sre.DOTALL)
test(r"""sre.X""", sre.VERBOSE)
test(r"""sre.T""", sre.TEMPLATE)
test(r"""sre.U""", sre.UNICODE)
for flags in [sre.I, sre.M, sre.X, sre.S, sre.L, sre.T, sre.U]:
try:
r = sre.compile('^pattern$', flags)
except:
print 'Exception raised on flag', flags
if verbose:
print 'Test engine limitations'
# Try nasty case that overflows the straightforward recursive
# implementation of repeated groups.
test("sre.match('(x)*', 50000*'x').span()", (0, 50000), RuntimeError)
test("sre.match(r'(x)*y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
test("sre.match(r'(x)*?y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
from re_tests import *
if verbose:
print 'Running re_tests test suite'
else:
# To save time, only run the first and last 10 tests
#tests = tests[:10] + tests[-10:]
pass
for t in tests:
sys.stdout.flush()
pattern=s=outcome=repl=expected=None
if len(t)==5:
pattern, s, outcome, repl, expected = t
elif len(t)==3:
pattern, s, outcome = t
else:
raise ValueError, ('Test tuples should have 3 or 5 fields',t)
try:
obj=sre.compile(pattern)
except sre.error:
if outcome==SYNTAX_ERROR: pass # Expected a syntax error
else:
print '=== Syntax error:', t
except KeyboardInterrupt: raise KeyboardInterrupt
except:
print '*** Unexpected error ***', t
if verbose:
traceback.print_exc(file=sys.stdout)
else:
try:
result=obj.search(s)
except (sre.error), msg:
print '=== Unexpected exception', t, repr(msg)
if outcome==SYNTAX_ERROR:
print '=== Compiled incorrectly', t
elif outcome==FAIL:
if result is None: pass # No match, as expected
else: print '=== Succeeded incorrectly', t
elif outcome==SUCCEED:
if result is not None:
# Matched, as expected, so now we compute the
# result string and compare it to our expected result.
start, end = result.span(0)
vardict={'found': result.group(0),
'groups': result.group(),
'flags': result.re.flags}
for i in range(1, 100):
try:
gi = result.group(i)
# Special hack because else the string concat fails:
if gi is None:
gi = "None"
except IndexError:
gi = "Error"
vardict['g%d' % i] = gi
for i in result.re.groupindex.keys():
try:
gi = result.group(i)
if gi is None:
gi = "None"
except IndexError:
gi = "Error"
vardict[i] = gi
repl=eval(repl, vardict)
if repl!=expected:
print '=== grouping error', t,
print repr(repl)+' should be '+repr(expected)
else:
print '=== Failed incorrectly', t
continue
# Try the match on a unicode string, and check that it
# still succeeds.
try:
u = unicode(s, "latin-1")
except NameError:
pass
except TypeError:
continue # skip unicode test strings
else:
result=obj.search(u)
if result==None:
print '=== Fails on unicode match', t
# Try the match on a unicode pattern, and check that it
# still succeeds.
try:
u = unicode(pattern, "latin-1")
except NameError:
pass
else:
obj=sre.compile(u)
result=obj.search(s)
if result==None:
print '=== Fails on unicode pattern match', t
# Try the match with the search area limited to the extent
# of the match and see if it still succeeds. \B will
# break (because it won't match at the end or start of a
# string), so we'll ignore patterns that feature it.
if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
obj=sre.compile(pattern)
result=obj.search(s, result.start(0), result.end(0)+1)
if result==None:
print '=== Failed on range-limited match', t
# Try the match with | |
= Constraint(expr= m.x546 + 1.26558121681553*m.b948 <= 1.26558121681553)
m.c466 = Constraint(expr= m.x547 + 1.26558121681553*m.b949 <= 1.26558121681553)
m.c467 = Constraint(expr= m.x608 - 0.572481933717686*m.b947 <= 0)
m.c468 = Constraint(expr= m.x609 - 0.572481933717686*m.b948 <= 0)
m.c469 = Constraint(expr= m.x610 - 0.572481933717686*m.b949 <= 0)
m.c470 = Constraint(expr= m.x611 + 0.572481933717686*m.b947 <= 0.572481933717686)
m.c471 = Constraint(expr= m.x612 + 0.572481933717686*m.b948 <= 0.572481933717686)
m.c472 = Constraint(expr= m.x613 + 0.572481933717686*m.b949 <= 0.572481933717686)
m.c473 = Constraint(expr=(m.x614/(1e-6 + m.b950) - 0.65*log(1 + m.x548/(1e-6 + m.b950)))*(1e-6 + m.b950) <= 0)
m.c474 = Constraint(expr=(m.x615/(1e-6 + m.b951) - 0.65*log(1 + m.x549/(1e-6 + m.b951)))*(1e-6 + m.b951) <= 0)
m.c475 = Constraint(expr=(m.x616/(1e-6 + m.b952) - 0.65*log(1 + m.x550/(1e-6 + m.b952)))*(1e-6 + m.b952) <= 0)
m.c476 = Constraint(expr=(m.x614/(1e-6 + m.b950) - 0.65*log(1 + m.x560/(1e-6 + m.b950)))*(1e-6 + m.b950) <= 0)
m.c477 = Constraint(expr=(m.x615/(1e-6 + m.b951) - 0.65*log(1 + m.x561/(1e-6 + m.b951)))*(1e-6 + m.b951) <= 0)
m.c478 = Constraint(expr=(m.x616/(1e-6 + m.b952) - 0.65*log(1 + m.x562/(1e-6 + m.b952)))*(1e-6 + m.b952) <= 0)
m.c479 = Constraint(expr= m.x551 == 0)
m.c480 = Constraint(expr= m.x552 == 0)
m.c481 = Constraint(expr= m.x553 == 0)
m.c482 = Constraint(expr= m.x563 == 0)
m.c483 = Constraint(expr= m.x564 == 0)
m.c484 = Constraint(expr= m.x565 == 0)
m.c485 = Constraint(expr= m.x617 == 0)
m.c486 = Constraint(expr= m.x618 == 0)
m.c487 = Constraint(expr= m.x619 == 0)
m.c488 = Constraint(expr= m.x203 - m.x548 - m.x551 == 0)
m.c489 = Constraint(expr= m.x204 - m.x549 - m.x552 == 0)
m.c490 = Constraint(expr= m.x205 - m.x550 - m.x553 == 0)
m.c491 = Constraint(expr= m.x212 - m.x560 - m.x563 == 0)
m.c492 = Constraint(expr= m.x213 - m.x561 - m.x564 == 0)
m.c493 = Constraint(expr= m.x214 - m.x562 - m.x565 == 0)
m.c494 = Constraint(expr= m.x239 - m.x614 - m.x617 == 0)
m.c495 = Constraint(expr= m.x240 - m.x615 - m.x618 == 0)
m.c496 = Constraint(expr= m.x241 - m.x616 - m.x619 == 0)
m.c497 = Constraint(expr= m.x548 - 1.26558121681553*m.b950 <= 0)
m.c498 = Constraint(expr= m.x549 - 1.26558121681553*m.b951 <= 0)
m.c499 = Constraint(expr= m.x550 - 1.26558121681553*m.b952 <= 0)
m.c500 = Constraint(expr= m.x551 + 1.26558121681553*m.b950 <= 1.26558121681553)
m.c501 = Constraint(expr= m.x552 + 1.26558121681553*m.b951 <= 1.26558121681553)
m.c502 = Constraint(expr= m.x553 + 1.26558121681553*m.b952 <= 1.26558121681553)
m.c503 = Constraint(expr= m.x560 - 33.5*m.b950 <= 0)
m.c504 = Constraint(expr= m.x561 - 33.5*m.b951 <= 0)
m.c505 = Constraint(expr= m.x562 - 33.5*m.b952 <= 0)
m.c506 = Constraint(expr= m.x563 + 33.5*m.b950 <= 33.5)
m.c507 = Constraint(expr= m.x564 + 33.5*m.b951 <= 33.5)
m.c508 = Constraint(expr= m.x565 + 33.5*m.b952 <= 33.5)
m.c509 = Constraint(expr= m.x614 - 2.30162356062425*m.b950 <= 0)
m.c510 = Constraint(expr= m.x615 - 2.30162356062425*m.b951 <= 0)
m.c511 = Constraint(expr= m.x616 - 2.30162356062425*m.b952 <= 0)
m.c512 = Constraint(expr= m.x617 + 2.30162356062425*m.b950 <= 2.30162356062425)
m.c513 = Constraint(expr= m.x618 + 2.30162356062425*m.b951 <= 2.30162356062425)
m.c514 = Constraint(expr= m.x619 + 2.30162356062425*m.b952 <= 2.30162356062425)
m.c515 = Constraint(expr= - m.x566 + m.x620 == 0)
m.c516 = Constraint(expr= - m.x567 + m.x621 == 0)
m.c517 = Constraint(expr= - m.x568 + m.x622 == 0)
m.c518 = Constraint(expr= m.x569 == 0)
m.c519 = Constraint(expr= m.x570 == 0)
m.c520 = Constraint(expr= m.x571 == 0)
m.c521 = Constraint(expr= m.x623 == 0)
m.c522 = Constraint(expr= m.x624 == 0)
m.c523 = Constraint(expr= m.x625 == 0)
m.c524 = Constraint(expr= m.x215 - m.x566 - m.x569 == 0)
m.c525 = Constraint(expr= m.x216 - m.x567 - m.x570 == 0)
m.c526 = Constraint(expr= m.x217 - m.x568 - m.x571 == 0)
m.c527 = Constraint(expr= m.x242 - m.x620 - m.x623 == 0)
m.c528 = Constraint(expr= m.x243 - m.x621 - m.x624 == 0)
m.c529 = Constraint(expr= m.x244 - m.x622 - m.x625 == 0)
m.c530 = Constraint(expr= m.x566 - 9*m.b953 <= 0)
m.c531 = Constraint(expr= m.x567 - 9*m.b954 <= 0)
m.c532 = Constraint(expr= m.x568 - 9*m.b955 <= 0)
m.c533 = Constraint(expr= m.x569 + 9*m.b953 <= 9)
m.c534 = Constraint(expr= m.x570 + 9*m.b954 <= 9)
m.c535 = Constraint(expr= m.x571 + 9*m.b955 <= 9)
m.c536 = Constraint(expr= m.x620 - 9*m.b953 <= 0)
m.c537 = Constraint(expr= m.x621 - 9*m.b954 <= 0)
m.c538 = Constraint(expr= m.x622 - 9*m.b955 <= 0)
m.c539 = Constraint(expr= m.x623 + 9*m.b953 <= 9)
m.c540 = Constraint(expr= m.x624 + 9*m.b954 <= 9)
m.c541 = Constraint(expr= m.x625 + 9*m.b955 <= 9)
m.c542 = Constraint(expr= - m.x572 + m.x626 == 0)
m.c543 = Constraint(expr= - m.x573 + m.x627 == 0)
m.c544 = Constraint(expr= - m.x574 + m.x628 == 0)
m.c545 = Constraint(expr= m.x575 == 0)
m.c546 = Constraint(expr= m.x576 == 0)
m.c547 = Constraint(expr= m.x577 == 0)
m.c548 = Constraint(expr= m.x629 == 0)
m.c549 = Constraint(expr= m.x630 == 0)
m.c550 = Constraint(expr= m.x631 == 0)
m.c551 = Constraint(expr= m.x218 - m.x572 - m.x575 == 0)
m.c552 = Constraint(expr= m.x219 - m.x573 - m.x576 == 0)
m.c553 = Constraint(expr= m.x220 - m.x574 - m.x577 == 0)
m.c554 = Constraint(expr= m.x245 - m.x626 - m.x629 == 0)
m.c555 = Constraint(expr= m.x246 - m.x627 - m.x630 == 0)
m.c556 = Constraint(expr= m.x247 - m.x628 - m.x631 == 0)
m.c557 = Constraint(expr= m.x572 - 9*m.b956 <= 0)
m.c558 = Constraint(expr= m.x573 - 9*m.b957 <= 0)
m.c559 = Constraint(expr= m.x574 - 9*m.b958 <= 0)
m.c560 = Constraint(expr= m.x575 + 9*m.b956 <= 9)
m.c561 = Constraint(expr= m.x576 + 9*m.b957 <= 9)
m.c562 = Constraint(expr= m.x577 + 9*m.b958 <= 9)
m.c563 = Constraint(expr= m.x626 - 9*m.b956 <= 0)
m.c564 = Constraint(expr= m.x627 - 9*m.b957 <= 0)
m.c565 = Constraint(expr= m.x628 - 9*m.b958 <= 0)
m.c566 = Constraint(expr= m.x629 + 9*m.b956 <= 9)
m.c567 = Constraint(expr= m.x630 + 9*m.b957 <= 9)
m.c568 = Constraint(expr= m.x631 + 9*m.b958 <= 9)
m.c569 = Constraint(expr=(m.x632/(1e-6 + m.b959) - 0.75*log(1 + m.x578/(1e-6 + m.b959)))*(1e-6 + m.b959) <= 0)
m.c570 = Constraint(expr=(m.x633/(1e-6 + m.b960) - 0.75*log(1 + m.x579/(1e-6 + m.b960)))*(1e-6 + m.b960) <= 0)
m.c571 = Constraint(expr=(m.x634/(1e-6 + m.b961) - 0.75*log(1 + m.x580/(1e-6 + m.b961)))*(1e-6 + m.b961) <= 0)
m.c572 = Constraint(expr= m.x581 == 0)
m.c573 = Constraint(expr= m.x582 == 0)
m.c574 = Constraint(expr= m.x583 == 0)
m.c575 = Constraint(expr= m.x635 == 0)
m.c576 = Constraint(expr= m.x636 == 0)
m.c577 = Constraint(expr= m.x637 == 0)
m.c578 = Constraint(expr= m.x221 - m.x578 - m.x581 == 0)
m.c579 = Constraint(expr= m.x222 - m.x579 - m.x582 == 0)
m.c580 = Constraint(expr= m.x223 - m.x580 - m.x583 == 0)
m.c581 = Constraint(expr= m.x248 - m.x632 - m.x635 == 0)
m.c582 = Constraint(expr= m.x249 - m.x633 - m.x636 == 0)
m.c583 = Constraint(expr= m.x250 - m.x634 - m.x637 == 0)
m.c584 = Constraint(expr= m.x578 - 3.04984759446376*m.b959 <= 0)
m.c585 = Constraint(expr= m.x579 - 3.04984759446376*m.b960 <= 0)
m.c586 = Constraint(expr= m.x580 - 3.04984759446376*m.b961 <= 0)
m.c587 = Constraint(expr= m.x581 + 3.04984759446376*m.b959 <= 3.04984759446376)
m.c588 = Constraint(expr= m.x582 + 3.04984759446376*m.b960 <= 3.04984759446376)
m.c589 = Constraint(expr= m.x583 + 3.04984759446376*m.b961 <= 3.04984759446376)
m.c590 = Constraint(expr= m.x632 - 1.04900943706034*m.b959 <= 0)
m.c591 = Constraint(expr= m.x633 - 1.04900943706034*m.b960 <= 0)
m.c592 = Constraint(expr= m.x634 - 1.04900943706034*m.b961 <= 0)
m.c593 = Constraint(expr= m.x635 + 1.04900943706034*m.b959 <= 1.04900943706034)
m.c594 = Constraint(expr= m.x636 + 1.04900943706034*m.b960 <= 1.04900943706034)
m.c595 = Constraint(expr= m.x637 + 1.04900943706034*m.b961 <= 1.04900943706034)
m.c596 = Constraint(expr=(m.x638/(1e-6 + m.b962) - 0.8*log(1 + m.x584/(1e-6 + m.b962)))*(1e-6 + m.b962) <= 0)
m.c597 = Constraint(expr=(m.x639/(1e-6 + m.b963) - 0.8*log(1 + m.x585/(1e-6 + m.b963)))*(1e-6 + m.b963) <= 0)
m.c598 = Constraint(expr=(m.x640/(1e-6 + m.b964) - 0.8*log(1 + m.x586/(1e-6 + m.b964)))*(1e-6 + m.b964) <= 0)
m.c599 = Constraint(expr= m.x587 == 0)
m.c600 = Constraint(expr= m.x588 == 0)
m.c601 = Constraint(expr= m.x589 == 0)
m.c602 = Constraint(expr= m.x641 == 0)
m.c603 = Constraint(expr= m.x642 == 0)
m.c604 = Constraint(expr= m.x643 == 0)
m.c605 = Constraint(expr= m.x224 - m.x584 - m.x587 == 0)
m.c606 = Constraint(expr= m.x225 - m.x585 - m.x588 == 0)
m.c607 = Constraint(expr= m.x226 - m.x586 - m.x589 == 0)
m.c608 = Constraint(expr= m.x251 - m.x638 - m.x641 == 0)
m.c609 = Constraint(expr= m.x252 - m.x639 - m.x642 == 0)
m.c610 = Constraint(expr= m.x253 - m.x640 - m.x643 == 0)
m.c611 = Constraint(expr= m.x584 - 3.04984759446376*m.b962 <= 0)
m.c612 = Constraint(expr= m.x585 - 3.04984759446376*m.b963 <= 0)
m.c613 = Constraint(expr= m.x586 - 3.04984759446376*m.b964 <= 0)
m.c614 = Constraint(expr= m.x587 + 3.04984759446376*m.b962 <= 3.04984759446376)
m.c615 = Constraint(expr= m.x588 + 3.04984759446376*m.b963 <= 3.04984759446376)
m.c616 = Constraint(expr= m.x589 + 3.04984759446376*m.b964 <= 3.04984759446376)
m.c617 = Constraint(expr= m.x638 - 1.11894339953103*m.b962 <= 0)
m.c618 = Constraint(expr= m.x639 - 1.11894339953103*m.b963 <= 0)
m.c619 = Constraint(expr= m.x640 - 1.11894339953103*m.b964 <= 0)
m.c620 = Constraint(expr= m.x641 + 1.11894339953103*m.b962 <= 1.11894339953103)
m.c621 = Constraint(expr= m.x642 + 1.11894339953103*m.b963 <= 1.11894339953103)
m.c622 = Constraint(expr= m.x643 + 1.11894339953103*m.b964 <= 1.11894339953103)
m.c623 = Constraint(expr=(m.x644/(1e-6 + m.b965) - 0.85*log(1 + m.x590/(1e-6 + m.b965)))*(1e-6 + m.b965) <= 0)
m.c624 = Constraint(expr=(m.x645/(1e-6 + m.b966) - 0.85*log(1 + m.x591/(1e-6 + m.b966)))*(1e-6 + m.b966) <= 0)
m.c625 = Constraint(expr=(m.x646/(1e-6 + m.b967) - 0.85*log(1 + m.x592/(1e-6 + m.b967)))*(1e-6 + m.b967) <= 0)
m.c626 = Constraint(expr= m.x593 == 0)
m.c627 = Constraint(expr= m.x594 == 0)
m.c628 = Constraint(expr= m.x595 == 0)
m.c629 = Constraint(expr= m.x647 == 0)
m.c630 = Constraint(expr= m.x648 == 0)
m.c631 = Constraint(expr= m.x649 == 0)
m.c632 = Constraint(expr= m.x227 - m.x590 - m.x593 == 0)
m.c633 = Constraint(expr= m.x228 | |
"""Tests for static validation."""
from datetime import datetime
import numpy as np
import pandas as pd
from delphi_validator.datafetcher import FILENAME_REGEX
from delphi_validator.report import ValidationReport
from delphi_validator.static import StaticValidator
class TestCheckMissingDates:
def test_empty_filelist(self):
params = {"data_source": "", "span_length": 8,
"end_date": "2020-09-09", "expected_lag": {}}
validator = StaticValidator(params)
report = ValidationReport([])
report = ValidationReport([])
filenames = list()
validator.check_missing_date_files(filenames, report)
assert len(report.raised_errors) == 1
assert "check_missing_date_files" in [
err.check_data_id[0] for err in report.raised_errors]
assert len(report.raised_errors[0].expression) == 9
def test_same_day(self):
params = {"data_source": "", "span_length": 0,
"end_date": "2020-09-01", "expected_lag": {}}
validator = StaticValidator(params)
report = ValidationReport([])
filenames = [("20200901_county_signal_signal.csv", "match_obj")]
validator.check_missing_date_files(filenames, report)
assert len(report.raised_errors) == 0
assert "check_missing_date_files" not in [
err.check_data_id[0] for err in report.raised_errors]
def test_duplicate_dates(self):
params = {"data_source": "", "span_length": 1,
"end_date": "2020-09-02", "expected_lag": {}}
validator = StaticValidator(params)
report = ValidationReport([])
filenames = [("20200901_county_signal_signal.csv", "match_obj"),
("20200903_county_signal_signal.csv", "match_obj"),
("20200903_usa_signal_signal.csv", "match_obj"),
("20200903_usa_signal_signal.csv", "match_obj")]
validator.check_missing_date_files(filenames, report)
assert len(report.raised_errors) == 1
assert "check_missing_date_files" in [
err.check_data_id[0] for err in report.raised_errors]
assert len([err.expression[0] for
err in report.raised_errors if err.check_data_id[0] ==
"check_missing_date_files"]) == 1
assert [err.expression[0] for
err in report.raised_errors if err.check_data_id[0] ==
"check_missing_date_files"][0] == datetime.strptime("20200902", "%Y%m%d").date()
class TestNameFormat:
def test_match_existence(self):
pattern_found = FILENAME_REGEX.match("20200903_usa_signal_signal.csv")
assert pattern_found
pattern_found = FILENAME_REGEX.match("2020090_usa_signal_signal.csv")
assert not pattern_found
pattern_found = FILENAME_REGEX.match("20200903_usa_signal_signal.pdf")
assert not pattern_found
pattern_found = FILENAME_REGEX.match("20200903_usa_.csv")
assert not pattern_found
def test_expected_groups(self):
pattern_found = FILENAME_REGEX.match(
"20200903_usa_signal_signal.csv").groupdict()
assert pattern_found["date"] == "20200903"
assert pattern_found["geo_type"] == "usa"
assert pattern_found["signal"] == "signal_signal"
class TestCheckBadGeoIdFormat:
params = {"data_source": "", "span_length": 0,
"end_date": "2020-09-02", "expected_lag": {}}
def test_empty_df(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
empty_df = pd.DataFrame(columns=["geo_id"], dtype=str)
validator.check_bad_geo_id_format(empty_df, "name", "county", report)
assert len(report.raised_errors) == 0
def test_invalid_geo_type(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
empty_df = pd.DataFrame(columns=["geo_id"], dtype=str)
validator.check_bad_geo_id_format(empty_df, "name", "hello", report)
assert len(report.raised_errors) == 1
assert "check_geo_type" in [
err.check_data_id[0] for err in report.raised_errors]
assert [err.expression for
err in report.raised_errors if err.check_data_id[0] ==
"check_geo_type"][0] == "hello"
def test_invalid_geo_id_county(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["0", "54321", "123", ".0000",
"abc12"], columns=["geo_id"])
validator.check_bad_geo_id_format(df, "name", "county", report)
assert len(report.raised_errors) == 1
assert "check_geo_id_format" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 2
assert "54321" not in report.raised_errors[0].expression
def test_invalid_geo_id_msa(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["0", "54321", "123", ".0000",
"abc12"], columns=["geo_id"])
validator.check_bad_geo_id_format(df, "name", "msa", report)
assert len(report.raised_errors) == 1
assert "check_geo_id_format" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 2
assert "54321" not in report.raised_errors[0].expression
def test_invalid_geo_id_hrr(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["1", "12", "123", "1234", "12345",
"a", ".", "ab1"], columns=["geo_id"])
validator.check_bad_geo_id_format(df, "name", "hrr", report)
assert len(report.raised_errors) == 1
assert "check_geo_id_format" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 5
assert "1" not in report.raised_errors[0].expression
assert "12" not in report.raised_errors[0].expression
assert "123" not in report.raised_errors[0].expression
def test_invalid_geo_id_state(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["aa", "hi", "HI", "hawaii",
"Hawaii", "a", "H.I."], columns=["geo_id"])
validator.check_bad_geo_id_format(df, "name", "state", report)
assert len(report.raised_errors) == 1
assert "check_geo_id_format" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 4
assert "aa" not in report.raised_errors[0].expression
assert "hi" not in report.raised_errors[0].expression
assert "HI" not in report.raised_errors[0].expression
def test_invalid_geo_id_national(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["usa", "SP", " us", "us",
"usausa", "US"], columns=["geo_id"])
validator.check_bad_geo_id_format(df, "name", "national", report)
assert len(report.raised_errors) == 1
assert "check_geo_id_format" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 3
assert "us" not in report.raised_errors[0].expression
assert "US" not in report.raised_errors[0].expression
assert "SP" not in report.raised_errors[0].expression
class TestDuplicatedRows:
params = {"data_source": "", "span_length": 1,
"end_date": "2020-09-02", "expected_lag": {}}
def test_no_duplicates(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([["a", "1"], ["b", "2"], ["c", "3"]])
validator.check_duplicate_rows(df, "file", report)
assert len(report.raised_warnings) == 0
def test_single_column_duplicates_but_not_row(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([["a", "1"], ["a", "2"], ["b", "2"]])
validator.check_duplicate_rows(df, "file", report)
assert len(report.raised_warnings) == 0
def test_non_consecutive_duplicates(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([["a", "1"], ["b", "2"], ["a", "1"]])
validator.check_duplicate_rows(df, "file", report)
assert len(report.raised_warnings) == 1
assert report.raised_warnings[0].expression == [2]
assert report.raised_warnings[0].check_data_id[1] == "file"
def test_multiple_distinct_duplicates(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([["a", "1"], ["b", "2"], ["a", "1"], ["b", "2"]])
validator.check_duplicate_rows(df, "file", report)
assert len(report.raised_warnings) == 1
assert report.raised_warnings[0].expression == [2, 3]
def test_more_than_two_copies(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([["a", "1"], ["b", "2"], ["b", "2"], ["b", "2"]])
validator.check_duplicate_rows(df, "file", report)
assert len(report.raised_warnings) == 1
assert report.raised_warnings[0].expression == [2, 3]
class TestCheckBadGeoIdValue:
params = {"data_source": "", "span_length": 0,
"end_date": "2020-09-02", "expected_lag": {},
"validator_static_file_dir": "../static"}
def test_empty_df(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
empty_df = pd.DataFrame(columns=["geo_id"], dtype=str)
validator.check_bad_geo_id_value(empty_df, "name", "county", report)
assert len(report.raised_errors) == 0
def test_invalid_geo_id_county(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["01001", "88888", "99999"], columns=["geo_id"])
validator.check_bad_geo_id_value(df, "name", "county", report)
assert len(report.raised_errors) == 1
assert "check_bad_geo_id_value" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 2
assert "01001" not in report.raised_errors[0].expression
assert "88888" in report.raised_errors[0].expression
assert "99999" in report.raised_errors[0].expression
def test_invalid_geo_id_msa(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["10180", "88888", "99999"], columns=["geo_id"])
validator.check_bad_geo_id_value(df, "name", "msa", report)
assert len(report.raised_errors) == 1
assert "check_bad_geo_id_value" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 2
assert "10180" not in report.raised_errors[0].expression
assert "88888" in report.raised_errors[0].expression
assert "99999" in report.raised_errors[0].expression
def test_invalid_geo_id_hrr(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["1", "11", "111", "8", "88",
"888"], columns=["geo_id"])
validator.check_bad_geo_id_value(df, "name", "hrr", report)
assert len(report.raised_errors) == 1
assert "check_bad_geo_id_value" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 3
assert "1" not in report.raised_errors[0].expression
assert "11" not in report.raised_errors[0].expression
assert "111" not in report.raised_errors[0].expression
assert "8" in report.raised_errors[0].expression
assert "88" in report.raised_errors[0].expression
assert "888" in report.raised_errors[0].expression
def test_invalid_geo_id_state(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["aa", "ak"], columns=["geo_id"])
validator.check_bad_geo_id_value(df, "name", "state", report)
assert len(report.raised_errors) == 1
assert "check_bad_geo_id_value" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 1
assert "ak" not in report.raised_errors[0].expression
assert "aa" in report.raised_errors[0].expression
def test_uppercase_geo_id(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["ak", "AK"], columns=["geo_id"])
validator.check_bad_geo_id_value(df, "name", "state", report)
assert len(report.raised_errors) == 0
assert len(report.raised_warnings) == 1
assert "check_geo_id_lowercase" in report.raised_warnings[0].check_data_id
assert "AK" in report.raised_warnings[0].expression
def test_invalid_geo_id_national(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame(["us", "zz"], columns=["geo_id"])
validator.check_bad_geo_id_value(df, "name", "national", report)
assert len(report.raised_errors) == 1
assert "check_bad_geo_id_value" in report.raised_errors[0].check_data_id
assert len(report.raised_errors[0].expression) == 1
assert "us" not in report.raised_errors[0].expression
assert "zz" in report.raised_errors[0].expression
class TestCheckBadVal:
params = {"data_source": "", "span_length": 1,
"end_date": "2020-09-02", "expected_lag": {}}
def test_empty_df(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
empty_df = pd.DataFrame(columns=["val"])
validator.check_bad_val(empty_df, "", "", report)
validator.check_bad_val(empty_df, "", "prop", report)
validator.check_bad_val(empty_df, "", "pct", report)
assert len(report.raised_errors) == 0
def test_missing(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([np.nan], columns=["val"])
validator.check_bad_val(df, "name", "signal", report)
assert len(report.raised_errors) == 1
assert "check_val_missing" in report.raised_errors[0].check_data_id
def test_lt_0(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([-5], columns=["val"])
validator.check_bad_val(df, "name", "signal", report)
assert len(report.raised_errors) == 1
assert "check_val_lt_0" in report.raised_errors[0].check_data_id
def test_gt_max_pct(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([1e7], columns=["val"])
validator.check_bad_val(df, "name", "pct", report)
assert len(report.raised_errors) == 1
assert "check_val_pct_gt_100" in report.raised_errors[0].check_data_id
def test_gt_max_prop(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
df = pd.DataFrame([1e7], columns=["val"])
validator.check_bad_val(df, "name", "prop", report)
assert len(report.raised_errors) == 1
assert "check_val_prop_gt_100k" in report.raised_errors[0].check_data_id
class TestCheckBadSe:
params = {"data_source": "", "span_length": 1,
"end_date": "2020-09-02", "expected_lag": {}}
def test_empty_df(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
empty_df = pd.DataFrame(
columns=["val", "se", "sample_size"], dtype=float)
validator.check_bad_se(empty_df, "", report)
assert len(report.raised_errors) == 0
validator.params.missing_se_allowed = True
validator.check_bad_se(empty_df, "", report)
assert len(report.raised_errors) == 0
def test_missing(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
validator.params.missing_se_allowed = True
df = pd.DataFrame([[np.nan, np.nan, np.nan]], columns=[
"val", "se", "sample_size"])
validator.check_bad_se(df, "name", report)
assert len(report.raised_errors) == 0
validator.params.missing_se_allowed = False
validator.check_bad_se(df, "name", report)
assert len(report.raised_errors) == 2
assert "check_se_not_missing_and_in_range" in [
err.check_data_id[0] for err in report.raised_errors]
assert "check_se_many_missing" in [
err.check_data_id[0] for err in report.raised_errors]
def test_e_0_missing_allowed(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
validator.params.missing_se_allowed = True
df = pd.DataFrame([[1, 0, 200], [1, np.nan, np.nan], [
1, np.nan, np.nan]], columns=["val", "se", "sample_size"])
validator.check_bad_se(df, "name", report)
assert len(report.raised_errors) == 2
assert "check_se_missing_or_in_range" in [
err.check_data_id[0] for err in report.raised_errors]
assert "check_se_0" in [
err.check_data_id[0] for err in report.raised_errors]
def test_e_0_missing_not_allowed(self):
validator = StaticValidator(self.params)
report = ValidationReport([])
validator.params.missing_se_allowed = False
df = pd.DataFrame([[1, 0, 200], [1, 0, np.nan], [
1, np.nan, np.nan]], columns=["val", "se", "sample_size"])
validator.check_bad_se(df, "name", report)
assert len(report.raised_errors) == 2
assert "check_se_not_missing_and_in_range" in [
err.check_data_id[0] for err in report.raised_errors]
assert "check_se_0" in [
err.check_data_id[0] for err in report.raised_errors]
| |
= subtenant + '/' + uid
if (apiType == 'N'):
uri = URI_ATMOS_NAMESPACE_PATH.format(keypath)
else :
uri = URI_ATMOS_OBJECTS_OID.format(keypath)
print uri
content_type = '*/*'
self._headers['x-emc-signature'] = self.atmos_hmac_base64_sig('GET', content_type, uri+'?acl', self._headers['date'], secret)
response = self.coreapi('GET', uri, qparms = {'acl':None}, content_type = '*/*')
self.checkAtmosResponse(response)
return response
@resetHeaders
def atmos_key_setacl(self, namespace, project, subtenant, keypath, apiType, useracl, groupacl, uid, secret):
self._headers['date'] = formatdate()
self._headers['x-emc-uid'] = subtenant + '/' + uid
if (useracl):
self._headers['x-emc-useracl'] = useracl
if (groupacl):
self._headers['x-emc-groupacl'] = groupacl
if (apiType == 'N'):
uri = URI_ATMOS_NAMESPACE_PATH.format(keypath)
else :
uri = URI_ATMOS_OBJECTS_OID.format(keypath)
print uri
content_type = '*/*'
self._headers['x-emc-signature'] = self.atmos_hmac_base64_sig('POST', content_type, uri+'?acl', self._headers['date'], secret)
response = self.coreapi('POST', uri, qparms = {'acl':None}, content_type = '*/*')
self.checkAtmosResponse(response)
return response
def security_add_zone_role(self, objecttype, objectname, role):
if( not objecttype in ['subject_id', 'group']):
raise Exception('type must be subject_id or group')
if( not role in ['SYSTEM_MONITOR','SYSTEM_AUDITOR','SYSTEM_ADMIN','SECURITY_ADMIN','TENANT_ADMIN',]):
raise Exception('role must be SYSTEM_MONITOR, SYSTEM_AUDITOR, SYSTEM_ADMIN, SECURITY_ADMIN, or TENANT_ADMIN')
parms = {
"add" : [ { "role" : [role], objecttype : objectname }]
}
print parms
response = self.__api('PUT', URI_VDC_ROLES, parms)
if (response.status_code != 200):
print "security assign role failed with code: ", response.status_code
raise Exception('security assign role: failed')
def _mpu_parse_init_response(self, payload):
root = ET.fromstring(payload)
inittag = '{' + S3_XML_NS + '}InitiateMultipartUploadResult'
buckettag = '{' + S3_XML_NS + '}Bucket'
keytag = '{' + S3_XML_NS + '}Key'
uploadidtag = '{' + S3_XML_NS + '}UploadId'
if root.tag != inittag:
print "invalid response payload", payload
raise Exception('Invalid response, no InitiateMultipartUploadResult')
bucket = root.find(buckettag).text
key = root.find(keytag).text
uploadid = root.find(uploadidtag).text
return {"bucket" : bucket, "key" : key, "uploadId" : uploadid}
@resetHeaders
def bucket_initiate_mpu(self, namespace, bucket, key, uid, secret):
qparms = {'uploads':None}
self._set_auth_and_ns_header('POST', namespace, bucket, key, uid, secret, parameters_to_sign = qparms)
uri = self._get_s3_key_uri(bucket, key)
response = self.coreapi('POST', uri, None, qparms , content_type=CONTENT_TYPE_XML)
if response.status_code != HTTP_OK:
print "failure", response
raise Exception('failed to initiate mpu!')
return self._mpu_parse_init_response(response.text)
@resetHeaders
def bucket_upload_mpu(self, namespace, bucket, key, uid, secret, uploadId, partNum):
qparms = {'uploadId':uploadId, 'partNumber':str(partNum)}
self._set_auth_and_ns_header('PUT', namespace, bucket, key, uid, secret, CONTENT_TYPE_OCTET, parameters_to_sign = qparms)
uri = self._get_s3_key_uri(bucket, key)
value = str(uuid.uuid4())
for i in range(100):
value = value + str(uuid.uuid4())
md5str = self._computeMD5(value)
response = self.coreapi('PUT', uri, value, qparms, content_type=CONTENT_TYPE_OCTET)
if response.status_code != HTTP_OK:
print "failure", response
raise Exception('failed to upload a part for mpu!')
self._checkETag(response, md5str)
return response.headers['ETag']
@resetHeaders
def bucket_copy_part(self, namespace, bucket, key, srcbucket, srckey, uid, secret,
uploadId, partNum):
qparms = {'uploadId':uploadId, 'partNumber':str(partNum)}
self._headers['x-amz-copy-source'] = URI_S3_KEY_INSTANCE.format(urllib.quote_plus(srcbucket), urllib.quote_plus(srckey))
self._set_auth_and_ns_header('PUT', namespace, bucket, key, uid, secret, CONTENT_TYPE_OCTET, parameters_to_sign = qparms)
uri = self._get_s3_key_uri(bucket, key)
response = self.coreapi('PUT', uri, None, qparms, content_type=CONTENT_TYPE_OCTET)
if response.status_code != HTTP_OK:
print "failure", response
raise Exception('failed to upload a part for mpu!')
# parse and return etag from response
print "got response: %s" % response.text
tree = ET.fromstring(response.text)
etag = tree.findtext('./{' + S3_XML_NS + '}ETag')
return etag
def _build_complete_mpu_payload(self, etagdict):
root = ET.Element('CompleteMultipartUpload')
root.set('xmlns', S3_XML_NS)
# Note, the part list should be in ascending order
sorted_keys = etagdict.keys()
for key in sorted_keys:
partElem = ET.SubElement(root, 'Part')
ET.SubElement(partElem, 'PartNumber').text = str(key)
ET.SubElement(partElem, 'ETag').text = etagdict[key]
return ET.tostring(root)
def _parse_complete_mpu_response(self, response):
version = None
if 'x-amz-version-id' in response.headers:
version = response.headers['x-amz-version-id']
payload = response.text
root = ET.fromstring(payload)
completetag = '{' + S3_XML_NS + '}CompleteMultipartUploadResult'
uritag = '{' + S3_XML_NS + '}Location'
buckettag = '{' + S3_XML_NS + '}Bucket'
keytag = '{' + S3_XML_NS + '}Key'
etagtag = '{' + S3_XML_NS + '}ETag'
if root.tag != completetag:
print "invalid response", response
raise Exception('Invalid response, no CompleteMultipartUploadResult')
bucket = root.find(buckettag).text
key = root.find(keytag).text
uri = root.find(uritag).text
etag = root.find(etagtag).text
return {'version':version, 'etag':etag, 'uri':uri, 'key':key, 'bucket':bucket}
def _parse_list_mpu_parts_response(self, payload):
result = {}
root = ET.fromstring(payload)
listtag = '{' + S3_XML_NS + '}ListPartsResult'
buckettag = '{' + S3_XML_NS + '}Bucket'
keytag = '{' + S3_XML_NS + '}Key'
if root.tag != listtag:
print "invalid response payload", payload
raise Exception('Invalid response, no ListPartsResult')
result['bucket'] = root.find(buckettag).text
result['key'] = root.find(keytag).text
initiatortag = '{' + S3_XML_NS + '}Initiator'
idtag = '{' + S3_XML_NS + '}ID'
nametag = '{' + S3_XML_NS + '}DisplayName'
ownertag= '{' + S3_XML_NS + '}Owner'
initiator = root.find(initiatortag)
print "debug initiator = ",initiator
result['initiator'] = {'id':initiator.find(idtag).text, 'name':initiator.find(nametag).text}
owner = root.find(ownertag)
result['owner'] = {'id':owner.find(idtag).text, 'name':owner.find(nametag).text}
maxtag = '{' + S3_XML_NS + '}MaxParts'
markertag = '{' + S3_XML_NS + '}PartNumberMarker'
nexttag = '{' + S3_XML_NS + '}NextPartNumberMarker'
trunctag = '{' + S3_XML_NS + '}IsTruncated'
result['maxparts'] = root.find(maxtag).text
if None != root.find(markertag):
result['marker'] = root.find(markertag).text
result['truncated'] = root.find(trunctag).text
if None != root.find(nexttag):
result['nextmarker'] = root.find(nexttag).text
parttag = '{' + S3_XML_NS + '}Part'
etagtag = '{' + S3_XML_NS + '}ETag'
sizetag = '{' + S3_XML_NS + '}Size'
mtimetag = '{' + S3_XML_NS + '}LastModified'
partnumtag = '{' + S3_XML_NS + '}PartNumber'
index = 1
parts = []
for part in root.findall(parttag):
partdict = {}
partdict['num'] = part.find(partnumtag).text
partdict['etag'] = part.find(etagtag).text
partdict['mtime'] = part.find(mtimetag).text
partdict['size'] = part.find(sizetag).text
parts.append(partdict)
result['parts'] = parts
return result
def _parse_list_mpu_uploads_response(self, payload):
result = {}
root = ET.fromstring(payload)
list_tag = '{' + S3_XML_NS + '}ListMultipartUploadsResult'
bucket_tag = '{' + S3_XML_NS + '}Bucket'
keymarker_tag = '{' + S3_XML_NS + '}KeyMarker'
uploadidmarker_tag = '{' + S3_XML_NS + '}UploadIdMarker'
nextkeymarker_tag = '{' + S3_XML_NS + '}NextKeyMarker'
nextuploadidmarker_tag = '{' + S3_XML_NS + '}NextUploadIdMarker'
maxuploads_tag = '{' + S3_XML_NS + '}MaxUploads'
delimiter_tag = '{' + S3_XML_NS + '}Delimiter'
prefix_tag = '{' + S3_XML_NS + '}Prefix'
commonprefixes_tag = '{' + S3_XML_NS + '}CommonPrefixes'
istruncated_tag = '{' + S3_XML_NS + '}IsTruncated'
upload_tag = '{' + S3_XML_NS + '}Upload'
if root.tag != list_tag:
print "invalid response payload", payload
raise Exception('Invalid response, no ListMultipartUploadsResult')
result['bucket'] = root.find(bucket_tag).text
if None != root.find(keymarker_tag):
result['keymarker'] = root.find(keymarker_tag).text
if None != root.find(uploadidmarker_tag):
result['uploadidmarker'] = root.find(uploadidmarker_tag).text
if None != root.find(nextkeymarker_tag):
result['nextkeymarker'] = root.find(nextkeymarker_tag).text
if None != root.find(nextuploadidmarker_tag):
result['nextuploadidmarker'] = root.find(nextuploadidmarker_tag).text
if None != root.find(maxuploads_tag):
result['maxuploads'] = root.find(maxuploads_tag).text
if None != root.find(delimiter_tag):
result['delimiter'] = root.find(delimiter_tag).text
if None != root.find(prefix_tag):
result['prefix'] = root.find(prefix_tag).text
if None != root.find(istruncated_tag):
result['istruncated'] = root.find(istruncated_tag).text
uploads = []
for upload in root.findall(upload_tag):
uploaddict = {}
key_tag = '{' + S3_XML_NS + '}Key'
uploadid_tag = '{' + S3_XML_NS + '}UploadId'
initiator_tag = '{' + S3_XML_NS + '}Initiator'
id_tag = '{' + S3_XML_NS + '}ID'
name_tag = '{' + S3_XML_NS + '}DisplayName'
owner_tag= '{' + S3_XML_NS + '}Owner'
initated_tag = '{' + S3_XML_NS + '}Initiated'
initiator = root.find(initiator_tag)
if None != initiator:
uploaddict['initiator'] = {'id':initiator.find(id_tag).text, 'name':initiator.find(name_tag).text}
owner = root.find(owner_tag)
if None != owner:
uploaddict['owner'] = {'id':owner.find(id_tag).text, 'name':owner.find(name_tag).text}
uploaddict['key'] = upload.find(key_tag).text
uploaddict['uploadid'] = upload.find(uploadid_tag).text
uploads.append(uploaddict)
result['uploads'] = uploads
commonPrefixes = []
for prefix in root.findall(commonprefixes_tag):
commonPrefixes.append({'prefix':prefix.find(prefix_tag).text})
result['commonPrefixes'] = commonPrefixes
return result
@resetHeaders
def bucket_complete_mpu(self, namespace, bucket, key, uid, secret, uploadId, etagdict):
qparms = {'uploadId':uploadId}
self._set_auth_and_ns_header('POST', namespace, bucket, key, uid, secret, CONTENT_TYPE_XML, parameters_to_sign = qparms)
uri = self._get_s3_key_uri(bucket, key)
parms = self._build_complete_mpu_payload(etagdict)
response = self.coreapi('POST', uri, parms, qparms, content_type=CONTENT_TYPE_XML)
if response.status_code != HTTP_OK:
print "failure", response
raise Exception('failed to complete mpu!')
return self._parse_complete_mpu_response(response)
@resetHeaders
def bucket_abort_mpu(self, namespace, bucket, key, uid, secret, uploadId):
qparms = {'uploadId':uploadId}
self._set_auth_and_ns_header('DELETE', namespace, bucket, key, uid, secret, CONTENT_TYPE_XML, parameters_to_sign = qparms)
uri = self._get_s3_key_uri(bucket, key)
response = self.coreapi('DELETE', uri, None, qparms, content_type=CONTENT_TYPE_XML)
if response.status_code != HTTP_OK and response.status_code != HTTP_NO_CONTENT:
print "failure", response
raise Exception('failed to abort mpu!')
return response
@resetHeaders
def bucket_list_mpu_parts(self, namespace, bucket, key, uid, secret, uploadId, maxParts, partNumMarker):
qparms = {'uploadId':uploadId}
parameters_to_sign = {'uploadId':uploadId}
if None != maxParts:
qparms['max-parts'] = maxParts
if None != partNumMarker:
qparms['part-number-marker'] = partNumMarker
self._set_auth_and_ns_header('GET', namespace, bucket, key, uid, secret, CONTENT_TYPE_XML, parameters_to_sign)
uri = self._get_s3_key_uri(bucket, key)
response = self.coreapi('GET', uri, None, qparms, content_type=CONTENT_TYPE_XML)
if response.status_code != HTTP_OK:
print "failure", response
raise Exception('failed to list mpu parts!')
return self._parse_list_mpu_parts_response(response.text)
@resetHeaders
def bucket_list_mpu_uploads(self, namespace, bucket, uid, secret, maxUploads, keyMarker, uploadIdMarker, delimiter, prefix):
parameters_to_sign = {'uploads':None}
qparms = {'uploads':None}
if keyMarker != None:
qparms['key-marker'] = keyMarker
if uploadIdMarker != None:
qparms['upload-id-marker'] = uploadIdMarker
if maxUploads != None:
qparms['max-uploads'] = maxUploads
if delimiter != None:
qparms['delimiter'] = delimiter
if prefix != None:
qparms['prefix'] = prefix
self._set_auth_and_ns_header('GET', namespace, bucket, None, uid, secret, CONTENT_TYPE_XML, | |
<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# # Generate [dividiti](http://dividiti.com)'s submissions to [MLPerf Inference v0.5](https://github.com/mlperf/inference/tree/master/v0.5)
# <a id="overview"></a>
# ## Overview
# This Jupyter notebook covers [dividiti](http://dividiti.com)'s submissions to [MLPerf Inference v0.5](https://github.com/mlperf/inference/tree/master/v0.5). It validates that experimental data obtained via automated, portable and reproducible [Collective Knowledge](http://cknowledge.org) workflows conforms to [General MLPerf Submission Rules](https://github.com/mlperf/policies/blob/master/submission_rules.adoc)
# and [MLPerf Inference Rules](https://github.com/mlperf/inference_policies/blob/master/inference_rules.adoc), including runnning the official [`submission_checker.py`](https://github.com/mlperf/inference/blob/master/v0.5/tools/submission/submission-checker.py).
# A live version of this Jupyter Notebook can be viewed [here](https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/1xlv5oacgobrfd4/mlperf-inference-v0.5-dividiti.ipynb).
# ## Table of Contents
# 1. [Overview](#overview)
# 1. [Includes](#includes)
# 1. [System templates](#templates)
# 1. [Firefly RK3399](#templates_firefly)
# 1. [Linaro HiKey960](#templates_hikey960)
# 1. [Huawei Mate 10 Pro](#templates_mate10pro)
# 1. [Raspberry Pi 4](#templates_rpi4)
# 1. [HP Z640](#templates_velociti)
# 1. [Default](#templates_default)
# 1. [Systems](#systems)
# 1. [Implementations](#implementations)
# 1. [Get the experimental data](#get)
# 1. [Image Classification - Closed](#get_image_classification_closed)
# 1. [Image Classification - Open](#get_image_classification_open)
# 1. [Object Detection - Open](#get_object_detection_open)
# 1. [Generate the submission checklist](#checklist)
# 1. [Check the experimental data](#check)
# <a id="includes"></a>
# ## Includes
# ### Standard
# In[ ]:
import os
import sys
import json
import re
from pprint import pprint
from shutil import copy2
from copy import deepcopy
# ### Scientific
# If some of the scientific packages are missing, please install them using:
# ```
# # python3 -m pip install jupyter pandas numpy matplotlib seaborn --user
# ```
# In[ ]:
import pandas as pd
import numpy as np
import subprocess
print ('Pandas version: %s' % pd.__version__)
print ('NumPy version: %s' % np.__version__)
# No need to hardcode e.g. as:
# sys.path.append('$CK_TOOLS/tool-coco-master-gcc-8.3.0-compiler.python-3.6.10-linux-64/')
# since it gets added to the Python path automatically via the dependency.
from pycocotools.coco import COCO
# No need to hardcode (e.g. as '$CK_TOOLS/dataset-coco-2017-val'),
# since it gets added to the path automatically via the dependency.
coco_dir = os.environ.get('CK_ENV_DATASET_COCO','')
if coco_dir=='':
print('Error: Path to COCO dataset not defined!')
exit(1)
# No need to hardcode (e.g. as '$CK_TOOLS/dataset-imagenet-ilsvrc2012-aux/val.txt'),
# since it gets added to the path automatically via the dependency.
imagenet_val_file = os.environ.get('CK_CAFFE_IMAGENET_VAL_TXT','')
if imagenet_val_file=='':
print('Error: Path to ImageNet labels not defined!')
exit(1)
# ### Collective Knowledge
# If CK is not installed, please install it using:
# ```
# # python -m pip install ck
# ```
# In[ ]:
import ck.kernel as ck
print ('CK version: %s' % ck.__version__)
# <a id="systems"></a>
# ## Systems
# Load platform_templates from CK SUT entries
#
r = ck.access({'action':'list', 'module_uoa':'sut'})
if r['return']>0:
print('Error: %s' % r['error'])
exit(1)
platform_templates = { sut['data_uoa']: sut['meta']['data'] for sut in r['lst'] }
inference_engine_to_printable = {
'armnn': 'ArmNN',
'tflite': 'TFLite',
'tensorrt': 'TensorRT',
'tensorflow': 'TensorFlow',
}
backend_to_printable = {
'neon': 'Neon',
'opencl': 'OpenCL',
'ruy': 'Ruy',
'cpu': 'CPU',
'cuda': 'CUDA',
'tensorrt': 'TensorRT-static',
'tensorrt-dynamic': 'TensorRT-dynamic',
}
system_description_cache = {}
def dump_system_description_dictionary(target_path, division, platform, inference_engine, inference_engine_version, backend):
if target_path in system_description_cache:
return system_description_cache[target_path]
library_backend = inference_engine + '_' + inference_engine_version + (('-' + backend) if backend else '')
division_system = division + '-' + platform + '-' + library_backend
if library_backend == 'tensorflow-v1.14-cpu':
status = 'RDI'
elif library_backend == 'tflite-v1.15.0' or library_backend == 'tensorrt-v6.0':
status = 'unofficial'
else:
status = 'available'
framework = inference_engine_to_printable[inference_engine] + ' ' + inference_engine_version + \
(' ({})'.format(backend_to_printable[backend]) if backend else '')
template = deepcopy(platform_templates[platform])
template.update({
'division' : division,
'submitter' : 'dividiti', # 'dividiti' if platform != 'velociti' else 'dividiti, Politecnico di Milano'
'status' : status,
'framework' : framework,
})
if (not library_backend.startswith('tensorrt') and not library_backend.startswith('tensorflow') and not library_backend.endswith('opencl')) or library_backend.endswith('cpu'):
template.update({
'accelerator_frequency' : '-',
'accelerator_memory_capacity' : '-',
'accelerator_memory_configuration': '-',
'accelerator_model_name' : '-',
'accelerator_on-chip_memories': '-',
'accelerators_per_node' : '0',
})
with open(target_path, 'w') as system_description_file:
json.dump(template, system_description_file, indent=2)
system_description_cache[target_path] = template
return template
# <a id="implementations"></a>
# ## Implementations
implementation_cache = {}
def dump_implementation_dictionary(target_path, model_dict, inference_engine, program_name, benchmark):
if target_path in implementation_cache:
return implementation_cache[target_path]
model_env = model_dict['cus']['install_env']
model_tags = model_dict['dict']['tags']
recorded_model_retraining = model_env.get('ML_MODEL_RETRAINING', 'no')
## fetch recorded model data types, if available, guess if unavailable:
recorded_model_data_type = model_env.get('ML_MODEL_DATA_TYPE')
recorded_model_input_data_type = model_env.get('ML_MODEL_INPUT_DATA_TYPE')
if not recorded_model_data_type:
if {'non-quantized', 'fp32', 'float', 'float32'} & set(model_tags):
recorded_model_data_type = 'fp32'
elif {'quantized', 'quant', 'uint8'} & set(model_tags):
recorded_model_data_type = 'uint8'
else:
print("Warning: could not guess whether the model is quantized or not - please add tags or attributes")
recorded_model_data_type = 'fp32'
if not recorded_model_input_data_type: # assume the same
recorded_model_input_data_type = recorded_model_data_type
## recorded_model_input_data_type may need translating from NumPy name into MLPerf's vocabulary:
model_input_type_mapping = {'float32': 'fp32', 'float16': 'fp16' }
if recorded_model_input_data_type in model_input_type_mapping:
recorded_model_input_data_type = model_input_type_mapping[recorded_model_input_data_type]
## fetching/constructing the URL of the (original) model:
if 'PACKAGE_URL' not in model_env: # this model is a result of conversion
model_env = model_dict['dict']['deps']['model-source']['dict']['customize']['install_env']
recorded_model_url = model_env['PACKAGE_URL'].rstrip('/') + '/' + model_env['PACKAGE_NAME']
## figure out the transformation path:
if program_name in [ 'image-classification-tflite-loadgen', 'image-classification-armnn-tflite-loadgen' ]:
if benchmark in ['resnet', 'resnet50']:
recorded_transformation_path = 'TF -> TFLite'
else:
recorded_transformation_path = 'TFLite'
elif program_name == 'image-classification-tensorrt-loadgen-py':
if benchmark in ['resnet', 'resnet50']:
recorded_transformation_path = 'ONNX'
else:
recorded_transformation_path = 'TF'
elif program_name == 'mlperf-inference-vision':
recorded_transformation_path = 'None (TensorFlow)'
else:
raise Exception("Don't know how to derive the transformation path of the model")
# Initial model is never supplied in one of these, so there must have been a transformation:
if inference_engine in ['armnn', 'tensorrt']:
recorded_transformation_path += ' -> '+inference_engine_to_printable[inference_engine]
implementation_dictionary = {
'retraining': recorded_model_retraining,
'input_data_types': recorded_model_input_data_type,
'weight_data_types': recorded_model_data_type,
'starting_weights_filename': recorded_model_url,
'weight_transformations': recorded_transformation_path,
}
with open(target_path, 'w') as implementation_file:
json.dump(implementation_dictionary, implementation_file, indent=2)
implementation_cache[target_path] = implementation_dictionary
return implementation_dictionary
# In[ ]:
implementation_readmes = {}
implementation_readmes['image-classification-tflite-loadgen'] = """# MLPerf Inference - Image Classification - TFLite
This C++ implementation uses TFLite to run TFLite models for Image Classification on CPUs.
## Links
- [Jupyter notebook](https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/1xlv5oacgobrfd4/mlperf-inference-v0.5-dividiti.ipynb)
- [Source code](https://github.com/ctuning/ck-mlperf/tree/master/program/image-classification-tflite-loadgen).
- [Instructions](https://github.com/mlperf/inference/blob/master/v0.5/classification_and_detection/optional_harness_ck/classification/tflite/README.md).
"""
implementation_readmes['image-classification-armnn-tflite-loadgen'] = """# MLPerf Inference - Image Classification - ArmNN-TFLite
This C++ implementation uses ArmNN with the TFLite frontend to run TFLite models for Image Classification on Arm Cortex CPUs and Arm Mali GPUs.
## Links
- [Jupyter notebook](https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/1xlv5oacgobrfd4/mlperf-inference-v0.5-dividiti.ipynb)
- [Source code](https://github.com/ctuning/ck-mlperf/tree/master/program/image-classification-armnn-tflite-loadgen).
- [Instructions](https://github.com/ARM-software/armnn-mlperf/blob/master/README.md).
"""
implementation_readmes['image-classification-tensorrt-loadgen-py'] = """# MLPerf Inference - Image Classification - TensorRT
This Python implementation uses TensorRT to run models Image Classification on Arm Cortex CPUs and Arm Mali GPUs.
### Links
- [Source code](https://github.com/ctuning/ck-mlperf/tree/master/program/image-classification-tensorrt-loadgen-py).
"""
implementation_readmes['mlperf-inference-vision'] = """# MLPerf Inference - Object Detection - TensorFlow
This Python implementation is the official MLPerf Inference vision application, modified to support other
object detection models and run with TensorRT.
## Links
- [CK wrapper](https://github.com/ctuning/ck-object-detection/tree/master/program/mlperf-inference-vision).
- [vision_with_ck branch in dividiti's fork of mlperf/inference](https://github.com/dividiti/inference/tree/vision_with_ck).
- [Docker image with instructions](https://github.com/ctuning/ck-mlperf/tree/master/docker/mlperf-inference-vision-with-ck.tensorrt.ubuntu-18.04).
- [Jupyter notebook](https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/1xlv5oacgobrfd4/mlperf-inference-v0.5-dividiti.ipynb)
"""
# In[ ]:
def get_program_path(program_name):
r = ck.access({'action':'find', 'repo_uoa':'*', 'module_uoa':'program', 'data_uoa':program_name})
if r['return']>0:
print('Error: %s' % r['error'])
exit(1)
return r['path']
# In[ ]:
measurements_readmes = {}
task = 'image-classification'
for division_upper in [ 'Closed', 'Open' ]:
division_lower = division_upper.lower()
measurements_readmes[division_lower+'-'+task] = '''# MLPerf Inference - {} Division - Image Classification
We performed our measurements using automated, customizable, portable and reproducible
[Collective Knowledge](http://cknowledge.org) workflows. Our workflows automatically
install dependencies (models, datasets, etc.), preprocess input data in the correct way,
and so on.
## CK repositories
As CK is always evolving, it is hard to pin particular revisions of all repositories.
The most relevant repositories and their latest revisions on the submission date (11/Oct/2019):
- [ck-mlperf](https://github.com/ctuning/ck-mlperf) @ [ee77cfd](https://github.com/ctuning/ck-mlperf/commit/ee77cfd3ddfa30739a8c2f483fe9ba83a233a000) (contains programs integrated with LoadGen, model packages and scripts).
- [ck-env](https://github.com/ctuning/ck-env) @ [f9ac337](https://github.com/ctuning/ck-env/commit/f9ac3372cdc82fa46b2839e45fc67848ab4bac03) (contains dataset descriptions, preprocessing methods, etc.)
- [ck-tensorflow](https://github.com/ctuning/ck-tensorflow) @ [eff8bec](https://github.com/ctuning/ck-tensorflow/commit/eff8bec192021162e4a336dbd3e795afa30b7d26) (contains TFLite packages).
- [armnn-mlperf](https://github.com/arm-software/armnn-mlperf) @ [42f44a2](https://github.com/ARM-software/armnn-mlperf/commit/42f44a266b6b4e04901255f46f6d34d12589208f) (contains ArmNN/ArmCL packages).
## Links
- [Bash script](https://github.com/ctuning/ck-mlperf/tree/master/script/mlperf-inference-v0.5.{}.image-classification) used to invoke benchmarking on Linux systems or Android devices.
'''.format(division_upper, division_lower)
task = 'object-detection'
for division_upper in [ 'Closed', 'Open' ]:
division_lower = division_upper.lower()
measurements_readmes[division_lower+'-'+task] = '''# MLPerf Inference - {} Division - Object Detection
We performed our measurements using automated, customizable, portable and reproducible
[Collective Knowledge](http://cknowledge.org) workflows. Our workflows automatically
install dependencies (models, datasets, etc.), preprocess input data in the correct way,
and so on.
## CK repositories
As CK is always evolving, it is hard to pin particular revisions of all repositories.
The most relevant repositories and their latest revisions on the submission date (18/Oct/2019):
- [ck-mlperf](https://github.com/ctuning/ck-mlperf) @ [ef1fced](https://github.com/ctuning/ck-mlperf/commit/ef1fcedd495fd03b5ad6d62d62c8ba271854f2ad) (contains the CK program wrapper, MLPerf SSD-MobileNet model packages and scripts).
- [ck-object-detection](https://github.com/ctuning/ck-object-detection) @ [780d328](https://github.com/ctuning/ck-object-detection/commit/780d3288ec19656cb60c5ad39b2486bbf0fbf97a) (contains most model packages)
- [ck-env](https://github.com/ctuning/ck-env) @ [5af9fbd](https://github.com/ctuning/ck-env/commit/5af9fbd93ad6c6465b631716645ad9442a333442) (contains dataset descriptions, preprocessing methods, etc.)
## Links
- [Docker image with instructions](https://github.com/ctuning/ck-mlperf/tree/master/docker/mlperf-inference-vision-with-ck.tensorrt.ubuntu-18.04).
- [Bash script](https://github.com/ctuning/ck-mlperf/tree/master/script/mlperf-inference-v0.5.{}.object-detection) used to invoke benchmarking via the Docker image.
'''.format(division_upper, division_lower)
# In[ ]:
# Snapshot of https://github.com/dividiti/inference/blob/61220457dec221ed1984c62bd9d382698bd71bc6/v0.5/mlperf.conf
mlperf_conf_6122045 = '''
# The format of this config file is 'key = value'.
# The key has the format 'model.scenario.key'. Value is mostly int64_t.
# Model maybe '*' as wildcard. In that case the value applies to all models.
# All times are in milli seconds
*.SingleStream.target_latency = 10
*.SingleStream.target_latency_percentile = 90
*.SingleStream.min_duration = 60000
*.SingleStream.min_query_count = 1024
*.MultiStream.target_qps = 20
*.MultiStream.target_latency_percentile = 99
*.MultiStream.samples_per_query = 4
*.MultiStream.max_async_queries = 1
*.MultiStream.target_latency = 50
*.MultiStream.min_duration = 60000
*.MultiStream.min_query_count = 270336
ssd-resnet34.MultiStream.target_qps = 15
ssd-resnet34.MultiStream.target_latency = 66
gnmt.MultiStream.min_query_count = 90112
gnmt.MultiStream.target_latency = 100
gnmt.MultiStream.target_qps = 10
gnmt.MultiStream.target_latency_percentile = 97
*.Server.target_qps = 1.0
*.Server.target_latency = 10
*.Server.target_latency_percentile = 99
*.Server.target_duration | |
workflow global to support the onExit handler
return {
'name': 'download',
'metadata': {
'labels': {'app': 'transcoder'},
},
'retryStrategy': {
'retryPolicy': 'Always',
'limit': 3,
'backoff': {
'duration': '5s',
'factor': 2
},
},
'inputs': {'parameters' : [{'name': 'original'},
{'name': 'url'}]},
'nodeSelector' : {'cpuWorker' : 'yes'},
'container': {
'image': '{{workflow.parameters.client_image}}',
'imagePullPolicy': 'IfNotPresent',
'command': ['wget',],
'args': ['-O', '{{inputs.parameters.original}}'] + headers + \
['{{inputs.parameters.url}}'],
'volumeMounts': [{
'name': 'transcode-scratch',
'mountPath': '/work',
}],
'resources': {
'limits': {
'memory': '4Gi',
'cpu': '1000m',
},
},
},
}
def get_unpack_and_transcode_tasks(self, paths, url):
""" Generate a task object describing the dependencies of a transcode from tar"""
# Generate an args structure for the DAG
args = [{'name': 'url', 'value': url}]
for key in paths:
args.append({'name': key, 'value': paths[key]})
parameters = {"parameters" : args}
def make_item_arg(name):
return {'name': name,
'value': f'{{{{item.{name}}}}}'}
instance_args = ['entity_type',
'name',
'md5']
item_parameters = {"parameters" : [make_item_arg(x) for x in instance_args]}
# unpack work list
item_parameters["parameters"].append({"name": "url",
"value": "None"})
item_parameters["parameters"].append({"name": "original",
"value": "{{item.dirname}}/{{item.name}}"})
item_parameters["parameters"].append({"name": "transcoded",
"value": "{{item.dirname}}/{{item.base}}_transcoded"})
item_parameters["parameters"].append({"name": "thumbnail",
"value": "{{item.dirname}}/{{item.base}}_thumbnail.jpg"})
item_parameters["parameters"].append({"name": "thumbnail_gif",
"value": "{{item.dirname}}/{{item.base}}_thumbnail_gif.gif"})
item_parameters["parameters"].append({"name": "segments",
"value": "{{item.dirname}}/{{item.base}}_segments.json"})
state_import_parameters = {"parameters" : [make_item_arg(x) for x in ["md5", "file"]]}
localization_import_parameters = {"parameters" : [make_item_arg(x) for x in ["md5", "file"]]}
state_import_parameters["parameters"].append({"name": "mode", "value": "state"})
localization_import_parameters["parameters"].append({"name": "mode", "value": "localizations"})
unpack_task = {
'name': 'unpack-pipeline',
'metadata': {
'labels': {'app': 'transcoder'},
},
'dag': {
# First download, unpack and delete archive. Then Iterate over each video and upload
# Lastly iterate over all localization and state files.
'tasks' : [{'name': 'download-task',
'template': 'download',
'arguments': parameters},
{'name': 'unpack-task',
'template': 'unpack',
'arguments': parameters,
'dependencies' : ['download-task']},
{'name': 'delete-task',
'template': 'delete',
'arguments': parameters,
'dependencies' : ['unpack-task']}
]
}
} # end of dag
unpack_task['dag']['tasks'].extend([{'name': f'transcode-task-{x}',
'template': 'transcode-pipeline',
'arguments' : item_parameters,
'withParam' : f'{{{{tasks.unpack-task.outputs.parameters.videos-{x}}}}}',
'dependencies' : ['unpack-task']} for x in range(NUM_WORK_PACKETS)])
unpack_task['dag']['tasks'].append({'name': f'image-upload-task',
'template': 'image-upload',
'dependencies' : ['unpack-task']})
deps = [f'transcode-task-{x}' for x in range(NUM_WORK_PACKETS)]
deps.append('image-upload-task')
unpack_task['dag']['tasks'].extend([{'name': f'state-import-task-{x}',
'template': 'data-import',
'arguments' : state_import_parameters,
'dependencies' : deps,
'withParam': f'{{{{tasks.unpack-task.outputs.parameters.states-{x}}}}}'} for x in range(NUM_WORK_PACKETS)])
unpack_task['dag']['tasks'].extend([{'name': f'localization-import-task-{x}',
'template': 'data-import',
'arguments' : localization_import_parameters,
'dependencies' : deps,
'withParam': f'{{{{tasks.unpack-task.outputs.parameters.localizations-{x}}}}}'} for x in range(NUM_WORK_PACKETS)])
return unpack_task
def get_transcode_dag(self, media_id=None):
""" Return the DAG that describes transcoding a single media file """
def make_passthrough_arg(name):
return {'name': name,
'value': f'{{{{inputs.parameters.{name}}}}}'}
instance_args = ['url',
'original',
'transcoded',
'thumbnail',
'thumbnail_gif',
'segments',
'entity_type',
'name',
'md5']
passthrough_parameters = {"parameters" : [make_passthrough_arg(x) for x in instance_args]}
pipeline_task = {
'name': 'transcode-pipeline',
'metadata': {
'labels': {'app': 'transcoder'},
},
'inputs': passthrough_parameters,
'dag': {
'tasks': [{
'name': 'prepare-task',
'template': 'prepare',
}, {
'name': 'transcode-task',
'template': 'transcode',
'arguments': {
'parameters': passthrough_parameters['parameters'] + [{
'name': 'category',
'value': '{{item.category}}',
}, {
'name': 'raw_width',
'value': '{{item.raw_width}}',
}, {
'name': 'raw_height',
'value': '{{item.raw_height}}',
}, {
'name': 'configs',
'value': '{{item.configs}}',
}, {
'name': 'id',
'value': '{{item.id}}',
}, {
'name': 'media',
'value': '{{tasks.prepare-task.outputs.parameters.media_id}}' \
if media_id is None else str(media_id),
}],
},
'dependencies': ['prepare-task'],
'withParam': '{{tasks.prepare-task.outputs.parameters.workloads}}',
}],
},
}
return pipeline_task
def get_single_file_pipeline(self, item, url):
""" Generate a task object describing the dependencies of a transcode """
# Generate an args structure for the DAG
args = [{'name': 'url', 'value': url}]
for key in item:
args.append({'name': key, 'value': item[key]})
parameters = {"parameters" : args}
pipeline = {
'name': 'single-file-pipeline',
'dag': {
# First download, unpack and delete archive. Then Iterate over each video and upload
# Lastly iterate over all localization and state files.
'tasks' : [{'name': 'transcode-task',
'template': 'transcode-pipeline',
'arguments' : parameters}]
}
}
return pipeline
def start_tar_import(self,
project,
entity_type,
token,
url,
name,
section,
md5,
gid,
uid,
user,
upload_size,
attributes):
""" Initiate a transcode based on the contents on an archive """
comps = name.split('.')
base = comps[0]
ext = '.'.join(comps[1:])
if entity_type != -1:
raise Exception("entity type is not -1!")
pvc_size = bytes_to_mi_str(upload_size * 2.5)
args = {'original': '/work/' + name,
'name': name}
docker_registry = os.getenv('SYSTEM_IMAGES_REGISTRY')
host = f'{PROTO}{os.getenv("MAIN_HOST")}'
global_args = {'upload_name': name,
'url': url,
'host': host,
'rest_url': f'{host}/rest',
'tus_url' : f'{host}/files/',
'project' : str(project),
'type': '-1',
'token' : str(token),
'section' : section,
'gid': gid,
'uid': uid,
'user': str(user),
'client_image' : get_client_image_name(),
'attributes' : json.dumps(attributes),
'media_id': '-1',
'size': str(upload_size)}
global_parameters=[{"name": x, "value": global_args[x]} for x in global_args]
pipeline_task = self.get_unpack_and_transcode_tasks(args, url)
# Define the workflow spec.
manifest = {
'apiVersion': 'argoproj.io/v1alpha1',
'kind': 'Workflow',
'metadata': {
'generateName': 'transcode-workflow-',
'labels': {
'job_type': 'upload',
'project': str(project),
'gid': gid,
'uid': uid,
'user': str(user),
},
'annotations': {
'name': name,
'section': section,
},
},
'spec': {
'entrypoint': 'unpack-pipeline',
'podGC': {'strategy': os.getenv('POD_GC_STRATEGY')},
'volumeClaimGC': {'strategy': 'OnWorkflowCompletion'},
'arguments': {'parameters' : global_parameters},
'ttlStrategy': {'secondsAfterSuccess': 300,
'secondsAfterFailure': 604800, # One week
'secondsAfterCompletion': 604800},
'volumeClaimTemplates': [{
'metadata': {
'name': 'transcode-scratch',
},
'spec': {
'storageClassName': _select_storage_class(),
'accessModes': [ 'ReadWriteOnce' ],
'resources': {
'requests': {
'storage': pvc_size,
}
}
}
}],
'parallelism': 4,
'templates': [
self.get_prepare_task(False),
self.get_download_task(),
self.delete_task,
self.get_transcode_task(False),
self.image_upload_task,
self.unpack_task,
self.get_transcode_dag(),
pipeline_task,
self.data_import,
self.notify_failure,
self.exit_handler,
],
'onExit': 'exit-handler',
},
}
# Create the workflow
response = self.create_workflow(manifest)
def start_transcode(self, project,
entity_type, token, url, name,
section, md5, gid, uid,
user, upload_size,
attributes, media_id):
MAX_WORKLOADS = 7 # 5 resolutions + audio + archival
""" Creates an argo workflow for performing a transcode.
"""
# Define paths for transcode outputs.
base, _ = os.path.splitext(name)
args = {
'original': '/work/' + name,
'transcoded': '/work/' + base + '_transcoded',
'thumbnail': '/work/' + base + '_thumbnail.jpg',
'thumbnail_gif': '/work/' + base + '_thumbnail_gif.gif',
'segments': '/work/' + base + '_segments.json',
'entity_type': str(entity_type),
'md5' : md5,
'name': name
}
# Determine whether to use RAM disks (smaller files) or PVCs (larger files)
pvc_bytes = upload_size * 2.5
pvc_size = bytes_to_mi_str(pvc_bytes)
max_ram_disk_size = os.getenv('TRANSCODER_MAX_RAM_DISK_SIZE')
unit = max_ram_disk_size[-2:]
ram_disk_bytes = int(max_ram_disk_size[:-2])
if unit == 'Mi':
ram_disk_bytes *= 1024 * 1024
elif unit == 'Gi':
ram_disk_bytes *= 1024 * 1024 * 1024
else:
raise ValueError('Max RAM disk size units must be Mi or Gi!')
use_ram_disk = pvc_bytes < ram_disk_bytes
logger.info(f"Scratch space requirements for {name}: {pvc_size}, using RAM disk: {use_ram_disk}")
docker_registry = os.getenv('SYSTEM_IMAGES_REGISTRY')
host = f'{PROTO}{os.getenv("MAIN_HOST")}'
global_args = {'upload_name': name,
'url': url,
'host': host,
'rest_url': f'{host}/rest',
'tus_url' : f'{host}/files/',
'token' : str(token),
'project' : str(project),
'type': str(entity_type),
'section' : section,
'gid': gid,
'uid': uid,
'user': str(user),
'client_image' : get_client_image_name(),
'attributes' : json.dumps(attributes),
'media_id': '-1' if media_id is None else str(media_id),
'size': str(upload_size)}
global_parameters=[{"name": x, "value": global_args[x]} for x in global_args]
pipeline_task = self.get_single_file_pipeline(args, url)
# Define the workflow spec.
manifest = {
'apiVersion': 'argoproj.io/v1alpha1',
'kind': 'Workflow',
'metadata': {
'generateName': 'transcode-workflow-',
'labels': {
'job_type': 'upload',
'project': str(project),
'gid': gid,
'uid': uid,
'user': str(user),
},
'annotations': {
'name': name,
'section': section,
},
},
'spec': {
'entrypoint': 'single-file-pipeline',
'podGC': {'strategy': os.getenv('POD_GC_STRATEGY')},
'volumeClaimGC': {'strategy': 'OnWorkflowCompletion'},
'arguments': {'parameters' : global_parameters},
'ttlStrategy': {'secondsAfterSuccess': 300,
'secondsAfterFailure': 86400,
'secondsAfterCompletion': 86400},
'templates': [
self.get_prepare_task(use_ram_disk),
self.get_transcode_task(use_ram_disk),
self.get_transcode_dag(media_id),
pipeline_task,
],
},
}
if not use_ram_disk:
manifest['spec']['volumeClaimTemplates'] = [{
'metadata': {
'name': f'scratch-{workload}',
},
'spec': {
'storageClassName': os.getenv('SCRATCH_STORAGE_CLASS'),
'accessModes': [ 'ReadWriteOnce' ],
'resources': {
'requests': {
'storage': pvc_size,
}
}
}
} for workload in ['prepare'] + list(range(MAX_WORKLOADS))]
# Create the workflow
response = self.create_workflow(manifest)
# Cache the job for cancellation/authentication.
TatorCache().set_job({'uid': uid,
'gid': gid,
'user': user,
'project': project,
'algorithm': -1,
'datetime': datetime.datetime.utcnow().isoformat() + 'Z'})
class TatorAlgorithm(JobManagerMixin):
""" Interface to kubernetes REST API for starting algorithms.
"""
def __init__(self, alg):
""" Intializes the connection. If algorithm object includes
a remote cluster, use that. Otherwise, use this cluster.
"""
if alg.cluster:
host = alg.cluster.host
port = alg.cluster.port
token = alg.cluster.token
fd, cert = tempfile.mkstemp(text=True)
with open(fd, 'w') as f:
f.write(alg.cluster.cert)
conf = Configuration()
conf.api_key['authorization'] = token
conf.host = f'{PROTO}{host}:{port}'
conf.verify_ssl = True
conf.ssl_ca_cert = cert
api_client = ApiClient(conf)
self.corev1 = CoreV1Api(api_client)
self.custom = CustomObjectsApi(api_client)
else:
load_incluster_config()
self.corev1 = CoreV1Api()
self.custom = CustomObjectsApi()
# Read in the manifest.
if alg.manifest:
self.manifest = yaml.safe_load(alg.manifest.open(mode='r'))
# Save off the algorithm.
self.alg = alg
def start_algorithm(self, media_ids, sections, gid, uid, token, project, user,
extra_params: list=[]):
""" Starts an algorithm job, substituting in parameters in the
workflow spec.
"""
# Make a copy of the manifest from the database.
manifest = copy.deepcopy(self.manifest)
# Update the storage class of the spec if | |
# Copyright (c) 2020-2021 impersonator.org authors (<NAME> and <NAME>). All rights reserved.
from collections import OrderedDict
import torch
import torch.nn as nn
def make_layers(block, no_relu_layers):
layers = []
for layer_name, v in block.items():
if 'pool' in layer_name:
layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1],
padding=v[2])
layers.append((layer_name, layer))
else:
conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1],
kernel_size=v[2], stride=v[3],
padding=v[4])
layers.append((layer_name, conv2d))
if layer_name not in no_relu_layers:
layers.append(('relu_' + layer_name, nn.ReLU(inplace=True)))
return nn.Sequential(OrderedDict(layers))
def body25_make_layers(block, act_types):
"""
Args:
block:
act_types (dict):
Returns:
module (nn.Sequential): the module layer.
"""
layers = []
for layer_name, v in block.items():
if 'pool' in layer_name:
layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1],
padding=v[2])
layers.append((layer_name, layer))
elif 'prelu' in layer_name:
layers.append((layer_name, nn.PReLU(num_parameters=v[0])))
else:
conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1],
kernel_size=v[2], stride=v[3],
padding=v[4])
layers.append((layer_name, conv2d))
if layer_name in act_types:
act = nn.ReLU(inplace=True)
layers.append((act_types[layer_name] + '_' + layer_name, act))
return nn.Sequential(OrderedDict(layers))
class MConvBlock(nn.Module):
def __init__(self, conv_ids, stage_ids, l_name, in_channel, out_channel,
kernel_size=3, stride=1, padding=1,
is_single=False, has_relu=True):
"""
Args:
conv_ids:
stage_ids:
l_name:
in_channel:
out_channel:
is_single:
has_relu:
"""
super().__init__()
self.is_single = is_single
if self.is_single:
name_template = "M{layer}{conv_ids}_stage{stage_ids}_L{l_name}"
m_split = list()
m_split.append(
(name_template.format(layer="conv", conv_ids=conv_ids, stage_ids=stage_ids, l_name=l_name),
nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
kernel_size=kernel_size, stride=stride, padding=padding))
)
if has_relu:
m_split.append(
(name_template.format(layer="prelu", conv_ids=conv_ids, stage_ids=stage_ids, l_name=l_name),
nn.PReLU(num_parameters=out_channel))
)
self.split0 = nn.Sequential(OrderedDict(m_split))
else:
name_template = "M{layer}{conv_ids}_stage{stage_ids}_L{l_name}_{col_num}"
conv_0 = [
(name_template.format(layer="conv", conv_ids=conv_ids, stage_ids=stage_ids,
l_name=l_name, col_num=0),
nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
kernel_size=kernel_size, stride=stride, padding=padding)),
(name_template.format(layer="prelu", conv_ids=conv_ids, stage_ids=stage_ids,
l_name=l_name, col_num=0),
nn.PReLU(num_parameters=out_channel))
]
self.split0 = nn.Sequential(OrderedDict(conv_0))
conv_1 = [
(name_template.format(layer="conv", conv_ids=conv_ids, stage_ids=stage_ids,
l_name=l_name, col_num=1),
nn.Conv2d(in_channels=out_channel, out_channels=out_channel,
kernel_size=kernel_size, stride=stride, padding=padding)),
(name_template.format(layer="prelu", conv_ids=conv_ids, stage_ids=stage_ids,
l_name=l_name, col_num=1),
nn.PReLU(num_parameters=out_channel))
]
self.split1 = nn.Sequential(OrderedDict(conv_1))
conv_2 = [
(name_template.format(layer="conv", conv_ids=conv_ids, stage_ids=stage_ids,
l_name=l_name, col_num=2),
nn.Conv2d(in_channels=out_channel, out_channels=out_channel,
kernel_size=kernel_size, stride=stride, padding=padding)),
(name_template.format(layer="prelu", conv_ids=conv_ids, stage_ids=stage_ids,
l_name=l_name, col_num=2),
nn.PReLU(num_parameters=out_channel))
]
self.split2 = nn.Sequential(OrderedDict(conv_2))
def forward(self, x):
conv0 = self.split0(x)
if not self.is_single:
conv1 = self.split1(conv0)
conv2 = self.split2(conv1)
out = torch.cat([conv0, conv1, conv2], dim=1)
else:
out = conv0
return out
class StackMConvBlock(nn.Module):
def __init__(self, stage, stage_params):
"""
Args:
stage (int):
stage_params (dict):
stage_params = {
# layer_num: [in_channel, out_channel, kernel_size, stride, padding, is_single, has_relu, l_name]
1: [128, 96, 3, 1, 1, False, True, 2],
2: [96 * 3, 96, 3, 1, 1, False, True, 2],
3: [96 * 3, 96, 3, 1, 1, False, True, 2],
4: [96 * 3, 96, 3, 1, 1, False, True, 2],
5: [96 * 3, 96, 3, 1, 1, False, True, 2],
6: [96 * 3, 256, 1, 1, 0, True, True, 2],
7: [256, 52, 1, 1, 0, True, False, 2],
}
"""
super().__init__()
# the first five mconv block
blocks = []
for i in range(1, 8):
in_channel, out_channel, kernel_size, stride, padding, is_single, has_relu, l_name = stage_params[i]
mblock = MConvBlock(conv_ids=i, stage_ids=stage, l_name=l_name, in_channel=in_channel,
kernel_size=kernel_size, stride=stride, padding=padding,
out_channel=out_channel, is_single=is_single, has_relu=has_relu)
blocks.append(mblock)
self.main = nn.Sequential(*blocks)
def forward(self, x):
return self.main(x)
class OpenPoseBody25Model(nn.Module):
def __init__(self, *args, **kwargs):
super(OpenPoseBody25Model, self).__init__()
# model 0
self.model0 = self.build_model0()
# M-stage0_L2
stage_0_L2_params = {
# layer_num: [in_channel, out_channel, kernel_size, stride, padding, is_single, has_relu]
1: [128, 96, 3, 1, 1, False, True, 2],
2: [96 * 3, 96, 3, 1, 1, False, True, 2],
3: [96 * 3, 96, 3, 1, 1, False, True, 2],
4: [96 * 3, 96, 3, 1, 1, False, True, 2],
5: [96 * 3, 96, 3, 1, 1, False, True, 2],
6: [96 * 3, 256, 1, 1, 0, True, True, 2],
7: [256, 52, 1, 1, 0, True, False, 2],
}
self.block02 = StackMConvBlock(stage=0, stage_params=stage_0_L2_params)
# M-stage1_L2
stage_1_L2_params = {
# layer_num: [in_channel, out_channel, kernel_size, stride, padding, is_single, has_relu]
1: [180, 128, 3, 1, 1, False, True, 2],
2: [128 * 3, 128, 3, 1, 1, False, True, 2],
3: [128 * 3, 128, 3, 1, 1, False, True, 2],
4: [128 * 3, 128, 3, 1, 1, False, True, 2],
5: [128 * 3, 128, 3, 1, 1, False, True, 2],
6: [128 * 3, 512, 1, 1, 0, True, True, 2],
7: [512, 52, 1, 1, 0, True, False, 2],
}
self.block12 = StackMConvBlock(stage=1, stage_params=stage_1_L2_params)
# M-stage2_L2
stage_2_L2_params = stage_1_L2_params
self.block22 = StackMConvBlock(stage=2, stage_params=stage_2_L2_params)
# M-stage3_L2
stage_3_L2_params = stage_1_L2_params
self.block32 = StackMConvBlock(stage=3, stage_params=stage_3_L2_params)
# M-stage0_L1
stage_0_L1_params = {
# layer_num: [in_channel, out_channel, kernel_size, stride, padding, is_single, has_relu]
1: [180, 96, 3, 1, 1, False, True, 1],
2: [96 * 3, 96, 3, 1, 1, False, True, 1],
3: [96 * 3, 96, 3, 1, 1, False, True, 1],
4: [96 * 3, 96, 3, 1, 1, False, True, 1],
5: [96 * 3, 96, 3, 1, 1, False, True, 1],
6: [96 * 3, 256, 1, 1, 0, True, True, 1],
7: [256, 26, 1, 1, 0, True, False, 1],
}
self.block01 = StackMConvBlock(stage=0, stage_params=stage_0_L1_params)
# M-stage1_L1
stage_1_L1_params = {
# layer_num: [in_channel, out_channel, kernel_size, stride, padding, is_single, has_relu]
1: [206, 128, 3, 1, 1, False, True, 1],
2: [128 * 3, 128, 3, 1, 1, False, True, 1],
3: [128 * 3, 128, 3, 1, 1, False, True, 1],
4: [128 * 3, 128, 3, 1, 1, False, True, 1],
5: [128 * 3, 128, 3, 1, 1, False, True, 1],
6: [128 * 3, 512, 1, 1, 0, True, True, 1],
7: [512, 26, 1, 1, 0, True, False, 1],
}
self.block11 = StackMConvBlock(stage=1, stage_params=stage_1_L1_params)
def build_model0(self):
# Stage 0
act_types = {
'conv1_1': 'relu', 'conv1_2': 'relu', 'conv2_1': 'relu', 'conv2_2': 'relu',
'conv3_1': 'relu', 'conv3_2': 'relu', 'conv3_3': 'relu', 'conv3_4': 'relu', 'conv4_1': 'relu'
}
block0 = OrderedDict([
('conv1_1', [3, 64, 3, 1, 1]),
('conv1_2', [64, 64, 3, 1, 1]),
('pool1_stage1', [2, 2, 0]),
('conv2_1', [64, 128, 3, 1, 1]),
('conv2_2', [128, 128, 3, 1, 1]),
('pool2_stage1', [2, 2, 0]),
('conv3_1', [128, 256, 3, 1, 1]),
('conv3_2', [256, 256, 3, 1, 1]),
('conv3_3', [256, 256, 3, 1, 1]),
('conv3_4', [256, 256, 3, 1, 1]),
('pool3_stage1', [2, 2, 0]),
('conv4_1', [256, 512, 3, 1, 1]),
('conv4_2', [512, 512, 3, 1, 1]),
('prelu4_2', [512]),
('conv4_3_CPM', [512, 256, 3, 1, 1]),
('prelu4_3_CPM', [256]),
('conv4_4_CPM', [256, 128, 3, 1, 1]),
('prelu4_4_CPM', [128])
])
model0 = body25_make_layers(block0, act_types)
return model0
def forward(self, x):
out1 = self.model0(x)
# M-stage0-L2
m_stage_0_L2 = self.block02(out1)
# M-stage1-L2
concat_stage1_L2 = torch.cat([out1, m_stage_0_L2], dim=1)
m_stage_1_L2 = self.block12(concat_stage1_L2)
# M-stage2-L2
concat_stage2_L2 = torch.cat([out1, m_stage_1_L2], dim=1)
m_stage_2_L2 = self.block22(concat_stage2_L2)
# M-stage3-L2
concat_stage3_L2 = torch.cat([out1, m_stage_2_L2], dim=1)
Mconv7_stage3_L2 = self.block32(concat_stage3_L2)
# M-stage0-L1
concat_stage0_L1 = torch.cat([out1, Mconv7_stage3_L2], dim=1)
Mconv7_stage0_L1 = self.block01(concat_stage0_L1)
# M-stage1-L1
# concat_stage1_L1 = torch.cat([out1, m_stage_3_L2, m_stage_0_L1], dim=1)
concat_stage1_L1 = torch.cat([out1, Mconv7_stage0_L1, Mconv7_stage3_L2], dim=1)
Mconv7_stage1_L1 = self.block11(concat_stage1_L1)
# outputs = {
# "heatMat": Mconv7_stage1_L1,
# "pafMat": Mconv7_stage3_L2
# }
return Mconv7_stage1_L1, Mconv7_stage3_L2
class OpenPoseBody18Model(nn.Module):
def __init__(self):
super(OpenPoseBody18Model, self).__init__()
# these layers have no relu layer
no_relu_layers = ['conv5_5_CPM_L1', 'conv5_5_CPM_L2', 'Mconv7_stage2_L1',
'Mconv7_stage2_L2', 'Mconv7_stage3_L1', 'Mconv7_stage3_L2',
'Mconv7_stage4_L1', 'Mconv7_stage4_L2', 'Mconv7_stage5_L1',
'Mconv7_stage5_L2', 'Mconv7_stage6_L1', 'Mconv7_stage6_L1']
blocks = {}
block0 = OrderedDict([
('conv1_1', [3, 64, 3, 1, 1]),
('conv1_2', [64, 64, 3, 1, 1]),
('pool1_stage1', [2, 2, 0]),
('conv2_1', [64, 128, 3, 1, 1]),
('conv2_2', [128, 128, 3, 1, 1]),
('pool2_stage1', [2, 2, 0]),
('conv3_1', [128, 256, 3, 1, 1]),
('conv3_2', [256, 256, 3, 1, 1]),
('conv3_3', [256, 256, 3, 1, 1]),
('conv3_4', [256, 256, 3, 1, 1]),
('pool3_stage1', [2, 2, 0]),
('conv4_1', [256, 512, 3, 1, 1]),
('conv4_2', [512, 512, 3, 1, 1]),
('conv4_3_CPM', [512, 256, 3, 1, 1]),
('conv4_4_CPM', [256, 128, 3, 1, 1])
])
# Stage 1
block1_1 = OrderedDict([
('conv5_1_CPM_L1', [128, 128, 3, 1, 1]),
('conv5_2_CPM_L1', [128, 128, 3, 1, 1]),
('conv5_3_CPM_L1', [128, 128, 3, 1, 1]),
('conv5_4_CPM_L1', [128, 512, 1, 1, 0]),
('conv5_5_CPM_L1', [512, 38, 1, 1, 0])
])
block1_2 = OrderedDict([
('conv5_1_CPM_L2', [128, 128, 3, 1, 1]),
('conv5_2_CPM_L2', [128, 128, 3, 1, 1]),
('conv5_3_CPM_L2', [128, 128, 3, 1, 1]),
('conv5_4_CPM_L2', [128, 512, 1, 1, 0]),
('conv5_5_CPM_L2', [512, 19, 1, 1, 0])
])
blocks['block1_1'] = block1_1
blocks['block1_2'] = block1_2
self.model0 = make_layers(block0, no_relu_layers)
# Stages 2 - 6
for i in range(2, 7):
blocks['block%d_1' % i] = OrderedDict([
('Mconv1_stage%d_L1' % i, [185, 128, 7, 1, 3]),
('Mconv2_stage%d_L1' % i, [128, 128, 7, 1, 3]),
('Mconv3_stage%d_L1' % i, [128, 128, 7, 1, 3]),
('Mconv4_stage%d_L1' % i, [128, 128, | |
},
'location_map': {
'id': 'query',
'attributes': 'query',
},
'collection_format_map': {
'attributes': 'csv',
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [],
},
api_client=api_client
)
self.portfolio_transaction_modify_post_endpoint = _Endpoint(
settings={
'response_type': (
{ 200: (InlineResponse2009,), },
None
),
'auth': [
'FactSetApiKey',
'FactSetOAuth2'
],
'endpoint_path': '/portfolio/transaction/modify',
'operation_id': 'portfolio_transaction_modify_post',
'http_method': 'POST',
'servers': None,
},
params_map={
'all': [
'body',
],
'required': [],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
'body':
(InlineObject6,),
},
'attribute_map': {
},
'location_map': {
'body': 'body',
},
'collection_format_map': {
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [
'application/json'
]
},
api_client=api_client
)
@staticmethod
def apply_kwargs_defaults(kwargs, return_http_data_only, async_req):
kwargs["async_req"] = async_req
kwargs["_return_http_data_only"] = return_http_data_only
kwargs["_preload_content"] = kwargs.get("_preload_content", True)
kwargs["_request_timeout"] = kwargs.get("_request_timeout", None)
kwargs["_check_input_type"] = kwargs.get("_check_input_type", True)
kwargs["_check_return_type"] = kwargs.get("_check_return_type", True)
kwargs["_spec_property_naming"] = kwargs.get("_spec_property_naming", False)
kwargs["_content_type"] = kwargs.get("_content_type")
kwargs["_host_index"] = kwargs.get("_host_index")
def portfolio_create_post(
self,
body,
**kwargs
) -> InlineResponse201:
"""Create a portfolio. # noqa: E501
Create a portfolio. Certain error conditions yield errors as follows: |Error Condition|HTTP Error| |-------|--------| |The number of portfolios would exceed 100.|400 Bad Request| # noqa: E501
This method makes a synchronous HTTP request. Returns the http data only
Args:
body (InlineObject):
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
InlineResponse201
Response Object
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=False)
kwargs['body'] = \
body
return self.portfolio_create_post_endpoint.call_with_http_info(**kwargs)
def portfolio_create_post_with_http_info(
self,
body,
**kwargs
) -> typing.Tuple[InlineResponse201, int, typing.MutableMapping]:
"""Create a portfolio. # noqa: E501
Create a portfolio. Certain error conditions yield errors as follows: |Error Condition|HTTP Error| |-------|--------| |The number of portfolios would exceed 100.|400 Bad Request| # noqa: E501
This method makes a synchronous HTTP request. Returns http data, http status and headers
Args:
body (InlineObject):
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
InlineResponse201
Response Object
int
Http Status Code
dict
Dictionary of the response headers
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=False)
kwargs['body'] = \
body
return self.portfolio_create_post_endpoint.call_with_http_info(**kwargs)
def portfolio_create_post_async(
self,
body,
**kwargs
) -> "ApplyResult[InlineResponse201]":
"""Create a portfolio. # noqa: E501
Create a portfolio. Certain error conditions yield errors as follows: |Error Condition|HTTP Error| |-------|--------| |The number of portfolios would exceed 100.|400 Bad Request| # noqa: E501
This method makes a asynchronous HTTP request. Returns the http data, wrapped in ApplyResult
Args:
body (InlineObject):
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[InlineResponse201]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=True)
kwargs['body'] = \
body
return self.portfolio_create_post_endpoint.call_with_http_info(**kwargs)
def portfolio_create_post_with_http_info_async(
self,
body,
**kwargs
) -> "ApplyResult[typing.Tuple[InlineResponse201, int, typing.MutableMapping]]":
"""Create a portfolio. # noqa: E501
Create a portfolio. Certain error conditions yield errors as follows: |Error Condition|HTTP Error| |-------|--------| |The number of portfolios would exceed 100.|400 Bad Request| # noqa: E501
This method makes a asynchronous HTTP request. Returns http data, http status and headers, wrapped in ApplyResult
Args:
body (InlineObject):
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[(InlineResponse201, int, typing.Dict)]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=True)
kwargs['body'] = \
body
return self.portfolio_create_post_endpoint.call_with_http_info(**kwargs)
def portfolio_delete_post(
self,
**kwargs
) -> InlineResponse200:
"""Delete a portfolio. # noqa: E501
Delete a portfolio. # noqa: E501
This method makes a synchronous HTTP request. Returns the http data only
Keyword Args:
body (InlineObject1): [optional]
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
InlineResponse200
Response Object
| |
fres = stringify(dicttoxml(res))
fmt_ext = 'xml'
if pretty:
zdom = minidom.parseString(fres)
fres = zdom.toprettyxml()
else:
raise ValueError(f"Output format {out_format!r} is not a valid output format.")
if empty(destination, itr=True) or destination in ['', '-', '/dev/stdout']:
if pretty:
print_std(fres)
else:
sys.stdout.write(fres)
sys.stdout.flush()
else:
print_err(f"[yellow]Writing generated {fmt_ext.upper()!r} data to file:[/] {destination!r}")
with open(destination, 'w') as fh:
fh.write(fres)
print_err(f"[green]Successfully wrote {fmt_ext.upper()!r} data to file:[/] {destination!r}")
def cmd_neigh(opt: argparse.Namespace):
asn: int = extract_number(opt.asn, int)
output: Optional[str] = opt.output
output = Path(output).expanduser().resolve() if not empty(output) else output
pretty: bool = opt.pretty
xasn = lookup_asn(asn)[0]
if empty(opt.ixp_name):
ixlist = xasn.ixps
else:
ixlist = xasn.find_ixps(opt.ixp_name, exact=opt.exact)
if opt.limit > 0:
ixlist = ixlist[:opt.limit]
kargs = dict(
port='', lock_version=opt.lock_version,
os=opt.os, peer_template=opt.peer_template, peer_policy_v4=opt.peer_policy_v4,
peer_policy_v6=opt.peer_policy_v6, peer_session=opt.peer_session,
trim_name=opt.trim_name, trim_words=opt.trim_words,
use_max_prefixes=opt.use_max_prefixes
# use_max_prefixes=True, max_prefixes_v4=None, max_prefixes_v6=None,
# max_prefix_config=None
)
if not empty(opt.as_name): kargs['as_name'] = opt.as_name
if not empty(opt.max_prefixes_v4): kargs['max_prefixes_v4'] = opt.max_prefixes_v4
if not empty(opt.max_prefixes_v6): kargs['max_prefixes_v6'] = opt.max_prefixes_v6
for idx, ix in enumerate(ixlist):
nb = generate_neigh(
ix, xasn, peer_idx=idx + 1, **kargs
)
if not empty(output):
print_err(f"[yellow]Writing neighbour config to file:[/] {output!s}")
with open(output, 'w') as fh:
fh.write(nb)
print_err(f"[green]Successfully wrote neighbour config to file:[/] {output!s}")
else:
if pretty:
print_std(nb)
else:
sys.stdout.write(nb)
sys.stdout.flush()
def cmd_sync(opt: argparse.Namespace = None):
print_err('[cyan]Running update_db() - attempting to sync PeeringDB to our local DB...[/]')
res = update_db(settings.PDB_CONFIG)
print_err("[yellow]Result from update_db():[/]", res)
print_err('[green] +++ Finished running update_db() - Synced PeeringDB to our local DB :) +++ [/]')
return 0
def cmd_dump_config(opt: argparse.Namespace = None):
out = opt.output if opt else None
if not empty(out) and out not in ['', '-', '/dev/stdout']:
out = Path(out).expanduser().resolve()
print_err("[yellow]Outputting dumped config to file:[/]", out)
cfg = settings.dump_config()
if empty(out) or out in ['', '-', '/dev/stdout']:
print_std(cfg)
if not empty(out) and out not in ['', '-', '/dev/stdout']:
with open(out, 'w') as fh:
fh.write(cfg)
print_err("[green]Successfully dumped config to file:[/]", out)
def cmd_conf_gen(opt: argparse.Namespace):
out = opt.output
cfgtype = opt.name
ex_path = settings.APP_DIR / 'extras' / CFGTYPE_MAP.get(cfgtype, cfgtype)
if not ex_path.exists():
print_err(f'[red]ERROR: Config file {ex_path!s} does not exist![/]')
return 5
if not empty(out) and out not in ['', '-', '/dev/stdout']:
out = Path(out).expanduser().resolve()
print_err("[yellow]Outputting dumped config to file:[/]", out)
with open(ex_path, 'r') as exmp_fh:
cfg = exmp_fh.read()
if empty(out) or out in ['', '-', '/dev/stdout']:
print_std(cfg)
if not empty(out) and out not in ['', '-', '/dev/stdout']:
with open(out, 'w') as fh:
fh.write(cfg)
print_err("[green]Successfully dumped config to file:[/]", out)
return 0
def main():
parser = ErrHelpParser(
sys.argv[0],
description=textwrap.dedent("""
Neighbour Peering Generator
A tool to display ASN peering information, generate BGP neighbour configs for datacenter routers/switches,
and more - by querying PeeringDB.com.
(C) 2021 Privex Inc. - https://www.privex.io
Official Repo: https://github.com/Privex/neighgen
"""),
epilog=textwrap.dedent(f"""
Examples:
##############
# asinfo
##############
Display PeeringDB information for AS210083 (Privex) as pretty printed tables:
{sys.argv[0]} asinfo 210083
Display PeeringDB information for AS210083 (Privex) as pretty printed tables,
and include internet exchange information:
{sys.argv[0]} asinfo -x 210083
Display PeeringDB information for AS210083 (Privex) as pretty printed tables,
and include both internet exchange information, and facility information:
{sys.argv[0]} asinfo -x -F as210083
##############
# asinfo-raw
##############
Display PeeringDB info for AS210083 in programmatic form - which by default is JSON:
{sys.argv[0]} asinfo-raw 210083
Display PeeringDB info for AS210083 in programmatic form, including both IXP and facility info:
{sys.argv[0]} asinfo-raw -x -F 210083
Display ONLY IXP information from PeeringDB for AS210083 in programmatic form:
{sys.argv[0]} asinfo-raw -OX 210083
Display ONLY Facility information from PeeringDB for AS210083 in programmatic form:
{sys.argv[0]} asinfo-raw -OF 210083
Display ONLY IXP information from PeeringDB for AS210083 in programmatic form - but as YAML
instead of JSON:
{sys.argv[0]} asinfo-raw -OX 210083 yml
Display PeeringDB info for AS210083 in programmatic form, including both IXP and facility info,
but as XML instead of JSON:
{sys.argv[0]} asinfo-raw -x -F 210083 xml
##############
# neigh
##############
Display neighbour configuration for peering with AS210083 at all of their IXPs,
using the default OS config format 'nxos' (Cisco NX-OS):
{sys.argv[0]} neigh 210083
Display neighbour configuration for peering with AS210083 at only exchanges with 'ams-ix'
in their name, using the default OS config format 'nxos' (Cisco NX-OS):
{sys.argv[0]} neigh 210083 ams-ix
Display neighbour configuration for peering with AS210083 at only exchanges with 'ams-ix'
in their name, this time we manually specify that we want the config to be formatted
for use with 'ios' (Cisco IOS).
{sys.argv[0]} neigh -o ios 210083 ams-ix
Same as previous, but we set the peer-policy for v4 and v6 to blank, which disables
it from adding peer-policy neighbour commands:
{sys.argv[0]} neigh -p4 '' -p6 '' -o ios 210083 ams-ix
The network AS13335 peers at several different AMS-IX regions, so to limit the neighbours to
use only the IXP called "AMS-IX", and not "AMS-IX Hong Kong" or "AMS-IX Caribbean",
we use "-X" to enable exact IXP matching (the matching isn't case sensitive though).
This ensure it only uses IXP peers on the exchange named "AMS-IX" and not their
other regions.
{sys.argv[0]} neigh -X 13335 ams-ix
"""), formatter_class=argparse.RawTextHelpFormatter
)
parser.set_defaults(cmd=None)
sp = parser.add_subparsers()
sync_parser = sp.add_parser('sync', help='Sync PeeringDB to our local DB')
sync_parser.set_defaults(cmd=cmd_sync)
dump_config_parser = sp.add_parser('dump_config', help='Dump the running config from memory as YAML')
dump_config_parser.add_argument(
'-o', '--output', '--destination', dest='output', default=None,
help='File/device to output the generated data to. Defaults to blank - which writes to stdout.'
)
dump_config_parser.set_defaults(cmd=cmd_dump_config)
conf_gen = sp.add_parser('gen_config', help='Reads an example config from neighgen/extras, for you to generate a base config')
conf_gen.add_argument(
'name', choices=CFGTYPE_MAP,
help=f"Select which type of example config you want to generate. Choices: {', '.join(CFGTYPE_MAP.keys())}"
)
conf_gen.add_argument(
'-o', '--output', '--destination', dest='output', default=None,
help='File/device to output the generated data to. Defaults to blank - which writes to stdout.'
)
conf_gen.set_defaults(cmd=cmd_conf_gen)
asparser = sp.add_parser('asinfo', help='Outputs info about a given ASN')
asparser.add_argument('asn')
asparser.add_argument(
'-x', '--exchanges', '--list-exchanges', action='store_true', dest='list_ixps', default=False,
help='Display a table of IXPs which the given ASN is a member of. Disabled by default.'
)
asparser.add_argument(
'-F', '--facilities', '--list-facilities', action='store_true', dest='list_facs', default=False,
help='Display a table of facilities which the given ASN is present within. Disabled by default.'
)
asparser.set_defaults(cmd=cmd_asinfo)
raw_asparser = sp.add_parser('asinfo-raw', help='Outputs info about a given ASN as JSON, XML, or YML')
raw_asparser.add_argument('asn')
raw_asparser.add_argument('out_format', default='json', choices=[
'js', 'jsn', 'json', 'y', 'yml', 'yaml', 'ym', 'yl', 'xml', 'xm', 'x', 'htm', 'html', 'ml'
], nargs='?')
raw_asparser.add_argument(
'-o', '--output', '--destination', dest='destination', default=None,
help='File/device to output the generated data to. Defaults to blank - which writes to stdout.'
)
raw_asparser.add_argument(
'-x', '--exchanges', '--list-exchanges', action='store_true', dest='list_ixps', default=False,
help='Display a table of IXPs which the given ASN is a member of. Disabled by default.'
)
raw_asparser.add_argument(
'-F', '--facilities', '--list-facilities', action='store_true', dest='list_facs', default=False,
help='Display a table of facilities which the given ASN is present within. Disabled by default.'
)
raw_asparser.add_argument(
'-OX', '--only-exchanges', '--only-ixps', action='store_true', dest='only_ixps', default=False,
help="Print ONLY information about the ASN's exchanges."
)
raw_asparser.add_argument(
'-OF', '--only-facilities', '--only-facs', action='store_true', dest='only_facs', default=False,
help="Print ONLY information about the ASN's facilities."
)
raw_asparser.add_argument(
'-np', '--no-pretty', '--flat', action='store_false', dest='pretty', default=True,
help='Disable pretty printing - print raw JSON/YML/XML'
)
raw_asparser.set_defaults(cmd=cmd_asinfo_raw)
neighparser = sp.add_parser('neigh', help='Generate a BGP neighbour config for a given ASN via PeeringDB')
neighparser.add_argument('asn')
neighparser.add_argument('ixp_name', nargs='?', default=None)
neighparser.add_argument('-X', '--exact-match', default=False, action='store_true', dest='exact',
help=f"Match ixp_name against IXP names EXACTLY.")
neighparser.add_argument('-L', '--limit', default=0, type=int, dest='limit',
help=f"Set to a number >=1 to limit how many IXPs can be matched by the query. "
f"This defaults to 0 (unlimited IXPs can match).")
neighparser.add_argument(
'-np', '--no-pretty', '--flat', action='store_false', dest='pretty', default=True,
help='Disable pretty printing - print raw JSON/YML/XML'
)
neighparser.add_argument('-o', '--os', default=settings.appcfg.default_os, choices=list(appcfg.template_map.keys()),
help=f"The OS to generate the config for. Options: {', '.join(appcfg.template_map.keys())}")
neighparser.add_argument('-f', '--output', default=None, dest='output',
help=f"The file/device to output the generated neighbour config to. By default, this is blank, "
f"which means the config will be outputted to stdout.")
neighparser.add_argument('-pt', '--peer-template', default=appcfg.peer_template, dest='peer_template',
help=f"The name of the peer template to use. Default: {appcfg.peer_template}")
neighparser.add_argument('-ps', '--peer-session', default=appcfg.peer_session, dest='peer_session',
| |
params["organizationgroup"] is None
): # noqa: E501
raise ValueError(
"Missing the required parameter `organizationgroup` when calling `get_all_roles_associated_with_organization_group`"
) # noqa: E501
collection_formats = {}
path_params = {}
if "organizationgroup" in params:
path_params["organizationgroup"] = params["organizationgroup"] # noqa: E501
query_params = []
if "role" in params:
query_params.append(("role", params["role"])) # 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 = ["Bearer"] # noqa: E501
return self.api_client.call_api(
"/config/authorization/organizationgroup/{organizationgroup}/roles",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="list[str]", # 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_all_users(self, **kwargs): # noqa: E501
"""Get users # noqa: E501
Get users # 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_all_users(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The user name.
:param str full_name: The user full name.
:param str description: The user description.
:return: list[UserHeader]
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_all_users_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_all_users_with_http_info(**kwargs) # noqa: E501
return data
def get_all_users_with_http_info(self, **kwargs): # noqa: E501
"""Get users # noqa: E501
Get users # 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_all_users_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The user name.
:param str full_name: The user full name.
:param str description: The user description.
:return: list[UserHeader]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["name", "full_name", "description"] # 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_all_users" % key
)
params[key] = val
del params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
if "name" in params:
query_params.append(("name", params["name"])) # noqa: E501
if "full_name" in params:
query_params.append(("fullName", params["full_name"])) # noqa: E501
if "description" in params:
query_params.append(("description", params["description"])) # 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 = ["Bearer"] # noqa: E501
return self.api_client.call_api(
"/config/authorization/users",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="list[UserHeader]", # 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_archive_statistics(self, **kwargs): # noqa: E501
"""Get Workload Archiving statistics # noqa: E501
Get list of statistical information for each Archiving rule and total information about the number of jobs that have been archived, data size of all job logs and outputs that have been archived, size of the Workload Archiving database including all tables and indexes and percentage of disk space used on the Workload Archiving server # 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_archive_statistics(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: RulesStatisticListSummary
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_archive_statistics_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_archive_statistics_with_http_info(**kwargs) # noqa: E501
return data
def get_archive_statistics_with_http_info(self, **kwargs): # noqa: E501
"""Get Workload Archiving statistics # noqa: E501
Get list of statistical information for each Archiving rule and total information about the number of jobs that have been archived, data size of all job logs and outputs that have been archived, size of the Workload Archiving database including all tables and indexes and percentage of disk space used on the Workload Archiving server # 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_archive_statistics_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: RulesStatisticListSummary
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # 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_archive_statistics" % key
)
params[key] = val
del params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
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 = ["Bearer"] # noqa: E501
return self.api_client.call_api(
"/config/archive/statistics",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RulesStatisticListSummary", # 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_external_user_authorized_folders(self, name, **kwargs): # noqa: E501
"""Get MFT external user authorized folders # noqa: E501
Get MFT external user authorized folders # 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_external_user_authorized_folders(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The external user name. (required)
:return: list[str]
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_external_user_authorized_folders_with_http_info(
name, **kwargs
) # noqa: E501
else:
(data) = self.get_external_user_authorized_folders_with_http_info(
name, **kwargs
) # noqa: E501
return data
def get_external_user_authorized_folders_with_http_info(
self, name, **kwargs
): # noqa: E501
"""Get MFT external user authorized folders # noqa: E501
Get MFT external user authorized folders # 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_external_user_authorized_folders_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The external user name. (required)
:return: list[str]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["name"] # 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_external_user_authorized_folders" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and (
"name" not in params or params["name"] is None
): # noqa: E501
raise ValueError(
"Missing the required parameter `name` when calling `get_external_user_authorized_folders`"
) # noqa: E501
collection_formats = {}
path_params = {}
if "name" in params:
path_params["name"] = params["name"] # noqa: E501
query_params = []
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 = ["Bearer"] # noqa: E501
return self.api_client.call_api(
"/config/mft/externaluser/{name}/virtualfolders",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="list[str]", # 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_external_users(self, **kwargs): # noqa: E501
"""Get MFT external users that match the search criteria. # noqa: E501
Get MFT external users that match the search criteria. # 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_external_users(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: The user name.
:param str email: The user email.
:param str description: The user description.
:param str company: The user company.
:param str phone_number: The user phoneNumber.
:return: list[ExternalUserData]
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_external_users_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_external_users_with_http_info(**kwargs) # noqa: E501
return data
def get_external_users_with_http_info(self, **kwargs): # noqa: E501
"""Get MFT external users that match the search criteria. # noqa: E501
Get MFT external users that match the search criteria. # 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_external_users_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param | |
= data_array[:, 4]
temperature = data_array[:, 5]
crowdedness = data_array[:, 6]
knowledge_of_surroundings = data_array[:, 7]
season = data_array[:, 8]
budget = data_array[:, 9]
daytime = data_array[:, 10]
weather = data_array[:, 11]
companion = data_array[:, 12]
mood = data_array[:, 13]
weekday = data_array[:, 14]
travelgoal = data_array[:, 15]
means_of_transport = data_array[:, 16]
category = data_array[:, 17]
distance_s = set(list(distance))
distance_s.discard(-1)
distance_dict = {f: i for i, f in enumerate(distance_s, start=0)}
time_available_s = set(list(time_available))
time_available_s.discard(-1)
time_available_dict = {f: i for i, f in enumerate(time_available_s, start=len(distance_dict))}
temperature_s = set(list(temperature))
temperature_s.discard(-1)
temperature_dict = {f: i for i, f in
enumerate(temperature_s, start=len(distance_dict) + len(time_available_dict))}
crowdedness_s = set(list(crowdedness))
crowdedness_s.discard(-1)
crowdedness_dict = {f: i for i, f in enumerate(crowdedness_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict))}
knowledge_of_surroundings_s = set(list(knowledge_of_surroundings))
knowledge_of_surroundings_s.discard(-1)
knowledge_of_surroundings_dict = {f: i for i, f in enumerate(knowledge_of_surroundings_s,
start=len(distance_dict) + len(
time_available_dict) + len(
temperature_dict) + len(crowdedness_dict))}
season_s = set(list(season))
season_s.discard(-1)
season_dict = {f: i for i, f in enumerate(season_s, start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(knowledge_of_surroundings_dict))}
budget_s = set(list(budget))
budget_s.discard(-1)
budget_dict = {f: i for i, f in enumerate(budget_s, start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(knowledge_of_surroundings_dict) + len(season_dict))}
daytime_s = set(list(daytime))
daytime_s.discard(-1)
daytime_dict = {f: i for i, f in enumerate(daytime_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict))}
weather_s = set(list(weather))
weather_s.discard(-1)
weather_dict = {f: i for i, f in enumerate(weather_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict) + len(daytime_dict))}
companion_s = set(list(companion))
companion_s.discard(-1)
companion_dict = {f: i for i, f in enumerate(companion_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict) + len(daytime_dict) + len(weather_dict))}
mood_s = set(list(mood))
mood_s.discard(-1)
mood_dict = {f: i for i, f in enumerate(mood_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict) + len(daytime_dict) + len(weather_dict) + len(
companion_dict))}
weekday_s = set(list(weekday))
weekday_s.discard(-1)
weekday_dict = {f: i for i, f in enumerate(weekday_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict) + len(daytime_dict) + len(weather_dict) + len(
companion_dict) + len(mood_dict))}
travelgoal_s = set(list(travelgoal))
travelgoal_s.discard(-1)
travelgoal_dict = {f: i for i, f in enumerate(travelgoal_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict) + len(daytime_dict) + len(weather_dict) + len(
companion_dict) + len(mood_dict) + len(weekday_dict))}
means_of_transport_s = set(list(means_of_transport))
means_of_transport_s.discard(-1)
means_of_transport_dict = {f: i for i, f in enumerate(means_of_transport_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(
season_dict) + len(
budget_dict) + len(daytime_dict) + len(
weather_dict) + len(companion_dict) + len(
mood_dict) + len(weekday_dict) + len(
travelgoal_dict))}
category_s = set(list(category))
category_s.discard(-1)
category_dict = {f: i for i, f in enumerate(category_s,
start=len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(
season_dict) + len(
budget_dict) + len(daytime_dict) + len(
weather_dict) + len(companion_dict) + len(
mood_dict) + len(weekday_dict) + len(
travelgoal_dict))}
N_edgeFeature = len(distance_dict) + len(time_available_dict) + len(
temperature_dict) + len(crowdedness_dict) + len(
knowledge_of_surroundings_dict) + len(season_dict) + len(
budget_dict) + len(daytime_dict) + len(weather_dict) + len(companion_dict) + len(mood_dict) + len(
weekday_dict) \
+ len(travelgoal_dict) + len(means_of_transport_dict) + +len(category_dict)
print(f"N_edgeFeature {N_edgeFeature}")
u_nodes_ratings, u_dict, num_users = map_data(u_nodes_ratings)
v_nodes_ratings, v_dict, num_items = map_data(v_nodes_ratings)
edge_features = np.zeros((num_users, num_items, N_edgeFeature), dtype=np.float32) # UxIxC
edge_features_list=np.zeros((len(u_nodes_ratings), N_edgeFeature),dtype=np.float32)
edge_features_list_f=[]
j = 0
i=0
for _, row in data.iterrows():
u_id = row['u_nodes']
v_id = row['v_nodes']
if v_id in v_dict.keys() and u_id in u_dict.keys():
if row['distance'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], distance_dict[row['distance']]] = 1.
edge_features_list[i,distance_dict[row['distance']]] = 1.
if row['time_available'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], time_available_dict[row['time_available']]] = 1.
edge_features_list[i, time_available_dict[row['time_available']]] = 1.
if row['temperature'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], temperature_dict[row['temperature']]] = 1.
edge_features_list[i, temperature_dict[row['temperature']]] = 1.
if row['crowdedness'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], crowdedness_dict[row['crowdedness']]] = 1.
edge_features_list[i, crowdedness_dict[row['crowdedness']]] = 1.
if row['knowledge_of_surroundings'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], knowledge_of_surroundings_dict[row['knowledge_of_surroundings']]] = 1.
edge_features_list[i, knowledge_of_surroundings_dict[row['knowledge_of_surroundings']]] = 1.
if row['season'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], season_dict[row['season']]] = 1.
edge_features_list[i, season_dict[row['season']]] = 1.
if row['budget'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], budget_dict[row['budget']]] = 1.
edge_features_list[i,budget_dict[row['budget']]] = 1.
if row['daytime'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], daytime_dict[row['daytime']]] = 1.
edge_features_list[i, daytime_dict[row['daytime']]] = 1.
if row['weather'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], weather_dict[row['weather']]] = 1.
edge_features_list[i, weather_dict[row['weather']]] = 1.
if row['companion'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], companion_dict[row['companion']]] = 1.
edge_features_list[i, companion_dict[row['companion']]] = 1.
if row['mood'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], mood_dict[row['mood']]] = 1.
edge_features_list[i, mood_dict[row['mood']]] = 1.
if row['weekday'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], weekday_dict[row['weekday']]] = 1.
edge_features_list[i, weekday_dict[row['weekday']]] = 1.
if row['travelgoal'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], travelgoal_dict[row['travelgoal']]] = 1.
edge_features_list[i, travelgoal_dict[row['travelgoal']]] = 1.
if row['means_of_transport'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], means_of_transport_dict[row['means_of_transport']]] = 1.
edge_features_list[i, means_of_transport_dict[row['means_of_transport']]] = 1.
if row['category'] != -1:
edge_features[u_dict[u_id], v_dict[v_id], category_dict[row['category']]] = 1.
edge_features_list[i, category_dict[row['category']]] = 1.
temp1 = edge_features_list[i, :].tolist()
edge_features_list_f.append(temp1)
j += 1
i +=1
u_nodes_ratings, v_nodes_ratings = u_nodes_ratings.astype(np.int64), v_nodes_ratings.astype(np.int32)
ratings = ratings.astype(np.float64)
##############################################################################################################
# item features (genres)= None
#############################################################################################################
# User feature
sep = '\t'
users_file = data_dir + files[1]
users_headers = ['user_id', 'age', 'sex', 'opennessToExperience', 'conscientiousness', 'extraversion',
'agreeableness', 'emotionalStability']
users_df = pd.read_csv(users_file, sep=sep, header=None,
names=users_headers, engine='python')
sex_dict = {'m': 0., 'f': 1.}
age = users_df['age'].values
age_max = age.max()
opennessToExperience_set = set(users_df['opennessToExperience'].values.tolist())
opennessToExperience_set.discard(-1)
opennessToExperience_dict = {f: i for i, f in enumerate(opennessToExperience_set, start=2)}
conscientiousness_set = set(users_df['conscientiousness'].values.tolist())
conscientiousness_set.discard(-1)
conscientiousness_dict = {f: i for i, f in
enumerate(conscientiousness_set, start=2 + len(opennessToExperience_dict))}
extraversion_set = set(users_df['extraversion'].values.tolist())
extraversion_set.discard(-1)
extraversion_dict = {f: i for i, f in enumerate(extraversion_set,
start=2 + len(opennessToExperience_dict) + len(
conscientiousness_dict))}
agreeableness_set = set(users_df['agreeableness'].values.tolist())
agreeableness_set.discard(-1)
agreeableness_dict = {f: i for i, f in enumerate(agreeableness_set,
start=2 + len(opennessToExperience_dict) + len(
conscientiousness_dict) + len(extraversion_dict))}
emotionalStability_set = set(users_df['emotionalStability'].values.tolist())
emotionalStability_set.discard(-1)
emotionalStability_dict = {f: i for i, f in enumerate(emotionalStability_set,
start=2 + len(opennessToExperience_dict) + len(
conscientiousness_dict) + len(
extraversion_dict) + len(agreeableness_dict))}
num_feats = 2 + len(opennessToExperience_dict) + len(conscientiousness_dict) + len(agreeableness_dict) + len(
emotionalStability_dict) + len(extraversion_dict)
u_features = np.zeros((num_users, num_feats), dtype=np.float32)
for _, row in users_df.iterrows():
u_id = row['user_id']
if u_id in u_dict.keys():
# age np.float(age_max)
if row['age'] != -1: u_features[u_dict[u_id], 0] = row['age'] / np.float(age_max)
# gender
if row['sex'] != '-1': u_features[u_dict[u_id], 1] = sex_dict[row['sex']]
if row['opennessToExperience'] != -1: u_features[
u_dict[u_id], opennessToExperience_dict[row['opennessToExperience']]] = 1.
if row['conscientiousness'] != -1: u_features[
u_dict[u_id], conscientiousness_dict[row['conscientiousness']]] = 1.
if row['emotionalStability'] != -1: u_features[
u_dict[u_id], emotionalStability_dict[row['emotionalStability']]] = 1.
if row['agreeableness'] != -1: u_features[u_dict[u_id], agreeableness_dict[row['agreeableness']]] = 1.
if row['extraversion'] != -1: u_features[u_dict[u_id], extraversion_dict[row['extraversion']]] = 1.
u_features = sp.csr_matrix(u_features)
# edge_features= sp.csr_matrix(edge_features)
ind = np.array(np.where(edge_features != 0)).T # (u v c) #non zero indices
elif fname == 'LDOS':
print("I am LDOS")
data_dir = '...\data\LDOS'
files = ['/LDOS-User-Item-RatingContext.txt', '/LDOS-ItemFeatures.txt', '/User-info.txt', '/LDOSSimilarUsers.txt']
sep = '\t'
filename = data_dir + files[0]
print(f"filename {filename}")
dtypes = {
'u_nodes': np.int32, 'v_nodes': np.int32,
'ratings': np.float32}
data = pd.read_csv(
filename, sep=sep, header=None,
names=['u_nodes', 'v_nodes', 'ratings', 'time', 'daytype', 'season', 'location', 'weather', 'social',
'endEmo', 'dominantEmo', 'mood', 'physical', 'decision', 'interaction'], dtype=dtypes)
# shuffle here like cf-nade paper with python's own random class
# make sure to convert to list, otherwise random.shuffle acts weird on it without a warning
data_array = data.values.tolist()
# random.seed(seed)
# random.shuffle(data_array)
data_array = np.array(data_array)
u_nodes_ratings = data_array[:, 0].astype(dtypes['u_nodes'])
v_nodes_ratings = data_array[:, 1].astype(dtypes['v_nodes'])
ratings = data_array[:, 2].astype(dtypes['ratings'])
rating_dict = {r: i for i, r in enumerate(np.sort(np.unique(ratings)).tolist())} # {0:1, 1:2, 2:3, 3:4, 4:5}
print(f"rating_dict {rating_dict}")
time = data_array[:, 3]
daytype = data_array[:, 4]
season = data_array[:, 5]
location = data_array[:, 6]
weather = data_array[:, 7]
social = data_array[:, 8]
endEmo = data_array[:, 9]
dominantEmo = data_array[:, 10]
mood = data_array[:, 11]
physical = data_array[:, 12]
decision = data_array[:, 13]
interaction = data_array[:, 14]
time_s = set(list(time))
time_s.discard(0)
time_dict = {f: i for i, f in enumerate(time_s, start=0)}
daytype_s = set(list(daytype))
daytype_s.discard(0)
daytype_dict = {f: i for i, f in enumerate(daytype_s, start=4)}
season_s = set(list(season))
season_s.discard(0)
season_dict = {f: i for i, f in enumerate(season_s, start=7)}
location_s = set(list(location))
location_s.discard(0)
location_dict = {f: i for i, f in enumerate(location_s, start=11)}
weather_s = set(list(weather))
weather_s.discard(0)
weather_dict = {f: i for i, f in enumerate(weather_s, start=14)}
social_s = set(list(social))
social_s.discard(0)
social_dict | |
<reponame>jp2011/spatial-poisson-mixtures
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.gaussian_process.kernels import Matern, RBF
from src.numeric.kronecker_algebra import kron_invert_matrices, kron_mv_prod, kron_log_det
class BetaPriorWithIntercept:
"""
Normal-InvGamma prior for the regression coefficients. The intercept is given a uniform (improper) prior.
"""
def __init__(self, a=1, b=0.001):
self.a = a
self.b = b
def log_pdf(self, beta, J):
non_intercept_beta = np.delete(beta, np.arange(0, beta.shape[0], J))
output = (-self.a - 0.5) * np.sum(np.log(0.5 * np.square(non_intercept_beta) + self.b))
return output
def nabla_beta_log_pdf(self, beta, J):
"""
Return the gradient of the log of the pdf of the prior with respect to the beta values.
"""
part1 = (-self.a - 0.5) * beta
part2 = 0.5 * np.square(beta) + self.b
gradient = np.divide(part1, part2)
gradient[::J] = 0 # intercept has uniform prior
return gradient
class BetaPriorNoIntercept:
"""
Normal-InvGamma prior for the regression coefficients which do not include the intercept.
"""
def __init__(self, a=1, b=0.001):
self.a = a
self.b = b
def log_pdf(self, beta):
"""
Return the log of the pdf of the prior for the regression coefficients.
"""
output = (-self.a - 0.5) * np.sum(np.log(0.5 * np.square(beta) + self.b))
return output
def nabla_beta_log_pdf(self, beta):
"""
Return the gradient of the log of the pdf of the prior with respect to the beta values.
"""
part1 = (-self.a - 0.5) * beta
part2 = 0.5 * np.square(beta) + self.b
gradient = np.divide(part1, part2)
return gradient
class GaussianPrior:
"""A generic prior for N iid Gaussian random variables"""
def __init__(self, mean, variance):
self.mean = mean
self.variance = variance
def log_pdf(self, x):
output = -0.5 * np.dot(np.square(x - self.mean), 1 / self.variance)
return output
def nabla_x_log_pdf(self, x):
"""
The gradient of the log-pdf with respect to the values of x
"""
output = -1 * np.divide(x - self.mean, self.variance)
return output
class GPPrior:
"""
Generic class for the zero-mean Gaussian process prior with the covariance function that has paremeters theta.
"""
def __init__(self):
pass
def get_cov_mmatrix(self, *, variance=1, lengthscale=1):
pass
def get_logpdf(self, *, variance=1, lengthscale=1, f=None):
pass
def get_nabla_f(self, *, variance=None, lengthscale=None, f=None):
pass
def get_nabla_theta(self, *, variance=None, lengthscale=None, f=None):
pass
class GPGridPriorMatern:
"""
Gaussian process prior for a 2D grid with zero-mean and Matern covariance function.
Given that the domain is a grid, Kronecker algebra can be used to speed up the computations. Before reading the
code, we recommend reading the relevant parts of PhD thesis of Yunus Saatci:
<NAME>. 2012. ‘Scalable Inference for Structured Gaussian Process Models’. PhD Thesis, Citeseer.
"""
def __init__(self, coord_x=None, coord_y=None, smoothness=1.5):
self.smoothness = smoothness
self.x_coordinates = np.reshape(coord_x, (-1, 1))
self.y_coordinates = np.reshape(coord_y, (-1, 1))
def get_cov_matrix(self, *, variance=1, lengthscale=1, expanded=False):
k1 = Matern(length_scale=lengthscale, nu=self.smoothness)
k2 = Matern(length_scale=lengthscale, nu=self.smoothness)
# we need to split the signal variance into two parts
K1 = np.sqrt(variance) * k1(self.x_coordinates)
K2 = np.sqrt(variance) * k2(self.y_coordinates)
return np.kron(K1, K2) if expanded else [K1, K2]
def get_logpdf(self, *, variance=1, lengthscale=1, f=None):
"""
The log-pdf of the GP
"""
Ks = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
log_det_K = kron_log_det(Ks)
Ks_inv = kron_invert_matrices(Ks)
return -0.5 * log_det_K - 0.5 * np.dot(f, kron_mv_prod(Ks_inv, f))
def get_nabla_f(self, *, variance=None, lengthscale=None, f=None):
"""
Gradient of the log-pdf of the GP with respect to the GP values.
"""
Ks = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
Ks_inv = kron_invert_matrices(Ks)
output = -1 * kron_mv_prod(Ks_inv, f)
return output
def get_nabla_theta(self, *, variance=1, lengthscale=1, f=None):
"""
Gradient of the log-pdf of the GP with respect to the hyper-parameters.
"""
k1 = Matern(length_scale=lengthscale, nu=self.smoothness)
k2 = Matern(length_scale=lengthscale, nu=self.smoothness)
C1, C_grad_1 = k1(self.x_coordinates, eval_gradient=True)
C2, C_grad_2 = k2(self.y_coordinates, eval_gradient=True)
# we need to split the signal variance into two parts
K1 = np.sqrt(variance) * C1
K2 = np.sqrt(variance) * C2
Ks = [K1, K2]
K_invs = kron_invert_matrices(Ks)
K1_nabla_var = (0.5 / np.sqrt(variance)) * C1
K2_nabla_var = (0.5 / np.sqrt(variance)) * C2
K1_nabla_l = np.sqrt(variance) * C_grad_1[:, :, 0]
K2_nabla_l = np.sqrt(variance) * C_grad_2[:, :, 0]
trace_comp_lengtscale = -0.5 * (
np.trace(np.dot(K_invs[0], K1_nabla_l)) * np.trace(np.dot(K_invs[1], Ks[1])) + np.trace(
np.dot(K_invs[1], K2_nabla_l)) * np.trace(np.dot(K_invs[0], Ks[0])))
trace_comp_var = -0.5 * (
np.trace(np.dot(K_invs[0], K1_nabla_var)) * np.trace(np.dot(K_invs[1], Ks[1])) + np.trace(
np.dot(K_invs[1], K2_nabla_var)) * np.trace(np.dot(K_invs[0], Ks[0])))
# non-trace component l
temp = kron_mv_prod(K_invs, f)
temp = kron_mv_prod([K1_nabla_l, K2], temp) + kron_mv_prod([K1, K2_nabla_l], temp)
temp = kron_mv_prod(K_invs, temp)
non_trace_lengthscale = 0.5 * np.dot(f, temp)
# non-trace component var
temp = kron_mv_prod(K_invs, f)
temp = kron_mv_prod([K1_nabla_var, K2], temp) + kron_mv_prod([K1, K2_nabla_var], temp)
temp = kron_mv_prod(K_invs, temp)
non_trace_var = 0.5 * np.dot(f, temp)
return np.asarray([trace_comp_var + non_trace_var, trace_comp_lengtscale + non_trace_lengthscale])
class GPNonGridPriorSqExp:
"""
Gaussian process prior for an arbitrary 2D domain with zero-mean and squared exponential covariance function.
"""
def __init__(self, coord_x=None, coord_y=None):
self.x_coordinates = coord_x
self.y_coordinates = coord_y
self.cov_func = RBF
def get_cov_matrix(self, *, variance=1, lengthscale=1):
self.XY = np.stack((self.x_coordinates, self.y_coordinates), axis=1)
distances = cdist(self.XY, self.XY) / lengthscale
K = np.sqrt(variance) * np.exp(-0.5 * np.square(distances))
return K
def get_logpdf(self, *, variance=1, lengthscale=1, f=None):
K = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
sign, val = np.linalg.slogdet(K)
log_det_K = sign * val
K_inv = np.linalg.pinv(K)
return -0.5 * log_det_K - 0.5 * np.dot(f, np.dot(K_inv, f))
def get_nabla_f(self, *, variance=None, lengthscale=None, f=None):
"""
Gradient of the log-pdf of the GP with respect to the GP values.
"""
K = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
K_inv = np.linalg.pinv(K)
output = -1 * np.dot(K_inv, f)
return output
def get_nabla_theta(self, *, variance=1, lengthscale=1, f=None):
"""
Gradient of the log-pdf of the GP with respect to the hyper-parameters.
"""
K = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
K_inv = np.linalg.pinv(K)
K_nabla_theta = (1 / lengthscale ** 3) * K
K_inv__time__K_nabla_theta = np.dot(K_inv, K_nabla_theta)
part1 = 0.5 * np.dot(f, np.dot(K_inv__time__K_nabla_theta, np.dot(K_inv, f)))
part2 = 0.5 * np.trace(K_inv__time__K_nabla_theta)
return np.asarray([part1 - part2])
class GPNonGridPriorSqExpFixed:
"""
Gaussian process prior for an arbitrary 2D domain with zero-mean and squared exponential covariance function, but
with fixed hyper-parameters.
"""
def __init__(self, coord_x=None, coord_y=None, variance=1, lengthscale=1):
self.cov_func = RBF
self.XY = np.stack((coord_x, coord_y), axis=1)
distances = cdist(self.XY, self.XY) / lengthscale
self.K = np.sqrt(variance) * np.exp(-0.5 * np.square(distances))
self.K_inv = np.linalg.pinv(self.K)
def get_logpdf(self, *, f=None):
return - 0.5 * np.dot(f, np.dot(self.K_inv, f))
def get_nabla_f(self, *, f=None):
"""
Gradient of the log-pdf of the GP with respect to the GP values.
"""
output = -1 * np.dot(self.K_inv, f)
return output
class GPGridPriorSqExp:
"""
Gaussian process prior for a 2D grid with zero-mean and squared exponential covariance function.
Given that the domain is a grid, Kronecker algebra can be used to speed up the computations. Before reading the
code, we recommend reading the relevant parts of PhD thesis of Yunus Saatci:
<NAME>. 2012. ‘Scalable Inference for Structured Gaussian Process Models’. PhD Thesis, Citeseer.
"""
def __init__(self, coord_x=None, coord_y=None):
self.x_coordinates = np.reshape(coord_x, (-1, 1))
self.y_coordinates = np.reshape(coord_y, (-1, 1))
self.cov_func = RBF
def get_cov_matrix(self, *, variance=1, lengthscale=1, expanded=False):
distances_X = cdist(self.x_coordinates, self.x_coordinates) / lengthscale
K1 = np.sqrt(variance) * np.exp(-0.5 * np.square(distances_X))
distances_Y = cdist(self.y_coordinates, self.y_coordinates) / lengthscale
K2 = np.sqrt(variance) * np.exp(-0.5 * np.square(distances_Y))
return np.kron(K1, K2) if expanded else [K1, K2]
def get_logpdf(self, *, variance=1, lengthscale=1, f=None):
Ks = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
log_det_K = kron_log_det(Ks)
Ks_inv = kron_invert_matrices(Ks)
return -0.5 * log_det_K - 0.5 * np.dot(f, kron_mv_prod(Ks_inv, f))
def get_nabla_f(self, *, variance=None, lengthscale=None, f=None):
"""
Gradient of the log-pdf of the GP with respect to the GP values.
"""
Ks = self.get_cov_matrix(variance=variance, lengthscale=lengthscale)
Ks_inv = kron_invert_matrices(Ks)
output = -1 * kron_mv_prod(Ks_inv, f)
return output
def get_nabla_theta(self, *, variance=1, lengthscale=1, f=None):
"""
Gradient of the log-pdf of the GP with respect to the hyper-parameters.
"""
distances_X = cdist(self.x_coordinates, self.x_coordinates) / lengthscale
C1 = np.exp(-0.5 * np.square(distances_X))
C_grad_1 = np.multiply(C1, np.square(distances_X) / lengthscale)
distances_Y = cdist(self.y_coordinates, self.y_coordinates) / lengthscale
C2 = np.exp(-0.5 * np.square(distances_Y))
C_grad_2 = np.multiply(C2, np.square(distances_Y) / lengthscale)
# we need to split the signal variance into two parts
K1 = np.sqrt(variance) * C1
K2 = np.sqrt(variance) * C2
Ks = [K1, K2]
K_invs = kron_invert_matrices(Ks)
K1_nabla_var = (0.5 / np.sqrt(variance)) * C1
K2_nabla_var = (0.5 / np.sqrt(variance)) * C2
K1_nabla_l = np.sqrt(variance) * C_grad_1
K2_nabla_l = np.sqrt(variance) * C_grad_2
trace_comp_lengtscale = -0.5 * (
np.trace(np.dot(K_invs[0], K1_nabla_l)) * np.trace(np.dot(K_invs[1], Ks[1])) + np.trace(
np.dot(K_invs[1], K2_nabla_l)) | |
import gym
import time
import os
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from gym import wrappers
from gym.wrappers.monitoring import stats_recorder, video_recorder
from datetime import datetime
import tensorflow as tf
import random
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Embedding
from tensorflow.keras.optimizers import SGD, RMSprop, Adam, Adamax
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
from pprint import pprint
import cv2
import datetime
from collections import deque
import glob
from shutil import copyfile
import pickle as pkl
import json
import ringbuffer
import argparse
def plot_running_avg(totalrewards, filename):
N = len(totalrewards)
running_avg = np.empty(N)
for t in range(N):
running_avg[t] = totalrewards[max(0, t-100):(t+1)].mean()
plt.plot(running_avg)
plt.title("Running Average")
plt.savefig(filename)
plt.close()
def reset_video_recorder_filename(filename,env):
if env.video_recorder:
env._close_video_recorder()
print("FILENAME IN VR:{}/{} ".format(env.directory, filename))
env.video_recorder = video_recorder.VideoRecorder(
env=env,
path=os.path.join(env.directory,filename),
metadata={'episode_id': env.episode_id},
enabled=env._video_enabled(),
)
env.video_recorder.capture_frame()
def transform(s):
bottom_black_bar = s[84:, 12:]
img = cv2.cvtColor(bottom_black_bar, cv2.COLOR_RGB2GRAY)
bottom_black_bar_bw = cv2.threshold(img, 1, 255, cv2.THRESH_BINARY)[1]
bottom_black_bar_bw = cv2.resize(bottom_black_bar_bw, (84, 12), interpolation = cv2.INTER_NEAREST)
upper_field = s[:84, 6:90] # we crop side of screen as they carry little information
img = cv2.cvtColor(upper_field, cv2.COLOR_RGB2GRAY)
upper_field_bw = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)[1]
upper_field_bw = cv2.resize(upper_field_bw, (10, 10), interpolation = cv2.INTER_NEAREST) # re scaled to 7x7 pixels
upper_field_bw = upper_field_bw.astype('float')/255
car_field = s[66:78, 43:53]
img = cv2.cvtColor(car_field, cv2.COLOR_RGB2GRAY)
car_field_bw = cv2.threshold(img, 80, 255, cv2.THRESH_BINARY)[1]
car_field_t = [car_field_bw[:, 3].mean()/255, car_field_bw[:, 4].mean()/255, car_field_bw[:, 5].mean()/255, car_field_bw[:, 6].mean()/255]
return bottom_black_bar_bw, upper_field_bw, car_field_t
# this function uses the bottom black bar of the screen and extracts steering setting, speed and gyro data
def compute_steering_speed_gyro_abs(a):
right_steering = a[6, 36:46].mean()/255
left_steering = a[6, 26:36].mean()/255
steering = (right_steering - left_steering + 1.0)/2
left_gyro = a[6, 46:60].mean()/255
right_gyro = a[6, 60:76].mean()/255
gyro = (right_gyro - left_gyro + 1.0)/2
speed = a[:, 0][:-2].mean()/255
# if speed>0:
# print("speed element: ", speed)
abs1 = a[:, 6][:-2].mean()/255
abs2 = a[:, 8][:-2].mean()/255
abs3 = a[:, 10][:-2].mean()/255
abs4 = a[:, 12][:-2].mean()/255
return [steering, speed, gyro, abs1, abs2, abs3, abs4]
vector_size = 10*10 + 7 + 4
def create_nn(model_to_load, stack_len, freeze_hidden=False, lr = 0.01):
try:
m = load_model(model_to_load)
print("Loaded pretrained model " + model_to_load)
init_weights = m.get_weights()
# only do this if loading a saved model. why would we freeze weights on a trained model?
if freeze_hidden == True:
m.layers[1].trainable = False # not sure if this is the right way to do this
m.compile(loss='mse', optimizer=Adamax(lr=0.01))
return m, init_weights
except Exception as e:
print("No model loaded, generating new")
model = Sequential()
model.add(Dense(512, input_shape=(stack_len*111,), kernel_initializer="lecun_uniform"))# 7x7 + 3. or 14x14 + 3 # a
model.add(Activation('relu'))
model.add(Dense(11, kernel_initializer="lecun_uniform"))
adamax = Adamax(lr=lr)
model.compile(loss='mse', optimizer=adamax)
if model_to_load:
model.save(model_to_load)
return model, model.get_weights()
class DQNAgent():
'''
This class is modified from https://gist.github.com/lmclupr/b35c89b2f8f81b443166e88b787b03ab#file-race-car-cv2-nn-network-td0-15-possible-actions-ipynb
'''
def __init__(self, num_episodes, model_name=None, carConfig=None, replay_freq=20, freeze_hidden=False, lr=0.01, video_callable=None, train_dir="train_logs_testing"):
K.clear_session()
env = gym.make('CarRacing-v0')
env = wrappers.Monitor(env, 'flaskapp/static', force=False, resume = True, video_callable= video_callable, mode='evaluation', write_upon_reset=False)
self.carConfig = carConfig
self.curr_pointer = 0
self.env = env
self.gamma = 0.99
self.K = 10
self.stack_len = 4 # number of continuous frames to stack
self.model_name = model_name
self.train_dir = train_dir
self.model, self.init_weights = create_nn(model_name, self.stack_len, freeze_hidden, lr) # consecutive steps, 111-element vector for each state
self.target_models = []
for _ in range(self.K):
target_model, _ = create_nn(model_name, self.stack_len)
target_model.set_weights(self.init_weights)
self.target_models.append(target_model)
self.model.summary()
self.replay_freq = replay_freq
if not model_name:
MEMORY_SIZE = 10000
self.memory = ringbuffer.RingBuffer(MEMORY_SIZE)
else:
MEMORY_SIZE = 5000 # smaller memory for retraining
self.memory = ringbuffer.RingBuffer(MEMORY_SIZE)
self.num_episodes = num_episodes
def predict(self, s):
return self.model.predict(np.reshape(s, (1, self.stack_len*111)), verbose=0)[0]
def target_predict(self, s):
total_pred = self.target_models[0].predict(np.reshape(s, (1, self.stack_len*111)), verbose=0)[0]
for i in range(1, self.K):
pred = self.target_models[i].predict(np.reshape(s, (1, self.stack_len*111)), verbose=0)[0]
total_pred += pred
next_pred = total_pred/self.K
return next_pred
def update_targets(self):
model_weights = self.model.get_weights()
self.target_models[self.curr_pointer%self.K].set_weights(model_weights)
def update(self, s, G, B):
self.model.fit(s, np.array(G).reshape(-1, 11), batch_size=B, epochs=1, use_multiprocessing=True, verbose=0)
def sample_action(self, s, eps):
qval = self.predict(s)
if np.random.random() < eps:
return random.randint(0, 10), qval
else:
return np.argmax(qval), qval
def convert_argmax_qval_to_env_action(self, output_value):
# to reduce the action space, gas and brake cannot be applied at the same time.
# as well, steering input and gas/brake cannot be applied at the same time.
# similarly to real life drive, you brake/accelerate in straight line, you coast while sterring.
gas = 0.0
brake = 0.0
steering = 0.0
# output value ranges from 0 to 10
if output_value <= 8:
# steering. brake and gas are zero.
output_value -= 4
steering = float(output_value)/4
elif output_value >= 9 and output_value <= 9:
output_value -= 8
gas = float(output_value)/3 # 33%
elif output_value >= 10 and output_value <= 10:
output_value -= 9
brake = float(output_value)/2 # 50% brakes
else:
print("error")
white = np.ones((round(brake * 100), 10))
black = np.zeros((round(100 - brake * 100), 10))
brake_display = np.concatenate((black, white))*255
white = np.ones((round(gas * 100), 10))
black = np.zeros((round(100 - gas * 100), 10))
gas_display = np.concatenate((black, white))*255
control_display = np.concatenate((brake_display, gas_display), axis=1)
return [steering, gas, brake]
def replay(self, batch_size):
batch = self.memory.sample(batch_size)
old_states = []
old_state_preds = []
for (old_state, argmax_qval, reward, next_state) in batch:
next_state_pred = self.target_predict(next_state)
max_next_pred = np.max(next_state_pred)
old_state_pred = self.predict(old_state)
target_q_value = reward + self.gamma * max_next_pred
y = old_state_pred[:]
y[argmax_qval] = target_q_value
old_states.append(old_state)
old_state_preds.append(y.reshape(1, 11))
old_states = np.reshape(old_states, (batch_size, 111*self.stack_len))
old_state_preds = np.array(old_state_preds).reshape(batch_size, 11)
self.model.fit(old_states, old_state_preds, batch_size=batch_size, epochs=1, verbose=0, workers=10, use_multiprocessing=True)
def play_one(self, eps,train=True,video_path=None):
if self.carConfig:
observation = self.env.reset(config=self.carConfig)
else:
observation = self.env.reset()
if video_path is not None:
print("Setting video path to: {}".format(video_path))
reset_video_recorder_filename(video_path,self.env)
done = False
full_reward_received = False
totalreward = 0
iters = 0
a, b, c = transform(observation)
state = np.concatenate((np.array([compute_steering_speed_gyro_abs(a)]).reshape(1,-1).flatten(), b.reshape(1,-1).flatten(), c), axis=0) # this is 3 + 7*7 size vector. all scaled in range 0..1
stacked_state = np.array([state]*self.stack_len, dtype='float32')
while not done:
argmax_qval, qval = self.sample_action(stacked_state, eps)
prev_state = stacked_state
action = self.convert_argmax_qval_to_env_action(argmax_qval)
observation, reward, done, info = self.env.step(action)
a, b, c = transform(observation)
curr_state = np.concatenate((np.array([compute_steering_speed_gyro_abs(a)]).reshape(1,-1).flatten(), b.reshape(1,-1).flatten(), c), axis=0) # this is 3 + 7*7 size vector. all scaled in range 0..1
curr_state.astype('float32')
stacked_state = np.append(stacked_state[1:], [curr_state], axis=0) # appending the lastest frame, pop the oldest
if train == True:
self.memory.append((prev_state, argmax_qval, reward, stacked_state))
if iters%250==0:
self.curr_pointer += 1
self.update_targets()
# replay batch from memory every n steps
if self.replay_freq!=0 and train==True:
if iters % self.replay_freq==0 and iters>10:
try:
self.replay(32)
except Exception as e: # will error if the memory size not enough for minibatch yet
print("error when replaying: ", e)
raise e
totalreward += reward
iters += 1
self.env.render()
if iters > 1500:
print("This episode is stuck")
break
return totalreward, iters
def train(self, retrain=False, eps_mode='dynamic'):
self.timestamp = time.strftime("%m%d_%H%M")
if retrain:
self.timestamp += "_retrain"
#create directory for this training run
dir_name = os.path.join(os.getcwd(), "{}/{}".format(self.train_dir,self.timestamp))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
totalrewards = np.empty(self.num_episodes)
for n in range(self.num_episodes):
print("training ", str(n))
if eps_mode == 'dynamic':
if not self.model_name:
eps = 1/np.sqrt(n + 100)
else: # want to use a very small eps during retraining
eps = 0.01
else:
eps = eps_mode
totalreward, iters = self.play_one(eps)
totalrewards[n] = totalreward
print("episode:", n, "iters", iters, "total reward:", totalreward, "eps:", eps, "avg reward (last 100):", totalrewards[max(0, n-100):(n+1)].mean())
if n>=0 and n%50==0 and not self.model_name:
# save model (assuming this is NOT the flask app, which WILL pass a model name)
trained_model = os.path.join(os.getcwd(),"{}/{}/avg_dqn_ep_{}.h5".format(self.train_dir,self.timestamp, str(n)))
with open(os.path.join(os.getcwd(), "{}/{}/avg_dqn_ep_{}.pkl".format(self.train_dir,self.timestamp, str(n))),'wb+') as outfile:
pkl.dump(totalrewards, outfile)
self.model.save(trained_model)
if self.model_name:
# we assume that this IS the flask app; if you are trying to retrain FROM an h5, put it in the flask_model directory for now
model_name_no_extension = os.path.basename(self.model_name)
new_model_name = os.path.join(os.getcwd(), "{}/{}/{}".format(self.train_dir,self.timestamp, model_name_no_extension))
print('saving: ', new_model_name)
self.model.save(new_model_name)
rp_name = os.path.join(os.getcwd(), "{}/{}/rewards_plot_{}.png".format(self.train_dir,self.timestamp, model_name_no_extension))
plt.plot(totalrewards, label='retraining reward')
plt.title("Rewards")
plt.savefig(rp_name)
plt.close()
rap_name = os.path.join(os.getcwd(), "{}/{}/ra_plot_{}.png".format(self.train_dir,self.timestamp, model_name_no_extension))
plot_running_avg(totalrewards, rap_name)
with open(os.path.join(os.getcwd(), "{}/{}/{}_rewards_flask.pkl".format(self.train_dir,self.timestamp, model_name_no_extension)),'wb+') as outfile:
pkl.dump(totalrewards, outfile)
with open(os.path.join(os.getcwd(), "{}/{}/{}_car_config.json".format(self.train_dir,self.timestamp, model_name_no_extension)),'w+') as outfile:
json.dump(self.carConfig, outfile)
if not self.model_name:
plt.plot(totalrewards)
# rp_name = os.path.join(os.getcwd(), "train_logs/avg_dqn_lr001_replay20_cpweights250.png")
rp_name = os.path.join(os.getcwd(), "{}/{}/rewards_plot.png".format(self.train_dir,self.timestamp))
plt.title("Rewards")
plt.savefig(rp_name)
plt.close()
rap_name = os.path.join(os.getcwd(), "{}/{}/ra_plot.png".format(self.train_dir,self.timestamp))
plot_running_avg(totalrewards, rap_name)
# with open(os.path.join(os.getcwd(), "train_logs/avg_dqn_total_rewards_final_lr001_replay20_cpweights250.pkl"),'wb+') as outfile:
with open(os.path.join(os.getcwd(), "{}/{}/total_rewards.pkl".format(self.train_dir,self.timestamp)),'wb+') as outfile:
pkl.dump(totalrewards, outfile)
with open(os.path.join(os.getcwd(), "{}/{}/car_config.json".format(self.train_dir,self.timestamp)),'w+') as outfile:
json.dump(self.carConfig, outfile)
self.model.save(os.path.join(os.getcwd(), "{}/{}.h5".format(self.train_dir,self.timestamp)))
copyfile(rap_name, "{}/reward_plot.png".format(self.train_dir))
self.env.close()
return totalrewards
if __name__ | |
"""
self.stdout.append("\r\n")
def WriteLine2(self, runspace, pipeline, value):
"""
MI: 16
SHOULD write the specified line on the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writeline
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param value: The string of characters to be written
"""
self.stdout.append(value + "\r\n")
def WriteLine3(self, runspace, pipeline, foreground_color,
background_color, value):
"""
MI: 17
SHOULD write the specified line with the specified foreground and
background color on the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writeline
This implementation just adds this result to the stdout list and
ignores the colors, create your own method implementation if you wish
to utilise this correctly
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param foreground_color: The int value of pypsrp.complex_objects.Color
of the foreground color to display the text with
:param background_color: The int value of pypsrp.complex_objects.Color
of the background color to display the text with
:param value: The string of characters to be written
"""
self.stdout.append(value + "\r\n")
def WriteErrorLine(self, runspace, pipeline, message):
"""
MI: 18
SHOULD write a line to the error display of the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writeerrorline
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param message: The message to display
"""
self.stderr.append(message + "\r\n")
def WriteDebugLine(self, runspace, pipeline, message):
"""
MI: 19
SHOULD write a line to the debug display of the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writedebugline
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param message: The message to display
"""
self.stdout.append("DEBUG: %s\r\n" % message)
def WriteProgress(self, runspace, pipeline, source_id, record):
"""
MI: 20
SHOULD display a progress record on the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writeprogress
Because of the way MS serializes the record in the method call args,
the value for record is the serialized XML string for a ProgressRecord
message. You can manually parse it like;
from pypsrp.messages import ProgressRecord
meta = ObjectMeta("Obj", object=ProgressRecord)
rec = runspace._serializer.deserialize(record, meta)
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param source_id: Unique identifier of the source of the record
:param record: A ProgressRecord serialized as XML
"""
pass
def WriteVerboseLine(self, runspace, pipeline, message):
"""
MI: 21
SHOULD write a line on the verbose display of the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writeverboseline
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param message: The verbose message to display
"""
self.stdout.append("VERBOSE: %s\r\n" % message)
def WriteWarningLine(self, runspace, pipeline, message):
"""
MI: 22
SHOULD write a line on the warning display of the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.writewarningline
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param message: The warning message to display
"""
self.stdout.append("WARNING: %s\r\n" % message)
def Prompt(self, runspace, pipeline, caption, message, descriptions):
"""
MI: 23
SHOULD prompt the user with a set of choices.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.prompt
The descriptions arg is a list of GenericComplexObjects with the
following extended attributes (correlates to FieldDescription in .NET):
attributes
defaultValue
helpMessage
isMandatory
label
name
parameterAssemblyFullName
parameterTypeFullName
parameterTypeName
For example you can access the prompt name from `Read-Host -Prompt`
with descriptions[i].extended_properties['name'].
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param caption: Caption to precede or title the prompt
:param message: A text description of the set of fields to be prompted
:param descriptions: list of serialized FieldDescriptions that contain
information about each field to be prompted for
:return: Dict with results of prompting. Key are the field names from
the FieldDescriptions, the values are objects representing the
values of the corresponding fields as collected from the user.
"""
raise NotImplementedError()
def PromptForCredential1(self, runspace, pipeline, caption, message,
user_name, target_name):
"""
MI: 24
SHOULD prompt the user for entering credentials with the specified
caption, message, user name and target name.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.promptforcredential
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param caption: Caption for the message
:param message: Text description for the credential to be prompted
:param user_name: Name of the user whose credential is to be prompted
for. If set to null or empty string, the function will prompt for
the user name first
:param target_name: Name of the target for which the credential is
being collected
:return: PSCredential object of the user input credential
"""
raise NotImplementedError()
def PromptForCredential2(self, runspace, pipeline, caption, message,
user_name, target_name, allowed_credential_types,
options):
"""
MI: 25
SHOULD prompt the user for entering credentials with the specified
caption, message, username, target name, allowed credential types and
options.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.promptforcredential
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param caption: Caption for the message
:param message: Text description for the credential to be prompted
:param user_name: Name of the user whose credential is to be prompted
for. If set to null or empty string, the function will prompt for
the user name first
:param target_name: Name of the target for which the credential is
being collected
:param allowed_credential_types: the int value for PSCredentialTypes,
types of credentials that can be supplied by the user
:param options: the int value for PSCredentialUIOptions, options that
control the credential gathering UI behavior
:return: PSCredential object of the user input credential
"""
raise NotImplementedError()
def PromptForChoice(self, runspace, pipeline, caption, message, choices,
default_choice):
"""
MI: 26
SHOULD display a list of choices to the user and MUST return the index
of the selected option.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.promptforchoice
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:param caption: The caption to precede or title the prompt
:param message: A message that describes what the choice is for
:param choices: A list of serialized (GenericComplexObject)
ChoiceDescription objects that describe each choice
:param default_choice: The index of the label in the choices collection
element to be present to the user as the default choice, -1 means
no default
:return: The index of the choices element that corresponds to the
option selected
"""
raise NotImplementedError()
class PSHostRawUserInterface(object):
def __init__(self, window_title, cursor_size, foreground_color,
background_color, cursor_position, window_position,
buffer_size, max_physical_window_size, max_window_size,
window_size):
"""
Defines the lowest-level user interface functions that an interactive
application hosting a Runspace can choose to implement if it wants
to support any cmdlet that does character-mode interaction with the
user.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostrawuserinterface
This is a basic framework implementation with the majority of the
methods not implemented or tested.
:param window_title: The titlebar text of the current view window
:param cursor_size: The size of the cursor as a percentage (0 to 100)
:param foreground_color: The pypsrp.complex_objects.Color used to
render characters on the screen buffer
:param background_color: The pypsrp.complex_objects.Color used to
render the backfround behind characters on the screen buffer
:param cursor_position: The pypsrp.complex_objects.Coordinates of the
position of the cursor in the screen buffer
:param window_position: The pypsrp.complex_objects.Coordinates of the
position of the window relative to the screen buffer, (0, 0) is the
upper left of the screen buffer
:param buffer_size: The pypsrp.complex_objects.Size of the screen
buffer
:param max_physical_window_size: The pypsrp.complex_objects.Size of the
largest windows possible for the display hardward
:param max_window_size: The pypsrp.complex_objects.Size of the window
possible for the current buffer
:param window_size: The pypsrp.complex_objects.Size of the current
window, cannot be larger than max_physical_window_size
"""
self.key_available = False
self.window_title = window_title
self.cursor_size = cursor_size
self.foreground_color = foreground_color
self.background_color = background_color
self.cursor_position = cursor_position
self.window_position = window_position
self.buffer_size = buffer_size
self.max_physical_window_size = max_physical_window_size
self.max_window_size = max_window_size
self.window_size = window_size
def GetForegroundColor(self, runspace, pipeline):
"""
MI: 27
SHOULD return the foreground color of the hosting application.
:param | |
<gh_stars>1-10
import concurrent.futures
import heisenberg.library.shooting_method_objective
import heisenberg.library.util
import heisenberg.util
import itertools
import numpy as np
import os
import sys
import traceback
import vorpy
import vorpy.pickle
import vorpy.symplectic_integration.exceptions
subprogram_description = 'Samples a specified parameter space of initial conditions, computing the corresponding integral curves, and computing and storing relevant data about the each curve in a file. This is intended to sample various functions of the initial condition space, and can be used in later processing; see the heisenberg.plot_samples subprogram.'
## TODO: Come up with less generic name.
#Sample = collections.namedtuple('Sample', ['initial', 'qp_0', 'dt', 'max_time', 'objective', 't_min', 'max_abs_H', 'max_abs_J_minus_J_0', 'flow_curve_was_salvaged'])
def make_sample_result (*, initial, qp_0, dt, max_time, objective, t_min, max_abs_H, max_abs_J_minus_J_0, flow_curve_was_salvaged, flow_curve):
return (initial, qp_0, dt, max_time, objective, t_min, max_abs_H, max_abs_J_minus_J_0, flow_curve_was_salvaged, flow_curve)
def worker (args):
assert len(args) == 6, 'passed wrong number of arguments to worker function'
dynamics_context, initial_preimage, dt, max_time, embedding_dimension, embedding_solution_sheet_index = args[0], args[1], args[2], args[3], args[4], args[5]
qp_0 = dynamics_context.embedding(N=embedding_dimension, sheet_index=embedding_solution_sheet_index)(initial_preimage)
try:
# Use disable_salvage=True to avoid clogging up the place.
smo = heisenberg.library.shooting_method_objective.ShootingMethodObjective(dynamics_context=dynamics_context, preimage_qp_0=initial_preimage, qp_0=qp_0, t_max=max_time, t_delta=dt, disable_salvage=True)
flow_curve = smo.flow_curve()
objective = smo.objective()
t_min = smo.t_min()
abs_H_v = np.abs(vorpy.apply_along_axes(dynamics_context.H, (-2,-1), (flow_curve,)))
J_v = vorpy.apply_along_axes(dynamics_context.J, (-2,-1), (flow_curve,))
J_0 = J_v[0]
J_v -= J_0
abs_J_minus_J_0 = np.abs(J_v)
sample_result = make_sample_result(
initial=initial_preimage,
qp_0=qp_0,
dt=dt,
max_time=max_time,
objective=objective,
t_min=t_min,
max_abs_H=np.max(abs_H_v),
max_abs_J_minus_J_0=np.max(abs_J_minus_J_0),
flow_curve_was_salvaged=smo.flow_curve_was_salvaged,
flow_curve=flow_curve
)
#print('recording sample {0}'.format(sample_result))
except Exception as e:
print('caught exception "{0}" -- storing and continuing'.format(e))
print('stack:')
ex_type,ex,tb = sys.exc_info()
traceback.print_tb(tb)
sample_result = make_sample_result(
initial=initial,
qp_0=qp_0,
dt=dt,
max_time=max_time,
objective=np.nan,
t_min=np.nan,
max_abs_H=np.nan,
max_abs_J_minus_J_0=np.nan,
flow_curve_was_salvaged=True, # Change this to "exception occurred" and store info about exception
flow_curve=flow_curve
)
return sample_result
def sample (dynamics_context, options, *, rng):
"""
Program to search for orbits in the 2D embedding space:
- Generate random points in the domain
-sqrt(1/(4*pi)) <= p_x <= sqrt(1/(4*pi))
-C <= p_y <= C
for some arbitrary positive constant C, say 2. Due to a discrete symmetry in the system
(reflection), p_y can be taken to be nonnegative. Thus the domain can be
-sqrt(1/(4*pi)) <= p_x <= sqrt(1/(4*pi))
0 <= p_y <= C
- For each of these, compute the embedding qp_0 into phase space and use that as the initial
condition for the flow curve. Use some fixed dt and max_time.
- For each flow curve, compute the following values:
- The objective function value (which could be NaN if the curve didn't go back toward itself)
- The t_min value (which for a closed curve would be its period)
- The upper bound on abs(H), or more detailed stats (mean and variance, or a histogram)
- The upper bound on abs(J - J_0), or more detailed stats (mean and variance, or a histogram)
- If it is [close to being] closed, then the order of its radial symmetry
- The deviation of its z(t) function from a sine wave (for closed, this sometimes but not
always appears to be a sine wave, but this hasn't been checked rigorously).
- Visualize these two functions to determine if they are continuous and/or have other structure
to them. Perhaps there are regions which are continuous surrounding zeros the objective function.
"""
if options.sampling_type == 'random':
if options.seed is None:
print('If --sampling-type=random, then --seed must be specified.')
sys.exit(-1)
if options.sample_count <= 0:
print('--sample-count option, if present, must specify a positive integer.')
sys.exit(-1)
if options.worker_chunksize <= 0:
print('--worker-chunksize option, if present, must specify a positive integer.')
sys.exit(-1)
if options.max_workers is not None and options.max_workers <= 0:
print('--max-workers option, if present, must specify a positive integer.')
sys.exit(-1)
heisenberg.util.ensure_dir_exists(options.samples_dir)
# Ensure that the requested embedding is already vorpy.symbolic.cache_lambdified, because otherwise
# the worker processes somehow crash, not being able to generate it themselves.
dynamics_context.embedding(N=options.embedding_dimension, sheet_index=options.embedding_solution_sheet_index)
sample_result_v = []
# Define sample_generator based on the sampling type.
if options.sampling_type == 'random':
def random_sample (rng):
return np.array([rng.uniform(low=options.sampling_domain_bound_v[axis,0], high=options.sampling_domain_bound_v[axis,1]) for axis in range(options.embedding_dimension)])
sample_generator = (random_sample(rng) for _ in range(options.sample_count))
elif options.sampling_type == 'ordered':
# Define uniform samplings of each axis in the sampling domain.
sample_vv = [np.linspace(options.sampling_domain_bound_v[axis,0], options.sampling_domain_bound_v[axis,1], options.sample_count_v[axis]) for axis in range(options.embedding_dimension)]
sample_generator = (np.array(sample) for sample in itertools.product(*sample_vv))
else:
assert False, 'this should never happen'
if options.max_workers is None or options.max_workers > 1:
# Map the worker function over multiple processes.
with concurrent.futures.ProcessPoolExecutor(max_workers=options.max_workers) as executor:
try:
#sample_counter = range(options.sample_count)
sample_index = 1
print('options:', options)
for sample_result in executor.map(worker, ((dynamics_context, sample, options.dt, options.max_time, options.embedding_dimension, options.embedding_solution_sheet_index) for sample in sample_generator), chunksize=options.worker_chunksize):
sample_result_v.append(sample_result)
print('**************** saving sample {0} (out of {1}): {2}'.format(sample_index, options.sample_count, sample_result))
sample_index += 1
except (Exception,KeyboardInterrupt) as e:
print('encountered exception of type {0} during sample; calling executor.shutdown(wait=True), saving results, and exiting. exception was: {1}'.format(type(e), e))
print('stack:')
ex_type,ex,tb = sys.exc_info()
traceback.print_tb(tb)
executor.shutdown(wait=True)
else:
# Run the worker function in this single process.
try:
for sample in sample_generator:
sample_result = worker((dynamics_context, sample, options.dt, options.max_time, options.embedding_dimension, options.embedding_solution_sheet_index))
sample_result_v.append(sample_result)
except (Exception,KeyboardInterrupt) as e:
print('encountered exception of type {0} during sample; saving results and exiting. exception was: {1}'.format(type(e), e))
print('stack:')
ex_type,ex,tb = sys.exc_info()
traceback.print_tb(tb)
# Create the data structure that will be pickled.
data = {
'full_commandline': heisenberg.util.reconstruct_full_commandline(executable=sys.executable, argv=sys.argv),
'options': vars(options), # vars ensures it's a dict, and not a stupid optparse.Values object.
'sample_v': sample_result_v,
}
print('saving results...')
maybe_seed_string = 'seed:{0}.'.format(options.seed) if options.sampling_type == 'random' else ''
base_filename = os.path.join(options.samples_dir, 'sample_v.{0}count:{1}'.format(maybe_seed_string, len(sample_result_v)))
vorpy.pickle.try_to_pickle(data=data, pickle_filename=base_filename+'.pickle', log_out=sys.stdout)
# Also create a human-readable summary of the pickle data.
heisenberg.util.write_human_readable_summary(data=data, filename=base_filename+'.summary')
if options.embedding_dimension == 1 and options.sampling_type == 'ordered':
print('finding minima of the objective function and classifying the curves.')
p_y_v = []
objective_v = []
t_min_v = []
# Create lists of the relevant sample_result values.
for sample_result in sample_result_v:
# See make_sample_result for which element is which.
# sample_result[0] is initial preimage, which in the case of --embedding-dimension=1, is the initial p_y (aka p_theta) value.
assert np.shape(sample_result[0]) == (1,) # Should be a 1-vector.
p_y_v.append(sample_result[0][0])
# sample_result[4] is the objective function value for that initial condition.
assert np.shape(sample_result[4]) == tuple() # Should be a scalar.
objective_v.append(sample_result[4])
# sample_result[5] is t_min, which is the time at which the curve most nearly closed up on itself.
assert np.shape(sample_result[5]) == tuple() # Should be a scalar.
t_min_v.append(sample_result[5])
# Turn those lists into np.array objects.
p_y_v = np.array(p_y_v)
objective_v = np.array(objective_v)
t_min_v = np.array(t_min_v)
# Compute all local minima of the objective function
local_min_index_v = [i for i in range(1,len(objective_v)-1) if objective_v[i-1] > objective_v[i] and objective_v[i] < objective_v[i+1]]
# Use exp quadratic fit to compute time of local mins at sub-sample accuracy -- use
# exp_quadratic_min_time_parameterized so that the computed min is nonnegative.
local_min_v = []
for local_min_index in local_min_index_v:
# For each local min, we only care about its discrete "neighborhood".
s = slice(local_min_index-1, local_min_index+2)
# Just take the "local" slice of p_y_v and objective_v
p_y_local_v = p_y_v[s]
objective_local_v = objective_v[s]
p_y_min,objective = heisenberg.library.util.exp_quadratic_min_time_parameterized(p_y_local_v, objective_local_v)
assert p_y_local_v[0] < p_y_min < p_y_local_v[-1], 'p_y_min is outside the neighborhood of the local min -- this should be impossible'
t_min_local_v = t_min_v[s]
#print('p_y_local_v = {0}, t_min_local_v = {1}, p_y_min = {2}'.format(p_y_local_v, t_min_local_v, p_y_min))
period = np.interp(p_y_min, p_y_local_v, t_min_local_v)
local_min_v.append((p_y_min, objective, period))
# Go through each local min, compute the curve, classify it, and plot it if indicated by the --for-each-1d-minimum=classify-and-plot option.
print('Curve classifications (symmetry class and order values are estimates):')
print('Format is "class:order <=> { initial_p_y=<value>, objective=<value>, period=<value>, dt=<value> }')
try:
plot_commands_filename = base_filename+'.plot_commands'
plot_commands_file = open(plot_commands_filename, 'w')
except IOError as e:
print('was not able to open file "{0}" for writing; not writing plot commands.'.format(plot_commands_filename))
plot_commands_file = None
for local_min in local_min_v:
# TODO: Make this parallelized.
initial_p_y = np.array([local_min[0]])
qp_0 = dynamics_context.embedding(N=options.embedding_dimension, sheet_index=options.embedding_solution_sheet_index)(initial_p_y)
objective = local_min[1]
period = local_min[2]
# Go a little bit further than the period so there's at least some overlap to work with.
max_time = 1.1*period
# Create the object that will actually compute everything.
smo = heisenberg.library.shooting_method_objective.ShootingMethodObjective(dynamics_context=dynamics_context, preimage_qp_0=initial_p_y, qp_0=qp_0, t_max=max_time, t_delta=options.dt, disable_salvage=True)
# Print the classification along with enough info to reconstruct the curve fully.
classification_string = 'order: {0}, class: {1}, symmetry type: {1}/{0} <=> {{ initial_p_y={2}, objective={3}, period={4}, dt={5} }}'.format(
smo.symmetry_order_estimate(),
smo.symmetry_class_estimate(),
| |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
from xml.etree import ElementTree
from glob import glob
from collections import OrderedDict
import re
import argparse
validName = re.compile('^[a-zA-Z0-9_]+$')
class Device:
# dummy
pass
def getText(element):
if element is None:
return "None"
return ''.join(element.itertext())
def formatText(text):
text = re.sub('[ \t\n]+', ' ', text) # Collapse whitespace (like in HTML)
text = text.replace('\\n ', '\n')
text = text.strip()
return text
# Replace characters that are not allowed in a symbol name with a '_'. This is
# useful to be able to process SVD files with errors.
def cleanName(text):
if not validName.match(text):
return ''.join(list(map(lambda c: c if validName.match(c) else '_', text)))
return text
def readSVD(path, sourceURL):
# Read ARM SVD files.
device = Device()
xml = ElementTree.parse(path)
root = xml.getroot()
deviceName = getText(root.find('name'))
deviceDescription = getText(root.find('description')).strip()
licenseTexts = root.findall('licenseText')
if len(licenseTexts) == 0:
licenseText = None
elif len(licenseTexts) == 1:
licenseText = formatText(getText(licenseTexts[0]))
else:
raise ValueError('multiple <licenseText> elements')
device.peripherals = []
peripheralDict = {}
groups = {}
interrupts = OrderedDict()
for periphEl in root.findall('./peripherals/peripheral'):
name = getText(periphEl.find('name'))
descriptionTags = periphEl.findall('description')
description = ''
if descriptionTags:
description = formatText(getText(descriptionTags[0]))
baseAddress = int(getText(periphEl.find('baseAddress')), 0)
groupNameTags = periphEl.findall('groupName')
groupName = None
if groupNameTags:
# Some group names (for example the STM32H7A3x) have an invalid
# group name. Replace invalid characters with '_'.
groupName = cleanName(getText(groupNameTags[0]))
interruptEls = periphEl.findall('interrupt')
for interrupt in interruptEls:
intrName = getText(interrupt.find('name'))
intrIndex = int(getText(interrupt.find('value')))
addInterrupt(interrupts, intrName, intrIndex, description)
# As a convenience, also use the peripheral name as the interrupt
# name. Only do that for the nrf for now, as the stm32 .svd files
# don't always put interrupts in the correct peripheral...
if len(interruptEls) == 1 and deviceName.startswith('nrf'):
addInterrupt(interrupts, name, intrIndex, description)
if periphEl.get('derivedFrom') or groupName in groups:
if periphEl.get('derivedFrom'):
derivedFromName = periphEl.get('derivedFrom')
derivedFrom = peripheralDict[derivedFromName]
else:
derivedFrom = groups[groupName]
peripheral = {
'name': name,
'groupName': derivedFrom['groupName'],
'description': description or derivedFrom['description'],
'baseAddress': baseAddress,
}
device.peripherals.append(peripheral)
peripheralDict[name] = peripheral
if 'subtypes' in derivedFrom:
for subtype in derivedFrom['subtypes']:
subp = {
'name': name + "_"+subtype['clusterName'],
'groupName': subtype['groupName'],
'description': subtype['description'],
'baseAddress': baseAddress,
}
device.peripherals.append(subp)
continue
peripheral = {
'name': name,
'groupName': groupName or name,
'description': description,
'baseAddress': baseAddress,
'registers': [],
'subtypes': [],
}
device.peripherals.append(peripheral)
peripheralDict[name] = peripheral
if groupName and groupName not in groups:
groups[groupName] = peripheral
regsEls = periphEl.findall('registers')
if regsEls:
if len(regsEls) != 1:
raise ValueError('expected just one <registers> in a <peripheral>')
for register in regsEls[0].findall('register'):
peripheral['registers'].extend(parseRegister(groupName or name, register, baseAddress))
for cluster in regsEls[0].findall('cluster'):
clusterName = getText(cluster.find('name')).replace('[%s]', '')
clusterDescription = getText(cluster.find('description'))
clusterPrefix = clusterName + '_'
clusterOffset = int(getText(cluster.find('addressOffset')), 0)
if cluster.find('dim') is None:
if clusterOffset == 0:
# make this a separate peripheral
cpRegisters = []
for regEl in cluster.findall('register'):
cpRegisters.extend(parseRegister(groupName, regEl, baseAddress, clusterName+"_"))
cpRegisters.sort(key=lambda r: r['address'])
clusterPeripheral = {
'name': name+ "_" +clusterName,
'groupName': groupName+ "_" +clusterName,
'description': description+ " - " +clusterName,
'clusterName': clusterName,
'baseAddress': baseAddress,
'registers': cpRegisters,
}
device.peripherals.append(clusterPeripheral)
peripheral['subtypes'].append(clusterPeripheral)
continue
dim = None
dimIncrement = None
else:
dim = int(getText(cluster.find('dim')))
if dim == 1:
dimIncrement = None
else:
dimIncrement = int(getText(cluster.find('dimIncrement')), 0)
clusterRegisters = []
for regEl in cluster.findall('register'):
clusterRegisters.extend(parseRegister(groupName or name, regEl, baseAddress + clusterOffset, clusterPrefix))
clusterRegisters.sort(key=lambda r: r['address'])
if dimIncrement is None:
lastReg = clusterRegisters[-1]
lastAddress = lastReg['address']
if lastReg['array'] is not None:
lastAddress = lastReg['address'] + lastReg['array'] * lastReg['elementsize']
firstAddress = clusterRegisters[0]['address']
dimIncrement = lastAddress - firstAddress
peripheral['registers'].append({
'name': clusterName,
'address': baseAddress + clusterOffset,
'description': clusterDescription,
'registers': clusterRegisters,
'array': dim,
'elementsize': dimIncrement,
})
peripheral['registers'].sort(key=lambda r: r['address'])
device.interrupts = sorted(interrupts.values(), key=lambda v: v['index'])
licenseBlock = ''
if licenseText is not None:
licenseBlock = '// ' + licenseText.replace('\n', '\n// ')
licenseBlock = '\n'.join(map(str.rstrip, licenseBlock.split('\n'))) # strip trailing whitespace
device.metadata = {
'file': os.path.basename(path),
'descriptorSource': sourceURL,
'name': deviceName,
'nameLower': deviceName.lower(),
'description': deviceDescription,
'licenseBlock': licenseBlock,
}
return device
def addInterrupt(interrupts, intrName, intrIndex, description):
if intrName in interrupts:
if interrupts[intrName]['index'] != intrIndex:
# Note: some SVD files like the one for STM32H7x7 contain mistakes.
# Instead of throwing an error, simply log it.
print ('interrupt with the same name has different indexes: %s (%d vs %d)'
% (intrName, interrupts[intrName]['index'], intrIndex))
if description not in interrupts[intrName]['description'].split(' // '):
interrupts[intrName]['description'] += ' // ' + description
else:
interrupts[intrName] = {
'name': intrName,
'index': intrIndex,
'description': description,
}
def parseBitfields(groupName, regName, fieldsEls, bitfieldPrefix=''):
fields = []
if fieldsEls:
for fieldEl in fieldsEls[0].findall('field'):
# Some bitfields (like the STM32H7x7) contain invalid bitfield
# names like 'CNT[31]'. Replace invalid characters with '_' when
# needed.
fieldName = cleanName(getText(fieldEl.find('name')))
lsbTags = fieldEl.findall('lsb')
if len(lsbTags) == 1:
lsb = int(getText(lsbTags[0]))
else:
lsb = int(getText(fieldEl.find('bitOffset')))
msbTags = fieldEl.findall('msb')
if len(msbTags) == 1:
msb = int(getText(msbTags[0]))
else:
msb = int(getText(fieldEl.find('bitWidth'))) + lsb - 1
fields.append({
'name': '{}_{}{}_{}_Pos'.format(groupName, bitfieldPrefix, regName, fieldName),
'description': 'Position of %s field.' % fieldName,
'value': lsb,
})
fields.append({
'name': '{}_{}{}_{}_Msk'.format(groupName, bitfieldPrefix, regName, fieldName),
'description': 'Bit mask of %s field.' % fieldName,
'value': (0xffffffff >> (31 - (msb - lsb))) << lsb,
})
if lsb == msb: # single bit
fields.append({
'name': '{}_{}{}_{}'.format(groupName, bitfieldPrefix, regName, fieldName),
'description': 'Bit %s.' % fieldName,
'value': 1 << lsb,
})
for enumEl in fieldEl.findall('enumeratedValues/enumeratedValue'):
enumName = getText(enumEl.find('name'))
enumDescription = getText(enumEl.find('description')).replace('\n', ' ')
enumValue = int(getText(enumEl.find('value')), 0)
fields.append({
'name': '{}_{}{}_{}_{}'.format(groupName, bitfieldPrefix, regName, fieldName, enumName),
'description': enumDescription,
'value': enumValue,
})
return fields
class Register:
def __init__(self, element, baseAddress):
self.element = element
self.baseAddress = baseAddress
def name(self):
return getText(self.element.find('name')).replace('[%s]', '')
def description(self):
return getText(self.element.find('description')).replace('\n', ' ')
def address(self):
offsetEls = self.element.findall('offset')
if not offsetEls:
offsetEls = self.element.findall('addressOffset')
return self.baseAddress + int(getText(offsetEls[0]), 0)
def dim(self):
dimEls = self.element.findall('dim')
if len(dimEls) == 0:
return None
elif len(dimEls) == 1:
return int(getText(dimEls[0]), 0)
else:
raise ValueError('expected at most one <dim> element in %s register' % self.name())
def size(self):
size = 4
elSizes = self.element.findall('size')
if elSizes:
size = int(getText(elSizes[0]), 0) // 8
return size
def parseRegister(groupName, regEl, baseAddress, bitfieldPrefix=''):
reg = Register(regEl, baseAddress)
fieldsEls = regEl.findall('fields')
if reg.dim() is not None:
dimIncrement = int(getText(regEl.find('dimIncrement')), 0)
if "%s" in reg.name():
# a "spaced array" of registers, special processing required
# we need to generate a separate register for each "element"
results = []
for i in range(reg.dim()):
regAddress = reg.address() + (i * dimIncrement)
results.append({
'name': reg.name().replace('%s', str(i)),
'address': regAddress,
'description': reg.description(),
'bitfields': [],
'array': None,
'elementsize': reg.size(),
})
# set first result bitfield
shortName = reg.name().replace('_%s', '').replace('%s', '')
results[0]['bitfields'] = parseBitfields(groupName, shortName, fieldsEls, bitfieldPrefix)
return results
return [{
'name': reg.name(),
'address': reg.address(),
'description': reg.description(),
'bitfields': parseBitfields(groupName, reg.name(), fieldsEls, bitfieldPrefix),
'array': reg.dim(),
'elementsize': reg.size(),
}]
def writeGo(outdir, device):
# The Go module for this device.
out = open(outdir + '/' + device.metadata['nameLower'] + '.go', 'w')
pkgName = os.path.basename(outdir.rstrip('/'))
out.write('''\
// Automatically generated file. DO NOT EDIT.
// Generated by gen-device-svd.py from {file}, see {descriptorSource}
// +build {pkgName},{nameLower}
// {description}
//
{licenseBlock}
package {pkgName}
import (
"runtime/volatile"
"unsafe"
)
// Some information about this device.
const (
DEVICE = "{name}"
)
'''.format(pkgName=pkgName, **device.metadata))
out.write('\n// Interrupt numbers\nconst (\n')
for intr in device.interrupts:
out.write('\tIRQ_{name} = {index} // {description}\n'.format(**intr))
intrMax = max(map(lambda intr: intr['index'], device.interrupts))
out.write('\tIRQ_max = {} // Highest interrupt number on this device.\n'.format(intrMax))
out.write(')\n')
# Define actual peripheral pointers.
out.write('\n// Peripherals.\nvar (\n')
for peripheral in device.peripherals:
out.write('\t{name} = (*{groupName}_Type)(unsafe.Pointer(uintptr(0x{baseAddress:x}))) // {description}\n'.format(**peripheral))
out.write(')\n')
# Define peripheral struct types.
for peripheral in device.peripherals:
if 'registers' not in peripheral:
# This peripheral was derived from another peripheral. No new type
# needs to be defined for it.
continue
out.write('\n// {description}\ntype {groupName}_Type struct {{\n'.format(**peripheral))
address = peripheral['baseAddress']
padNumber = 0
for register in peripheral['registers']:
if address > register['address'] and 'registers' not in register :
# In Nordic SVD files, these registers are deprecated or
# duplicates, so can be ignored.
#print('skip: %s.%s %s - %s %s' % (peripheral['name'], register['name'], address, register['address'], register['elementsize']))
continue
eSize = register['elementsize']
if eSize == 4:
regType = 'volatile.Register32'
elif eSize == 2:
regType = 'volatile.Register16'
elif eSize == 1:
regType = 'volatile.Register8'
else:
eSize = 4
regType = 'volatile.Register32'
# insert padding, if needed
if address < register['address']:
bytesNeeded = register['address'] - address
if bytesNeeded == 1:
out.write('\t_padding{padNumber} {regType}\n'.format(padNumber=padNumber, regType='volatile.Register8'))
elif bytesNeeded == 2:
out.write('\t_padding{padNumber} {regType}\n'.format(padNumber=padNumber, regType='volatile.Register16'))
elif bytesNeeded == 3:
| |
<reponame>calvofl0/rhd_dq
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This nMBP module locates non-magnetic bright points using an indicator based
on three parameters: temperature, vorticity and depth at isosurface tau=1.
This indicator is a growing function of its parameters. Local maxima above
some threshold of this indicator are considered to be nMBPs. The indicator
has been experimentally built, and hasn't any theoretical justification.
When nMBPs are too close, only the brightest one (in the intensity map) is
retained, considering that the underlying structure is that of one single
nMBP providing two close local maxima in the indicator.
Also if the position of the hypothetical nMBP in the intensity map is too
far away from the underlying structure, the nMBP is eliminated.
Via the functions export_nMBPs, import_nMBPs, importNext, report and
setActive the nMBPs can be studies. The typical strategy is:
1. export_nMBPs(fullfile, parfile, meanfile, height)
-> This will create uio files with cuts centred on each nMBP and
at height 'height'. It also creates an index file '.nmbps'
This step does not requires matplotlib
2. import_nMBPs(indexfile, parfile)
-> This loads the header of the index file, and these next steps
should be done in a computer where matplotlib is installed
3. importNext()
-> This should be called as many times as there are nMBPs. At each
call a new nMBP is loaded. It returns a list with:
* The coordinates (a tuple)
* Contrast (with respect to local neighbourhood)
* Contrast (with respect to global average)
* Diameter of the nMBP
* A flag specifying wheter or not the nMBP is set active
(this flag is switched off for non-valid nMBPs after
visual examination)
4. report()
-> Prints a report of the physical properties of the current nMBP
together with the corresponding plots
5. setActive(active_flag)
-> Set the active_flag of the current nMBP (this modifies the index)
6. close()
-> Closes the index
'''
import numpy as np
import pybold
import snake
import xdrlib
from slicingTools import vorticity
from snake import find_min, select_disk, d2
from analyze2d import getGranules, circleFootprint
from analyze3d import wilson_depression, contrast
from pybold import uio_struct, varAtLevel
try:
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.colors import colorConverter
import matplotlib as mpl
import matplotlib.pyplot as plt
from analyze3d import plotv_slice
except ImportError: print('Warning: matplotlib is missing.')
if not '_model' in globals(): _model = uio_struct()
if not '_modelfile' in globals(): _modelfile = None
if not '_parfile' in globals(): _parfile = None
if not '_meanfile' in globals(): _meanfile = None
if not '_indexfile' in globals(): _indexfile = None
if not '_index' in globals(): _index = None
if not '_tau1' in globals(): _tau1 = None
if not '_vtau1' in globals(): _vtau1 = None
if not '_T' in globals(): _T = None
if not '_allrad' in globals(): _allrad = None
if not '_rad' in globals(): _rad = None
if not '_xdr' in globals(): _xdr = None
if not '_Nx' in globals(): _Nx = 0
if not '_Ny' in globals(): _Ny = 0
if not '_Npts' in globals(): _Npts = 0
if not '_pt' in globals(): _pt = 0
if not '_parameters' in globals(): _parameters = None
if not '_pos' in globals(): _pos = 0
def load_uio(modelfile, parfile=None, meanfile=None):
'''
Loads an uio file.
'''
global _model, _modelfile, _parfile, _meanfile, _allrad, _rad
#_model = uio_struct()
_modelfile = modelfile
_parfile = None
if meanfile != None:
_meanmodel = uio_struct()
_meanmodel.open(meanfile)
_meanfile = meanfile
_meanmodel.header
_allrad = dict()
while _meanmodel.next >= 0:
_allrad[_meanmodel.modelitime] = np.copy(_meanmodel.rad.intb3_r[:,:,0])
_meanmodel.close
if parfile:
_model.open(modelfile, parfile)
_parfile = parfile
else: _model.open(modelfile)
_model.header
return next()
def next():
'''
Loads next snapshot
'''
global _model, _modelfile, _parfile, _meanfile, _allrad, _rad
if _modelfile is None: return -1
print('Get next snapshot')
if _model.next < 0: return -1
print('Got next snapshot')
if _meanfile != None:
itime = _model.modelitime
if _allrad.has_key(itime):
_rad = _allrad[itime]
else: print('Warning: snapshot not found in MEAN file.')
return _model.modelitime
def close():
'''
Closes model or index file depending on the context
'''
global _model, _index
if _index != None:
_index.close()
_index = None
else:
_model.close
def get_tau1vars(model=_model):
'''
Compute physical quantities that will be used as indicators
'''
global _tau1, _vtau1, _T
# tau1
NX, NY, NZ = np.size(model.z.xc1), np.size(model.z.xc2), np.size(model.z.xc3)
Z = np.repeat(np.array([np.repeat([model.z.xc3[0,0,:]],NY,axis=0)]),NX,axis=0)
_tau1 = varAtLevel(Z,model.dq.tau,1.)
# vtau1
v1, v2 = model.z.v1, model.z.v2
#dxb1 = model.z.xb1[1:,:,:] - model.z.xb1[:-1,:,:]
#dxb2 = model.z.xb2[:,1:,:] - model.z.xb2[:,:-1,:]
#dxb1 = np.repeat(dxb1, NY, 1)
#dxb1 = np.repeat(dxb1, NZ, 2)
#dxb2 = np.repeat(dxb2, NX, 0)
#dxb2 = np.repeat(dxb2, NZ, 2)
#dv1d2 = (np.roll(v1, -1, 1) - v1) / dxb2
#dv2d1 = (np.roll(v2, -1, 0) - v2) / dxb1
#_vtau1 = varAtLevel(dv1d2-dv2d1,model.dq.tau,1.)
v1 = varAtLevel(v1, model.dq.tau, 1.)
v2 = varAtLevel(v2, model.dq.tau, 1.)
_vtau1 = vorticity(v1, v2)
# T
_T = varAtLevel(model.dq.T,model.dq.tau,1.)
#import pickle
#with open('rad1145.pickle') as f:
# rad=pickle.load(f)
#with open('tau1145.pickle') as f:
# tau1=pickle.load(f)
#with open('snap1145.pickle') as f:
# v1,v2,v3,rho=pickle.load(f)
# v=vorticity(v1,v2)
#with open('vorticity1145.pickle') as f:
# vtau1=pickle.load(f)
#with open('T1145.pickle') as f:
# T=pickle.load(f)
normalize = lambda data: (data-np.min(data))/(np.max(data)-np.min(data))
def computeIndicator(T=None, tau1=None, vorticity=None):
'''
This functions computes the indicator used to select nMBPs
It is the core of the detection algorithm
'''
if T is None: T=_T
if tau1 is None: tau1=_tau1
if vorticity is None: vorticity=_vtau1
return np.sqrt(normalize(T)**2*normalize(-tau1)**2*normalize(np.abs(vorticity)**2))
def nearestMin(data, p, max_dist=20):
'''
Returns the nearest minimum to p together to a flag checking whether
or not it is not further away than max_dist
'''
mins = find_min(data)
dist = []
intensity = []
for m in mins:
dist.append(d2(p,m))
intensity.append(data[int(m[0]),int(m[1])])
sortTable = np.argsort(np.array(intensity))
intensity = np.array(intensity)[sortTable]
mins = np.array(mins)[sortTable]
dist = np.array(dist)[sortTable]
for m,d in zip(mins,dist):
if d <= max_dist**2: return (int(m[0]), int(m[1])), 0
# print('Warning: nearest min is further than max_dist.')
m = mins[np.argmin(dist)]
return (int(m[0]), int(m[1])), 1
def circleFootprint(N):
'''
Creates a circular "footprint" (or stencil) of diameter N
'''
fp = np.zeros((N,N), dtype=bool)
r = (N-1.)/2.
for i in range(N):
for j in range(N):
if (i-r)**2+(j-r)**2 <= r**2: fp[i,j] = True
return fp
def getNMBPs(indicator, intensity=None, granules=None, l=50, footprint=None):
'''
Gets all nMBPs using the given indicator. If an intensity map is not
provided, temperature at isosurface tau=1. is taken in place. If
granules were already computed, they can be provided here to avoid
a new computations. If footprint is not provided a circular footprint
(or stencil) of diameter l is used.
'''
global _model, _T
if intensity is None: intensity = _T
if granules is None and _model is None: granules = getGranules(intensity, shrink=0.)
if granules is None and _model != None:
v3 = varAtLevel(_model.z.v3, _model.dq.tau, 1.)
granules = v3>0.
if footprint is None: fp = circleFootprint(l)
elif type(footprint) == int: fp = circleFootprint(footprint)
else: fp = footprint
p = find_min(-indicator)
p = [(int(p0[0]), int(p0[1])) for p0 in p]
p = [p0 for p0 in p if indicator[p0]>.2]
zones = []
toRemove = set()
#minimas = []
nmbps = []
for p00,p01 in p:
nx, ny = np.shape(indicator)
mgrid=np.meshgrid(np.arange(p00-l,p00+l+1)%nx,np.arange(p01-l,p01+l+1)%ny)
mgrid=(mgrid[0].T,mgrid[1].T)
q,err = nearestMin(-intensity[mgrid],(l+1,l+1))
if err != 0:
print('Warning: nearest nMBP in intensity map to point ('+str(p00)+', '+str(p01)+') is further than max_dist.')
s,d,b = select_disk(-intensity[mgrid],q)
zones.append(zip((s[0]+p00-l)%nx,(s[1]+p01-l)%ny))
nmbps.append(((q[0]+p00-l)%nx,(q[1]+p01-l)%ny))
for i in range(len(p)):
if p[i] not in zones[i]:
toRemove.add(i)
continue
for j in range(len(p)):
if j>=i: break
s = set.intersection(set(zones[i]), set(zones[j]))
if len(s) == 0: continue
if len(zones[j])>len(zones[i]): toRemove.add(i)
else: toRemove.add(j)
if len(toRemove)>0:
toRemove = np.sort(np.array(list(toRemove)))-np.arange(len(toRemove))
for i in toRemove:
p.pop(i)
zones.pop(i)
nmbps.pop(i)
background = []
contrast_local = []
contrast_global = []
diametre = []
int_global = np.mean(intensity)
for i in range(len(nmbps)):
xshift = int(nmbps[i][0]-(np.size(fp, axis=0)-1)/2.)
yshift = int(nmbps[i][1]-(np.size(fp, axis=1)-1)/2.)
NX, NY = np.shape(intensity)
n = np.count_nonzero(fp)
fp_mask = np.array(np.where(fp))+np.repeat([[xshift],[yshift]], n, axis=1)
fp_mask = (np.mod(fp_mask[0], NX), np.mod(fp_mask[1], NY))
nmbp_mask = zip(*zones[i])
mask = zip(*set.difference(set(zip(*fp_mask)), set(zip(*nmbp_mask))))
dnh = intensity[mask]*(1-granules[mask]) # Dark neighbourhood
background.append(np.sum(dnh)/np.count_nonzero(dnh))
contrast_local.append(np.mean(intensity[zip(*zones[i])]) / background[i])
contrast_global.append(np.mean(intensity[zip(*zones[i])]) / int_global)
diametre.append(2.*np.sqrt(len(zones[i])/np.pi))
return zip(p, np.array(contrast_local)-1., np.array(contrast_global)-1., diametre)
def export_nMBPs(modelfile, parfile, meanfile, height, box=(100,100,100)):
'''
Export all nMBPs to smaller boxes of size 'box' centred at the nMBPs
position and height 'height' and saves the boxes to uio files.
An index file is further written, including intensity maps.
'''
global _model, _modelfile, _parfile, _meanfile, _allrad, _rad
itime = load_uio(modelfile, parfile, meanfile)
parts = modelfile.split('.')
l = max(0, len(parts)-1)
filename = ''.join(parts[:l])
xdr = xdrlib.Packer()
xdr.pack_string('nmbps_index')
Nx = _model.z.dimension[1][0]-_model.z.dimension[0][0]+1
Ny = _model.z.dimension[1][1]-_model.z.dimension[0][1]+1
xdr.pack_int(Nx)
xdr.pack_int(Ny)
while itime >= 0:
xdr.pack_bool(True)
xdr.pack_array(_rad.flatten(), xdr.pack_float)
get_tau1vars()
indicator = computeIndicator()
nmbps = getNMBPs(indicator, intensity=_rad)
xdr.pack_int(len(nmbps))
for pt in nmbps:
xdr.pack_int(_model.modelitime)
pX = pt[0][0]
pY = pt[0][1]
xdr.pack_int(pt[0][0])
xdr.pack_int(pt[0][1])
xdr.pack_float(pt[1])
xdr.pack_float(pt[2])
xdr.pack_float(pt[3])
xdr.pack_bool(True)
# Save uio file here!
_model.export(filename+'_'+str(_model.modelitime)+'_'+str(pX)+'_'+str(pY)+'.uio', centre=(pX, pY, height), box=box)
itime = next()
xdr.pack_bool(False)
with open(filename+'.nmbps', 'wb') as f:
f.write(xdr.get_buffer())
def show_nMBPs(indexfile):
'''
Show all available nMBPs in indexfile
'''
with open(indexfile, 'rb') as f:
xdr = xdrlib.Unpacker(f.read())
if xdr.unpack_string() != 'nmbps_index':
print('Error: unknown file.')
return
Nx = xdr.unpack_int()
Ny = xdr.unpack_int()
pt = 0
Npts = 0
while xdr.unpack_bool():
rad = np.array(xdr.unpack_array(xdr.unpack_float)).reshape((Nx, Ny))
Npts = xdr.unpack_int()
pt = 0
pX = []
pY = []
circs = []
while pt < Npts:
pt += 1
modelitime = xdr.unpack_int()
pX = xdr.unpack_int()
pY = xdr.unpack_int()
contrast_local = xdr.unpack_float()
contrast_global = xdr.unpack_float()
diametre = xdr.unpack_float()
active_flag = xdr.unpack_bool()
if active_flag:
circs += [plt.Circle((pX,pY),50,color='r',fill=False)]
fig = plt.figure()
plt.imshow(rad.T,origin='bottom',cmap=plt.cm.gray)
for c in circs:
fig.gca().add_artist(c)
def import_nMBPs(indexfile, parfile):
'''
Loads nMBPs that where written by the corresponding exporting
function. Actually this only reads the header of the index file.
'''
global _model, _modelfile, _parfile, _indexfile, _xdr, _Nx, _Ny, _Npts, _pt
_parfile = parfile
_indexfile = indexfile.strip('.nmbps')
with open(indexfile, 'rb') as f:
_xdr = xdrlib.Unpacker(f.read())
if _xdr.unpack_string() != 'nmbps_index':
print('Error: unknown file.')
return
_Nx = _xdr.unpack_int()
_Ny = _xdr.unpack_int()
_pt = 0
_Npts = 0
def importNext():
'''
Loads the next available nMBP (after calling import_nMBPs)
'''
global _model, _modelfile, _parfile, _indexfile, _rad, _xdr, _Nx, _Ny, _Npts, _pt, _parameters, _pos
if _pt < 0:
print('No more nMBPs available.')
return
if _pt >= _Npts-1:
if not _xdr.unpack_bool():
_pt = -1
print('No more nMBPs available.')
return
_rad = np.array(_xdr.unpack_array(_xdr.unpack_float)).reshape((_Nx, _Ny))
_Npts = _xdr.unpack_int()
_pt = 0
if _Npts <= _pt:
_pt = -1
print('No more nMBPs available.')
return
else:
_pt = _pt+1
modelitime = _xdr.unpack_int()
pX = _xdr.unpack_int()
pY = _xdr.unpack_int()
contrast_local = _xdr.unpack_float()
contrast_global = _xdr.unpack_float()
#dpos = _xdr.get_position()
diametre = _xdr.unpack_float()
_pos = _xdr.get_position()
active_flag = _xdr.unpack_bool()
#with open(_indexfile+'.nmbps', 'r+b') as f:
# f.seek(dpos)
# xdr = xdrlib.Packer()
# xdr.pack_float(2.*diametre)
# f.write(xdr.get_buffer())
#return True
# Load uio_file | |
False) ]))
transitions.append(fac.Transition(st_25, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_26, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_27, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_28, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_22, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_22, False) ]))
st_23._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_24, [
fac.UpdateInstruction(cc_23, True) ]))
transitions.append(fac.Transition(st_25, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_26, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_27, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_28, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_23, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_23, False) ]))
st_24._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_25, [
fac.UpdateInstruction(cc_24, True) ]))
transitions.append(fac.Transition(st_26, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_27, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_28, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_24, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_24, False) ]))
st_25._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_26, [
fac.UpdateInstruction(cc_25, True) ]))
transitions.append(fac.Transition(st_27, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_28, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_25, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_25, False) ]))
st_26._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_27, [
fac.UpdateInstruction(cc_26, True) ]))
transitions.append(fac.Transition(st_28, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_26, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_26, False) ]))
st_27._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_28, [
fac.UpdateInstruction(cc_27, True) ]))
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_27, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_27, False) ]))
st_28._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_29, [
fac.UpdateInstruction(cc_28, True) ]))
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_28, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_28, False) ]))
st_29._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_30, [
fac.UpdateInstruction(cc_29, True) ]))
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_29, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_29, False) ]))
st_30._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_31, [
fac.UpdateInstruction(cc_30, True) ]))
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_30, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_30, False) ]))
st_31._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_32, [
fac.UpdateInstruction(cc_31, True) ]))
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_31, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_31, False) ]))
st_32._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_33, [
fac.UpdateInstruction(cc_32, True) ]))
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_32, False) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_32, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_32, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_32, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_32, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_32, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_32, False) ]))
st_33._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_34, [
fac.UpdateInstruction(cc_33, True) ]))
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_33, False) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_33, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_33, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_33, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_33, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_33, False) ]))
st_34._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_35, [
fac.UpdateInstruction(cc_34, True) ]))
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_34, False) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_34, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_34, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_34, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_34, False) ]))
st_35._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_36, [
fac.UpdateInstruction(cc_35, True) ]))
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_35, False) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_35, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_35, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_35, False) ]))
st_36._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_37, [
fac.UpdateInstruction(cc_36, True) ]))
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_36, False) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_36, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_36, False) ]))
st_37._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_38, [
fac.UpdateInstruction(cc_37, True) ]))
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_37, False) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_37, False) ]))
st_38._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_39, [
fac.UpdateInstruction(cc_38, True) ]))
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_38, False) ]))
st_39._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_40, [
fac.UpdateInstruction(cc_39, True) ]))
st_40._set_transitionSet(transitions)
return fac.Automaton(states, counters, False, containing_state=None)
CTD_ANON_3._Automaton = _BuildAutomaton_3()
CTD_ANON_4._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'Information'), CTD_ANON_5, scope=CTD_ANON_4, location=pyxb.utils.utility.Location('./pug_rest.xsd', 78, 8)))
CTD_ANON_4._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'SourceName'), pyxb.binding.datatypes.string, scope=CTD_ANON_4, location=pyxb.utils.utility.Location('./pug_rest.xsd', 120, 8)))
def _BuildAutomaton_4 ():
# Remove this helper function from the namespace after it is invoked
global _BuildAutomaton_4
del _BuildAutomaton_4
import pyxb.utils.fac as fac
counters = set()
cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 78, 8))
counters.add(cc_0)
cc_1 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 120, 8))
counters.add(cc_1)
states = []
final_update = set()
final_update.add(fac.UpdateInstruction(cc_0, False))
symbol = pyxb.binding.content.ElementUse(CTD_ANON_4._UseForTag(pyxb.namespace.ExpandedName(None, 'Information')), pyxb.utils.utility.Location('./pug_rest.xsd', 78, 8))
st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False)
states.append(st_0)
final_update = set()
final_update.add(fac.UpdateInstruction(cc_1, False))
symbol = pyxb.binding.content.ElementUse(CTD_ANON_4._UseForTag(pyxb.namespace.ExpandedName(None, 'SourceName')), pyxb.utils.utility.Location('./pug_rest.xsd', 120, 8))
st_1 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False)
states.append(st_1)
transitions = []
transitions.append(fac.Transition(st_0, [
fac.UpdateInstruction(cc_0, True) ]))
transitions.append(fac.Transition(st_1, [
fac.UpdateInstruction(cc_0, False) ]))
st_0._set_transitionSet(transitions)
transitions = []
transitions.append(fac.Transition(st_1, [
fac.UpdateInstruction(cc_1, True) ]))
st_1._set_transitionSet(transitions)
return fac.Automaton(states, counters, True, containing_state=None)
CTD_ANON_4._Automaton = _BuildAutomaton_4()
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'CID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 82, 16)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'SID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 83, 16)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'AID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 84, 16)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'Synonym'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 86, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'GI'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 90, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'GeneID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 91, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'DepositionDate'), DateTime, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 92, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'ModificationDate'), DateTime, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 93, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'CreationDate'), DateTime, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 94, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'HoldDate'), DateTime, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 95, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'RegistryID'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 96, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'RN'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 97, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'PubMedID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 98, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'MMDBID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 99, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'DBURL'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 100, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'SBURL'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 101, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'ProteinGI'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 102, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'NucleotideGI'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 103, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'TaxonomyID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 104, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'MIMID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 105, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'ProbeID'), pyxb.binding.datatypes.int, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 106, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'PatentID'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 107, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'ProteinName'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 108, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'GeneSymbol'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 109, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'SourceName'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 110, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'SourceCategory'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 111, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'Title'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 112, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'Description'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 113, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'DescriptionSourceName'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 114, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'DescriptionURL'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 115, 14)))
CTD_ANON_5._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(None, 'ConformerID'), pyxb.binding.datatypes.string, scope=CTD_ANON_5, location=pyxb.utils.utility.Location('./pug_rest.xsd', 116, 14)))
def _BuildAutomaton_5 ():
# Remove this helper function from the namespace after it is invoked
global _BuildAutomaton_5
del _BuildAutomaton_5
import pyxb.utils.fac as fac
counters = set()
cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 86, 14))
counters.add(cc_0)
cc_1 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 87, 14))
counters.add(cc_1)
cc_2 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('./pug_rest.xsd', 88, | |
<reponame>preranaandure/wildlifecompliance<filename>wildlifecompliance/components/artifact/api.py
import json
import re
import operator
import traceback
import os
import base64
import geojson
from django.db.models import Q, Min, Max
from django.db import transaction
from django.http import HttpResponse
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.core.exceptions import ValidationError
from django.conf import settings
from wildlifecompliance import settings
from django.contrib import messages
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from rest_framework import viewsets, serializers, status, generics, views, filters
import rest_framework.exceptions as rest_exceptions
from rest_framework.decorators import (
detail_route,
list_route,
renderer_classes,
parser_classes,
api_view
)
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser, BasePermission
from rest_framework.pagination import PageNumberPagination
from collections import OrderedDict
from django.core.cache import cache
from ledger.accounts.models import EmailUser, Address
from ledger.address.models import Country
from ledger.checkout.utils import calculate_excl_gst
from datetime import datetime, timedelta, date
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
from wildlifecompliance.components.main.api import save_location
from wildlifecompliance.components.main.models import TemporaryDocumentCollection
from wildlifecompliance.components.main.process_document import (
process_generic_document,
save_comms_log_document_obj,
save_default_document_obj,
save_renderer_document_obj,
#save_details_document_obj,
#save_storage_document_obj,
)
from wildlifecompliance.components.main.email import prepare_mail
from wildlifecompliance.components.users.serializers import (
UserAddressSerializer,
ComplianceUserDetailsSerializer,
)
from wildlifecompliance.helpers import is_customer, is_internal
from wildlifecompliance.components.artifact.models import (
Artifact,
DocumentArtifact,
PhysicalArtifact,
DocumentArtifactType,
PhysicalArtifactType,
PhysicalArtifactDisposalMethod,
ArtifactUserAction,
PhysicalArtifactFormDataRecord,
DocumentArtifactLegalCases,
PhysicalArtifactLegalCases,
)
from wildlifecompliance.components.artifact.serializers import (
ArtifactSerializer,
DocumentArtifactSerializer,
SaveDocumentArtifactSerializer,
SavePhysicalArtifactSerializer,
PhysicalArtifactSerializer,
#DocumentArtifactTypeSerializer,
PhysicalArtifactTypeSerializer,
PhysicalArtifactTypeSchemaSerializer,
PhysicalArtifactDisposalMethodSerializer,
ArtifactUserActionSerializer,
ArtifactCommsLogEntrySerializer,
ArtifactPaginatedSerializer,
)
from wildlifecompliance.components.users.serializers import ComplianceManagementSaveUserSerializer
from wildlifecompliance.components.users.models import (
CompliancePermissionGroup,
)
from django.contrib.auth.models import Permission, ContentType
#from utils import SchemaParser
from rest_framework_datatables.pagination import DatatablesPageNumberPagination
from rest_framework_datatables.filters import DatatablesFilterBackend
from rest_framework_datatables.renderers import DatatablesRenderer
from wildlifecompliance.components.legal_case.email import (
send_mail)
from wildlifecompliance.components.legal_case.models import LegalCase
from reversion.models import Version
#import unicodedata
class DocumentArtifactViewSet(viewsets.ModelViewSet):
queryset = DocumentArtifact.objects.all()
serializer_class = DocumentArtifactSerializer
def get_queryset(self):
# import ipdb; ipdb.set_trace()
user = self.request.user
if is_internal(self.request):
return DocumentArtifact.objects.all()
return DocumentArtifact.objects.none()
def create(self, request, *args, **kwargs):
try:
with transaction.atomic():
request_data = request.data
instance, headers = self.common_save(request_data)
instance.log_user_action(
ArtifactUserAction.ACTION_CREATE_ARTIFACT.format(
instance.number), request)
return_serializer = DocumentArtifactSerializer(instance, context={'request': request})
return Response(
return_serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
except serializers.ValidationError:
print(traceback.print_exc())
raise
except ValidationError as e:
if hasattr(e, 'error_dict'):
raise serializers.ValidationError(repr(e.error_dict))
else:
# raise serializers.ValidationError(repr(e[0].encode('utf-8')))
raise serializers.ValidationError(repr(e[0]))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
@list_route(methods=['GET', ])
def document_type_choices(self, request, *args, **kwargs):
res_obj = []
for choice in DocumentArtifact.DOCUMENT_TYPE_CHOICES:
res_obj.append({'id': choice[0], 'display': choice[1]});
res_json = json.dumps(res_obj)
return HttpResponse(res_json, content_type='application/json')
@renderer_classes((JSONRenderer,))
#def inspection_save(self, request, workflow=False, *args, **kwargs):
def update(self, request, workflow=False, *args, **kwargs):
try:
with transaction.atomic():
instance = self.get_object()
request_data = request.data
instance, headers = self.common_save(request_data, instance)
instance.log_user_action(
ArtifactUserAction.ACTION_SAVE_ARTIFACT.format(
instance.number), request)
return_serializer = DocumentArtifactSerializer(instance, context={'request': request})
return Response(
return_serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
except serializers.ValidationError:
print(traceback.print_exc())
raise
except ValidationError as e:
print(traceback.print_exc())
raise serializers.ValidationError(repr(e.error_dict))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
def common_save(self, request_data, instance=None):
print("common save")
print(request_data)
try:
with transaction.atomic():
#document_type = request_data.get('document_type')
#document_type_id = None
#if document_type:
# document_type_id = document_type.get('id')
# request_data['document_type_id'] = document_type_id
if instance:
serializer = SaveDocumentArtifactSerializer(
instance=instance,
data=request_data,
partial=True
)
else:
serializer = SaveDocumentArtifactSerializer(
data=request_data,
partial=True
)
serializer.is_valid(raise_exception=True)
if serializer.is_valid():
print("serializer.validated_data")
print(serializer.validated_data)
saved_instance = serializer.save()
headers = self.get_success_headers(serializer.data)
# save legal_case_id
legal_case_id = request_data.get('legal_case_id')
if legal_case_id:
try:
legal_case_id_int = int(legal_case_id)
except Exception as e:
raise e
legal_case = LegalCase.objects.get(id=legal_case_id_int)
if legal_case:
if not DocumentArtifactLegalCases.objects.filter(
legal_case_id=legal_case.id,
document_artifact_id=saved_instance.id):
DocumentArtifactLegalCases.objects.create_with_primary(
legal_case_id=legal_case.id,
document_artifact_id=saved_instance.id)
# save temp doc if exists
if request_data.get('temporary_document_collection_id'):
self.handle_document(request_data, saved_instance)
# create officer_interviewer_email_user if required and attach to DocumentArtifact
if request_data.get('officer_interviewer'):
officer_interviewer = request_data.get('officer_interviewer')
email_user_instance = self.create_officer_interviewer_email_user(officer_interviewer)
if email_user_instance:
saved_instance.officer_interviewer = email_user_instance
saved_instance.save()
#import ipdb; ipdb.set_trace()
#if not (saved_instance.officer_interviewer or saved_instance.person_providing_statement):
if saved_instance.document_type == 'record_of_interview' and not saved_instance.offender:
raise serializers.ValidationError('Record of Interview must have an associated Offender')
if saved_instance.document_type == 'witness_statement' and not saved_instance.person_providing_statement:
raise serializers.ValidationError('Witness Statement must have an associated Witness')
if saved_instance.document_type == 'expert_statement' and not saved_instance.person_providing_statement:
raise serializers.ValidationError('Expert Statement must have an associated Expert')
if saved_instance.document_type == 'officer_statement' and not saved_instance.officer_interviewer:
raise serializers.ValidationError('Officer Statement must have an associated Officer')
#else:
# saved_instance.save()
return (saved_instance, headers)
except serializers.ValidationError:
print(traceback.print_exc())
raise
except ValidationError as e:
print(traceback.print_exc())
raise serializers.ValidationError(repr(e.error_dict))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
def create_officer_interviewer_email_user(self, officer_interviewer, *args, **kwargs):
try:
#email_user_id_requested = request.data.get('email_user', {}).get('id', {})
#email_address = request.data.get('email_user', {}).get('email', '')
email_user_instance = None
email_address = officer_interviewer.get('email')
#first_name = officer_interviewer.get('given_name') if officer_interviewer.get('given_name') else officer_interviewer.get('first_name')
#last_name = officer_interviewer.get('surname') if officer_interviewer.get('surname') else officer_interviewer.get('last_name')
first_name = officer_interviewer.get('given_name', '')
last_name = officer_interviewer.get('surname', '')
## only write new value if new person selected in front end
if not (first_name and last_name):
return None
else:
if not email_address:
#first_name = request.data.get('email_user', {}).get('first_name', '')
#last_name = request.data.get('email_user', {}).get('last_name', '')
email_address = generate_dummy_email(first_name, last_name)
# generate queryset to test whether user exists in EmailUser
qs = EmailUser.objects.filter(email=email_address)
if qs and qs.first():
email_user_instance = qs.first()
else:
email_user_instance = EmailUser.objects.create_user(email_address, '')
email_user_instance.is_staff = True
email_user_instance.save()
#request.data['email_user'].update({'email': email_address})
email_user_serializer = ComplianceManagementSaveUserSerializer(
email_user_instance,
#data=request.data['email_user'],
data={
"first_name": first_name,
"surname": last_name,
},
partial=True)
if email_user_serializer.is_valid(raise_exception=True):
email_user_instance = email_user_serializer.save()
return email_user_instance
except ValidationError as e:
print(traceback.print_exc())
raise serializers.ValidationError(repr(e.error_dict))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
def handle_document(self, request_data, instance=None, *args, **kwargs):
print("handle document")
try:
if not instance:
instance = self.get_object()
temporary_document_collection_dict = request_data.get('temporary_document_collection_id')
temporary_document_collection_id = temporary_document_collection_dict.get('temp_doc_id')
if temporary_document_collection_id:
temp_doc_collection, created = TemporaryDocumentCollection.objects.get_or_create(
id=temporary_document_collection_id)
if temp_doc_collection:
for doc in temp_doc_collection.documents.all():
save_default_document_obj(instance, doc)
temp_doc_collection.delete()
except ValidationError as e:
print(traceback.print_exc())
raise serializers.ValidationError(repr(e.error_dict))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
#@detail_route(methods=['POST'])
#@renderer_classes((JSONRenderer,))
#def process_default_document(self, request, *args, **kwargs):
# try:
# instance = self.get_object()
# returned_data = process_generic_document(request, instance)
# if returned_data:
# return Response(returned_data)
# else:
# return Response()
# except serializers.ValidationError:
# print(traceback.print_exc())
# raise
# except ValidationError as e:
# if hasattr(e, 'error_dict'):
# raise serializers.ValidationError(repr(e.error_dict))
# else:
# raise serializers.ValidationError(repr(e[0].encode('utf-8')))
# except Exception as e:
# print(traceback.print_exc())
# raise serializers.ValidationError(str(e))
class PhysicalArtifactViewSet(viewsets.ModelViewSet):
queryset = PhysicalArtifact.objects.all()
serializer_class = PhysicalArtifactSerializer
def get_queryset(self):
# import ipdb; ipdb.set_trace()
user = self.request.user
if is_internal(self.request):
return PhysicalArtifact.objects.all()
return PhysicalArtifact.objects.none()
def create(self, request, *args, **kwargs):
#print("create")
#print(request.data)
try:
with transaction.atomic():
request_data = request.data
instance, headers = self.common_save(request_data)
instance.log_user_action(
ArtifactUserAction.ACTION_CREATE_ARTIFACT.format(
instance.number), request)
return_serializer = PhysicalArtifactSerializer(instance, context={'request': request})
return Response(
return_serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
except serializers.ValidationError:
print(traceback.print_exc())
raise
except ValidationError as e:
if hasattr(e, 'error_dict'):
raise serializers.ValidationError(repr(e.error_dict))
else:
# raise serializers.ValidationError(repr(e[0].encode('utf-8')))
raise serializers.ValidationError(repr(e[0]))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
@renderer_classes((JSONRenderer,))
#def inspection_save(self, request, workflow=False, *args, **kwargs):
def update(self, request, workflow=False, *args, **kwargs):
#print(request.data)
try:
with transaction.atomic():
instance = self.get_object()
request_data = request.data
instance, headers = self.common_save(request_data, instance)
instance.log_user_action(
ArtifactUserAction.ACTION_SAVE_ARTIFACT.format(
instance.number), request)
# disposal
if request.data.get('disposal_date'):
instance.dispose(request)
return_serializer = PhysicalArtifactSerializer(instance, context={'request': request})
return Response(
return_serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
except serializers.ValidationError:
print(traceback.print_exc())
raise
except ValidationError as e:
print(traceback.print_exc())
raise serializers.ValidationError(repr(e.error_dict))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
@detail_route(methods=['POST'])
@renderer_classes((JSONRenderer,))
def process_renderer_document(self, request, *args, **kwargs):
print("process_renderer_document")
try:
instance = self.get_object()
returned_data = process_generic_document(
request,
instance,
document_type='renderer_documents'
)
if returned_data:
print("returned_data")
print(returned_data)
filedata = returned_data.get('filedata')
# Log action if file uploaded
if filedata and request.data.get('action') == 'save':
file_name = filedata[0].get('name')
#if file_name:
# instance.log_user_action(
# ArtifactUserAction.ACTION_UPLOAD_INSPECTION_REPORT.format(
# file_name), request)
return Response(returned_data)
else:
return Response()
except serializers.ValidationError:
print(traceback.print_exc())
raise
except ValidationError as e:
if hasattr(e, 'error_dict'):
raise serializers.ValidationError(repr(e.error_dict))
else:
# raise serializers.ValidationError(repr(e[0].encode('utf-8')))
raise serializers.ValidationError(repr(e[0]))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
@detail_route(methods=['post'])
@renderer_classes((JSONRenderer,))
def form_data(self, instance, request_data, *args, **kwargs):
print("form data")
print(request_data)
try:
#instance = self.get_object()
PhysicalArtifactFormDataRecord.process_form(
instance,
request_data.get('renderer_data'),
action=PhysicalArtifactFormDataRecord.ACTION_TYPE_ASSIGN_VALUE
)
return redirect(reverse('external'))
except ValidationError as e:
raise serializers.ValidationError(repr(e.error_dict))
except Exception as e:
print(traceback.print_exc())
raise serializers.ValidationError(str(e))
def common_save(self, request_data, instance=None):
print(request_data)
try:
with transaction.atomic():
#physical_artifact_type = request_data.get('physical_artifact_type')
#physical_artifact_type_id = None
#if physical_artifact_type:
# physical_artifact_type_id = physical_artifact_type.get('id')
# request_data['physical_artifact_type_id'] = physical_artifact_type_id
disposal_method = request_data.get('disposal_method')
disposal_method_id = None
if disposal_method:
disposal_method_id = disposal_method.get('id')
request_data['disposal_method_id'] = disposal_method_id
if instance:
serializer = SavePhysicalArtifactSerializer(
instance=instance,
data=request_data,
partial=True
)
else:
serializer = SavePhysicalArtifactSerializer(
data=request_data,
partial=True
)
serializer.is_valid(raise_exception=True)
if serializer.is_valid():
print("serializer.validated_data")
print(serializer.validated_data)
saved_instance = serializer.save()
headers = self.get_success_headers(serializer.data)
# save legal_case_id
legal_case_id = request_data.get('legal_case_id')
used_within_case = (request_data.get('used_within_case') if
'used_within_case' in request_data.keys() else None)
sensitive_non_disclosable = (request_data.get('sensitive_non_disclosable') if
'sensitive_non_disclosable' in request_data.keys() else None)
#reason_sensitive_non_disclosable = request_data.get('reason_sensitive_non_disclosable')
if legal_case_id:
#instance.add_legal_case(legal_case_id)
try:
legal_case_id_int = int(legal_case_id)
except Exception as e:
raise e
legal_case = LegalCase.objects.get(id=legal_case_id_int)
if legal_case:
link = None
if PhysicalArtifactLegalCases.objects.filter(
legal_case_id=legal_case.id,
physical_artifact_id=saved_instance.id):
# get link
print("get link")
link= PhysicalArtifactLegalCases.objects.get(
legal_case_id=legal_case.id,
physical_artifact_id=saved_instance.id)
else:
# create link
print("create link")
link = PhysicalArtifactLegalCases.objects.create_with_primary(
legal_case_id=legal_case.id,
physical_artifact_id=saved_instance.id)
if used_within_case is not None:
link.used_within_case = used_within_case
if sensitive_non_disclosable is not None:
link.sensitive_non_disclosable = sensitive_non_disclosable
#if reason_sensitive_non_disclosable:
# link.reason_sensitive_non_disclosable = reason_sensitive_non_disclosable
link.save()
# save temp doc if exists
if request_data.get('temporary_document_collection_list'):
self.handle_document(request_data, saved_instance)
# renderer data
if request_data.get('renderer_data'):
self.form_data(saved_instance, | |
<gh_stars>0
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2017 RDK Management
#
# 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.
##########################################################################
'''
<?xml version='1.0' encoding='utf-8'?>
<xml>
<id></id>
<!-- Do not edit id. This will be auto filled while exporting. If you are adding a new script keep the id empty -->
<version>6</version>
<!-- Do not edit version. This will be auto incremented while updating. If you are adding a new script you can keep the vresion as 1 -->
<name>TS_LMLite_CheckConnectedDeviceNumber_InBridgeMode</name>
<!-- If you are adding a new script you can specify the script name. Script Name should be unique same as this file name with out .py extension -->
<primitive_test_id></primitive_test_id>
<!-- Do not change primitive_test_id if you are editing an existing script. -->
<primitive_test_name>LMLiteStub_Get</primitive_test_name>
<!-- -->
<primitive_test_version>1</primitive_test_version>
<!-- -->
<status>FREE</status>
<!-- -->
<synopsis>If gateway is in bridge mode, Device.Hosts.X_CISCO_COM_ConnectedDeviceNumber should be zero.</synopsis>
<!-- -->
<groups_id />
<!-- -->
<execution_time>10</execution_time>
<!-- -->
<long_duration>false</long_duration>
<!-- -->
<advanced_script>false</advanced_script>
<!-- execution_time is the time out time for test execution -->
<remarks></remarks>
<!-- Reason for skipping the tests if marked to skip -->
<skip>false</skip>
<!-- -->
<box_types>
<box_type>Broadband</box_type>
<!-- -->
<box_type>Emulator</box_type>
<!-- -->
</box_types>
<rdk_versions>
<rdk_version>RDKB</rdk_version>
<!-- -->
</rdk_versions>
<test_cases>
<test_case_id>TC_LMLite_10</test_case_id>
<test_objective>If gateway is in bridge mode, Device.Hosts.X_CISCO_COM_ConnectedDeviceNumber should be zero.</test_objective>
<test_type>Positive</test_type>
<test_setup>XB3,Emulator,RPI</test_setup>
<pre_requisite>1.Ccsp Components should be in a running state else invoke cosa_start.sh manually that includes all the ccsp components.
2.TDK Agent should be in running state or invoke it through StartTdk.sh script</pre_requisite>
<api_or_interface_used>LMLiteStub_Get</api_or_interface_used>
<input_parameters>Device.Hosts.X_CISCO_COM_ConnectedDeviceNumber
Device.X_CISCO_COM_DeviceControl.LanManagementEntry.1.LanMode</input_parameters>
<automation_approch>1. Load Lmlite modules
2. From script invoke LMLiteStub_Get to get the number of connected devices.
3. Check if the device is in bridge mode or not
4.if it is bridge mode number of connected devices should be zero
5. Validation of the result is done within the python script and send the result status to Test Manager.
6.Test Manager will publish the result in GUI as PASS/FAILURE based on the response from lmlite stub.</automation_approch>
<except_output>CheckPoint 1:
The output should be logged in the Agent console/Component log
CheckPoint 2:
Stub function result should be success and should see corresponding log in the agent console log
CheckPoint 3:
TestManager GUI will publish the result as PASS in Execution/Console page of Test Manager</except_output>
<priority>High</priority>
<test_stub_interface>None</test_stub_interface>
<test_script>TS_LMLite_CheckConnectedDeviceNumber_InBridgeMode</test_script>
<skipped>No</skipped>
<release_version></release_version>
<remarks></remarks>
</test_cases>
<script_tags />
</xml>
'''
# use tdklib library,which provides a wrapper for tdk testcase script
import tdklib;
from time import sleep;
#Test component to be tested
obj = tdklib.TDKScriptingLibrary("lmlite","1");
wifiobj = tdklib.TDKScriptingLibrary("wifiagent","1");
#IP and Port of box, No need to change,
#This will be replaced with correspoing Box Ip and port while executing script
ip = <ipaddress>
port = <port>
obj.configureTestCase(ip,port,'TS_LMLite_CheckConnectedDeviceNumber_InBridgeMode');
wifiobj.configureTestCase(ip,port,'TS_LMLite_CheckConnectedDeviceNumber_InBridgeMode');
#Get the result of connection with test component and DUT
loadmodulestatus=obj.getLoadModuleResult();
wifiloadmodulestatus=wifiobj.getLoadModuleResult();
if "SUCCESS" in (loadmodulestatus.upper() and wifiloadmodulestatus.upper()):
#Set the result status of execution
obj.setLoadModuleStatus("SUCCESS");
#Disable WiFi before testing LMLite features
tdkTestObj = wifiobj.createTestStep('WIFIAgent_Set');
tdkTestObj.addParameter("paramName","Device.WiFi.SSID.1.Enable");
tdkTestObj.addParameter("paramValue","false");
tdkTestObj.addParameter("paramType","boolean");
expectedresult="SUCCESS"
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult1 = tdkTestObj.getResult();
Details = tdkTestObj.getResultDetails();
tdkTestObj = wifiobj.createTestStep('WIFIAgent_Set');
tdkTestObj.addParameter("paramName","Device.WiFi.SSID.2.Enable");
tdkTestObj.addParameter("paramValue","false");
tdkTestObj.addParameter("paramType","boolean");
expectedresult="SUCCESS"
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult2 = tdkTestObj.getResult();
Details = tdkTestObj.getResultDetails();
if expectedresult in (actualresult1 and actualresult2):
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP : Disable WiFi before testing LMLite features";
print "EXPECTED RESULT : Should disable WiFi";
print "ACTUAL RESULT :%s" %Details;
#Get the result of execution
print "[TEST EXECUTION RESULT] : SUCCESS";
#Check if device is in bridge mode or not
tdkTestObj = obj.createTestStep('LMLiteStub_Get');
tdkTestObj.addParameter("paramName","Device.X_CISCO_COM_DeviceControl.LanManagementEntry.1.LanMode");
expectedresult="SUCCESS";
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult = tdkTestObj.getResult();
Current_Mode = tdkTestObj.getResultDetails();
if "router" not in Current_Mode:
Mode = "bridge mode";
else:
Mode = "Router mode"
if expectedresult in actualresult:
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP 1: Check if the device is in bridge mode or not";
print "EXPECTED RESULT 1: Should get the mode of device";
print "ACTUAL RESULT 1: :LanMode is %s" %Mode;
#Get the result of execution
print "[TEST EXECUTION RESULT] : SUCCESS";
if "bridge mode" not in Mode:
tdkTestObj = obj.createTestStep('LMLiteStub_Set');
tdkTestObj.addParameter("ParamName","Device.X_CISCO_COM_DeviceControl.LanManagementEntry.1.LanMode");
tdkTestObj.addParameter("ParamValue","bridge-static");
tdkTestObj.addParameter("Type","string");
expectedresult="SUCCESS";
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult = tdkTestObj.getResult();
details = tdkTestObj.getResultDetails();
if expectedresult in actualresult:
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP 2: Set the LanMode as bridge ";
print "EXPECTED RESULT 2: Should set the LanMode as bridge mode";
print "ACTUAL RESULT 2: : %s" %details;
Mode = "bridge mode";
#Get the result of execution
print "[TEST EXECUTION RESULT] : SUCCESS";
else:
#Set the result status of execution
tdkTestObj.setResultStatus("FAILURE");
print "TEST STEP 2: Set the LanMode as bridge ";
print "EXPECTED RESULT 2: Should set the LanMode as bridge mode";
print "ACTUAL RESULT 2: : %s" %details;
#Get the result of execution
print "[TEST EXECUTION RESULT] : FAILURE";
obj.unloadModule("lmlite");
exit();
#Wait for few seconds for the Lan mode to get reflected
sleep(30);
tdkTestObj = obj.createTestStep('LMLiteStub_Get');
tdkTestObj.addParameter("paramName","Device.Hosts.X_CISCO_COM_ConnectedDeviceNumber");
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult = tdkTestObj.getResult();
NoOfClients = tdkTestObj.getResultDetails();
print "Lan Mode retrieved is: %s" %Mode;
if expectedresult in actualresult:
if "bridge mode" in Mode and int(NoOfClients) == 0:
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP 3:Check the number of connected devices";
print "EXPECTED RESULT 3: The number of connected devices should be zero if device is in bridge mode";
print "ACTUAL RESULT 3: No of Clients is %s" %NoOfClients;
#Get the result of execution
print "[TEST EXECUTION RESULT] : SUCCESS";
else:
#Set the result status of execution
tdkTestObj.setResultStatus("FAILURE");
print "TEST STEP 3:Check the number of connected devices";
print "EXPECTED RESULT 3: The number of connected devices should be zero if device is in bridge mode";
print "ACTUAL RESULT 3: :No of Clients is %s" %NoOfClients;
#Get the result of execution
print "[TEST EXECUTION RESULT] : FAILURE";
else:
#Set the result status of execution
tdkTestObj.setResultStatus("FAILURE");
print "TEST STEP 2:Get the number of active clients connected";
print "EXPECTED RESULT 2: Should get the number of active clients connected";
print "ACTUAL RESULT 2: :No of Clients is %s" %NoOfClients;
#Get the result of execution
print "[TEST EXECUTION RESULT] : FAILURE";
#set default LanMode
tdkTestObj = obj.createTestStep('LMLiteStub_Set');
tdkTestObj.addParameter("ParamName","Device.X_CISCO_COM_DeviceControl.LanManagementEntry.1.LanMode");
tdkTestObj.addParameter("ParamValue",Current_Mode);
tdkTestObj.addParameter("Type","string");
expectedresult="SUCCESS";
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult = tdkTestObj.getResult();
details = tdkTestObj.getResultDetails();
if expectedresult in actualresult:
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP : Set the LanMode to default ";
print "EXPECTED RESULT : Should set the LanMode as default value";
print "ACTUAL RESULT : %s" %details;
#Get the result of execution
print "[TEST EXECUTION RESULT] : SUCCESS";
#Wait for few seconds for the Lan mode to get reflected
sleep(70);
else:
#Set the result status of execution
tdkTestObj.setResultStatus("FAILURE");
print "TEST STEP : Set the LanMode to default ";
print "EXPECTED RESULT : Should set the LanMode as default value";
print "ACTUAL RESULT : %s" %details;
#Get the result of execution
print "[TEST EXECUTION RESULT] : FAILURE";
else:
#Set the result status of execution
tdkTestObj.setResultStatus("FAILURE");
print "TEST STEP 1: Check if the device is in bridge mode or not";
print "EXPECTED RESULT 1: Should get the mode of device";
print "ACTUAL RESULT 1: :LanMode is %s" %Current_Mode;
#Get the result of execution
print "[TEST EXECUTION RESULT] : FAILURE";
#Enabling WiFi before exiting the test
tdkTestObj = wifiobj.createTestStep('WIFIAgent_Set');
tdkTestObj.addParameter("paramName","Device.WiFi.SSID.1.Enable");
tdkTestObj.addParameter("paramValue","true");
tdkTestObj.addParameter("paramType","boolean");
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult1 = tdkTestObj.getResult();
Details = tdkTestObj.getResultDetails();
tdkTestObj = wifiobj.createTestStep('WIFIAgent_Set');
tdkTestObj.addParameter("paramName","Device.WiFi.SSID.2.Enable");
tdkTestObj.addParameter("paramValue","true");
tdkTestObj.addParameter("paramType","boolean");
#Execute the test case in DUT
tdkTestObj.executeTestCase(expectedresult);
actualresult2 = tdkTestObj.getResult();
Details = tdkTestObj.getResultDetails();
if expectedresult in (actualresult1 and actualresult2):
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP : Enable WiFi | |
]
row_rcb = base_cell.row
col_rcb = base_cell.col
blk_rcb = base_cell.blk
self.assertEqual( base_cell.common_rcbs( [] ), [] )
self.assertEqual( base_cell.common_rcbs( [cell_with_none] ), [] )
self.assertEqual( base_cell.common_rcbs( [cell_same_row] ), [row_rcb] )
self.assertEqual( base_cell.common_rcbs( [cell_same_col] ), [col_rcb] )
self.assertEqual( base_cell.common_rcbs( [cell_same_blk] ), [blk_rcb] )
self.assertEqual( base_cell.common_rcbs( [cell_same_row_blk] ), [row_rcb, blk_rcb] )
self.assertEqual( base_cell.common_rcbs( [cell_same_col_blk] ), [col_rcb, blk_rcb] )
self.assertEqual( base_cell.common_rcbs( all_test_cells ), [] )
def test_input_bad_input_wrong_row_cnt(self) :
# Only 7 rows, values don't matter
puzzle = [ [0] * 9 for i in range(7) ]
# Make sure it raise the exception
self.assertRaises(ExcBadPuzzleInput, Board, puzzle)
# Verify the error message
try :
Board(puzzle)
except ExcBadPuzzleInput as exc :
self.assertEqual(exc.message, 'Wrong number of rows: 7')
# Make sure string spec'ed board generates a error
# The error message may differ
self.assertRaises(ExcBadPuzzleInput, Board, str(puzzle))
def test_input_bad_value(self) :
# 9 rows, , values don't matter
puzzle = [ [0] * 9 for i in range(9) ]
# Make a single bad value
puzzle[3][6] = 18
# Make sure it raise the exception
self.assertRaises(ExcBadPuzzleInput, Board, puzzle)
# Verify the error message
try :
Board(puzzle)
except ExcBadPuzzleInput as exc :
self.assertEqual(exc.message,
'Bad value: 18 at (row,col) (3,6)')
def test_input_bad_input_wrong_row_size(self) :
# 9 rows, , values don't matter
puzzle = [ [0] * 9 for i in range(9) ]
# remove an cell from a row
puzzle[4] = puzzle[4][1:]
# Make sure it raise the exception
self.assertRaises(ExcBadPuzzleInput, Board, puzzle)
# Verify the error message
try :
Board(puzzle)
except ExcBadPuzzleInput as exc :
self.assertEqual(exc.message, 'Row 4: Wrong size: 8')
# Make sure string spec'ed board generates a error
# The error message may differ
self.assertRaises(ExcBadPuzzleInput, Board, str(puzzle))
def test_input_duplicate_values(self) :
some_board_spec = [ \
[0, 4, 6, 1, 2, 7, 9, 5, 8], # 0 row
[7, 0, 0, 6, 9, 4, 1, 3, 2], # 1 row
[2, 1, 9, 0, 0, 0, 4, 6, 7], # 2 row
[4, 6, 2, 5, 3, 1, 0, 0, 0], # 3 row
[0, 3, 0, 2, 0, 8, 0, 0, 0], # 4 row
[8, 5, 7, 9, 4, 6, 2, 0, 3], # 5 row
[0, 9, 8, 4, 1, 3, 7, 2, 6], # 6 row
[6, 2, 4, 7, 5, 9, 3, 8, 1], # 7 row
[1, 7, 3, 8, 6, 2, 5, 9, 4] # 8 row
# col 0 1 2 3 4 5 6 7 8
]
# Make some illegal input
# duplicate value in a row
dup_in_row = copy.deepcopy(some_board_spec)
dup_in_row[3][7] = 1
expected_err_msg = "cell#34 at (3,7) value:1 is duplicated in cell's row"
self.assertRaises(ExcBadPuzzleInput, Board, dup_in_row) # Make sure it raise the exception
try:
board = Board(dup_in_row)
except ExcBadPuzzleInput as exc :
self.assertEqual(exc.message, expected_err_msg) # with right error message
# Make sure string spec'ed board generates a error
# The error message may differ
self.assertRaises(ExcBadPuzzleInput, Board, str(dup_in_row))
# duplicate value in a col
dup_in_col = copy.deepcopy(some_board_spec)
dup_in_col[4][7] = 5
dup_in_col[3][3] = 0 # avoid duplicate in the block
expected_err_msg = "cell#43 at (4,7) value:5 is duplicated in cell's col"
self.assertRaises(ExcBadPuzzleInput, Board, dup_in_col) # Make sure it raise the exception
try:
board = Board(dup_in_col)
except ExcBadPuzzleInput as exc :
self.assertEqual(exc.message, expected_err_msg) # with right error message
# Make sure string spec'ed board generates a error
# The error message may differ
self.assertRaises(ExcBadPuzzleInput, Board, str(dup_in_col))
# duplicate value in a blk
dup_in_blk = copy.deepcopy(some_board_spec)
dup_in_blk[6][7] = 4
expected_err_msg = "cell#61 at (6,7) value:4 is duplicated in cell's row"
self.assertRaises(ExcBadPuzzleInput, Board, dup_in_blk) # Make sure it raise the exception
try:
board = Board(dup_in_blk)
except ExcBadPuzzleInput as exc :
self.assertEqual(exc.message, expected_err_msg) # with right error message
# Make sure string spec'ed board generates a error
# The error message may differ
self.assertRaises(ExcBadPuzzleInput, Board, str(dup_in_blk))
def test_solve_cells(self) :
# Empty Board
board = Board()
# Solve 1 cell only
# Shouldn't solve any others
cells_to_solve = set( [CellToSolve( board[4][6], 3)])
num_solved = board.solve_cells( cells_to_solve)
self.assertEqual( num_solved, 1)
self.assertEqual( len( board.unsolved_cells), NUM_CELLS-1)
# Board with 4 unsolved that don't influence each other
input_spec ='''
0 4 6 1 2 7 9 5 8
7 8 5 6 9 4 1 3 0
2 1 9 3 8 5 4 6 7
4 0 2 5 3 1 8 7 9
9 3 1 2 7 8 6 0 5
8 5 7 9 4 6 2 1 3
5 9 8 4 1 3 7 2 6
6 2 4 7 5 9 3 8 1
1 7 3 8 6 2 5 9 4
'''
board = Board(input_spec)
solutions = [ CellToSolve( board[0][0] , 3 ),
CellToSolve( board[1][8] , 2 ),
CellToSolve( board[3][1] , 6 ),
CellToSolve( board[4][7] , 4 )
]
# Make sure we got that right
for (cell,value) in solutions :
self.assertTrue (cell in board.unsolved_cells)
self.assertTrue (value in cell.possible_values)
# Solve each cell in turn and make sure they solve the right amt of others
for cell_to_solve in solutions :
num_solved = board.solve_cells( set([ cell_to_solve ]))
self.assertEqual( num_solved, 1)
self.assertTrue ( board.is_solved() )
# Partially populated board
input_spec ='''
3 0 6 1 2 7 9 5 8
7 0 0 6 9 4 1 3 2
2 1 9 3 8 5 4 6 7
4 6 2 5 3 1 8 7 9
9 3 1 2 7 8 6 4 5
0 0 0 9 0 6 2 1 3
5 9 8 4 1 3 7 2 6
6 2 4 7 5 9 3 8 1
1 7 3 8 6 2 5 9 0
'''
board = Board(input_spec)
# All the cells that will solve this
solutions = [ CellToSolve( board[0][1] , 4 ),
CellToSolve( board[1][1] , 8 ),
CellToSolve( board[1][2] , 5 ),
CellToSolve( board[5][0] , 8 ),
CellToSolve( board[5][1] , 5 ),
CellToSolve( board[5][2] , 7 ),
CellToSolve( board[5][4] , 4 ),
CellToSolve( board[8][8] , 4 )
]
# Make sure we got that right
self.assertEqual (len(solutions), len(board.unsolved_cells))
for (cell,value) in solutions :
self.assertTrue (cell in board.unsolved_cells)
# Now solve it
num_solved = board.solve_cells ( solutions )
self.assertEqual ( num_solved, len( solutions) )
self.assertTrue ( board.is_solved() )
def test_common_rcbs(self) :
# empty board
board = Board()
#### Cells with no rcbs in common
ncc = [\
board[0][0],
board[1][3],
board[2][6],
board[3][1],
board[4][4],
board[5][7],
board[6][2],
board[7][5],
board[8][8],
]
for cell in ncc :
# One at a time, test against all others
common_rcbs = cell.common_rcbs( [ other_cell for other_cell in ncc if cell != other_cell])
self.assertFalse (common_rcbs)
#### Row and blk in common
cell_a = board[6][7]
cell_b = board[6][6]
self.assertEqual ( cell_a.row_num, cell_b.row_num )
self.assertEqual ( cell_a.blk_num, cell_b.blk_num )
self.assertNotEqual( cell_a.col_num, cell_b.col_num )
ones_in_common = cell_a.common_rcbs( [cell_b] )
self.assertEqual ( len(ones_in_common), 2)
self.assertTrue ( board.rows[6] in ones_in_common )
self.assertTrue ( board.blks[8] in ones_in_common )
### col and blk in common
cell_a = board[4][7]
cell_b = board[5][7]
self.assertNotEqual( cell_a.row_num, cell_b.row_num )
self.assertEqual ( cell_a.blk_num, cell_b.blk_num )
self.assertEqual ( cell_a.col_num, cell_b.col_num )
ones_in_common = cell_a.common_rcbs( [cell_b] )
self.assertEqual ( len(ones_in_common), 2)
self.assertTrue ( board.blks[5] in ones_in_common )
self.assertTrue ( board.cols[7] in ones_in_common )
def test_most_constrained_cell_num(self) :
# None solved, should return cell#0
bd = Board()
self.assertEqual(0, bd.most_constrained_cell_num() )
# All solved, should return cell#0
bd = Board(Test_board.full_spec_lrl)
self.assertEqual(0, bd.most_constrained_cell_num() )
# One unsolved cell. It should be returned
lrl = copy.deepcopy(Test_board.full_spec_lrl)
lrl[4][8] = 0
bd = Board(lrl)
self.assertEqual(4*9 + 8, bd.most_constrained_cell_num() )
# Two unsolved cells with same rcb unsolved count
# Should pick the first (by cell #)
lrl = copy.deepcopy(Test_board.full_spec_lrl)
lrl[3][7] = 0
lrl[6][2] = 0
bd = Board(lrl)
self.assertEqual(3*9 + 7, bd.most_constrained_cell_num() )
# Three unsolved cells with different rcb unsolved count
lrl = copy.deepcopy(Test_board.full_spec_lrl)
lrl[4][2] = 0 # same blk
lrl[5][1] = 0 # same | |
have the same length, but nothing deeper
assert ak.concatenate(arrays, axis=2).tolist() == [
[[0.0, 1.1, 2.2, 10, 20], [30]],
[[3.3, 4.4, 40]],
[[5.5, 50, 60, 70], [6.6, 7.7, 8.8, 9.9, 80, 90]],
]
def test_negative_axis_concatenate():
arrays = [
ak.Array([[[0.0, 1.1, 2.2], []], [[3.3, 4.4]], [[5.5], [6.6, 7.7, 8.8, 9.9]]]),
ak.Array([[[10, 20], [30]], [[40]], [[50, 60, 70], [80, 90]]]),
]
assert ak.concatenate(arrays, axis=-1).tolist() == [
[[0.0, 1.1, 2.2, 10, 20], [30]],
[[3.3, 4.4, 40]],
[[5.5, 50, 60, 70], [6.6, 7.7, 8.8, 9.9, 80, 90]],
]
assert ak.concatenate(arrays, axis=-2).tolist() == [
[[0.0, 1.1, 2.2], [], [10, 20], [30]],
[[3.3, 4.4], [40]],
[[5.5], [6.6, 7.7, 8.8, 9.9], [50, 60, 70], [80, 90]],
]
assert ak.concatenate(arrays, axis=-3).tolist() == [
[[0.0, 1.1, 2.2], []],
[[3.3, 4.4]],
[[5.5], [6.6, 7.7, 8.8, 9.9]],
[[10, 20], [30]],
[[40]],
[[50, 60, 70], [80, 90]],
]
def test_even_more():
dim1 = ak.Array([1.1, 2.2, 3.3, 4.4, 5.5])
dim1a = ak.Array([[1.1], [2.2], [3.3], [4.4], [5.5]])
dim1b = ak.Array(np.array([[1.1], [2.2], [3.3], [4.4], [5.5]]))
dim2 = ak.Array([[0, 1, 2], [], [3, 4], [5], [6, 7, 8, 9]])
dim3 = ak.Array([[[0, 1, 2], []], [[3, 4]], [], [[5], [6, 7, 8, 9]], []])
assert ak.concatenate([dim1, 999]).tolist() == [1.1, 2.2, 3.3, 4.4, 5.5, 999]
assert ak.concatenate([999, dim1]).tolist() == [999, 1.1, 2.2, 3.3, 4.4, 5.5]
assert ak.concatenate([dim1, dim2]).tolist() == [
1.1,
2.2,
3.3,
4.4,
5.5,
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
]
assert ak.concatenate([dim2, dim1]).tolist() == [
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
1.1,
2.2,
3.3,
4.4,
5.5,
]
with pytest.raises(ValueError):
ak.concatenate([dim1, 999], axis=1)
assert ak.concatenate([dim2, 999], axis=1).tolist() == [
[0, 1, 2, 999],
[999],
[3, 4, 999],
[5, 999],
[6, 7, 8, 9, 999],
]
assert ak.concatenate([999, dim2], axis=1).tolist() == [
[999, 0, 1, 2],
[999],
[999, 3, 4],
[999, 5],
[999, 6, 7, 8, 9],
]
with pytest.raises(ValueError):
ak.concatenate([dim1, dim2], axis=1)
with pytest.raises(ValueError):
ak.concatenate([dim2, dim1], axis=1)
assert ak.concatenate([dim1a, dim2], axis=1).tolist() == [
[1.1, 0, 1, 2],
[2.2],
[3.3, 3, 4],
[4.4, 5],
[5.5, 6, 7, 8, 9],
]
assert ak.concatenate([dim2, dim1a], axis=1).tolist() == [
[0, 1, 2, 1.1],
[2.2],
[3, 4, 3.3],
[5, 4.4],
[6, 7, 8, 9, 5.5],
]
assert ak.concatenate([dim1b, dim2], axis=1).tolist() == [
[1.1, 0, 1, 2],
[2.2],
[3.3, 3, 4],
[4.4, 5],
[5.5, 6, 7, 8, 9],
]
assert ak.concatenate([dim2, dim1b], axis=1).tolist() == [
[0, 1, 2, 1.1],
[2.2],
[3, 4, 3.3],
[5, 4.4],
[6, 7, 8, 9, 5.5],
]
assert ak.concatenate([123, dim1, dim2]).tolist() == [
123,
1.1,
2.2,
3.3,
4.4,
5.5,
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
]
assert ak.concatenate([123, dim2, dim1]).tolist() == [
123,
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
1.1,
2.2,
3.3,
4.4,
5.5,
]
assert ak.concatenate([dim1, 123, dim2]).tolist() == [
1.1,
2.2,
3.3,
4.4,
5.5,
123,
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
]
assert ak.concatenate([dim1, dim2, 123]).tolist() == [
1.1,
2.2,
3.3,
4.4,
5.5,
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
123,
]
assert ak.concatenate([dim2, 123, dim1]).tolist() == [
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
123,
1.1,
2.2,
3.3,
4.4,
5.5,
]
assert ak.concatenate([dim2, dim1, 123]).tolist() == [
[0, 1, 2],
[],
[3, 4],
[5],
[6, 7, 8, 9],
1.1,
2.2,
3.3,
4.4,
5.5,
123,
]
with pytest.raises(ValueError):
ak.concatenate([123, dim1, dim2], axis=1)
with pytest.raises(ValueError):
ak.concatenate([123, dim2, dim1], axis=1)
with pytest.raises(ValueError):
ak.concatenate([dim1, 123, dim2], axis=1)
with pytest.raises(ValueError):
ak.concatenate([dim1, dim2, 123], axis=1)
with pytest.raises(ValueError):
ak.concatenate([dim2, 123, dim1], axis=1)
with pytest.raises(ValueError):
ak.concatenate([dim2, dim1, 123], axis=1)
assert ak.concatenate([123, dim1a, dim2], axis=1).tolist() == [
[123, 1.1, 0, 1, 2],
[123, 2.2],
[123, 3.3, 3, 4],
[123, 4.4, 5],
[123, 5.5, 6, 7, 8, 9],
]
assert ak.concatenate([123, dim2, dim1a], axis=1).tolist() == [
[123, 0, 1, 2, 1.1],
[123, 2.2],
[123, 3, 4, 3.3],
[123, 5, 4.4],
[123, 6, 7, 8, 9, 5.5],
]
assert ak.concatenate([dim1a, 123, dim2], axis=1).tolist() == [
[1.1, 123, 0, 1, 2],
[2.2, 123],
[3.3, 123, 3, 4],
[4.4, 123, 5],
[5.5, 123, 6, 7, 8, 9],
]
assert ak.concatenate([dim1a, dim2, 123], axis=1).tolist() == [
[1.1, 0, 1, 2, 123],
[2.2, 123],
[3.3, 3, 4, 123],
[4.4, 5, 123],
[5.5, 6, 7, 8, 9, 123],
]
assert ak.concatenate([dim2, 123, dim1a], axis=1).tolist() == [
[0, 1, 2, 123, 1.1],
[123, 2.2],
[3, 4, 123, 3.3],
[5, 123, 4.4],
[6, 7, 8, 9, 123, 5.5],
]
assert ak.concatenate([dim2, dim1a, 123], axis=1).tolist() == [
[0, 1, 2, 1.1, 123],
[2.2, 123],
[3, 4, 3.3, 123],
[5, 4.4, 123],
[6, 7, 8, 9, 5.5, 123],
]
assert ak.concatenate([123, dim1b, dim2], axis=1).tolist() == [
[123, 1.1, 0, 1, 2],
[123, 2.2],
[123, 3.3, 3, 4],
[123, 4.4, 5],
[123, 5.5, 6, 7, 8, 9],
]
assert ak.concatenate([123, dim2, dim1b], axis=1).tolist() == [
[123, 0, 1, 2, 1.1],
[123, 2.2],
[123, 3, 4, 3.3],
[123, 5, 4.4],
[123, 6, 7, 8, 9, 5.5],
]
assert ak.concatenate([dim1b, 123, dim2], axis=1).tolist() == [
[1.1, 123, 0, 1, 2],
[2.2, 123],
[3.3, 123, 3, 4],
[4.4, 123, 5],
[5.5, 123, 6, 7, 8, 9],
]
assert ak.concatenate([dim1b, dim2, 123], axis=1).tolist() == [
[1.1, 0, 1, 2, 123],
[2.2, 123],
[3.3, 3, 4, 123],
[4.4, 5, 123],
[5.5, 6, 7, 8, 9, 123],
]
assert ak.concatenate([dim2, 123, dim1b], axis=1).tolist() == [
[0, 1, 2, 123, 1.1],
[123, 2.2],
[3, 4, 123, 3.3],
[5, 123, 4.4],
[6, 7, 8, 9, 123, 5.5],
]
assert ak.concatenate([dim2, dim1b, 123], axis=1).tolist() == [
[0, 1, 2, 1.1, 123],
[2.2, 123],
[3, 4, 3.3, 123],
[5, 4.4, 123],
[6, 7, 8, 9, 5.5, 123],
]
assert ak.concatenate([dim3, 123]).tolist() == [
[[0, 1, 2], []],
[[3, 4]],
[],
[[5], [6, 7, 8, 9]],
[],
123,
]
assert ak.concatenate([123, dim3]).tolist() == [
123,
[[0, 1, 2], []],
[[3, 4]],
[],
[[5], [6, 7, 8, 9]],
[],
]
assert ak.concatenate([dim3, 123], axis=1).tolist() == [
[[0, 1, 2], [], 123],
[[3, 4], 123],
[123],
[[5], [6, 7, 8, 9], 123],
[123],
]
assert ak.concatenate([123, dim3], axis=1).tolist() == [
[123, [0, 1, 2], []],
[123, [3, 4]],
[123],
[123, [5], [6, 7, 8, 9]],
[123],
]
with pytest.raises(ValueError):
ak.concatenate([dim3, dim1], axis=1)
with pytest.raises(ValueError):
ak.concatenate([dim1, dim3], axis=1)
assert ak.concatenate([dim3, dim2], axis=1).tolist() == [
[[0, 1, 2], [], 0, 1, 2],
[[3, 4]],
[3, 4],
[[5], [6, 7, 8, 9], 5],
[6, 7, 8, 9],
]
assert ak.concatenate([dim2, dim3], axis=1).tolist() == [
[0, 1, 2, [0, 1, 2], []],
[[3, 4]],
[3, 4],
[5, [5], [6, 7, 8, 9]],
[6, 7, 8, 9],
]
assert ak.concatenate([dim3, 123], axis=2).tolist() == [
[[0, 1, 2, 123], [123]],
[[3, 4, 123]],
[],
[[5, 123], [6, 7, 8, 9, 123]],
[],
]
assert ak.concatenate([123, dim3], axis=2).tolist() == [
[[123, 0, 1, 2], [123]],
[[123, 3, 4]],
[],
[[123, 5], [123, 6, 7, 8, 9]],
[],
]
assert ak.concatenate([dim3, dim3], axis=2).tolist() == [
[[0, 1, 2, 0, 1, 2], []],
[[3, 4, 3, 4]],
[],
[[5, 5], [6, 7, 8, 9, 6, 7, 8, 9]],
[],
]
rec1 = ak.Array(
[
{"x": [1, 2], "y": [1.1]},
{"x": [], "y": [2.2, 3.3]},
{"x": [3], "y": []},
{"x": [5, 6, 7], "y": []},
{"x": [8, 9], "y": [4.4, 5.5]},
]
)
rec2 = ak.Array(
[
{"x": [100], "y": [10, 20]},
{"x": [200], "y": []},
{"x": [300, 400], "y": [30]},
{"x": [], "y": [40, 50]},
{"x": [400, 500], "y": [60]},
]
)
assert ak.concatenate([rec1, rec2]).tolist() == [
{"x": [1, 2], "y": [1.1]},
{"x": [], "y": [2.2, 3.3]},
{"x": [3], "y": []},
{"x": [5, 6, 7], "y": []},
{"x": [8, 9], "y": [4.4, 5.5]},
{"x": [100], "y": [10, 20]},
{"x": [200], "y": []},
{"x": [300, 400], "y": [30]},
{"x": [], "y": [40, 50]},
{"x": [400, 500], "y": [60]},
]
assert ak.concatenate([rec1, rec2], axis=1).tolist() == [
{"x": [1, 2, 100], "y": [1.1, 10, 20]},
{"x": [200], "y": [2.2, 3.3]},
{"x": [3, | |
in self._attributeMap["edge"].keys() if ":" not in i]
d = list(self._attributeMap["detail"].keys())
if allInOne:
result = []
result.extend(v)
result.extend(f)
result.extend(e)
result.extend(d)
else:
result = {'vertex': v,
'face': f,
'edge': e,
'detail': d}
return result
def _getAttribType(self, attribClass, name):
"""
Get attribute value type.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
Returns:
str.
"""
if attribClass == "vertex":
value = self.getVertexAttrib(name, 0)
elif attribClass == "edge":
value = self.getEdgeAttrib(name, 0)
elif attribClass == "face":
value = self.getFaceAttrib(name, 0)
elif attribClass == "detail":
value = self.getDetailAttrib(name)
else:
return 'none'
checkType = type(value)
if checkType is np.ndarray or checkType is list:
if checkType is np.ndarray:
size = value.size
else:
size = len(value)
if size == 2:
return 'vector2'
elif size == 3:
return 'vector3'
elif size == 4:
return 'vector4'
elif size == 9:
return 'matrix3'
elif size == 16:
return 'matrix4'
return DATA_TYPE_MAP.get(checkType, 'none')
def getAttribType(self, attribClass, name):
"""
Get attribute type.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
Returns:
attribute type(str).
"""
if not self.hasAttribute(attribClass, name):
raise AttributeError("the attribute does't exist!")
return self._attributeMap[attribClass][name]['type']
def getAttribDefaultValue(self, attribClass, name):
"""
Get attribute default value
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
Returns:
default attribute value.
"""
if not self.hasAttribute(attribClass, name):
raise AttributeError("the attribute does't exist!")
return self._attributeMap[attribClass][name]['default_value']
def getAttribIsArray(self, attribClass, name):
"""
Get whether attribute is array.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
Returns:
bool.
"""
if not self.hasAttribute(attribClass, name):
raise AttributeError("the attribute does't exist!")
return self._attributeMap[attribClass][name]['is_array']
def getAttribInfo(self, attribClass, name):
"""
Get attribute info.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
Returns:
dict {'default_value': defaultValue, 'type': attribType, is_array': array_mode}.
"""
return self._attributeMap[attribClass][name]
def setAttribInfo(self, attribClass, name, info):
"""
Set attribute info.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
info(dict): {'default_value': defaultValue, 'type': attribType, is_array': array_mode}.
"""
self._attributeMap[attribClass][name] = info
def createAttribute(self, attribClass, name, attribType=None, defaultValue=None, applyValue=True):
"""
Create a new attribute.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
attribType(str): type of the attribute value->[float, int, vector2, vector3, vector4, matrix3, matrix4 , bool, list, tuple, custom].
defaultValue(any): default value of the attribute.
applyValue(bool): apply the default value.
"""
if attribType is None:
attribType = self._getAttribType(attribClass, name)
if defaultValue is None:
defaultValue = DEFAULT_VALUE_MAP.get(attribType, None)
array_mode = DATA_IS_ARRAY_MAP.get(attribType, False)
shape = DATA_SHAPE_MAP.get(attribType, None)
if attribType == 'list':
shape = [0, len(defaultValue)]
if attribClass == "vertex":
if name == 'pos':
return
if array_mode:
self._mesh.vertex_property_array(name)
else:
self._mesh.vertex_property(name)
if applyValue:
data = np.broadcast_to(defaultValue, get_shape(self.getNumVertexes(), shape))
if array_mode:
self._mesh.set_vertex_property_array(name, data)
else:
self._mesh.set_vertex_property(name, list(data))
elif attribClass == "face":
if array_mode:
self._mesh.face_property_array(name)
else:
self._mesh.face_property(name)
if applyValue:
data = np.broadcast_to(defaultValue, get_shape(self.getNumFaces(), shape))
if array_mode:
self._mesh.set_face_property_array(name, data)
else:
self._mesh.set_face_property(name, list(data))
elif attribClass == "edge":
if array_mode:
self._mesh.edge_property_array(name)
else:
self._mesh.edge_property(name)
if applyValue:
data = np.broadcast_to(defaultValue, get_shape(self.getNumEdges(), shape))
if array_mode:
self._mesh.set_edge_property_array(name, data)
else:
self._mesh.set_edge_property(name, list(data))
elif attribClass == "detail":
array_mode = False
else:
raise AttributeError("please input attribute class in ['vertex', 'edge', 'face', 'detail']")
self._attributeMap[attribClass][name] = {'default_value': defaultValue, 'type': attribType,
'is_array': array_mode}
def removeAttribute(self, attribClass, name):
"""
Remove a attribute.
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
"""
if attribClass == "vertex":
if name == 'pos':
return
if self._mesh.has_vertex_property(name):
self._mesh.remove_vertex_property(name)
self._attributeMap["vertex"].pop(name)
elif attribClass == "face":
if self._mesh.has_face_property(name):
self._mesh.remove_face_property(name)
self._attributeMap["face"].pop(name)
elif attribClass == "edge":
if self._mesh.has_edge_property(name):
self._mesh.remove_edge_property(name)
self._attributeMap["edge"].pop(name)
elif attribClass == "detail":
if name in self._attributeMap["detail"].keys():
self._attributeMap["detail"].pop(name)
def renameAttribute(self, attribClass, name, new_name):
"""
Rename a attribute
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail']
names(str): specific attribute name
new_names(str): new attribute name
"""
self.copyAttribute(attribClass, name, new_name, True)
def copyAttribute(self, attribClass, from_name, to_name, remove=False):
"""
Copy attribute data to a new attribute.
Args:
attribClass: one of ['vertex', 'edge', 'face', 'detail'].
from_name: specific attribute name.
to_name: new attribute name.
remove: remove the from attribute.
"""
if not self.hasAttribute(attribClass, from_name):
raise AttributeError("attribute {} of {} not exist".format(from_name, attribClass))
if from_name == to_name:
return
attrib_type = self.getAttribType(attribClass, from_name)
default_value = self.getAttribDefaultValue(attribClass, from_name)
if attribClass == "vertex":
a = self.getVertexAttribData(from_name)
self.setVertexAttribData(to_name, a, attrib_type, default_value)
elif attribClass == "face":
a = self.getFaceAttribData(from_name)
self.setFaceAttribData(to_name, a, attrib_type, default_value)
elif attribClass == "edge":
a = self.getEdgeAttribData(from_name)
self.setEdgeAttribData(to_name, a, attrib_type, default_value)
elif attribClass == "detail":
self.createAttribute("detail", to_name, attrib_type, default_value)
if remove:
self.removeAttribute(attribClass, from_name)
def hasAttribute(self, attribClass, name):
"""
Returns whether the mesh contains a specific attribute
Args:
attribClass(str): one of ['vertex', 'edge', 'face', 'detail'].
name(str): specific attribute name.
Returns:
bool.
"""
if attribClass in self._attributeMap.keys():
if name in self._attributeMap[attribClass].keys():
return True
return False
def addVertex(self, pos):
"""
Add a vertex to the mesh.
Args:
pos(list/tuple/np.ndarray): position of the new vertex, type can be: [list,ndarray,tuple].
Returns:
openmesh.VertexHandle.
"""
if type(pos) is list:
return self._mesh.add_vertex(np.array(pos))
elif type(pos) is np.ndarray:
return self._mesh.add_vertex(pos)
elif type(pos) is tuple:
return self._mesh.add_vertex(np.array([pos[0], pos[1], pos[2]]))
def addFace(self, vts):
"""
Add a face to the mesh.
Args:
vts(list): vertices of the new face, type can be: list of [openmesh.VertexHandle, int]
Returns:
openmesh.FaceHandle
"""
self._GLFaces = None
if type(vts[0]) is openmesh.VertexHandle:
return self._mesh.add_face(vts)
else:
return self._mesh.add_face([self._mesh.vertex_handle(i) for i in vts])
def addVertices(self, vts):
"""
Add vertices to the mesh.
Args:
vts: new vertices , np.ndarray or list, shape = (n,3).
"""
self._GLFaces = None
self._mesh.add_vertices(vts)
def addFaces(self, fcs):
"""
Add faces to the mesh.
Args:
fcs: new faces , np.ndarray or list of ndarray.
"""
self._GLFaces = None
self._mesh.add_faces(fcs)
def removeVertex(self, vt, isolate=False, clean=True):
"""
Remove a vertex from mesh.
Args:
vt(int/openmesh.VertexHandle): vertex index or vertex handle.
isolate(bool): if True, delete the connected elements.
clean(bool): if True, garbage collection after delete.
"""
if type(vt) is not openmesh.VertexHandle:
vt = self._mesh.vertex_handle(vt)
if vt.idx() < self.getNumVertexes():
self._mesh.delete_vertex(vt, isolate)
if clean:
self._mesh.garbage_collection()
self._GLFaces = None
def removeFace(self, fc, isolate=False, clean=True):
"""
Remove a face from mesh.
Args:
fc(int/openmesh.FaceHandle): face index or face handle.
isolate(bool): if True, delete the connected elements.
clean(bool): if True, garbage collection after delete.
"""
if type(fc) is not openmesh.FaceHandle:
fc = self._mesh.face_handle(fc)
if fc.idx() < self.getNumFaces():
self._mesh.delete_face(fc, isolate)
if clean:
self._mesh.garbage_collection()
self._GLFaces = None
def removeEdge(self, eg, isolate=False, clean=True):
"""
Remove an edge from mesh.
Args:
eg(int/openmesh.EdgeHandle): edge index or edge handle.
isolate(bool): if True, delete the connected elements.
clean(bool): if True, garbage collection after delete.
"""
if type(eg) is not openmesh.EdgeHandle:
eg = self._mesh.edge_handle(eg)
if eg.idx() < self.getNumEdges():
self._mesh.delete_edge(eg, isolate)
if clean:
self._mesh.garbage_collection()
self._GLFaces = None
def removeVertices(self, vts, isolate=False):
"""
Remove vertices from mesh.
@param vts: list of vertex index or list of vertex handle.
@param isolate: if True, delete the connected elements.
"""
for vt in vts:
self.removeVertex(vt, isolate, False)
self._mesh.garbage_collection()
def removeFaces(self, fcs, isolate=False):
"""
Remove faces from mesh.
Args:
fcs(list): list of face index or list of face handle.
isolate(bool): if True, delete the connected elements.
"""
for fc in fcs:
self.removeFace(fc, isolate, False)
self._mesh.garbage_collection()
def removeEdges(self, egs, isolate=False):
"""
Remove edges from mesh.
Args:
egs(list): list of edge index or list of edge handle.
isolate(bool): if True, delete the connected elements.
"""
for eg in egs:
self.removeEdge(eg, isolate, False)
self._mesh.garbage_collection()
def clear(self):
"""
Clear all mesh data.
"""
self._mesh.clear()
self._attributeMap = {}
self.signals.emit_attribChanged()
self.update()
def getVertexAttribData(self, name):
"""
Get vertex attribute data.
Args:
name(str): specific attribute name.
Returns:
vertex attribute data.
"""
if name == 'pos':
return self._mesh.points()
elif name == 'normal':
return self.getNormals()
else:
if not self.hasAttribute('vertex', name):
raise AttributeError("Attribute {} does't exist!".format(name))
if self.getAttribIsArray('vertex', name):
return self._mesh.vertex_property_array(name)
else:
return self._mesh.vertex_property(name)
def getFaceAttribData(self, name):
"""
Get face attribute data.
Args:
name(str): specific attribute name.
Returns:
face attribute data.
"""
if name == 'normal':
return self.getFaceNormals()
else:
if not self._mesh.has_face_property(name):
raise AttributeError("Attribute {} does't exist!".format(name))
if self.getAttribIsArray('face', name):
return self._mesh.face_property_array(name)
else:
return self._mesh.face_property(name)
def getEdgeAttribData(self, name):
"""
Get edge attribute data.
Args:
name(str): specific attribute name.
Returns:
edge attribute data.
"""
if not self._mesh.has_edge_property(name):
raise AttributeError("Attribute {} does't exist!".format(name))
if self.getAttribIsArray('edge', name):
return self._mesh.edge_property_array(name)
else:
return self._mesh.edge_property(name)
def setVertexAttribData(self, name, | |
#!/usr/bin/python
import sqlite3
import datetime
import ConfigParser
#import calendar
#import pprint
from operator import itemgetter
config = ConfigParser.ConfigParser()
config.read("config.txt")
DEBUG = int(config.get('main','DEBUG'))
class schedule():
def __init__(self):
self.holding = False
self.active = False
# 0 1 2 3 4 5 6
self.days = ('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')
self.caldays = {'week' : ['Mo','Tu','We','Th','Fr','Sa','Su']}
self.months = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
self.current = ()
self.working = {}
# Schedules are activation periods for settings. The name field matches a setting name.
self.schedules = []
# Settings establish low and high temperatures for activating the AC unit. They are scheduled by schedules with a matching name.
self.settings = []
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
# Verify existence of tables
c.execute('CREATE TABLE IF NOT EXISTS settings (sename TEXT, low FLOAT, high FLOAT)')
c.execute('CREATE TABLE IF NOT EXISTS schedule (scname TEXT, startday INT, start TIMESTAMP, endday INT, end TIMESTAMP)')
c.execute('CREATE TABLE IF NOT EXISTS activation (active BOOL)')
c.execute('CREATE TABLE IF NOT EXISTS holding (hold TEXT)')
# Check for empty (new) settings table
c.execute("SELECT COUNT(sename) FROM settings")
row = c.fetchone()[0]
if row == 0:
c.execute('INSERT INTO settings VALUES(?,?,?)', ('Away', 65.0,77.0))
c.execute('INSERT INTO settings VALUES(?,?,?)', ('Home', 67.0,74.0))
c.execute('INSERT INTO settings VALUES(?,?,?)', ('Night', 66.0,75.0))
c.execute('INSERT INTO settings VALUES(?,?,?)', ('Weekend',66.0,75.0))
scconn.commit()
# Check for empty (new) schedule table
c.execute("SELECT COUNT(scname) FROM schedule")
row = c.fetchone()[0]
if row == 0:
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Away', 0,'06:30:00',0,'17:00:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Away', 1,'06:30:00',1,'17:00:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Away', 2,'06:30:00',2,'17:00:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Away', 3,'06:30:00',3,'17:00:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Away', 4,'06:30:00',4,'17:00:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Home', 0,'17:00:00',0,'23:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Home', 1,'17:00:00',1,'23:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Home', 2,'17:00:00',2,'23:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Home', 3,'17:00:00',3,'23:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Home', 4,'17:00:00',4,'23:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Night', 6,'23:30:00',0,'04:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Night', 0,'23:30:00',1,'04:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Night', 1,'23:30:00',2,'04:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Night', 2,'23:30:00',3,'04:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Night', 3,'23:30:00',4,'04:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Night', 4,'23:30:00',5,'04:30:00'))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Weekend',5,'04:30:00',-1,''))
c.execute('INSERT INTO schedule VALUES(?,?,?,?,?)', ('Weekend',-1,'',6,'23:30:00'))
scconn.commit()
scconn.close()
#self.read_schedule()
#self.set_current()
def read_schedule(self):
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
d = scconn.cursor()
self.schedules = []
self.settings = []
# Populate schedule as combination of schedule and settings
for row in c.execute('SELECT schedule.scname,schedule.startday,schedule.start,schedule.endday,schedule.end,settings.low,settings.high FROM schedule INNER JOIN settings ON settings.sename = schedule.scname'):
self.schedules.extend({row})
# Populate settings alone
for row in d.execute('SELECT sename,low,high FROM settings'):
self.settings.extend({row})
for row in c.execute('SELECT active FROM activation'):
self.active = row[0]
# print self.settings
# print self.schedules
scconn.close()
self.clean_schedule()
self.check_hold()
# Merge days for schedules crossing over midnight
# For example, a schedule starts Friday 6pm and ends Sunday 3am. The database will have two lines.
# This function merges those into one schedule line
def clean_schedule(self):
found = bool()
out = []
for pschedule in self.schedules:
for schedule in self.schedules:
found = False
if schedule[0] == pschedule[0] and schedule[1] == -1 and pschedule[3] == -1 and schedule != pschedule:
temp = (schedule[0], pschedule[1], pschedule[2], schedule[3], schedule[4], schedule[5], schedule[6])
out.extend({temp})
found = True
if found == False and pschedule[1] != -1 and pschedule[3] != -1:
out.extend({pschedule})
self.schedules = out
def check_hold(self):
hold = ''
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
for row in c.execute('SELECT hold FROM holding'):
hold = row[0]
if hold:
self.hold(hold)
else:
self.holding = False
scconn.close()
def nohold(self):
self.holding = False
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
c.execute('DELETE FROM holding');
scconn.commit()
scconn.close()
self.set_current()
if DEBUG > 0:
print "schedule.nohold: Schedule override removed."
def hold(self,name):
# Set and hold a schedule setting (override schedule)
#(u'Away', 2, u'06:30:00', 1, u'17:00:00', 65.0, 77.0)
now = datetime.datetime.now()
today = now.weekday()
res = filter(lambda t: t[0] == name, self.settings)
#print res[0]
newres = [(res[0][0], today, '0:00:00', today, '23:59:59', res[0][1], res[0][2])]
self.current = newres
self.holding = True
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
c.execute('DELETE FROM holding');
scconn.commit()
c.execute('INSERT INTO holding(hold) VALUES (?)', (name,))
scconn.commit()
scconn.close()
if DEBUG > 0:
print "schedule.hold: Override schedule and set: " + name
print res
def del_setting(self,name):
if DEBUG > 0:
print "schedule.del_setting: Deleting: " + name
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
c.execute("DELETE FROM settings WHERE sename=?", (name,))
c.execute("DELETE FROM schedule WHERE scname=?", (name,))
scconn.commit()
scconn.close()
self.read_schedule()
return True
def save_setting(self,setting,new):
if setting[0] and setting[1] and setting[2]:
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
if new == True:
c.execute("INSERT INTO settings (sename,low,high) VALUES (?,?,?)", (setting[0],float(setting[1]),float(setting[2])))
else:
c.execute("UPDATE settings SET low=?,high=? WHERE sename=?", (float(setting[1]),float(setting[2]),setting[0]))
scconn.commit()
scconn.close()
self.read_schedule()
return True
else:
print "schedule.savesetting: bad data!"
return False
def save_schedule(self,setting,new,start,end):
if DEBUG > 0:
print "schedule.save_schedule:"
print setting
print start
print end
if setting[0] and setting[1] and setting[2]:
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
if new == True:
if DEBUG > 0:
print "schedule.save_schedule: INSERT INTO settings (sename,low,high) VALUES (?,?,?)", (setting[0],float(setting[1]),float(setting[2]))
c.execute("INSERT INTO settings (sename,low,high) VALUES (?,?,?)", (setting[0],float(setting[1]),float(setting[2])))
else:
if DEBUG > 0:
print "schedule.save_schedule: UPDATE settings SET low=?,high=? WHERE sename=?", (float(setting[1]),float(setting[2]),setting[0])
c.execute("UPDATE settings SET low=?,high=? WHERE sename=?", (float(setting[1]),float(setting[2]),setting[0]))
scconn.commit()
c.execute("DELETE FROM schedule WHERE scname='" + setting[0] + "'")
scconn.commit()
# For each day 0-6 (until 7)
for i in range(0,7):
startday = i
endday = i
print "schedule.save_schedule: Checking schedule " + setting[0] + " for " + self.days[i]
if start[i] == '' and end[i] == '':
if DEBUG > 0:
print "schedule.save_schedule: Start and end times cancelled. No new data to insert."
continue
elif start[i] == 'X' and end[i] == 'X':
if DEBUG > 0:
print "schedule.save_schedule: Start and end times cancelled. No new data to insert."
continue
elif start[i] == 'X' or start[i] == '':
startday = -1
start[i] = ''
if len(end[i]) < 8:
end[i] = end[i] + ':00'
elif end[i] == 'X' or end[i] == '':
endday = -1
end[i] = ''
if len(start[i]) < 8:
start[i] = start[i] + ':00'
else:
if len(start[i]) < 8:
start[i] = start[i] + ':00'
if len(end[i]) < 8:
end[i] = end[i] + ':00'
if DEBUG > 0:
print "schedule.save_schedule: start[i] and end[i] present..." + start[i] + ", " + end[i]
c.execute('INSERT INTO schedule VALUES (?,?,?,?,?)', (setting[0], startday, start[i], endday, end[i]))
scconn.commit()
scconn.close()
self.read_schedule()
return True
else:
print "schedule.save_schedule: bad data!"
return False
def get_one(self,name):
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
for row in c.execute("SELECT scname,startday,start,endday,end FROM schedule WHERE scname='" + name + "'"):
startday = row[1]
start = row[2]
endday = row[3]
end = row[4]
scconn.close()
return (name,startday,start,endday,end)
def get_one_day(self,name,day):
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
for row in c.execute("SELECT scname,startday,start,endday,end FROM schedule WHERE scname='" + name + "' AND (startday=? OR endday=?)",(day,day,)):
startday = row[1]
start = row[2]
endday = row[3]
end = row[4]
scconn.close()
return (name,startday,start,endday,end)
return ()
def print_schedule(self):
for schedule in self.schedules:
setting = schedule
name = itemgetter(0)(schedule)
startday = self.days[itemgetter(1)(schedule)]
start = itemgetter(2)(schedule)
endday = self.days[itemgetter(3)(schedule)]
end = itemgetter(4)(schedule)
low = str(itemgetter(5)(schedule))
high = str(itemgetter(6)(schedule))
print name + ": starts " + startday + " at " + start + " and ends " + endday + " at " + end + " with min/max temp of " + low + "/" + high + "."
def set_schedule(self):
if working:
c.execute("INSERT OR REPLACE INTO schedule (name,startday,start,endday,end,low,high) VALUES (?,?,?,?,?,?,?)", working)
def check_schedule(self):
self.set_current()
if self.current:
if DEBUG > 0:
if self.active == True:
print "schedule.check_schedule: Schedule currently active!"
else:
print "schedule.check_schedule: Schedule currently inactive!"
print schedule
def save_active(self):
if DEBUG > 0:
print "schedule.save_active(" + str(self.active) + ")"
scconn = sqlite3.connect("schedule.db")
c = scconn.cursor()
c.execute('DELETE FROM activation');
scconn.commit()
c.execute('INSERT INTO activation (active) VALUES (?)', (self.active,))
scconn.commit()
scconn.close()
def set_active(self):
if DEBUG > 0:
print "schedule.set_active: Setting schedule to active."
self.active = True
self.save_active()
def set_inactive(self):
if DEBUG > 0:
print "schedule.set_inactive: Setting schedule to inactive."
self.active = False
self.save_active()
def set_current(self):
if self.holding == True:
if DEBUG > 0:
print "schedule.set_current: Schedule hold set to "
print self.current
return self.current
# Set the current schedule based on the current date, time, and available schedules
now = datetime.datetime.now()
year = now.year
month = now.month
today = now.weekday()
hour = now.hour
minute = now.minute
mytimestr = str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':00'
| |
<gh_stars>0
# -*- coding: utf-8 -*-
# ==============================================================================
# SBEMimage, ver. 2.0
# Acquisition control software for serial block-face electron microscopy
# (c) 2018-2019 <NAME> Institute for Biomedical Research, Basel.
# This software is licensed under the terms of the MIT License.
# See LICENSE.txt in the project root folder.
# ==============================================================================
"""This module contains all dialog windows."""
import os
import re
import string
import threading
import datetime
import glob
import json
import validators
import requests
import shutil
from random import random
from time import sleep, time
from validate_email import validate_email
from math import atan, sqrt
from queue import Queue
from PIL import Image
from skimage.io import imread
from skimage.feature import register_translation
import numpy as np
from imreg_dft import translation
from zipfile import ZipFile
from PyQt5.uic import loadUi
from PyQt5.QtCore import Qt, QObject, QSize, pyqtSignal
from PyQt5.QtGui import QPixmap, QIcon, QPalette, QColor, QFont
from PyQt5.QtWidgets import QApplication, QDialog, QMessageBox, \
QFileDialog, QLineEdit, QDialogButtonBox
import utils
import acq_func
class Trigger(QObject):
"""Custom signal for updating GUI from within running threads."""
s = pyqtSignal()
#------------------------------------------------------------------------------
class ConfigDlg(QDialog):
"""Ask the user to select a configuration file. The previously used
configuration is preselected in the list widget. If no previously used
configuration found, use default.ini. If status.dat does not exists,
show warning message box."""
def __init__(self, VERSION):
super().__init__()
loadUi('..\\gui\\config_dlg.ui', self)
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.label_version.setText('Version ' + VERSION)
self.labelIcon.setPixmap(QPixmap('..\\img\\logo.png'))
self.label_website.setText('<a href="https://github.com/SBEMimage">'
'https://github.com/SBEMimage</a>')
self.label_website.setOpenExternalLinks(True)
self.setFixedSize(self.size())
self.show()
self.abort = False
# Populate the list widget with existing .ini files
inifile_list = []
for file in os.listdir('..\\cfg'):
if file.endswith('.ini'):
inifile_list.append(file)
self.listWidget_filelist.addItems(inifile_list)
# Which .ini file was used previously? Check in status.dat
if os.path.isfile('..\\cfg\\status.dat'):
status_file = open('..\\cfg\\status.dat', 'r')
last_inifile = status_file.readline()
status_file.close()
try:
last_item_used = self.listWidget_filelist.findItems(
last_inifile, Qt.MatchExactly)[0]
self.listWidget_filelist.setCurrentItem(last_item_used)
except:
# If the file indicated in status.dat does not exist,
# select default.ini.
# This dialog is called from SBEMimage.py only if default.ini
# is found in cfg directory.
default_item = self.listWidget_filelist.findItems(
'default.ini', Qt.MatchExactly)[0]
self.listWidget_filelist.setCurrentItem(default_item)
else:
# If status.dat does not exists, the program crashed or a second
# instance is running. Display a warning and select default.ini
default_item = self.listWidget_filelist.findItems(
'default.ini', Qt.MatchExactly)[0]
self.listWidget_filelist.setCurrentItem(default_item)
QMessageBox.warning(
self, 'Problem detected: Crash or other SBEMimage instance '
'running',
'WARNING: SBEMimage appears to have crashed during the '
'previous run, or there is already another instance of '
'SBEMimage running. Please either close the other instance '
'or abort this one.\n\n'
'If you are restarting a stack after a crash, doublecheck '
'all settings before restarting!',
QMessageBox.Ok)
def reject(self):
self.abort = True
super().reject()
def get_ini_file(self):
if not self.abort:
return self.listWidget_filelist.currentItem().text()
else:
return 'abort'
#------------------------------------------------------------------------------
class SaveConfigDlg(QDialog):
"""Save current configuration in a new config file."""
def __init__(self):
super().__init__()
loadUi('..\\gui\\save_config_dlg.ui', self)
self.setWindowModality(Qt.ApplicationModal)
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.setFixedSize(self.size())
self.show()
self.lineEdit_cfgFileName.setText('')
self.file_name = None
def get_file_name(self):
return self.file_name
def accept(self):
# Replace spaces in file name with underscores.
without_spaces = self.lineEdit_cfgFileName.text().replace(' ', '_')
self.lineEdit_cfgFileName.setText(without_spaces)
# Check whether characters in name are permitted.
# Use may not overwrite "default.ini"
reg = re.compile('^[a-zA-Z0-9_-]+$')
if (reg.match(self.lineEdit_cfgFileName.text())
and self.lineEdit_cfgFileName.text().lower != 'default'):
self.file_name = self.lineEdit_cfgFileName.text() + '.ini'
super().accept()
else:
QMessageBox.warning(
self, 'Error',
'Name contains forbidden characters.',
QMessageBox.Ok)
#------------------------------------------------------------------------------
class SEMSettingsDlg(QDialog):
"""Let user change SEM beam settings (target EHT, taget beam current).
Display current working distance and stigmation.
"""
def __init__(self, sem):
super().__init__()
self.sem = sem
loadUi('..\\gui\\sem_settings_dlg.ui', self)
self.setWindowModality(Qt.ApplicationModal)
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.setFixedSize(self.size())
self.show()
# Display current target settings:
self.doubleSpinBox_EHT.setValue(self.sem.get_eht())
self.spinBox_beamCurrent.setValue(self.sem.get_beam_current())
# Display current focus/stig:
self.lineEdit_currentFocus.setText(
'{0:.6f}'.format(sem.get_wd() * 1000))
self.lineEdit_currentStigX.setText('{0:.6f}'.format(sem.get_stig_x()))
self.lineEdit_currentStigY.setText('{0:.6f}'.format(sem.get_stig_y()))
def accept(self):
self.sem.set_eht(self.doubleSpinBox_EHT.value())
self.sem.set_beam_current(self.spinBox_beamCurrent.value())
super().accept()
#------------------------------------------------------------------------------
class MicrotomeSettingsDlg(QDialog):
"""Adjust stage motor limits and wait interval after stage moves."""
def __init__(self, microtome, sem, microtome_active=True):
super().__init__()
self.microtome = microtome
self.sem = sem
self.microtom_active = microtome_active
loadUi('..\\gui\\microtome_settings_dlg.ui', self)
self.setWindowModality(Qt.ApplicationModal)
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.setFixedSize(self.size())
self.show()
# If microtome not active, change selection label:
if microtome_active:
self.label_selectedStage.setText('Microtome stage active.')
# Display settings that can only be changed in DM:
self.lineEdit_knifeCutSpeed.setText(
str(self.microtome.get_knife_cut_speed()))
self.lineEdit_knifeRetractSpeed.setText(
str(self.microtome.get_knife_retract_speed()))
self.checkBox_useOscillation.setChecked(
self.microtome.is_oscillation_enabled())
# Settings changeable in GUI:
self.doubleSpinBox_waitInterval.setValue(
self.microtome.get_stage_move_wait_interval())
current_motor_limits = self.microtome.get_motor_limits()
current_calibration = self.microtome.get_stage_calibration()
speed_x, speed_y = self.microtome.get_motor_speeds()
else:
self.label_selectedStage.setText('SEM stage active.')
# Display stage limits. Not editable for SEM.
self.spinBox_stageMaxX.setMaximum(200000)
self.spinBox_stageMaxY.setMaximum(200000)
self.spinBox_stageMinX.setMaximum(0)
self.spinBox_stageMinY.setMaximum(0)
self.spinBox_stageMinX.setEnabled(False)
self.spinBox_stageMaxX.setEnabled(False)
self.spinBox_stageMinY.setEnabled(False)
self.spinBox_stageMaxY.setEnabled(False)
current_motor_limits = self.sem.get_motor_limits()
current_calibration = self.sem.get_stage_calibration()
speed_x, speed_y = self.sem.get_motor_speeds()
self.doubleSpinBox_waitInterval.setValue(
self.sem.get_stage_move_wait_interval())
# Show current calibration:
self.spinBox_stageMinX.setValue(current_motor_limits[0])
self.spinBox_stageMaxX.setValue(current_motor_limits[1])
self.spinBox_stageMinY.setValue(current_motor_limits[2])
self.spinBox_stageMaxY.setValue(current_motor_limits[3])
# Other settings that can be changed in SBEMimage,
# but in a different dialog (CalibrationDgl):
self.lineEdit_scaleFactorX.setText(str(current_calibration[0]))
self.lineEdit_scaleFactorY.setText(str(current_calibration[1]))
self.lineEdit_rotationX.setText(str(current_calibration[2]))
self.lineEdit_rotationY.setText(str(current_calibration[3]))
# Motor speeds:
self.lineEdit_speedX.setText(str(speed_x))
self.lineEdit_speedY.setText(str(speed_y))
def accept(self):
if self.microtom_active:
self.microtome.set_stage_move_wait_interval(
self.doubleSpinBox_waitInterval.value())
self.microtome.set_motor_limits([
self.spinBox_stageMinX.value(), self.spinBox_stageMaxX.value(),
self.spinBox_stageMinY.value(), self.spinBox_stageMaxY.value()])
else:
self.sem.set_stage_move_wait_interval(
self.doubleSpinBox_waitInterval.value())
super().accept()
#------------------------------------------------------------------------------
class KatanaSettingsDlg(QDialog):
"""Adjust settings for the katana microtome."""
def __init__(self, microtome):
super().__init__()
self.microtome = microtome
loadUi('..\\gui\\katana_settings_dlg.ui', self)
self.setWindowModality(Qt.ApplicationModal)
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.setFixedSize(self.size())
self.show()
# Set up COM port selector
self.comboBox_portSelector.addItems(utils.get_serial_ports())
self.comboBox_portSelector.setCurrentIndex(0)
self.comboBox_portSelector.currentIndexChanged.connect(
self.reconnect)
self.display_connection_status()
self.display_current_settings()
def reconnect(self):
pass
def display_connection_status(self):
# Show message in dialog whether or not katana is connected.
pal = QPalette(self.label_connectionStatus.palette())
if self.microtome.connected:
# Use red colour if not connected
pal.setColor(QPalette.WindowText, QColor(Qt.black))
self.label_connectionStatus.setPalette(pal)
self.label_connectionStatus.setText('katana microtome connected.')
else:
pal.setColor(QPalette.WindowText, QColor(Qt.red))
self.label_connectionStatus.setPalette(pal)
self.label_connectionStatus.setText('katana microtome is not connected.')
def display_current_settings(self):
self.spinBox_knifeCutSpeed.setValue(
self.microtome.get_knife_cut_speed())
self.spinBox_knifeFastSpeed.setValue(
self.microtome.get_knife_fast_speed())
cut_window_start, cut_window_end = self.microtome.get_cut_window()
self.spinBox_cutWindowStart.setValue(cut_window_start)
self.spinBox_cutWindowEnd.setValue(cut_window_end)
self.checkBox_useOscillation.setChecked(
self.microtome.is_oscillation_enabled())
self.spinBox_oscAmplitude.setValue(
self.microtome.get_oscillation_amplitude())
self.spinBox_oscFrequency.setValue(
self.microtome.get_oscillation_frequency())
if not self.microtome.simulation_mode and self.microtome.connected:
self.doubleSpinBox_zPosition.setValue(self.microtome.get_stage_z())
z_range_min, z_range_max = self.microtome.get_stage_z_range()
self.doubleSpinBox_zRangeMin.setValue(z_range_min)
self.doubleSpinBox_zRangeMax.setValue(z_range_max)
# Retraction clearance is stored in nanometres, display in micrometres
self.doubleSpinBox_retractClearance.setValue(
self.microtome.get_retract_clearance() / 1000)
def accept(self):
new_cut_speed = self.spinBox_knifeCutSpeed.value()
new_fast_speed = self.spinBox_knifeFastSpeed.value()
new_cut_start = self.spinBox_cutWindowStart.value()
new_cut_end = self.spinBox_cutWindowEnd.value()
new_osc_frequency = self.spinBox_oscFrequency.value()
new_osc_amplitude = self.spinBox_oscAmplitude. value()
# retract_clearance in nanometres
new_retract_clearance = (
self.doubleSpinBox_retractClearance.value() * 1000)
# End position of cut window must be smaller than start position:
if new_cut_end < new_cut_start:
self.microtome.set_knife_cut_speed(new_cut_speed)
self.microtome.set_knife_fast_speed(new_fast_speed)
self.microtome.set_cut_window(new_cut_start, new_cut_end)
self.microtome.set_oscillation_enabled(
self.checkBox_useOscillation.isChecked())
self.microtome.set_oscillation_frequency(new_osc_frequency)
self.microtome.set_oscillation_amplitude(new_osc_amplitude)
self.microtome.set_retract_clearance(new_retract_clearance)
super().accept()
else:
QMessageBox.warning(
self, 'Invalid input',
'The start position of the cutting window must be larger '
'than the end position.',
QMessageBox.Ok)
#------------------------------------------------------------------------------
class StageCalibrationDlg(QDialog):
"""Calibrate the stage (rotation and scaling) and the motor speeds."""
def __init__(self, config, stage, sem):
super().__init__()
self.base_dir = config['acq']['base_dir']
self.stage = stage
self.sem = sem
self.current_eht = self.sem.get_eht()
self.x_shift_vector = [0, 0]
self.y_shift_vector = [0, 0]
self.finish_trigger = Trigger()
self.finish_trigger.s.connect(self.process_results)
self.update_calc_trigger = Trigger()
self.update_calc_trigger.s.connect(self.update_log)
self.calc_exception = None
self.busy = False
loadUi('..\\gui\\stage_calibration_dlg.ui', self)
self.setWindowModality(Qt.ApplicationModal)
self.setWindowIcon(QIcon('..\\img\\icon_16px.ico'))
self.setFixedSize(self.size())
self.show()
self.arrow_symbol1.setPixmap(QPixmap('..\\img\\arrow.png'))
self.arrow_symbol2.setPixmap(QPixmap('..\\img\\arrow.png'))
self.lineEdit_EHT.setText('{0:.2f}'.format(self.current_eht))
params = self.stage.get_stage_calibration()
self.doubleSpinBox_stageScaleFactorX.setValue(params[0])
self.doubleSpinBox_stageScaleFactorY.setValue(params[1])
self.doubleSpinBox_stageRotationX.setValue(params[2])
self.doubleSpinBox_stageRotationY.setValue(params[3])
speed_x, speed_y = self.stage.get_motor_speeds()
self.doubleSpinBox_motorSpeedX.setValue(speed_x)
self.doubleSpinBox_motorSpeedY.setValue(speed_y)
self.comboBox_dwellTime.addItems(map(str, self.sem.DWELL_TIME))
self.comboBox_dwellTime.setCurrentIndex(4)
self.comboBox_package.addItems(['imreg_dft', 'skimage'])
self.pushButton_startImageAcq.clicked.connect(
self.start_calibration_procedure)
if config['sys']['simulation_mode'] == 'True':
self.pushButton_startImageAcq.setEnabled(False)
self.pushButton_helpCalibration.clicked.connect(self.show_help)
self.pushButton_calcStage.clicked.connect(
self.calculate_stage_parameters_from_user_input)
self.pushButton_calcMotor.clicked.connect(
self.calculate_motor_parameters)
def calculate_motor_parameters(self):
"""Calculate the motor speeds from the duration measurements provided
by the user and let user confirm the new speeds."""
duration_x = self.doubleSpinBox_durationX.value()
duration_y = self.doubleSpinBox_durationY.value()
motor_speed_x = 1000 / duration_x
motor_speed_y = 1000 / duration_y
user_choice = QMessageBox.information(
self, 'Calculated parameters',
'Results:\nMotor speed X: ' + '{0:.2f}'.format(motor_speed_x)
+ ';\nMotor speed Y: ' + '{0:.2f}'.format(motor_speed_y)
+ '\n\nDo you want to use these values?',
QMessageBox.Ok | QMessageBox.Cancel)
if user_choice == QMessageBox.Ok:
self.doubleSpinBox_motorSpeedX.setValue(motor_speed_x)
self.doubleSpinBox_motorSpeedY.setValue(motor_speed_y)
def show_help(self):
QMessageBox.information(
self, 'Stage calibration procedure',
'If you click on "Start automatic calibration", '
'three images will be acquired and saved in the current base '
'directory: start.tif, shift_x.tif, shift_y.tif. '
'You can set the pixel size and dwell time for these images and '
'specify how far the stage should move along the X and the Y axis. '
'The X/Y moves must be small enough to allow some overlap between '
'the test images. The frame size is set automatically. '
'Make sure that structure is visible in the images, and that the '
'beam is focused.\n'
'The current stage position will be used as the starting '
'position. The recommended starting position is the centre of the '
'stage (0, 0).\n'
'Shift vectors between the acquired images will be computed using '
'a function from the selected package (imreg_dft or skimage). '
'Angles and scale factors will then be computed from these '
'shifts.\n\n'
'Alternatively, you can manually provide the pixel shifts by '
'looking at the calibration images start.tif, shift_x.tif, and '
'shift_y.tif and measuring the difference (with ImageJ, for '
'example) in the XY pixel position for some feature in the image. '
'Click on "Calculate" to calculate the calibration parameters '
'from these shifts.',
QMessageBox.Ok)
def start_calibration_procedure(self):
"""Acquire three images to be used for the stage calibration"""
# TODO: error handling!
reply = QMessageBox.information(
self, 'Start calibration procedure',
'This will acquire three images and save them in the current base '
'directory: start.tif, | |
#!/usr/bin/python
# Copyright 2018 BlueCat Networks (USA) Inc. and its affiliates
#
# 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.
#
# By: BlueCat Networks
from collections import OrderedDict
import json
import os
import re
import urllib
from ansible.module_utils.basic import AnsibleModule
import requests
requests.packages.urllib3.disable_warnings()
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'bluecat',
}
DOCUMENTATION = '''
---
module: BlueCat Ansible Module for Gateway
short_description: This is an experimental Ansible module for integrating with BlueCat Gateway
version_added: "1.0"
description:
- "Manage BlueCat Gateway and BlueCat Address Manager via REST API
options:
username:
description:
- BlueCat Address Manager API username
- The user must be at least an API user and should have permissions to access the resources on Address Manager
required: true
password:
description:
- <PASSWORD>
required: true
protocol:
description:
- HTTP or HTTPS for connecting to BlueCat Gateway
required: false
domain:
description:
- Fully qualified domain name or IP address for BlueCat Gateway
required: true
version:
description:
- Version of BlueCat Gateway REST API to use
required: true
resource:
description:
- BlueCat Address Manager resource to retrieve
required: true
action:
description:
- HTTP method to perform, GETALL is used in place of GET for retrieving a collection of resources
required: true
choices: ["GET", "PUT", "DELETE", "POST", "GETALL"]
resource_path:
description:
- Resource hierarchy path to reach the resource user wants to retrieve
required: false
json_data:
description:
- Any JSON data to be sent to the Gateway as part of the request
required: false
author:
- <NAME> (@xiax)
'''
EXAMPLES = '''
# Get zones in a zone
---
- hosts: localhost
vars_files:
- external_vars.yml
tasks:
- bluecat:
username: "{{ username }}"
password: "{{ password }}"
protocol: "{{ protocol }}"
domain: "{{ domain }}"
version: "{{ version }}"
resource: zone
action: getall
resource_path:
- zone: "{{ zone }}"
register: result
# Same as above except parent zones are specified in playbook:
---
- hosts: localhost
vars_files:
- external_vars.yml
tasks:
- bluecat:
username: "{{ username }}"
password: "{{ password }}"
protocol: "{{ protocol }}"
domain: "{{ domain }}"
version: "{{ version }}"
resource: zone
action: getall
resource_path:
- zone:
- parent_zone1
- parent_zone2
register: result
# external_vars.yml file:
username: portalUser
password: <PASSWORD>
protocol: http
domain: localhost
version: 1
'''
RETURN = '''
status_code:
description: The status code returned by the BAM for the REST API request
type: int
msg:
description: The output message that may have been generated as a result of the request
json:
description: The JSON returned by the request
'''
class Gateway(object):
def __init__(self, api_json, protocol, domain, version, username, password, mocked=False, **kwargs):
self.base_url = '{protocol}://{domain}'.format(protocol=protocol, domain=domain)
self.api_url = self.base_url + '/api/v{version}'.format(version=version)
self.username = username
self.password = password
# If the `api_json` parameter is not provided explicitly, use API to request it
if api_json:
self.json = api_json
else:
self.json = self.get_api_json()
self.session = requests.Session()
self.mocked = mocked
# List of one item dictionaries
self.resource_path = kwargs['resource_path']
self.json_data = kwargs['json_data']
self.response_key = {'PUT': 204, 'POST': 201, 'DELETE': 204}
def get_api_json(self):
""" Request JSON containing Gateway API specification.
Writes the JSON to a file named `gateway_api.json`.
:return: Dictionary representing the API specification.
"""
response = requests.get(self.api_url + '/gateway_api_json/')
with open('gateway_api.json', 'w') as api_json_file:
api_json_file.write(json.dumps(response.json()))
return response.json()['resources']
def login(self, username, password):
""" Authenticate and establish user session using provided credentials.
:param username: Username for the user being signed in as.
:param password: <PASSWORD> with the given username.
"""
self.session.post(
'{base_url}/rest_login'.format(base_url=self.base_url),
data={'username': username, 'password': password},
)
def logout(self):
""" End currently established user session. """
self.session.get('{base_url}/logout'.format(base_url=self.base_url))
def invoke(self, resource, action):
""" Request a REST action to be performed against the specified resource.
:param resource: The name of the resource that the action should be performed on.
:param action: The REST verb that needs to be performed on the resource.
:return: The result of performing the action as a Response object.
:raises: Exception: If path parameters don't match any valid paths or match multiple paths.
"""
# If the module is being tested with a request other than `get`, return a mock response
if self.mocked and action.lower() not in ['get']:
return self.generate_mocked_response(resource, action)
resource = resource.lower()
action = action.lower()
get_all = False
if action == 'getall':
get_all = True
action = 'get'
# Begin user session
self.login(self.username, self.password)
# Get API specification for resource
definition = self.json[resource][action]
# Populate query_params with any matches in kwargs
query_params = self.parse_query_params(definition)
# Populate path_params with any matches in kwargs
resources = OrderedDict()
for resource in self.resource_path:
# There should only be one item in each resource defined in resource_path
for key, value in resource.items():
resources[key] = value
# Populate processed_path_params with paths that match user provided path parameters
processed_path_params = self.parse_path_params(definition, resources)
# If more than one path matched user parameters, check which we should use based on get_all flag
if len(processed_path_params.keys()) > 1 and get_all:
for path in list(processed_path_params):
if path.strip('/').endswith('}'):
del processed_path_params[path]
elif not get_all and action != 'post':
for path in list(processed_path_params):
if not path.strip('/').endswith('}'):
del processed_path_params[path]
if len(processed_path_params.keys()) > 1:
raise Exception('Provided path parameters match multiple paths!')
# Insert user provided parameter values into path
url_path = ''
for path in processed_path_params:
try:
url_path = path.format(**processed_path_params[path])
break
except KeyError:
continue
if not url_path:
raise Exception('Provided parameters do not match any valid paths!')
# Perform action against the constructed resource path
response = self.session.request(action, self.api_url + url_path, json=query_params)
# End user session
self.logout()
return response
def generate_mocked_response(self, resource, action):
""" Create mock response object.
Used for mocking responses to actions that can modify a resource when running in Ansible's `check mode`.
:param resource: The name of the resource that the action should be performed on.
:param action: The REST verb that needs to be performed on the resource.
:return: A mocked Response object.
"""
response = requests.models.Response()
response.status_code = self.response_key[action.upper()]
response._content = {'message': 'No changes made to {resource}'.format(resource=resource)}
return response
def parse_query_params(self, definition):
""" Parse query parameters associated with the resource being accessed.
:param definition: Dictionary representing the API specification for the resource.
:return: Dictionary containing parsed query parameters and their values.
"""
query_params = {}
# Parse values from the query keeping the type of the value in mind.
for key, value in definition['query_parameters'].items():
if key in self.json_data:
if value['type'] == 'boolean' and isinstance(self.json_data[key], str):
if self.json_data[key].lower() == 'true':
query_params[key] = True
else:
query_params[key] = False
elif value['type'] == 'integer':
query_params[key] = int(self.json_data[key])
else:
query_params[key] = self.json_data[key]
return query_params
@staticmethod
def parse_path_params(definition, resources):
""" Parse path(s) from API specification that match parameters supplied by user.
:param definition: Dictionary representing the API specification for the resource.
:param resources: Dictionary containing the parameters specified by the user.
:return: Dictionary containing the matching paths and the corresponding parameters as values.
"""
processed_path_params = {}
for path, parameters in definition['path_parameters'].items():
# Make sure parameters user gave match parameters accepted by path
if set(parameters.keys()) != set(resources.keys()):
continue
processed_path_params[path] = {}
last_param_position = 0
for param, value in resources.items():
# Make sure path parameter order matches order that user specified parameters in
param_position = path.find('{' + param + '}')
if last_param_position >= param_position:
del processed_path_params[path]
break
else:
last_param_position = param_position
# If value is a list, have to split it into a recursive path
if isinstance(value, list):
search_string = r'/([^/]+)/(\{%s\})' % param
match = re.search(search_string, path)
if match:
value_string = '%s' % value[0]
for item in value[1:]:
value_string += '/{resource}/{item}'.format(resource=match.group(1), item=item)
processed_path_params[path][param] = value_string
# Escape path parameters to be safe for URLs
if param not in processed_path_params[path]:
try:
escaped_value = urllib.quote(value.encode('utf8'))
except AttributeError:
escaped_value = value
processed_path_params[path][param] = escaped_value
return processed_path_params
def run_module():
""" Entry point for the module.
Parses and prepares arguments passed in and executes the associated task.
| |
<reponame>balazsdukai/tile-processor
# -*- coding: utf-8 -*-
"""Workers run the executables. Executables can be anything, but most likely
they are compiled software that are called in a subprocess, for example
*3dfier* (threedfier). In order to implement your own Worker, implement your
class/function here and register it in the click command.
The Factory-pattern reference: `https://realpython.com/factory-method-python/
<https://realpython.com/factory-method-python/>`_
"""
import os
import logging
from locale import getpreferredencoding
from subprocess import PIPE
from typing import Sequence, List
from time import time, sleep
from psutil import Popen, STATUS_ZOMBIE, STATUS_SLEEPING
import yaml
from tile_processor.tileconfig import DbTilesAHN
log = logging.getLogger(__name__)
# TODO BD: might be worth to make a Worker parent class with the run_subprocess
# method in it. On the other hand, not every Worker might need a subprocess
# runner
class WorkerFactory:
"""Registers and instantiates an Worker.
A Worker is responsible for running an executable, e.g. 3dfier in case of
:py:class:`.ThreedfierWorker`
"""
def __init__(self):
self._executors = {}
def register_worker(self, key, worker):
"""Register a worker for use.
:param key: Name of the worker
:param worker: Can be a function, a class, or an object that implements
`.__call__()`
"""
self._executors[key] = worker
def create(self, key, **kwargs):
"""Instantiate a worker"""
worker = self._executors.get(key)
if not worker:
raise ValueError(key)
return worker(**kwargs)
class ExampleWorker:
"""Runs the template."""
def execute(self, monitor_log, monitor_interval, tile, **ignore) -> bool:
"""Execute the TemplateWorker with the provided configuration.
The worker will execute the `./src/simlate_memory_use.sh` script, which
allocates a constant amount of RAM (~600Mb) and 'holds' it for 10s.
:return: True/False on success/failure
"""
log.debug(f"Running {self.__class__.__name__}:{tile}")
package_dir = os.path.dirname(os.path.dirname(__file__))
exe = os.path.join(package_dir, "src", "simulate_memory_use.sh")
command = ["bash", exe, "5s"]
res = run_subprocess(
command,
monitor_log=monitor_log,
monitor_interval=monitor_interval,
tile_id=tile,
)
return res
class ExampleDbWorker:
"""Runs the template."""
def execute(self, monitor_log, monitor_interval, tile, **ignore) -> bool:
"""Execute the TemplateWorker with the provided configuration.
Simply print the processed tile ID into a file.
:return: True/False on success/failure
"""
log.debug(f"Running {self.__class__.__name__}:{tile}")
package_dir = os.path.dirname(os.path.dirname(__file__))
exe = os.path.join(package_dir, "src", "exampledb_processor.sh")
command = ["bash", exe, "exampledb.output", tile]
res = run_subprocess(
command,
monitor_log=monitor_log,
monitor_interval=monitor_interval,
tile_id=tile,
)
return res
class ThreedfierWorker:
"""Runs 3dfier."""
def create_yaml(self, tile, dbtilesahn, ahn_paths):
"""Create the YAML configuration for 3dfier."""
ahn_file = ""
if len(ahn_paths) > 1:
for p, v in ahn_paths:
ahn_file += "- " + p + "\n" + " "
else:
ahn_file += "- " + ahn_paths[0]
ahn_version = set([version for path, version in ahn_paths])
if dbtilesahn.conn.password:
d = "PG:dbname={dbname} host={host} port={port} user={user} password={pw} schemas={schema_tiles} tables={bag_tile}"
dsn = d.format(
dbname=dbtilesahn.conn.dbname,
host=dbtilesahn.conn.host,
port=dbtilesahn.conn.port,
user=dbtilesahn.conn.user,
pw=dbtilesahn.conn.password,
schema_tiles=dbtilesahn.feature_tiles.features.schema.string,
bag_tile=dbtilesahn.feature_views[tile],
)
else:
d = "PG:dbname={dbname} host={host} port={port} user={user} schemas={schema_tiles} tables={bag_tile}"
dsn = d.format(
dbname=dbtilesahn.conn.dbname,
host=dbtilesahn.conn.host,
port=dbtilesahn.conn.port,
user=dbtilesahn.conn.user,
schema_tiles=dbtilesahn.feature_tiles.features.schema.string,
bag_tile=dbtilesahn.feature_views[tile],
)
if ahn_version == {2}:
las_building = [1]
elif ahn_version == {3}:
las_building = [6]
elif ahn_version == {2, 3}:
las_building = [1, 6]
else:
las_building = None
uniqueid = dbtilesahn.feature_tiles.features.field.uniqueid.string
yml = yaml.load(
f"""
input_polygons:
- datasets:
- "{dsn}"
uniqueid: {uniqueid}
lifting: Building
lifting_options:
Building:
roof:
height: percentile-95
use_LAS_classes: {las_building}
ground:
height: percentile-10
use_LAS_classes: [2]
input_elevation:
- datasets:
{ahn_file}
omit_LAS_classes:
thinning: 0
options:
building_radius_vertex_elevation: 0.5
radius_vertex_elevation: 0.5
threshold_jump_edges: 0.5
""",
yaml.FullLoader,
)
return yml
def execute(
self,
tile,
tiles,
path_executable,
monitor_log,
monitor_interval,
**ignore,
) -> bool:
"""
:param tile:
:param tiles: DbTilesAHN object
:param path_executable:
:param monitor_log:
:param monitor_interval:
:param ignore:
:return:
"""
log.debug(f"Running {self.__class__.__name__}:{tile}")
if len(tiles.elevation_file_index[tile]) == 0:
log.debug(f"Elevation files are not available for tile {tile}")
return False
else:
yml = self.create_yaml(
tile=tile,
dbtilesahn=tiles,
ahn_paths=tiles.elevation_file_index[tile],
)
yml_path = str(tiles.output.dir.join_path(f"{tile}.yml"))
try:
with open(yml_path, "w") as fo:
yaml.dump(yml, fo)
except BaseException as e:
log.exception(f"Error: cannot write {yml_path}")
output_path = str(tiles.output.dir.join_path(f"{tile}.csv"))
command = [
path_executable,
yml_path,
"--stat_RMSE",
"--CSV-BUILDINGS-MULTIPLE",
output_path,
]
try:
success = run_subprocess(
command,
shell=True,
doexec=True,
monitor_log=monitor_log,
monitor_interval=monitor_interval,
tile_id=tile,
)
return success
except BaseException as e:
log.exception("Cannot run 3dfier on tile %s", tile)
return False
finally:
try:
os.remove(yml_path)
except Exception as e:
log.error(e)
class ThreedfierTINWorker:
def create_yaml(self, tile, dbtilesahn, ahn_paths, simplification_tinsimp):
"""Create the YAML configuration for 3dfier."""
ahn_file = ""
if len(ahn_paths) > 1:
for p, v in ahn_paths:
ahn_file += "- " + p + "\n" + " "
else:
ahn_file += "- " + ahn_paths[0]
if dbtilesahn.conn.password:
d = "PG:dbname={dbname} host={host} port={port} user={user} password={pw} schemas={schema_tiles} tables={bag_tile}"
dsn = d.format(
dbname=dbtilesahn.conn.dbname,
host=dbtilesahn.conn.host,
port=dbtilesahn.conn.port,
user=dbtilesahn.conn.user,
pw=dbtilesahn.conn.password,
schema_tiles=dbtilesahn.feature_tiles.features.schema.string,
bag_tile=dbtilesahn.feature_views[tile],
)
else:
d = "PG:dbname={dbname} host={host} port={port} user={user} schemas={schema_tiles} tables={bag_tile}"
dsn = d.format(
dbname=dbtilesahn.conn.dbname,
host=dbtilesahn.conn.host,
port=dbtilesahn.conn.port,
user=dbtilesahn.conn.user,
schema_tiles=dbtilesahn.feature_tiles.features.schema.string,
bag_tile=dbtilesahn.feature_views[tile],
)
uniqueid = dbtilesahn.feature_tiles.features.field.uniqueid.string
simplification_tinsimp = str(simplification_tinsimp)
yml = yaml.load(
f"""
input_polygons:
- datasets:
- "{dsn}"
uniqueid: {uniqueid}
lifting: Terrain
lifting_options:
Terrain:
simplification_tinsimp: {simplification_tinsimp}
inner_buffer: 0.1
use_LAS_classes:
- 2
input_elevation:
- datasets:
{ahn_file}
omit_LAS_classes:
thinning: 0
options:
building_radius_vertex_elevation: 0.5
radius_vertex_elevation: 0.5
threshold_jump_edges: 0.5
""",
yaml.FullLoader,
)
return yml
def execute(
self,
tile,
tiles,
simplification_tinsimp,
out_format,
out_format_ext,
path_executable,
monitor_log,
monitor_interval,
**ignore,
) -> bool:
log.debug(f"Running {self.__class__.__name__}:{tile}")
if len(tiles.elevation_file_index[tile]) == 0:
log.debug(f"Elevation files are not available for tile {tile}")
return False
else:
yml = self.create_yaml(
tile=tile,
dbtilesahn=tiles,
ahn_paths=tiles.elevation_file_index[tile],
simplification_tinsimp=simplification_tinsimp,
)
yml_path = str(tiles.output.dir.join_path(f"{tile}.yml"))
log.debug(f"{yml_path}\n{yml}")
try:
with open(yml_path, "w") as fo:
yaml.dump(yml, fo)
except BaseException as e:
log.exception(f"Error: cannot write {yml_path}")
output_path = str(
tiles.output.dir.join_path(f"{tile}.{out_format_ext}")
)
command = [path_executable, yml_path, out_format, output_path]
try:
success = run_subprocess(
command,
shell=True,
doexec=True,
monitor_log=monitor_log,
monitor_interval=monitor_interval,
tile_id=tile,
)
return success
except BaseException as e:
log.exception("Cannot run 3dfier on tile %s", tile)
return False
finally:
try:
os.remove(yml_path)
except Exception as e:
log.error(e)
class Geoflow:
def create_configuration(self, tile: str, tiles: DbTilesAHN, kwargs) -> List:
"""Create a tile-specific configuration file."""
pass
def execute(
self,
tile: str,
tiles: DbTilesAHN,
path_executable: str,
path_flowchart: str,
monitor_log: logging.Logger,
monitor_interval: int,
path_toml: str = None,
doexec: bool = True,
run_reference: str = None,
**ignore,
) -> bool:
"""Execute Geoflow.
:param path_toml:
:param tile: Tile ID to process
:param tiles: Feature tiles configuration object
:param path_executable: Absolute path to the Geoflow exe
:param path_flowchart: Absolute path to the Geoflow flowchart
:param path_toml: Absolute path to the Geoflow configuration TOML file that holds default values
:param monitor_log:
:param monitor_interval:
:param doexec:
:return: Success or Failure
"""
log.debug(f"Running {self.__class__.__name__}:{tile}")
if len(tiles.elevation_file_index[tile]) == 0:
log.debug(f"Elevation files are not available for tile {tile}")
return False
kwargs = {"run_reference": run_reference}
config = self.create_configuration(tile=tile, tiles=tiles, kwargs=kwargs)
if config is not None and len(config) > 0:
if path_toml is not None and len(path_toml) > 0:
command = [
path_executable,
path_flowchart,
"--config",
path_toml,
] + config
else:
command = [path_executable, path_flowchart] + config
try:
success = run_subprocess(
command,
shell=False,
doexec=doexec,
monitor_log=monitor_log,
monitor_interval=monitor_interval,
tile_id=tile,
)
return success
except BaseException:
log.exception(
f"Cannot run {os.path.basename(path_executable)} on tile {tile}"
)
return False
else:
return False
class BuildingReconstructionWorker(Geoflow):
def create_configuration(self, tile: str, tiles: DbTilesAHN, kwargs):
# Create the Postgres connection string
dsn_in = (
f"PG:dbname={tiles.conn.dbname} "
f"host={tiles.conn.host} "
f"port={tiles.conn.port} "
f"user={tiles.conn.user} "
f"schemas={tiles.feature_tiles.features.schema.string} "
f"tables={tiles.feature_views[tile]}"
)
if tiles.conn.password:
dsn_in += f" password={tiles.conn.password}"
# Select the las file paths for the tile
input_las_files = []
for ahn_tile in tiles.elevation_file_index[tile]:
input_las_files.extend(ahn_tile["file_list"])
# Create the output connection string
if tiles.output.db is not None:
dsn_out = tiles.output.db.dsn_no_relation()
if tiles.output.db.schema is not None:
out_layer_template = f"{tiles.output.db.schema}.{tiles.output.kwargs.get('table_prefix', '')}"
else:
out_layer_template = tiles.output.kwargs.get("table_prefix", "")
t_lod11_2d = out_layer_template + "lod11_2d"
t_lod12_2d = out_layer_template + "lod12_2d"
t_lod12_3d = out_layer_template + "lod12_3d"
t_lod13_2d = out_layer_template + "lod13_2d"
t_lod13_3d = out_layer_template + "lod13_3d"
t_lod22_2d = out_layer_template + "lod22_2d"
t_lod22_3d = out_layer_template + "lod22_3d"
t_lod12_3d_tri = out_layer_template + "lod12_3d_tri"
t_lod13_3d_tri = out_layer_template + "lod13_3d_tri"
t_lod22_3d_tri = out_layer_template + "lod22_3d_tri"
format_out = "PostgreSQL"
else:
raise ValueError(f"Invalid Output type {type(tiles.output)}")
# Put together the configuration
config = []
config.append(f"--INPUT_FOOTPRINT_SOURCE={dsn_in}")
config.append(f"--overwrite_output=false")
config.append(f"--OUTPUT_DB_CONNECTION={dsn_out}")
config.append(f"--OUTPUT_LAYERNAME_LOD11_2D={t_lod11_2d}")
config.append(f"--OUTPUT_LAYERNAME_LOD12_2D={t_lod12_2d}")
config.append(f"--OUTPUT_LAYERNAME_LOD12_3D={t_lod12_3d}")
config.append(f"--OUTPUT_LAYERNAME_LOD13_2D={t_lod13_2d}")
config.append(f"--OUTPUT_LAYERNAME_LOD13_3D={t_lod13_3d}")
config.append(f"--OUTPUT_LAYERNAME_LOD22_2D={t_lod22_2d}")
config.append(f"--OUTPUT_LAYERNAME_LOD22_3D={t_lod22_3d}")
config.append(f"--OUTPUT_LAYERNAME_LOD12_3D_tri={t_lod12_3d_tri}")
config.append(f"--OUTPUT_LAYERNAME_LOD13_3D_tri={t_lod13_3d_tri}")
config.append(f"--OUTPUT_LAYERNAME_LOD22_3D_tri={t_lod22_3d_tri}")
config.append(f"--TILE_ID={tile}")
config.append(f"--OUTPUT_FORMAT={format_out}")
if tiles.output.dir is not None and "obj" in tiles.output.dir:
config.append(f"--OUTPUT_OBJ_DIR={tiles.output.dir['obj'].path}")
if tiles.output.dir is not None and "cityjson" in tiles.output.dir:
config.append(f"--OUTPUT_CITYJSON_DIR={tiles.output.dir['cityjson'].path}")
config.append(f"--RUN_REFERENCE={kwargs['run_reference']}")
config.append(f"--INPUT_LAS_FILES=")
config.extend(input_las_files)
return config
class BuildingReconstructionAHN34CompareWorker(Geoflow):
def create_configuration(self, tile: str, tiles: DbTilesAHN, kwargs):
# Create the Postgres connection string
dsn_in = (
f"PG:dbname={tiles.conn.dbname} "
f"host={tiles.conn.host} "
f"port={tiles.conn.port} "
f"user={tiles.conn.user} "
f"schemas={tiles.feature_tiles.features.schema.string} "
f"tables={tiles.feature_views[tile]}"
)
if tiles.conn.password:
dsn_in += f" password={tiles.conn.password}"
# Select the las file paths for the tile
input_las_files_ahn3 = []
input_las_files_ahn4 = []
for ahn_tile in tiles.elevation_file_index[tile]:
if ahn_tile["version"] == 3:
input_las_files_ahn3.extend(ahn_tile["file_list"])
elif ahn_tile["version"] == 4:
input_las_files_ahn4.extend(ahn_tile["file_list"])
# Create the output connection string
if tiles.output.db is | |
all the information for a saved sample, or empty
dictionary if troubles getting the sample.
Examples
--------
>>> get_sample('sample1')
{'time_created': '2021-01-06 11:43:40.701095',
'top_left': [0, 0],
'top_right': [4.0, -1.0],
'bottom_right': [4.4, -3.5],
'bottom_left': [1.0, -3.0],
'M': 10,
'N': 10,
'coefficients': [1.1686746987951824,
-0.3855421686746996,
-9.730859023513261e-15,
-0.29216867469879476,
1.1566265060240974,
6.281563288265657e-16,
0.042168674698794054,
-0.05220883534136586],
xx:
...
yy:
...}
"""
path = path or os.path.join(self._path, sample_name + '.yml')
data = None
with open(path) as sample_file:
try:
data = yaml.safe_load(sample_file)
except yaml.YAMLError as err:
logger.error('Error when loading the samples yaml file: %s',
err)
raise err
if data is None:
logger.warning('The file is empty, no sample grid yet. '
'Please use `save_presets` to insert grids '
'in the file.')
return {}
try:
return data[str(sample_name)]
except Exception:
logger.error('The sample %s might not exist in the file.',
sample_name)
return {}
def get_sample_map_info(self, sample_name, path=None):
"""
Given a sample name, get the m and n points, as well as the coeffs.
Parameters
----------
sample_name : str
The name of the sample to get the mapped points from. To see the
available mapped samples call the `mapped_samples()` method.
path : str, optional
Path to the samples yaml file.
"""
path = path or os.path.join(self._path, sample_name + '.yml')
sample = self.get_sample_data(str(sample_name), path=path)
coeffs = []
m_points, n_points = 0, 0
if sample:
try:
coeffs = sample["coefficients"]
m_points = sample['M']
n_points = sample['N']
except Exception as ex:
logger.error('Something went wrong when getting the '
'information for sample %s. %s', sample_name, ex)
raise ex
else:
err_msg = ('This sample probably does not exist. Please call'
' mapped_samples() to see which ones are available.')
logger.error(err_msg)
raise Exception(err_msg)
return m_points, n_points, coeffs
def save_grid(self, sample_name, path=None):
"""
Save a grid file of mapped points for a sample.
This will save the date it was created, along with the sample name,
the m and n points, the coordinates for the four corners, and the
coefficients that will help get the x and y position on the grid.
If an existing name for a sample is saved again, it will override
the information for that samplefile keeping the status of the targets.
When overriding a sample, this is assuming that a re-calibration was
needed for that sample, so in case we have already shot targets from
that sample - we want to keep track of that.
Parameters
----------
sample_name : str
A name to identify the sample grid, should be snake_case style.
path : str, optional
Path to the sample folder where this sample will be saved.
Defaults to the path defined when creating this object.
Examples
--------
>>> save_grid('sample_1')
"""
path = path or self._path
entry = os.path.join(path, sample_name + '.yml')
now = str(datetime.now())
top_left, top_right, bottom_right, bottom_left = [], [], [], []
if self.get_presets():
top_left, top_right, bottom_right, bottom_left = self.get_presets()
xx, yy = self.positions_x, self.positions_y
flat_xx, flat_yy = [], []
if xx and yy:
flat_xx = [float(x) for x in xx]
flat_yy = [float(y) for y in yy]
# add False to each target to indicate they
# have not been shot yet
flat_xx = [{"pos": x, "status": False} for x in flat_xx]
flat_yy = [{"pos": y, "status": False} for y in flat_yy]
m_points, n_points = self.m_n_points
coefficients = self.coefficients
data = {sample_name: {"time_created": now,
"top_left": list(top_left),
"top_right": list(top_right),
"bottom_right": list(bottom_right),
"bottom_left": list(bottom_left),
"M": m_points, # number of rows
"N": n_points, # number of columns
"coefficients": coefficients,
"xx": flat_xx,
"yy": flat_yy}}
try:
jsonschema.validate(data[sample_name], self.sample_schema)
except jsonschema.exceptions.ValidationError as err:
logger.warning('Invalid input: %s', err)
raise err
# entry = os.path.join(path, sample_name + '.yml')
# if this is an existing file, overrite the info but keep the statuses
if os.path.isfile(entry):
with open(entry) as sample_file:
yaml_dict = yaml.safe_load(sample_file)
sample = yaml_dict[sample_name]
# when overriding the same sample, this is assuming that a
# re-calibration was done - so keep the previous statuses.
temp_xx = sample['xx']
temp_yy = sample['yy']
temp_x_status = [i['status'] for i in temp_xx]
temp_y_status = [i['status'] for i in temp_yy]
# update the current data statuses with previous ones
for xd, status in zip(data[sample_name]['xx'], temp_x_status):
xd.update((k, status)
for k, v in xd.items() if k == 'status')
for yd, status in zip(data[sample_name]['yy'], temp_y_status):
yd.update((k, status)
for k, v in yd.items() if k == 'status')
yaml_dict.update(data)
with open(entry, 'w') as sample_file:
yaml.safe_dump(data, sample_file,
sort_keys=False, default_flow_style=False)
else:
# create a new file
with open(entry, 'w') as sample_file:
yaml.safe_dump(data, sample_file,
sort_keys=False, default_flow_style=False)
def reset_statuses(self, sample_name, path=None):
"""
Reset the statuses to `False` for the sample targets.
Parameters
----------
sample_name : str
A name to identify the sample grid, should be snake_case style.
path : str, optional
Path to the `.yml` file. Defaults to the path defined when
creating this object.
"""
path = path or os.path.join(self._path, sample_name + '.yml')
with open(path) as sample_file:
yaml_dict = yaml.safe_load(sample_file) or {}
sample = yaml_dict.get(sample_name)
if sample:
for xd in sample.get('xx'):
xd.update((k, False)
for k, v in xd.items() if k == 'status')
for yd in sample.get('yy'):
yd.update((k, False)
for k, v in yd.items() if k == 'status')
yaml_dict[sample_name].update(sample)
else:
raise ValueError('Could not find this sample name in the file:'
f' {sample}')
with open(path, 'w') as sample_file:
yaml.safe_dump(yaml_dict, sample_file,
sort_keys=False, default_flow_style=False)
def map_points(self, snake_like=True, top_left=None, top_right=None,
bottom_right=None, bottom_left=None, m_rows=None,
n_columns=None):
"""
Map the points of a quadrilateral.
Given the 4 corners coordinates of a grid, and the numbers of rows and
columns, map all the sample positions in 2-d coordinates.
Parameters
----------
snake_like : bool
Indicates if the points should be saved in a snake_like pattern.
top_left : tuple, optional
(x, y) coordinates of the top left corner
top_right : tuple, optional
(x, y) coordinates of the top right corner
bottom_right : tuple, optional
(x, y) coordinates of the bottom right corner
bottom_left : tuple, optional
(x, y) coordinates of the bottom left corner
m_rows : int, optional
Number of rows the grid has.
n_columns : int, optional
Number of columns the grid has.
Returns
-------
xx, yy : tuple
Tuple of two lists with all mapped points for x and y positions in
the grid.
"""
top_left = top_left or self.get_presets()[0]
top_right = top_right or self.get_presets()[1]
bottom_right = bottom_right or self.get_presets()[2]
bottom_left = bottom_left or self.get_presets()[3]
if any(v is None for v in [top_left, top_right, bottom_right,
bottom_left]):
raise ValueError('Could not get presets, make sure you set presets'
' first using the `set_presets` method.')
rows = m_rows or self.m_n_points[0]
columns = n_columns or self.m_n_points[1]
a_coeffs, b_coeffs = mesh_interpolation(top_left, top_right,
bottom_right, bottom_left)
self.coefficients = a_coeffs.tolist() + b_coeffs.tolist()
x_points, y_points = [], []
xx, yy = get_unit_meshgrid(m_rows=rows, n_columns=columns)
# return x_points, y_points
for rowx, rowy in zip(xx, yy):
for x, y in zip(rowx, rowy):
i, j = convert_to_physical(a_coeffs=a_coeffs,
b_coeffs=b_coeffs,
logic_x=x, logic_y=y)
x_points.append(i)
y_points.append(j)
if snake_like:
x_points = snake_grid_list(
np.array(x_points).reshape(rows, columns))
y_points = snake_grid_list(
np.array(y_points).reshape(rows, columns))
self.positions_x = x_points
self.positions_y = y_points
return x_points, y_points
def is_target_shot(self, m, n, sample=None, path=None):
"""
Check to see if the target position at MxN is shot.
Parameters
----------
sample_name : str, optional
The name of the sample to get the mapped points from. To see the
available mapped samples call the `mapped_samples()` method.
m_point : int
Represents the row value of the point we want the position for.
n_point : int
Represents the column value of the point we want the position for.
path : str, optional
Sample path.
Returns
-------
is_shot : bool
Indicates is target is shot or not.
"""
sample = sample or self.current_sample
path = path or self.current_sample_path
x, y = self.compute_mapped_point(m_row=m,
n_column=n,
sample_name=sample, path=path)
data = self.get_sample_data(sample)
xx = data.get('xx')
x_status = None
# one value should be enough
# TODO: this is assuming that none of the points will be the unique.
if xx is not None:
x_status = next((item['status']
for item in xx if item['pos'] == x), None)
return x_status
def compute_mapped_point(self, m_row, n_column, sample_name=None,
path=None, compute_all=False):
"""
For a given sample, compute the x, y position for M | |
if verbose:
print("Updated output matrix shapes:")
for _om in self.output_mtrx:
print(_om.shape)
print("Updated output names:")
print(self.output_names)
# Check dimensions of all output matrices defined
self.check_outputs()
def PrintSystemMatrices(self,printShapes=True,printValues=False):
"""
Function is used to print system matrices to text window
***
Useful for documentation and debugging
"""
print("**** PrintSystemMatrices() : `{0}` ****\n".format(self.name))
# Print names of all systems and sub-systems
names_list = [x.name for x in self.DynSys_list]
print("Systems list:")
print(names_list)
print("")
# Loop through all systems and subsystems
for x in self.DynSys_list:
print("---- System matrices for `{0}` ----\n".format(x.name))
# Print general system matrices
attr_list = ["_M_mtrx", "_C_mtrx", "_K_mtrx"]
for attr in attr_list:
if hasattr(x,attr):
val = getattr(x,attr)
print("{0} matrix:".format(attr))
print(type(val))
if printShapes: print(val.shape)
if printValues: print(val)
print("")
# Print constraints matrices
print("---- Constraint matrices for `{0}` ----\n".format(x.name))
if not x._J_dict:
print("(No constraints matrices defined)\n")
else:
for key, val in x._J_dict.items():
print("key: {0}".format(key))
print(type(val))
if printShapes: print(val.shape)
if printValues: print(val)
print("")
def GetSystemMatrices(self,
unconstrained:bool=False,
createNewSystem:bool=False):
"""
Function is used to retrieve system matrices, which are not usually to
be accessed directly, except by member functions
***
Optional:
* `unconstrained`, boolean, if True system matrices applicable to
the _unconstrained problem_ are returned. Note: only applicable to
systems with constraint equations. Default value = False.
Refer documentation for `transform_to_unconstrained()` for details.
* `createNewSystem`, boolean, if True a new `DynSys()` class instance
is initialised, using the system matrices of the full system.
Default value = False.
***
Returns:
Matrices (and other results) are returned as a dictionary
"""
# Create empty dictionay
d = {}
# Get list of systems
DynSys_list = self.DynSys_list
# Determine properties of overall system
isLinear = all([x.isLinear for x in DynSys_list])
isSparse = all([x.isSparse for x in DynSys_list])
# Retrieve system matrices from all listed systems
nDOF_list = []
M_list = []
C_list = []
K_list = []
J_key_list = []
for x in DynSys_list:
nDOF_list.append(x.nDOF)
M_list.append(x._M_mtrx.tolist())
C_list.append(x._C_mtrx.tolist())
K_list.append(x._K_mtrx.tolist())
# Compile list of all J keys
J_key_list += list(x._J_dict.keys())
J_key_list = list(set(J_key_list)) # remove duplicates
# Assemble system matrices for full system
# i.e. including all appended systems
nDOF_new = sum(nDOF_list)
M_mtrx = block_diag(*tuple(M_list))
C_mtrx = block_diag(*tuple(C_list))
K_mtrx = block_diag(*tuple(K_list))
# Assemble constraints matrix for full system
J_dict = {}
for key in J_key_list:
J_list = []
m=0 # denotes number of constraint equations
for x in DynSys_list:
if key in list(x._J_dict.keys()):
J_mtrx = x._J_dict[key]
m = J_mtrx.shape[0]
if x.isSparse:
J_mtrx = sparse.csc_matrix(J_mtrx)
J_list.append(J_mtrx)
else:
J_list.append(npy.asmatrix(npy.zeros((m,x.nDOF))))
# Assemble rows of full matrix
full_J_mtrx = npy.hstack(tuple(J_list))
J_dict[key] =full_J_mtrx
# Assemble full constraints matrix
if J_dict:
J_mtrx = npy.vstack(list(J_dict.values()))
else:
J_mtrx = npy.zeros((0,nDOF_new))
# Check shapes of new matrices
self._CheckSystemMatrices(nDOF=nDOF_new,
M_mtrx=M_mtrx,
C_mtrx=C_mtrx,
K_mtrx=K_mtrx,
J_dict=J_dict)
self.CheckConstraints(J=J_mtrx,verbose=False)
# Project system matrices onto null space of constraints matrix
# to transform to unconstrained problem
if unconstrained and self.hasConstraints():
mdict = transform_to_unconstrained(J=J_mtrx,M=M_mtrx,
C=C_mtrx,K=K_mtrx)
M_mtrx = mdict["M"]
C_mtrx = mdict["C"]
K_mtrx = mdict["K"]
Z_mtrx = mdict["Null_J"]
# Populate dictionary
d["nDOF"] = nDOF_new
d["M_mtrx"]=M_mtrx
d["C_mtrx"]=C_mtrx
d["K_mtrx"]=K_mtrx
d["J_dict"]=J_dict
d["J_mtrx"]=J_mtrx
d["isLinear"]=isLinear
d["isSparse"]=isSparse
if unconstrained and self.hasConstraints():
d["Null_J"]=Z_mtrx
# Create new system object, given system matrices
if createNewSystem:
DynSys_full = DynSys(M=M_mtrx,
C=C_mtrx,
K=K_mtrx,
J_dict=J_dict,
isLinear=isLinear,
isSparse=isSparse,
name=[x.name for x in self.DynSys_list],
showMsgs=False)
d["DynSys_full"]=DynSys_full
# Return dictionary
return d
def AddConstraintEqns(self,Jnew,Jkey,checkConstraints=True):
"""
Function is used to append a constraint equation
***
Constraint equations are assumed to take the following form:
$$ J\ddot{y} = 0 $$
***
Required:
* `Jnew`, _matrix_ of dimensions _[m,n]_ where:
* _m_ denotes the number of constraint equations
* _n_ denotes the number of DOFS of the system
* `Jkey`, key used to denote Jnew within dict
***
**Important note**: `Jnew` must be *full rank*, i.e. must itself have
independent constraints. In addition `Jnew` must be independent of any
constraints previously defined.
`CheckConstraints()` should be used to test whether constraint
equations are independent
"""
# Convert Jnew to appropriate representation
if not self.isSparse:
Jnew = npy.asmatrix(Jnew)
else:
Jnew = sparse.csc_matrix(Jnew)
# Check dimensions
if Jnew.shape[1]!=self.nDOF:
raise ValueError("Error: constraint eqn dimensions inconsistent!")
# Store constraint equation as new dict item
self._J_dict[Jkey]=Jnew
# Check constraints matrix is valid
if checkConstraints:
self.CheckConstraints()
def CalcStateMatrix(self,
M=None,
C=None,
K=None,
nDOF=None,
unconstrained=False,
saveAsAttr:bool=True):
"""
Assembles the continous-time state matrix `A_mtrx` used in state-space
methods
***
The continuous-time state matrix is as follows:
$$ A = [[0,I],[-M^{-1}K,-M^{-1}C]] $$
where **M** is the system mass matrix, **C** is the system damping
matrix, **K** is the system stiffness matrix and **I** is an
identity matrix.
***
Optional:
_Unless optional arguments are specified, system matrices stored as
class attributes will be used._
* `M`, mass matrix
* `C`, damping matrix
* `K`, stiffness matrix
* `unconstrained`, _boolean_; if True load matrix for the
_unconstrained problem_ will be returned. Only applicable if
constraint equations are defined. Refer documentation of
`transform_to_unconstrained()` method for further details
* `saveAsAttr`: if `True` state matrix returned will also be saved as
an object instance attribute
"""
# Retrieve system matrices
d = self.GetSystemMatrices(unconstrained=unconstrained)
# Handle optional arguments
if M is None: M = d["M_mtrx"]
if C is None: C = d["C_mtrx"]
if K is None: K = d["K_mtrx"]
if nDOF is None: nDOF = d["nDOF"]
# Check shape of system matrices
self._CheckSystemMatrices(M_mtrx=M,
C_mtrx=C,
K_mtrx=K,
checkConstraints=False,
nDOF=M.shape[0])
# Assemble state matrix
A, Minv = calc_state_matrix(M=M,K=K,C=C,isSparse=self.isSparse)
# Save as attribute
if saveAsAttr:
self._A_mtrx = A
self._Minv = Minv
if unconstrained:
self._Null_J = d["Null_J"]
return A
def GetStateMatrix(self,
unconstrained=False,
recalculate=True):
"""
Helper function to obtain state matrix, if already calculated
and held as attribute. Otherwise state matrix will be recalculated
***
Optional:
* `unconstrained`, _boolean_; if True load matrix for the
_unconstrained problem_ will be returned. Only applicable if
constraint equations are defined.
* `recalculate`, _boolean_; if True load matrix will always be
re-evaluated upon function call. Otherwise if load matrix has already
been evaluated for system (and is held as attribute) then it will
not be re-evaluated.
"""
attr = "_A_mtrx"
if recalculate or not hasattr(self,attr):
return self.CalcStateMatrix(unconstrained=unconstrained)
else:
return getattr(self,attr)
def CalcLoadMatrix(self,
M=None,
unconstrained=False,
saveAsAttr=True):
"""
Assembles the load matrix `B_mtrx` used in state-space methods
***
Load matrix **B** is given by the following:
$$ B = [[0],[M^{-1}]] $$
where **M** is the system mass matrix.
***
Optional:
_Unless optional arguments are specified, system matrices stored as
class attributes will be used._
* `M`, mass matrix
* `unconstrained`, _boolean_; if True load matrix for the
_unconstrained problem_ will be returned. Only applicable if
constraint equations are defined. Refer documentation of
`transform_to_unconstrained()` method for further details
* `saveAsAttr`: if `True` state matrix returned will also be saved as
an object instance attribute
"""
hasConstraints = self.hasConstraints()
# Retrieve system matrices
if M is None:
mdict = self.GetSystemMatrices(unconstrained=unconstrained)
M = mdict["M_mtrx"]
if hasConstraints and unconstrained:
J = mdict["J_mtrx"]
Z = mdict["Null_J"]
else:
self._CheckSystemMatrices(M_mtrx=M)
# Convert to unconstrained problem, if applicable
if unconstrained and hasConstraints:
Minv = npy.linalg.inv(M)
Minv = Minv @ Z.T
B, Minv = calc_load_matrix(M=None,Minv=Minv,isSparse=False)
else:
B, Minv = calc_load_matrix(M=M,isSparse=self.isSparse)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.