repository_name
stringlengths 7
107
| function_path
stringlengths 4
190
| function_identifier
stringlengths 1
236
| language
stringclasses 1
value | function
stringlengths 9
647k
| docstring
stringlengths 5
488k
| function_url
stringlengths 71
285
| context
stringlengths 0
2.51M
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|---|
datamllab/tods
|
tods/feature_analysis/StatisticalMeanAbsTemporalDerivative.py
|
StatisticalMeanAbsTemporalDerivativePrimitive._produce
|
python
|
def _produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> base.CallResult[Outputs]:
self.logger.info('Statistical MeanAbsTemporalDerivative Primitive called')
self._fitted = False
self._training_inputs, self._training_indices = self._get_columns_to_fit(inputs, self.hyperparams)
self._input_column_names = self._training_inputs.columns
if len(self._training_indices) > 0:
self._fitted = True
else:
if self.hyperparams['error_on_no_input']:
raise RuntimeError("No input columns were selected")
self.logger.warn("No input columns were selected")
if not self._fitted:
raise PrimitiveNotFittedError("Primitive not fitted.")
statistical_mean_abs_temporal_derivative_input = inputs
if self.hyperparams['use_semantic_types']:
statistical_mean_abs_temporal_derivative_input = inputs.iloc[:, self._training_indices]
output_columns = []
if len(self._training_indices) > 0:
statistical_mean_abs_temporal_derivative_output = self._mean_abs_temporal_derivative(statistical_mean_abs_temporal_derivative_input,self.hyperparams["window_size"])
if sparse.issparse(statistical_mean_abs_temporal_derivative_output):
statistical_mean_abs_temporal_derivative_output = statistical_mean_abs_temporal_derivative_output.toarray()
outputs = self._wrap_predictions(inputs, statistical_mean_abs_temporal_derivative_output)
output_columns = [outputs]
else:
if self.hyperparams['error_on_no_input']:
raise RuntimeError("No input columns were selected")
self.logger.warn("No input columns were selected")
outputs = base_utils.combine_columns(return_result=self.hyperparams['return_result'],
add_index_columns=self.hyperparams['add_index_columns'],
inputs=inputs, column_indices=self._training_indices,
columns_list=output_columns)
self.logger.info('Statistical MeanAbsTemporalDerivative Primitive returned')
return base.CallResult(outputs)
|
Args:
inputs: Container DataFrame
timeout: Default
iterations: Default
Returns:
Container DataFrame containing mean_abs_temporal_derivative of time series
|
https://github.com/datamllab/tods/blob/f77825bc6ee865db18e3930ce93de672969282d7/tods/feature_analysis/StatisticalMeanAbsTemporalDerivative.py#L114-L170
|
import os
from typing import Any,Optional,List
import statsmodels.api as sm
import numpy as np
from d3m import container, utils as d3m_utils
from d3m import utils
from numpy import ndarray
from collections import OrderedDict
from scipy import sparse
import os
import uuid
import numpy
import typing
import time
from d3m import container
from d3m.primitive_interfaces import base, transformer
from d3m.container import DataFrame as d3m_dataframe
from d3m.metadata import hyperparams, params, base as metadata_base
from d3m.base import utils as base_utils
from d3m.exceptions import PrimitiveNotFittedError
from ..common.TODSBasePrimitives import TODSTransformerPrimitiveBase
__all__ = ('StatisticalMeanAbsTemporalDerivativePrimitive',)
Inputs = container.DataFrame
Outputs = container.DataFrame
class Params(params.Params):
use_column_names: Optional[Any]
class Hyperparams(hyperparams.Hyperparams):
window_size = hyperparams.Hyperparameter(default=-1, semantic_types=[
'https://metadata.datadrivendiscovery.org/types/TuningParameter',
], description="Window Size for decomposition")
use_columns = hyperparams.Set(
elements=hyperparams.Hyperparameter[int](-1),
default=(),
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
description="A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.",
)
exclude_columns = hyperparams.Set(
elements=hyperparams.Hyperparameter[int](-1),
default=(),
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
description="A set of column indices to not operate on. Applicable only if \"use_columns\" is not provided.",
)
return_result = hyperparams.Enumeration(
values=['append', 'replace', 'new'],
default='append',
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
description="Should parsed columns be appended, should they replace original columns, or should only parsed columns be returned? This hyperparam is ignored if use_semantic_types is set to false.",
)
use_semantic_types = hyperparams.UniformBool(
default=False,
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
description="Controls whether semantic_types metadata will be used for filtering columns in input dataframe. Setting this to false makes the code ignore return_result and will produce only the output dataframe"
)
add_index_columns = hyperparams.UniformBool(
default=False,
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
description="Also include primary index columns if input data has them. Applicable only if \"return_result\" is set to \"new\".",
)
error_on_no_input = hyperparams.UniformBool(
default=True,
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
description="Throw an exception if no input column is selected/provided. Defaults to true to behave like sklearn. To prevent pipelines from breaking set this to False.",
)
return_semantic_type = hyperparams.Enumeration[str](
values=['https://metadata.datadrivendiscovery.org/types/Attribute',
'https://metadata.datadrivendiscovery.org/types/ConstructedAttribute'],
default='https://metadata.datadrivendiscovery.org/types/Attribute',
description='Decides what semantic type to attach to generated attributes',
semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter']
)
class StatisticalMeanAbsTemporalDerivativePrimitive(TODSTransformerPrimitiveBase[Inputs, Outputs, Hyperparams]):
metadata = metadata_base.PrimitiveMetadata({
"__author__": "DATA Lab @ Texas A&M University",
'name': 'Time Series Decompostional',
'python_path': 'd3m.primitives.tods.feature_analysis.statistical_mean_abs_temporal_derivative',
'keywords': ['Time Series','MeanAbsTemporalDerivative'],
'source': {
'name': 'DATA Lab @ Texas A&M University',
'contact': 'mailto:khlai037@tamu.edu'
},
'version': '0.1.0',
"hyperparams_to_tune": ['window_size'],
'algorithm_types': [
metadata_base.PrimitiveAlgorithmType.TODS_PRIMITIVE,
],
'primitive_family': metadata_base.PrimitiveFamily.FEATURE_CONSTRUCTION,
'id': str(uuid.uuid3(uuid.NAMESPACE_DNS, 'StatisticalMeanAbsTemporalDerivativePrimitive')),
})
|
Apache License 2.0
|
secondmind-labs/gpflux
|
gpflux/helpers.py
|
construct_basic_kernel
|
python
|
def construct_basic_kernel(
kernels: Union[gpflow.kernels.Kernel, List[gpflow.kernels.Kernel]],
output_dim: Optional[int] = None,
share_hyperparams: bool = False,
) -> gpflow.kernels.MultioutputKernel:
if isinstance(kernels, list):
mo_kern = SeparateIndependent(kernels)
elif not share_hyperparams:
copies = [deepcopy(kernels) for _ in range(output_dim)]
mo_kern = SeparateIndependent(copies)
else:
mo_kern = SharedIndependent(kernels, output_dim)
return mo_kern
|
r"""
Construct a :class:`~gpflow.kernels.MultioutputKernel` to use
in :class:`GPLayer`\ s.
:param kernels: A single kernel or list of :class:`~gpflow.kernels.Kernel`\ s.
- When a single kernel is passed, the same kernel is used for all
outputs. Depending on ``share_hyperparams``, the hyperparameters will be
shared across outputs. You must also specify ``output_dim``.
- When a list of kernels is passed, each kernel in the list is used on a separate
output dimension and a :class:`gpflow.kernels.SeparateIndependent` is returned.
:param output_dim: The number of outputs. This is equal to the number of latent GPs
in the :class:`GPLayer`. When only a single kernel is specified for ``kernels``,
you must also specify ``output_dim``. When a list of kernels is specified for ``kernels``,
we assume that ``len(kernels) == output_dim``, and ``output_dim`` is not required.
:param share_hyperparams: If `True`, use the type of kernel and the same hyperparameters
(variance and lengthscales) for the different outputs. Otherwise, the
same type of kernel (Squared-Exponential, Matern12, and so on) is used for
the different outputs, but the kernel can have different hyperparameter values for each.
|
https://github.com/secondmind-labs/gpflux/blob/e05d7ba86aa3739a34dc6615de8f9ff810642605/gpflux/helpers.py#L42-L73
|
import inspect
import warnings
from dataclasses import fields
from typing import List, Optional, Type, TypeVar, Union
import numpy as np
import gpflow
from gpflow import default_float
from gpflow.inducing_variables import (
InducingPoints,
SeparateIndependentInducingVariables,
SharedIndependentInducingVariables,
)
from gpflow.kernels import SeparateIndependent, SharedIndependent
from gpflow.utilities import deepcopy
from gpflux.layers.gp_layer import GPLayer
|
Apache License 2.0
|
mozilla/make.mozilla.org
|
vendor-local/lib/python/requests/models.py
|
Request.send
|
python
|
def send(self, anyway=False, prefetch=False):
url = self.full_url
if self.config.get('verbose'):
self.config.get('verbose').write('%s %s %s\n' % (
datetime.now().isoformat(), self.method, url
))
body = None
content_type = None
if self.files:
if not isinstance(self.data, str):
try:
fields = self.data.copy()
except AttributeError:
fields = dict(self.data)
for (k, v) in list(self.files.items()):
if isinstance(v, (tuple, list)):
fn, fp = v
else:
fn = guess_filename(v) or k
fp = v
fields.update({k: (fn, fp.read())})
(body, content_type) = encode_multipart_formdata(fields)
else:
pass
else:
if self.data:
body = self._enc_data
if isinstance(self.data, str):
content_type = None
else:
content_type = 'application/x-www-form-urlencoded'
if (content_type) and (not 'content-type' in self.headers):
self.headers['Content-Type'] = content_type
if not self.auth and self.config.get('trust_env'):
self.auth = get_netrc_auth(url)
if self.auth:
if isinstance(self.auth, tuple) and len(self.auth) == 2:
self.auth = HTTPBasicAuth(*self.auth)
r = self.auth(self)
self.__dict__.update(r.__dict__)
_p = urlparse(url)
proxy = self.proxies.get(_p.scheme)
if proxy:
conn = poolmanager.proxy_from_url(proxy)
_proxy = urlparse(proxy)
if '@' in _proxy.netloc:
auth, url = _proxy.netloc.split('@', 1)
self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))
r = self.proxy_auth(self)
self.__dict__.update(r.__dict__)
else:
if self.config.get('keep_alive'):
conn = self._poolmanager.connection_from_url(url)
else:
conn = connectionpool.connection_from_url(url)
if url.startswith('https') and self.verify:
cert_loc = None
if self.verify is not True:
cert_loc = self.verify
if not cert_loc and self.config.get('trust_env'):
cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')
if not cert_loc and self.config.get('trust_env'):
cert_loc = os.environ.get('CURL_CA_BUNDLE')
if not cert_loc:
cert_loc = __import__('certifi').where()
conn.cert_reqs = 'CERT_REQUIRED'
conn.ca_certs = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.ca_certs = None
if self.cert and self.verify:
if len(self.cert) == 2:
conn.cert_file = self.cert[0]
conn.key_file = self.cert[1]
else:
conn.cert_file = self.cert
if not self.sent or anyway:
if self.cookies:
if 'cookie' not in self.headers:
c = SimpleCookie()
for (k, v) in list(self.cookies.items()):
c[k] = v
cookie_header = c.output(header='', sep='; ').strip()
self.headers['Cookie'] = cookie_header
r = dispatch_hook('pre_request', self.hooks, self)
self.__dict__.update(r.__dict__)
try:
try:
r = conn.urlopen(
method=self.method,
url=self.path_url,
body=body,
headers=self.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.config.get('max_retries', 0),
timeout=self.timeout,
)
self.sent = True
except MaxRetryError as e:
raise ConnectionError(e)
except (_SSLError, _HTTPError) as e:
if self.verify and isinstance(e, _SSLError):
raise SSLError(e)
raise Timeout('Request timed out.')
except RequestException as e:
if self.config.get('safe_mode', False):
r = HTTPResponse()
r.error = e
else:
raise
self._build_response(r)
self.response = dispatch_hook('response', self.hooks, self.response)
r = dispatch_hook('post_request', self.hooks, self)
self.__dict__.update(r.__dict__)
if prefetch:
self.response.content
if self.config.get('danger_mode'):
self.response.raise_for_status()
return self.sent
|
Sends the request. Returns True of successful, False if not.
If there was an HTTPError during transmission,
self.response.status_code will contain the HTTPError code.
Once a request is successfully sent, `sent` will equal True.
:param anyway: If True, request will be sent, even if it has
already been sent.
|
https://github.com/mozilla/make.mozilla.org/blob/98b87c517b463a5bae09f29284b1dabca97bb376/vendor-local/lib/python/requests/models.py#L412-L614
|
import os
from datetime import datetime
from .hooks import dispatch_hook, HOOKS
from .structures import CaseInsensitiveDict
from .status_codes import codes
from .auth import HTTPBasicAuth, HTTPProxyAuth
from .packages.urllib3.response import HTTPResponse
from .packages.urllib3.exceptions import MaxRetryError
from .packages.urllib3.exceptions import SSLError as _SSLError
from .packages.urllib3.exceptions import HTTPError as _HTTPError
from .packages.urllib3 import connectionpool, poolmanager
from .packages.urllib3.filepost import encode_multipart_formdata
from .defaults import SCHEMAS
from .exceptions import (
ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,
URLRequired, SSLError, MissingSchema, InvalidSchema)
from .utils import (
get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,
dict_from_string, stream_decode_response_unicode, get_netrc_auth)
from .compat import (
urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,
SimpleCookie, is_py2)
try:
import chardet
except ImportError:
pass
REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)
class Request(object):
def __init__(self,
url=None,
headers=dict(),
files=None,
method=None,
data=dict(),
params=dict(),
auth=None,
cookies=None,
timeout=None,
redirect=False,
allow_redirects=False,
proxies=None,
hooks=None,
config=None,
_poolmanager=None,
verify=None,
session=None,
cert=None):
self.config = dict(config or [])
self.timeout = timeout
self.url = url
self.headers = dict(headers or [])
self.files = files
self.method = method
self.data = None
self.params = None
self.redirect = redirect
self.allow_redirects = allow_redirects
self.proxies = dict(proxies or [])
if not self.proxies and self.config.get('trust_env'):
if 'HTTP_PROXY' in os.environ:
self.proxies['http'] = os.environ['HTTP_PROXY']
if 'HTTPS_PROXY' in os.environ:
self.proxies['https'] = os.environ['HTTPS_PROXY']
self.data, self._enc_data = self._encode_params(data)
self.params, self._enc_params = self._encode_params(params)
self.response = Response()
self.auth = auth
self.cookies = dict(cookies or [])
self.sent = False
self.hooks = {}
for event in HOOKS:
self.hooks[event] = []
hooks = hooks or {}
for (k, v) in list(hooks.items()):
self.register_hook(event=k, hook=v)
self.session = session
self.verify = verify
self.cert = cert
if headers:
headers = CaseInsensitiveDict(self.headers)
else:
headers = CaseInsensitiveDict()
for (k, v) in list(self.config.get('base_headers', {}).items()):
if k not in headers:
headers[k] = v
self.headers = headers
self._poolmanager = _poolmanager
def __repr__(self):
return '<Request [%s]>' % (self.method)
def _build_response(self, resp):
def build(resp):
response = Response()
response.config = self.config
if resp:
response.status_code = getattr(resp, 'status', None)
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))
response.encoding = get_encoding_from_headers(response.headers)
cookies = self.cookies or dict()
if 'set-cookie' in response.headers:
cookie_header = response.headers['set-cookie']
cookies = dict_from_string(cookie_header)
response.cookies = cookies
response.error = getattr(resp, 'error', None)
response.raw = resp
if isinstance(self.full_url, bytes):
response.url = self.full_url.decode('utf-8')
else:
response.url = self.full_url
return response
history = []
r = build(resp)
self.cookies.update(r.cookies)
if r.status_code in REDIRECT_STATI and not self.redirect:
while (('location' in r.headers) and
((r.status_code is codes.see_other) or (self.allow_redirects))):
r.content
if not len(history) < self.config.get('max_redirects'):
raise TooManyRedirects()
r.raw.release_conn()
history.append(r)
url = r.headers['location']
data = self.data
if url.startswith('//'):
parsed_rurl = urlparse(r.url)
url = '%s:%s' % (parsed_rurl.scheme, url)
if not urlparse(url).netloc:
url = urljoin(r.url,
requote_uri(url))
if r.status_code is codes.see_other:
method = 'GET'
data = None
else:
method = self.method
if (not self.config.get('strict_mode')):
if r.status_code in (codes.moved, codes.found) and self.method == 'POST':
method = 'GET'
data = None
if (r.status_code == 303) and self.method != 'HEAD':
method = 'GET'
data = None
headers = self.headers
try:
del headers['Cookie']
except KeyError:
pass
request = Request(
url=url,
headers=headers,
files=self.files,
method=method,
params=self.session.params,
auth=self.auth,
cookies=self.cookies,
redirect=True,
data=data,
config=self.config,
timeout=self.timeout,
_poolmanager=self._poolmanager,
proxies=self.proxies,
verify=self.verify,
session=self.session,
cert=self.cert
)
request.send()
r = request.response
self.cookies.update(r.cookies)
r.history = history
self.response = r
self.response.request = self
self.response.cookies.update(self.cookies)
@staticmethod
def _encode_params(data):
if isinstance(data, bytes):
return data, data
if hasattr(data, '__iter__') and not isinstance(data, str):
data = dict(data)
if hasattr(data, 'items'):
result = []
for k, vs in list(data.items()):
for v in isinstance(vs, list) and vs or [vs]:
result.append((k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
return result, urlencode(result, doseq=True)
else:
return data, data
@property
def full_url(self):
if not self.url:
raise URLRequired()
url = self.url
scheme, netloc, path, params, query, fragment = urlparse(url)
if not scheme:
raise MissingSchema("Invalid URL %r: No schema supplied" % url)
if not scheme in SCHEMAS:
raise InvalidSchema("Invalid scheme %r" % scheme)
netloc = netloc.encode('idna').decode('utf-8')
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(params, str):
params = params.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
url = (urlunparse([scheme, netloc, path, params, query, fragment]))
if self._enc_params:
if urlparse(url).query:
url = '%s&%s' % (url, self._enc_params)
else:
url = '%s?%s' % (url, self._enc_params)
if self.config.get('encode_uri', True):
url = requote_uri(url)
return url
@property
def path_url(self):
url = []
p = urlsplit(self.full_url)
if p.scheme in self.proxies:
return self.full_url
path = p.path
if not path:
path = '/'
url.append(path)
query = p.query
if query:
url.append('?')
url.append(query)
return ''.join(url)
def register_hook(self, event, hook):
return self.hooks[event].append(hook)
|
BSD 3-Clause New or Revised License
|
qiskit/qiskit-aqua
|
qiskit/chemistry/algorithms/pes_samplers/extrapolator.py
|
WindowExtrapolator.window
|
python
|
def window(self, window: int) -> None:
self._window = window
|
Set the size of the window
Args:
window: the size of the window to set.
|
https://github.com/qiskit/qiskit-aqua/blob/5ccf0e20129880e78a57f2f78c59b9a362ebb208/qiskit/chemistry/algorithms/pes_samplers/extrapolator.py#L306-L312
|
from abc import ABC, abstractmethod
from typing import Optional, List, Dict, Union, cast
import numpy as np
from sklearn import linear_model
from sklearn.decomposition import PCA, KernelPCA
from qiskit.aqua import AquaError
class Extrapolator(ABC):
@abstractmethod
def extrapolate(self, points: List[float],
param_dict: Dict[float, List[float]]) -> Dict[float, List[float]]:
raise NotImplementedError()
@staticmethod
def factory(mode: str, **kwargs) -> 'Extrapolator':
if mode == 'window':
return WindowExtrapolator(**kwargs)
elif mode == 'poly':
return PolynomialExtrapolator(**kwargs)
elif mode == 'diff_model':
return DifferentialExtrapolator(**kwargs)
elif mode == 'pca':
return PCAExtrapolator(**kwargs)
elif mode == 'l1':
return SieveExtrapolator(**kwargs)
else:
raise AquaError('No extrapolator called {}'.format(mode))
class PolynomialExtrapolator(Extrapolator):
def __init__(self, degree: int = 1) -> None:
self._degree = degree
def extrapolate(self, points: List[float], param_dict: Optional[Dict[float, List[float]]]) -> Dict[float, List[float]]:
param_arr = np.transpose(list(param_dict.values()))
data_points = list(param_dict.keys())
ret_param_arr = []
for params in param_arr:
coefficients = np.polyfit(data_points, params, deg=self._degree)
poly = np.poly1d(coefficients)
ret_param_arr += [poly(points)]
ret_param_arr = np.transpose(ret_param_arr).tolist()
ret_params = dict(zip(points, ret_param_arr))
return ret_params
class DifferentialExtrapolator(Extrapolator):
def __init__(self,
degree: int = 1,
model: Optional[Union[linear_model.LinearRegression, linear_model.Ridge,
linear_model.RidgeCV, linear_model.SGDRegressor]] = None) -> None:
self._degree = degree
self._model = model or linear_model.LinearRegression()
def extrapolate(self, points: List[float], param_dict: Optional[Dict[float, List[float]]]) -> Dict[float, List[float]]:
response = list(param_dict.values())[1:]
features = [list(param_dict.values())]
for i in range(self._degree - 1):
grad = np.gradient(features[i], axis=0)
features.append(list(grad))
features = np.concatenate(features, axis=1)
self._model.fit(features[:-1], response)
next_params = np.asarray(self._model.predict([features[-1]])[0].tolist())
ret_params = {point: next_params for point in points}
return cast(Dict[float, List[float]], ret_params)
class WindowExtrapolator(Extrapolator):
def __init__(self,
extrapolator: Union[PolynomialExtrapolator,
DifferentialExtrapolator] = None,
window: int = 2) -> None:
self._extrapolator = extrapolator
self._window = window
def extrapolate(self, points: List[float], param_dict: Optional[Dict[float, List[float]]]) -> Dict[float, List[float]]:
ret_params = {}
sorted_points = sorted(points)
reference_points = [pt for pt in sorted(param_dict.keys()) if pt < max(sorted_points)]
for bottom_index, bottom in enumerate(reference_points):
if bottom_index < len(reference_points) - 1:
top = reference_points[bottom_index + 1]
else:
top = float('inf')
extrapolation_group = [pt for pt in sorted_points if bottom < pt <= top]
window_points = [pt for pt in reference_points if pt <= bottom]
if len(window_points) > self._window:
window_points = window_points[-self._window:]
window_param_dict = {pt: param_dict[pt] for pt in window_points}
if extrapolation_group:
ret_params.update(self._extrapolator.extrapolate(extrapolation_group,
param_dict=window_param_dict))
return ret_params
@property
def extrapolator(self) -> Extrapolator:
return self._extrapolator
@extrapolator.setter
def extrapolator(self, extrapolator: Union[PolynomialExtrapolator,
DifferentialExtrapolator]) -> None:
self._extrapolator = extrapolator
@property
def window(self) -> int:
return self._window
@window.setter
|
Apache License 2.0
|
danbradham/fsfs
|
fsfs/lockfile.py
|
LockFile.release
|
python
|
def release(self):
if not self.acquired:
raise LockFileError('Can not release an unacquired lock...')
self._release_lockfile()
|
Release the lock
|
https://github.com/danbradham/fsfs/blob/7e0158b2b1db3160ff2955e6818dc7b3c0f437ed/fsfs/lockfile.py#L288-L294
|
from __future__ import absolute_import
__all__ = [
'LockFileError',
'LockFileTimeOutError',
'LockFilePump',
'LockFile',
'lockfile'
]
import atexit
import os
import time
import errno
import threading
from warnings import warn
from datetime import datetime
from timeit import default_timer
from contextlib import contextmanager
class LockFileError(Exception): pass
class LockFileTimeOutError(Exception): pass
class LockFilePump(threading.Thread):
def __init__(self):
super(LockFilePump, self).__init__()
self.daemon = True
self._shutdown = threading.Event()
self._stopped = threading.Event()
self._started = threading.Event()
atexit.register(self.stop)
@property
def started(self):
return self._started.is_set()
@property
def stopped(self):
return self._stopped.is_set()
@property
def shutdown(self):
return self._shutdown.is_set()
def stop(self):
if not self.started and not self.shutdown:
return
self._shutdown.set()
self._stopped.wait()
if self.isAlive():
self.join()
def run(self):
try:
self._started.set()
while True:
for lock in list(LockFile._acquired_locks):
if lock.locked:
try:
lock._touch()
except OSError as e:
msg = (
'PumpThread failed to update mtime of lock: \n'
'{errno}: {massge}'
).format(e.errno, e.message)
warn(msg)
if self._shutdown.wait(LockFile._pump_interval_):
break
finally:
self._stopped.set()
class LockFile(object):
_pump_ = LockFilePump()
_pump_interval_ = 1
_expiration = 2
_acquired_locks = []
def __init__(self, path):
self.path = os.path.abspath(path)
self.acquired = False
self._depth = 0
self._start_pump()
def __enter__(self):
if self._depth == 0:
self.acquire()
self._depth += 1
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self._depth == 1:
self.release()
self._depth -= 1
@contextmanager
def __call__(self, timeout=0):
try:
if self._depth == 0:
self.acquire(timeout)
self._depth += 1
yield self
finally:
if self._depth == 1:
self.release()
self._depth -= 1
@property
def locked(self):
return os.path.exists(self.path)
@property
def expired(self):
return self._time_since_modified() > self._expiration
def _start_pump(self):
if self._pump_.started:
return
self._pump_.start()
while not self._pump_.started:
time.sleep(0.01)
def _touch(self):
with open(self.path, 'a'):
os.utime(self.path, None)
def _time_since_modified(self):
return (
datetime.now() -
datetime.fromtimestamp(os.path.getmtime(self.path))
).total_seconds()
def _acquire_expired_lock(self):
self._release_lockfile()
self._try_to_acquire()
if not self.acquired:
raise LockFileError('Failed to acquire expired lock...')
def _try_to_acquire(self):
if self.acquired:
self.acquired = True
return
if self.locked:
self.acquired = False
return
self._touch()
self._acquired_locks.append(self)
self.acquired = True
def acquire(self, timeout=0):
self._try_to_acquire()
if self.acquired:
return
if self.locked and self.expired:
self._acquire_expired_lock()
return
s = default_timer()
while not self.acquired:
if timeout > 0 and default_timer() - s > timeout:
raise LockFileTimeOutError(
'Timed out while trying to acquire lock...'
)
if self.locked and self.expired:
self._acquire_expired_lock()
return
self._try_to_acquire()
time.sleep(0.05)
def _release_lockfile(self):
try:
os.remove(self.path)
except OSError as e:
if e.errno != errno.ENOENT:
raise e
finally:
if self in self._acquired_locks:
self._acquired_locks.remove(self)
self.acquired = False
|
MIT License
|
digidotcom/xbee-micropython
|
lib/eddystonebeacon/EddystoneBeacon.py
|
parse
|
python
|
def parse(frame: bytes):
if not _check_for_valid_eddystone(frame):
raise TypeError("Incoming Eddystone frame is invalid")
eddy_type = struct.unpack('>b', frame[11:12])[0]
eddy_len = struct.unpack('>b', frame[_LENGTH_INDEX:_LENGTH_INDEX + 1])[0]
if eddy_type == TYPE_URL:
eddy_frame = EddystoneURLFrame(ranging_data=0, url='http://.com')
elif eddy_type == TYPE_UID:
eddy_frame = EddystoneUIDFrame(ranging_data=0, uid=bytearray(16))
elif eddy_type == TYPE_TLM:
eddy_frame = EddystoneTLMFrame(advertisement_count=0, time_sec=0)
else:
raise TypeError("Eddystone type is not supported: {}".format(eddy_type))
eddy_frame.set_raw_payload(frame[(8 + 4):(12 + eddy_len - 4)])
if not eddy_frame.validate_payload():
raise TypeError("Eddystone Payload is invalid")
return eddy_type, eddy_frame
|
Parses a raw advertisement frame, returning a parsed Eddystone frame.
:param frame: The raw advertisement to be parsed.
:return: The type of the frame and a parsed Eddystone frame of that type:
int, (EddystoneUIDFrame or EddystoneURLFrame or EddystoneTLMFrame).
|
https://github.com/digidotcom/xbee-micropython/blob/209f94fcf2c2ecd794891ef505549d2a50af0edc/lib/eddystonebeacon/EddystoneBeacon.py#L372-L401
|
import struct
TYPE_UID = 0x00
TYPE_URL = 0x10
TYPE_TLM = 0x20
_DEFAULT_FRAME = (
b"\x02"
b"\x01"
b"\x00"
b"\x03"
b"\x03"
b"\xAA\xFE"
b"\x04"
b"\x16"
b"\xAA\xFE"
)
_FLAGS_INDEX = 2
_DEFAULT_FLAGS = 0x06
_LENGTH_INDEX = 7
def _check_for_valid_eddystone(frame, expected_len=None):
frame_len = len(frame)
parse_len = 0
while True:
parse_len += frame[parse_len] + 1
if expected_len is not None and parse_len == _LENGTH_INDEX and frame[parse_len] != expected_len:
return False
if parse_len > frame_len:
return False
elif parse_len == frame_len:
break
if (
frame[:_FLAGS_INDEX] != _DEFAULT_FRAME[:_FLAGS_INDEX] or
frame[_FLAGS_INDEX + 1:_LENGTH_INDEX] != _DEFAULT_FRAME[_FLAGS_INDEX + 1:_LENGTH_INDEX] or
frame[8:11] != _DEFAULT_FRAME[8:11]
):
return False
return True
class _EddystoneGenericFrame(object):
def __init__(self, eddystone_type, payload_len, data_flags):
self._frame = bytearray()
self._frame.extend(_DEFAULT_FRAME)
self._frame[_FLAGS_INDEX] = data_flags
self._frame.append(eddystone_type)
self._frame += bytearray(payload_len)
self._set_payload_length(payload_len)
def _set_payload_length(self, length):
self._frame[_LENGTH_INDEX] = 4 + length
def set_raw_payload(self, payload):
payload_len = len(payload)
if payload_len > 19:
raise TypeError("The payload is too large")
offset = len(_DEFAULT_FRAME)
self._frame = self._frame[:offset + 1]
self._frame.extend(payload)
self._set_payload_length(payload_len)
def get_bytes(self) -> bytes:
return bytes(self._frame)
def _validate_payload(self, expected_len=None):
return _check_for_valid_eddystone(self._frame, expected_len)
def validate_payload(self):
return self._validate_payload(None)
@property
def eddystone_type(self):
if len(self._frame) >= 13 and self._frame[11] in [TYPE_UID, TYPE_URL, TYPE_TLM]:
return self._frame[11]
else:
return None
class EddystoneURLFrame(_EddystoneGenericFrame):
_EXTENSIONS = [
".com/", ".org/", ".edu/", ".net/", ".info/", ".biz/", ".gov/",
".com", ".org", ".edu", ".net", ".info", ".biz", ".gov",
]
_SCHEMES = [
"http://www.",
"https://www.",
"http://",
"https://",
]
def __init__(self, ranging_data, url, data_flags=_DEFAULT_FLAGS):
super().__init__(eddystone_type=TYPE_URL, payload_len=3, data_flags=data_flags)
self.ranging_data = ranging_data
self.url = url
@property
def ranging_data(self) -> int:
return struct.unpack('>b', self._frame[12:13])[0]
@ranging_data.setter
def ranging_data(self, ranging_data: int):
if ranging_data < -100 or ranging_data > 20:
raise ValueError("ranging_data is out of range")
tx_power_byte = struct.pack('>b', ranging_data)
self._frame = self._frame[:12] + tx_power_byte + self._frame[13:]
def __find_scheme_id(self, input_url):
for i in range(len(self._SCHEMES)):
if input_url.startswith(self._SCHEMES[i]):
return i, len(self._SCHEMES[i])
else:
raise ValueError("The URL does not use a supported prefix scheme")
def __find_extension_id(self, input_url, pos):
for ext_id in range(len(self._EXTENSIONS)):
extension = self._EXTENSIONS[ext_id]
if input_url.startswith(extension, pos):
return ext_id
return None
@property
def url(self) -> str:
url = self._frame[13:]
if len(url) == 0:
return str()
if url[0] >= len(self._SCHEMES):
raise ValueError("Invalid URL scheme")
decoded_url = self._SCHEMES[url[0]]
extension_index_max = len(self._EXTENSIONS) - 1
for c in url[1:]:
if c <= extension_index_max:
decoded_url += self._EXTENSIONS[c]
elif 0x21 <= c < 0x7F:
decoded_url += chr(c)
else:
raise ValueError("Invalid URL")
return decoded_url
@url.setter
def url(self, input_url: str):
encoded_url = bytearray()
scheme_id, scheme_len = self.__find_scheme_id(input_url)
encoded_url.append(scheme_id)
pos = scheme_len
while pos < len(input_url):
ext_id = self.__find_extension_id(input_url, pos)
if ext_id is not None:
encoded_url += struct.pack('>b', ext_id)
pos += len(self._EXTENSIONS[ext_id])
else:
encoded_url.append(ord(input_url[pos]))
pos += 1
self._frame = self._frame[:13] + encoded_url
self._set_payload_length(len(encoded_url) + 1)
class EddystoneUIDFrame(_EddystoneGenericFrame):
def __init__(self, ranging_data, uid, data_flags=_DEFAULT_FLAGS):
super().__init__(eddystone_type=TYPE_UID, payload_len=19, data_flags=data_flags)
self.ranging_data = ranging_data
self.uid = uid
@property
def ranging_data(self) -> int:
return struct.unpack('>b', self._frame[12:13])[0]
@ranging_data.setter
def ranging_data(self, ranging_data: int):
if ranging_data < -100 or ranging_data > 20:
raise ValueError("ranging_data is out of range")
ranging_data_byte = struct.pack('>b', ranging_data)
self._frame = self._frame[:12] + ranging_data_byte + self._frame[13:]
@property
def uid(self) -> bytes:
return bytes(self._frame[13:29])
@uid.setter
def uid(self, uid: bytes):
if len(uid) != 16:
raise ValueError("The UID field is an incorrect size, expected 16 bytes")
self._frame = self._frame[:13] + uid + self._frame[29:]
def validate_payload(self):
return self._validate_payload(23)
class EddystoneTLMFrame(_EddystoneGenericFrame):
def __init__(self, advertisement_count, time_sec, beacon_temperature=-128, battery_voltage=0, data_flags=_DEFAULT_FLAGS):
super().__init__(eddystone_type=TYPE_TLM, payload_len=13, data_flags=data_flags)
self.battery_voltage = battery_voltage
self.beacon_temperature = beacon_temperature
self.advertisement_count = advertisement_count
self.time_sec = time_sec
@staticmethod
def __to_fixed88(fl):
if fl < -128 or fl > 127.9961:
raise ValueError("Out of range of representable values")
return struct.pack('>h', int(fl * (2 ** 8)))
@staticmethod
def __from_fixed88(fp):
return float(struct.unpack('>h', fp)[0] * (2 ** -8))
@property
def battery_voltage(self) -> float:
b = self._frame[13:15]
return float(struct.unpack('>H', b)[0]) / 1000
@battery_voltage.setter
def battery_voltage(self, voltage: float):
voltage = int(voltage * 1000)
if voltage & ~0xFFFF:
raise ValueError("Voltage is out of range")
voltage_bytes = struct.pack('>H', voltage)
self._frame = self._frame[:13] + voltage_bytes + self._frame[15:]
@property
def beacon_temperature(self) -> float:
return self.__from_fixed88(bytes(self._frame[15:17]))
@beacon_temperature.setter
def beacon_temperature(self, temperature: float):
temperature_bytes = self.__to_fixed88(temperature)
self._frame = self._frame[:15] + temperature_bytes + self._frame[17:]
@property
def advertisement_count(self) -> int:
return struct.unpack('>I', self._frame[17:21])[0]
@advertisement_count.setter
def advertisement_count(self, count: int):
if count >= 1 << 32:
raise ValueError("Advertisement count is out of range of representable values")
count_bytes = struct.pack('>I', count)
self._frame = self._frame[:17] + count_bytes + self._frame[21:]
@property
def time_sec(self) -> float:
return struct.unpack('>I', self._frame[21:25])[0] / 10.0
@time_sec.setter
def time_sec(self, time_sec: float):
count = int(time_sec * 10)
if count >= 1 << 32:
raise ValueError("Time stamp out of range")
count_bytes = struct.pack('>I', count)
self._frame = self._frame[:21] + count_bytes
def validate_payload(self):
return super()._validate_payload(17)
|
MIT License
|
microsoft/petridishnn
|
tensorpack/dataflow/parallel.py
|
MultiProcessPrefetchData.__init__
|
python
|
def __init__(self, ds, nr_prefetch, nr_proc):
if os.name == 'nt':
logger.warn("MultiProcessPrefetchData does support Windows. \
However, Windows requires more strict picklability on processes, which may \
lead of failure on some of the code.")
super(MultiProcessPrefetchData, self).__init__(ds)
try:
self._size = len(ds)
except NotImplementedError:
self._size = -1
self.nr_proc = nr_proc
self.nr_prefetch = nr_prefetch
if nr_proc > 1:
logger.info("[MultiProcessPrefetchData] Will fork a dataflow more than one times. "
"This assumes the datapoints are i.i.d.")
self.queue = mp.Queue(self.nr_prefetch)
self.procs = [MultiProcessPrefetchData._Worker(self.ds, self.queue, idx)
for idx in range(self.nr_proc)]
ensure_proc_terminate(self.procs)
start_proc_mask_signal(self.procs)
|
Args:
ds (DataFlow): input DataFlow.
nr_prefetch (int): size of the queue to hold prefetched datapoints.
nr_proc (int): number of processes to use.
|
https://github.com/microsoft/petridishnn/blob/78a813a74896ec880812a2806d0b091f3e30dc4f/tensorpack/dataflow/parallel.py#L172-L200
|
import atexit
import errno
import itertools
import multiprocessing as mp
import os
import sys
import uuid
import weakref
from contextlib import contextmanager
import zmq
from six.moves import queue, range
from ..utils import logger
from ..utils.concurrency import (
StoppableThread, enable_death_signal, ensure_proc_terminate, start_proc_mask_signal)
from ..utils.serialize import dumps, loads
from .base import DataFlow, DataFlowReentrantGuard, DataFlowTerminated, ProxyDataFlow
__all__ = ['PrefetchData', 'MultiProcessPrefetchData',
'PrefetchDataZMQ', 'MultiThreadPrefetchData']
def _repeat_iter(get_itr):
while True:
for x in get_itr():
yield x
def _bind_guard(sock, name):
try:
sock.bind(name)
except zmq.ZMQError:
logger.error(
"ZMQError in socket.bind('{}'). Perhaps you're \
using pipes on a non-local file system. See documentation of PrefetchDataZMQ \
for more information.".format(name))
raise
def _get_pipe_name(name):
if sys.platform.startswith('linux'):
pipename = "ipc://@{}-pipe-{}".format(name, str(uuid.uuid1())[:8])
pipedir = os.environ.get('TENSORPACK_PIPEDIR', None)
if pipedir is not None:
logger.warn("TENSORPACK_PIPEDIR is not used on Linux any more! Abstract sockets will be used.")
else:
pipedir = os.environ.get('TENSORPACK_PIPEDIR', None)
if pipedir is not None:
logger.info("ZMQ uses TENSORPACK_PIPEDIR={}".format(pipedir))
else:
pipedir = '.'
assert os.path.isdir(pipedir), pipedir
filename = '{}/{}-pipe-{}'.format(pipedir.rstrip('/'), name, str(uuid.uuid1())[:6])
assert not os.path.exists(filename), "Pipe {} exists! You may be unlucky.".format(filename)
pipename = "ipc://{}".format(filename)
return pipename
def del_weakref(x):
o = x()
if o is not None:
o.__del__()
@contextmanager
def _zmq_catch_error(name):
try:
yield
except zmq.ContextTerminated:
logger.info("[{}] Context terminated.".format(name))
raise DataFlowTerminated()
except zmq.ZMQError as e:
if e.errno == errno.ENOTSOCK:
logger.info("[{}] Socket closed.".format(name))
raise DataFlowTerminated()
else:
raise
except Exception:
raise
class _MultiProcessZMQDataFlow(DataFlow):
def __init__(self):
assert os.name != 'nt', "ZMQ IPC doesn't support windows!"
self._reset_done = False
self._procs = []
def reset_state(self):
assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!"
self._reset_done = True
atexit.register(del_weakref, weakref.ref(self))
def _start_processes(self):
start_proc_mask_signal(self._procs)
def __del__(self):
try:
if not self._reset_done:
return
if not self.context.closed:
self.socket.close(0)
self.context.destroy(0)
for x in self._procs:
x.terminate()
x.join(5)
print("{} successfully cleaned-up.".format(type(self).__name__))
except Exception:
pass
class MultiProcessPrefetchData(ProxyDataFlow):
class _Worker(mp.Process):
def __init__(self, ds, queue, idx):
super(MultiProcessPrefetchData._Worker, self).__init__()
self.ds = ds
self.queue = queue
self.idx = idx
def run(self):
enable_death_signal(_warn=self.idx == 0)
self.ds.reset_state()
while True:
for dp in self.ds:
self.queue.put(dp)
|
MIT License
|
rogerzhangzz/cag_uda
|
data/base_dataset.py
|
__adjust
|
python
|
def __adjust(img):
ow, oh = img.size
mult = 4
if ow % mult == 0 and oh % mult == 0:
return img
w = (ow - 1) // mult
w = (w + 1) * mult
h = (oh - 1) // mult
h = (h + 1) * mult
if ow != w or oh != h:
__print_size_warning(ow, oh, w, h)
return img.resize((w, h), Image.BICUBIC)
|
Modify the width and height to be multiple of 4.
Parameters:
img (PIL image) -- input image
Returns a modified image whose width and height are mulitple of 4.
the size needs to be a multiple of 4,
because going through generator network may change img size
and eventually cause size mismatch error
|
https://github.com/rogerzhangzz/cag_uda/blob/422f99e2e0a5cb26a40d4f17ee5832f81580f7f0/data/base_dataset.py#L103-L127
|
import torch.utils.data as data
from PIL import Image
import torchvision.transforms as transforms
from abc import ABC, abstractmethod
class BaseDataset(data.Dataset, ABC):
def __init__(self, cfg):
self.cfg = cfg
self.root = cfg['rootpath']
@staticmethod
def modify_commandline_options(parser, is_train):
return parser
@abstractmethod
def __len__(self):
return 0
@abstractmethod
def __getitem__(self, index):
pass
def get_transform(opt, grayscale=False, convert=True, crop=True, flip=True):
transform_list = []
if grayscale:
transform_list.append(transforms.Grayscale(1))
if opt.preprocess == 'resize_and_crop':
osize = [opt.load_size, opt.load_size]
transform_list.append(transforms.Resize(osize, Image.BICUBIC))
transform_list.append(transforms.RandomCrop(opt.crop_size))
elif opt.preprocess == 'crop' and crop:
transform_list.append(transforms.RandomCrop(opt.crop_size))
elif opt.preprocess == 'scale_width':
transform_list.append(transforms.Lambda(lambda img: __scale_width(img, opt.crop_size)))
elif opt.preprocess == 'scale_width_and_crop':
transform_list.append(transforms.Lambda(lambda img: __scale_width(img, opt.load_size)))
if crop:
transform_list.append(transforms.RandomCrop(opt.crop_size))
elif opt.preprocess == 'none':
transform_list.append(transforms.Lambda(lambda img: __adjust(img)))
else:
raise ValueError('--preprocess %s is not a valid option.' % opt.preprocess)
if not opt.no_flip and flip:
transform_list.append(transforms.RandomHorizontalFlip())
if convert:
transform_list += [transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5),
(0.5, 0.5, 0.5))]
return transforms.Compose(transform_list)
|
MIT License
|
sberbank-ai-lab/lightautoml
|
lightautoml/addons/uplift/metalearners.py
|
RLearner._fit_predict_propensity_learner
|
python
|
def _fit_predict_propensity_learner(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
propensity_roles = copy.deepcopy(roles)
target_role, target_col = _get_target_role(roles)
propensity_roles.pop(target_role)
treatment_role, treatment_col = _get_treatment_role(roles)
propensity_roles.pop(treatment_role)
propensity_roles["target"] = treatment_col
train_cp = train_data.copy()
train_cp.drop(target_col, axis=1, inplace=True)
propensity_pred = self.propensity_learner.fit_predict(train_cp, propensity_roles, verbose=verbose).data.ravel()
return propensity_pred
|
Fit propensity score
Args:
train_data: Dataset to train
roles: Roles dict with 'treatment' roles
|
https://github.com/sberbank-ai-lab/lightautoml/blob/51a4e2bd0ebffbe0817fb50434280f8e7c40fa4c/lightautoml/addons/uplift/metalearners.py#L831-L853
|
import copy
import logging
from abc import ABCMeta
from abc import abstractmethod
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import numpy as np
from pandas import DataFrame
from lightautoml.automl.base import AutoML
from lightautoml.automl.presets.tabular_presets import TabularAutoML
from lightautoml.tasks import Task
from lightautoml.utils.timer import Timer
from lightautoml.validation.np_iterators import UpliftIterator
from .utils import _get_target_role
from .utils import _get_treatment_role
from .utils import create_linear_automl
logger = logging.getLogger(__name__)
class NotTrainedError(Exception):
pass
class MetaLearner(metaclass=ABCMeta):
def __init__(
self,
base_task: Task,
timeout: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
self.base_task = base_task
self.timeout = timeout
self.cpu_limit = cpu_limit
self.gpu_ids = gpu_ids
self._is_fitted = False
self._timer = Timer()
if timeout is not None:
self._timer._timeout = timeout
def fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
self._timer.start()
self._fit(train_data, roles, verbose)
self._is_fitted = True
if self._timer.time_limit_exceeded():
logger.warning("{} is trained, but time limit exceeded.", self.__class__.__name__)
def predict(self, data: DataFrame) -> Tuple[np.ndarray, ...]:
if not self._is_fitted:
raise NotTrainedError()
return self._predict(data)
@abstractmethod
def _fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
pass
@abstractmethod
def _predict(self, data: DataFrame):
pass
def _get_default_learner(self, task: Task):
return create_linear_automl(task)
def _get_task(self, learner: AutoML) -> Task:
if isinstance(learner, TabularAutoML):
return learner.task
elif isinstance(learner, AutoML):
return learner.reader.task
else:
raise RuntimeError("Can't extract 'task' from learner")
def _check_timer(self):
if self._timer.time_limit_exceeded():
logger.warning(
"MetaLearner '%s' isn't trained, because time limit was exceeded",
self.__class__.__name__,
)
raise NotTrainedError()
class SLearner(MetaLearner):
def __init__(
self,
learner: Optional[AutoML] = None,
base_task: Optional[Task] = None,
timeout: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
if base_task is None:
if learner is not None:
base_task = self._get_task(learner)
else:
raise RuntimeError('Must specify any of learners or "base_task"')
super().__init__(base_task, timeout, cpu_limit, gpu_ids)
if learner is None:
self.learner = self._get_default_learner(base_task)
else:
self.learner = learner
self._treatment_col: str
def _fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
treatment_role, treatment_col = _get_treatment_role(roles)
self._treatment_col = treatment_col
uplift_roles = copy.deepcopy(roles)
uplift_roles.pop(treatment_role)
self.learner.fit_predict(train_data, uplift_roles, verbose=verbose)
def _predict(self, data: DataFrame) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
data_c = data.copy()
data_c[self._treatment_col] = 0
control_pred = self.learner.predict(data_c).data.ravel()
data_c[self._treatment_col] = 1
treatment_pred = self.learner.predict(data_c).data.ravel()
uplift_pred = treatment_pred - control_pred
return uplift_pred, treatment_pred, control_pred
class TLearner(MetaLearner):
def __init__(
self,
treatment_learner: Optional[AutoML] = None,
control_learner: Optional[AutoML] = None,
base_task: Optional[Task] = None,
timeout: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
assert any(
x is not None for x in [treatment_learner, control_learner, base_task]
), 'Must specify any of learners or "base_task"'
if base_task is None:
if treatment_learner is not None:
base_task = self._get_task(treatment_learner)
elif control_learner is not None:
base_task = self._get_task(control_learner)
super().__init__(base_task, timeout, cpu_limit, gpu_ids)
self.treatment_learner = (
treatment_learner if treatment_learner is not None else self._get_default_learner(self.base_task)
)
self.control_learner = (
control_learner if control_learner is not None else self._get_default_learner(self.base_task)
)
def _fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
treatment_role, treatment_col = _get_treatment_role(roles)
new_roles = copy.deepcopy(roles)
new_roles.pop(treatment_role)
control_train_data = train_data[train_data[treatment_col] == 0]
treatment_train_data = train_data[train_data[treatment_col] == 1]
control_train_data.drop(treatment_col, axis=1, inplace=True)
treatment_train_data.drop(treatment_col, axis=1, inplace=True)
self.treatment_learner.fit_predict(treatment_train_data, new_roles, verbose=verbose)
self._check_timer()
self.control_learner.fit_predict(control_train_data, new_roles, verbose=verbose)
def _predict(self, data: Any) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
treatment_pred = self.treatment_learner.predict(data).data.ravel()
control_pred = self.control_learner.predict(data).data.ravel()
uplift = treatment_pred - control_pred
return uplift, treatment_pred, control_pred
class T2Learner(MetaLearner):
def __init__(
self,
treatment_learner: Optional[AutoML] = None,
control_learner: Optional[AutoML] = None,
n_uplift_iterator_folds: int = 5,
base_task: Optional[Task] = None,
timeout: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
if base_task is None:
if treatment_learner is not None:
base_task = self._get_task(treatment_learner)
elif control_learner is not None:
base_task = self._get_task(control_learner)
else:
raise RuntimeError('Must specify any of learners or "base_task"')
super().__init__(base_task, timeout, cpu_limit, gpu_ids)
self._n_uplift_iterator_folds = n_uplift_iterator_folds
self.treatment_learner = (
treatment_learner if treatment_learner is not None else self._get_default_learner(self.base_task)
)
self.control_learner = (
control_learner if control_learner is not None else self._get_default_learner(self.base_task)
)
def _fit(self, train_data: DataFrame, roles: Dict):
treatment_role, treatment_col = _get_treatment_role(roles)
_, target_col = _get_target_role(roles)
self._treatment_col = treatment_col
new_roles = copy.deepcopy(roles)
new_roles.pop(treatment_role)
train_data_c = train_data.copy()
treatment_values = train_data_c[treatment_col].values
target_values = train_data[target_col].values
treatment_iterator = UpliftIterator(
treatment_values,
target_values,
True,
self.base_task,
self._n_uplift_iterator_folds,
)
self.treatment_learner.fit_predict(train_data_c, new_roles, cv_iter=treatment_iterator)
control_iterator = UpliftIterator(
treatment_values,
target_values,
False,
self.base_task,
self._n_uplift_iterator_folds,
)
self.control_learner.fit_predict(train_data_c, new_roles, cv_iter=control_iterator)
def _predict(self, data: DataFrame):
data_с = data.copy()
data_с[self._treatment_col] = True
treatment_pred = self.treatment_learner.predict(data_с).data.ravel()
data_с[self._treatment_col] = False
control_pred = self.control_learner.predict(data_с).data.ravel()
uplift = treatment_pred - control_pred
return uplift, treatment_pred, control_pred
class TDLearner(MetaLearner):
def __init__(
self,
treatment_learner: Optional[AutoML] = None,
control_learner: Optional[AutoML] = None,
base_task: Optional[Task] = None,
timeout: Optional[int] = None,
dependent_group: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
assert any(
x is not None for x in [treatment_learner, control_learner, base_task]
), 'Must specify any of learners or "base_task"'
if base_task is None and (treatment_learner is None or control_learner is None):
if treatment_learner is not None:
base_task = self._get_task(treatment_learner)
elif control_learner is not None:
base_task = self._get_task(control_learner)
super().__init__(base_task, timeout, cpu_limit, gpu_ids)
self.treatment_learner = (
treatment_learner if treatment_learner is not None else self._get_default_learner(self.base_task)
)
self.control_learner = (
control_learner if control_learner is not None else self._get_default_learner(self.base_task)
)
self._other_group_pred_col = "__OTHER_GROUP_PREDICTION__"
self._dependent_group: Optional[int] = dependent_group
def _fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
treatment_role, treatment_col = _get_treatment_role(roles)
self._set_dependent_group(train_data[treatment_col].mean())
new_roles = copy.deepcopy(roles)
new_roles.pop(treatment_role)
control_train_data = train_data[train_data[treatment_col] == 0]
treatment_train_data = train_data[train_data[treatment_col] == 1]
control_train_data.drop(treatment_col, axis=1, inplace=True)
treatment_train_data.drop(treatment_col, axis=1, inplace=True)
if self._dependent_group == 1:
dependent_train_data = treatment_train_data
dependent_learner = self.treatment_learner
independent_train_data = control_train_data
independent_learner = self.control_learner
else:
dependent_train_data = control_train_data
dependent_learner = self.control_learner
independent_train_data = treatment_train_data
independent_learner = self.treatment_learner
independent_learner.fit_predict(independent_train_data, new_roles)
self._check_timer()
sg_oof_pred = independent_learner.predict(dependent_train_data).data.ravel()
dependent_train_data[self._other_group_pred_col] = sg_oof_pred
self._check_timer()
dependent_learner.fit_predict(dependent_train_data, new_roles)
def _predict(self, data: Any) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
data_c = data.copy()
if self._dependent_group == 1:
dependent_learner, independent_learner = (
self.treatment_learner,
self.control_learner,
)
else:
dependent_learner, independent_learner = (
self.control_learner,
self.treatment_learner,
)
independent_pred = independent_learner.predict(data_c).data.ravel()
data_c[self._other_group_pred_col] = independent_pred
dependent_pred = dependent_learner.predict(data_c).data.ravel()
if self._dependent_group == 1:
control_pred, treatment_pred = independent_pred, dependent_pred
else:
control_pred, treatment_pred = dependent_pred, independent_pred
uplift = treatment_pred - control_pred
return uplift, treatment_pred, control_pred
def _set_dependent_group(self, treatment_rate: float):
if self._dependent_group is None:
self._dependent_group = 1 if treatment_rate > 0.5 else 0
class XLearner(MetaLearner):
def __init__(
self,
outcome_learners: Optional[Sequence[AutoML]] = None,
effect_learners: Optional[Sequence[AutoML]] = None,
propensity_learner: Optional[AutoML] = None,
base_task: Optional[Task] = None,
timeout: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
if (outcome_learners is None or len(outcome_learners) == 0) and base_task is None:
raise RuntimeError('Must specify any of learners or "base_task"')
if outcome_learners is not None and len(outcome_learners) > 0:
base_task = self._get_task(outcome_learners[0])
super().__init__(self._get_task(outcome_learners[0]))
super().__init__(base_task, timeout, cpu_limit, gpu_ids)
self.learners: Dict[str, Union[Dict[str, AutoML], AutoML]] = {
"outcome": {},
"effect": {},
}
if propensity_learner is None:
self.learners["propensity"] = self._get_default_learner(Task("binary"))
else:
self.learners["propensity"] = propensity_learner
if outcome_learners is None or len(outcome_learners) == 0:
self.learners["outcome"]["control"] = self._get_default_learner(self.base_task)
self.learners["outcome"]["treatment"] = self._get_default_learner(self.base_task)
elif len(outcome_learners) == 1:
self.learners["outcome"]["control"] = outcome_learners[0]
self.learners["outcome"]["treatment"] = copy.deepcopy(outcome_learners[0])
elif len(outcome_learners) == 2:
self.learners["outcome"]["control"] = outcome_learners[0]
self.learners["outcome"]["treatment"] = outcome_learners[1]
else:
raise RuntimeError('The number of "outcome_learners" must be 0/1/2')
if effect_learners is None or len(effect_learners) == 0:
self.learners["effect"]["control"] = self._get_default_learner(Task("reg"))
self.learners["effect"]["treatment"] = self._get_default_learner(Task("reg"))
elif len(effect_learners) == 1:
self.learners["effect"]["control"] = effect_learners[0]
self.learners["effect"]["treatment"] = copy.deepcopy(effect_learners[0])
elif len(effect_learners) == 2:
self.learners["effect"]["control"] = effect_learners[0]
self.learners["effect"]["treatment"] = effect_learners[1]
else:
raise RuntimeError('The number of "effect_learners" must be 0/1/2')
def _fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
self._fit_propensity_learner(train_data, roles, verbose)
self._fit_outcome_learners(train_data, roles, verbose)
self._fit_effect_learners(train_data, roles, verbose)
def _fit_propensity_learner(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
propensity_roles = copy.deepcopy(roles)
target_role, target_col = _get_target_role(roles)
propensity_roles.pop(target_role)
treatment_role, treatment_col = _get_treatment_role(roles)
propensity_roles.pop(treatment_role)
propensity_roles["target"] = treatment_col
train_cp = train_data.copy()
train_cp.drop(target_col, axis=1, inplace=True)
self.learners["propensity"].fit_predict(train_cp, propensity_roles, verbose=verbose)
def _fit_outcome_learners(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
treatment_role, treatment_col = _get_treatment_role(roles)
outcome_roles = copy.deepcopy(roles)
outcome_roles.pop(treatment_role)
for group_name, outcome_learner in self.learners["outcome"].items():
self._check_timer()
group = 1 if group_name == "treatment" else 0
train_data_outcome = train_data[train_data[treatment_col] == group].copy()
train_data_outcome.drop(treatment_col, axis=1, inplace=True)
outcome_learner.fit_predict(train_data_outcome, outcome_roles, verbose=verbose)
def _fit_effect_learners(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
treatment_role, treatment_col = _get_treatment_role(roles)
_, target_col = _get_target_role(roles)
effect_roles: Dict = copy.deepcopy(roles)
effect_roles.pop(treatment_role)
for group_name, effect_learner in self.learners["effect"].items():
self._check_timer()
group = 1 if group_name == "treatment" else 0
opposite_group_name = "treatment" if group_name == "control" else "control"
train_data_effect = train_data[train_data[treatment_col] == group].copy()
train_data_effect.drop(treatment_col, axis=1, inplace=True)
outcome_pred = self.learners["outcome"][opposite_group_name].predict(train_data_effect).data.ravel()
train_data_effect[target_col] = train_data_effect[target_col] - outcome_pred
if group_name == "control":
train_data_effect[target_col] *= -1
train_data_effect = train_data_effect[train_data_effect[target_col].notnull()]
effect_learner.fit_predict(train_data_effect, effect_roles, verbose=verbose)
def _predict(self, data: Any) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
outcome_control_pred = self.learners["outcome"]["control"].predict(data).data.ravel()
outcome_treatment_pred = self.learners["outcome"]["treatment"].predict(data).data.ravel()
propensity_score = self.learners["propensity"].predict(data).data.ravel()
uplift_control_pred = self.learners["effect"]["control"].predict(data).data.ravel()
uplift_treatment_pred = self.learners["effect"]["treatment"].predict(data).data.ravel()
uplift = propensity_score * uplift_treatment_pred + (1.0 - propensity_score) * uplift_control_pred
return uplift, outcome_treatment_pred, outcome_control_pred
class RLearner(MetaLearner):
_epsi = 10 ** -5
def __init__(
self,
propensity_learner: Optional[AutoML] = None,
mean_outcome_learner: Optional[AutoML] = None,
effect_learner: Optional[AutoML] = None,
base_task: Optional[Task] = Task("binary"),
timeout: Optional[int] = None,
cpu_limit: int = 4,
gpu_ids: Optional[str] = "all",
):
if propensity_learner is not None and self._get_task(propensity_learner).name != "binary":
raise RuntimeError("Task of 'propensity_learner' must be 'binary'")
if mean_outcome_learner is None and base_task is None:
raise RuntimeError("Must specify 'mean_outcome_learner' or base_task")
if effect_learner is not None and self._get_task(effect_learner).name != "reg":
raise RuntimeError("Task of effect_learner must be 'reg'")
super().__init__(base_task, timeout, cpu_limit, gpu_ids)
self.propensity_learner: AutoML
self.mean_outcome_learner: AutoML
self.effect_learner: AutoML
no_learners = (propensity_learner is None) and (mean_outcome_learner is None) and (effect_learner is None)
tabular_timeout = timeout / 3 if no_learners and timeout is not None else None
if propensity_learner is None:
self.propensity_learner = TabularAutoML(task=Task("binary"), timeout=tabular_timeout)
else:
self.propensity_learner = propensity_learner
if mean_outcome_learner is not None:
self.mean_outcome_learner = mean_outcome_learner
self.base_task = self._get_task(mean_outcome_learner)
elif base_task is not None:
self.mean_outcome_learner = TabularAutoML(task=base_task, timeout=tabular_timeout)
if effect_learner is None:
self.effect_learner = TabularAutoML(task=Task("reg"), timeout=tabular_timeout)
else:
self.effect_learner = effect_learner
def _fit(self, train_data: DataFrame, roles: Dict, verbose: int = 0):
propensity_pred = self._fit_predict_propensity_learner(train_data, roles, verbose)
self._check_timer()
mean_outcome_pred = self._fit_predict_mean_outcome_learner(train_data, roles, verbose)
self._check_timer()
self._fit_effect_learner(train_data, roles, propensity_pred, mean_outcome_pred, verbose)
def _predict(self, data: Any) -> Tuple[np.ndarray, None, None]:
return self.effect_learner.predict(data).data.ravel(), None, None
|
Apache License 2.0
|
hichamjanati/mutar
|
mutar/otfunctions.py
|
barycenterkl_img_log
|
python
|
def barycenterkl_img_log(P, M, epsilon, gamma, b=None, tol=1e-4,
max_iter=1000, xp=np, threshold=0.):
xp = get_module(M)
psum = P.sum()
P = P.reshape(xp.r_[M.shape, -1])
n_tasks = P.shape[-1]
n_features = P.size // n_tasks
frac = gamma / (gamma + epsilon)
if b is None:
b = xp.zeros_like(P)
Kb = utils.kls(b, M)
log = {'cstr': [], 'flag': 0, 'obj': []}
weights = xp.ones(n_tasks) / n_tasks
logweights = xp.log(weights)[None, None, :]
logp = xp.log(P + 1e-10)
b = xp.zeros_like(logp)
qold = P.mean(axis=-1) + 1e-10
for i in range(max_iter):
a = frac * (logp - Kb)
Ka = utils.kls(a, M.T)
kaw = logweights + Ka * (1 - frac)
logq = utils.logsumexp(kaw, axis=-1) - xp.log(weights.sum())
logq = (1 / (1 - frac)) * logq
logQ = logq[:, :, xp.newaxis]
b = frac * (logQ - Ka)
Kb = utils.kls(b, M)
q = xp.exp(logq)
if i % 10 == 0:
cstr = float((abs(q - qold)).max())
cstr /= float(max(q.max(), qold.max(), 1e-20))
qold = q.copy()
log["cstr"].append(cstr)
if cstr < tol and i > 5:
break
if i == max_iter - 1:
log['flag'] = 3
marginals = xp.exp(a + Kb).reshape(n_features, n_tasks).T
try:
marginals = marginals.get()
q = q.get()
except AttributeError:
pass
f = wklobjective_converged(n_tasks * q.sum(), 0.,
psum, epsilon, gamma)
return f, log, marginals, b, q.flatten()
|
KL OT Barycenters for 2D images.
|
https://github.com/hichamjanati/mutar/blob/b682ba951fdcb5cb18fb6eeca0de976de96d3193/mutar/otfunctions.py#L170-L220
|
import numpy as np
from . import utils
try:
import cupy as cp
get_module = cp.get_array_module
except ImportError:
def get_module(x):
return np
def wklobjective_converged(qsum, f0, plansum, epsilon, gamma):
obj = gamma * (plansum + qsum)
obj += epsilon * f0
obj += - (epsilon + 2 * gamma) * plansum
return obj
def barycenterkl_log(P, M, epsilon, gamma, b=None, tol=1e-4,
max_iter=1000, weights=None, threshold=1e-10):
xp = get_module(M)
frac = gamma / (gamma + epsilon)
n_tasks = P.shape[-1]
n_features = M.shape[-1]
psum = P.sum()
support = (P > threshold).any(axis=1)
logps = np.log(P[support] + 1e-100)
logps = xp.asarray(logps)
M = M[xp.asarray(support)]
if b is None:
Kb = utils.logsumexp(M, axis=1)
Kb = xp.tile(Kb, (n_tasks, 1)).T
else:
Kb = xp.zeros((len(M), n_tasks))
for k in range(n_tasks):
Kb[:, k] = utils.logsumexp(b[:, k][None, :] + M, axis=1)
log = {'cstr': [], 'flag': 0, 'obj': []}
if weights is None:
weights = xp.ones(n_tasks) / n_tasks
logweights = xp.log(weights)[None, :]
qold = xp.ones(n_features)[:, None]
Ka = xp.zeros((n_features, n_tasks))
for i in range(max_iter):
a = frac * (logps - Kb)
for k in range(n_tasks):
Ka[:, k] = utils.logsumexp(a[:, k][:, None] + M, axis=0)
logq = logweights + Ka * (1 - frac)
logq = utils.logsumexp(logq, axis=1)
logq = (1 / (1 - frac)) * logq
b = frac * (logq[:, None] - Ka)
for k in range(n_tasks):
Kb[:, k] = utils.logsumexp(b[:, k][None, :] + M, axis=1)
q = xp.exp(logq)
cstr = float(abs(q - qold).max())
cstr /= float(max(q.max(), qold.max(), 1.))
qold = q.copy()
log["cstr"].append(cstr)
if cstr < tol and i > 3:
break
if i == max_iter - 1:
log['flag'] = 3
try:
a = a.get()
Kb = Kb.get()
q = q.get()
logps = logps.get()
except AttributeError:
pass
marginals = np.exp(a + Kb).T
marginals[~np.isfinite(marginals)] = 1
m = np.zeros((n_tasks, n_features))
f = wklobjective_converged(n_tasks * q.sum(), 0.,
psum, epsilon, gamma)
m[:, support] = marginals
marginals = m
b[~np.isfinite(b)] = 0.
return f, log, marginals, b, q
def barycenterkl(P, M, epsilon, gamma, b=None, tol=1e-4,
max_iter=1000, weights=None, threshold=1e-10):
xp = get_module(M)
frac = gamma / (gamma + epsilon)
psum = P.sum()
n_features, n_tasks = P.shape
frac = gamma / (gamma + epsilon)
support = (P > threshold).any(axis=1)
if len(support) == 0:
support = P.any(axis=1)
P = P[support]
P = xp.asarray(P)
M = M[xp.asarray(support)]
M = xp.exp(M)
if b is None:
b = xp.ones((n_features, n_tasks))
Kb = M.dot(b)
log = {'cstr': [], 'flag': 0, 'obj': []}
if weights is None:
weights = xp.ones(n_tasks) / n_tasks
q = xp.ones(n_features)
qold = q.copy()
return_nan = False
cstr = 1.
qmax_old = 1.
qmax = 1.
for i in range(max_iter):
a = (P / Kb) ** frac
Ka = M.T.dot(a)
q = ((Ka ** (1 - frac)).dot(weights))
q = q ** (1 / (1 - frac))
Q = q[:, None]
qmax = q.max()
if i > 2:
cstr = float(abs(q - qold).max() / max(qmax_old, qmax, 1.))
qold = q.copy()
qmax_old = qmax
b_old = b.copy()
b = (Q / Ka) ** frac
if not xp.isfinite(b).all():
return_nan = True
break
Kb = M.dot(b)
log["cstr"].append(cstr)
if abs(cstr) < tol and i > 2:
break
if i == max_iter - 1:
log['flag'] = - 1
marginals = (a * Kb).T
try:
marginals = marginals.get()
q = q.get()
utils.free_gpu_memory(xp)
except AttributeError:
pass
f = wklobjective_converged(n_tasks * q.sum(), 0.,
psum, epsilon, gamma)
m = np.zeros((n_tasks, n_features))
marginals[~np.isfinite(marginals)] = 1
m[:, support] = marginals
marginals = m
if return_nan or xp.isnan(f):
f = None
b = b_old
return f, log, marginals, b, q
|
BSD 3-Clause New or Revised License
|
transceptor-technology/aiogcd
|
aiogcd/orm/filter.py
|
Filter.get_keys
|
python
|
async def get_keys(
self, gcd: GcdConnector, offset=None, limit=None) -> list:
self._set_offset(offset)
self._set_limit(limit)
return await gcd.get_keys(self)
|
Returns a list containing Gcd keys from the supplied filter.
:param gcd: GcdConnector instance.
:param offset: integer to specify how many keys to skip
:param limit: integer to specify max number of keys to return
:return: list containing Gcd key objects.
|
https://github.com/transceptor-technology/aiogcd/blob/5235b8ef272bee4a9dc6f46f515d983772e1bd3f/aiogcd/orm/filter.py#L140-L151
|
from ..connector.key import Key
from ..connector import GcdConnector
class Filter(dict):
def __init__(self, model, *filters, has_ancestor=None, key=None):
self._model = model
self._cursor = None
filters = list(filters)
if has_ancestor is not None:
assert isinstance(has_ancestor, Key), 'Keyword argument \'has_ancestor\' should be of type ' '\'Key\' but found type {!r}' .format(has_ancestor.__class__.__name__)
filters.append({
'property': {'name': '__key__'},
'value': {'keyValue': has_ancestor.get_dict()},
'op': 'HAS_ANCESTOR'})
if key is not None:
assert isinstance(key, Key), 'Keyword argument \'key\' should be of type \'Key\' ' 'but found type {!r}' .format(key.__class__.__name__)
filters.append({
'property': {'name': '__key__'},
'value': {'keyValue': key.get_dict()},
'op': 'EQUAL'})
filter_dict = {'query': {'kind': [{'name': self._model.get_kind()}]}}
if self._model.__namespace__:
filter_dict['partitionId'] = {
'namespaceId': self._model.__namespace__
}
if len(filters) == 1:
filter_dict['query']['filter'] = {
'propertyFilter': filters[0]
}
elif len(filters) > 1:
filter_dict['query']['filter'] = {
'compositeFilter': {
'op': 'AND',
'filters': [{'propertyFilter': f} for f in filters]
}
}
super().__init__(**filter_dict)
def _set_start_cursor(self, start_cursor):
if start_cursor:
if not isinstance(start_cursor, str):
raise TypeError(
'start_cursor is expected to be str, {} passed'.format(
type(start_cursor)))
self['query']['startCursor'] = start_cursor
def _set_offset(self, offset):
if offset:
if not isinstance(offset, int):
raise TypeError(
'offset is expected to be int, {} passed'.format(
type(offset)))
self['query']['offset'] = offset
def _set_limit(self, limit):
if limit:
if not isinstance(limit, int):
raise TypeError(
'limit is expected to be int, {} passed'.format(
type(limit)))
self['query']['limit'] = limit
@property
def cursor(self):
return self._cursor
def order_by(self, *order):
self['query']['order'] = [
{
'property': {'name': p[0]},
'direction': p[1]
} if isinstance(p, tuple) else {
'property': {'name': p.name},
'direction': 'DIRECTION_UNSPECIFIED'
}
for p in order
]
return self
def limit(self, limit, start_cursor=None):
self._set_limit(limit)
self._set_start_cursor(start_cursor)
return self
async def get_entity(self, gcd: GcdConnector):
entity = await gcd.get_entity(self)
return None if entity is None else self._model(entity)
async def get_entities(
self, gcd: GcdConnector, offset=None, limit=None) -> list:
self._set_offset(offset)
self._set_limit(limit)
entities, cursor = await gcd._get_entities_cursor(self)
self._cursor = cursor
return [self._model(ent) for ent in entities]
async def get_key(self, gcd: GcdConnector):
return await gcd.get_key(self)
|
MIT License
|
sissaschool/elementpath
|
elementpath/regex/patterns.py
|
translate_pattern
|
python
|
def translate_pattern(pattern: str, flags: int = 0, xsd_version: str = '1.0',
back_references: bool = True, lazy_quantifiers: bool = True,
anchors: bool = True) -> str:
def parse_character_class():
nonlocal pos
nonlocal msg
pos += 1
if pattern[pos] == '^':
pos += 1
negative = True
else:
negative = False
char_class_pos = pos
while True:
if pattern[pos] == '[':
msg = "invalid character '[' at position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
elif pattern[pos] == '\\':
if pattern[pos + 1].isdigit():
msg = "illegal back-reference in character class at position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
pos += 2
elif pattern[pos] == ']' or pattern[pos:pos + 2] == '-[':
if pos == char_class_pos:
msg = "empty character class at position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
char_class_pattern = pattern[char_class_pos:pos]
if HYPHENS_PATTERN.search(char_class_pattern) and pos - char_class_pos > 2:
msg = "invalid character range '--' at position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
if xsd_version == '1.0':
hyphen_match = INVALID_HYPHEN_PATTERN.search(char_class_pattern)
if hyphen_match is not None:
hyphen_pos = char_class_pos + hyphen_match.span()[1] - 2
msg = "unescaped character '-' at position {}: {!r}"
raise RegexError(msg.format(hyphen_pos, pattern))
char_class = CharacterClass(char_class_pattern, xsd_version)
if negative:
char_class.complement()
break
else:
pos += 1
if pattern[pos] != ']':
pos += 1
subtracted_class = parse_character_class()
pos += 1
char_class -= subtracted_class
return char_class
group_open_char = '(' if back_references else '(?:'
regex = [] if anchors else ['^%s' % group_open_char]
pos = 0
pattern_len = len(pattern)
total_groups = 0
nested_groups = 0
dot_all = flags & re.DOTALL
if back_references:
match = FORBIDDEN_ESCAPES_REF_PATTERN.search(pattern)
else:
match = FORBIDDEN_ESCAPES_NOREF_PATTERN.search(pattern)
if match:
msg = "not allowed escape sequence {!r} at position {}: {!r}"
raise RegexError(msg.format(match.group(), match.span()[0], pattern))
while pos < pattern_len:
ch = pattern[pos]
if ch == '.':
regex.append(ch if dot_all else '[^\r\n]')
elif ch in ('^', '$'):
if not anchors:
regex.append(r'\%s' % ch)
elif ch == '^':
regex.append(r'(?<!\n\Z)^' if flags & re.MULTILINE else '^')
else:
regex.append('$' if flags & re.MULTILINE else r'$(?!\n\Z)')
elif ch == '[':
try:
char_class_repr = str(parse_character_class())
except IndexError:
msg = "unterminated character class at position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
else:
if char_class_repr == '[]':
regex.append(r'[^\w\W]')
else:
regex.append(char_class_repr)
elif ch == '{':
if pos == 0:
msg = "unexpected quantifier {!r} at position {}: {!r}"
raise RegexError(msg.format(ch, pos, pattern))
match = QUANTIFIER_PATTERN.match(pattern[pos:])
if match is None:
msg = "invalid quantifier {!r} at position {}: {!r}"
raise RegexError(msg.format(ch, pos, pattern))
regex.append(match.group())
pos += len(match.group())
if not lazy_quantifiers and pos < pattern_len and pattern[pos] in ('?', '+', '*'):
msg = "unexpected meta character {!r} at position {}: {!r}"
raise RegexError(msg.format(pattern[pos], pos, pattern))
continue
elif ch == '(':
if pattern[pos:pos + 2] == '(?':
msg = "invalid '(?...)' extension notation ad position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
total_groups += 1
nested_groups += 1
regex.append(group_open_char)
elif ch == ']':
msg = "unexpected meta character {!r} at position {}: {!r}"
raise RegexError(msg.format(ch, pos, pattern))
elif ch == ')':
if nested_groups == 0:
msg = "unbalanced parenthesis ')' at position {}: {!r}"
raise RegexError(msg.format(pos, pattern))
nested_groups -= 1
regex.append(ch)
elif ch in ('?', '+', '*'):
if pos == 0:
msg = "unexpected quantifier {!r} at position {}: {!r}"
raise RegexError(msg.format(ch, pos, pattern))
elif lazy_quantifiers:
pass
elif pos < pattern_len - 1 and pattern[pos + 1] in ('?', '+', '*', '{'):
msg = "unexpected meta character {!r} at position {}: {!r}"
raise RegexError(msg.format(pattern[pos + 1], pos + 1, pattern))
regex.append(ch)
elif ch == '\\':
pos += 1
if flags & re.VERBOSE:
while pos < pattern_len and pattern[pos] == ' ':
pos += 1
if pos >= pattern_len:
regex.append('\\')
elif pattern[pos].isdigit():
regex.append('\\%s' % pattern[pos])
reference = DIGITS_PATTERN.match(pattern[pos:]).group()
if len(reference) > 1:
k = 0
for k in range(1, len(reference)):
if total_groups < int(reference[:k + 1]):
regex.append('[%s]' % pattern[pos + k])
break
else:
regex.append(pattern[pos + k])
pos += k
elif pattern[pos] == 'i':
regex.append('[%s]' % I_SHORTCUT_REPLACE)
elif pattern[pos] == 'I':
regex.append('[^%s]' % I_SHORTCUT_REPLACE)
elif pattern[pos] == 'c':
regex.append('[%s]' % C_SHORTCUT_REPLACE)
elif pattern[pos] == 'C':
regex.append('[^%s]' % C_SHORTCUT_REPLACE)
elif pattern[pos] in 'pP':
block_pos = pos - 1
try:
if pattern[pos + 1] != '{':
raise RegexError("a '{' expected, found %r." % pattern[pos + 1])
while pattern[pos] != '}':
pos += 1
except (IndexError, ValueError):
msg = "truncated unicode block escape at position {}: {!r}"
raise RegexError(msg.format(block_pos, pattern))
block_name = pattern[block_pos + 3:pos]
if flags & re.VERBOSE:
block_name = block_name.replace(' ', '')
try:
p_shortcut_set = unicode_subset(block_name)
except RegexError:
if xsd_version == '1.0' or not block_name.startswith('Is'):
raise
p_shortcut_group = '[%s]' % UnicodeSubset([(0, maxunicode)])
else:
if pattern[block_pos + 1] == 'p':
p_shortcut_group = '[%s]' % p_shortcut_set
else:
p_shortcut_group = '[^%s]' % p_shortcut_set
if flags & re.IGNORECASE:
regex.append('(?-i:%s)' % p_shortcut_group)
else:
regex.append(p_shortcut_group)
else:
regex.append('\\%s' % pattern[pos])
else:
regex.append(ch)
pos += 1
if nested_groups > 0:
raise RegexError("unterminated subpattern in expression: %r" % pattern)
if not anchors:
regex.append(r')$(?!\n\Z)')
return ''.join(regex)
|
Translates a pattern regex expression to a Python regex pattern. With default
options the translator processes XPath 2.0/XQuery 1.0 regex patterns. For XML
Schema patterns set all boolean options to `False`.
:param pattern: the source XML Schema regular expression.
:param flags: regex flags as represented by Python's re module.
:param xsd_version: apply regex rules of a specific XSD version, '1.0' for default.
:param back_references: if `True` supports back-references and capturing groups.
:param lazy_quantifiers: if `True` supports lazy quantifiers (\\*?, +?).
:param anchors: if `True` supports ^ and $ anchors, otherwise the translated \
pattern is anchored to its boundaries and anchors are treated as normal characters.
|
https://github.com/sissaschool/elementpath/blob/a74ce89c04622d8ae98ab739886c3e46f87b024e/elementpath/regex/patterns.py#L31-L265
|
import re
from sys import maxunicode
from .unicode_subsets import RegexError, UnicodeSubset, unicode_subset
from .character_classes import I_SHORTCUT_REPLACE, C_SHORTCUT_REPLACE, CharacterClass
HYPHENS_PATTERN = re.compile(r'(?<!\\)--')
INVALID_HYPHEN_PATTERN = re.compile(r'[^\\]-[^\\]-[^\\]')
DIGITS_PATTERN = re.compile(r'\d+')
QUANTIFIER_PATTERN = re.compile(r'{\d+(,(\d+)?)?}')
FORBIDDEN_ESCAPES_NOREF_PATTERN = re.compile(
r'(?<!\\)\\(U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|o{\d+}|\d+|A|Z|z|B|b|o)'
)
FORBIDDEN_ESCAPES_REF_PATTERN = re.compile(
r'(?<!\\)\\(U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|o{\d+}|A|Z|z|B|b|o)'
)
|
MIT License
|
pyro-ppl/pyro
|
pyro/contrib/timeseries/base.py
|
TimeSeriesModel.get_dist
|
python
|
def get_dist(self):
raise NotImplementedError
|
Get a :class:`~pyro.distributions.Distribution` object corresponding to
this time series model. Often this is a
:class:`~pyro.distributions.GaussianHMM`.
|
https://github.com/pyro-ppl/pyro/blob/751843a16ffca0fec0ec722aa4d57cad246db648/pyro/contrib/timeseries/base.py#L43-L49
|
from pyro.nn import PyroModule, pyro_method
class TimeSeriesModel(PyroModule):
@pyro_method
def log_prob(self, targets):
raise NotImplementedError
@pyro_method
def forecast(self, targets, dts):
raise NotImplementedError
|
Apache License 2.0
|
symbiflow/prjxray
|
fuzzers/046-clk-bufg-muxed-pips/top.py
|
ClockSources.get_random_source
|
python
|
def get_random_source(self, cmt):
if cmt not in self.merged_sources:
choices = []
if 'ANY' in self.sources:
choices.extend(self.sources['ANY'])
if cmt in self.sources:
choices.extend(self.sources[cmt])
x, y = CMT_XY_FUN(cmt)
if x % 2 == 0:
x += 1
else:
x -= 1
paired_cmt = 'X{}Y{}'.format(x, y)
if paired_cmt in self.sources:
choices.extend(self.sources[paired_cmt])
self.merged_sources[cmt] = choices
if self.merged_sources[cmt]:
source = random.choice(self.merged_sources[cmt])
source_cmt = self.source_to_cmt[source]
if source_cmt not in self.used_sources_from_cmt:
self.used_sources_from_cmt[source_cmt] = set()
self.used_sources_from_cmt[source_cmt].add(source)
if source_cmt != 'ANY' and len(
self.used_sources_from_cmt[source_cmt]) > 14:
print('//', self.used_sources_from_cmt)
self.used_sources_from_cmt[source_cmt].remove(source)
return None
else:
return source
|
Get a random source that is routable to the specific CMT.
get_random_source will return a source that is either cmt='ANY',
cmt equal to the input CMT, or the adjecent CMT.
|
https://github.com/symbiflow/prjxray/blob/60168e9b7e89956ce8a197f3cfdf6d4bc80926d3/fuzzers/046-clk-bufg-muxed-pips/top.py#L61-L105
|
import os
import random
random.seed(int(os.getenv("SEED"), 16))
from prjxray import util
from prjxray.lut_maker import LutMaker
from prjxray.db import Database
from io import StringIO
CMT_XY_FUN = util.create_xy_fun(prefix='')
BUFGCTRL_XY_FUN = util.create_xy_fun('BUFGCTRL_')
def read_site_to_cmt():
with open(os.path.join(os.getenv('FUZDIR'), 'build',
'cmt_regions.csv')) as f:
for l in f:
site, cmt = l.strip().split(',')
yield (site, cmt)
class ClockSources(object):
def __init__(self):
self.sources = {}
self.merged_sources = {}
self.source_to_cmt = {}
self.used_sources_from_cmt = {}
def add_clock_source(self, source, cmt):
if cmt not in self.sources:
self.sources[cmt] = []
self.sources[cmt].append(source)
assert source not in self.source_to_cmt or self.source_to_cmt[
source] == cmt, source
self.source_to_cmt[source] = cmt
|
ISC License
|
ktbyers/pyplus_course
|
class4/collateral/textfsm.py
|
TextFSM._ParseFSMVariables
|
python
|
def _ParseFSMVariables(self, template):
self.values = []
for line in template:
self._line_num += 1
line = line.rstrip()
if not line:
return
if self.comment_regex.match(line):
continue
if line.startswith('Value '):
try:
value = TextFSMValue(
fsm=self, max_name_len=self.MAX_NAME_LEN,
options_class=self._options_cls)
value.Parse(line)
except TextFSMTemplateError as error:
raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num))
if value.name in self.header:
raise TextFSMTemplateError(
"Duplicate declarations for Value '%s'. Line: %s."
% (value.name, self._line_num))
try:
self._ValidateOptions(value)
except TextFSMTemplateError as error:
raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num))
self.values.append(value)
self.value_map[value.name] = value.template
elif not self.values:
raise TextFSMTemplateError('No Value definitions found.')
else:
raise TextFSMTemplateError(
'Expected blank line after last Value entry. Line: %s.'
% (self._line_num))
|
Extracts Variables from start of template file.
Values are expected as a contiguous block at the head of the file.
These will be line separated from the State definitions that follow.
Args:
template: Valid template file, with Value definitions at the top.
Raises:
TextFSMTemplateError: If syntax or semantic errors are found.
|
https://github.com/ktbyers/pyplus_course/blob/b8cdeb61ea2abd5607e5da41134bedd116144220/class4/collateral/textfsm.py#L691-L745
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__version__ = '0.4.1'
import getopt
import inspect
import re
import string
import sys
import colorama
DEBUG = True
class Error(Exception):
class Usage(Exception):
class TextFSMError(Error):
class TextFSMTemplateError(Error):
class FSMAction(Exception):
class SkipRecord(FSMAction):
class SkipValue(FSMAction):
class TextFSMOptions(object):
class OptionBase(object):
def __init__(self, value):
self.value = value
@property
def name(self):
return self.__class__.__name__.replace('option', '')
def OnCreateOptions(self):
def OnClearVar(self):
def OnClearAllVar(self):
def OnAssignVar(self):
def OnGetValue(self):
def OnSaveRecord(self):
@classmethod
def ValidOptions(cls):
valid_options = []
for obj_name in dir(cls):
obj = getattr(cls, obj_name)
if inspect.isclass(obj) and issubclass(obj, cls.OptionBase):
valid_options.append(obj_name)
return valid_options
@classmethod
def GetOption(cls, name):
return getattr(cls, name)
class Required(OptionBase):
def OnSaveRecord(self):
if not self.value.value:
raise SkipRecord
class Filldown(OptionBase):
def OnCreateOptions(self):
self._myvar = None
def OnAssignVar(self):
self._myvar = self.value.value
def OnClearVar(self):
self.value.value = self._myvar
def OnClearAllVar(self):
self._myvar = None
class Fillup(OptionBase):
def OnAssignVar(self):
if self.value.value:
value_idx = self.value.fsm.values.index(self.value)
for result in reversed(self.value.fsm._result):
if result[value_idx]:
break
result[value_idx] = self.value.value
class Key(OptionBase):
class List(OptionBase):
def OnCreateOptions(self):
self.OnClearAllVar()
def OnAssignVar(self):
if self.value.compiled_regex.groups > 1:
match = self.value.compiled_regex.match(self.value.value)
else:
match = None
if match and match.groupdict():
self._value.append(match.groupdict())
else:
self._value.append(self.value.value)
def OnClearVar(self):
if 'Filldown' not in self.value.OptionNames():
self._value = []
def OnClearAllVar(self):
self._value = []
def OnSaveRecord(self):
self.value.value = list(self._value)
class TextFSMValue(object):
def __init__(self, fsm=None, max_name_len=48, options_class=None):
self.max_name_len = max_name_len
self.name = None
self.options = []
self.regex = None
self.value = None
self.fsm = fsm
self._options_cls = options_class
def AssignVar(self, value):
self.value = value
_ = [option.OnAssignVar() for option in self.options]
def ClearVar(self):
self.value = None
_ = [option.OnClearVar() for option in self.options]
def ClearAllVar(self):
self.value = None
_ = [option.OnClearAllVar() for option in self.options]
def Header(self):
_ = [option.OnGetValue() for option in self.options]
return self.name
def OptionNames(self):
return [option.name for option in self.options]
def Parse(self, value):
value_line = value.split(' ')
if len(value_line) < 3:
raise TextFSMTemplateError('Expect at least 3 tokens on line.')
if not value_line[2].startswith('('):
options = value_line[1]
for option in options.split(','):
self._AddOption(option)
_ = [option.OnCreateOptions() for option in self.options]
self.name = value_line[2]
self.regex = ' '.join(value_line[3:])
else:
self.name = value_line[1]
self.regex = ' '.join(value_line[2:])
if len(self.name) > self.max_name_len:
raise TextFSMTemplateError(
"Invalid Value name '%s' or name too long." % self.name)
if (not re.match(r'^\(.*\)$', self.regex) or
self.regex.count('(') != self.regex.count(')')):
raise TextFSMTemplateError(
"Value '%s' must be contained within a '()' pair." % self.regex)
self.template = re.sub(r'^\(', '(?P<%s>' % self.name, self.regex)
if any(map(lambda x: isinstance(x, TextFSMOptions.List), self.options)):
try:
self.compiled_regex = re.compile(self.regex)
except re.error as e:
raise TextFSMTemplateError(str(e))
def _AddOption(self, name):
if name in [option.name for option in self.options]:
raise TextFSMTemplateError('Duplicate option "%s"' % name)
try:
option = self._options_cls.GetOption(name)(self)
except AttributeError:
raise TextFSMTemplateError('Unknown option "%s"' % name)
self.options.append(option)
def OnSaveRecord(self):
_ = [option.OnSaveRecord() for option in self.options]
def __str__(self):
if self.options:
return 'Value %s %s %s' % (
','.join(self.OptionNames()),
self.name,
self.regex)
else:
return 'Value %s %s' % (self.name, self.regex)
class CopyableRegexObject(object):
def __init__(self, pattern):
self.pattern = pattern
self.regex = re.compile(pattern)
def match(self, *args, **kwargs):
return self.regex.match(*args, **kwargs)
def sub(self, *args, **kwargs):
return self.regex.sub(*args, **kwargs)
def __copy__(self):
return CopyableRegexObject(self.pattern)
def __deepcopy__(self, unused_memo):
return self.__copy__()
class TextFSMRule(object):
MATCH_ACTION = re.compile(r'(?P<match>.*)(\s->(?P<action>.*))')
LINE_OP = ('Continue', 'Next', 'Error')
RECORD_OP = ('Clear', 'Clearall', 'Record', 'NoRecord')
LINE_OP_RE = '(?P<ln_op>%s)' % '|'.join(LINE_OP)
RECORD_OP_RE = '(?P<rec_op>%s)' % '|'.join(RECORD_OP)
OPERATOR_RE = r'(%s(\.%s)?)' % (LINE_OP_RE, RECORD_OP_RE)
NEWSTATE_RE = r'(?P<new_state>\w+|\".*\")'
ACTION_RE = re.compile(r'\s+%s(\s+%s)?$' % (OPERATOR_RE, NEWSTATE_RE))
ACTION2_RE = re.compile(r'\s+%s(\s+%s)?$' % (RECORD_OP_RE, NEWSTATE_RE))
ACTION3_RE = re.compile(r'(\s+%s)?$' % (NEWSTATE_RE))
def __init__(self, line, line_num=-1, var_map=None):
self.match = ''
self.regex = ''
self.regex_obj = None
self.line_op = ''
self.record_op = ''
self.new_state = ''
self.line_num = line_num
line = line.strip()
if not line:
raise TextFSMTemplateError('Null data in FSMRule. Line: %s'
% self.line_num)
match_action = self.MATCH_ACTION.match(line)
if match_action:
self.match = match_action.group('match')
else:
self.match = line
self.regex = self.match
if var_map:
try:
self.regex = string.Template(self.match).substitute(var_map)
except (ValueError, KeyError):
raise TextFSMTemplateError(
"Duplicate or invalid variable substitution: '%s'. Line: %s." %
(self.match, self.line_num))
try:
self.regex_obj = CopyableRegexObject(self.regex)
except re.error:
raise TextFSMTemplateError(
"Invalid regular expression: '%s'. Line: %s." %
(self.regex, self.line_num))
if not match_action:
return
action_re = self.ACTION_RE.match(match_action.group('action'))
if not action_re:
action_re = self.ACTION2_RE.match(match_action.group('action'))
if not action_re:
action_re = self.ACTION3_RE.match(match_action.group('action'))
if not action_re:
raise TextFSMTemplateError("Badly formatted rule '%s'. Line: %s." %
(line, self.line_num))
if 'ln_op' in action_re.groupdict() and action_re.group('ln_op'):
self.line_op = action_re.group('ln_op')
if 'rec_op' in action_re.groupdict() and action_re.group('rec_op'):
self.record_op = action_re.group('rec_op')
if 'new_state' in action_re.groupdict() and action_re.group('new_state'):
self.new_state = action_re.group('new_state')
if self.line_op == 'Continue' and self.new_state:
raise TextFSMTemplateError(
"Action '%s' with new state %s specified. Line: %s."
% (self.line_op, self.new_state, self.line_num))
if self.line_op != 'Error' and self.new_state:
if not re.match(r'\w+', self.new_state):
raise TextFSMTemplateError(
'Alphanumeric characters only in state names. Line: %s.'
% (self.line_num))
def __str__(self):
operation = ''
if self.line_op and self.record_op:
operation = '.'
operation = '%s%s%s' % (self.line_op, operation, self.record_op)
if operation and self.new_state:
new_state = ' ' + self.new_state
else:
new_state = self.new_state
if not (operation or new_state):
return ' %s' % self.match
return ' %s -> %s%s' % (self.match, operation, new_state)
class TextFSM(object):
MAX_NAME_LEN = 48
comment_regex = re.compile(r'^\s*#')
state_name_re = re.compile(r'^(\w+)$')
_DEFAULT_OPTIONS = TextFSMOptions
def __init__(self, template, options_class=_DEFAULT_OPTIONS):
self._options_cls = options_class
self.states = {}
self.state_list = []
self.values = []
self.value_map = {}
self._line_num = 0
self._cur_state = None
self._cur_state_name = None
try:
self._Parse(template)
finally:
template.seek(0)
self.Reset()
def __str__(self):
result = '\n'.join([str(value) for value in self.values])
result += '\n'
for state in self.state_list:
result += '\n%s\n' % state
state_rules = '\n'.join([str(rule) for rule in self.states[state]])
if state_rules:
result += state_rules + '\n'
return result
def Reset(self):
self._cur_state = self.states['Start']
self._cur_state_name = 'Start'
self._result = []
self._ClearAllRecord()
@property
def header(self):
return self._GetHeader()
def _GetHeader(self):
header = []
for value in self.values:
try:
header.append(value.Header())
except SkipValue:
continue
return header
def _GetValue(self, name):
for value in self.values:
if value.name == name:
return value
def _AppendRecord(self):
if not self.values:
return
cur_record = []
for value in self.values:
try:
value.OnSaveRecord()
except SkipRecord:
self._ClearRecord()
return
except SkipValue:
continue
cur_record.append(value.value)
if len(cur_record) == (cur_record.count(None) + cur_record.count([])):
return
while None in cur_record:
cur_record[cur_record.index(None)] = ''
self._result.append(cur_record)
if DEBUG:
print("{}{}: {}".format(colorama.Fore.BLUE, "RECORD > ", cur_record))
print(colorama.Style.RESET_ALL)
self._ClearRecord()
def _Parse(self, template):
if not template:
raise TextFSMTemplateError('Null template.')
self._ParseFSMVariables(template)
while self._ParseFSMState(template):
pass
self._ValidateFSM()
|
Apache License 2.0
|
italia/cie-nis-python-sdk
|
pkg/lib/CIEInterface.py
|
CIEInterface.initialSelect
|
python
|
def initialSelect(self):
apdu = string_to_byte("00A4040C07A0000002471001")
return self.transmit(apdu)
|
Sends an "initial selection" APDU to the card preparing it for the EAC authentication
:return: The response sent by the CIE
|
https://github.com/italia/cie-nis-python-sdk/blob/cc16e96fa2b4fe727f783e32d9f8d0367ea514eb/pkg/lib/CIEInterface.py#L115-L122
|
import progressbar
import six
import sys
from smartcard.CardType import AnyCardType
from smartcard.CardRequest import CardRequest
from smartcard.util import toHexString
from smartcard.Exceptions import CardRequestTimeoutException
from .Utilities import *
from .Algorithms import *
from .asn1lib import *
if six.PY3:
xrange = range
__author__ = "Alekos Filini, Daniela Brozzoni"
__license__ = "BSD-3-Clause"
__version__ = "1.0"
__status__ = "Develop"
class CIEInterface:
def __init__(self):
cardtype = AnyCardType()
cardrequest = CardRequest(timeout=3, cardType=cardtype)
self.seq = None
self.kSessEnc = None
self.kSessMac = None
self.index = 0
print('Waiting for the CIE...')
try:
self.cardservice = cardrequest.waitforcard()
except CardRequestTimeoutException:
print('Card not found, exiting')
sys.exit(1)
self.cardservice.connection.connect()
print('Connected!')
def selectIAS(self):
apdu = [0x00,
0xa4,
0x04,
0x0c,
0x0d,
0xA0, 0x00, 0x00, 0x00, 0x30, 0x80, 0x00, 0x00, 0x00, 0x09, 0x81, 0x60, 0x01
]
return self.transmit(apdu)
def selectCIE(self):
apdu = [
0x00,
0xa4,
0x04,
0x0c,
0x06,
0xA0, 0x00, 0x00, 0x00, 0x00, 0x39
]
return self.transmit(apdu)
def seqIncrement(self, index=None):
if index is None:
return self.seqIncrement(len(self.seq) - 1)
if self.seq[index] == 0xFF:
self.seq[index] = 0
self.seqIncrement(index - 1)
else:
self.seq[index] += 1
def readNIS(self):
self.selectIAS()
self.selectCIE()
response, _ = self.transmit(string_to_byte("00B081000C"))
return nfc_response_to_array(response)
|
BSD 3-Clause New or Revised License
|
alonazrael/keras-aquarium
|
keras_aquarium/hatt_rnn.py
|
HierarchicalAttentionRNN
|
python
|
def HierarchicalAttentionRNN(
max_sents,
max_sent_length,
n_classes,
embeddings=None,
n_words=None,
word_dim=50,
word_hidden_dim=100,
sent_hidden_dim=100,
):
if embeddings is None:
embedding_layer = Embedding(n_words+1,
word_dim,
input_length=max_sent_length,
trainable=True)
else:
embedding_layer = Embedding(len(embeddings),
len(embeddings[0]),
weights=[embeddings],
input_length=max_sent_length,
mask_zero=True,
trainable=True)
sent_input = Input(shape=(max_sent_length,), dtype='int32')
embedded_sequences = embedding_layer(sent_input)
class AttLayer(Layer):
def __init__(self, hit=None, **kwargs):
self.init = initializers.glorot_uniform()
super(AttLayer, self).__init__(**kwargs)
self.hit = hit
def build(self, input_shape_li):
input_shape = input_shape_li[-1]
assert len(input_shape)==3
self.W = self.init((input_shape[-1],))
self.W = K.variable(self.W)
self._x_input_shape = input_shape
self.trainable_weights = [self.W]
super(AttLayer, self).build(input_shape)
def call(self, xli, mask=None):
hit, x = xli
def get_weights_(x):
eij = K.dot(x, K.reshape(self.W, [self._x_input_shape[-1], 1]) )
eij = K.squeeze(eij, axis=-1)
ai = K.exp(eij)
ai_sum = K.sum(ai, axis=1)
ai_sum = K.reshape(ai_sum, [-1, 1])
weights = ai/ai_sum
return weights
weights = get_weights_(x)
self.output_weights = Lambda(get_weights_, )(x)
weights = K.expand_dims(weights, axis=1)
weighted_input = K.batch_dot(weights, hit, axes=[2, 1, ])
weighted_input = K.squeeze(weighted_input, axis=1)
return weighted_input
def get_output_shape_for(self, input_shape_li):
input_shape = input_shape_li[-1]
return (input_shape[0], input_shape[-1])
def compute_output_shape(self, input_shape_li):
return self.get_output_shape_for(input_shape_li)
def get_weights(args):
a, b = args
eij = K.dot(a, K.transpose(b))
ai = K.exp(eij)
weights = ai / K.sum(ai, axis=1)
return weights
layer_mode = True
sent_hidden = Bidirectional(
GRU(word_hidden_dim, activation="tanh", return_sequences=True)
)(embedded_sequences)
bi_word_hidden_dim = 2 * word_hidden_dim
sent_hidden_att = TimeDistributed(
Dense(bi_word_hidden_dim, activation="sigmoid")
)(sent_hidden)
if layer_mode:
word_att_layer = AttLayer()
sent_encoded = word_att_layer([sent_hidden, sent_hidden_att])
else:
words_attention = K.random_uniform_variable(
[1, bi_word_hidden_dim], low=0, high=1, )
word_weights = get_weights([sent_hidden_att, words_attention])
def attend_words(args):
sent_hidden, sent_hidden_att = args
weighted_input = sent_hidden * word_weights
weighted_input = K.sum(weighted_input, axis=1)
return weighted_input
sent_encoded = Lambda(attend_words, )([sent_hidden, sent_hidden_att])
sent_encoder = Model(sent_input, sent_encoded)
sents_input = Input(
shape=(max_sents, max_sent_length), dtype='int32', )
sents_encoded = TimeDistributed(sent_encoder)(sents_input)
doc_hidden = Bidirectional(
GRU(sent_hidden_dim, activation="tanh", return_sequences=True)
)(sents_encoded)
bi_sent_hidden_dim = 2 * sent_hidden_dim
doc_hidden_att = TimeDistributed(
Dense(bi_sent_hidden_dim, activation="sigmoid")
)(doc_hidden)
if layer_mode:
sent_att_layer = AttLayer()
doc_encoded = sent_att_layer([doc_hidden, doc_hidden_att])
else:
sents_attention = K.random_uniform_variable(
[1, bi_sent_hidden_dim], low=0, high=1, )
sent_weights = get_weights([doc_hidden_att, sents_attention])
def attend_doc(args):
doc_hidden, doc_hidden_att = args
weighted_input = sent_hidden * sent_weights
weighted_input = K.sum(weighted_input, axis=1)
return weighted_input
doc_encoded = Lambda(attend_doc, )([doc_hidden, doc_hidden_att])
pred = Dense(n_classes, activation='softmax')(doc_encoded)
model = Model(sents_input, pred)
model.compile(
loss='categorical_crossentropy',
optimizer='nadam',
metrics=['accuracy'])
if layer_mode:
sent_weights_model = Model(sents_input, sent_att_layer.output_weights)
else:
word_weights_layer = Lambda(get_weights, )([sent_hidden_att, words_attention])
print K.int_shape(word_weights_layer)
word_weights_model = Model(sent_input, word_weights_layer)
sents_word_weights = TimeDistributed(word_weights_model)(sents_input)
word_weights_model = Model(sents_input, sents_word_weights)
sent_weights_layer = Lambda(get_weights, )([doc_hidden_att, sents_attention])
sent_weights_model = Model(sents_input, sent_weights_layer)
model._keras_aquarium_params = dict(
model_type="hatt_rnn",
sent_weights_model=sent_weights_model,
max_sents=max_sents,
max_sent_length=max_sent_length,
)
return model
|
Hierarchical Attention RNN(GRU)
Two level of lstm network for text Classification, encode sentence by words first, then encode document by sentences.
Also add attention for both words and sentences.
Check paper [HIERARCHICAL ATTENTION NETWORKS FOR DOCUMENT CLASSIFICATION](https://www.cs.cmu.edu/~hovy/papers/16HLT-hierarchical-attention-networks.pdf) for more details.
Parameters
----------
max_sents : number of sentences in a document
max_sent_length : number of words in a sentence
n_classes : number of classes
embeddings :
use it to initialize word embeddings if applied
n_words : number of words in vocabulary
word_dim : dim of word embeddings
word_hidden_dim : number of word units in rnn
sent_hidden_dim : number of sentence units in rnn
Examples
--------
import keras
from keras_aquarium import hatt_rnn
from scipy.sparse import csr_matrix
import numpy as np
# suppose you have a 3D matrix (n_docs * n_sentences_in_doc * n_words_in_sentence), represents documents,
sequence_docs = np.zeros([n_docs, n_sentences_in_doc, n_words_in_sentence]) # padding zeros
word_embeddings = load_glove_word_embeddings()
vocabulary = load_vocabulary()
model = hatt_rnn.HierarchicalAttentionRNN(
max_sents,
max_sent_length,
n_classes,
# if use word_embeddings to initialize word embeddings layer
embeddings=word_embeddings,
# else
n_words=len(vocabulary),
word_dim=50,
# units in words and sentences gru layer
word_hidden_dim=100,
sent_hidden_dim=100,
)
model.fit(sequence_docs, labels)
|
https://github.com/alonazrael/keras-aquarium/blob/4924417fbe4a4a8f6c8add42cd33278c66fb1922/keras_aquarium/hatt_rnn.py#L11-L249
|
from keras.layers import Embedding, Dense, Input, Flatten, Lambda, LSTM, GRU, Bidirectional, TimeDistributed, Layer
from keras.models import Model
from keras import initializers
from keras import backend as K
from keras.utils import to_categorical
import numpy as np
|
MIT License
|
cymmetria/honeycomb
|
honeycomb/utils/config_utils.py
|
validate_config
|
python
|
def validate_config(config_json, fields):
for field_name, validator_obj in six.iteritems(fields):
field_value = config_json.get(field_name, None)
if field_value is None:
raise exceptions.ConfigFieldMissing(field_name)
if not validator_obj.validator_func(field_value):
raise exceptions.ConfigFieldValidationError(field_name, field_value, validator_obj.get_error_message())
|
Validate a JSON file configuration against list of :obj:`honeycomb.defs.ConfigField`.
|
https://github.com/cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L30-L38
|
from __future__ import unicode_literals, absolute_import
import os
import re
import json
import logging
import six
import yaml
from honeycomb import defs, exceptions
from honeycomb.error_messages import CONFIG_FIELD_TYPE_ERROR
logger = logging.getLogger(__name__)
def config_field_type(field, cls):
return defs.ConfigField(lambda _: isinstance(_, cls),
lambda: CONFIG_FIELD_TYPE_ERROR.format(field, cls.__name__))
|
MIT License
|
burnysc2/python-sc2
|
sc2/bot_ai.py
|
BotAI.find_placement
|
python
|
async def find_placement(
self,
building: Union[UnitTypeId, AbilityId],
near: Point2,
max_distance: int = 20,
random_alternative: bool = True,
placement_step: int = 2,
addon_place: bool = False,
) -> Optional[Point2]:
assert isinstance(building, (AbilityId, UnitTypeId))
assert isinstance(near, Point2), f"{near} is no Point2 object"
if isinstance(building, UnitTypeId):
building = self._game_data.units[building.value].creation_ability.id
if await self.can_place_single(
building, near
) and (not addon_place or await self.can_place_single(UnitTypeId.SUPPLYDEPOT, near.offset((2.5, -0.5)))):
return near
if max_distance == 0:
return None
for distance in range(placement_step, max_distance, placement_step):
possible_positions = [
Point2(p).offset(near).to2 for p in (
[(dx, -distance) for dx in range(-distance, distance + 1, placement_step)] +
[(dx, distance) for dx in range(-distance, distance + 1, placement_step)] +
[(-distance, dy) for dy in range(-distance, distance + 1, placement_step)] +
[(distance, dy) for dy in range(-distance, distance + 1, placement_step)]
)
]
res = await self._client._query_building_placement_fast(building, possible_positions)
possible = [p for r, p in zip(res, possible_positions) if r]
if addon_place:
res = await self._client._query_building_placement_fast(
AbilityId.TERRANBUILDDROP_SUPPLYDEPOTDROP,
[p.offset((2.5, -0.5)) for p in possible],
)
possible = [p for r, p in zip(res, possible) if r]
if not possible:
continue
if random_alternative:
return random.choice(possible)
else:
return min(possible, key=lambda p: p.distance_to_point2(near))
return None
|
Finds a placement location for building.
Example::
if self.townhalls:
cc = self.townhalls[0]
depot_position = await self.find_placement(UnitTypeId.SUPPLYDEPOT, near=cc)
:param building:
:param near:
:param max_distance:
:param random_alternative:
:param placement_step:
:param addon_place:
|
https://github.com/burnysc2/python-sc2/blob/a0b90b4447f23fc352a9bd931ae95ee5f4911032/sc2/bot_ai.py#L863-L929
|
from __future__ import annotations
import itertools
import math
import random
import time
import warnings
from collections import Counter
from contextlib import suppress
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union
from loguru import logger
from s2clientprotocol import sc2api_pb2 as sc_pb
from sc2.cache import property_cache_once_per_frame, property_cache_once_per_frame_no_copy
from sc2.constants import (
ALL_GAS,
EQUIVALENTS_FOR_TECH_PROGRESS,
IS_PLACEHOLDER,
PROTOSS_TECH_REQUIREMENT,
TERRAN_STRUCTURES_REQUIRE_SCV,
TERRAN_TECH_REQUIREMENT,
ZERG_TECH_REQUIREMENT,
FakeEffectID,
abilityid_to_unittypeid,
geyser_ids,
mineral_ids,
)
from sc2.data import ActionResult, Alert, Race, Result, Target, race_townhalls
from sc2.dicts.unit_research_abilities import RESEARCH_INFO
from sc2.dicts.unit_train_build_abilities import TRAIN_INFO
from sc2.dicts.unit_trained_from import UNIT_TRAINED_FROM
from sc2.dicts.upgrade_researched_from import UPGRADE_RESEARCHED_FROM
from sc2.distances import DistanceCalculation
from sc2.game_data import AbilityData, Cost, GameData
from sc2.game_state import Blip, EffectData, GameState
from sc2.ids.ability_id import AbilityId
from sc2.ids.unit_typeid import UnitTypeId
from sc2.ids.upgrade_id import UpgradeId
from sc2.pixel_map import PixelMap
from sc2.position import Point2
from sc2.unit import Unit
from sc2.unit_command import UnitCommand
from sc2.units import Units
if TYPE_CHECKING:
from sc2.client import Client
from sc2.game_info import GameInfo, Ramp
class BotAI(DistanceCalculation):
EXPANSION_GAP_THRESHOLD = 15
def _initialize_variables(self):
DistanceCalculation.__init__(self)
if not hasattr(self, "opponent_id"):
self.opponent_id: str = None
if not hasattr(self, "distance_calculation_method"):
self.distance_calculation_method: int = 2
if not hasattr(self, "unit_command_uses_self_do"):
self.unit_command_uses_self_do: bool = False
self.realtime: bool = False
self.base_build: int = -1
self.all_units: Units = Units([], self)
self.units: Units = Units([], self)
self.workers: Units = Units([], self)
self.larva: Units = Units([], self)
self.structures: Units = Units([], self)
self.townhalls: Units = Units([], self)
self.gas_buildings: Units = Units([], self)
self.all_own_units: Units = Units([], self)
self.enemy_units: Units = Units([], self)
self.enemy_structures: Units = Units([], self)
self.all_enemy_units: Units = Units([], self)
self.resources: Units = Units([], self)
self.destructables: Units = Units([], self)
self.watchtowers: Units = Units([], self)
self.mineral_field: Units = Units([], self)
self.vespene_geyser: Units = Units([], self)
self.placeholders: Units = Units([], self)
self.techlab_tags: Set[int] = set()
self.reactor_tags: Set[int] = set()
self.minerals: int = 50
self.vespene: int = 0
self.supply_army: float = 0
self.supply_workers: float = 12
self.supply_cap: float = 15
self.supply_used: float = 12
self.supply_left: float = 3
self.idle_worker_count: int = 0
self.army_count: int = 0
self.warp_gate_count: int = 0
self.actions: List[UnitCommand] = []
self.blips: Set[Blip] = set()
self.race: Race = None
self.enemy_race: Race = None
self._units_created: Counter = Counter()
self._unit_tags_seen_this_game: Set[int] = set()
self._units_previous_map: Dict[int, Unit] = {}
self._structures_previous_map: Dict[int, Unit] = {}
self._enemy_units_previous_map: Dict[int, Unit] = {}
self._enemy_structures_previous_map: Dict[int, Unit] = {}
self._all_units_previous_map: Dict[int, Unit] = {}
self._previous_upgrades: Set[UpgradeId] = set()
self._expansion_positions_list: List[Point2] = []
self._resource_location_to_expansion_position_dict: Dict[Point2, Point2] = {}
self._time_before_step: float = None
self._time_after_step: float = None
self._min_step_time: float = math.inf
self._max_step_time: float = 0
self._last_step_step_time: float = 0
self._total_time_in_on_step: float = 0
self._total_steps_iterations: int = 0
self.unit_tags_received_action: Set[int] = set()
@property
def time(self) -> float:
return self.state.game_loop / 22.4
@property
def time_formatted(self) -> str:
t = self.time
return f"{int(t // 60):02}:{int(t % 60):02}"
@property
def step_time(self) -> Tuple[float, float, float, float]:
avg_step_duration = (
(self._total_time_in_on_step / self._total_steps_iterations) if self._total_steps_iterations else 0
)
return (
self._min_step_time * 1000,
avg_step_duration * 1000,
self._max_step_time * 1000,
self._last_step_step_time * 1000,
)
@property
def game_info(self) -> GameInfo:
return self._game_info
@property
def game_data(self) -> GameData:
return self._game_data
@property
def client(self) -> Client:
return self._client
@property
def larva_count(self):
warnings.warn(
"self.larva_count will be removed soon, please use len(self.larva) or self.larva.amount instead",
DeprecationWarning,
stacklevel=2,
)
return len(self.larva)
def alert(self, alert_code: Alert) -> bool:
assert isinstance(alert_code, Alert), f"alert_code {alert_code} is no Alert"
return alert_code.value in self.state.alerts
@property
def start_location(self) -> Point2:
return self._game_info.player_start_location
@property
def enemy_start_locations(self) -> List[Point2]:
return self._game_info.start_locations
@property
def main_base_ramp(self) -> Ramp:
if hasattr(self, "cached_main_base_ramp"):
return self.cached_main_base_ramp
try:
self.cached_main_base_ramp = min(
(ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in {2, 5}),
key=lambda r: self.start_location.distance_to(r.top_center),
)
except ValueError:
self.cached_main_base_ramp = min(
(ramp for ramp in self.game_info.map_ramps if len(ramp.upper) in {4, 9}),
key=lambda r: self.start_location.distance_to(r.top_center),
)
return self.cached_main_base_ramp
@property_cache_once_per_frame
def expansion_locations_list(self) -> List[Point2]:
assert (
self._expansion_positions_list
), f"self._find_expansion_locations() has not been run yet, so accessing the list of expansion locations is pointless."
return self._expansion_positions_list
@property_cache_once_per_frame
def expansion_locations_dict(self) -> Dict[Point2, Units]:
assert (
self._expansion_positions_list
), f"self._find_expansion_locations() has not been run yet, so accessing the list of expansion locations is pointless."
expansion_locations: Dict[Point2, Units] = {pos: Units([], self) for pos in self._expansion_positions_list}
for resource in self.resources:
exp_position: Point2 = self._resource_location_to_expansion_position_dict.get(resource.position, None)
if exp_position:
assert exp_position in expansion_locations
expansion_locations[exp_position].append(resource)
return expansion_locations
@property_cache_once_per_frame
def expansion_locations(self) -> Dict[Point2, Units]:
assert (
self._expansion_positions_list
), f"self._find_expansion_locations() has not been run yet, so accessing the list of expansion locations is pointless."
warnings.warn(
f"You are using 'self.expansion_locations', please use 'self.expansion_locations_list' (fast) or 'self.expansion_locations_dict' (slow) instead.",
DeprecationWarning,
stacklevel=2,
)
return self.expansion_locations_dict
def _find_expansion_locations(self):
resource_spread_threshold: float = 8.5
geysers: Units = self.vespene_geyser
resource_groups: List[List[Unit]] = [
[resource] for resource in self.resources
if resource.name != "MineralField450"
]
merged_group = True
while merged_group:
merged_group = False
for group_a, group_b in itertools.combinations(resource_groups, 2):
if any(
resource_a.distance_to(resource_b) <= resource_spread_threshold
for resource_a, resource_b in itertools.product(group_a, group_b)
):
resource_groups.remove(group_a)
resource_groups.remove(group_b)
resource_groups.append(group_a + group_b)
merged_group = True
break
offset_range = 7
offsets = [
(x, y) for x, y in itertools.product(range(-offset_range, offset_range + 1), repeat=2)
if 4 < math.hypot(x, y) <= 8
]
centers = {}
for resources in resource_groups:
amount = len(resources)
center_x = int(sum(resource.position.x for resource in resources) / amount) + 0.5
center_y = int(sum(resource.position.y for resource in resources) / amount) + 0.5
possible_points = (Point2((offset[0] + center_x, offset[1] + center_y)) for offset in offsets)
possible_points = (
point for point in possible_points
if self._game_info.placement_grid[point.rounded] == 1
and all(
point.distance_to(resource) >= (7 if resource._proto.unit_type in geyser_ids else 6)
for resource in resources
)
)
result: Point2 = min(
possible_points, key=lambda point: sum(point.distance_to(resource) for resource in resources)
)
centers[result] = resources
self._expansion_positions_list.append(result)
for resource in resources:
self._resource_location_to_expansion_position_dict[resource.position] = result
@property
def units_created(self) -> Counter:
return self._units_created
def _correct_zerg_supply(self):
half_supply_units = {
UnitTypeId.ZERGLING,
UnitTypeId.ZERGLINGBURROWED,
UnitTypeId.BANELING,
UnitTypeId.BANELINGBURROWED,
UnitTypeId.BANELINGCOCOON,
}
correction = self.units(half_supply_units).amount % 2
self.supply_used += correction
self.supply_army += correction
self.supply_left -= correction
async def get_available_abilities(
self, units: Union[List[Unit], Units], ignore_resource_requirements: bool = False
) -> List[List[AbilityId]]:
return await self._client.query_available_abilities(units, ignore_resource_requirements)
async def expand_now(
self, building: UnitTypeId = None, max_distance: float = 10, location: Optional[Point2] = None
):
if not building:
start_townhall_type = {
Race.Protoss: UnitTypeId.NEXUS,
Race.Terran: UnitTypeId.COMMANDCENTER,
Race.Zerg: UnitTypeId.HATCHERY,
}
building = start_townhall_type[self.race]
assert isinstance(building, UnitTypeId), f"{building} is no UnitTypeId"
if not location:
location = await self.get_next_expansion()
if not location:
logger.warning("Trying to expand_now() but bot is out of locations to expand to")
return
await self.build(building, near=location, max_distance=max_distance, random_alternative=False, placement_step=1)
async def get_next_expansion(self) -> Optional[Point2]:
closest = None
distance = math.inf
for el in self.expansion_locations_list:
def is_near_to_expansion(t):
return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD
if any(map(is_near_to_expansion, self.townhalls)):
continue
startp = self._game_info.player_start_location
d = await self._client.query_pathing(startp, el)
if d is None:
continue
if d < distance:
distance = d
closest = el
return closest
async def distribute_workers(self, resource_ratio: float = 2):
if not self.mineral_field or not self.workers or not self.townhalls.ready:
return
worker_pool = [worker for worker in self.workers.idle]
bases = self.townhalls.ready
gas_buildings = self.gas_buildings.ready
deficit_mining_places = []
for mining_place in bases | gas_buildings:
difference = mining_place.surplus_harvesters
if not difference:
continue
if mining_place.has_vespene:
local_workers = self.workers.filter(
lambda unit: unit.order_target == mining_place.tag or
(unit.is_carrying_vespene and unit.order_target == bases.closest_to(mining_place).tag)
)
else:
local_minerals_tags = {
mineral.tag
for mineral in self.mineral_field if mineral.distance_to(mining_place) <= 8
}
local_workers = self.workers.filter(
lambda unit: unit.order_target in local_minerals_tags or
(unit.is_carrying_minerals and unit.order_target == mining_place.tag)
)
if difference > 0:
for worker in local_workers[:difference]:
worker_pool.append(worker)
else:
deficit_mining_places += [mining_place for _ in range(-difference)]
if len(worker_pool) > len(deficit_mining_places):
all_minerals_near_base = [
mineral for mineral in self.mineral_field
if any(mineral.distance_to(base) <= 8 for base in self.townhalls.ready)
]
for worker in worker_pool:
if deficit_mining_places:
if self.vespene and self.minerals / self.vespene < resource_ratio:
possible_mining_places = [place for place in deficit_mining_places if not place.vespene_contents]
else:
possible_mining_places = [place for place in deficit_mining_places if place.vespene_contents]
if not possible_mining_places:
possible_mining_places = deficit_mining_places
current_place = min(deficit_mining_places, key=lambda place: place.distance_to(worker))
deficit_mining_places.remove(current_place)
if current_place.vespene_contents:
worker.gather(current_place)
else:
local_minerals = (
mineral for mineral in self.mineral_field if mineral.distance_to(current_place) <= 8
)
target_mineral = max(local_minerals, key=lambda mineral: mineral.mineral_contents, default=None)
if target_mineral:
worker.gather(target_mineral)
elif worker.is_idle and all_minerals_near_base:
target_mineral = min(all_minerals_near_base, key=lambda mineral: mineral.distance_to(worker))
worker.gather(target_mineral)
else:
pass
@property
def owned_expansions(self) -> Dict[Point2, Unit]:
owned = {}
for el in self.expansion_locations_list:
def is_near_to_expansion(t):
return t.distance_to(el) < self.EXPANSION_GAP_THRESHOLD
th = next((x for x in self.townhalls if is_near_to_expansion(x)), None)
if th:
owned[el] = th
return owned
def calculate_supply_cost(self, unit_type: UnitTypeId) -> float:
if unit_type in {UnitTypeId.ZERGLING}:
return 1
unit_supply_cost = self._game_data.units[unit_type.value]._proto.food_required
if unit_supply_cost > 0 and unit_type in UNIT_TRAINED_FROM and len(UNIT_TRAINED_FROM[unit_type]) == 1:
producer: UnitTypeId
for producer in UNIT_TRAINED_FROM[unit_type]:
producer_unit_data = self.game_data.units[producer.value]
if producer_unit_data._proto.food_required <= unit_supply_cost:
producer_supply_cost = producer_unit_data._proto.food_required
unit_supply_cost -= producer_supply_cost
return unit_supply_cost
def can_feed(self, unit_type: UnitTypeId) -> bool:
required = self.calculate_supply_cost(unit_type)
return required <= 0 or self.supply_left >= required
def calculate_unit_value(self, unit_type: UnitTypeId) -> Cost:
unit_data = self.game_data.units[unit_type.value]
return Cost(unit_data._proto.mineral_cost, unit_data._proto.vespene_cost)
def calculate_cost(self, item_id: Union[UnitTypeId, UpgradeId, AbilityId]) -> Cost:
if isinstance(item_id, UnitTypeId):
if item_id in {UnitTypeId.REACTOR, UnitTypeId.TECHLAB, UnitTypeId.ARCHON}:
if item_id == UnitTypeId.REACTOR:
return Cost(50, 50)
elif item_id == UnitTypeId.TECHLAB:
return Cost(50, 25)
elif item_id == UnitTypeId.ARCHON:
return self.calculate_unit_value(UnitTypeId.ARCHON)
unit_data = self._game_data.units[item_id.value]
return self._game_data.calculate_ability_cost(unit_data.creation_ability)
elif isinstance(item_id, UpgradeId):
cost = self._game_data.upgrades[item_id.value].cost
else:
cost = self._game_data.calculate_ability_cost(item_id)
return cost
def can_afford(self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool = True) -> bool:
cost = self.calculate_cost(item_id)
if cost.minerals > self.minerals or cost.vespene > self.vespene:
return False
if check_supply_cost and isinstance(item_id, UnitTypeId):
supply_cost = self.calculate_supply_cost(item_id)
if supply_cost and supply_cost > self.supply_left:
return False
return True
async def can_cast(
self,
unit: Unit,
ability_id: AbilityId,
target: Optional[Union[Unit, Point2]] = None,
only_check_energy_and_cooldown: bool = False,
cached_abilities_of_unit: List[AbilityId] = None,
) -> bool:
assert isinstance(unit, Unit), f"{unit} is no Unit object"
assert isinstance(ability_id, AbilityId), f"{ability_id} is no AbilityId"
assert isinstance(target, (type(None), Unit, Point2))
if cached_abilities_of_unit:
abilities = cached_abilities_of_unit
else:
abilities = (await self.get_available_abilities([unit], ignore_resource_requirements=False))[0]
if ability_id in abilities:
if only_check_energy_and_cooldown:
return True
cast_range = self._game_data.abilities[ability_id.value]._proto.cast_range
ability_target = self._game_data.abilities[ability_id.value]._proto.target
if (
ability_target == 1 or ability_target == Target.PointOrNone.value and isinstance(target, Point2)
and unit.distance_to(target) <= unit.radius + target.radius + cast_range
):
return True
elif (
ability_target in {Target.Unit.value, Target.PointOrUnit.value} and isinstance(target, Unit)
and unit.distance_to(target) <= unit.radius + target.radius + cast_range
):
return True
elif (
ability_target in {Target.Point.value, Target.PointOrUnit.value} and isinstance(target, Point2)
and unit.distance_to(target) <= unit.radius + cast_range
):
return True
return False
def select_build_worker(self, pos: Union[Unit, Point2], force: bool = False) -> Optional[Unit]:
workers = (
self.workers.filter(lambda w: (w.is_gathering or w.is_idle) and w.distance_to(pos) < 20) or self.workers
)
if workers:
for worker in workers.sorted_by_distance_to(pos).prefer_idle:
if (
worker not in self.unit_tags_received_action and not worker.orders or len(worker.orders) == 1
and worker.orders[0].ability.id in {AbilityId.MOVE, AbilityId.HARVEST_GATHER}
):
return worker
return workers.random if force else None
async def can_place_single(self, building: Union[AbilityId, UnitTypeId], position: Point2) -> bool:
if isinstance(building, UnitTypeId):
creation_ability = self._game_data.units[building.value].creation_ability.id
return (await self._client._query_building_placement_fast(creation_ability, [position]))[0]
return (await self._client._query_building_placement_fast(building, [position]))[0]
async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId],
positions: List[Point2]) -> List[bool]:
building_type = type(building)
assert type(building) in {AbilityData, AbilityId, UnitTypeId}, f"{building}, {building_type}"
if building_type == UnitTypeId:
building = self._game_data.units[building.value].creation_ability.id
elif building_type == AbilityData:
warnings.warn(
"Using AbilityData is deprecated and may be removed soon. Please use AbilityId or UnitTypeId instead.",
DeprecationWarning,
stacklevel=2,
)
building = building_type.id
if isinstance(positions, (Point2, tuple)):
warnings.warn(
"The support for querying single entries will be removed soon. Please use either 'await self.can_place_single(building, position)' or 'await (self.can_place(building, [position]))[0]",
DeprecationWarning,
stacklevel=2,
)
return await self.can_place_single(building, positions)
else:
assert isinstance(positions, list), f"Expected an iterable (list, tuple), but was: {positions}"
assert isinstance(
positions[0], Point2
), f"List is expected to have Point2, but instead had: {positions[0]} {type(positions[0])}"
return await self._client._query_building_placement_fast(building, positions)
|
MIT License
|
numba/numba
|
numba/np/numpy_support.py
|
_check_struct_alignment
|
python
|
def _check_struct_alignment(rec, fields):
if rec.aligned:
for k, dt in zip(fields['names'], fields['formats']):
llvm_align = rec.alignof(k)
npy_align = dt.alignment
if llvm_align is not None and npy_align != llvm_align:
msg = (
'NumPy is using a different alignment ({}) '
'than Numba/LLVM ({}) for {}. '
'This is likely a NumPy bug.'
)
raise ValueError(msg.format(npy_align, llvm_align, dt))
|
Check alignment compatibility with Numpy
|
https://github.com/numba/numba/blob/8d4559a83b7b12da9121c030b8e3780874204a34/numba/np/numpy_support.py#L188-L200
|
import collections
import ctypes
import re
import numpy as np
from numba.core import errors, types
from numba.core.typing.templates import signature
from numba.core.errors import TypingError
from numba.core.cgutils import is_nonelike
numpy_version = tuple(map(int, np.__version__.split('.')[:2]))
FROM_DTYPE = {
np.dtype('bool'): types.boolean,
np.dtype('int8'): types.int8,
np.dtype('int16'): types.int16,
np.dtype('int32'): types.int32,
np.dtype('int64'): types.int64,
np.dtype('uint8'): types.uint8,
np.dtype('uint16'): types.uint16,
np.dtype('uint32'): types.uint32,
np.dtype('uint64'): types.uint64,
np.dtype('float32'): types.float32,
np.dtype('float64'): types.float64,
np.dtype('complex64'): types.complex64,
np.dtype('complex128'): types.complex128,
np.dtype(object): types.pyobject,
}
re_typestr = re.compile(r'[<>=\|]([a-z])(\d+)?$', re.I)
re_datetimestr = re.compile(r'[<>=\|]([mM])8?(\[([a-z]+)\])?$', re.I)
sizeof_unicode_char = np.dtype('U1').itemsize
def _from_str_dtype(dtype):
m = re_typestr.match(dtype.str)
if not m:
raise NotImplementedError(dtype)
groups = m.groups()
typecode = groups[0]
if typecode == 'U':
if dtype.byteorder not in '=|':
raise NotImplementedError("Does not support non-native "
"byteorder")
count = dtype.itemsize // sizeof_unicode_char
assert count == int(groups[1]), "Unicode char size mismatch"
return types.UnicodeCharSeq(count)
elif typecode == 'S':
count = dtype.itemsize
assert count == int(groups[1]), "Char size mismatch"
return types.CharSeq(count)
else:
raise NotImplementedError(dtype)
def _from_datetime_dtype(dtype):
m = re_datetimestr.match(dtype.str)
if not m:
raise NotImplementedError(dtype)
groups = m.groups()
typecode = groups[0]
unit = groups[2] or ''
if typecode == 'm':
return types.NPTimedelta(unit)
elif typecode == 'M':
return types.NPDatetime(unit)
else:
raise NotImplementedError(dtype)
def from_dtype(dtype):
if type(dtype) == type and issubclass(dtype, np.generic):
dtype = np.dtype(dtype)
elif getattr(dtype, "fields", None) is not None:
return from_struct_dtype(dtype)
try:
return FROM_DTYPE[dtype]
except KeyError:
pass
try:
char = dtype.char
except AttributeError:
pass
else:
if char in 'SU':
return _from_str_dtype(dtype)
if char in 'mM':
return _from_datetime_dtype(dtype)
if char in 'V' and dtype.subdtype is not None:
subtype = from_dtype(dtype.subdtype[0])
return types.NestedArray(subtype, dtype.shape)
raise errors.NumbaNotImplementedError(dtype)
_as_dtype_letters = {
types.NPDatetime: 'M8',
types.NPTimedelta: 'm8',
types.CharSeq: 'S',
types.UnicodeCharSeq: 'U',
}
def as_dtype(nbtype):
nbtype = types.unliteral(nbtype)
if isinstance(nbtype, (types.Complex, types.Integer, types.Float)):
return np.dtype(str(nbtype))
if nbtype is types.bool_:
return np.dtype('?')
if isinstance(nbtype, (types.NPDatetime, types.NPTimedelta)):
letter = _as_dtype_letters[type(nbtype)]
if nbtype.unit:
return np.dtype('%s[%s]' % (letter, nbtype.unit))
else:
return np.dtype(letter)
if isinstance(nbtype, (types.CharSeq, types.UnicodeCharSeq)):
letter = _as_dtype_letters[type(nbtype)]
return np.dtype('%s%d' % (letter, nbtype.count))
if isinstance(nbtype, types.Record):
return as_struct_dtype(nbtype)
if isinstance(nbtype, types.EnumMember):
return as_dtype(nbtype.dtype)
if isinstance(nbtype, types.npytypes.DType):
return as_dtype(nbtype.dtype)
if isinstance(nbtype, types.NumberClass):
return as_dtype(nbtype.dtype)
if isinstance(nbtype, types.NestedArray):
spec = (as_dtype(nbtype.dtype), tuple(nbtype.shape))
return np.dtype(spec)
if isinstance(nbtype, types.PyObject):
return np.dtype(object)
msg = f"{nbtype} cannot be represented as a NumPy dtype"
raise errors.NumbaNotImplementedError(msg)
def as_struct_dtype(rec):
assert isinstance(rec, types.Record)
names = []
formats = []
offsets = []
titles = []
for k, t in rec.members:
if not rec.is_title(k):
names.append(k)
formats.append(as_dtype(t))
offsets.append(rec.offset(k))
titles.append(rec.fields[k].title)
fields = {
'names': names,
'formats': formats,
'offsets': offsets,
'itemsize': rec.size,
'titles': titles,
}
_check_struct_alignment(rec, fields)
return np.dtype(fields, align=rec.aligned)
|
BSD 2-Clause Simplified License
|
google-research/meta-dataset
|
meta_dataset/data/imagenet_specification.py
|
init_split_subgraphs
|
python
|
def init_split_subgraphs(class_splits, spanning_leaves, valid_test_roots):
train_wn_ids = class_splits['train']
valid_wn_ids = class_splits['valid']
test_wn_ids = class_splits['test']
valid_root_wn_id = valid_test_roots['valid'].wn_id
test_root_wn_id = valid_test_roots['test'].wn_id
graph_copy_train, _ = copy_graph(spanning_leaves.keys())
graph_copy_valid, valid_root = copy_graph(spanning_leaves.keys(),
valid_root_wn_id)
graph_copy_test, test_root = copy_graph(spanning_leaves.keys(),
test_root_wn_id)
train_classes = set([s for s in graph_copy_train if s.wn_id in train_wn_ids])
valid_classes = set([s for s in graph_copy_valid if s.wn_id in valid_wn_ids])
test_classes = set([s for s in graph_copy_test if s.wn_id in test_wn_ids])
split_leaves = {
'train': train_classes,
'valid': valid_classes,
'test': test_classes
}
split_roots = {'valid': valid_root, 'test': test_root}
return split_leaves, split_roots
|
Gets leaf and root Synsets from different copies of the graph.
In particular, a new copy is created for each split. For all three splits, the
leaf Synsets of the corresponding copy that correspond to split classes are
returned. For the validation and test graphs, the corresponding root Synsets
are returned as well from the new copies. These will have the same WordNet id
and name as those in valid_test_roots but are nodes from the copy of the graph
instead of the original one.
Args:
class_splits: a dict whose keys are 'train', 'valid' and 'test' and whose
value for a given key is the set of WordNet id's of the classes that are
assigned to the corresponding split.
spanning_leaves: A dict mapping each Synset to the leaf Synsets that are
reachable from it.
valid_test_roots: A dict whose keys should be 'valid' and 'test' and whose
value for a given key is a Synset that spans all and only the leaves that
will desirably be assigned to the corresponding split.
Returns:
a dict mapping each of 'train', 'valid' and 'test' to the set of Synsets (of
the respective copy of the graph) corresponding to the classes that are
assigned to that split.
Raises:
ValueError: invalid keys for valid_test_roots, or same synset provided as
the root of both valid and test.
|
https://github.com/google-research/meta-dataset/blob/67546ff9f6992acfa4bc17edb92c82ff7bbcfbbc/meta_dataset/data/imagenet_specification.py#L465-L519
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
from absl import logging
from meta_dataset.data import imagenet_stats
import numpy as np
import six
import tensorflow.compat.v1 as tf
tf.flags.DEFINE_string(
'ilsvrc_2012_data_root',
'',
'Path to the root of the ImageNet data.')
tf.flags.DEFINE_string(
'path_to_is_a',
'',
'Path to the file containing is-a relationships (parent, child) pairs. '
'If empty, it defaults to "wordnet.is_a.txt" in ilsvrc_2012_data_root.')
tf.flags.DEFINE_string(
'path_to_words',
'',
'Path to the file containing (synset, word description) pairs. '
'If empty, it defaults to "words.txt" in ilsvrc_2012_data_root.')
FLAGS = tf.flags.FLAGS
class Synset(object):
def __init__(self, wn_id, words, children, parents):
self.wn_id = wn_id
self.words = words
self.children = children
self.parents = parents
def get_node_ancestors(synset):
ancestors = set()
to_visit = set(synset.parents)
visited = set()
while to_visit:
ancestor = to_visit.pop()
ancestors.add(ancestor)
visited.add(ancestor)
to_visit = to_visit | set(ancestor.parents) - visited
return ancestors
def get_ancestors(synsets):
all_ancestors = set()
for s in synsets:
all_ancestors = all_ancestors | get_node_ancestors(s)
return all_ancestors
def isolate_graph(nodes):
for n in nodes:
n.children = list(nodes & set(n.children))
n.parents = list(nodes & set(n.parents))
def isolate_node(node):
for p in node.parents:
p.children.remove(node)
for c in node.children:
c.parents.remove(node)
node.children = []
node.parents = []
def collapse(nodes):
def collapse_once(nodes):
num_collapsed = 0
non_collapsed_nodes = set()
for n in nodes:
if len(n.children) == 1:
n.children[0].parents += n.parents
for p in n.parents:
p.children.append(n.children[0])
isolate_node(n)
num_collapsed += 1
else:
non_collapsed_nodes.add(n)
assert len(nodes) - len(non_collapsed_nodes) == num_collapsed
return non_collapsed_nodes, num_collapsed
nodes, num_collapsed = collapse_once(nodes)
while num_collapsed:
nodes, num_collapsed = collapse_once(nodes)
return nodes
def get_leaves(nodes):
leaves = []
for n in nodes:
if not n.children:
leaves.append(n)
return leaves
def get_synsets_from_ids(wn_ids, synsets):
wn_ids = set(wn_ids)
requested_synsets = {}
for s in synsets:
if s.wn_id in wn_ids:
requested_synsets[s.wn_id] = s
found = set(requested_synsets.keys())
assert found == wn_ids, ('Did not find synsets for ids: {}.'.format(wn_ids -
found))
return requested_synsets
def get_spanning_leaves(nodes):
leaves = get_leaves(nodes)
spanning_leaves = {}
for n in nodes:
spanning_leaves[n] = set()
for l in leaves:
if is_descendent(l, n) or l == n:
spanning_leaves[n].add(l)
return spanning_leaves
def get_num_spanning_images(spanning_leaves, num_leaf_images):
num_images = {}
for node, leaves in spanning_leaves.items():
num_images[node] = sum([num_leaf_images[l.wn_id] for l in leaves])
return num_images
def create_sampling_graph(synsets, root=None):
nodes = get_ancestors(synsets)
if root is not None:
nodes_to_remove = [
n for n in nodes if not (root == n or is_descendent(n, root))
]
nodes = nodes - set(nodes_to_remove)
nodes = nodes | set(synsets)
isolate_graph(nodes)
nodes = collapse(nodes)
return nodes
def propose_valid_test_roots(spanning_leaves,
margin=50,
desired_num_valid_classes=150,
desired_num_test_classes=150):
def _sort_key(synset_and_leaves):
synset, leaves = synset_and_leaves
return (len(leaves), synset.wn_id)
spanning_leaves_sorted = sorted(six.iteritems(spanning_leaves), key=_sort_key)
spanning_leaves_sorted.reverse()
valid_candidates, test_candidates = [], []
for s, leaves in spanning_leaves_sorted:
num_leaves = len(leaves)
low_limit_valid = desired_num_valid_classes - margin
high_limit_valid = desired_num_valid_classes + margin
if low_limit_valid < num_leaves and num_leaves < high_limit_valid:
valid_candidates.append(s)
low_limit_test = desired_num_test_classes - margin
high_limit_test = desired_num_test_classes + margin
if low_limit_test < num_leaves and num_leaves < high_limit_test:
test_candidates.append(s)
if not valid_candidates or not test_candidates:
raise RuntimeError('Found no root candidates. Try a different margin.')
for cand in valid_candidates:
logging.info('Candidate %s, %s with %d spanning leaves', cand.words,
cand.wn_id, len(spanning_leaves[cand]))
valid_root = valid_candidates[0]
test_candidate_ind = 0
test_root = test_candidates[test_candidate_ind]
while test_root == valid_root:
test_candidate_ind += 1
if test_candidate_ind == len(test_candidates):
raise RuntimeError('No candidates for test root. Try a different margin.')
test_root = test_candidates[test_candidate_ind]
return {'valid': valid_root, 'test': test_root}
def get_class_splits(spanning_leaves, valid_test_roots=None, **kwargs):
if valid_test_roots is not None:
if valid_test_roots['valid'] is None or valid_test_roots['test'] is None:
raise ValueError('A root cannot be None.')
if valid_test_roots is None:
valid_test_roots = propose_valid_test_roots(spanning_leaves, **kwargs)
valid_root, test_root = valid_test_roots['valid'], valid_test_roots['test']
valid_wn_ids = set([s.wn_id for s in spanning_leaves[valid_root]])
test_wn_ids = set([s.wn_id for s in spanning_leaves[test_root]])
overlap = [s for s in valid_wn_ids if s in test_wn_ids]
logging.info('Size of overlap: %d leaves', len(overlap))
assign_to_valid = True
for s in overlap:
if assign_to_valid:
test_wn_ids.remove(s)
else:
valid_wn_ids.remove(s)
assign_to_valid = not assign_to_valid
leaves = get_leaves(spanning_leaves.keys())
train_wn_ids = set([
s.wn_id
for s in leaves
if s.wn_id not in valid_wn_ids and s.wn_id not in test_wn_ids
])
split_classes = {
'train': train_wn_ids,
'valid': valid_wn_ids,
'test': test_wn_ids
}
return split_classes, valid_test_roots
|
Apache License 2.0
|
yingtongdou/nash-detect
|
Utils/yelpFeatureExtraction.py
|
FeatureExtractor.PR_NR
|
python
|
def PR_NR(self, data):
feature = {}
for i, d in data.items():
positives = [1 for t in d if t[1] > 3]
negatives = [1 for t in d if t[1] < 3]
feature[i] = (float(len(positives)) / len(d), float(len(negatives)) / len(d))
return feature
|
Ratio of positive and negative reviews of a user or product
Args:
data is a dictionary with key=u_id or p_id and value = tuples of (neighbor id, rating, label, posting time)
Return:
dictionary with key = u_id or p_id and value = (PR, NR)
|
https://github.com/yingtongdou/nash-detect/blob/cda62b7a1c899b5640e46b11582cbdd68c89d5a6/Utils/yelpFeatureExtraction.py#L92-L106
|
import math
from copy import deepcopy
from datetime import datetime
import numpy as np
import sys
import os
sys.path.insert(0, os.path.abspath('../'))
from Utils.iohelper import *
class FeatureExtractor:
date_time_format_str = '%Y-%m-%d'
def __init__(self):
self.user_mnr_normalizer = 0
self.prod_mnr_normalizer = 0
self.product_num_ratings = {}
self.product_sum_ratings = {}
def MNR(self, data, data_type='user'):
feature = {}
for i, d in data.items():
frequency = {}
for t in d:
if t[3] not in frequency:
frequency[t[3]] = 1
else:
frequency[t[3]] += 1
feature[i] = max(frequency.values())
if data_type == 'user':
self.user_mnr_normalizer = max(feature.values())
for k in feature.keys():
feature[k] /= self.user_mnr_normalizer
else:
self.prod_mnr_normalizer = max(feature.values())
for k in feature.keys():
feature[k] /= self.prod_mnr_normalizer
return feature
def iMNR(self, data, new_data, data_type='user'):
feature = {}
for i, d in new_data.items():
all_d = deepcopy(d)
if i in data:
all_d += data[i]
frequency = {}
for t in all_d:
if t[3] not in frequency:
frequency[t[3]] = 1
else:
frequency[t[3]] += 1
feature[i] = max(frequency.values())
if data_type == 'user':
self.user_mnr_normalizer = max(max(feature.values()), self.user_mnr_normalizer)
for k in feature.keys():
feature[k] /= self.user_mnr_normalizer
else:
self.prod_mnr_normalizer = max(max(feature.values()), self.prod_mnr_normalizer)
for k in feature.keys():
feature[k] /= self.prod_mnr_normalizer
return feature
|
Apache License 2.0
|
google/citest
|
citest/service_testing/http_agent.py
|
BaseHttpOperation.data
|
python
|
def data(self):
return self.__data
|
The HTTP payload data to send, or None if there is no payload.
|
https://github.com/google/citest/blob/eda9171eed35b82ce6f048229bebd898edc25369/citest/service_testing/http_agent.py#L523-L525
|
import base64
import json
import re
import ssl
import sys
import traceback
try:
from urllib2 import build_opener
from urllib2 import Request
from urllib2 import HTTPCookieProcessor
from urllib2 import HTTPSHandler
from urllib2 import HTTPError
from urllib2 import URLError
except ImportError:
from urllib.request import build_opener
from urllib.request import Request
from urllib.request import HTTPCookieProcessor
from urllib.request import HTTPSHandler
from urllib.error import HTTPError
from urllib.error import URLError
try:
import httplib
except ImportError:
import http.client as httplib
from citest.base import JournalLogger
from citest.base import JsonSnapshotableEntity
from .http_scrubber import HttpScrubber
from . import base_agent
class HttpResponseType(JsonSnapshotableEntity):
@property
def http_code(self):
return self.__http_code
@property
def output(self):
return self.__output
@property
def exception(self):
return self.__exception
@property
def headers(self):
return self.__headers
@property
def error_message(self):
return (None if self.ok()
else self.exception if self.exception else self.output)
def __init__(self, http_code=None, output=None, exception=None, headers=None):
if (http_code is None) == (exception is None):
raise ValueError('http_code and exception should be disjoint.')
self.__http_code = http_code
self.__output = output
self.__exception = exception
self.__headers = headers or {}
def __str__(self):
return 'http_code={0} output={1!r} exception={2!r}'.format(
self.http_code, self.output, self.exception)
def export_to_json_snapshot(self, snapshot, entity, **kwargs):
format = kwargs.pop('format', None)
self.__export_to_json_snapshot_helper(
snapshot, entity, as_summary=False, format=format)
def export_summary_to_json_snapshot(self, snapshot, entity):
self.__export_to_json_snapshot_helper(snapshot, entity, as_summary=True)
def __export_to_json_snapshot_helper(
self, snapshot, entity, as_summary=False, format=None):
builder = snapshot.edge_builder
code_relation = { 2: 'VALID', 4: 'INVALID', 5: 'ERROR' }.get(
self.http_code // 100, None)
edge = builder.make(entity, 'HTTP Code', self.http_code,
relation=code_relation)
if self.headers:
edge = builder.make_data(entity, 'Response Headers', self.headers)
if not self.ok():
edge.add_metadata('relation', 'ERROR')
if self.exception:
edge = builder.make_error(entity, 'Response Error', self.exception)
if format:
edge.add_metadata('format', format)
if as_summary:
return
if self.output or not self.exception:
edge = builder.make_output(entity, 'Response Output', self.output)
if format:
edge.add_metadata('format', format)
def ok(self):
return self.http_code >= 200 and self.http_code < 300
def check_ok(self):
if not self.ok():
if self.exception:
raise ValueError('HTTP has no response: {ex}'.format(ex=self.exception))
else:
raise ValueError('Unexpected HTTP response {code}:\n{body}'.format(
code=self.http_code, body=self.output))
def get_header(self, key, default=None):
regex = re.compile(r'(?i)%s: (.*)\r?\n?' % key)
for header in self.__headers:
match = regex.match(header)
if match:
return match.group(1).strip()
return default
class HttpOperationStatus(base_agent.AgentOperationStatus):
@property
def finished(self):
return True
@property
def timed_out(self):
return self.__http_response.http_code in [httplib.REQUEST_TIMEOUT,
httplib.GATEWAY_TIMEOUT]
@property
def id(self):
return str(id(self))
@property
def finished_ok(self):
return self.__http_response.ok()
@property
def detail(self):
return self.__http_response.output
@property
def error(self):
return self.__http_response.error_message
@property
def snapshot_format(self):
return self.__snapshot_format
@property
def raw_http_response(self):
return self.__http_response
def __init__(self, operation, http_response):
super(HttpOperationStatus, self).__init__(operation)
self.__http_response = http_response
self.__snapshot_format = None
def __cmp__(self, response):
return self.__http_response.__cmp__(response.raw_http_response)
def __str__(self):
return 'http_response={0}'.format(self.__http_response)
def set_snapshot_format(self, format):
self.__snapshot_format = format
def set_http_response(self, http_response):
self.__http_response = http_response
def export_to_json_snapshot(self, snapshot, entity):
super(HttpOperationStatus, self).export_to_json_snapshot(snapshot, entity)
self.__http_response.export_to_json_snapshot(
snapshot, entity, format=self.__snapshot_format)
def export_summary_to_json_snapshot(self, snapshot, entity):
super(HttpOperationStatus, self).export_summary_to_json_snapshot(
snapshot, entity)
self.__http_response.export_summary_to_json_snapshot(snapshot, entity)
class SynchronousHttpOperationStatus(HttpOperationStatus):
@property
def id(self):
return None
@property
def timed_out(self):
return False
class HttpAgent(base_agent.BaseAgent):
@property
def headers(self):
return self.__headers
@property
def base_url(self):
return self.__base_url
@property
def http_scrubber(self):
return self.__http_scrubber
@http_scrubber.setter
def http_scrubber(self, scrubber):
self.__http_scrubber = scrubber
@property
def ignore_ssl_cert_verification(self):
return self.__ignore_ssl_cert_verification
@ignore_ssl_cert_verification.setter
def ignore_ssl_cert_verification(self, ignore_ssl_cert_verification):
self.__ignore_ssl_cert_verification = ignore_ssl_cert_verification
@staticmethod
def make_json_payload_from_object(payload_obj):
return json.JSONEncoder().encode(payload_obj)
@staticmethod
def make_json_payload_from_kwargs(**kwargs):
payload_dict = kwargs
return json.JSONEncoder().encode(payload_dict)
def __init__(self, base_url, logger=None):
super(HttpAgent, self).__init__(logger=logger)
self.__base_url = base_url
self.__status_class = HttpOperationStatus
self.__headers = {}
self.__http_scrubber = HttpScrubber()
self.__ignore_ssl_cert_verification = False
def add_header(self, key, value):
self.__headers[key] = value
def add_basic_auth_header(self, user, password):
text = '{user}:{password}'.format(user=user, password=password)
encoded_auth = base64.encodestring(str.encode(text))[:-1]
self.add_header('Authorization', 'Basic ' + bytes.decode(encoded_auth))
def export_to_json_snapshot(self, snapshot, entity):
snapshot.edge_builder.make_control(entity, 'Base URL', self.__base_url)
super(HttpAgent, self).export_to_json_snapshot(snapshot, entity)
def new_post_operation(self, title, path, data, status_class=None,
max_wait_secs=None):
return HttpPostOperation(title, path, data, self,
status_class=status_class,
max_wait_secs=max_wait_secs)
def new_delete_operation(self, title, path, data, status_class=None,
max_wait_secs=None):
return HttpDeleteOperation(title, path, data, self,
status_class=status_class,
max_wait_secs=max_wait_secs)
def _new_messaging_status(self, operation, http_response):
status_class = operation.status_class or self.__status_class
return status_class(operation, http_response)
def __send_http_request(self, path, http_type, data=None, headers=None):
if headers is None:
all_headers = self.__headers
else:
all_headers = self.__headers.copy()
all_headers.update(headers)
if path[0] == '/':
path = path[1:]
url = '{0}/{1}'.format(self.__base_url, path)
encoded_data = str.encode(data) if data is not None else None
req = Request(url=url, data=encoded_data, headers=all_headers)
req.get_method = lambda: http_type
scrubbed_url = self.__http_scrubber.scrub_url(url)
scrubbed_data = self.__http_scrubber.scrub_request(data)
if data is not None:
JournalLogger.journal_or_log_detail(
'{type} {url}'.format(type=http_type, url=scrubbed_url),
scrubbed_data,
_logger=self.logger,
_context='request')
else:
JournalLogger.journal_or_log(
'{type} {url}'.format(type=http_type, url=scrubbed_url),
_logger=self.logger,
_context='request')
if self.__ignore_ssl_cert_verification:
context = ssl._create_unverified_context()
opener = build_opener(HTTPSHandler(context=context), HTTPCookieProcessor())
else:
opener = build_opener(HTTPCookieProcessor())
code = None
output = None
exception = None
headers = None
try:
response = opener.open(req)
code = response.getcode()
output = bytes.decode(response.read())
if sys.version_info[0] > 2:
headers = dict(response.headers.items())
else:
headers = response.info().headers
scrubbed_output = self.__http_scrubber.scrub_response(output)
JournalLogger.journal_or_log_detail(
'HTTP {code}'.format(code=code),
scrubbed_output,
_logger=self.logger,
_context='response')
except HTTPError as ex:
code = ex.getcode()
output = bytes.decode(ex.read())
scrubbed_error = self.__http_scrubber.scrub_response(output)
JournalLogger.journal_or_log_detail(
'HTTP {code}'.format(code=code), scrubbed_error,
_logger=self.logger,
_context='response')
except URLError as ex:
JournalLogger.journal_or_log(
'Caught exception: {ex}\n{stack}'.format(
ex=ex, stack=traceback.format_exc()),
_logger=self.logger)
exception = ex
return HttpResponseType(http_code=code, output=output,
exception=exception, headers=headers)
def patch(self, path, data, content_type='application/json'):
return self.__send_http_request(
path, 'PATCH', data=data,
headers={'Content-Type': content_type})
def post(self, path, data, content_type='application/json'):
return self.__send_http_request(
path, 'POST', data=data,
headers={'Content-Type': content_type})
def put(self, path, data, content_type='application/json'):
return self.__send_http_request(
path, 'PUT', data=data,
headers={'Content-Type': content_type})
def delete(self, path, data, content_type='application/json'):
return self.__send_http_request(
path, 'DELETE', data=data,
headers={'Content-Type': content_type})
def get(self, path):
return self.__send_http_request(path, 'GET')
class BaseHttpOperation(base_agent.AgentOperation):
@property
def path(self):
return self.__path
@property
|
Apache License 2.0
|
tenzir/threatbus
|
plugins/backbones/threatbus_rabbitmq/threatbus_rabbitmq/rabbitmq_consumer.py
|
RabbitMQConsumer.on_connection_open_error
|
python
|
def on_connection_open_error(
self, _connection: pika.connection.Connection, err: Exception
):
self.logger.error(f"RabbitMQ consumer: connection failed to open {err}")
self.__shutdown()
|
Invoked as callback when opening a new pika.SelectConnecion.
Issues opening of a channel.
@param _connection The opened connection
|
https://github.com/tenzir/threatbus/blob/baca18075b6b09c18950f3f23305c903a36b61de/plugins/backbones/threatbus_rabbitmq/threatbus_rabbitmq/rabbitmq_consumer.py#L130-L139
|
from dynaconf.utils.boxing import DynaBox
import json
import pika
from logging import Logger
from stix2 import Indicator, Sighting, parse
import threatbus
from threatbus.data import (
SnapshotRequest,
SnapshotEnvelope,
SnapshotRequestDecoder,
SnapshotEnvelopeDecoder,
)
import time
from typing import Callable, List, Union
class RabbitMQConsumer(threatbus.StoppableWorker):
def __init__(
self,
conn_params: pika.ConnectionParameters,
exchange_name: str,
queue_params: DynaBox,
provision_callback: Callable[
[str, Union[Indicator, Sighting, SnapshotEnvelope, SnapshotRequest]], None
],
logger: Logger,
):
super(RabbitMQConsumer, self).__init__()
self.conn_params: pika.ConnectionParameters = conn_params
self.__provision_callback: Callable[
[str, Union[Indicator, Sighting, SnapshotEnvelope, SnapshotRequest]], None
] = provision_callback
self.logger: Logger = logger
self.consumers: List[str] = list()
self.exchange_name = exchange_name
self._reconnect_delay: int = 5
self._connection: Union[pika.SelectConnection, None] = None
self._channel: Union[pika.channel.Channel, None] = None
join_symbol = queue_params.name_join_symbol
queue_name_suffix = queue_params.name_suffix
self.queue_name = f"threatbus{join_symbol}{queue_name_suffix}"
queue_mode = "default" if not queue_params.lazy else "lazy"
self.queue_kwargs = {
"durable": queue_params.durable,
"exclusive": queue_params.exclusive,
"auto_delete": queue_params.auto_delete,
"arguments": {"x-queue-mode": queue_mode},
}
if queue_params.max_items:
self.queue_kwargs["arguments"]["x-max-length"] = queue_params.max_items
def __provision(self, _channel, method_frame, _header_frame, msg):
msg_type = None
try:
dct = json.loads(msg)
msg_type = dct.get("type", None)
except Exception as e:
self.logger.error(f"RabbitMQ consumer: error reading message {msg}: {e}")
try:
if msg_type == "indicator" or msg_type == "sighting":
self.__provision_callback(
f"stix2/{msg_type}", parse(msg, allow_custom=True)
)
elif msg_type == "snapshotrequest":
self.__provision_callback(
f"threatbus/{msg_type}", json.loads(msg, cls=SnapshotRequestDecoder)
)
elif msg_type == "snapshotenvelope":
self.__provision_callback(
f"threatbus/{msg_type}",
json.loads(msg, cls=SnapshotEnvelopeDecoder),
)
else:
self.logger.error(
f"RabbitMQ consumer: received message with unknown or missing 'type' field {msg}"
)
except Exception as e:
self.logger.error(f"RabbitMQ consumer: error decoding message {msg}: {e}")
self._channel.basic_ack(delivery_tag=method_frame.delivery_tag)
def __shutdown(self):
self._connection.ioloop.stop()
def join(self, *args, **kwargs):
self._reconnect_delay = 0
self.__shutdown()
super(RabbitMQConsumer, self).join(*args, **kwargs)
def on_connection_open(self, _connection: pika.connection.Connection):
self._connection.channel(on_open_callback=self.on_channel_open)
|
BSD 3-Clause New or Revised License
|
luci/recipes-py
|
recipe_modules/cas/api.py
|
CasApi._run
|
python
|
def _run(self, name, cmd, step_test_data=None):
return self.m.step(
name,
[
self.m.cipd.ensure_tool('infra/tools/luci/cas/${platform}',
self._version)
] + list(cmd),
step_test_data=step_test_data,
infra_step=True)
|
Returns a cas command step.
Args:
* name: (str): name of the step.
* cmd (list(str|Path)): cas client subcommand to run.
|
https://github.com/luci/recipes-py/blob/32f0255a6910af47c6cb35546032ae4d60fe9a92/recipe_modules/cas/api.py#L49-L63
|
from recipe_engine import recipe_api
class CasApi(recipe_api.RecipeApi):
def __init__(self, env_properties, **kwargs):
super(CasApi, self).__init__(**kwargs)
self._instance = None
self._cached_version = None
self._env_properties = env_properties
@property
def instance(self):
if self._instance:
return self._instance
swarming_server = (
self._env_properties.SWARMING_SERVER or
'https://example-cas-server.appspot.com')
project = swarming_server[len('https://'):-len('.appspot.com')]
self._instance = 'projects/%s/instances/default_instance' % project
return self._instance
@property
def _version(self):
if self.m.runtime.is_experimental:
return 'latest'
if self._cached_version is None:
self._cached_version = self.m.file.read_text(
"read infra revision",
self.resource("infra.sha1"),
test_data='git_revision:mock_infra_git_revision').strip()
return self._cached_version
|
Apache License 2.0
|
chaffelson/whoville
|
whoville/cloudbreak/models/flex_subscription_response.py
|
FlexSubscriptionResponse.__init__
|
python
|
def __init__(self, name=None, subscription_id=None, smart_sense_subscription_id=None, used_as_default=False, used_for_controller=False, id=None, owner=None, account=None, public_in_account=False, smart_sense_subscription=None):
self._name = None
self._subscription_id = None
self._smart_sense_subscription_id = None
self._used_as_default = None
self._used_for_controller = None
self._id = None
self._owner = None
self._account = None
self._public_in_account = None
self._smart_sense_subscription = None
self.name = name
if subscription_id is not None:
self.subscription_id = subscription_id
if smart_sense_subscription_id is not None:
self.smart_sense_subscription_id = smart_sense_subscription_id
if used_as_default is not None:
self.used_as_default = used_as_default
if used_for_controller is not None:
self.used_for_controller = used_for_controller
if id is not None:
self.id = id
if owner is not None:
self.owner = owner
if account is not None:
self.account = account
if public_in_account is not None:
self.public_in_account = public_in_account
if smart_sense_subscription is not None:
self.smart_sense_subscription = smart_sense_subscription
|
FlexSubscriptionResponse - a model defined in Swagger
|
https://github.com/chaffelson/whoville/blob/f71fda629c9fd50d0a482120165ea5abcc754522/whoville/cloudbreak/models/flex_subscription_response.py#L59-L93
|
from pprint import pformat
from six import iteritems
import re
class FlexSubscriptionResponse(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str',
'subscription_id': 'str',
'smart_sense_subscription_id': 'int',
'used_as_default': 'bool',
'used_for_controller': 'bool',
'id': 'int',
'owner': 'str',
'account': 'str',
'public_in_account': 'bool',
'smart_sense_subscription': 'SmartSenseSubscriptionJson'
}
attribute_map = {
'name': 'name',
'subscription_id': 'subscriptionId',
'smart_sense_subscription_id': 'smartSenseSubscriptionId',
'used_as_default': 'usedAsDefault',
'used_for_controller': 'usedForController',
'id': 'id',
'owner': 'owner',
'account': 'account',
'public_in_account': 'publicInAccount',
'smart_sense_subscription': 'smartSenseSubscription'
}
|
Apache License 2.0
|
mozilla/firefox-flicks
|
flicks/videos/models.py
|
Video2013.has_vote_from
|
python
|
def has_vote_from(self, user):
return (user.is_authenticated() and
self.voters.filter(pk=user.pk).exists())
|
Check if the given user has voted for this video.
|
https://github.com/mozilla/firefox-flicks/blob/ad19ed59aac682744badae6d19a149327037f293/flicks/videos/models.py#L121-L124
|
import os
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.db import models
from django.dispatch import receiver
import requests
from caching.base import CachingManager, CachingMixin
from funfactory.helpers import static
from requests.exceptions import RequestException
from tower import ugettext as _, ugettext_lazy as _lazy
from flicks.base.util import get_object_or_none
from flicks.videos import vimeo
from flicks.videos.tasks import process_deletion
from flicks.videos.util import (send_approval_email, vidly_embed_code,
vimeo_embed_code)
class Video2013(models.Model, CachingMixin):
title = models.CharField(max_length=255, blank=False)
description = models.TextField(blank=True)
user = models.ForeignKey(User)
created = models.DateTimeField(default=datetime.now)
random_ordering = models.IntegerField(default=0)
vimeo_id = models.IntegerField()
filename = models.CharField(max_length=255, blank=False)
approved = models.BooleanField(default=False)
processed = models.BooleanField(default=False)
user_notified = models.BooleanField(default=False)
voters = models.ManyToManyField(User, through='Vote',
related_name='voted_videos')
def _thumbnail_path(self, filename):
root, ext = os.path.splitext(filename)
return 'vimeo_thumbs/{0}{1}'.format(self.vimeo_id, ext)
thumbnail = models.ImageField(blank=True, upload_to=_thumbnail_path,
max_length=settings.MAX_FILEPATH_LENGTH)
objects = CachingManager()
@property
def region(self):
return self.user.userprofile.region
@property
def thumbnail_url(self):
return (self.thumbnail.url if self.thumbnail else
static('img/video-blank.jpg'))
@property
def vote_count(self):
return self.voters.count()
def save(self, *args, **kwargs):
original = get_object_or_none(Video2013, id=self.id)
if original and original.approved != self.approved:
self.process_approval()
return_value = super(Video2013, self).save(*args, **kwargs)
if original and self.approved and not self.user_notified:
send_approval_email(self)
self.user_notified = True
return_value = super(Video2013, self).save(*args, **kwargs)
return return_value
def embed_html(self, **kwargs):
return vimeo_embed_code(self.vimeo_id, **kwargs)
def process_approval(self):
if self.approved:
try:
self.download_thumbnail(commit=False)
except (RequestException, vimeo.VimeoServiceError):
pass
vimeo.set_privacy(self.vimeo_id, 'anybody')
else:
vimeo.set_privacy(self.vimeo_id, 'password',
password=settings.VIMEO_VIDEO_PASSWORD)
def download_thumbnail(self, commit=True):
thumbnails = vimeo.get_thumbnail_urls(self.vimeo_id)
try:
thumbnail = next(t for t in thumbnails if t['height'] == '150')
except StopIteration:
raise vimeo.VimeoServiceError('No medium thumbnail found.')
response = requests.get(thumbnail['_content'])
filename = response.url.rsplit('/')[-1]
content_file = ContentFile(response.content)
self.thumbnail.save(filename, content_file, save=False)
if commit:
self.save()
|
BSD 3-Clause New or Revised License
|
stephenhky/pyshorttextcategorization
|
shorttext/classifiers/embed/sumvec/SumEmbedVecClassification.py
|
SumEmbeddedVecClassifier.savemodel
|
python
|
def savemodel(self, nameprefix):
if not self.trained:
raise ModelNotTrainedException()
pickle.dump(self.addvec, open(nameprefix+'_embedvecdict.pkl', 'wb'))
|
Save the trained model into files.
Given the prefix of the file paths, save the model into files, with name given by the prefix,
and add "_embedvecdict.pickle" at the end. If there is no trained model, a `ModelNotTrainedException`
will be thrown.
:param nameprefix: prefix of the file path
:return: None
:type nameprefix: str
:raise: ModelNotTrainedException
|
https://github.com/stephenhky/pyshorttextcategorization/blob/52b49b6cf9b48c4211ce15c3310262c6b4bbc96c/shorttext/classifiers/embed/sumvec/SumEmbedVecClassification.py#L61-L75
|
import pickle
from collections import defaultdict
import numpy as np
from scipy.spatial.distance import cosine
from shorttext.utils.classification_exceptions import ModelNotTrainedException
from shorttext.utils import shorttext_to_avgvec
from shorttext.utils.compactmodel_io import CompactIOMachine
class SumEmbeddedVecClassifier(CompactIOMachine):
def __init__(self, wvmodel, vecsize=None, simfcn=lambda u, v: 1-cosine(u, v)):
CompactIOMachine.__init__(self, {'classifier': 'sumvec'}, 'sumvec', ['_embedvecdict.pkl'])
self.wvmodel = wvmodel
self.vecsize = self.wvmodel.vector_size if vecsize == None else vecsize
self.simfcn = simfcn
self.trained = False
def train(self, classdict):
self.addvec = defaultdict(lambda : np.zeros(self.vecsize))
for classtype in classdict:
self.addvec[classtype] = np.sum([self.shorttext_to_embedvec(shorttext)
for shorttext in classdict[classtype]],
axis=0)
self.addvec[classtype] /= np.linalg.norm(self.addvec[classtype])
self.addvec = dict(self.addvec)
self.trained = True
|
MIT License
|
enzet/roentgen
|
map_machine/feature/road.py
|
Road.draw
|
python
|
def draw(self, svg: Drawing, flinger: Flinger, is_border: bool) -> None:
filter_: Filter = self.get_filter(svg, is_border)
style: dict[str, Union[int, float, str]] = self.get_style(
flinger, is_border
)
path_commands: str = self.line.get_path()
path: Path
if filter_:
path = Path(d=path_commands, filter=filter_.get_funciri())
else:
path = Path(d=path_commands)
path.update(style)
svg.add(path)
|
Draw road as simple SVG path.
|
https://github.com/enzet/roentgen/blob/38c4e00de3d9429348485f114788baaccab64974/map_machine/feature/road.py#L481-L496
|
from dataclasses import dataclass
from typing import Any, Optional, Union
import numpy as np
import svgwrite
from colour import Color
from svgwrite import Drawing
from svgwrite.filters import Filter
from svgwrite.path import Path
from svgwrite.shapes import Circle
from map_machine.drawing import PathCommands
from map_machine.geometry.flinger import Flinger
from map_machine.osm.osm_reader import OSMNode, Tagged
from map_machine.scheme import RoadMatcher
from map_machine.geometry.vector import (
Line,
Polyline,
compute_angle,
norm,
turn_by_angle,
)
__author__ = "Sergey Vartanov"
__email__ = "me@enzet.ru"
USE_BLUR: bool = False
@dataclass
class Lane:
width: Optional[float] = None
is_forward: Optional[bool] = None
min_speed: Optional[float] = None
turn: Optional[str] = None
change: Optional[str] = None
destination: Optional[str] = None
def set_forward(self, is_forward: bool) -> None:
self.is_forward = is_forward
def get_width(self, scale: float) -> float:
if self.width is None:
return 3.7 * scale
return self.width * scale
class RoadPart:
def __init__(
self,
point_1: np.ndarray,
point_2: np.ndarray,
lanes: list[Lane],
scale: float,
) -> None:
self.point_1: np.ndarray = point_1
self.point_2: np.ndarray = point_2
self.lanes: list[Lane] = lanes
if lanes:
self.width = sum(map(lambda x: x.get_width(scale), lanes))
else:
self.width = 1
self.left_offset: float = self.width / 2
self.right_offset: float = self.width / 2
self.turned: np.ndarray = norm(
turn_by_angle(self.point_2 - self.point_1, np.pi / 2)
)
self.right_vector: np.ndarray = self.turned * self.right_offset
self.left_vector: np.ndarray = -self.turned * self.left_offset
self.right_connection: Optional[np.ndarray] = None
self.left_connection: Optional[np.ndarray] = None
self.right_projection: Optional[np.ndarray] = None
self.left_projection: Optional[np.ndarray] = None
self.left_outer: Optional[np.ndarray] = None
self.right_outer: Optional[np.ndarray] = None
self.point_a: Optional[np.ndarray] = None
self.point_middle: Optional[np.ndarray] = None
def update(self) -> None:
if self.left_connection is not None:
self.right_projection = (
self.left_connection + self.right_vector - self.left_vector
)
if self.right_connection is not None:
self.left_projection = (
self.right_connection - self.right_vector + self.left_vector
)
if (
self.left_connection is not None
and self.right_connection is not None
):
a = np.linalg.norm(self.right_connection - self.point_1)
b = np.linalg.norm(self.right_projection - self.point_1)
if a > b:
self.right_outer = self.right_connection
self.left_outer = self.left_projection
else:
self.right_outer = self.right_projection
self.left_outer = self.left_connection
self.point_middle = self.right_outer - self.right_vector
max_: float = 100
if np.linalg.norm(self.point_middle - self.point_1) > max_:
self.point_a = self.point_1 + max_ * norm(
self.point_middle - self.point_1
)
self.right_outer = self.point_a + self.right_vector
self.left_outer = self.point_a + self.left_vector
else:
self.point_a = self.point_middle
def get_angle(self) -> float:
return compute_angle(self.point_2 - self.point_1)
def draw_normal(self, drawing: svgwrite.Drawing) -> None:
line: Path = drawing.path(
("M", self.point_1, "L", self.point_2),
fill="none",
stroke="#8888FF",
stroke_width=self.width,
)
drawing.add(line)
def draw_debug(self, drawing: svgwrite.Drawing) -> None:
line: Path = drawing.path(
("M", self.point_1, "L", self.point_2),
fill="none",
stroke="#000000",
)
drawing.add(line)
line: Path = drawing.path(
(
"M", self.point_1 + self.right_vector,
"L", self.point_2 + self.right_vector,
),
fill="none",
stroke="#FF0000",
stroke_width=0.5,
)
drawing.add(line)
line = drawing.path(
(
"M", self.point_1 + self.left_vector,
"L", self.point_2 + self.left_vector,
),
fill="none",
stroke="#0000FF",
stroke_width=0.5,
)
drawing.add(line)
opacity: float = 0.4
radius: float = 2
if self.right_connection is not None:
circle = drawing.circle(
self.right_connection, 2.5, fill="#FF0000", opacity=opacity
)
drawing.add(circle)
if self.left_connection is not None:
circle = drawing.circle(
self.left_connection, 2.5, fill="#0000FF", opacity=opacity
)
drawing.add(circle)
if self.right_projection is not None:
circle = drawing.circle(
self.right_projection, 1.5, fill="#FF0000", opacity=opacity
)
drawing.add(circle)
if self.left_projection is not None:
circle = drawing.circle(
self.left_projection, 1.5, fill="#0000FF", opacity=opacity
)
drawing.add(circle)
if self.right_outer is not None:
circle = drawing.circle(
self.right_outer,
3.5,
stroke_width=0.5,
fill="none",
stroke="#FF0000",
opacity=opacity,
)
drawing.add(circle)
if self.left_outer is not None:
circle = drawing.circle(
self.left_outer,
3.5,
stroke_width=0.5,
fill="none",
stroke="#0000FF",
opacity=opacity,
)
drawing.add(circle)
if self.point_a is not None:
circle = drawing.circle(self.point_a, radius, fill="#000000")
drawing.add(circle)
def draw(self, drawing: svgwrite.Drawing) -> None:
if self.left_connection is not None:
path_commands = [
"M", self.point_2 + self.right_vector,
"L", self.point_2 + self.left_vector,
"L", self.left_connection,
"L", self.right_connection,
"Z",
]
drawing.add(drawing.path(path_commands, fill="#CCCCCC"))
def draw_entrance(
self, drawing: svgwrite.Drawing, is_debug: bool = False
) -> None:
if (
self.left_connection is not None
and self.right_connection is not None
):
path_commands = [
"M", self.right_projection,
"L", self.right_connection,
"L", self.left_projection,
"L", self.left_connection,
"Z",
]
if is_debug:
path = drawing.path(
path_commands,
fill="none",
stroke="#880088",
stroke_width=0.5,
)
drawing.add(path)
else:
drawing.add(drawing.path(path_commands, fill="#88FF88"))
def draw_lanes(self, drawing: svgwrite.Drawing, scale: float) -> None:
for lane in self.lanes:
shift = self.right_vector - self.turned * lane.get_width(scale)
path = drawing.path(
["M", self.point_middle + shift, "L", self.point_2 + shift],
fill="none",
stroke="#FFFFFF",
stroke_width=2,
stroke_dasharray="7,7",
)
drawing.add(path)
class Intersection:
def __init__(self, parts: list[RoadPart]) -> None:
self.parts: list[RoadPart] = sorted(parts, key=lambda x: x.get_angle())
for index in range(len(self.parts)):
next_index: int = 0 if index == len(self.parts) - 1 else index + 1
part_1: RoadPart = self.parts[index]
part_2: RoadPart = self.parts[next_index]
line_1: Line = Line(
part_1.point_1 + part_1.right_vector,
part_1.point_2 + part_1.right_vector,
)
line_2: Line = Line(
part_2.point_1 + part_2.left_vector,
part_2.point_2 + part_2.left_vector,
)
intersection: np.ndarray = line_1.get_intersection_point(line_2)
part_1.right_connection = intersection
part_2.left_connection = intersection
part_1.update()
part_2.update()
for index in range(len(self.parts)):
next_index: int = 0 if index == len(self.parts) - 1 else index + 1
part_1: RoadPart = self.parts[index]
part_2: RoadPart = self.parts[next_index]
part_1.update()
part_2.update()
if (
part_1.right_connection is None
and part_2.left_connection is None
):
part_1.left_connection = part_1.right_projection
part_2.right_connection = part_2.left_projection
part_1.left_outer = part_1.right_projection
part_2.right_outer = part_2.left_projection
part_1.update()
part_2.update()
def draw(self, drawing: svgwrite.Drawing, is_debug: bool = False) -> None:
inner_commands = ["M"]
for part in self.parts:
inner_commands += [part.left_connection, "L"]
inner_commands[-1] = "Z"
outer_commands = ["M"]
for part in self.parts:
outer_commands += [part.left_connection, "L"]
outer_commands += [part.left_outer, "L"]
outer_commands += [part.right_outer, "L"]
outer_commands[-1] = "Z"
if is_debug:
drawing.add(
drawing.path(outer_commands, fill="#0000FF", opacity=0.2)
)
drawing.add(
drawing.path(inner_commands, fill="#FF0000", opacity=0.2)
)
for part in self.parts:
if is_debug:
part.draw_debug(drawing)
else:
part.draw_entrance(drawing)
if not is_debug:
drawing.add(drawing.path(inner_commands, fill="#FF8888"))
class Road(Tagged):
def __init__(
self,
tags: dict[str, str],
nodes: list[OSMNode],
matcher: RoadMatcher,
flinger: Flinger,
) -> None:
super().__init__(tags)
self.nodes: list[OSMNode] = nodes
self.matcher: RoadMatcher = matcher
self.line: Polyline = Polyline(
[flinger.fling(x.coordinates) for x in self.nodes]
)
self.width: Optional[float] = matcher.default_width
self.lanes: list[Lane] = []
if "lanes" in tags:
try:
self.width = int(tags["lanes"]) * 3.7
self.lanes = [Lane()] * int(tags["lanes"])
except ValueError:
pass
if "width:lanes" in tags:
try:
widths: list[float] = list(
map(float, tags["width:lanes"].split("|"))
)
if len(widths) == len(self.lanes):
for index, lane in enumerate(self.lanes):
lane.width = widths[index]
except ValueError:
pass
number: int
if "lanes:forward" in tags:
number = int(tags["lanes:forward"])
[x.set_forward(True) for x in self.lanes[-number:]]
if "lanes:backward" in tags:
number = int(tags["lanes:backward"])
[x.set_forward(False) for x in self.lanes[:number]]
if "width" in tags:
try:
self.width = float(tags["width"])
except ValueError:
pass
self.layer: float = 0
if "layer" in tags:
self.layer = float(tags["layer"])
def get_style(
self, flinger: Flinger, is_border: bool, is_for_stroke: bool = False
) -> dict[str, Union[int, float, str]]:
width: float
if self.width is not None:
width = self.width
else:
width = self.matcher.default_width
border_width: float
if is_border:
color = self.get_border_color()
border_width = 2.0
else:
color = self.get_color()
border_width = 0.0
extra_width: float = 0.0
if is_border:
if self.tags.get("bridge") == "yes":
extra_width = 0.5
if self.tags.get("ford") == "yes":
extra_width = 2.0
if self.tags.get("embankment") == "yes":
extra_width = 4.0
scale: float = flinger.get_scale(self.nodes[0].coordinates)
style: dict[str, Union[int, float, str]] = {
"fill": "none",
"stroke": color.hex,
"stroke-linecap": "butt",
"stroke-linejoin": "round",
"stroke-width": scale * width + extra_width + border_width,
}
if is_for_stroke:
style["stroke-width"] = 2 + extra_width
if is_border and self.tags.get("embankment") == "yes":
style["stroke-dasharray"] = "1,3"
if self.tags.get("tunnel") == "yes":
if is_border:
style["stroke-dasharray"] = "3,3"
return style
def get_filter(self, svg: Drawing, is_border: bool) -> Optional[Filter]:
if not USE_BLUR:
return None
if is_border and self.tags.get("bridge") == "yes":
filter_ = svg.defs.add(svg.filter())
filter_.feGaussianBlur(in_="SourceGraphic", stdDeviation=2)
return filter_
return None
|
MIT License
|
capitalone/rubicon
|
rubicon_ml/repository/asynchronous/base.py
|
AsynchronousBaseRepository.get_dataframe_metadata
|
python
|
async def get_dataframe_metadata(self, project_name, dataframe_id, experiment_id=None):
dataframe_metadata_path = self._get_dataframe_metadata_path(
project_name, experiment_id, dataframe_id
)
try:
dataframe = json.loads(await self.filesystem._cat_file(dataframe_metadata_path))
except FileNotFoundError:
raise RubiconException(f"No dataframe with id `{dataframe_id}` found.")
return domain.Dataframe(**dataframe)
|
Overrides `rubicon.repository.BaseRepository.get_dataframe_metadata`
to asynchronously retrieve a dataframes's metadata from the configured
filesystem.
Parameters
----------
project_name : str
The name of the project the dataframe with ID
`dataframe_id` is logged to.
dataframe_id : str
The ID of the dataframe to retrieve.
experiment_id : str, optional
The ID of the experiment the dataframe with ID
`dataframe_id` is logged to. Dataframes do not
need to belong to an experiment.
Returns
-------
rubicon.domain.Dataframe
The dataframe with ID `dataframe_id`.
|
https://github.com/capitalone/rubicon/blob/86278a98cf5fd0b7e179a2949fce5a12e42fd7be/rubicon_ml/repository/asynchronous/base.py#L572-L603
|
import asyncio
import os
import warnings
import fsspec
from rubicon_ml import domain
from rubicon_ml.exceptions import RubiconException
from rubicon_ml.repository import BaseRepository
from rubicon_ml.repository.utils import json
def connect(func):
async def connect_first(*args, **kwargs):
repo, *_ = args
if not repo._is_connected:
await repo._connect()
repo._is_connected = True
return await func(*args, **kwargs)
return connect_first
def invalidate_cache(func):
async def invalidate_cache_after(*args, **kwargs):
result = await func(*args, **kwargs)
repo, *_ = args
repo.filesystem.invalidate_cache()
return result
return invalidate_cache_after
class AsynchronousBaseRepository(BaseRepository):
PROTOCOL = None
def __init__(self, root_dir, loop=None, **storage_options):
self.root_dir = root_dir
self.filesystem = fsspec.filesystem(
self.PROTOCOL, asynchronous=True, loop=loop, **storage_options
)
self._is_connected = False
async def _ls_directories_only(self, path):
return [
os.path.join(p.get("name"), "metadata.json")
for p in await self.filesystem._ls(path, detail=True)
if p.get("type", p.get("StorageClass")).lower() == "directory"
]
async def _cat_paths(self, metadata_paths):
files = []
paths = await self.filesystem._cat(metadata_paths, on_error="return")
for metadata in paths.values():
if isinstance(metadata, FileNotFoundError):
warning = f"{metadata} not found. Was this file unintentionally created?"
warnings.warn(warning)
else:
files.append(metadata)
return files
async def _connect(self):
pass
@connect
@invalidate_cache
async def create_project(self, project):
project_metadata_path = self._get_project_metadata_path(project.name)
if await self.filesystem._exists(project_metadata_path):
raise RubiconException(f"A project with name '{project.name}' already exists.")
await self._persist_domain(project, project_metadata_path)
@connect
async def get_project(self, project_name):
project_metadata_path = self._get_project_metadata_path(project_name)
try:
project = json.loads(await self.filesystem._cat_file(project_metadata_path))
except FileNotFoundError:
raise RubiconException(f"No project with name '{project_name}' found.")
return domain.Project(**project)
@connect
async def get_projects(self):
try:
project_metadata_paths = await self._ls_directories_only(self.root_dir)
projects = [
domain.Project(**json.loads(metadata))
for metadata in await self._cat_paths(project_metadata_paths)
]
except FileNotFoundError:
return []
return projects
@connect
@invalidate_cache
async def create_experiment(self, experiment):
experiment_metadata_path = self._get_experiment_metadata_path(
experiment.project_name, experiment.id
)
await self._persist_domain(experiment, experiment_metadata_path)
@connect
async def get_experiment(self, project_name, experiment_id):
experiment_metadata_path = self._get_experiment_metadata_path(project_name, experiment_id)
try:
experiment = json.loads(await self.filesystem._cat_file(experiment_metadata_path))
except FileNotFoundError:
raise RubiconException(f"No experiment with id `{experiment_id}` found.")
return domain.Experiment(**experiment)
@connect
async def get_experiments(self, project_name):
experiment_metadata_root = self._get_experiment_metadata_root(project_name)
try:
experiment_metadata_paths = await self._ls_directories_only(experiment_metadata_root)
experiments = [
domain.Experiment(**json.loads(metadata))
for metadata in await self._cat_paths(experiment_metadata_paths)
]
except FileNotFoundError:
return []
return experiments
@connect
@invalidate_cache
async def create_feature(self, feature, project_name, experiment_id):
feature_metadata_path = self._get_feature_metadata_path(
project_name, experiment_id, feature.name
)
if await self.filesystem._exists(feature_metadata_path):
raise RubiconException(f"A feature with name '{feature.name}' already exists.")
await self._persist_domain(feature, feature_metadata_path)
@connect
async def get_feature(self, project_name, experiment_id, feature_name):
feature_metadata_path = self._get_feature_metadata_path(
project_name, experiment_id, feature_name
)
try:
feature = json.loads(await self.filesystem._cat_file(feature_metadata_path))
except FileNotFoundError:
raise RubiconException(f"No feature with name '{feature_name}' found.")
return domain.Feature(**feature)
@connect
async def get_features(self, project_name, experiment_id):
feature_metadata_root = self._get_feature_metadata_root(project_name, experiment_id)
try:
feature_metadata_paths = await self._ls_directories_only(feature_metadata_root)
features = [
domain.Feature(**json.loads(metadata))
for metadata in await self._cat_paths(feature_metadata_paths)
]
except FileNotFoundError:
return []
return features
@connect
@invalidate_cache
async def create_parameter(self, parameter, project_name, experiment_id):
parameter_metadata_path = self._get_parameter_metadata_path(
project_name, experiment_id, parameter.name
)
if await self.filesystem._exists(parameter_metadata_path):
raise RubiconException(f"A parameter with name '{parameter.name}' already exists.")
await self._persist_domain(parameter, parameter_metadata_path)
@connect
async def get_parameter(self, project_name, experiment_id, parameter_name):
parameter_metadata_path = self._get_parameter_metadata_path(
project_name, experiment_id, parameter_name
)
try:
parameter = json.loads(await self.filesystem._cat_file(parameter_metadata_path))
except FileNotFoundError:
raise RubiconException(f"No parameter with name '{parameter_name}' found.")
return domain.Parameter(**parameter)
@connect
async def get_parameters(self, project_name, experiment_id):
parameter_metadata_root = self._get_parameter_metadata_root(project_name, experiment_id)
try:
parameter_metadata_paths = await self._ls_directories_only(parameter_metadata_root)
parameters = [
domain.Parameter(**json.loads(metadata))
for metadata in await self._cat_paths(parameter_metadata_paths)
]
except FileNotFoundError:
return []
return parameters
@connect
@invalidate_cache
async def create_metric(self, metric, project_name, experiment_id):
metric_metadata_path = self._get_metric_metadata_path(
project_name, experiment_id, metric.name
)
if await self.filesystem._exists(metric_metadata_path):
raise RubiconException(f"A metric with name '{metric.name}' already exists.")
await self._persist_domain(metric, metric_metadata_path)
@connect
async def get_metric(self, project_name, experiment_id, metric_name):
metric_metadata_path = self._get_metric_metadata_path(
project_name, experiment_id, metric_name
)
try:
metric = json.loads(await self.filesystem._cat_file(metric_metadata_path))
except FileNotFoundError:
raise RubiconException(f"No metric with name '{metric_name}' found.")
return domain.Metric(**metric)
@connect
async def get_metrics(self, project_name, experiment_id):
metric_metadata_root = self._get_metric_metadata_root(project_name, experiment_id)
try:
metric_metadata_paths = await self._ls_directories_only(metric_metadata_root)
metrics = [
domain.Metric(**json.loads(metadata))
for metadata in await self._cat_paths(metric_metadata_paths)
]
except FileNotFoundError:
return []
return metrics
@connect
@invalidate_cache
async def create_dataframe(self, dataframe, data, project_name, experiment_id=None):
dataframe_metadata_path = self._get_dataframe_metadata_path(
project_name, experiment_id, dataframe.id
)
dataframe_data_path = self._get_dataframe_data_path(
project_name, experiment_id, dataframe.id
)
self._persist_dataframe(data, dataframe_data_path)
await self._persist_domain(dataframe, dataframe_metadata_path)
@connect
|
Apache License 2.0
|
beta-team/beta-recsys
|
beta_rec/utils/common_util.py
|
print_dict_as_table
|
python
|
def print_dict_as_table(dic, tag=None, columns=["keys", "values"]):
print("-" * 80)
if tag is not None:
print(tag)
df = pd.DataFrame(dic.items(), columns=columns)
print(tabulate(df, headers=columns, tablefmt="psql"))
print("-" * 80)
return tabulate(df, headers=columns, tablefmt="psql")
|
Print a dictionary as table.
Args:
dic (dict): dict object to be formatted.
tag (str): A name for this dictionary.
columns ([str,str]): default ["keys", "values"]. columns name for keys and values.
Returns:
None
|
https://github.com/beta-team/beta-recsys/blob/be6a5c9307e00cc7bb06cbfd407a637e9d5afbb0/beta_rec/utils/common_util.py#L166-L183
|
import argparse
import gzip
import os
import random
import time
import zipfile
from functools import wraps
import numpy as np
import pandas as pd
import scipy.sparse as sp
import torch
from tabulate import tabulate
from ..utils.constants import (
DEFAULT_ITEM_COL,
DEFAULT_ORDER_COL,
DEFAULT_RATING_COL,
DEFAULT_TIMESTAMP_COL,
DEFAULT_USER_COL,
)
def normalized_adj_single(adj):
rowsum = np.array(adj.sum(1))
d_inv = np.power(rowsum, -1).flatten()
d_inv[np.isinf(d_inv)] = 0.0
d_mat_inv = sp.diags(d_inv)
norm_adj = d_mat_inv.dot(adj)
print("generate single-normalized adjacency matrix.")
return norm_adj.tocoo()
def ensureDir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def update_args(config, args):
args_dic = {}
for cfg in ["system", "model", "dataset"]:
for k, v in vars(args).items():
if v is not None and k in config[cfg]:
config[cfg][k] = v
args_dic[f"{cfg}:{k}"] = v
print_dict_as_table(args_dic, "Received parameters from command line (or default):")
def parse_gzip_file(path):
file = gzip.open(path, "rb")
for line in file:
yield eval(line)
def get_data_frame_from_gzip_file(path):
i = 0
df = {}
for d in parse_gzip_file(path):
df[i] = d
i += 1
return pd.DataFrame.from_dict(df, orient="index")
def save_dataframe_as_npz(data, data_file):
user_ids = data[DEFAULT_USER_COL].to_numpy(dtype=data[DEFAULT_USER_COL].dtypes)
item_ids = data[DEFAULT_ITEM_COL].to_numpy(dtype=data[DEFAULT_ITEM_COL].dtypes)
ratings = data[DEFAULT_RATING_COL].to_numpy(dtype=np.float32)
data_dic = {
"user_ids": user_ids,
"item_ids": item_ids,
"ratings": ratings,
}
if DEFAULT_ORDER_COL in data.columns:
order_ids = data[DEFAULT_ORDER_COL].to_numpy(dtype=np.long)
data_dic["order_ids"] = order_ids
if DEFAULT_TIMESTAMP_COL in data.columns:
timestamps = data[DEFAULT_TIMESTAMP_COL].to_numpy(dtype=np.long)
data_dic["timestamps"] = timestamps
else:
data_dic["timestamps"] = np.zeros_like(ratings)
np.savez_compressed(data_file, **data_dic)
def get_dataframe_from_npz(data_file):
np_data = np.load(data_file)
data_dic = {
DEFAULT_USER_COL: np_data["user_ids"],
DEFAULT_ITEM_COL: np_data["item_ids"],
DEFAULT_RATING_COL: np_data["ratings"],
}
if "timestamps" in np_data:
data_dic[DEFAULT_TIMESTAMP_COL] = np_data["timestamps"]
if "order_ids" in np_data:
data_dic[DEFAULT_ORDER_COL] = np_data["order_ids"]
data = pd.DataFrame(data_dic)
return data
def un_zip(file_name, target_dir=None):
if target_dir is None:
target_dir = os.path.dirname(file_name)
zip_file = zipfile.ZipFile(file_name)
for names in zip_file.namelist():
print(f"unzip file {names} ...")
zip_file.extract(names, target_dir)
zip_file.close()
|
MIT License
|
buysdb/singlecellmultiomics
|
singlecellmultiomics/features/features.py
|
FeatureContainer.get_gene_to_location_dict
|
python
|
def get_gene_to_location_dict(self, meta_key='gene_name', with_strand=False):
location_map = {}
for contig, start, end, name, strand, meta in self:
meta =dict(meta)
try:
if with_strand:
location_map[ meta[meta_key]] = (contig, start,end,strand)
else:
location_map[ meta[meta_key]] = (contig, start,end)
except Exception as e:
pass
return location_map
|
generate dictionary, {gene_name: contig,start,end}
Args:
meta_key(str): key of the meta information used to use as primary key for the returned gene_locations
Returns:
gene_locations(dict)
|
https://github.com/buysdb/singlecellmultiomics/blob/8fc8455ef3109a423188cb0323dd1a185dc17b41/singlecellmultiomics/features/features.py#L83-L105
|
import numpy as np
import gzip
import itertools
import re
import functools
import pysam
from singlecellmultiomics.utils import Prefetcher
from copy import copy
import collections
import pandas as pd
def get_gene_id_to_gene_name_conversion_table(annotation_path_exons,
featureTypes=['gene_name']):
conversion_table = {}
with (gzip.open(annotation_path_exons, 'rt') if annotation_path_exons.endswith('.gz') else open(annotation_path_exons, 'r')) as t:
for i, line in enumerate(t):
parts = line.rstrip().split(None, 8)
keyValues = {}
for part in parts[-1].split(';'):
kv = part.strip().split()
if len(kv) == 2:
key = kv[0]
value = kv[1].replace('"', '')
keyValues[key] = value
if 'gene_id' in keyValues and any(
[feat in keyValues for feat in featureTypes]):
conversion_table[keyValues['gene_id']] = '_'.join([
keyValues.get(feature, 'None')
for feature in featureTypes])
return conversion_table
class FeatureContainer(Prefetcher):
def __init__(self, verbose=False):
self.args = locals().copy()
self.startCoordinates = {}
self.features = {}
self.endCoordinates = {}
self.sorted = True
self.debug = False
self.remapKeys = {}
self.verbose = verbose
self.preload_list = []
def debugMsg(self, msg):
if self.verbose:
print(msg)
def __repr__(self):
s= 'FeatureContainer,'
if len(self.preload_list):
s+= ' Preloaded files:\n'
for f in self.preload_list:
s+=str(f)+'\n'
if len(self.features):
s+=f'Features in memory for {len(self.features)} contigs\n'
else:
s+='No features in memory\n'
return s
def __len__(self):
return sum(len(f) for f in self.features.values())
def preload_GTF(self, **kwargs):
self.preload_list.append( {'gtf':kwargs} )
|
MIT License
|
rspivak/slimit
|
src/slimit/parser.py
|
Parser.p_relational_expr
|
python
|
def p_relational_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
|
relational_expr : shift_expr
| relational_expr LT shift_expr
| relational_expr GT shift_expr
| relational_expr LE shift_expr
| relational_expr GE shift_expr
| relational_expr INSTANCEOF shift_expr
| relational_expr IN shift_expr
|
https://github.com/rspivak/slimit/blob/3533eba9ad5b39f3a015ae6269670022ab310847/src/slimit/parser.py#L554-L566
|
__author__ = 'Ruslan Spivak <ruslan.spivak@gmail.com>'
import ply.yacc
from slimit import ast
from slimit.lexer import Lexer
try:
from slimit import lextab, yacctab
except ImportError:
lextab, yacctab = 'lextab', 'yacctab'
class Parser(object):
def __init__(self, lex_optimize=True, lextab=lextab,
yacc_optimize=True, yacctab=yacctab, yacc_debug=False):
self.lex_optimize = lex_optimize
self.lextab = lextab
self.yacc_optimize = yacc_optimize
self.yacctab = yacctab
self.yacc_debug = yacc_debug
self.lexer = Lexer()
self.lexer.build(optimize=lex_optimize, lextab=lextab)
self.tokens = self.lexer.tokens
self.parser = ply.yacc.yacc(
module=self, optimize=yacc_optimize,
debug=yacc_debug, tabmodule=yacctab, start='program')
self._error_tokens = {}
def _has_been_seen_before(self, token):
if token is None:
return False
key = token.type, token.value, token.lineno, token.lexpos
return key in self._error_tokens
def _mark_as_seen(self, token):
if token is None:
return
key = token.type, token.value, token.lineno, token.lexpos
self._error_tokens[key] = True
def _raise_syntax_error(self, token):
raise SyntaxError(
'Unexpected token (%s, %r) at %s:%s between %s and %s' % (
token.type, token.value, token.lineno, token.lexpos,
self.lexer.prev_token, self.lexer.token())
)
def parse(self, text, debug=False):
return self.parser.parse(text, lexer=self.lexer, debug=debug)
def p_empty(self, p):
pass
def p_auto_semi(self, p):
pass
def p_error(self, token):
if self._has_been_seen_before(token):
self._raise_syntax_error(token)
if token is None or token.type != 'SEMI':
next_token = self.lexer.auto_semi(token)
if next_token is not None:
self._mark_as_seen(token)
self.parser.errok()
return next_token
self._raise_syntax_error(token)
def p_program(self, p):
p[0] = ast.Program(p[1])
def p_source_elements(self, p):
p[0] = p[1]
def p_source_element_list(self, p):
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[2])
p[0] = p[1]
def p_source_element(self, p):
p[0] = p[1]
def p_statement(self, p):
p[0] = p[1]
def p_block(self, p):
p[0] = ast.Block(p[2])
def p_literal(self, p):
p[0] = p[1]
def p_boolean_literal(self, p):
p[0] = ast.Boolean(p[1])
def p_null_literal(self, p):
p[0] = ast.Null(p[1])
def p_numeric_literal(self, p):
p[0] = ast.Number(p[1])
def p_string_literal(self, p):
p[0] = ast.String(p[1])
def p_regex_literal(self, p):
p[0] = ast.Regex(p[1])
def p_identifier(self, p):
p[0] = ast.Identifier(p[1])
def p_primary_expr(self, p):
p[0] = p[1]
def p_primary_expr_no_brace_1(self, p):
p[1]._mangle_candidate = True
p[1]._in_expression = True
p[0] = p[1]
def p_primary_expr_no_brace_2(self, p):
p[0] = ast.This()
def p_primary_expr_no_brace_3(self, p):
p[0] = p[1]
def p_primary_expr_no_brace_4(self, p):
p[2]._parens = True
p[0] = p[2]
def p_array_literal_1(self, p):
p[0] = ast.Array(items=p[2])
def p_array_literal_2(self, p):
items = p[2]
if len(p) == 6:
items.extend(p[4])
p[0] = ast.Array(items=items)
def p_element_list(self, p):
if len(p) == 3:
p[0] = p[1] + [p[2]]
else:
p[1].extend(p[3])
p[1].append(p[4])
p[0] = p[1]
def p_elision_opt_1(self, p):
p[0] = []
def p_elision_opt_2(self, p):
p[0] = p[1]
def p_elision(self, p):
if len(p) == 2:
p[0] = [ast.Elision(p[1])]
else:
p[1].append(ast.Elision(p[2]))
p[0] = p[1]
def p_object_literal(self, p):
if len(p) == 3:
p[0] = ast.Object()
else:
p[0] = ast.Object(properties=p[2])
def p_property_list(self, p):
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1]
def p_property_assignment(self, p):
if len(p) == 4:
p[0] = ast.Assign(left=p[1], op=p[2], right=p[3])
elif len(p) == 8:
p[0] = ast.GetPropAssign(prop_name=p[2], elements=p[6])
else:
p[0] = ast.SetPropAssign(
prop_name=p[2], parameters=p[4], elements=p[7])
def p_property_name(self, p):
p[0] = p[1]
def p_member_expr(self, p):
if len(p) == 2:
p[0] = p[1]
elif p[1] == 'new':
p[0] = ast.NewExpr(p[2], p[3])
elif p[2] == '.':
p[0] = ast.DotAccessor(p[1], p[3])
else:
p[0] = ast.BracketAccessor(p[1], p[3])
def p_member_expr_nobf(self, p):
if len(p) == 2:
p[0] = p[1]
elif p[1] == 'new':
p[0] = ast.NewExpr(p[2], p[3])
elif p[2] == '.':
p[0] = ast.DotAccessor(p[1], p[3])
else:
p[0] = ast.BracketAccessor(p[1], p[3])
def p_new_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.NewExpr(p[2])
def p_new_expr_nobf(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.NewExpr(p[2])
def p_call_expr(self, p):
if len(p) == 3:
p[0] = ast.FunctionCall(p[1], p[2])
elif len(p) == 4:
p[0] = ast.DotAccessor(p[1], p[3])
else:
p[0] = ast.BracketAccessor(p[1], p[3])
def p_call_expr_nobf(self, p):
if len(p) == 3:
p[0] = ast.FunctionCall(p[1], p[2])
elif len(p) == 4:
p[0] = ast.DotAccessor(p[1], p[3])
else:
p[0] = ast.BracketAccessor(p[1], p[3])
def p_arguments(self, p):
if len(p) == 4:
p[0] = p[2]
def p_argument_list(self, p):
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1]
def p_lef_hand_side_expr(self, p):
p[0] = p[1]
def p_lef_hand_side_expr_nobf(self, p):
p[0] = p[1]
def p_postfix_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix=True)
def p_postfix_expr_nobf(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix=True)
def p_unary_expr(self, p):
p[0] = p[1]
def p_unary_expr_nobf(self, p):
p[0] = p[1]
def p_unary_expr_common(self, p):
p[0] = ast.UnaryOp(p[1], p[2])
def p_multiplicative_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
def p_multiplicative_expr_nobf(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
def p_additive_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
def p_additive_expr_nobf(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
def p_shift_expr(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
def p_shift_expr_nobf(self, p):
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
|
MIT License
|
wdm0006/dummyrdd
|
dummy_spark/context.py
|
SparkContext.parallelize
|
python
|
def parallelize(self, c, numSlices=None):
return RDD(c, self, None)
|
:param c:
:param numSlices:
:return:
|
https://github.com/wdm0006/dummyrdd/blob/d66c30495cbaa001a744128c89d41fb55741fba5/dummy_spark/context.py#L254-L261
|
from __future__ import print_function
import gzip
import time
import sys
if sys.version_info.major == 3:
from io import BytesIO as buffer
elif sys.version_info.major == 2:
try:
import cStringIO as buffer
except ImportError:
import StringIO as buffer
else:
raise ValueError('Python %s not supported' % (sys.version_info.major, ))
from threading import Lock
from dummy_spark.rdd import RDD
try:
import tinys3
has_tinys3 = True
except ImportError as e:
has_tinys3 = False
__all__ = ['SparkContext']
__author__ = 'willmcginnis'
class hadoopConfiguration(object):
def __init__(self):
pass
def set(self, a, b):
setattr(self, a, b)
return True
def get(self, a):
return getattr(self, a, None)
class jvm(object):
def __init__(self):
self.hc = hadoopConfiguration()
def hadoopConfiguration(self):
return self.hc
def textFile(self, file_name):
if file_name.startswith('s3'):
if has_tinys3:
file_name = file_name.split('://')[1]
bucket_name = file_name.split('/')[0]
key_name = file_name.replace(bucket_name, '')[1:]
access_key = self.hc.get('fs.s3n.awsAccessKeyId')
secret_key = self.hc.get('fs.s3n.awsSecretAccessKey')
region = self.hc.get('fs.s3n.endpoint')
if region is None:
region = 's3.amazonaws.com'
conn = tinys3.Connection(access_key, secret_key, endpoint=region)
file = conn.get(key_name, bucket_name)
if file_name.endswith('.gz'):
compressed = buffer(file.content)
gzipper = gzip.GzipFile(fileobj=compressed)
return gzipper.readlines()
return file.content.decode('utf-8').split('\n')
else:
raise Exception('Need TinyS3 to use s3 files')
else:
if file_name.endswith('.gz'):
opener = gzip.open
else:
opener = open
with opener(file_name, 'r') as f:
return f.readlines()
class SparkContext(object):
_gateway = None
_jvm = None
_next_accum_id = 0
_active_spark_context = None
_lock = Lock()
_jsc = jvm()
_python_includes = None
PACKAGE_EXTENSIONS = ('.zip', '.egg', '.jar')
DUMMY_VERSION = 'dummy version'
def __init__(self, master=None, appName=None, sparkHome=None, pyFiles=None, environment=None, batchSize=0, serializer=None, conf=None, gateway=None, jsc=None, profiler_cls=None):
self._callsite = None
SparkContext._ensure_initialized(self, gateway=gateway)
self.start_time = time.time()
try:
self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, jsc, profiler_cls)
except:
self.stop()
raise
def _do_init(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, jsc, profiler_cls):
return
def _initialize_context(self, jconf):
return None
@classmethod
def _ensure_initialized(cls, instance=None, gateway=None):
return True
def __enter__(self):
return self
def __exit__(self, type, value, trace):
self.stop()
def setLogLevel(self, logLevel):
pass
@classmethod
def setSystemProperty(cls, key, value):
pass
@property
def version(self):
return self.DUMMY_VERSION
@property
def startTime(self):
return self.start_time
@property
def defaultParallelism(self):
return 1
@property
def defaultMinPartitions(self):
return 1
def stop(self):
pass
def emptyRDD(self):
return RDD([], self, None)
def range(self, start, end=None, step=1, numSlices=None):
return RDD(list(range(start, end, step)), self, None)
|
BSD 3-Clause New or Revised License
|
eth-cscs/reframe
|
reframe/core/modules.py
|
ModulesSystemImpl.execute
|
python
|
def execute(self, cmd, *args):
try:
exec_output = self._execute(cmd, *args)
except SpawnedProcessError as e:
raise EnvironError('could not execute module operation') from e
return exec_output
|
Execute an arbitrary module command using the modules backend.
:arg cmd: The command to execute, e.g., ``load``, ``restore`` etc.
:arg args: The arguments to pass to the command.
:returns: The command output.
|
https://github.com/eth-cscs/reframe/blob/adca255dec1b731837c178e75653c57bc4d7f36a/reframe/core/modules.py#L447-L459
|
import abc
import os
import re
from collections import OrderedDict
import reframe.core.fields as fields
import reframe.utility.osext as osext
import reframe.utility.typecheck as types
from reframe.core.exceptions import (ConfigError, EnvironError,
SpawnedProcessError)
from reframe.core.logging import getlogger
from reframe.utility import OrderedSet
class Module:
def __init__(self, name, collection=False, path=None):
if not isinstance(name, str):
raise TypeError('module name not a string')
name = name.strip()
if not name:
raise ValueError('module name cannot be empty')
try:
self._name, self._version = name.split('/', maxsplit=1)
except ValueError:
self._name, self._version = name, None
self._path = path
self._collection = collection
@property
def name(self):
return self._name
@property
def version(self):
return self._version
@property
def collection(self):
return self._collection
@property
def path(self):
return self._path
@property
def fullname(self):
if self.version is not None:
return '/'.join((self.name, self.version))
else:
return self.name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
if self.path != other.path:
return False
if self.collection != other.collection:
return False
if not self.version or not other.version:
return self.name == other.name
else:
return self.name == other.name and self.version == other.version
def __repr__(self):
return (f'{type(self).__name__}({self.fullname}, '
'{self.collection}, {self.path})')
def __str__(self):
return self.fullname
class ModulesSystem:
module_map = fields.TypedField(types.Dict[str, types.List[str]])
@classmethod
def create(cls, modules_kind=None):
getlogger().debug(f'Initializing modules system {modules_kind!r}')
if modules_kind is None or modules_kind == 'nomod':
return ModulesSystem(NoModImpl())
elif modules_kind == 'tmod31':
return ModulesSystem(TMod31Impl())
elif modules_kind == 'tmod':
return ModulesSystem(TModImpl())
elif modules_kind == 'tmod32':
return ModulesSystem(TModImpl())
elif modules_kind == 'tmod4':
return ModulesSystem(TMod4Impl())
elif modules_kind == 'lmod':
return ModulesSystem(LModImpl())
elif modules_kind == 'spack':
return ModulesSystem(SpackImpl())
else:
raise ConfigError('unknown module system: %s' % modules_kind)
def __init__(self, backend):
self._backend = backend
self.module_map = {}
def resolve_module(self, name):
ret = OrderedSet()
visited = set()
unvisited = [(name, None)]
path = []
while unvisited:
node, parent = unvisited.pop()
while path and path[-1] != parent:
path.pop()
if node == parent:
ret.add(node)
continue
try:
adjacent = reversed(self.module_map[node])
except KeyError:
ret.add(node)
else:
path.append(node)
for m in adjacent:
if m in path and m != node:
raise EnvironError('module cyclic dependency: ' +
'->'.join(path + [m]))
if m not in visited:
unvisited.append((m, node))
visited.add(node)
return list(ret)
@property
def backend(self):
return(self._backend)
def available_modules(self, substr=None):
return [str(m) for m in self._backend.available_modules(substr or '')]
def loaded_modules(self):
return [str(m) for m in self._backend.loaded_modules()]
def conflicted_modules(self, name, collection=False, path=None):
ret = []
for m in self.resolve_module(name):
ret += self._conflicted_modules(m, collection, path)
return ret
def _conflicted_modules(self, name, collection=False, path=None):
return [
str(m)
for m in self._backend.conflicted_modules(
Module(name, collection, path)
)
]
def execute(self, cmd, *args):
return self._backend.execute(cmd, *args)
def load_module(self, name, collection=False, path=None, force=False):
ret = []
for m in self.resolve_module(name):
ret.append((m, self._load_module(m, collection, path, force)))
return ret
def _load_module(self, name, collection=False, path=None, force=False):
module = Module(name, collection, path)
loaded_modules = self._backend.loaded_modules()
if module in loaded_modules:
return []
unload_list = set()
if force:
conflict_list = self._backend.conflicted_modules(module)
unload_list = set(loaded_modules) & set(conflict_list)
for m in unload_list:
self._backend.unload_module(m)
self._backend.load_module(module)
return [str(m) for m in unload_list]
def unload_module(self, name, collection=False, path=None):
for m in reversed(self.resolve_module(name)):
self._unload_module(m, collection, path)
def _unload_module(self, name, collection=False, path=None):
self._backend.unload_module(Module(name, collection, path))
def is_module_loaded(self, name):
return all(self._is_module_loaded(m)
for m in self.resolve_module(name))
def _is_module_loaded(self, name):
return self._backend.is_module_loaded(Module(name))
def load_mapping(self, mapping):
key, *rest = mapping.split(':')
if len(rest) != 1:
raise ConfigError('invalid mapping syntax: %s' % mapping)
key = key.strip()
values = rest[0].split()
if not key:
raise ConfigError('no key found in mapping: %s' % mapping)
if not values:
raise ConfigError('no mapping defined for module: %s' % key)
self.module_map[key] = list(OrderedDict.fromkeys(values))
def load_mapping_from_file(self, filename):
with open(filename) as fp:
for lineno, line in enumerate(fp, start=1):
line = line.strip().split('#')[0]
if not line:
continue
try:
self.load_mapping(line)
except ConfigError as e:
raise ConfigError('%s:%s' % (filename, lineno)) from e
@property
def name(self):
return self._backend.name()
@property
def version(self):
return self._backend.version()
def unload_all(self):
return self._backend.unload_all()
@property
def searchpath(self):
return self._backend.searchpath()
def searchpath_add(self, *dirs):
return self._backend.searchpath_add(*dirs)
def searchpath_remove(self, *dirs):
return self._backend.searchpath_remove(*dirs)
def change_module_path(self, *dirs):
return self._backend.change_module_path(*dirs)
def emit_load_commands(self, name, collection=False, path=None):
return self._backend.emit_load_instr(Module(name, collection, path))
def emit_unload_commands(self, name, collection=False, path=None):
return self._backend.emit_unload_instr(Module(name, collection, path))
def __str__(self):
return str(self._backend)
class ModulesSystemImpl(abc.ABC):
|
BSD 3-Clause New or Revised License
|
scalyr/scalyr-agent-2
|
scalyr_agent/third_party_python2/glob2/fnmatch.py
|
filter
|
python
|
def filter(names, pat, norm_paths=True, case_sensitive=True, sep=None):
result = []
pat = _norm_paths(pat, norm_paths, sep)
match = _compile_pattern(pat, case_sensitive)
for name in names:
m = match(_norm_paths(name, norm_paths, sep))
if m:
result.append((name,
tuple(_norm_paths(p, norm_paths, sep) for p in m.groups())))
return result
|
Return the subset of the list NAMES that match PAT.
|
https://github.com/scalyr/scalyr-agent-2/blob/6d32b861889078f044c9ab3f1f7157f2c89ba04a/scalyr_agent/third_party_python2/glob2/fnmatch.py#L83-L93
|
import os
import re
try:
from functools import lru_cache
except ImportError:
from .compat import lru_cache
__all__ = ["filter", "fnmatch", "fnmatchcase", "translate"]
def _norm_paths(path, norm_paths, sep):
if norm_paths is None:
path = re.sub(r'\/', sep or os.sep, path)
elif norm_paths:
path = os.path.normcase(path)
return path
def fnmatch(name, pat, norm_paths=True, case_sensitive=True, sep=None):
name, pat = [_norm_paths(p, norm_paths, sep)
for p in (name, pat)]
return fnmatchcase(name, pat, case_sensitive=case_sensitive)
@lru_cache(maxsize=256, typed=True)
def _compile_pattern(pat, case_sensitive):
if isinstance(pat, bytes):
pat_str = pat.decode('ISO-8859-1')
res_str = translate(pat_str)
res = res_str.encode('ISO-8859-1')
else:
res = translate(pat)
flags = 0 if case_sensitive else re.IGNORECASE
return re.compile(res, flags).match
|
Apache License 2.0
|
econforge/dolo.py
|
dolo/numeric/tensor.py
|
sdot
|
python
|
def sdot(U, V):
nu = U.ndim
return np.tensordot(U, V, axes=(nu - 1, 0))
|
Computes the tensorproduct reducing last dimensoin of U with first dimension of V.
For matrices, it is equal to regular matrix product.
|
https://github.com/econforge/dolo.py/blob/eff42d454816919c81f9daed1dc20bbf8676a89d/dolo/numeric/tensor.py#L48-L55
|
import numpy as np
def multidot_old(ten, mats):
resp = ten
n_d = ten.ndim
n_m = len(mats)
for i in range(n_m):
resp = np.tensordot(resp, mats[i], (n_d - n_m, 0))
return resp
def mdot_signature(M, *C):
M_syms = [chr(97 + e) for e in range(len(M))]
fC_syms = M_syms[-len(C) :]
ic = 97 + len(M_syms)
C_syms = []
for i in range(len(C)):
c_sym = [fC_syms[i]]
for j in range(len(C[i]) - 1):
c_sym.append(chr(ic))
ic += 1
C_syms.append(c_sym)
C_sig = [M_syms] + C_syms
out_sig = [M_syms[: -len(C)]] + [cc[1:] for cc in C_syms]
args = ",".join(["".join(g) for g in C_sig])
out = "".join(["".join(g) for g in out_sig])
return args + "->" + out
from numpy import einsum
def mdot(M, *C):
sig = mdot_signature(M.shape, *[c.shape for c in C])
return einsum(sig, M, *C)
|
BSD 2-Clause Simplified License
|
danielslater/alphatoe
|
techniques/train_supervised.py
|
train_supervised
|
python
|
def train_supervised(game_spec, create_network, network_file_path,
positions,
test_set_ratio=0.4,
regularization_coefficent=1e-5,
batch_size=100,
learn_rate=1e-4,
stop_turns_without_improvement = 7):
input_layer, output_layer, variables = create_network()
test_set_count = int(len(positions) * test_set_ratio)
train_set = positions[:-test_set_count]
test_set = positions[-test_set_count:]
actual_move_placeholder = tf.placeholder("float", (None, game_spec.outputs()))
error = tf.reduce_sum(tf.square(actual_move_placeholder - output_layer))
regularizer = None
for var in variables:
if regularizer is None:
regularizer = tf.nn.l2_loss(var)
else:
regularizer += tf.nn.l2_loss(var)
loss = error + regularizer * regularization_coefficent
train_step = tf.train.RMSPropOptimizer(learn_rate).minimize(loss)
correct_pred = tf.equal(tf.argmax(output_layer, 1), tf.argmax(actual_move_placeholder, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
with tf.Session() as session:
session.run(tf.global_variables_initializer())
if os.path.isfile(network_file_path):
print("loading existing network")
load_network(session, variables, network_file_path)
episode_number = 1
turns_without_test_improvement = 0
best_test_error, test_accuracy = session.run([error, accuracy],
feed_dict={
input_layer: [x[0] for x in test_set],
actual_move_placeholder: [x[1] for x in test_set]})
while True:
random.shuffle(train_set)
train_error = 0
for start_index in range(0, len(train_set) - batch_size + 1, batch_size):
mini_batch = train_set[start_index:start_index + batch_size]
batch_error, _ = session.run([error, train_step],
feed_dict={input_layer: [x[0] for x in mini_batch],
actual_move_placeholder: [x[1] for x in mini_batch]})
train_error += batch_error
new_test_error, test_accuracy = session.run([error, accuracy],
feed_dict={input_layer: [x[0] for x in test_set],
actual_move_placeholder: [x[1] for x in test_set]})
print("episode: %s train_error: %s test_error: %s test_acc: %s" %
(episode_number, train_error, new_test_error, test_accuracy))
if new_test_error < best_test_error:
best_test_error = new_test_error
turns_without_test_improvement = 0
else:
turns_without_test_improvement += 1
if turns_without_test_improvement > stop_turns_without_improvement:
train_accuracy = session.run([accuracy], feed_dict={input_layer: [x[0] for x in train_set],
actual_move_placeholder: [x[1] for x in
train_set]})
print("test error not improving for %s turns, ending training" % (stop_turns_without_improvement, ))
break
episode_number += 1
print("final episode: %s train_error: %s train acc: %s test_error: %s test_acc: %s" %
(episode_number, train_error, train_accuracy, new_test_error, test_accuracy))
save_network(session, variables, network_file_path)
return episode_number, train_error, train_accuracy, new_test_error, test_accuracy
|
Train a network using supervised learning using against a list of game positions and moves chosen.
We stop after we have had stop_turns_without_improvement without an improvement in the test error.
The test set is used as a validation set as well, will possibly improve this in the future to have a seperate test
and validation set.
Args:
stop_turns_without_improvement (int): we stop training after this many iterations without any improvement in
the test error.
regularization_coefficent (float): amount to multiply the l2 regularizer by in the loss function
test_set_ratio (float): portion of the data to divide into the test set,
positions ([(board_state, move)]): list of tuples of board states and the moves chosen in those board_states
game_spec (games.base_game_spec.BaseGameSpec): The game we are playing
create_network (->(input_layer : tf.placeholder, output_layer : tf.placeholder, variables : [tf.Variable])):
Method that creates the network we will train.
network_file_path (str): path to the file with weights we want to load for this network
learn_rate (float):
batch_size (int):
Returns:
episode_number, train_error, train_accuracy, new_test_error, test_accuracy
|
https://github.com/danielslater/alphatoe/blob/1220f4f883dbbd7ac1d84092bdaf04ca18a4dbc2/techniques/train_supervised.py#L9-L115
|
import os
import random
import tensorflow as tf
from common.network_helpers import save_network, load_network
|
MIT License
|
biasvariancelabs/aitlas
|
aitlas/base/datasets.py
|
BaseDataset.__getitem__
|
python
|
def __getitem__(self, index):
raise NotImplementedError(
"Please implement the `__getittem__` method for your dataset"
)
|
Implement here what you want to return
|
https://github.com/biasvariancelabs/aitlas/blob/20473cdd8c46211444b8ee742b944b07200a7d43/aitlas/base/datasets.py#L34-L38
|
import torch
from torch.utils.data import Dataset
from .config import Configurable
from .schemas import BaseDatasetSchema
from .transforms import load_transforms
class BaseDataset(Dataset, Configurable):
schema = BaseDatasetSchema
labels = None
name = None
def __init__(self, config):
Dataset.__init__(self)
Configurable.__init__(self, config)
self.shuffle = self.config.shuffle
self.batch_size = self.config.batch_size
self.num_workers = self.config.num_workers
self.pin_memory = self.config.pin_memory
if not self.labels and self.config.labels:
self.labels = self.config.labels
self.transform = self.load_transforms(self.config.transforms)
self.target_transform = self.load_transforms(self.config.target_transforms)
self.joint_transform = self.load_transforms(self.config.joint_transforms)
|
MIT License
|
ic-labs/django-icekit
|
icekit/workflow/admin.py
|
get_users_for_assigned_to
|
python
|
def get_users_for_assigned_to():
User = get_user_model()
return User.objects.filter(is_active=True, is_staff=True)
|
Return a list of users who can be assigned to workflow states
|
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/workflow/admin.py#L11-L14
|
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.admin import GenericTabularInline
from django import forms
from django.utils.text import Truncator
from . import models
|
MIT License
|
weasyl/weasyl
|
weasyl/resetpassword.py
|
_find_reset_target
|
python
|
def _find_reset_target(db, email):
matches = db.execute(
"SELECT userid, email, username FROM login"
" INNER JOIN profile USING (userid)"
' WHERE lower(email COLLATE "C") = lower(%(email)s COLLATE "C")',
email=email,
).fetchall()
for match in matches:
if match.email == email:
return match
return matches[0] if matches else None
|
Get information about the user whose password can be reset by access to the
provided normalized e-mail address, or None if there is no such user.
Matches the address case-insensitively, with priority given to a
case-sensitive match if there are multiple matches.
|
https://github.com/weasyl/weasyl/blob/80c86942c6f20a815086e2895fdad51d3aa77eed/weasyl/resetpassword.py#L35-L61
|
import hashlib
import string
from collections import namedtuple
from libweasyl import security
from weasyl import define as d
from weasyl import emailer
from weasyl.error import WeasylError
Unregistered = namedtuple('Unregistered', ['email'])
def _hash_token(token):
return hashlib.sha256(token.encode("ascii")).digest()
def request(email):
token = security.generate_key(25, key_characters=string.digits + string.ascii_lowercase)
token_sha256 = _hash_token(token)
email = emailer.normalize_address(email)
if email is None:
raise WeasylError("emailInvalid")
d.engine.execute(
"INSERT INTO forgotpassword (email, token_sha256)"
" VALUES (%(email)s, %(token_sha256)s)",
email=email, token_sha256=bytearray(token_sha256))
emailer.send(email, "Weasyl Account Recovery", d.render("email/reset_password.html", [token]))
|
Apache License 2.0
|
astropy/photutils
|
photutils/centroids/core.py
|
centroid_sources
|
python
|
def centroid_sources(data, xpos, ypos, box_size=11, footprint=None,
error=None, mask=None, centroid_func=centroid_com):
xpos = np.atleast_1d(xpos)
ypos = np.atleast_1d(ypos)
if xpos.ndim != 1:
raise ValueError('xpos must be a 1D array.')
if ypos.ndim != 1:
raise ValueError('ypos must be a 1D array.')
if footprint is None:
if box_size is None:
raise ValueError('box_size or footprint must be defined.')
box_size = np.atleast_1d(box_size)
if len(box_size) == 1:
box_size = np.repeat(box_size, 2)
if len(box_size) != 2:
raise ValueError('box_size must have 1 or 2 elements.')
footprint = np.ones(box_size, dtype=bool)
else:
footprint = np.asanyarray(footprint, dtype=bool)
if footprint.ndim != 2:
raise ValueError('footprint must be a 2D array.')
use_error = False
spec = inspect.getfullargspec(centroid_func)
if 'mask' not in spec.args:
raise ValueError('The input "centroid_func" must have a "mask" '
'keyword.')
if 'error' in spec.args:
use_error = True
xcentroids = []
ycentroids = []
for xp, yp in zip(xpos, ypos):
slices_large, slices_small = overlap_slices(data.shape,
footprint.shape, (yp, xp))
data_cutout = data[slices_large]
mask_cutout = None
if mask is not None:
mask_cutout = mask[slices_large]
footprint_mask = ~footprint
footprint_mask = footprint_mask[slices_small]
if mask_cutout is None:
mask_cutout = footprint_mask
else:
mask_cutout = np.logical_or(mask_cutout, footprint_mask)
kwargs = {'mask': mask_cutout}
if error is not None and use_error:
kwargs['error'] = error[slices_large]
xcen, ycen = centroid_func(data_cutout, **kwargs)
xcentroids.append(xcen + slices_large[1].start)
ycentroids.append(ycen + slices_large[0].start)
return np.array(xcentroids), np.array(ycentroids)
|
Calculate the centroid of sources at the defined positions.
A cutout image centered on each input position will be used to
calculate the centroid position. The cutout image is defined either
using the ``box_size`` or ``footprint`` keyword. The ``footprint``
keyword can be used to create a non-rectangular cutout image.
Parameters
----------
data : array_like
The 2D array of the image.
xpos, ypos : float or array-like of float
The initial ``x`` and ``y`` pixel position(s) of the center
position. A cutout image centered on this position be used to
calculate the centroid.
box_size : int or array-like of int, optional
The size of the cutout image along each axis. If ``box_size``
is a number, then a square cutout of ``box_size`` will be
created. If ``box_size`` has two elements, they should be in
``(ny, nx)`` order. Either ``box_size`` or ``footprint`` must be
defined. If they are both defined, then ``footprint`` overrides
``box_size``.
footprint : `~numpy.ndarray` of bools, optional
A 2D boolean array where `True` values describe the local
footprint region to cutout. ``footprint`` can be used to create
a non-rectangular cutout image, in which case the input ``xpos``
and ``ypos`` represent the center of the minimal bounding box
for the input ``footprint``. ``box_size=(n, m)`` is equivalent
to ``footprint=np.ones((n, m))``. Either ``box_size`` or
``footprint`` must be defined. If they are both defined, then
``footprint`` overrides ``box_size``.
mask : array_like, bool, optional
A 2D boolean array with the same shape as ``data``, where a
`True` value indicates the corresponding element of ``data`` is
masked.
error : array_like, optional
The 2D array of the 1-sigma errors of the input ``data``.
``error`` must have the same shape as ``data``. ``error`` will
be used only if supported by the input ``centroid_func``.
centroid_func : callable, optional
A callable object (e.g., function or class) that is used to
calculate the centroid of a 2D array. The ``centroid_func``
must accept a 2D `~numpy.ndarray`, have a ``mask`` keyword and
optionally an ``error`` keyword. The callable object must return
a tuple of two 1D `~numpy.ndarray`, representing the x and y
centroids. The default is `~photutils.centroids.centroid_com`.
Returns
-------
xcentroid, ycentroid : `~numpy.ndarray`
The ``x`` and ``y`` pixel position(s) of the centroids.
|
https://github.com/astropy/photutils/blob/17192d6ee4517514187fc01c7624fe6eb4b0e233/photutils/centroids/core.py#L271-L392
|
import inspect
import warnings
from astropy.nddata.utils import overlap_slices
from astropy.utils.decorators import deprecated
from astropy.utils.exceptions import AstropyUserWarning
import numpy as np
from ..utils._round import _py2intround
__all__ = ['centroid_com', 'centroid_quadratic', 'centroid_sources',
'centroid_epsf']
def centroid_com(data, mask=None, oversampling=1):
data = data.astype(float)
if mask is not None and mask is not np.ma.nomask:
mask = np.asarray(mask, dtype=bool)
if data.shape != mask.shape:
raise ValueError('data and mask must have the same shape.')
data[mask] = 0.
oversampling = np.atleast_1d(oversampling)
if len(oversampling) == 1:
oversampling = np.repeat(oversampling, 2)
oversampling = oversampling[::-1]
if np.any(oversampling <= 0):
raise ValueError('Oversampling factors must all be positive numbers.')
badmask = ~np.isfinite(data)
if np.any(badmask):
warnings.warn('Input data contains non-finite values (e.g., NaN or '
'inf) that were automatically masked.',
AstropyUserWarning)
data[badmask] = 0.
total = np.sum(data)
indices = np.ogrid[[slice(0, i) for i in data.shape]]
return np.array([np.sum(indices[axis] * data) / total / oversampling[axis]
for axis in range(data.ndim)])[::-1]
def centroid_quadratic(data, xpeak=None, ypeak=None, fit_boxsize=5,
search_boxsize=None, mask=None):
if ((xpeak is None and ypeak is not None)
or (xpeak is not None and ypeak is None)):
raise ValueError('xpeak and ypeak must both be input or "None"')
data = np.asanyarray(data, dtype=float)
ny, nx = data.shape
badmask = ~np.isfinite(data)
if np.any(badmask):
warnings.warn('Input data contains non-finite values (e.g., NaN or '
'inf) that were automatically masked.',
AstropyUserWarning)
data[badmask] = np.nan
if mask is not None:
if data.shape != mask.shape:
raise ValueError('data and mask must have the same shape.')
data[mask] = np.nan
fit_boxsize = _process_boxsize(fit_boxsize, data.shape)
if np.product(fit_boxsize) < 6:
raise ValueError('fit_boxsize is too small. 6 values are required '
'to fit a 2D quadratic polynomial.')
if xpeak is None:
yidx, xidx = np.unravel_index(np.nanargmax(data), data.shape)
else:
xidx = _py2intround(xpeak)
yidx = _py2intround(ypeak)
if search_boxsize is not None:
search_boxsize = _process_boxsize(search_boxsize, data.shape)
slc_data, _ = overlap_slices(data.shape, search_boxsize,
(yidx, xidx), mode='trim')
cutout = data[slc_data]
yidx, xidx = np.unravel_index(np.nanargmax(cutout), cutout.shape)
xidx += slc_data[1].start
yidx += slc_data[0].start
if xidx == 0 or xidx == nx - 1 or yidx == 0 or yidx == ny - 1:
warnings.warn('maximum value is at the edge of the data and its '
'position was returned; no quadratic fit was '
'performed', AstropyUserWarning)
return np.array((xidx, yidx), dtype=float)
slc_data, _ = overlap_slices(data.shape, fit_boxsize, (yidx, xidx),
mode='trim')
xidx0, xidx1 = (slc_data[1].start, slc_data[1].stop)
yidx0, yidx1 = (slc_data[0].start, slc_data[0].stop)
if (xidx1 - xidx0) < fit_boxsize[1]:
if xidx0 == 0:
xidx1 = min(nx, xidx0 + fit_boxsize[1])
if xidx1 == nx:
xidx0 = max(0, xidx1 - fit_boxsize[1])
if (yidx1 - yidx0) < fit_boxsize[0]:
if yidx0 == 0:
yidx1 = min(ny, yidx0 + fit_boxsize[0])
if yidx1 == ny:
yidx0 = max(0, yidx1 - fit_boxsize[0])
cutout = data[yidx0:yidx1, xidx0:xidx1].ravel()
if np.count_nonzero(~np.isnan(cutout)) < 6:
warnings.warn('at least 6 unmasked data points are required to '
'perform a 2D quadratic fit',
AstropyUserWarning)
return np.array((np.nan, np.nan))
xi = np.arange(xidx0, xidx1)
yi = np.arange(yidx0, yidx1)
x, y = np.meshgrid(xi, yi)
x = x.ravel()
y = y.ravel()
coeff_matrix = np.vstack((np.ones_like(x), x, y, x * y, x * x, y * y)).T
try:
c = np.linalg.lstsq(coeff_matrix, cutout, rcond=None)[0]
except np.linalg.LinAlgError:
warnings.warn('quadratic fit failed', AstropyUserWarning)
return np.array((np.nan, np.nan))
_, c10, c01, c11, c20, c02 = c
det = 4 * c20 * c02 - c11**2
if det <= 0 or ((c20 > 0.0 and c02 >= 0.0) or (c20 >= 0.0 and c02 > 0.0)):
warnings.warn('quadratic fit does not have a maximum',
AstropyUserWarning)
return np.array((np.nan, np.nan))
xm = (c01 * c11 - 2.0 * c02 * c10) / det
ym = (c10 * c11 - 2.0 * c20 * c01) / det
if 0.0 < xm < (nx - 1.0) and 0.0 < ym < (ny - 1.0):
xycen = np.array((xm, ym), dtype=float)
else:
warnings.warn('quadratic polynomial maximum value falls outside '
'of the image', AstropyUserWarning)
return np.array((np.nan, np.nan))
return xycen
def _process_boxsize(box_size, data_shape):
box_size = np.round(np.atleast_1d(box_size)).astype(int)
if len(box_size) == 1:
box_size = np.repeat(box_size, 2)
if len(box_size) > 2:
raise ValueError('box size must contain only 1 or 2 values')
if np.any(box_size < 0):
raise ValueError('box size must be >= 0')
box_size = (min(box_size[0], data_shape[0]),
min(box_size[1], data_shape[1]))
return box_size
|
BSD 3-Clause New or Revised License
|
reiinakano/scikit-plot
|
scikitplot/metrics.py
|
plot_calibration_curve
|
python
|
def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
y_true = np.asarray(y_true)
if not isinstance(probas_list, list):
raise ValueError('`probas_list` does not contain a list.')
classes = np.unique(y_true)
if len(classes) > 2:
raise ValueError('plot_calibration_curve only '
'works for binary classification')
if clf_names is None:
clf_names = ['Classifier {}'.format(x+1)
for x in range(len(probas_list))]
if len(clf_names) != len(probas_list):
raise ValueError('Length {} of `clf_names` does not match length {} of'
' `probas_list`'.format(len(clf_names),
len(probas_list)))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
for i, probas in enumerate(probas_list):
probas = np.asarray(probas)
if probas.ndim > 2:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
if probas.ndim == 2:
probas = probas[:, 1]
if probas.shape != y_true.shape:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
probas = (probas - probas.min()) / (probas.max() - probas.min())
fraction_of_positives, mean_predicted_value = calibration_curve(y_true, probas, n_bins=n_bins)
color = plt.cm.get_cmap(cmap)(float(i) / len(probas_list))
ax.plot(mean_predicted_value, fraction_of_positives, 's-',
label=clf_names[i], color=color)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel('Mean predicted value', fontsize=text_fontsize)
ax.set_ylabel('Fraction of positives', fontsize=text_fontsize)
ax.set_ylim([-0.05, 1.05])
ax.legend(loc='lower right')
return ax
|
Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves
|
https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/metrics.py#L911-L1042
|
from __future__ import absolute_import, division, print_function, unicode_literals
import itertools
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import label_binarize
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import silhouette_score
from sklearn.metrics import silhouette_samples
from sklearn.calibration import calibration_curve
from sklearn.utils import deprecated
from scipy import interp
from scikitplot.helpers import binary_ks_curve, validate_labels
from scikitplot.helpers import cumulative_gain_curve
def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, hide_counts=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
text_fontsize="medium"):
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
cm = confusion_matrix(y_true, y_pred, labels=labels)
if labels is None:
classes = unique_labels(y_true, y_pred)
else:
classes = np.asarray(labels)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = np.around(cm, decimals=2)
cm[np.isnan(cm)] = 0.0
if true_labels is None:
true_classes = classes
else:
validate_labels(classes, true_labels, "true_labels")
true_label_indexes = np.in1d(classes, true_labels)
true_classes = classes[true_label_indexes]
cm = cm[true_label_indexes]
if pred_labels is None:
pred_classes = classes
else:
validate_labels(classes, pred_labels, "pred_labels")
pred_label_indexes = np.in1d(classes, pred_labels)
pred_classes = classes[pred_label_indexes]
cm = cm[:, pred_label_indexes]
if title:
ax.set_title(title, fontsize=title_fontsize)
elif normalize:
ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)
else:
ax.set_title('Confusion Matrix', fontsize=title_fontsize)
image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))
plt.colorbar(mappable=image)
x_tick_marks = np.arange(len(pred_classes))
y_tick_marks = np.arange(len(true_classes))
ax.set_xticks(x_tick_marks)
ax.set_xticklabels(pred_classes, fontsize=text_fontsize,
rotation=x_tick_rotation)
ax.set_yticks(y_tick_marks)
ax.set_yticklabels(true_classes, fontsize=text_fontsize)
thresh = cm.max() / 2.
if not hide_counts:
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if not (hide_zeros and cm[i, j] == 0):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
verticalalignment="center",
fontsize=text_fontsize,
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label', fontsize=text_fontsize)
ax.set_xlabel('Predicted label', fontsize=text_fontsize)
ax.grid(False)
return ax
@deprecated('This will be removed in v0.5.0. Please use '
'scikitplot.metrics.plot_roc instead.')
def plot_roc_curve(y_true, y_probas, title='ROC Curves',
curves=('micro', 'macro', 'each_class'),
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
y_true = np.array(y_true)
y_probas = np.array(y_probas)
if 'micro' not in curves and 'macro' not in curves and 'each_class' not in curves:
raise ValueError('Invalid argument for curves as it '
'only takes "micro", "macro", or "each_class"')
classes = np.unique(y_true)
probas = y_probas
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(len(classes)):
fpr[i], tpr[i], _ = roc_curve(y_true, probas[:, i],
pos_label=classes[i])
roc_auc[i] = auc(fpr[i], tpr[i])
micro_key = 'micro'
i = 0
while micro_key in fpr:
i += 1
micro_key += str(i)
y_true = label_binarize(y_true, classes=classes)
if len(classes) == 2:
y_true = np.hstack((1 - y_true, y_true))
fpr[micro_key], tpr[micro_key], _ = roc_curve(y_true.ravel(),
probas.ravel())
roc_auc[micro_key] = auc(fpr[micro_key], tpr[micro_key])
all_fpr = np.unique(np.concatenate([fpr[x] for x in range(len(classes))]))
mean_tpr = np.zeros_like(all_fpr)
for i in range(len(classes)):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(classes)
macro_key = 'macro'
i = 0
while macro_key in fpr:
i += 1
macro_key += str(i)
fpr[macro_key] = all_fpr
tpr[macro_key] = mean_tpr
roc_auc[macro_key] = auc(fpr[macro_key], tpr[macro_key])
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
if 'each_class' in curves:
for i in range(len(classes)):
color = plt.cm.get_cmap(cmap)(float(i) / len(classes))
ax.plot(fpr[i], tpr[i], lw=2, color=color,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(classes[i], roc_auc[i]))
if 'micro' in curves:
ax.plot(fpr[micro_key], tpr[micro_key],
label='micro-average ROC curve '
'(area = {0:0.2f})'.format(roc_auc[micro_key]),
color='deeppink', linestyle=':', linewidth=4)
if 'macro' in curves:
ax.plot(fpr[macro_key], tpr[macro_key],
label='macro-average ROC curve '
'(area = {0:0.2f})'.format(roc_auc[macro_key]),
color='navy', linestyle=':', linewidth=4)
ax.plot([0, 1], [0, 1], 'k--', lw=2)
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('False Positive Rate', fontsize=text_fontsize)
ax.set_ylabel('True Positive Rate', fontsize=text_fontsize)
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='lower right', fontsize=text_fontsize)
return ax
def plot_roc(y_true, y_probas, title='ROC Curves',
plot_micro=True, plot_macro=True, classes_to_plot=None,
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
y_true = np.array(y_true)
y_probas = np.array(y_probas)
classes = np.unique(y_true)
probas = y_probas
if classes_to_plot is None:
classes_to_plot = classes
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
fpr_dict = dict()
tpr_dict = dict()
indices_to_plot = np.in1d(classes, classes_to_plot)
for i, to_plot in enumerate(indices_to_plot):
fpr_dict[i], tpr_dict[i], _ = roc_curve(y_true, probas[:, i],
pos_label=classes[i])
if to_plot:
roc_auc = auc(fpr_dict[i], tpr_dict[i])
color = plt.cm.get_cmap(cmap)(float(i) / len(classes))
ax.plot(fpr_dict[i], tpr_dict[i], lw=2, color=color,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(classes[i], roc_auc))
if plot_micro:
binarized_y_true = label_binarize(y_true, classes=classes)
if len(classes) == 2:
binarized_y_true = np.hstack(
(1 - binarized_y_true, binarized_y_true))
fpr, tpr, _ = roc_curve(binarized_y_true.ravel(), probas.ravel())
roc_auc = auc(fpr, tpr)
ax.plot(fpr, tpr,
label='micro-average ROC curve '
'(area = {0:0.2f})'.format(roc_auc),
color='deeppink', linestyle=':', linewidth=4)
if plot_macro:
all_fpr = np.unique(np.concatenate([fpr_dict[x] for x in range(len(classes))]))
mean_tpr = np.zeros_like(all_fpr)
for i in range(len(classes)):
mean_tpr += interp(all_fpr, fpr_dict[i], tpr_dict[i])
mean_tpr /= len(classes)
roc_auc = auc(all_fpr, mean_tpr)
ax.plot(all_fpr, mean_tpr,
label='macro-average ROC curve '
'(area = {0:0.2f})'.format(roc_auc),
color='navy', linestyle=':', linewidth=4)
ax.plot([0, 1], [0, 1], 'k--', lw=2)
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('False Positive Rate', fontsize=text_fontsize)
ax.set_ylabel('True Positive Rate', fontsize=text_fontsize)
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='lower right', fontsize=text_fontsize)
return ax
def plot_ks_statistic(y_true, y_probas, title='KS Statistic Plot',
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
y_true = np.array(y_true)
y_probas = np.array(y_probas)
classes = np.unique(y_true)
if len(classes) != 2:
raise ValueError('Cannot calculate KS statistic for data with '
'{} category/ies'.format(len(classes)))
probas = y_probas
thresholds, pct1, pct2, ks_statistic, max_distance_at, classes = binary_ks_curve(y_true,
probas[:, 1].ravel())
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
ax.plot(thresholds, pct1, lw=3, label='Class {}'.format(classes[0]))
ax.plot(thresholds, pct2, lw=3, label='Class {}'.format(classes[1]))
idx = np.where(thresholds == max_distance_at)[0][0]
ax.axvline(max_distance_at, *sorted([pct1[idx], pct2[idx]]),
label='KS Statistic: {:.3f} at {:.3f}'.format(ks_statistic,
max_distance_at),
linestyle=':', lw=3, color='black')
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.0])
ax.set_xlabel('Threshold', fontsize=text_fontsize)
ax.set_ylabel('Percentage below threshold', fontsize=text_fontsize)
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='lower right', fontsize=text_fontsize)
return ax
@deprecated('This will be removed in v0.5.0. Please use '
'scikitplot.metrics.plot_precision_recall instead.')
def plot_precision_recall_curve(y_true, y_probas,
title='Precision-Recall Curve',
curves=('micro', 'each_class'), ax=None,
figsize=None, cmap='nipy_spectral',
title_fontsize="large",
text_fontsize="medium"):
y_true = np.array(y_true)
y_probas = np.array(y_probas)
classes = np.unique(y_true)
probas = y_probas
if 'micro' not in curves and 'each_class' not in curves:
raise ValueError('Invalid argument for curves as it '
'only takes "micro" or "each_class"')
precision = dict()
recall = dict()
average_precision = dict()
for i in range(len(classes)):
precision[i], recall[i], _ = precision_recall_curve(
y_true, probas[:, i], pos_label=classes[i])
y_true = label_binarize(y_true, classes=classes)
if len(classes) == 2:
y_true = np.hstack((1 - y_true, y_true))
for i in range(len(classes)):
average_precision[i] = average_precision_score(y_true[:, i],
probas[:, i])
micro_key = 'micro'
i = 0
while micro_key in precision:
i += 1
micro_key += str(i)
precision[micro_key], recall[micro_key], _ = precision_recall_curve(
y_true.ravel(), probas.ravel())
average_precision[micro_key] = average_precision_score(y_true, probas,
average='micro')
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
if 'each_class' in curves:
for i in range(len(classes)):
color = plt.cm.get_cmap(cmap)(float(i) / len(classes))
ax.plot(recall[i], precision[i], lw=2,
label='Precision-recall curve of class {0} '
'(area = {1:0.3f})'.format(classes[i],
average_precision[i]),
color=color)
if 'micro' in curves:
ax.plot(recall[micro_key], precision[micro_key],
label='micro-average Precision-recall curve '
'(area = {0:0.3f})'.format(average_precision[micro_key]),
color='navy', linestyle=':', linewidth=4)
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('Recall')
ax.set_ylabel('Precision')
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax
def plot_precision_recall(y_true, y_probas,
title='Precision-Recall Curve',
plot_micro=True,
classes_to_plot=None, ax=None,
figsize=None, cmap='nipy_spectral',
title_fontsize="large",
text_fontsize="medium"):
y_true = np.array(y_true)
y_probas = np.array(y_probas)
classes = np.unique(y_true)
probas = y_probas
if classes_to_plot is None:
classes_to_plot = classes
binarized_y_true = label_binarize(y_true, classes=classes)
if len(classes) == 2:
binarized_y_true = np.hstack(
(1 - binarized_y_true, binarized_y_true))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
indices_to_plot = np.in1d(classes, classes_to_plot)
for i, to_plot in enumerate(indices_to_plot):
if to_plot:
average_precision = average_precision_score(
binarized_y_true[:, i],
probas[:, i])
precision, recall, _ = precision_recall_curve(
y_true, probas[:, i], pos_label=classes[i])
color = plt.cm.get_cmap(cmap)(float(i) / len(classes))
ax.plot(recall, precision, lw=2,
label='Precision-recall curve of class {0} '
'(area = {1:0.3f})'.format(classes[i],
average_precision),
color=color)
if plot_micro:
precision, recall, _ = precision_recall_curve(
binarized_y_true.ravel(), probas.ravel())
average_precision = average_precision_score(binarized_y_true,
probas,
average='micro')
ax.plot(recall, precision,
label='micro-average Precision-recall curve '
'(area = {0:0.3f})'.format(average_precision),
color='navy', linestyle=':', linewidth=4)
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('Recall')
ax.set_ylabel('Precision')
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax
def plot_silhouette(X, cluster_labels, title='Silhouette Analysis',
metric='euclidean', copy=True, ax=None, figsize=None,
cmap='nipy_spectral', title_fontsize="large",
text_fontsize="medium"):
cluster_labels = np.asarray(cluster_labels)
le = LabelEncoder()
cluster_labels_encoded = le.fit_transform(cluster_labels)
n_clusters = len(np.unique(cluster_labels))
silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
sample_silhouette_values = silhouette_samples(X, cluster_labels,
metric=metric)
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlim([-0.1, 1])
ax.set_ylim([0, len(X) + (n_clusters + 1) * 10 + 10])
ax.set_xlabel('Silhouette coefficient values', fontsize=text_fontsize)
ax.set_ylabel('Cluster label', fontsize=text_fontsize)
y_lower = 10
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[
cluster_labels_encoded == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = plt.cm.get_cmap(cmap)(float(i) / n_clusters)
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(le.classes_[i]),
fontsize=text_fontsize)
y_lower = y_upper + 10
ax.axvline(x=silhouette_avg, color="red", linestyle="--",
label='Silhouette score: {0:0.3f}'.format(silhouette_avg))
ax.set_yticks([])
ax.set_xticks(np.arange(-0.1, 1.0, 0.2))
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax
|
MIT License
|
educational-technology-collective/morf
|
morf-python-api/build/lib/morf/workflow/evaluate.py
|
evaluate_all
|
python
|
def evaluate_all():
return
|
Fetch metrics overall.
:return:
|
https://github.com/educational-technology-collective/morf/blob/f17afcacef68929a5ce9e7714208be1002a42418/morf-python-api/build/lib/morf/workflow/evaluate.py#L112-L118
|
import numpy as np
import sklearn.metrics
from morf.utils.api_utils import *
from morf.utils.config import MorfJobConfig
from morf.utils.job_runner_utils import load_docker_image
from morf.utils.log import set_logger_handlers
from morf.utils.security import hash_df_column
from morf.utils.s3interface import make_s3_key_path
mode = "evaluate"
CONFIG_FILENAME = "config.properties"
module_logger = logging.getLogger(__name__)
def check_dataframe_complete(df, job_config, columns):
logger = set_logger_handlers(module_logger, job_config)
logger.info("[INFO] checking predictions")
courses = [x[0] for x in fetch_all_complete_courses_and_sessions(job_config)]
df_to_check = df[df.course.isin(courses)]
null_counts = df_to_check.loc[:,columns].apply(lambda x: sum(x.isnull()), axis=0)
if null_counts.sum() > 0:
logger.error("Null values detected in the following columns: {} \n Did you include predicted probabilities and labels for all users?".format(null_counts.loc[null_counts > 0].index.tolist()))
missing_courses = df_to_check[df_to_check.prob.isnull()]['course'].unique()
logger.error("missing values detected in these courses: {}".format(missing_courses))
raise
else:
return
def fetch_binary_classification_metrics(job_config, df, course, pred_prob_col = "prob", pred_col = "pred",
label_col = "label_value", course_col = "course"):
logger = set_logger_handlers(module_logger, job_config)
logger.info("fetching metrics for course {}".format(course))
df = df[df[course_col] == course]
metrics = {}
y_pred = df[pred_col].values.astype(float)
y_true = df[label_col].values.astype(float)
y_score = df[pred_prob_col].values
metrics["accuracy"] = sklearn.metrics.accuracy_score(y_true, y_pred)
try:
metrics["auc"] = sklearn.metrics.roc_auc_score(y_true, y_score)
metrics["log_loss"] = sklearn.metrics.log_loss(y_true, y_score)
metrics["precision"] = sklearn.metrics.precision_score(y_true, y_pred)
metrics["recall"] = sklearn.metrics.recall_score(y_true, y_pred)
metrics["f1_score"] = sklearn.metrics.f1_score(y_true, y_pred)
except ValueError:
logger.warning("Only one class present in y_true for course {}. ROC AUC score, log_loss, precision, recall, F1 are undefined.".format(course))
metrics["auc"] = np.nan
metrics["log_loss"] = np.nan
metrics["precision"] = np.nan
metrics["recall"] = np.nan
metrics["f1_score"] = np.nan
metrics["cohen_kappa_score"] = sklearn.metrics.cohen_kappa_score(y_true, y_pred)
metrics["N"] = df.shape[0]
metrics["N_n"] = df[label_col].value_counts().get(0,0)
metrics["N_p"] = df[label_col].value_counts().get(1,0)
cm = sklearn.metrics.confusion_matrix(y_true, y_pred)
try:
spec = cm[0,0] / float(cm[0,0] + cm[1,0])
except Exception as e:
print("[ERROR] error when computing specificity from confusion matrix: {}".format(e))
print("confusion matrix is: {}".format(cm))
spec = np.nan
metrics["specificity"] = spec
metrics_df = pd.DataFrame(metrics, index = [course])
return metrics_df
|
MIT License
|
opennetworkingfoundation/tapi
|
RI/flask_server/tapi_server/models/tapi_topology_node_owned_node_edge_point.py
|
TapiTopologyNodeOwnedNodeEdgePoint.cep_list
|
python
|
def cep_list(self, cep_list):
self._cep_list = cep_list
|
Sets the cep_list of this TapiTopologyNodeOwnedNodeEdgePoint.
:param cep_list: The cep_list of this TapiTopologyNodeOwnedNodeEdgePoint.
:type cep_list: TapiConnectivityContextTopologycontextTopologyNodeOwnednodeedgepointCepList
|
https://github.com/opennetworkingfoundation/tapi/blob/1f3fd9483d5674552c5a31206c97399c8c151897/RI/flask_server/tapi_server/models/tapi_topology_node_owned_node_edge_point.py#L160-L168
|
from __future__ import absolute_import
from datetime import date, datetime
from typing import List, Dict
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_common_administrative_state import TapiCommonAdministrativeState
from tapi_server.models.tapi_common_capacity import TapiCommonCapacity
from tapi_server.models.tapi_common_layer_protocol_name import TapiCommonLayerProtocolName
from tapi_server.models.tapi_common_lifecycle_state import TapiCommonLifecycleState
from tapi_server.models.tapi_common_name_and_value import TapiCommonNameAndValue
from tapi_server.models.tapi_common_operational_state import TapiCommonOperationalState
from tapi_server.models.tapi_common_port_direction import TapiCommonPortDirection
from tapi_server.models.tapi_common_port_role import TapiCommonPortRole
from tapi_server.models.tapi_common_service_interface_point_ref import TapiCommonServiceInterfacePointRef
from tapi_server.models.tapi_common_termination_direction import TapiCommonTerminationDirection
from tapi_server.models.tapi_common_termination_state import TapiCommonTerminationState
from tapi_server.models.tapi_connectivity_context_topologycontext_topology_node_ownednodeedgepoint_cep_list import TapiConnectivityContextTopologycontextTopologyNodeOwnednodeedgepointCepList
from tapi_server.models.tapi_connectivity_owned_node_edge_point_augmentation3 import TapiConnectivityOwnedNodeEdgePointAugmentation3
from tapi_server.models.tapi_odu_odu_node_edge_point_spec import TapiOduOduNodeEdgePointSpec
from tapi_server.models.tapi_odu_owned_node_edge_point_augmentation1 import TapiOduOwnedNodeEdgePointAugmentation1
from tapi_server.models.tapi_photonic_media_media_channel_node_edge_point_spec import TapiPhotonicMediaMediaChannelNodeEdgePointSpec
from tapi_server.models.tapi_photonic_media_owned_node_edge_point_augmentation2 import TapiPhotonicMediaOwnedNodeEdgePointAugmentation2
from tapi_server.models.tapi_topology_node_edge_point import TapiTopologyNodeEdgePoint
from tapi_server.models.tapi_topology_node_edge_point_ref import TapiTopologyNodeEdgePointRef
from tapi_server import util
class TapiTopologyNodeOwnedNodeEdgePoint(Model):
def __init__(self, cep_list=None, odu_node_edge_point_spec=None, media_channel_node_edge_point_spec=None, operational_state=None, lifecycle_state=None, administrative_state=None, available_capacity=None, total_potential_capacity=None, name=None, uuid=None, termination_direction=None, termination_state=None, link_port_role=None, mapped_service_interface_point=None, aggregated_node_edge_point=None, layer_protocol_name=None, link_port_direction=None, supported_cep_layer_protocol_qualifier=None):
self.openapi_types = {
'cep_list': TapiConnectivityContextTopologycontextTopologyNodeOwnednodeedgepointCepList,
'odu_node_edge_point_spec': TapiOduOduNodeEdgePointSpec,
'media_channel_node_edge_point_spec': TapiPhotonicMediaMediaChannelNodeEdgePointSpec,
'operational_state': TapiCommonOperationalState,
'lifecycle_state': TapiCommonLifecycleState,
'administrative_state': TapiCommonAdministrativeState,
'available_capacity': TapiCommonCapacity,
'total_potential_capacity': TapiCommonCapacity,
'name': List[TapiCommonNameAndValue],
'uuid': str,
'termination_direction': TapiCommonTerminationDirection,
'termination_state': TapiCommonTerminationState,
'link_port_role': TapiCommonPortRole,
'mapped_service_interface_point': List[TapiCommonServiceInterfacePointRef],
'aggregated_node_edge_point': List[TapiTopologyNodeEdgePointRef],
'layer_protocol_name': TapiCommonLayerProtocolName,
'link_port_direction': TapiCommonPortDirection,
'supported_cep_layer_protocol_qualifier': List[str]
}
self.attribute_map = {
'cep_list': 'cep-list',
'odu_node_edge_point_spec': 'odu-node-edge-point-spec',
'media_channel_node_edge_point_spec': 'media-channel-node-edge-point-spec',
'operational_state': 'operational-state',
'lifecycle_state': 'lifecycle-state',
'administrative_state': 'administrative-state',
'available_capacity': 'available-capacity',
'total_potential_capacity': 'total-potential-capacity',
'name': 'name',
'uuid': 'uuid',
'termination_direction': 'termination-direction',
'termination_state': 'termination-state',
'link_port_role': 'link-port-role',
'mapped_service_interface_point': 'mapped-service-interface-point',
'aggregated_node_edge_point': 'aggregated-node-edge-point',
'layer_protocol_name': 'layer-protocol-name',
'link_port_direction': 'link-port-direction',
'supported_cep_layer_protocol_qualifier': 'supported-cep-layer-protocol-qualifier'
}
self._cep_list = cep_list
self._odu_node_edge_point_spec = odu_node_edge_point_spec
self._media_channel_node_edge_point_spec = media_channel_node_edge_point_spec
self._operational_state = operational_state
self._lifecycle_state = lifecycle_state
self._administrative_state = administrative_state
self._available_capacity = available_capacity
self._total_potential_capacity = total_potential_capacity
self._name = name
self._uuid = uuid
self._termination_direction = termination_direction
self._termination_state = termination_state
self._link_port_role = link_port_role
self._mapped_service_interface_point = mapped_service_interface_point
self._aggregated_node_edge_point = aggregated_node_edge_point
self._layer_protocol_name = layer_protocol_name
self._link_port_direction = link_port_direction
self._supported_cep_layer_protocol_qualifier = supported_cep_layer_protocol_qualifier
@classmethod
def from_dict(cls, dikt) -> 'TapiTopologyNodeOwnedNodeEdgePoint':
return util.deserialize_model(dikt, cls)
@property
def cep_list(self):
return self._cep_list
@cep_list.setter
|
Apache License 2.0
|
blacktear23/py-servicebus
|
servicebus/pika/connection.py
|
Connection.consumer_cancel_notify
|
python
|
def consumer_cancel_notify(self):
return self.server_capabilities.get('consumer_cancel_notify', False)
|
Specifies if the server supports consumer cancel notification on the
active connection.
:rtype: bool
|
https://github.com/blacktear23/py-servicebus/blob/c3d6ccf0b2abf131ca1060d89f3c0d4ab08481e4/servicebus/pika/connection.py#L809-L816
|
import ast
import sys
import collections
import logging
import math
import platform
import threading
import urllib
import warnings
if sys.version_info > (3,):
import urllib.parse as urlparse
else:
import urlparse
from servicebus.pika import __version__
from servicebus.pika import callback
from servicebus.pika import channel
from servicebus.pika import credentials as pika_credentials
from servicebus.pika import exceptions
from servicebus.pika import frame
from servicebus.pika import heartbeat
from servicebus.pika import utils
from servicebus.pika import spec
from servicebus.pika.compat import basestring, url_unquote, dictkeys
BACKPRESSURE_WARNING = ("Pika: Write buffer exceeded warning threshold at "
"%i bytes and an estimated %i frames behind")
PRODUCT = "Pika Python Client Library"
LOGGER = logging.getLogger(__name__)
class Parameters(object):
DEFAULT_BACKPRESSURE_DETECTION = False
DEFAULT_CONNECTION_ATTEMPTS = 1
DEFAULT_CHANNEL_MAX = 0
DEFAULT_FRAME_MAX = spec.FRAME_MAX_SIZE
DEFAULT_HEARTBEAT_INTERVAL = None
DEFAULT_HOST = 'localhost'
DEFAULT_LOCALE = 'en_US'
DEFAULT_PASSWORD = 'guest'
DEFAULT_PORT = 5672
DEFAULT_RETRY_DELAY = 2.0
DEFAULT_SOCKET_TIMEOUT = 0.25
DEFAULT_SSL = False
DEFAULT_SSL_OPTIONS = {}
DEFAULT_SSL_PORT = 5671
DEFAULT_USERNAME = 'guest'
DEFAULT_VIRTUAL_HOST = '/'
def __init__(self):
self.virtual_host = self.DEFAULT_VIRTUAL_HOST
self.backpressure_detection = self.DEFAULT_BACKPRESSURE_DETECTION
self.channel_max = self.DEFAULT_CHANNEL_MAX
self.connection_attempts = self.DEFAULT_CONNECTION_ATTEMPTS
self.credentials = self._credentials(self.DEFAULT_USERNAME,
self.DEFAULT_PASSWORD)
self.frame_max = self.DEFAULT_FRAME_MAX
self.heartbeat = self.DEFAULT_HEARTBEAT_INTERVAL
self.host = self.DEFAULT_HOST
self.locale = self.DEFAULT_LOCALE
self.port = self.DEFAULT_PORT
self.retry_delay = self.DEFAULT_RETRY_DELAY
self.ssl = self.DEFAULT_SSL
self.ssl_options = self.DEFAULT_SSL_OPTIONS
self.socket_timeout = self.DEFAULT_SOCKET_TIMEOUT
def __repr__(self):
return ('<%s host=%s port=%s virtual_host=%s ssl=%s>' %
(self.__class__.__name__, self.host, self.port,
self.virtual_host, self.ssl))
def _credentials(self, username, password):
return pika_credentials.PlainCredentials(username, password)
def _validate_backpressure(self, backpressure_detection):
if not isinstance(backpressure_detection, bool):
raise TypeError('backpressure detection must be a bool')
return True
def _validate_channel_max(self, channel_max):
if not isinstance(channel_max, int):
raise TypeError('channel_max must be an int')
if channel_max < 1 or channel_max > 65535:
raise ValueError('channel_max must be <= 65535 and > 0')
return True
def _validate_connection_attempts(self, connection_attempts):
if not isinstance(connection_attempts, int):
raise TypeError('connection_attempts must be an int')
if connection_attempts < 1:
raise ValueError('connection_attempts must be None or > 0')
return True
def _validate_credentials(self, credentials):
for credential_type in pika_credentials.VALID_TYPES:
if isinstance(credentials, credential_type):
return True
raise TypeError('Credentials must be an object of type: %r' %
pika_credentials.VALID_TYPES)
def _validate_frame_max(self, frame_max):
if not isinstance(frame_max, int):
raise TypeError('frame_max must be an int')
if frame_max < spec.FRAME_MIN_SIZE:
raise exceptions.InvalidMinimumFrameSize
elif frame_max > spec.FRAME_MAX_SIZE:
raise exceptions.InvalidMaximumFrameSize
return True
def _validate_heartbeat_interval(self, heartbeat_interval):
if not isinstance(heartbeat_interval, int):
raise TypeError('heartbeat must be an int')
if heartbeat_interval < 0:
raise ValueError('heartbeat_interval must >= 0')
return True
def _validate_host(self, host):
if not isinstance(host, basestring):
raise TypeError('host must be a str or unicode str')
return True
def _validate_locale(self, locale):
if not isinstance(locale, basestring):
raise TypeError('locale must be a str')
return True
def _validate_port(self, port):
if not isinstance(port, int):
raise TypeError('port must be an int')
return True
def _validate_retry_delay(self, retry_delay):
if not any([isinstance(retry_delay, int),
isinstance(retry_delay, float)]):
raise TypeError('retry_delay must be a float or int')
return True
def _validate_socket_timeout(self, socket_timeout):
if not any([isinstance(socket_timeout, int),
isinstance(socket_timeout, float)]):
raise TypeError('socket_timeout must be a float or int')
if not socket_timeout > 0:
raise ValueError('socket_timeout must be > 0')
return True
def _validate_ssl(self, ssl):
if not isinstance(ssl, bool):
raise TypeError('ssl must be a bool')
return True
def _validate_ssl_options(self, ssl_options):
if not isinstance(ssl_options, dict) and ssl_options is not None:
raise TypeError('ssl_options must be either None or dict')
return True
def _validate_virtual_host(self, virtual_host):
if not isinstance(virtual_host, basestring):
raise TypeError('virtual_host must be a str')
return True
class ConnectionParameters(Parameters):
def __init__(self,
host=None,
port=None,
virtual_host=None,
credentials=None,
channel_max=None,
frame_max=None,
heartbeat_interval=None,
ssl=None,
ssl_options=None,
connection_attempts=None,
retry_delay=None,
socket_timeout=None,
locale=None,
backpressure_detection=None):
super(ConnectionParameters, self).__init__()
if not credentials:
credentials = self._credentials(self.DEFAULT_USERNAME,
self.DEFAULT_PASSWORD)
if host and self._validate_host(host):
self.host = host
if port is not None and self._validate_port(port):
self.port = port
if virtual_host and self._validate_virtual_host(virtual_host):
self.virtual_host = virtual_host
if credentials and self._validate_credentials(credentials):
self.credentials = credentials
if channel_max is not None and self._validate_channel_max(channel_max):
self.channel_max = channel_max
if frame_max is not None and self._validate_frame_max(frame_max):
self.frame_max = frame_max
if locale and self._validate_locale(locale):
self.locale = locale
if (heartbeat_interval is not None and self._validate_heartbeat_interval(heartbeat_interval)):
self.heartbeat = heartbeat_interval
if ssl is not None and self._validate_ssl(ssl):
self.ssl = ssl
if ssl_options and self._validate_ssl_options(ssl_options):
self.ssl_options = ssl_options or dict()
if (connection_attempts is not None and self._validate_connection_attempts(connection_attempts)):
self.connection_attempts = connection_attempts
if retry_delay is not None and self._validate_retry_delay(retry_delay):
self.retry_delay = retry_delay
if (socket_timeout is not None and self._validate_socket_timeout(socket_timeout)):
self.socket_timeout = socket_timeout
if (backpressure_detection is not None and self._validate_backpressure(backpressure_detection)):
self.backpressure_detection = backpressure_detection
class URLParameters(Parameters):
def __init__(self, url):
super(URLParameters, self).__init__()
self._process_url(url)
def _process_url(self, url):
if url[0:4] == 'amqp':
url = 'http' + url[4:]
parts = urlparse.urlparse(url)
if parts.scheme == 'https':
self.ssl = True
if self._validate_host(parts.hostname):
self.host = parts.hostname
if not parts.port:
if self.ssl:
self.port = self.DEFAULT_SSL_PORT if self.ssl else self.DEFAULT_PORT
elif self._validate_port(parts.port):
self.port = parts.port
if parts.username is not None:
self.credentials = pika_credentials.PlainCredentials(parts.username,
parts.password)
if len(parts.path) <= 1:
self.virtual_host = self.DEFAULT_VIRTUAL_HOST
else:
path_parts = parts.path.split('/')
virtual_host = url_unquote(path_parts[1])
if self._validate_virtual_host(virtual_host):
self.virtual_host = virtual_host
values = urlparse.parse_qs(parts.query)
for key in dictkeys(values):
values[key] = values[key].pop(0)
if values[key].isdigit():
values[key] = int(values[key])
else:
try:
values[key] = float(values[key])
except ValueError:
pass
if 'backpressure_detection' in values:
if values['backpressure_detection'] == 't':
self.backpressure_detection = True
elif values['backpressure_detection'] == 'f':
self.backpressure_detection = False
else:
raise ValueError('Invalid backpressure_detection value: %s' %
values['backpressure_detection'])
if ('channel_max' in values and self._validate_channel_max(values['channel_max'])):
self.channel_max = values['channel_max']
if ('connection_attempts' in values and self._validate_connection_attempts(values['connection_attempts'])):
self.connection_attempts = values['connection_attempts']
if ('frame_max' in values and self._validate_frame_max(values['frame_max'])):
self.frame_max = values['frame_max']
if ('heartbeat_interval' in values and self._validate_heartbeat_interval(values['heartbeat_interval'])):
self.heartbeat = values['heartbeat_interval']
if ('locale' in values and self._validate_locale(values['locale'])):
self.locale = values['locale']
if ('retry_delay' in values and self._validate_retry_delay(values['retry_delay'])):
self.retry_delay = values['retry_delay']
if ('socket_timeout' in values and self._validate_socket_timeout(values['socket_timeout'])):
self.socket_timeout = values['socket_timeout']
if 'ssl_options' in values:
options = ast.literal_eval(values['ssl_options'])
if self._validate_ssl_options(options):
self.ssl_options = options
class Connection(object):
ON_CONNECTION_BACKPRESSURE = '_on_connection_backpressure'
ON_CONNECTION_BLOCKED = '_on_connection_blocked'
ON_CONNECTION_CLOSED = '_on_connection_closed'
ON_CONNECTION_ERROR = '_on_connection_error'
ON_CONNECTION_OPEN = '_on_connection_open'
ON_CONNECTION_UNBLOCKED = '_on_connection_unblocked'
CONNECTION_CLOSED = 0
CONNECTION_INIT = 1
CONNECTION_PROTOCOL = 2
CONNECTION_START = 3
CONNECTION_TUNE = 4
CONNECTION_OPEN = 5
CONNECTION_CLOSING = 6
def __init__(self,
parameters=None,
on_open_callback=None,
on_open_error_callback=None,
on_close_callback=None):
self._write_lock = threading.Lock()
self.callbacks = callback.CallbackManager()
self.callbacks.add(0, self.ON_CONNECTION_ERROR,
on_open_error_callback or self._on_connection_error,
False)
self.heartbeat = None
if on_open_callback:
self.add_on_open_callback(on_open_callback)
if on_close_callback:
self.add_on_close_callback(on_close_callback)
self.params = parameters or ConnectionParameters()
self._init_connection_state()
self.connect()
def add_backpressure_callback(self, callback_method):
self.callbacks.add(0, self.ON_CONNECTION_BACKPRESSURE, callback_method,
False)
def add_on_close_callback(self, callback_method):
self.callbacks.add(0, self.ON_CONNECTION_CLOSED, callback_method, False)
def add_on_connection_blocked_callback(self, callback_method):
self.callbacks.add(0, spec.Connection.Blocked, callback_method, False)
def add_on_connection_unblocked_callback(self, callback_method):
self.callbacks.add(0, spec.Connection.Unblocked, callback_method, False)
def add_on_open_callback(self, callback_method):
self.callbacks.add(0, self.ON_CONNECTION_OPEN, callback_method, False)
def add_on_open_error_callback(self, callback_method, remove_default=True):
if remove_default:
self.callbacks.remove(0, self.ON_CONNECTION_ERROR,
self._on_connection_error)
self.callbacks.add(0, self.ON_CONNECTION_ERROR, callback_method, False)
def add_timeout(self, deadline, callback_method):
raise NotImplementedError
def channel(self, on_open_callback, channel_number=None):
if not channel_number:
channel_number = self._next_channel_number()
self._channels[channel_number] = self._create_channel(channel_number,
on_open_callback)
self._add_channel_callbacks(channel_number)
self._channels[channel_number].open()
return self._channels[channel_number]
def close(self, reply_code=200, reply_text='Normal shutdown'):
if self.is_closing or self.is_closed:
return
if self._has_open_channels:
self._close_channels(reply_code, reply_text)
self._set_connection_state(self.CONNECTION_CLOSING)
LOGGER.debug("Closing connection (%s): %s", reply_code, reply_text)
self.closing = reply_code, reply_text
if not self._has_open_channels:
self._on_close_ready()
def connect(self):
self._set_connection_state(self.CONNECTION_INIT)
error = self._adapter_connect()
if not error:
return self._on_connected()
self.remaining_connection_attempts -= 1
LOGGER.warning('Could not connect, %i attempts left',
self.remaining_connection_attempts)
if self.remaining_connection_attempts:
LOGGER.debug('Retrying in %i seconds', self.params.retry_delay)
self.add_timeout(self.params.retry_delay, self.connect)
else:
self.callbacks.process(0, self.ON_CONNECTION_ERROR, self, self,
error)
self.remaining_connection_attempts = self.params.connection_attempts
self._set_connection_state(self.CONNECTION_CLOSED)
def remove_timeout(self, callback_method):
raise NotImplementedError
def set_backpressure_multiplier(self, value=10):
self._backpressure = value
@property
def is_closed(self):
return self.connection_state == self.CONNECTION_CLOSED
@property
def is_closing(self):
return self.connection_state == self.CONNECTION_CLOSING
@property
def is_open(self):
return self.connection_state == self.CONNECTION_OPEN
@property
def basic_nack(self):
return self.server_capabilities.get('basic.nack', False)
@property
|
BSD 3-Clause New or Revised License
|
inovex/illuminatio
|
src/illuminatio/test_generator.py
|
invert_cluster_host
|
python
|
def invert_cluster_host(host: ClusterHost):
if host.pod_labels == {}:
return [ClusterHost("%s%s" % (INVERTED_ATTRIBUTE_PREFIX, host.namespace), {})]
inverted_hosts = [
ClusterHost(
"%s%s" % (INVERTED_ATTRIBUTE_PREFIX, host.namespace), host.pod_labels
),
ClusterHost(
"%s%s" % (INVERTED_ATTRIBUTE_PREFIX, host.namespace),
invert_label_selector(host.pod_labels),
),
ClusterHost(host.namespace, invert_label_selector(host.pod_labels)),
]
return inverted_hosts
|
Returns a list of ClusterHosts with
once inverted pod label selectors,
once inverted namespace label selectors
and once both
|
https://github.com/inovex/illuminatio/blob/dd57599ef675451ddbb35225d5c4ee09c70a3b3a/src/illuminatio/test_generator.py#L320-L340
|
import time
from typing import List
import kubernetes as k8s
from illuminatio.k8s_util import labels_to_string
from illuminatio.rule import Rule
from illuminatio.test_case import NetworkTestCase
from illuminatio.host import ClusterHost, GenericClusterHost
from illuminatio.util import rand_port, INVERTED_ATTRIBUTE_PREFIX
def _get_other_host_from(connection_targets, rule_namespace):
namespace_labels = "namespaceLabels"
pod_labels = "podLabels"
namespace = "namespace"
if namespace_labels in connection_targets and pod_labels in connection_targets:
return GenericClusterHost(
connection_targets[namespace_labels], connection_targets[pod_labels]
)
if namespace in connection_targets and pod_labels in connection_targets:
return ClusterHost(
connection_targets[namespace], connection_targets[pod_labels]
)
if namespace_labels in connection_targets:
return GenericClusterHost(connection_targets[namespace_labels], {})
if pod_labels in connection_targets:
return ClusterHost(rule_namespace, connection_targets[pod_labels])
if connection_targets == {}:
return GenericClusterHost({}, {})
raise ValueError(
"Unknown combination of field in connection %s" % connection_targets
)
def get_namespace_label_strings(namespace_labels, namespaces):
return {
labels_to_string(namespace_label): [
namespace.metadata.name
for namespace in namespaces
if namespace.metadata.labels is not None
and namespace_label.items() <= namespace.metadata.labels.items()
]
for namespace_label in namespace_labels
}
class NetworkTestCaseGenerator:
def __init__(self, log):
self.logger = log
def generate_test_cases(
self,
network_policies: List[k8s.client.V1NetworkPolicy],
namespaces: List[k8s.client.V1Namespace],
):
runtimes = {}
start_time = time.time()
isolated_hosts = []
other_hosts = []
outgoing_test_cases = []
incoming_test_cases = []
self.logger.debug("Generating test cases for %s", network_policies)
rules = [Rule.from_network_policy(netPol) for netPol in network_policies]
net_pol_parsing_time = time.time()
runtimes["parse"] = net_pol_parsing_time - start_time
self.logger.debug("Rule: %s", rules)
for rule in rules:
rule_host = ClusterHost(
rule.concerns["namespace"], rule.concerns["podLabels"]
)
if rule_host not in isolated_hosts:
isolated_hosts.append(rule_host)
if rule.allowed:
for connection in rule.allowed:
for port in connection.ports:
on_port = port
other_host = _get_other_host_from(
connection.targets, rule.concerns["namespace"]
)
other_hosts.append(other_host)
if connection.direction == "to":
case = NetworkTestCase(rule_host, other_host, on_port, True)
outgoing_test_cases.append(case)
elif connection.direction == "from":
case = NetworkTestCase(other_host, rule_host, on_port, True)
incoming_test_cases.append(case)
else:
raise ValueError(
"Direction '%s' unknown!" % connection.direction
)
positive_test_time = time.time()
runtimes["positiveTestGen"] = positive_test_time - net_pol_parsing_time
(
negative_test_cases,
negative_test_gen_runtimes,
) = self.generate_negative_cases_for_incoming_cases(
isolated_hosts, incoming_test_cases, other_hosts, namespaces
)
runtimes["negativeTestGen"] = negative_test_gen_runtimes
return outgoing_test_cases + negative_test_cases + incoming_test_cases, runtimes
def generate_negative_cases_for_incoming_cases(
self, isolated_hosts, incoming_test_cases, other_hosts, namespaces
):
runtimes = {}
start_time = time.time()
namespace_labels = [
h.namespace_labels for h in other_hosts if isinstance(h, GenericClusterHost)
]
namespaces_per_label_strings = get_namespace_label_strings(
namespace_labels, namespaces
)
namespace_label_resolve_time = time.time()
runtimes["nsLabelResolve"] = namespace_label_resolve_time - start_time
labels_per_namespace = {n.metadata.name: n.metadata.labels for n in namespaces}
overlaps_per_host = {
host: self.get_overlapping_hosts(
host,
namespaces_per_label_strings,
labels_per_namespace,
isolated_hosts + other_hosts,
)
for host in isolated_hosts
}
overlap_calc_time = time.time()
runtimes["overlapCalc"] = overlap_calc_time - namespace_label_resolve_time
cases = []
for host in isolated_hosts:
host_string = str(host)
host_start_time = time.time()
runtimes[host_string] = {}
self.logger.debug(overlaps_per_host[host])
allowed_hosts_with_ports = [
(test_case.from_host, test_case.port_string)
for test_case in incoming_test_cases
if test_case.to_host in overlaps_per_host[host]
]
self.logger.debug("allowed_hosts_with_ports=%s", allowed_hosts_with_ports)
reaching_host_find_time = time.time()
runtimes[host_string]["findReachingHosts"] = (
reaching_host_find_time - host_start_time
)
if allowed_hosts_with_ports:
allowed_hosts, _ = zip(*allowed_hosts_with_ports)
ports_per_host = {
host: [
port
for _host, port in allowed_hosts_with_ports
if _host == host
]
for host in allowed_hosts
}
match_all_host = GenericClusterHost({}, {})
if match_all_host in allowed_hosts:
if "*" in ports_per_host[match_all_host]:
self.logger.info(
"Not generating negative tests for host %s"
"as all connections to it are allowed",
host,
)
else:
cases.append(
NetworkTestCase(
match_all_host,
host,
rand_port(ports_per_host[match_all_host]),
False,
)
)
runtimes[host_string]["matchAllCase"] = (
time.time() - reaching_host_find_time
)
else:
inverted_hosts = set(
[
h
for l in [invert_host(host) for host in allowed_hosts]
for h in l
]
)
hosts_on_inverted = {
h: originalHost
for l, originalHost in [
(invert_host(host), host) for host in allowed_hosts
]
for h in l
}
host_inversion_time = time.time()
runtimes[host_string]["hostInversion"] = (
host_inversion_time - reaching_host_find_time
)
overlaps_for_inverted_hosts = {
h: self.get_overlapping_hosts(
h,
namespaces_per_label_strings,
labels_per_namespace,
allowed_hosts,
)
for h in inverted_hosts
}
overlap_calc_time = time.time()
runtimes[host_string]["overlapCalc"] = (
overlap_calc_time - host_inversion_time
)
self.logger.debug("InvertedHosts: %s", inverted_hosts)
negative_test_targets = [
h
for h in inverted_hosts
if len(overlaps_for_inverted_hosts[h]) <= 1
]
self.logger.debug("NegativeTestTargets: %s", negative_test_targets)
for target in negative_test_targets:
ports_for_inverted_hosts_original_host = ports_per_host[
hosts_on_inverted[target]
]
if ports_for_inverted_hosts_original_host:
cases.append(
NetworkTestCase(
target,
host,
ports_for_inverted_hosts_original_host[0],
False,
)
)
else:
cases.append(NetworkTestCase(target, host, "*", False))
runtimes[host_string]["casesGen"] = time.time() - overlap_calc_time
else:
cases.append(NetworkTestCase(host, host, "*", False))
runtimes["all"] = time.time() - start_time
return cases, runtimes
def get_overlapping_hosts(
self, host, namespaces_per_label_strings, labels_per_namespace, other_hosts
):
out = [host]
for other in other_hosts:
if host is not other:
namespace_overlap = self.namespaces_overlap(
host, namespaces_per_label_strings, labels_per_namespace, other
)
pod_label_overlap = label_selector_overlap(
other.pod_labels, host.pod_labels
)
if namespace_overlap and pod_label_overlap:
out.append(other)
return out
def namespaces_overlap(
self, host, namespaces_per_label_strings, labels_per_namespace, other_host
):
host_ns = self.resolve_namespaces(host, namespaces_per_label_strings)
other_ns = self.resolve_namespaces(other_host, namespaces_per_label_strings)
if host_ns and other_ns:
return any(ns in other_ns for ns in host_ns)
ns_labels = lookup_namespace_labels(host, labels_per_namespace)
other_ns_labels = lookup_namespace_labels(other_host, labels_per_namespace)
if ns_labels is not None and other_ns_labels is not None:
return label_selector_overlap(ns_labels, other_ns_labels)
return False
def resolve_namespaces(self, host, namespaces_per_label_strings):
self.logger.debug(host)
if isinstance(host, ClusterHost):
return [host.namespace]
labels = labels_to_string(host.namespace_labels)
return (
namespaces_per_label_strings[labels]
if labels in namespaces_per_label_strings
else []
)
def invert_host(host):
if isinstance(host, GenericClusterHost):
return invert_generic_cluster_host(host)
if isinstance(host, ClusterHost):
return invert_cluster_host(host)
raise ValueError("Host %s is of unsupported type" % host)
|
Apache License 2.0
|
liyi14/mx-deepim
|
lib/render_glumpy/render_py_light_modelnet.py
|
Render_Py_Light_ModelNet.render
|
python
|
def render(self, r, t, light_position, light_intensity, brightness_k=0, r_type="quat"):
if r_type == "quat":
R = quat2mat(r)
elif r_type == "mat":
R = r
self.brightness_k = brightness_k
self.render_kernels[brightness_k]["u_view"] = self._get_view_mtx(R, t)
self.render_kernels[brightness_k]["u_light_position"] = light_position
self.render_kernels[brightness_k]["u_normal"] = np.array(
np.matrix(
np.dot(
self.render_kernels[brightness_k]["u_view"].reshape(4, 4),
self.render_kernels[brightness_k]["u_model"].reshape(4, 4),
)
).I.T
)
self.render_kernels[brightness_k]["u_light_intensity"] = light_intensity
app.run(framecount=0)
rgb_buffer = np.zeros((self.height, self.width, 4), dtype=np.float32)
gl.glReadPixels(0, 0, self.width, self.height, gl.GL_RGBA, gl.GL_FLOAT, rgb_buffer)
rgb_gl = np.copy(rgb_buffer)
rgb_gl.shape = 480, 640, 4
rgb_gl = rgb_gl[::-1, :]
rgb_gl = np.round(rgb_gl[:, :, :3] * 255).astype(np.uint8)
bgr_gl = rgb_gl[:, :, [2, 1, 0]]
depth_buffer = np.zeros((self.height, self.width), dtype=np.float32)
gl.glReadPixels(0, 0, self.width, self.height, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, depth_buffer)
depth_gl = np.copy(depth_buffer)
depth_gl.shape = 480, 640
depth_gl = depth_gl[::-1, :]
depth_bg = depth_gl == 1
depth_gl = 2 * self.zFar * self.zNear / (self.zFar + self.zNear - (self.zFar - self.zNear) * (2 * depth_gl - 1))
depth_gl[depth_bg] = 0
return bgr_gl, depth_gl
|
:param r:
:param t:
:param light_position:
:param light_intensity:
:param brightness_k: choose which brightness in __init__
:param r_type:
:return:
|
https://github.com/liyi14/mx-deepim/blob/f1c850e5f8f75f1051a89c40daff9185870020f5/lib/render_glumpy/render_py_light_modelnet.py#L128-L173
|
from __future__ import print_function, division
import numpy as np
from glumpy import app, gl, gloo, data, log
import logging
log.setLevel(logging.WARNING)
from lib.pair_matching.RT_transform import quat2mat
vertex = """
uniform mat4 u_model; // Model matrix
uniform mat4 u_view; // View matrix
uniform mat4 u_projection; // Projection matrix
attribute vec3 position;
attribute vec3 normal;
attribute vec2 texcoord;
varying vec3 v_normal;
varying vec3 v_position;
varying vec2 v_texcoord;
void main()
{
// Assign varying variables
v_normal = normal;
v_position = position;
v_texcoord = texcoord;
// Final position
gl_Position = u_projection * u_view * u_model * vec4(position, 1.0);
}
"""
def get_fragment(brightness_ratio=0.4):
fragment = """
uniform mat4 u_model; // Model matrix
uniform mat4 u_view; // View matrix
uniform mat4 u_normal; // Normal matrix
uniform mat4 u_projection; // Projection matrix
uniform sampler2D u_texture; // Texture
uniform vec3 u_light_position; // Light position
uniform vec3 u_light_intensity; // Light intensity
varying vec3 v_normal; // Interpolated normal (in)
varying vec3 v_position; // Interpolated position (in)
varying vec2 v_texcoord; // Interpolated fragment texture coordinates (in)
void main()
{{
// Calculate normal in world coordinates
vec3 normal = normalize(u_normal * vec4(v_normal,1.0)).xyz;
// Calculate the location of this fragment (pixel) in world coordinates
vec3 position = vec3(u_view*u_model * vec4(v_position, 1));
//vec3 light_position = vec3(u_view*u_model * vec4(u_light_position, 1));
// Calculate the vector from this pixels surface to the light source
vec3 surfaceToLight = u_light_position - position;
// Calculate the cosine of the angle of incidence (brightness)
float brightness = dot(normal, surfaceToLight) /
(length(surfaceToLight) * length(normal));
brightness = max(min(brightness,1.0),0.0);
// Calculate final color of the pixel, based on:
// 1. The angle of incidence: brightness
// 2. The color/intensities of the light: light.intensities
// 3. The texture and texture coord: texture(tex, fragTexCoord)
// Get texture color
vec4 t_color = vec4(texture2D(u_texture, v_texcoord).rgb, 1.0);
// Final color
gl_FragColor = t_color * (({} + {}*brightness) * vec4(u_light_intensity, 1));
}}
""".format(
1 - brightness_ratio, brightness_ratio
)
return fragment
class Render_Py_Light_ModelNet:
def __init__(
self, model_path, texture_path, K, width=640, height=480, zNear=0.25, zFar=6.0, brightness_ratios=[0.7]
):
self.width = width
self.height = height
self.zNear = zNear
self.zFar = zFar
self.K = K
self.model_path = model_path
log.info("Loading mesh")
vertices, indices = data.objload("{}".format(model_path), rescale=True)
vertices["position"] = vertices["position"] / 10.0
self.render_kernels = []
for brightness_ratio in brightness_ratios:
fragment = get_fragment(brightness_ratio=brightness_ratio)
render_kernel = gloo.Program(vertex, fragment)
render_kernel.bind(vertices)
log.info("Loading texture")
render_kernel["u_texture"] = np.copy(data.load("{}".format(texture_path))[::-1, :, :])
render_kernel["u_model"] = np.eye(4, dtype=np.float32)
u_projection = self.my_compute_calib_proj(K, width, height, zNear, zFar)
render_kernel["u_projection"] = np.copy(u_projection)
render_kernel["u_light_intensity"] = 1, 1, 1
self.render_kernels.append(render_kernel)
self.brightness_k = 0
self.window = app.Window(width=width, height=height, visible=False)
@self.window.event
def on_draw(dt):
self.window.clear()
gl.glDisable(gl.GL_BLEND)
gl.glEnable(gl.GL_DEPTH_TEST)
self.render_kernels[self.brightness_k].draw(gl.GL_TRIANGLES)
@self.window.event
def on_init():
gl.glEnable(gl.GL_DEPTH_TEST)
|
Apache License 2.0
|
jorritwillaert/pythonbattleshipgame
|
game_functions.py
|
convert_position
|
python
|
def convert_position(position):
letter = position[0]
column = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'].index(letter)
row = int(position[1:]) - 1
return row, column
|
Convert position to 'absolute' position! (B7 becomes (1, 6))
|
https://github.com/jorritwillaert/pythonbattleshipgame/blob/18022317a654953ca2ab4d1e40d227a455f5efe4/game_functions.py#L110-L115
|
import time
import random
import helper
class Game():
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
def starting_up(self, own, opponent):
helper.clear()
ship_list = [("Destroyer", 2), ("Submarine", 3), ("Cruiser", 3), ('Battleship', 4), ('Carrier', 5)]
input(own.name + ", press Enter if you're ready. ")
for ship in reversed(ship_list):
succesful = False
while not succesful:
helper.clear()
own.draw_boards(own, opponent)
position = insert_position(own, ship, starting = True)
direction = insert_direction()
if check_if_possible(own, position, direction, ship):
succesful = True
own.draw_ship(position, direction, ship)
else:
print("\nIt's not possible to place a ship here. Please chose an other location.\n")
time.sleep(2)
helper.clear()
own.draw_boards(own, opponent)
time.sleep(1)
def make_move(self, own, opponent):
succesful = False
while not succesful:
helper.clear()
own.draw_boards(own, opponent)
position = insert_position(own, ship = None, starting = False)
coordinate = convert_position(position)
if check_if_first_time(coordinate, opponent):
succesful = True
else:
print('Please enter a non-chosen position.')
time.sleep(1)
helper.clear()
if opponent.check_if_hit(coordinate):
print('Hit!')
else:
print('Miss!')
ships_name = opponent.check_if_sunk()
if ships_name:
print(ships_name + ' sunked!')
time.sleep(1)
own.draw_boards(own, opponent)
time.sleep(1)
def victory(self, own):
helper.clear()
if own.name != 'CPU':
print("Congratulations " + own.name + ", you've won.")
else:
print('Unfortunately, but the computer did beat you...')
while True:
new_game = input("Do you want to play a new game? (y, n) ").lower()
if new_game == 'y':
return True
elif new_game == 'n':
return False
else:
print('Enter a valid option!\n')
def starting_up_cpu(self, cpu):
ship_list = [("Destroyer", 2), ("Submarine", 3), ("Cruiser", 3), ('Battleship', 4), ('Carrier', 5)]
for ship in reversed(ship_list):
succesful = False
while not succesful:
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
letter = letters[random.randint(0, 9)]
number = str(random.randint(1, 10))
position = letter + number
directions = ['h', 'v']
direction = directions[random.randint(0,1)]
if check_if_possible(cpu, position, direction, ship):
succesful = True
cpu.draw_ship(position, direction, ship)
def make_move_cpu(self, cpu, opponent):
None
def check_if_possible(player, position, direction, ship):
row, column = convert_position(position)
for length in range(ship[1]):
if direction == 'h':
if column + length >= 10 or player.board_obj.board[row][column + length].symbol != '.':
return False
else:
if row + length >= 10 or player.board_obj.board[row + length][column].symbol != '.':
return False
return True
|
MIT License
|
argoproj-labs/argo-client-python
|
argo/workflows/client/models/v1alpha1_node_status.py
|
V1alpha1NodeStatus.memoization_status
|
python
|
def memoization_status(self):
return self._memoization_status
|
Gets the memoization_status of this V1alpha1NodeStatus. # noqa: E501
:return: The memoization_status of this V1alpha1NodeStatus. # noqa: E501
:rtype: V1alpha1MemoizationStatus
|
https://github.com/argoproj-labs/argo-client-python/blob/993d684cab39a834770b296e028519cec035c7b5/argo/workflows/client/models/v1alpha1_node_status.py#L385-L392
|
import pprint
import re
import six
from argo.workflows.client.configuration import Configuration
class V1alpha1NodeStatus(object):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'boundary_id': 'str',
'children': 'list[str]',
'daemoned': 'bool',
'display_name': 'str',
'estimated_duration': 'int',
'finished_at': 'datetime',
'host_node_name': 'str',
'id': 'str',
'inputs': 'V1alpha1Inputs',
'memoization_status': 'V1alpha1MemoizationStatus',
'message': 'str',
'name': 'str',
'outbound_nodes': 'list[str]',
'outputs': 'V1alpha1Outputs',
'phase': 'str',
'pod_ip': 'str',
'progress': 'str',
'resources_duration': 'dict(str, int)',
'started_at': 'datetime',
'stored_template_id': 'str',
'synchronization_status': 'V1alpha1NodeSynchronizationStatus',
'template_name': 'str',
'template_ref': 'V1alpha1TemplateRef',
'template_scope': 'str',
'type': 'str',
'workflow_template_name': 'str'
}
attribute_map = {
'boundary_id': 'boundaryID',
'children': 'children',
'daemoned': 'daemoned',
'display_name': 'displayName',
'estimated_duration': 'estimatedDuration',
'finished_at': 'finishedAt',
'host_node_name': 'hostNodeName',
'id': 'id',
'inputs': 'inputs',
'memoization_status': 'memoizationStatus',
'message': 'message',
'name': 'name',
'outbound_nodes': 'outboundNodes',
'outputs': 'outputs',
'phase': 'phase',
'pod_ip': 'podIP',
'progress': 'progress',
'resources_duration': 'resourcesDuration',
'started_at': 'startedAt',
'stored_template_id': 'storedTemplateID',
'synchronization_status': 'synchronizationStatus',
'template_name': 'templateName',
'template_ref': 'templateRef',
'template_scope': 'templateScope',
'type': 'type',
'workflow_template_name': 'workflowTemplateName'
}
def __init__(self, boundary_id=None, children=None, daemoned=None, display_name=None, estimated_duration=None, finished_at=None, host_node_name=None, id=None, inputs=None, memoization_status=None, message=None, name=None, outbound_nodes=None, outputs=None, phase=None, pod_ip=None, progress=None, resources_duration=None, started_at=None, stored_template_id=None, synchronization_status=None, template_name=None, template_ref=None, template_scope=None, type=None, workflow_template_name=None, local_vars_configuration=None):
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._boundary_id = None
self._children = None
self._daemoned = None
self._display_name = None
self._estimated_duration = None
self._finished_at = None
self._host_node_name = None
self._id = None
self._inputs = None
self._memoization_status = None
self._message = None
self._name = None
self._outbound_nodes = None
self._outputs = None
self._phase = None
self._pod_ip = None
self._progress = None
self._resources_duration = None
self._started_at = None
self._stored_template_id = None
self._synchronization_status = None
self._template_name = None
self._template_ref = None
self._template_scope = None
self._type = None
self._workflow_template_name = None
self.discriminator = None
if boundary_id is not None:
self.boundary_id = boundary_id
if children is not None:
self.children = children
if daemoned is not None:
self.daemoned = daemoned
if display_name is not None:
self.display_name = display_name
if estimated_duration is not None:
self.estimated_duration = estimated_duration
if finished_at is not None:
self.finished_at = finished_at
if host_node_name is not None:
self.host_node_name = host_node_name
self.id = id
if inputs is not None:
self.inputs = inputs
if memoization_status is not None:
self.memoization_status = memoization_status
if message is not None:
self.message = message
self.name = name
if outbound_nodes is not None:
self.outbound_nodes = outbound_nodes
if outputs is not None:
self.outputs = outputs
if phase is not None:
self.phase = phase
if pod_ip is not None:
self.pod_ip = pod_ip
if progress is not None:
self.progress = progress
if resources_duration is not None:
self.resources_duration = resources_duration
if started_at is not None:
self.started_at = started_at
if stored_template_id is not None:
self.stored_template_id = stored_template_id
if synchronization_status is not None:
self.synchronization_status = synchronization_status
if template_name is not None:
self.template_name = template_name
if template_ref is not None:
self.template_ref = template_ref
if template_scope is not None:
self.template_scope = template_scope
self.type = type
if workflow_template_name is not None:
self.workflow_template_name = workflow_template_name
@property
def boundary_id(self):
return self._boundary_id
@boundary_id.setter
def boundary_id(self, boundary_id):
self._boundary_id = boundary_id
@property
def children(self):
return self._children
@children.setter
def children(self, children):
self._children = children
@property
def daemoned(self):
return self._daemoned
@daemoned.setter
def daemoned(self, daemoned):
self._daemoned = daemoned
@property
def display_name(self):
return self._display_name
@display_name.setter
def display_name(self, display_name):
self._display_name = display_name
@property
def estimated_duration(self):
return self._estimated_duration
@estimated_duration.setter
def estimated_duration(self, estimated_duration):
self._estimated_duration = estimated_duration
@property
def finished_at(self):
return self._finished_at
@finished_at.setter
def finished_at(self, finished_at):
self._finished_at = finished_at
@property
def host_node_name(self):
return self._host_node_name
@host_node_name.setter
def host_node_name(self, host_node_name):
self._host_node_name = host_node_name
@property
def id(self):
return self._id
@id.setter
def id(self, id):
if self.local_vars_configuration.client_side_validation and id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
self._id = id
@property
def inputs(self):
return self._inputs
@inputs.setter
def inputs(self, inputs):
self._inputs = inputs
@property
|
Apache License 2.0
|
integreat/integreat-cms
|
src/cms/models/events/event.py
|
Event.get_translation
|
python
|
def get_translation(self, language_slug):
return self.translations.filter(language__slug=language_slug).first()
|
This function uses the reverse foreign key ``self.translations`` to get all translations of ``self``
and filters them to the requested :class:`~cms.models.languages.language.Language` slug.
:param language_slug: The slug of the desired :class:`~cms.models.languages.language.Language`
:type language_slug: str
:return: The event translation in the requested :class:`~cms.models.languages.language.Language` or :obj:`None`
if no translation exists
:rtype: ~cms.models.events.event_translation.EventTranslation
|
https://github.com/integreat/integreat-cms/blob/656680f8499e0458b5770fc6a8cbcfb98eec0d55/src/cms/models/events/event.py#L101-L113
|
from datetime import datetime, time, date
from dateutil.rrule import weekday, rrule
from django.db import models
from django.utils.translation import get_language, ugettext_lazy as _
from ...constants import frequency, status
from ...utils.slug_utils import generate_unique_slug
from ..media.media_file import MediaFile
from ..pois.poi import POI
from ..regions.region import Region, Language
from .recurrence_rule import RecurrenceRule
class Event(models.Model):
region = models.ForeignKey(
Region,
on_delete=models.CASCADE,
related_name="events",
verbose_name=_("region"),
)
location = models.ForeignKey(
POI,
null=True,
blank=True,
on_delete=models.PROTECT,
related_name="events",
verbose_name=_("location"),
)
start_date = models.DateField(verbose_name=_("start date"))
start_time = models.TimeField(blank=True, verbose_name=_("start time"))
end_date = models.DateField(verbose_name=_("end date"))
end_time = models.TimeField(blank=True, verbose_name=_("end time"))
recurrence_rule = models.OneToOneField(
RecurrenceRule,
null=True,
on_delete=models.SET_NULL,
verbose_name=_("recurrence rule"),
)
icon = models.ForeignKey(
MediaFile,
verbose_name=_("icon"),
on_delete=models.SET_NULL,
related_name="icon_events",
blank=True,
null=True,
)
archived = models.BooleanField(default=False, verbose_name=_("archived"))
@property
def languages(self):
return Language.objects.filter(event_translations__event=self)
@property
def is_recurring(self):
return bool(self.recurrence_rule)
@property
def is_all_day(self):
return self.start_time == time.min and self.end_time == time.max.replace(
second=0, microsecond=0
)
@property
def has_location(self):
return bool(self.location)
|
Apache License 2.0
|
by571/soft-actor-critic-and-extensions
|
files/ReplayBuffers.py
|
ReplayBuffer.add
|
python
|
def add(self, state, action, reward, next_state, done):
if self.iter_ == self.parallel_env:
self.iter_ = 0
self.n_step_buffer[self.iter_].append((state, action, reward, next_state, done))
if len(self.n_step_buffer[self.iter_]) == self.n_step:
state, action, reward, next_state, done = self.calc_multistep_return(self.n_step_buffer[self.iter_])
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
self.iter_ += 1
|
Add a new experience to memory.
|
https://github.com/by571/soft-actor-critic-and-extensions/blob/23ab34bd508d80409ebfb0df8bfe0981f16b1315/files/ReplayBuffers.py#L30-L39
|
import random
import torch
import numpy as np
from collections import namedtuple, deque
class ReplayBuffer:
def __init__(self, buffer_size, batch_size, device, seed, gamma, n_step=1, parallel_env=1, ere=False):
self.device = device
self.memory = deque(maxlen=buffer_size)
self.batch_size = batch_size
self.n_step = n_step
self.n_step_buffer = [deque(maxlen=self.n_step) for i in range(parallel_env)]
self.parallel_env = parallel_env
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = random.seed(seed)
self.gamma = gamma
self.iter_ = 0
self.ere = ere
|
MIT License
|
timvink/mkdocs-git-authors-plugin
|
mkdocs_git_authors_plugin/plugin.py
|
GitAuthorsPlugin.repo
|
python
|
def repo(self):
return self._repo
|
Reference to the Repo object of the current project.
|
https://github.com/timvink/mkdocs-git-authors-plugin/blob/080b568519e07b18499a365ccd59b02302ce91c7/mkdocs_git_authors_plugin/plugin.py#L264-L268
|
from mkdocs_git_authors_plugin.git.command import GitCommandError
import re
import logging
from mkdocs.config import config_options
from mkdocs.plugins import BasePlugin
from . import util
from .git.repo import Repo
from mkdocs_git_authors_plugin.ci import raise_ci_warnings
from mkdocs_git_authors_plugin.exclude import exclude
logger = logging.getLogger("mkdocs.plugins")
class GitAuthorsPlugin(BasePlugin):
config_scheme = (
("show_contribution", config_options.Type(bool, default=False)),
("show_line_count", config_options.Type(bool, default=False)),
("count_empty_lines", config_options.Type(bool, default=True)),
("fallback_to_empty", config_options.Type(bool, default=False)),
("exclude", config_options.Type(list, default=[])),
("enabled", config_options.Type(bool, default=True)),
)
def __init__(self):
self._repo = None
self._fallback = False
def on_config(self, config, **kwargs):
if not self.config.get('enabled'):
return config
try:
self._repo = Repo()
self._fallback = False
self.repo().set_config(self.config)
raise_ci_warnings(path = self.repo()._root)
except GitCommandError:
if self.config["fallback_to_empty"]:
self._fallback = True
logger.warning(
"[git-authors-plugin] Unable to find a git directory and/or git is not installed."
" Option 'fallback_to_empty' set to 'true': Falling back to empty authors list"
)
else:
raise
def on_files(self, files, config, **kwargs):
if not self.config.get('enabled'):
return
if self._fallback:
return
for file in files:
excluded_pages = self.config.get("exclude", [])
if exclude(file.src_path, excluded_pages):
continue
path = file.abs_src_path
if path.endswith(".md"):
_ = self.repo().page(path)
def on_page_content(self, html, page, config, files, **kwargs):
if not self.config.get('enabled'):
return html
excluded_pages = self.config.get("exclude", [])
if exclude(page.file.src_path, excluded_pages):
return html
list_pattern = re.compile(
r"\{\{\s*git_site_authors\s*\}\}", flags=re.IGNORECASE
)
if list_pattern.search(html):
html = list_pattern.sub(
"" if self._fallback else
util.site_authors_summary(self.repo().get_authors(), self.config), html
)
return html
def on_page_markdown(self, markdown, page, config, files, **kwargs):
if not self.config.get('enabled'):
return markdown
excluded_pages = self.config.get("exclude", [])
if exclude(page.file.src_path, excluded_pages):
return markdown
pattern_authors_summary = re.compile(
r"\{\{\s*git_authors_summary\s*\}\}", flags=re.IGNORECASE
)
pattern_page_authors = re.compile(
r"\{\{\s*git_page_authors\s*\}\}", flags=re.IGNORECASE
)
if not pattern_authors_summary.search(
markdown
) and not pattern_page_authors.search(markdown):
return markdown
if self._fallback:
markdown = pattern_authors_summary.sub("", markdown)
markdown = pattern_page_authors.sub("", markdown)
return markdown
page_obj = self.repo().page(page.file.abs_src_path)
page_authors = util.page_authors_summary(page_obj, self.config)
markdown = pattern_authors_summary.sub(page_authors, markdown)
markdown = pattern_page_authors.sub(page_authors, markdown)
return markdown
def on_page_context(self, context, page, config, nav, **kwargs):
if not self.config.get('enabled'):
return context
if self._fallback:
return context
excluded_pages = self.config.get("exclude", [])
if exclude(page.file.src_path, excluded_pages):
logging.debug("on_page_context, Excluding page " + page.file.src_path)
return context
path = page.file.abs_src_path
page_obj = self.repo().page(path)
authors = page_obj.get_authors()
page_authors = util.page_authors_summary(page_obj, self.config)
site_authors = util.site_authors_summary(self.repo().get_authors(), self.config)
context["git_info"] = {
"page_authors": util.page_authors(authors, path),
"site_authors": util.page_authors(self.repo().get_authors(), path),
}
context["git_page_authors"] = page_authors
context["git_site_authors"] = site_authors
context["git_authors"] = util.page_authors(authors, path)
context["git_authors_summary"] = page_authors
return context
|
MIT License
|
rockyzhengwu/transformer-en-zh
|
transformer/utils/tokenizer.py
|
_save_vocab_file
|
python
|
def _save_vocab_file(vocab_file, subtoken_list):
with tf.gfile.Open(vocab_file, mode="w") as f:
for subtoken in subtoken_list:
f.write("'%s'\n" % _unicode_to_native(subtoken))
|
Save subtokens to file.
|
https://github.com/rockyzhengwu/transformer-en-zh/blob/4179c12f22842893931567877901758f6e064381/transformer/utils/tokenizer.py#L180-L184
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import re
import sys
import unicodedata
import numpy as np
import six
from six.moves import xrange
import tensorflow as tf
PAD = "<pad>"
PAD_ID = 0
EOS = "<EOS>"
EOS_ID = 1
RESERVED_TOKENS = [PAD, EOS]
_ESCAPE_CHARS = set(u"\\_u;0123456789")
_UNESCAPE_REGEX = re.compile(r"\\u|\\\\|\\([0-9]+);")
_UNDEFINED_UNICODE = u"\u3013"
_ALPHANUMERIC_CHAR_SET = set(
six.unichr(i) for i in xrange(sys.maxunicode)
if (unicodedata.category(six.unichr(i)).startswith("L") or
unicodedata.category(six.unichr(i)).startswith("N")))
_MIN_MIN_COUNT = 1
_MAX_MIN_COUNT = 1000
class Subtokenizer(object):
def __init__(self, vocab_file, reserved_tokens=None):
tf.logging.info("Initializing Subtokenizer from file %s." % vocab_file)
if reserved_tokens is None:
reserved_tokens = RESERVED_TOKENS
self.subtoken_list = _load_vocab_file(vocab_file, reserved_tokens)
self.alphabet = _generate_alphabet_dict(self.subtoken_list)
self.subtoken_to_id_dict = _list_to_index_dict(self.subtoken_list)
self.max_subtoken_length = 0
for subtoken in self.subtoken_list:
self.max_subtoken_length = max(self.max_subtoken_length, len(subtoken))
self._cache_size = 2 ** 20
self._cache = [(None, None)] * self._cache_size
@staticmethod
def init_from_files(
vocab_file, files, target_vocab_size, threshold, min_count=None,
file_byte_limit=1e6, reserved_tokens=None):
if reserved_tokens is None:
reserved_tokens = RESERVED_TOKENS
if tf.gfile.Exists(vocab_file):
tf.logging.info("Vocab file already exists (%s)" % vocab_file)
else:
tf.logging.info("Begin steps to create subtoken vocabulary...")
token_counts = _count_tokens(files, file_byte_limit)
alphabet = _generate_alphabet_dict(token_counts)
subtoken_list = _generate_subtokens_with_target_vocab_size(
token_counts, alphabet, target_vocab_size, threshold, min_count,
reserved_tokens)
tf.logging.info("Generated vocabulary with %d subtokens." %
len(subtoken_list))
_save_vocab_file(vocab_file, subtoken_list)
return Subtokenizer(vocab_file)
def encode(self, raw_string, add_eos=False):
ret = []
tokens = _split_string_to_tokens(_native_to_unicode(raw_string))
for token in tokens:
ret.extend(self._token_to_subtoken_ids(token))
if add_eos:
ret.append(EOS_ID)
return ret
def _token_to_subtoken_ids(self, token):
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._cache[cache_location]
if cache_key == token:
return cache_value
ret = _split_token_to_subtokens(
_escape_token(token, self.alphabet), self.subtoken_to_id_dict,
self.max_subtoken_length)
ret = [self.subtoken_to_id_dict[subtoken_id] for subtoken_id in ret]
self._cache[cache_location] = (token, ret)
return ret
def decode(self, subtokens):
if isinstance(subtokens, np.ndarray):
subtokens = subtokens.tolist()
if not subtokens:
return ""
assert isinstance(subtokens, list) and isinstance(subtokens[0], int), (
"Subtokens argument passed into decode() must be a list of integers.")
return _unicode_to_native(
_join_tokens_to_string(self._subtoken_ids_to_tokens(subtokens)))
def _subtoken_ids_to_tokens(self, subtokens):
escaped_tokens = "".join([
self.subtoken_list[s] for s in subtokens
if s < len(self.subtoken_list)])
escaped_tokens = escaped_tokens.split("_")
ret = []
for token in escaped_tokens:
if token:
ret.append(_unescape_token(token))
return ret
|
Apache License 2.0
|
googleapis/python-bigtable
|
google/cloud/bigtable/instance.py
|
Instance.create
|
python
|
def create(
self,
location_id=None,
serve_nodes=None,
default_storage_type=None,
clusters=None,
):
if clusters is None:
warnings.warn(
_INSTANCE_CREATE_WARNING.format(
"location_id", "serve_nodes", "default_storage_type"
),
DeprecationWarning,
stacklevel=2,
)
cluster_id = "{}-cluster".format(self.instance_id)
clusters = [
self.cluster(
cluster_id,
location_id=location_id,
serve_nodes=serve_nodes,
default_storage_type=default_storage_type,
)
]
elif (
location_id is not None
or serve_nodes is not None
or default_storage_type is not None
):
raise ValueError(
"clusters and one of location_id, serve_nodes, \
default_storage_type can not be set \
simultaneously."
)
instance_pb = instance.Instance(
display_name=self.display_name, type_=self.type_, labels=self.labels
)
parent = self._client.project_path
return self._client.instance_admin_client.create_instance(
request={
"parent": parent,
"instance_id": self.instance_id,
"instance": instance_pb,
"clusters": {c.cluster_id: c._to_pb() for c in clusters},
}
)
|
Create this instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_api_create_prod_instance]
:end-before: [END bigtable_api_create_prod_instance]
:dedent: 4
.. note::
Uses the ``project`` and ``instance_id`` on the current
:class:`Instance` in addition to the ``display_name``.
To change them before creating, reset the values via
.. code:: python
instance.display_name = 'New display name'
instance.instance_id = 'i-changed-my-mind'
before calling :meth:`create`.
:type location_id: str
:param location_id: (Creation Only) The location where nodes and
storage of the cluster owned by this instance
reside. For best performance, clients should be
located as close as possible to cluster's location.
For list of supported locations refer to
https://cloud.google.com/bigtable/docs/locations
:type serve_nodes: int
:param serve_nodes: (Optional) The number of nodes in the instance's
cluster; used to set up the instance's cluster.
:type default_storage_type: int
:param default_storage_type: (Optional) The storage media type for
persisting Bigtable data.
Possible values are represented
by the following constants:
:data:`google.cloud.bigtable.enums.StorageType.SSD`.
:data:`google.cloud.bigtable.enums.StorageType.HDD`,
Defaults to
:data:`google.cloud.bigtable.enums.StorageType.UNSPECIFIED`.
:type clusters: class:`~[~google.cloud.bigtable.cluster.Cluster]`
:param clusters: List of clusters to be created.
:rtype: :class:`~google.api_core.operation.Operation`
:returns: The long-running operation corresponding to the create
operation.
:raises: :class:`ValueError <exceptions.ValueError>` if both
``clusters`` and one of ``location_id``, ``serve_nodes``
and ``default_storage_type`` are set.
|
https://github.com/googleapis/python-bigtable/blob/a99bf88417d6aec03923447c70c2752f6bb5c459/google/cloud/bigtable/instance.py#L225-L332
|
import re
from google.cloud.bigtable.app_profile import AppProfile
from google.cloud.bigtable.cluster import Cluster
from google.cloud.bigtable.table import Table
from google.protobuf import field_mask_pb2
from google.cloud.bigtable_admin_v2.types import instance
from google.iam.v1 import options_pb2
from google.api_core.exceptions import NotFound
from google.cloud.bigtable.policy import Policy
import warnings
_INSTANCE_NAME_RE = re.compile(
r"^projects/(?P<project>[^/]+)/" r"instances/(?P<instance_id>[a-z][-a-z0-9]*)$"
)
_INSTANCE_CREATE_WARNING = """
Use of `instance.create({0}, {1}, {2})` will be deprecated.
Please replace with
`cluster = instance.cluster({0}, {1}, {2})`
`instance.create(clusters=[cluster])`."""
class Instance(object):
def __init__(
self,
instance_id,
client,
display_name=None,
instance_type=None,
labels=None,
_state=None,
):
self.instance_id = instance_id
self._client = client
self.display_name = display_name or instance_id
self.type_ = instance_type
self.labels = labels
self._state = _state
def _update_from_pb(self, instance_pb):
if not instance_pb.display_name:
raise ValueError("Instance protobuf does not contain display_name")
self.display_name = instance_pb.display_name
self.type_ = instance_pb.type_
self.labels = dict(instance_pb.labels)
self._state = instance_pb.state
@classmethod
def from_pb(cls, instance_pb, client):
match = _INSTANCE_NAME_RE.match(instance_pb.name)
if match is None:
raise ValueError(
"Instance protobuf name was not in the " "expected format.",
instance_pb.name,
)
if match.group("project") != client.project:
raise ValueError(
"Project ID on instance does not match the " "project ID on the client"
)
instance_id = match.group("instance_id")
result = cls(instance_id, client)
result._update_from_pb(instance_pb)
return result
@property
def name(self):
return self._client.instance_admin_client.instance_path(
project=self._client.project, instance=self.instance_id
)
@property
def state(self):
return self._state
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return other.instance_id == self.instance_id and other._client == self._client
def __ne__(self, other):
return not self == other
|
Apache License 2.0
|
ucb-art/bag_framework
|
bag/data/lti.py
|
LTICircuit.add_vccs
|
python
|
def add_vccs(self, gm, p_name, n_name, cp_name, cn_name='gnd'):
node_p = self._get_node_id(p_name)
node_n = self._get_node_id(n_name)
node_cp = self._get_node_id(cp_name)
node_cn = self._get_node_id(cn_name)
if node_p == node_n or node_cp == node_cn:
return
if node_cp >= 0:
if node_p >= 0:
self._add(self._gmat_data, (node_p, node_cp), gm)
if node_n >= 0:
self._add(self._gmat_data, (node_n, node_cp), -gm)
if node_cn >= 0:
if node_p >= 0:
self._add(self._gmat_data, (node_p, node_cn), -gm)
if node_n >= 0:
self._add(self._gmat_data, (node_n, node_cn), gm)
|
Adds a voltage controlled current source to the circuit.
Parameters
----------
gm : float
the gain of the voltage controlled current source, in Siemens.
p_name : str
the terminal that the current flows out of.
n_name : str
the terminal that the current flows in to.
cp_name : str
the positive voltage control terminal.
cn_name : str
the negative voltage control terminal. Defaults to 'gnd'.
|
https://github.com/ucb-art/bag_framework/blob/8efa57ad719b2b02a005e234d87ad6f0e5e7a3de/bag/data/lti.py#L104-L138
|
from typing import Dict, List, Tuple, Union, Optional
import numpy as np
import scipy.signal
import scipy.sparse
import scipy.sparse.linalg
from scipy.signal.ltisys import StateSpaceContinuous, TransferFunctionContinuous
class LTICircuit(object):
_float_min = np.finfo(np.float64).eps
def __init__(self, udot_tol=1e-12):
self._num_n = 0
self._gmat_data = {}
self._cmat_data = {}
self._vcvs_list = []
self._ind_data = {}
self._node_id = {'gnd': -1}
self._udot_tol = udot_tol
def _get_node_id(self, name):
if name not in self._node_id:
ans = self._num_n
self._node_id[name] = ans
self._num_n += 1
return ans
else:
return self._node_id[name]
@staticmethod
def _add(mat, key, val):
if key in mat:
mat[key] += val
else:
mat[key] = val
def add_res(self, res, p_name, n_name):
res_sgn = 1 if res >= 0 else -1
g = res_sgn / max(abs(res), self._float_min)
self.add_conductance(g, p_name, n_name)
def add_conductance(self, g, p_name, n_name):
node_p = self._get_node_id(p_name)
node_n = self._get_node_id(n_name)
if node_p == node_n:
return
if node_p < node_n:
node_p, node_n = node_n, node_p
self._add(self._gmat_data, (node_p, node_p), g)
if node_n >= 0:
self._add(self._gmat_data, (node_p, node_n), -g)
self._add(self._gmat_data, (node_n, node_p), -g)
self._add(self._gmat_data, (node_n, node_n), g)
|
BSD 3-Clause New or Revised License
|
dask/dask
|
versioneer.py
|
git_get_keywords
|
python
|
def git_get_keywords(versionfile_abs):
keywords = {}
try:
f = open(versionfile_abs)
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
f.close()
except OSError:
pass
return keywords
|
Extract version information from the given file.
|
https://github.com/dask/dask/blob/e05d1cf32899a0379f38c9e2a971b11465f470a4/versioneer.py#L973-L994
|
try:
import configparser
except ImportError:
import ConfigParser as configparser
import errno
import json
import os
import re
import subprocess
import sys
class VersioneerConfig:
def get_root():
root = os.path.realpath(os.path.abspath(os.getcwd()))
setup_py = os.path.join(root, "setup.py")
versioneer_py = os.path.join(root, "versioneer.py")
if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
setup_py = os.path.join(root, "setup.py")
versioneer_py = os.path.join(root, "versioneer.py")
if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
err = ("Versioneer was unable to run the project root directory. "
"Versioneer requires setup.py to be executed from "
"its immediate directory (like 'python setup.py COMMAND'), "
"or in a way that lets it use sys.argv[0] to find the root "
"(like 'python path/to/setup.py COMMAND').")
raise VersioneerBadRootError(err)
try:
me = os.path.realpath(os.path.abspath(__file__))
if os.path.splitext(me)[0] != os.path.splitext(versioneer_py)[0]:
print("Warning: build in %s is using versioneer.py from %s"
% (os.path.dirname(me), versioneer_py))
except NameError:
pass
return root
def get_config_from_root(root):
setup_cfg = os.path.join(root, "setup.cfg")
parser = configparser.SafeConfigParser()
with open(setup_cfg) as f:
parser.readfp(f)
VCS = parser.get("versioneer", "VCS")
def get(parser, name):
if parser.has_option("versioneer", name):
return parser.get("versioneer", name)
return None
cfg = VersioneerConfig()
cfg.VCS = VCS
cfg.style = get(parser, "style") or ""
cfg.versionfile_source = get(parser, "versionfile_source")
cfg.versionfile_build = get(parser, "versionfile_build")
cfg.tag_prefix = get(parser, "tag_prefix")
if cfg.tag_prefix in ("''", '""'):
cfg.tag_prefix = ""
cfg.parentdir_prefix = get(parser, "parentdir_prefix")
cfg.verbose = get(parser, "verbose")
return cfg
class NotThisMethod(Exception):
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method):
def decorate(f):
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(e)
return None
else:
if verbose:
print(f"unable to find command, tried {commands}")
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
return None
return stdout
LONG_VERSION_PY['git'] = r'''
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number.
# This file is released into the public domain. Generated by
# versioneer-0.16 (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keywords().
git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
keywords = {"refnames": git_refnames, "full": git_full}
return keywords
class VersioneerConfig:
"""Container for Versioneer configuration parameters."""
def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "%(STYLE)s"
cfg.tag_prefix = "%(TAG_PREFIX)s"
cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s"
cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s"
cfg.verbose = False
return cfg
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %%s" %% dispcmd)
print(e)
return None
else:
if verbose:
print("unable to find command, tried %%s" %% (commands,))
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %%s (error)" %% dispcmd)
return None
return stdout
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes
both the project name and a version string.
"""
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%%s', but '%%s' doesn't start with "
"prefix '%%s'" %% (root, dirname, parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None}
@register_vcs_handler("git", "get_keywords")
def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %%d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "main".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%%s', no digits" %% ",".join(refs-tags))
if verbose:
print("likely tags: %%s" %% ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %%s" %% r)
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None
}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
"""
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %%s" %% root)
raise NotThisMethod("no .git directory")
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%%s*" %% tag_prefix],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%%s'"
%% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%%s' doesn't start with prefix '%%s'"
print(fmt %% (full_tag, tag_prefix))
pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'"
%% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
return pieces
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%%d" %% pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%%d" %% pieces["distance"]
return rendered
def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%%d" %% pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%%s" %% pieces["short"]
else:
# exception #1
rendered = "0.post%%d" %% pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%%s" %% pieces["short"]
return rendered
def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%%d" %% pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%%d" %% pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
return rendered
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%%s'" %% style)
return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None}
def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
# case we can only use expanded keywords.
cfg = get_config()
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree"}
try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version"}
'''
@register_vcs_handler("git", "get_keywords")
|
BSD 3-Clause New or Revised License
|
evidence-surveillance/trial2rev
|
app/views.py
|
submit_trial
|
python
|
def submit_trial():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 400, {
'ContentType': 'application/json'}
data = request.json
conn = dblib.create_con(VERBOSE=True)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
if data['nct_id'] and data['review']:
cur.execute("SELECT * FROM tregistry_entries WHERE nct_id =%s;", (data['nct_id'],))
trial_reg_data = cur.fetchone()
conn.close()
if not trial_reg_data:
missing = crud.add_missing_trial(data['nct_id'])
if not missing:
conn.close()
return json.dumps({'success': False, 'message': 'Unable to retrieve trial'}), 200, {
'ContentType': 'application/json'}
if utils.is_doi(data['review']):
data['review'] = crud.convert_id(data['review'], 'review_id')
result = crud.check_existing_review_trial(data['review'], data['nct_id'])
if not result:
crud.review_trial(data['review'], data['nct_id'], False, data['relationship'], current_user.nickname,
current_user.db_id)
return json.dumps({'success': True, 'message': 'Added trial successfully', 'data': str(data)}), 200, {
'ContentType': 'application/json'}
elif data['relationship'] == result['relationship']:
return json.dumps({'success': False, 'message': 'Trial already exists', 'move': False}), 200, {
'ContentType': 'application/json'}
elif data['relationship'] == 'relevant' and result['relationship'] == 'included':
return json.dumps(
{'success': False, 'message': 'Trial is already listed as included', 'move': True}), 200, {
'ContentType': 'application/json'}
else:
return json.dumps(
{'success': False, 'message': 'Trial already in list of relevant trials', 'move': True}), 200, {
'ContentType': 'application/json'}
|
submit a relevant or included trial for the current article
@return: success/failure message
|
https://github.com/evidence-surveillance/trial2rev/blob/c007df6ac54fa9f446c6a3c6b29442e4d77970df/app/views.py#L807-L848
|
import json
import psycopg2.extras
from flask import render_template, request, url_for, redirect, flash, send_file, abort
from flask_login import login_required, LoginManager, login_user, logout_user, current_user
from itsdangerous import URLSafeTimedSerializer
import bot
import config
import dblib
import plot
import crud
from app import app, mail, socketio, cache
from .forms import EmailPasswordForm, NewUserForm, ChangePasswordForm, ForgotPasswordForm, PasswordForm, RequestRegisterForm, ContactForm
from .user import User
from celery import chord
import random
import utils
import request_data
import eventlet
from flask_socketio import emit
from eutils import Client
from collections import OrderedDict
from timeit import default_timer as time
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
ts = URLSafeTimedSerializer(app.secret_key)
eutils_key = config.EUTILS_KEY
@socketio.on('connect')
def test_connect():
emit('my_response', {'data': 'Connected'})
@socketio.on('trigger_basicbot2')
def trigger_basicbot2(json):
review = json['review_id']
if not bot.check_basicbot2_running(review):
bot.basicbot2.delay(review_id=review, sess_id=request.sid)
@app.route('/plot', methods=['POST'])
def get_plot():
ids = crud.get_locked()
test_id = random.choice(ids)
review_data = crud.review_medtadata_db(test_id)
trials = crud.get_review_trials_fast(test_id, usr=current_user if current_user.is_authenticated else None)
return json.dumps(
{'success': True, 'data': {'section': 'plot', 'data': plot.get_tsne_data(trials['reg_trials']), 'page': 'home',
'review_id': test_id,
'title': review_data['title']}
}), 200, {
'ContentType': 'application/json'}
@socketio.on('get_trial')
def trial_data(data):
trial_id = data['trial_id']
trial = crud.get_trial_data(trial_id)
socketio.emit('trial_data', {
'trial': trial
}, room=request.sid)
@socketio.on('refresh_related')
def refresh_related(data):
trials = data['trials']
related = crud.related_reviews_from_trials(trials)
socketio.emit('page_content', {
'section': 'related_reviews_update',
'data': render_template('related_review_item.html', related_reviews=related)
}, room=request.sid)
@socketio.on('freetext_trials')
def freetext_trials(data):
start = time()
freetext = ''
if 'abstract' in data:
freetext = data['abstract']
crud.update_ftext_review(data['review_id'], current_user.db_id, freetext)
else:
freetext = crud.get_ftext_review(data['review_id'], current_user.db_id)['abstract']
bp1 = time()
print('1 Time since last breakpoint: ', bp1 - start)
print('Total time: ', bp1 - start)
emit('blank_update', {'msg': 'finding similar trials'}, room=request.sid)
trial_ids = list(
OrderedDict.fromkeys(
bot.basicbot2_freetext(data['review_id']) + bot.docsim_freetext(freetext)
).keys()
)
bp2 = time()
print('2 Time since last breakpoint: ', bp2 - bp1)
print('Total time: ', bp2 - start)
emit('blank_update', {'msg': 'retrieving related reviews'}, room=request.sid)
related = crud.related_reviews_from_trials(trial_ids, True)
recommended_trials = crud.get_trials_by_id(trial_ids, True) if trial_ids else []
flagged_trials = crud.get_ftext_trials_fast(data['review_id'])['reg_trials']
flagged_ids = [flagged_trial['nct_id'] for flagged_trial in flagged_trials]
recommended_trials = [trial for trial in recommended_trials if trial['nct_id'] not in flagged_ids]
plot_trials = []
for t in (recommended_trials + flagged_trials):
t = dict(t)
t['sum'] = 2
t['verified'] = False
t['relationship'] = 'included' if t['nct_id'] in flagged_ids else 'relevant'
plot_trials.append(t)
emit('blank_update', {'msg': 'loading plots'}, room=request.sid)
formatted = utils.trials_to_plotdata(plot_trials)
socketio.emit('page_content',
{'section': 'plot', 'data': formatted, 'page': 'blank',
}, room=request.sid)
emit('blank_update', {'msg': 'rendering page'}, room=request.sid)
bp3 = time()
print('3 Time since last breakpoint: ', bp3 - bp2)
print('Total time: ', bp3 - start)
bp4 = time()
print('4 Time since last breakpoint: ', bp4 - bp3)
print('Total time: ', bp4 - start)
emit('page_content', {
'section': 'recommended_trials',
'data': render_template('recommended_trials.html', reg_trials=recommended_trials),
}, room=request.sid)
emit('page_content', {
'section': 'related_reviews',
'data': render_template('related_reviews.html', related_reviews=related)
}, room=request.sid)
emit('page_content',
{'section': 'incl_trials',
'data': render_template('ftext_incl_trials.html', reg_trials=flagged_trials)
}, room=request.sid)
emit('blank_update', {'msg': 'loading complete'}, room=request.sid)
bp5 = time()
print('5 Time since last breakpoint: ', bp5 - bp4)
print('Total time: ', bp5 - start)
@socketio.on('refresh_trials')
def refresh_trials(json):
id = json['review_id']
type = json['type']
plot_bool = json['plot']
ftext_bool = json.get('ftext', False)
sort = json['sort'] if 'sort' in json else 'total_votes'
if ftext_bool:
trials = crud.get_ftext_trials_fast(id)['reg_trials']
emit('page_content',
{'section': 'incl_trials',
'sort': sort,
'data': render_template('ftext_incl_trials.html', reg_trials=trials)
}, room=request.sid)
if plot_bool:
recommended_trials = crud.get_trials_by_id(json['rec_trials'])
flagged_ids = [trial['nct_id'] for trial in trials]
recommended_trials = [trial for trial in recommended_trials if trial['nct_id'] not in flagged_ids]
plot_trials = []
for t in (recommended_trials + trials):
t = dict(t)
t['sum'] = 2
t['verified'] = False
t['relationship'] = 'included' if t['nct_id'] in flagged_ids else 'relevant'
plot_trials.append(t)
formatted = utils.trials_to_plotdata(plot_trials)
socketio.emit('page_content',
{'section': 'plot', 'data': formatted, 'page': 'reviewdetail',
'review_id': id
}, room=request.sid)
else:
trials = crud.get_review_trials_fast(id, order=sort,
usr=current_user if current_user.is_authenticated else None)
locked = crud.review_lock_status(id)
relevant = [trial['nct_id'] for trial in trials['reg_trials'] if trial['relationship'] == 'relevant']
verified = [trial['nct_id'] for trial in trials['reg_trials'] if trial['relationship'] == 'included']
if (type == 'rel' and relevant) or (type == 'incl' and verified):
emit('page_content',
{'section': 'rel_trials' if type == 'rel' else 'incl_trials', 'sort': sort,
'data': render_template('rel_trials.html' if type == 'rel' else 'incl_trials.html',
reg_trials=trials['reg_trials'],
locked=locked)}, room=request.sid)
if plot_bool:
formatted = utils.trials_to_plotdata(trials['reg_trials'])
socketio.emit('page_content',
{'section': 'plot', 'data': formatted, 'page': 'reviewdetail',
'review_id': id
}, room=request.sid)
elif type == 'incl' and not verified['ids']:
emit('page_content',
{'section': 'incl_trials', 'sort': sort,
'data': render_template('incl_trials.html',
reg_trials=[],
locked=False)}, room=request.sid)
@socketio.on('search')
def search(json):
id = json['review_id']
emit('search_update', {'msg': 'Searching...'}, room=request.sid)
eventlet.sleep(0)
if not id:
emit('page_content', {'section': 'no_results', 'data': render_template('noresults.html', id=id)},
room=request.sid)
return
conn = dblib.create_con(VERBOSE=True)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
review = ''
found = True
if (utils.RepresentsInt(id)):
review = crud.review_medtadata_db(id)
elif utils.is_doi(id):
cur.execute("SELECT * FROM systematic_reviews WHERE doi = %s;", (id,))
review = cur.fetchone()
conn.close()
else:
conn.close()
emit('search_update', {'msg': 'Searching for keyword matches in our database'}, room=request.sid)
search_result = request_data.advanced_search(id)
if not search_result:
emit('page_content', {'section': 'no_results', 'data': render_template('noresults.html', id=id)},
room=request.sid)
return
emit('page_content', {'section': 'search_results',
'data': render_template('searchresult.html', reviews=search_result, searchterm=id)},
room=request.sid)
return
if review is None:
found = False
if not current_user.is_authenticated:
conn.close()
emit('page_content', {'section': 'no_results', 'data': render_template('noresults.html', id=id)},
room=request.sid)
return
emit('search_update', {'msg': 'Not found in local database. Searching PubMed for article'}, room=request.sid)
eventlet.sleep(0)
if utils.is_doi(id):
convert = crud.convert_id(id, 'pmid')
if convert:
id = convert
else:
emit('search_update', {'msg': 'Not found in Pubmed :('},
room=request.sid)
emit('page_content', {'section': 'no_results', 'data': render_template('noresults.html', id=id)},
room=request.sid)
return
ec = Client(api_key=eutils_key)
article = ec.efetch(db='pubmed', id=id)
found_review = None
for art in article:
if art and str(art.pmid) == id:
found_review = art
break
if found_review:
result = found_review.pmid
if not result:
flash('Unable to retrieve metadata for this article. Please try again later')
abort(404)
emit('search_update', {'msg': 'Found article on PubMed. Downloading metadata...'}, room=request.sid)
eventlet.sleep(0)
crud.pubmedarticle_to_db(found_review, 'systematic_reviews')
review = crud.review_medtadata_db(id)
emit('page_content', {'data': render_template('review_data.html', review=review), 'section': 'review_data'},
room=request.sid)
eventlet.sleep(0)
emit('search_update', {'msg': 'Saved metadata... triggering bots'}, room=request.sid)
bot.docsim.delay(id, sess_id=request.sid)
eventlet.sleep(0)
if 'cochrane' in review['source'].lower() and 'doi' in review:
cb_bb = bot.cochrane_ongoing_excluded.si(review['doi'], id, sess_id=request.sid)
cb_bb.link(bot.basicbot2.si(review_id=id, sess_id=request.sid))
chord((bot.cochranebot.s(review['doi'], id, sess_id=request.sid),
bot.check_citations.s(id, sess_id=request.sid)),
cb_bb).delay()
else:
chord((bot.check_citations.s(id, sess_id=request.sid)),
bot.basicbot2.si(review_id=id, sess_id=request.sid)).delay()
else:
print
emit('page_content', {'section': 'no_results', 'data': render_template('noresults.html', id=id)},
room=request.sid)
return
if found:
print
eventlet.sleep(0)
emit('search_update', {'msg': 'Found review in our database! Retrieving data..'}, room=request.sid)
eventlet.sleep(0)
print
emit('page_content', {'data': render_template('review_data.html', review=review,
starred=crud.is_starred(review['review_id'],
current_user.db_id) if current_user.is_authenticated else False),
'section': 'review_data',
'related_reviews': render_template('related_reviews.html',
related_reviews=crud.related_reviews(
review['review_id']))},
room=request.sid)
eventlet.sleep(0)
trials = crud.get_review_trials_fast(review[0], usr=current_user if current_user.is_authenticated else None)
relevant = [trial['nct_id'] for trial in trials['reg_trials'] if trial['relationship'] == 'relevant']
verified = [trial['nct_id'] for trial in trials['reg_trials'] if trial['relationship'] == 'included']
emit('search_update', {'msg': 'Generating cool plots...'}, room=request.sid)
eventlet.sleep(0)
formatted = utils.trials_to_plotdata(trials['reg_trials'])
socketio.emit('page_content',
{'section': 'plot', 'data': formatted, 'page': 'reviewdetail',
'review_id': review[0]
}, room=request.sid)
emit('page_content',
{'section': 'rel_trials', 'data': render_template('rel_trials.html', reg_trials=trials['reg_trials'],
locked=review['included_complete'])}, room=request.sid)
eventlet.sleep(0)
if verified:
emit('page_content',
{'section': 'incl_trials', 'data': render_template('incl_trials.html', reg_trials=trials['reg_trials'],
locked=review['included_complete'])},
room=request.sid)
eventlet.sleep(0)
else:
emit('page_content',
{'section': 'incl_trials', 'data': render_template('incl_trials.html', reg_trials=[],
locked=False)}, room=request.sid)
@login_manager.user_loader
def load_user(id):
obj = User.get(id)
if obj is not None:
return obj
else:
return None
@cache.cached(timeout=60)
@app.route('/')
def index():
return render_template('index.html')
@cache.cached(timeout=60)
@app.route('/data_summary', methods=['GET'])
def unique_reviews_trials():
return json.dumps({'success': True, 'data': crud.data_summary()
}, default=str), 200, {
'ContentType': 'application/json'}
@cache.cached(timeout=600)
@app.route('/browse')
def browse():
categories = [{
"name": category['category'],
"badge_code": category['code'],
"href": "/category/%s" % category['id']
} for category in crud.get_categories()]
return render_template('browse.html', items=categories)
@cache.cached(timeout=86400)
@app.route('/category/<category>')
def browse_category(category):
conditions = [{
"name": condition['condition'],
"badge_code": "condition_%s" % condition['id'],
"href": "/condition/%s" % condition['id']
} for condition in crud.get_conditions(category)]
return render_template('browse.html',
items=conditions,
title=crud.category_name(category)
)
@app.route('/condition_counts', methods=['POST'])
def condition_counts():
data = request.json
try:
only_verified = bool(int(data['onlyVerified']))
except ValueError as e:
return json.dumps({'success': False, 'msg': 'bad value for onlyVerified'
}), 400, {
'ContentType': 'application/json'}
return json.dumps({'success': True, 'data': crud.condition_counts(data['category'], only_verified)
}), 200, {
'ContentType': 'application/json'}
@app.route('/category_counts', methods=['GET'])
def category_counts():
try:
only_verified = bool(int(request.args.get('onlyVerified')))
except ValueError as e:
return json.dumps({'success': False, 'msg': 'bad value for onlyVerified'
}), 400, {
'ContentType': 'application/json'}
return json.dumps({'success': True, 'data': crud.category_counts(only_verified)
}), 200, {
'ContentType': 'application/json'}
@cache.cached(timeout=60)
@app.route('/condition/<condition>')
def review_conditions(condition):
return render_template('reviews_by_condition.html', reviews=crud.reviews_for_condition(condition))
@app.route('/information')
def information():
return render_template('information.html')
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for('login', _external=True, _scheme='https'))
@app.route('/login', methods=['GET'])
def login():
return render_template('login.html', loginform=EmailPasswordForm(), forgotpw=ForgotPasswordForm(),
accessform=RequestRegisterForm())
@app.route('/login', methods=['POST'])
def submit_login():
if request.form['submit'] == "Login":
login_form = EmailPasswordForm(request.form)
if login_form.validate_on_submit():
registered_user = User.get(login_form.login_email.data)
if registered_user is None or registered_user.password is None:
flash('Username is invalid', 'error')
return render_template('login.html', loginform=login_form, forgotpw=ForgotPasswordForm(),
accessform=RequestRegisterForm())
if not registered_user.check_password(login_form.password.data):
flash('Password is invalid', 'error')
return render_template('login.html', loginform=login_form, forgotpw=ForgotPasswordForm(),
accessform=RequestRegisterForm())
login_user(registered_user)
return redirect(request.args.get('next') or url_for('index', _external=True, _scheme='https'))
else:
return render_template('login.html', loginform=login_form, forgotpw=ForgotPasswordForm(),
accessform=RequestRegisterForm())
@app.route('/search', methods=['GET'])
def search():
return render_template('reviewdetail.html')
@app.route('/trial', methods=['GET'])
def trial():
return render_template('trial.html')
@app.route('/blank', methods=['GET'])
@login_required
def blank():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
review_id = request.args.get('id')
if not review_id:
review_id = crud.get_most_recent_ftext_review(current_user.db_id)
return redirect('/blank?id=%s' % review_id)
review = crud.get_ftext_review(review_id, current_user.db_id)
if not review:
return "That resource does not exist.", 404, {
'ContentType': 'application/json'}
if current_user.db_id != review['user_id']:
return "Sorry! You do not have access to view this.", 403, {
'ContentType': 'application/json'}
return render_template('blank.html', review_id=review_id, abstract=review['abstract'], title=review['title'])
@app.route('/recent_ftext_review', methods=['GET'])
def recent_ftext_review():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
user_id = current_user.db_id
idx = crud.get_most_recent_ftext_review(user_id)
return json.dumps({'success': True, 'message': 'Review retrieved successfully', 'idx': idx}), 200, {
'ContentType': 'application/json'}
@app.route('/createftext', methods=['POST'])
def create_ftext_review():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
idx = crud.create_ftext_review(current_user.db_id)
return json.dumps({'success': True, 'message': 'Review created successfully', 'idx': idx}), 201, {
'ContentType': 'application/json'}
@app.route('/deleteftext', methods=['POST'])
def delete_ftext_review():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
data = request.json
review_id = data['review_id']
user_id = current_user.db_id
idx = crud.delete_ftext_review(review_id, user_id)
if idx:
return json.dumps({'success': True, 'message': 'Review deleted successfully', 'idx': review_id}), 200, {
'ContentType': 'application/json'}
else:
return json.dumps({'success': False, 'message': 'Review not found', 'idx': review_id}), 404, {
'ContentType': 'application/json'}
@app.route('/updateftexttitle', methods=['POST'])
def update_ftext_title():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
data = request.json
review_id = data['review_id']
user_id = current_user.db_id
title = data['title']
idx = crud.update_ftext_title(review_id, title, user_id)
if idx:
return json.dumps({'success': True, 'message': 'Review deleted successfully', 'idx': review_id}), 200, {
'ContentType': 'application/json'}
else:
return json.dumps({'success': False, 'message': 'Review not found', 'idx': review_id}), 404, {
'ContentType': 'application/json'}
@app.route('/saved', methods=['GET'])
@login_required
def saved():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
reviews = crud.get_saved_reviews(current_user.db_id)
ftext_reviews = crud.get_ftext_reviews(current_user.db_id)
return render_template('saved.html', reviews=reviews, ftext_reviews=ftext_reviews)
@app.route('/save_review', methods=['POST'])
def save_review():
data = request.json
crud.save_review(data['review_id'], current_user.db_id, data['value'])
return json.dumps({'success': True, 'message': 'Review saved successfully'}), 200, {
'ContentType': 'application/json'}
@app.route('/included_relevant', methods=['POST'])
def incl_rel():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 400, {
'ContentType': 'application/json'}
data = request.json
if utils.is_doi(data['review']):
data['review'] = crud.convert_id(data['review'], 'pmid')
link_id = crud.get_link_id(data['nct_id'], data['review'])
crud.change_relationship(link_id, 'relevant')
return json.dumps({'success': True, 'message': 'Trial moved successfully'}), 200, {
'ContentType': 'application/json'}
@app.route('/download/<detail>', methods=['GET'])
@login_required
def download_matrix(detail):
try:
if detail == 'all':
return send_file('../review_trial_matrix.csv', as_attachment=True)
if detail == 'complete':
return send_file('../complete_review_matrix.csv', as_attachment=True)
except Exception as e:
abort(404)
@app.route('/download', methods=['GET'])
@login_required
def download():
return render_template('download.html')
@app.route('/relevant_included', methods=['POST'])
def rel_incl():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 400, {
'ContentType': 'application/json'}
data = request.json
if utils.is_doi(data['review']):
data['review'] = crud.convert_id(data['review'], 'pmid')
link_id = crud.get_link_id(data['nct_id'], data['review'])
crud.change_relationship(link_id, 'included')
return json.dumps({'success': True, 'message': 'Trial moved successfully'}), 200, {
'ContentType': 'application/json'}
@app.route('/included_complete', methods=['POST'])
def included_complete():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 400, {
'ContentType': 'application/json'}
data = request.json
review = data['review_id']
complete = data['value']
crud.complete_studies(review, complete)
return json.dumps({'success': True, 'message': 'Thanks for verifying!'}), 200, {
'ContentType': 'application/json'}
@app.route('/vote', methods=['POST'])
def vote():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 400, {
'ContentType': 'application/json'}
current_userid = current_user.db_id
data = request.json
if utils.is_doi(data['review']):
data['review'] = crud.convert_id(data['review'], 'pmid')
conn = dblib.create_con(VERBOSE=True)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
link_id = crud.get_link_id(data['id'], data['review'])
cur.execute(
"SELECT * FROM votes WHERE link_id = %s AND user_id = %s;",
(link_id, current_userid))
current = cur.fetchone()
if data['up'] and (not current or (current and current['vote_type'] == 'down')):
crud.vote(link_id, 'up', current_userid)
if data['down'] and (not current or (current and current['vote_type'] == 'up')):
crud.vote(link_id, 'down', current_userid)
if current and (data['up'] is False and data['down'] is False) or (data['up'] is False and data['down'] == 0) or (
data['down'] is False and data['up'] == 0):
cur.execute("DELETE FROM votes WHERE vote_id = %s;", (current['vote_id'],))
conn.commit()
conn.close()
return json.dumps({'success': True, 'voters': update_voters(data['review'], data['id'])}), 200, {
'ContentType': 'application/json'}
@app.route('/removeftexttrial', methods=['POST'])
def remove_ftext_trial():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
data = request.json
if data['nct_id'] and data['review_id']:
crud.remove_ftext_trial(data['review_id'], data['nct_id'])
return json.dumps({'success': True, 'message': 'Trial removed successfully'}), 200, {
'ContentType': 'application/json'}
else:
return json.dumps(
{'success': False, 'message': 'Request requires nct_id and review_id parameters', 'move': True}), 400, {
'ContentType': 'application/json'}
@app.route('/submitftexttrial', methods=['POST'])
def submit_ftext_trial():
if not current_user.is_authenticated:
return "Sorry! This action is only available to logged-in users", 401, {
'ContentType': 'application/json'}
data = request.json
if data['nct_id'] and data['review']:
crud.link_ftext_trial(data['review'], data['nct_id'])
return json.dumps({'success': True, 'message': 'Added trial successfully'}), 201, {
'ContentType': 'application/json'}
else:
return json.dumps(
{'success': False, 'message': 'Request requires nct_id and review_id parameters', 'move': True}), 400, {
'ContentType': 'application/json'}
@app.route('/submittrial', methods=['POST'])
|
MIT License
|
mozilla/firefox-flicks
|
vendor-local/lib/python/requests/adapters.py
|
HTTPAdapter.get_connection
|
python
|
def get_connection(self, url, proxies=None):
proxies = proxies or {}
proxy = proxies.get(urlparse(url).scheme)
if proxy:
proxy = prepend_scheme_if_needed(proxy, urlparse(url).scheme)
conn = proxy_from_url(proxy)
else:
conn = self.poolmanager.connection_from_url(url)
return conn
|
Returns a connection for the given URL.
|
https://github.com/mozilla/firefox-flicks/blob/ad19ed59aac682744badae6d19a149327037f293/vendor-local/lib/python/requests/adapters.py#L116-L127
|
import socket
from .models import Response
from .packages.urllib3.poolmanager import PoolManager, proxy_from_url
from .packages.urllib3.response import HTTPResponse
from .hooks import dispatch_hook
from .compat import urlparse, basestring, urldefrag
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
prepend_scheme_if_needed)
from .structures import CaseInsensitiveDict
from .packages.urllib3.exceptions import MaxRetryError
from .packages.urllib3.exceptions import TimeoutError
from .packages.urllib3.exceptions import SSLError as _SSLError
from .packages.urllib3.exceptions import HTTPError as _HTTPError
from .cookies import extract_cookies_to_jar
from .exceptions import ConnectionError, Timeout, SSLError
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
class BaseAdapter(object):
def __init__(self):
super(BaseAdapter, self).__init__()
def send(self):
raise NotImplementedError
def close(self):
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE):
self.max_retries = DEFAULT_RETRIES
self.config = {}
super(HTTPAdapter, self).__init__()
self.init_poolmanager(pool_connections, pool_maxsize)
def init_poolmanager(self, connections, maxsize):
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize)
def cert_verify(self, conn, url, verify, cert):
if url.startswith('https') and verify:
cert_loc = None
if verify is not True:
cert_loc = verify
if not cert_loc:
cert_loc = DEFAULT_CA_BUNDLE_PATH
if not cert_loc:
raise Exception("Could not find a suitable SSL CA certificate bundle.")
conn.cert_reqs = 'CERT_REQUIRED'
conn.ca_certs = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.ca_certs = None
if cert:
if not isinstance(cert, basestring):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
conn.cert_file = cert
def build_response(self, req, resp):
response = Response()
response.status_code = getattr(resp, 'status', None)
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
extract_cookies_to_jar(response.cookies, req, resp)
response.request = req
response.connection = self
response = dispatch_hook('response', req.hooks, response)
return response
|
BSD 3-Clause New or Revised License
|
discreetai/dashboard-api
|
dashboard-api/app.py
|
delete_repo
|
python
|
def delete_repo(repo_id):
claims = authorize_user(request, use_header=False)
if not claims: return jsonify(make_unauthorized_error()), 200
user_id = claims["pk"]
try:
run_delete_routine(repo_id)
api_key = _remove_api_key(user_id, repo_id)
_remove_logs(repo_id)
_remove_repo_from_user_details(user_id, repo_id, api_key)
_remove_creds_from_repo(user_id, repo_id)
_remove_repo_details(user_id, repo_id)
except Exception as e:
return jsonify(make_error(str(e))), 200
return jsonify({
"Error": False,
})
|
Deletes a repo under the authenticated user.
|
https://github.com/discreetai/dashboard-api/blob/918e7e00689852190d4795ef00ed47a91cb377cc/dashboard-api/app.py#L144-L166
|
import re
import time
import secrets
import decimal
import hashlib
import jwt
import boto3
import requests
from flask_cors import CORS
from boto3.dynamodb.conditions import Key, Attr
from flask import Flask, request, jsonify
from deploy import run_deploy_routine, run_delete_routine
from dynamodb import DB
JWT_SECRET = "datajbsnmd5h84rbewvzx6*cax^jgmqw@m3$ds_%z-4*qy0n44fjr5shark"
JWT_ALGO = "HS256"
APPLICATION_NAME = "cloud-node"
app = Flask(__name__)
db = DB()
CORS(app)
@app.route("/")
def home():
return "This is the dashboard api homepage!"
@app.route('/reset_state/<repo_id>', methods=['POST', 'GET'])
def reset_state(repo_id):
claims = authorize_user(request, use_header=False)
if claims is None: return jsonify(make_unauthorized_error()), 400
try:
response = requests.get(CLOUD_BASE_ENDPOINT.format(repo_id))
except Exception as e:
print("Error: " + str(e))
return jsonify(make_error(str(e)))
return jsonify(make_success(response.text))
@app.route('/get_username/<repo_id>', methods=['POST', 'GET'])
def get_username(repo_id):
claims = authorize_user(request, use_header=False)
if claims is None: return jsonify(make_unauthorized_error()), 400
user_id = claims["pk"]
try:
username = db.get_username(user_id, repo_id)
except Exception as e:
print("Error: " + str(e))
return jsonify(make_error(str(e)))
return jsonify(make_success(username))
@app.route("/userdata", methods=["GET"])
def get_user_data():
claims = authorize_user(request)
if claims is None: return jsonify(make_unauthorized_error()), 400
user_id = claims["pk"]
try:
user_data = _get_user_data(user_id)
repos_remaining = user_data['ReposRemaining']
except:
return jsonify(make_error("Error while getting user's permissions.")), 400
return jsonify({"ReposRemaining": True if repos_remaining > 0 else False})
@app.route("/repo/<repo_id>", methods=["GET"])
def get_repo(repo_id):
claims = authorize_user(request)
if claims is None: return jsonify(make_unauthorized_error()), 400
user_id = claims["pk"]
try:
repo_details = _get_repo_details(user_id, repo_id)
except:
return jsonify(make_error("Error while getting the details for this repo.")), 400
return jsonify(repo_details)
@app.route("/repo", methods=["POST"])
def create_new_repo():
claims = authorize_user(request)
if claims is None: return jsonify(make_unauthorized_error()), 400
params = request.get_json()
if "RepoName" not in params:
return jsonify(make_error("Missing repo name from request.")), 400
if "RepoDescription" not in params:
return jsonify(make_error("Missing repo description from request.")), 400
repo_name = params["RepoName"][:20]
repo_description = params["RepoDescription"][:80]
user_id = claims["pk"]
repo_name = re.sub('[^a-zA-Z0-9-]', '-', repo_name)
try:
_assert_user_has_repos_left(user_id)
repo_id = _create_new_repo_document(user_id, repo_name, repo_description)
api_key, true_api_key = _create_new_api_key(user_id, repo_id)
_update_user_data_with_new_repo(user_id, repo_id, api_key)
_create_new_cloud_node(repo_id, api_key)
except Exception as e:
return jsonify(make_error(str(e))), 200
return jsonify({
"Error": False,
"Results": {
"RepoId": repo_id,
"TrueApiKey": true_api_key
}
})
@app.route("/delete/<repo_id>", methods=["POST"])
|
MIT License
|
google/qkeras
|
qkeras/qtools/qgraph.py
|
GraphRemoveNodeWithNodeType
|
python
|
def GraphRemoveNodeWithNodeType(graph, node_type):
nodes_to_remove = [v for v in graph.nodes
if graph.nodes[v]["type"][-1] == node_type]
for v in nodes_to_remove:
GraphRemoveNode(graph, v)
|
Removes node with attribute node_type, reconnecting network.
|
https://github.com/google/qkeras/blob/8dbc20d3ca32cf4536ad675d57e70586f8aedbb2/qkeras/qtools/qgraph.py#L59-L67
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import networkx as nx
import tensorflow.keras.backend as K
from tensorflow.keras.layers import InputLayer
from qkeras.qtools.quantized_operators import quantizer_factory as quantizer_factory_module
from qkeras.qtools.settings import cfg
SOURCE = -1
SINK = -2
class WrongInputQuantizerError(ValueError):
pass
def GraphRemoveNode(graph, v):
incoming = [u for u in graph.predecessors(v) if u != v]
outgoing = [w for w in graph.successors(v) if w != v]
for u in incoming:
for w in outgoing:
in_attr = graph[u][v]
out_attr = graph[v][w]
assert list(in_attr["shape"]) == list(out_attr["shape"])
graph.add_edges_from([(u, w, out_attr)])
graph.remove_node(v)
|
Apache License 2.0
|
sony/nnabla
|
python/src/nnabla/backward_function/max.py
|
max_backward
|
python
|
def max_backward(inputs, axes=None, keep_dims=False, with_index=False, only_index=False):
dy = inputs[0]
x0 = inputs[1]
y0 = get_output(x0, "Max")
if keep_dims:
y0 = F.broadcast(y0, x0.shape)
dy = F.broadcast(dy, x0.shape)
else:
axes = [i for i in range(
x0.ndim)] if axes is None else force_list(axes)
shape = [1 if i in axes else s for i, s in enumerate(x0.shape)]
y0 = F.broadcast(F.reshape(y0, shape, inplace=False), x0.shape)
dy = F.broadcast(F.reshape(dy, shape, inplace=False), x0.shape)
m0 = F.equal(x0, y0)
m0 = no_grad(m0)
dx0 = dy * m0
if not with_index and not only_index:
return dx0
elif with_index:
return dx0, None
elif only_index:
return None
|
Args:
inputs (list of nn.Variable): Incomming grads/inputs to/of the forward function.
kwargs (dict of arguments): Dictionary of the corresponding function arguments.
Return:
list of Variable: Return the gradients wrt inputs of the corresponding function.
|
https://github.com/sony/nnabla/blob/fef9b6bca02a002de880a13f3196df14369445f4/python/src/nnabla/backward_function/max.py#L21-L50
|
import nnabla.functions as F
from .utils import no_grad, force_list, get_output
|
Apache License 2.0
|
tusimple/simpledet
|
models/tridentnet/resnet_v1.py
|
TridentResNetV1Builder.resnet_trident_unit
|
python
|
def resnet_trident_unit(cls, data, name, filter, stride, dilate, proj, norm_type, norm_mom, ndev,
branch_ids, branch_bn_shared, branch_conv_shared, branch_deform=False):
if branch_ids is None:
branch_ids = range(len(data))
norm = X.normalizer_factory(type=norm_type, ndev=ndev, mom=norm_mom)
conv1 = cls.conv_shared(
data, name=name + "_conv1", num_filter=filter // 4, kernel=(1, 1), stride=stride,
branch_ids=branch_ids, share_weight=branch_conv_shared)
bn1 = cls.bn_shared(
conv1, name=name + "_bn1", normalizer=norm, branch_ids=branch_ids, share_weight=branch_bn_shared)
relu1 = [X.relu(bn) for bn in bn1]
if not branch_deform:
conv2 = cls.conv_shared(
relu1, name=name + "_conv2", num_filter=filter // 4, kernel=(3, 3),
pad=dilate, dilate=dilate,
branch_ids=branch_ids, share_weight=branch_conv_shared)
else:
conv2_offset = cls.conv_shared(
relu1, name=name + "_conv2_offset", num_filter=72, kernel=(3, 3),
pad=(1, 1), stride=(1, 1), dilate=(1, 1), no_bias=False,
branch_ids=branch_ids, share_weight=branch_conv_shared)
conv2 = cls.deform_conv_shared(
relu1, name=name + "_conv2", conv_offset=conv2_offset, num_filter=filter // 4, kernel=(3, 3),
pad=dilate, dilate=dilate, num_deformable_group=4,
branch_ids=branch_ids, share_weight=branch_conv_shared)
bn2 = cls.bn_shared(
conv2, name=name + "_bn2", normalizer=norm, branch_ids=branch_ids, share_weight=branch_bn_shared)
relu2 = [X.relu(bn) for bn in bn2]
conv3 = cls.conv_shared(
relu2, name=name + "_conv3", num_filter=filter, kernel=(1, 1),
branch_ids=branch_ids, share_weight=branch_conv_shared)
bn3 = cls.bn_shared(
conv3, name=name + "_bn3", normalizer=norm, branch_ids=branch_ids, share_weight=branch_bn_shared)
if proj:
shortcut = cls.conv_shared(
data, name=name + "_sc", num_filter=filter, kernel=(1, 1),
branch_ids=branch_ids, share_weight=branch_conv_shared)
shortcut = cls.bn_shared(
shortcut, name=name + "_sc_bn", normalizer=norm, branch_ids=branch_ids,
share_weight=branch_bn_shared)
else:
shortcut = data
plus = [X.add(bn3_i, shortcut_i, name=name + "_plus_branch{}".format(i)) for i, bn3_i, shortcut_i in zip(branch_ids, bn3, shortcut)]
return [X.relu(p) for p in plus]
|
One resnet unit is comprised of 2 or 3 convolutions and a shortcut.
:param data:
:param name:
:param filter:
:param stride:
:param dilate:
:param proj:
:param norm_type:
:param norm_mom:
:param ndev:
:param branch_ids:
:param branch_bn_shared:
:param branch_conv_shared:
:param branch_deform:
:return:
|
https://github.com/tusimple/simpledet/blob/97413463f0bc3116f684eaf7031fd3dd6ded3149/models/tridentnet/resnet_v1.py#L104-L172
|
from __future__ import print_function
import mxnet as mx
import mxnext as X
from mxnext.backbone.resnet_v1 import Builder
bn_count = [10000]
class TridentResNetV1Builder(Builder):
def __init__(self):
super().__init__()
@staticmethod
def bn_shared(data, name, normalizer, branch_ids=None, share_weight=True):
if branch_ids is None:
branch_ids = range(len(data))
gamma = X.var(name + "_gamma")
beta = X.var(name + "_beta")
moving_mean = X.var(name + "_moving_mean")
moving_var = X.var(name + "_moving_var")
bn_layers = []
for i, data_i in zip(branch_ids, data):
if share_weight:
bn_i = normalizer(data=data_i, name=name + "_shared%d" % i,
gamma=gamma, beta=beta, moving_mean=moving_mean, moving_var=moving_var)
else:
bn_i = normalizer(data=data_i, name=name + "_branch%d" % i)
bn_layers.append(bn_i)
return bn_layers
@staticmethod
def conv_shared(data, name, kernel, num_filter, branch_ids=None, no_bias=True, share_weight=True,
pad=(0, 0), stride=(1, 1), dilate=(1, 1)):
if branch_ids is None:
branch_ids = range(len(data))
weight = X.var(name + '_weight')
if no_bias:
bias = None
else:
bias = X.var(name + '_bias')
conv_layers = []
for i in range(len(data)):
data_i = data[i]
stride_i = stride[i] if type(stride) is list else stride
dilate_i = dilate[i] if type(dilate) is list else dilate
pad_i = pad[i] if type(pad) is list else pad
branch_i = branch_ids[i]
if share_weight:
conv_i = X.conv(data=data_i, kernel=kernel, filter=num_filter, stride=stride_i, dilate=dilate_i, pad=pad_i,
name=name + '_shared%d' % branch_i, no_bias=no_bias, weight=weight, bias=bias)
else:
conv_i = X.conv(data=data_i, kernel=kernel, filter=num_filter, stride=stride_i, dilate=dilate_i, pad=pad_i,
name=name + '_branch%d' % branch_i, no_bias=no_bias)
conv_layers.append(conv_i)
return conv_layers
@staticmethod
def deform_conv_shared(data, name, conv_offset, kernel, num_filter, branch_ids=None, no_bias=True, share_weight=True,
num_deformable_group=4, pad=(0, 0), stride=(1, 1), dilate=(1, 1)):
if branch_ids is None:
branch_ids = range(len(data))
weight = X.var(name + '_weight')
if no_bias:
bias = None
else:
bias = X.var(name + '_bias')
conv_layers = []
for i in range(len(data)):
data_i = data[i]
stride_i = stride[i] if type(stride) is list else stride
dilate_i = dilate[i] if type(dilate) is list else dilate
pad_i = pad[i] if type(pad) is list else pad
conv_offset_i = conv_offset[i] if type(conv_offset) is list else conv_offset
branch_i = branch_ids[i]
if share_weight:
conv_i = mx.contrib.symbol.DeformableConvolution(
data=data_i, offset=conv_offset_i, kernel=kernel, num_filter=num_filter, stride=stride_i, num_deformable_group=4,
dilate=dilate_i, pad=pad_i, no_bias=no_bias, weight=weight, bias=bias, name=name + '_shared%d' % branch_i)
else:
conv_i = mx.contrib.symbol.DeformableConvolution(
data=data_i, offset=conv_offset_i, kernel=kernel, num_filter=num_filter, stride=stride_i, num_deformable_group=4,
dilate=dilate_i, pad=pad_i, no_bias=no_bias, name=name + '_branch%d' % branch_i)
conv_layers.append(conv_i)
return conv_layers
@staticmethod
def stack_branch_symbols(data_list):
data = mx.symbol.stack(*data_list, axis=1)
data = mx.symbol.Reshape(data, (-3, -2))
return data
@classmethod
|
Apache License 2.0
|
slice/dogbot
|
dog/ext/info.py
|
Info.icon
|
python
|
async def icon(self, ctx: lifesaver.Context):
if not ctx.guild.icon_url:
await ctx.send("No server icon.")
return
await ctx.send(ctx.guild.icon_url_as(format="png"))
|
Sends this server's icon.
|
https://github.com/slice/dogbot/blob/7605093e2bd5b948884ff2065bf6ef2bd92620e0/dog/ext/info.py#L75-L81
|
from textwrap import dedent
import discord
import lifesaver
from discord.ext import commands
from lifesaver.utils import human_delta
from dog.converters import HardMember
def date(date) -> str:
return f"{date}\n{human_delta(date)} ago"
class Info(lifesaver.Cog):
@lifesaver.command(aliases=["about"])
async def info(self, ctx: lifesaver.Context):
app_info = await ctx.bot.application_info()
embed = discord.Embed(color=discord.Color.green())
embed.set_author(
name=ctx.bot.user,
url="https://github.com/slice/dogbot",
icon_url=ctx.bot.user.avatar_url,
)
embed.description = ctx.bot.description
embed.add_field(
name="Created", value=human_delta(ctx.bot.user.created_at) + " ago"
)
embed.set_footer(
text=f"Owned by {app_info.owner}", icon_url=app_info.owner.avatar_url
)
await ctx.send(embed=embed)
@lifesaver.group(
aliases=["guild", "guild_info", "server_info"], invoke_without_command=True
)
@commands.guild_only()
async def server(self, ctx: lifesaver.Context):
embed = discord.Embed(title=ctx.guild.name)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_footer(
text=f"Owned by {ctx.guild.owner}", icon_url=ctx.guild.owner.avatar_url
)
g: discord.Guild = ctx.guild
n_humans = sum(1 for m in g.members if not m.bot)
n_bots = len(g.members) - n_humans
embed.description = dedent(
f"""\
{n_humans} humans, {n_bots} bots ({n_humans + n_bots} members)
Created {g.created_at}
{human_delta(g.created_at)} ago
"""
)
embed.add_field(
name="Entities",
value=dedent(
f"""\
{len(g.text_channels)} text channels, {len(g.voice_channels)} voice channels, {len(g.categories)} categories
{len(g.roles)} roles
"""
),
)
await ctx.send(embed=embed)
@server.command(aliases=["icon_url"])
@commands.guild_only()
|
MIT License
|
mrod5/pyturb
|
src/pyturb/power_plant/control_volume.py
|
ControlVolume.rho_et
|
python
|
def rho_et(self):
raise NotImplementedError
|
Stagnation density at the entrance of the CV. [kg/m**3]
|
https://github.com/mrod5/pyturb/blob/08b4016528fc50733fff58d967d1000bf1e634c9/src/pyturb/power_plant/control_volume.py#L125-L129
|
from abc import abstractmethod
from pyturb.gas_models.perfect_ideal_gas import PerfectIdealGas
from pyturb.gas_models.semiperfect_ideal_gas import SemiperfectIdealGas
class ControlVolume(object):
def __init__(self, fluid):
if not(isinstance(fluid, PerfectIdealGas) or isinstance(fluid, SemiperfectIdealGas)):
raise TypeError("PerfectIdealGas, SemiperfectIdealGas")
self.fluid = fluid
return
@property
@abstractmethod
def p_e(self):
raise NotImplementedError
@property
@abstractmethod
def T_e(self):
raise NotImplementedError
@property
@abstractmethod
def rho_e(self):
raise NotImplementedError
@property
@abstractmethod
def h_e(self):
raise NotImplementedError
@property
@abstractmethod
def p_et(self):
raise NotImplementedError
@property
@abstractmethod
def T_et(self):
raise NotImplementedError
@property
@abstractmethod
|
MIT License
|
iristyle/chocolateypackages
|
EthanBrown.SublimeText2.WebPackages/tools/PackageCache/Emmet/emmet-plugin.py
|
unindent_text
|
python
|
def unindent_text(text, pad):
lines = text.splitlines()
for i,line in enumerate(lines):
if line.startswith(pad):
lines[i] = line[len(pad):]
return '\n'.join(lines)
|
Removes padding at the beginning of each text's line
@type text: str
@type pad: str
|
https://github.com/iristyle/chocolateypackages/blob/8c9833710577de6db6e8b1db5d9196e19e19d117/EthanBrown.SublimeText2.WebPackages/tools/PackageCache/Emmet/emmet-plugin.py#L197-L209
|
import sublime
import sublime_plugin
import re
import imp
import json
import sys
import os.path
import traceback
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PACKAGES_PATH = sublime.packages_path() or os.path.dirname(BASE_PATH)
EMMET_GRAMMAR = 'Packages/%s/Emmet.tmLanguage' % os.path.basename(BASE_PATH)
sys.path += [BASE_PATH] + [os.path.join(BASE_PATH, f) for f in ['emmet_completions', 'emmet']]
if 'emmet.reloader' in sys.modules:
imp.reload(sys.modules['emmet.reloader'])
import emmet.reloader
import emmet.pyv8loader as pyv8loader
import emmet_completions as cmpl
from emmet_completions.meta import HTML_ELEMENTS_ATTRIBUTES, HTML_ATTRIBUTES_VALUES
from emmet.context import Context
from emmet.context import js_file_reader as _js_file_reader
from emmet.pyv8loader import LoaderDelegate
__version__ = '1.1'
__core_version__ = '1.0'
__authors__ = ['"Sergey Chikuyonok" <serge.che@gmail.com>'
'"Nicholas Dudfield" <ndudfield@gmail.com>']
is_python3 = sys.version_info[0] > 2
ctx = None
settings = None
user_settings = None
def is_st3():
return sublime.version()[0] == '3'
def js_file_reader(file_path, use_unicode=True):
if hasattr(sublime, 'load_resource'):
rel_path = file_path
for prefix in [sublime.packages_path(), sublime.installed_packages_path()]:
if rel_path.startswith(prefix):
rel_path = os.path.join('Packages', rel_path[len(prefix) + 1:])
break
rel_path = rel_path.replace('.sublime-package', '')
rel_path = rel_path.replace('\\', '/')
return sublime.load_resource(rel_path)
return _js_file_reader(file_path, use_unicode)
def init():
globals()['user_settings'] = sublime.load_settings('Preferences.sublime-settings')
globals()['settings'] = sublime.load_settings('Emmet.sublime-settings')
settings.add_on_change('extensions_path', update_settings)
pyv8_paths = [
os.path.join(PACKAGES_PATH, 'PyV8'),
os.path.join(PACKAGES_PATH, 'PyV8', pyv8loader.get_arch()),
os.path.join(PACKAGES_PATH, 'PyV8', 'pyv8-%s' % pyv8loader.get_arch())
]
sys.path += pyv8_paths
for p in pyv8_paths:
pyv8loader.unpack_pyv8(p)
contrib = {
'sublime': sublime,
'sublimeReplaceSubstring': replace_substring,
'sublimeGetOption': settings.get
}
delegate = SublimeLoaderDelegate()
globals()['ctx'] = Context(
files=['../editor.js'],
ext_path=settings.get('extensions_path', None),
contrib=contrib,
logger=delegate.log,
reader=js_file_reader
)
update_settings()
pyv8loader.load(pyv8_paths[1], delegate)
if settings.get('remove_html_completions', False):
sublime.set_timeout(cmpl.remove_html_completions, 2000)
class SublimeLoaderDelegate(LoaderDelegate):
def __init__(self, settings=None):
if settings is None:
settings = {}
for k in ['http_proxy', 'https_proxy', 'timeout']:
if user_settings.has(k):
settings[k] = user_settings.get(k, None)
LoaderDelegate.__init__(self, settings)
self.state = None
self.message = 'Loading PyV8 binary, please wait'
self.i = 0
self.addend = 1
self.size = 8
def on_start(self, *args, **kwargs):
self.state = 'loading'
def on_progress(self, *args, **kwargs):
if kwargs['progress'].is_background:
return
before = self.i % self.size
after = (self.size - 1) - before
msg = '%s [%s=%s]' % (self.message, ' ' * before, ' ' * after)
if not after:
self.addend = -1
if not before:
self.addend = 1
self.i += self.addend
sublime.set_timeout(lambda: sublime.status_message(msg), 0)
def on_complete(self, *args, **kwargs):
self.state = 'complete'
if kwargs['progress'].is_background:
return
sublime.set_timeout(lambda: sublime.status_message('PyV8 binary successfully loaded'), 0)
def on_error(self, exit_code=-1, thread=None):
self.state = 'error'
sublime.set_timeout(lambda: show_pyv8_error(exit_code), 0)
def setting(self, name, default=None):
return self.settings.get(name, default)
def log(self, message):
print('Emmet: %s' % message)
def show_pyv8_error(exit_code):
if 'PyV8' not in sys.modules:
sublime.error_message('Error while loading PyV8 binary: exit code %s \nTry to manually install PyV8 from\nhttps://github.com/emmetio/pyv8-binaries' % exit_code)
def active_view():
return sublime.active_window().active_view()
def check_context(verbose=False):
if not ctx.js():
if verbose:
sublime.message_dialog('Please wait a bit while PyV8 binary is being downloaded')
return False
return True
def replace_substring(start, end, value, no_indent=False):
view = active_view()
view.sel().clear()
view.sel().add(sublime.Region(start, end or start))
if not is_python3:
value = value.decode('utf-8')
if no_indent:
line = view.substr(view.line(view.sel()[0]))
value = unindent_text(value, get_line_padding(line))
view.run_command('insert_snippet', {'contents': value})
|
MIT License
|
beloglazov/openstack-neat
|
neat/locals/overload/mhod/multisize_estimation.py
|
update_request_windows
|
python
|
def update_request_windows(request_windows, previous_state, current_state):
request_windows[previous_state].append(current_state)
return request_windows
|
Update and return the updated request windows.
:param request_windows: The previous request windows.
:type request_windows: list(deque)
:param previous_state: The previous state.
:type previous_state: int,>=0
:param current_state: The current state.
:type current_state: int,>=0
:return: The updated request windows.
:rtype: list(deque)
|
https://github.com/beloglazov/openstack-neat/blob/a5a853ae2affb0cdc582e3ab641737f5ebd3d0a7/neat/locals/overload/mhod/multisize_estimation.py#L98-L114
|
from contracts import contract
from neat.contracts_primitive import *
from neat.contracts_extra import *
from itertools import islice
from collections import deque
import logging
log = logging.getLogger(__name__)
@contract
def mean(data, window_size):
return float(sum(data)) / window_size
@contract
def variance(data, window_size):
m = mean(data, window_size)
return float(sum((x - m) ** 2 for x in data)) / (window_size - 1)
@contract
def acceptable_variance(probability, window_size):
return float(probability * (1 - probability)) / window_size
@contract
def estimate_probability(data, window_size, state):
return float(data.count(state)) / window_size
@contract
|
Apache License 2.0
|
lscsoft/bilby
|
bilby/gw/detector/calibration.py
|
Recalibrate.get_calibration_factor
|
python
|
def get_calibration_factor(self, frequency_array, **params):
self.set_calibration_parameters(**params)
return np.ones_like(frequency_array)
|
Apply calibration model
This method should be overwritten by subclasses
Parameters
==========
frequency_array: array-like
The frequency values to calculate the calibration factor for.
params : dict
Dictionary of sampling parameters which includes
calibration parameters.
Returns
=======
calibration_factor : array-like
The factor to multiply the strain by.
|
https://github.com/lscsoft/bilby/blob/b1e02f1dfae03d4939cae9c95eff300c22919689/bilby/gw/detector/calibration.py#L110-L129
|
import numpy as np
from scipy.interpolate import interp1d
def read_calibration_file(filename, frequency_array, number_of_response_curves, starting_index=0):
import tables
calibration_file = tables.open_file(filename, 'r')
calibration_amplitude = calibration_file.root.deltaR.draws_amp_rel[starting_index:number_of_response_curves + starting_index]
calibration_phase = calibration_file.root.deltaR.draws_phase[starting_index:number_of_response_curves + starting_index]
calibration_frequencies = calibration_file.root.deltaR.freq[:]
calibration_file.close()
if len(calibration_amplitude.dtype) != 0:
calibration_amplitude = calibration_amplitude.view(np.float64).reshape(calibration_amplitude.shape + (-1,))
calibration_phase = calibration_phase.view(np.float64).reshape(calibration_phase.shape + (-1,))
calibration_frequencies = calibration_frequencies.view(np.float64)
calibration_draws = calibration_amplitude * np.exp(1j * calibration_phase)
calibration_draws = interp1d(
calibration_frequencies, calibration_draws, kind='cubic',
bounds_error=False, fill_value=1)(frequency_array)
return calibration_draws
def write_calibration_file(filename, frequency_array, calibration_draws, calibration_parameter_draws=None):
import tables
calibration_file = tables.open_file(filename, 'w')
deltaR_group = calibration_file.create_group(calibration_file.root, 'deltaR')
calibration_file.create_carray(deltaR_group, 'draws_amp_rel', obj=np.abs(calibration_draws))
calibration_file.create_carray(deltaR_group, 'draws_phase', obj=np.angle(calibration_draws))
calibration_file.create_carray(deltaR_group, 'freq', obj=frequency_array)
calibration_file.close()
if calibration_parameter_draws is not None:
calibration_parameter_draws.to_hdf(filename, key='CalParams', data_columns=True, format='table')
class Recalibrate(object):
name = 'none'
def __init__(self, prefix='recalib_'):
self.params = dict()
self.prefix = prefix
def __repr__(self):
return self.__class__.__name__ + '(prefix=\'{}\')'.format(self.prefix)
|
MIT License
|
square/connect-python-sdk
|
squareconnect/models/create_order_request_discount.py
|
CreateOrderRequestDiscount.percentage
|
python
|
def percentage(self):
return self._percentage
|
Gets the percentage of this CreateOrderRequestDiscount.
Only used for ad hoc discounts. The percentage of the discount, as a string representation of a decimal number. A value of `7.25` corresponds to a percentage of 7.25%. This value range between 0.0 up to 100.0
:return: The percentage of this CreateOrderRequestDiscount.
:rtype: str
|
https://github.com/square/connect-python-sdk/blob/e00e2889b2dd2c55048219cbe64db79962a68633/squareconnect/models/create_order_request_discount.py#L115-L123
|
from pprint import pformat
from six import iteritems
import re
class CreateOrderRequestDiscount(object):
def __init__(self, catalog_object_id=None, name=None, percentage=None, amount_money=None):
self.swagger_types = {
'catalog_object_id': 'str',
'name': 'str',
'percentage': 'str',
'amount_money': 'Money'
}
self.attribute_map = {
'catalog_object_id': 'catalog_object_id',
'name': 'name',
'percentage': 'percentage',
'amount_money': 'amount_money'
}
self._catalog_object_id = catalog_object_id
self._name = name
self._percentage = percentage
self._amount_money = amount_money
@property
def catalog_object_id(self):
return self._catalog_object_id
@catalog_object_id.setter
def catalog_object_id(self, catalog_object_id):
if catalog_object_id is None:
raise ValueError("Invalid value for `catalog_object_id`, must not be `None`")
if len(catalog_object_id) > 192:
raise ValueError("Invalid value for `catalog_object_id`, length must be less than `192`")
self._catalog_object_id = catalog_object_id
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if name is None:
raise ValueError("Invalid value for `name`, must not be `None`")
if len(name) > 255:
raise ValueError("Invalid value for `name`, length must be less than `255`")
self._name = name
@property
|
Apache License 2.0
|
grossjohannes/alignnet-3d
|
tp_utils/pointcloud.py
|
Calibration.read_calib_file
|
python
|
def read_calib_file(self, filepath):
data = {}
with open(filepath, 'r') as f:
for line in f.readlines():
line = line.rstrip()
if len(line) == 0:
continue
key, value = line.split(' ', 1)
key = key.replace(':', '')
try:
data[key] = np.array([float(x) for x in value.split()])
except ValueError:
pass
data['Tr_velo_to_cam'] = data['Tr_velo_cam']
data['R0_rect'] = data['R_rect']
return data
|
Read in a calibration file and parse into a dictionary.
Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
|
https://github.com/grossjohannes/alignnet-3d/blob/eb34e03a38012f06f86bc2847ae4093b14355e04/tp_utils/pointcloud.py#L99-L122
|
import numpy as np
import quaternion
from pyntcloud import PyntCloud
import pyntcloud
import pandas as pd
from scipy.spatial.transform import Rotation
import io
import base64
import open3d as o3
import pythreejs
import time
import sys
import trimesh
import copy
from functools import lru_cache
from IPython.display import display, clear_output
import json
from tqdm import tqdm_notebook
import os
from PIL import Image
from tensorflow.python.util import nest
from scipy.spatial import Delaunay
import ipywidgets
from contextlib import contextmanager
def inverse_rigid_trans(Tr):
inv_Tr = np.zeros_like(Tr)
inv_Tr[0:3, 0:3] = np.transpose(Tr[0:3, 0:3])
inv_Tr[0:3, 3] = np.dot(-np.transpose(Tr[0:3, 0:3]), Tr[0:3, 3])
return inv_Tr
class Calibration(object):
def __init__(self, calib_filepath, from_video=False, from_sun=False):
if from_video:
calibs = self.read_calib_from_video(calib_filepath)
elif from_sun:
calibs = self.read_calib_from_sun(calib_filepath)
else:
calibs = self.read_calib_file(calib_filepath)
self.P = calibs['P2']
self.P = np.reshape(self.P, [3, 4])
self.V2C = calibs['Tr_velo_to_cam']
self.V2C = np.reshape(self.V2C, [3, 4])
self.C2V = inverse_rigid_trans(self.V2C)
self.R0 = calibs['R0_rect']
self.R0 = np.reshape(self.R0, [3, 3])
self.c_u = self.P[0, 2]
self.c_v = self.P[1, 2]
self.f_u = self.P[0, 0]
self.f_v = self.P[1, 1]
self.b_x = self.P[0, 3] / (-self.f_u)
self.b_y = self.P[1, 3] / (-self.f_v)
|
BSD 3-Clause New or Revised License
|
killthekitten/kaggle-carvana-2017
|
keras_iterator.py
|
ImageDataGenerator.fit
|
python
|
def fit(self, x,
augment=False,
rounds=1,
seed=None):
x = np.asarray(x, dtype=K.floatx())
if x.ndim != 4:
raise ValueError('Input to `.fit()` should have rank 4. '
'Got array with shape: ' + str(x.shape))
if x.shape[self.channel_axis] not in {1, 3, 4}:
raise ValueError(
'Expected input to be images (as Numpy array) '
'following the data format convention "' + self.data_format + '" '
'(channels on axis ' + str(
self.channel_axis) + '), i.e. expected '
'either 1, 3 or 4 channels on axis ' + str(self.channel_axis) + '. '
'However, it was passed an array with shape ' + str(
x.shape) +
' (' + str(x.shape[self.channel_axis]) + ' channels).')
if seed is not None:
np.random.seed(seed)
x = np.copy(x)
if augment:
ax = np.zeros(tuple([rounds * x.shape[0]] + list(x.shape)[1:]), dtype=K.floatx())
for r in range(rounds):
for i in range(x.shape[0]):
ax[i + r * x.shape[0]] = self.random_transform(x[i])
x = ax
if self.featurewise_center:
self.mean = np.mean(x, axis=(0, self.row_axis, self.col_axis))
broadcast_shape = [1, 1, 1]
broadcast_shape[self.channel_axis - 1] = x.shape[self.channel_axis]
self.mean = np.reshape(self.mean, broadcast_shape)
x -= self.mean
if self.featurewise_std_normalization:
self.std = np.std(x, axis=(0, self.row_axis, self.col_axis))
broadcast_shape = [1, 1, 1]
broadcast_shape[self.channel_axis - 1] = x.shape[self.channel_axis]
self.std = np.reshape(self.std, broadcast_shape)
x /= (self.std + K.epsilon())
if self.zca_whitening:
flat_x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2] * x.shape[3]))
sigma = np.dot(flat_x.T, flat_x) / flat_x.shape[0]
u, s, _ = linalg.svd(sigma)
self.principal_components = np.dot(np.dot(u, np.diag(1. / np.sqrt(s + 10e-7))), u.T)
|
Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 4.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`.
|
https://github.com/killthekitten/kaggle-carvana-2017/blob/90795b1587af0714e5499ae72a301be38014d8b9/keras_iterator.py#L516-L582
|
import os
import threading
import warnings
import keras.backend as K
import numpy as np
from keras.preprocessing.image import load_img, img_to_array, array_to_img, NumpyArrayIterator, flip_axis, random_channel_shift, apply_transform, transform_matrix_offset_center
from scipy import linalg, random
from six.moves import range
class Iterator(object):
def __init__(self, n, batch_size, shuffle, seed):
self.n = n
self.batch_size = batch_size
self.shuffle = shuffle
self.batch_index = 0
self.total_batches_seen = 0
self.lock = threading.Lock()
self.index_generator = self._flow_index(n, batch_size, shuffle, seed)
def reset(self):
self.batch_index = 0
def _flow_index(self, n, batch_size=32, shuffle=False, seed=None):
self.reset()
while 1:
if seed is not None:
np.random.seed(seed + self.total_batches_seen)
if self.batch_index == 0:
index_array = np.arange(n)
if shuffle:
index_array = np.random.permutation(n)
current_index = (self.batch_index * batch_size) % n
if n > current_index + batch_size:
current_batch_size = batch_size
self.batch_index += 1
else:
current_batch_size = n - current_index
self.batch_index = 0
self.total_batches_seen += 1
yield (index_array[current_index: current_index + current_batch_size],
current_index, current_batch_size)
def __iter__(self):
return self
def __next__(self, *args, **kwargs):
return self.next(*args, **kwargs)
class DirectoryIterator(Iterator):
def __init__(self, directory, image_data_generator,
target_size=(256, 256), color_mode='rgb',
classes=None, class_mode='categorical',
batch_size=32, shuffle=True, seed=None,
data_format=None,
save_to_dir=None, save_prefix='', save_format='jpeg',
follow_links=False, file_name_to_y=None, output_function=None):
if data_format is None:
data_format = K.image_data_format()
self.directory = directory
self.image_data_generator = image_data_generator
self.target_size = tuple(target_size)
self.output_function = output_function
self.file_name_to_y = file_name_to_y
if color_mode not in {'rgb', 'grayscale'}:
raise ValueError('Invalid color mode:', color_mode,
'; expected "rgb" or "grayscale".')
self.color_mode = color_mode
self.data_format = data_format
if self.color_mode == 'rgb':
if self.data_format == 'channels_last':
self.image_shape = self.target_size + (3,)
else:
self.image_shape = (3,) + self.target_size
else:
if self.data_format == 'channels_last':
self.image_shape = self.target_size + (1,)
else:
self.image_shape = (1,) + self.target_size
self.classes = classes
if class_mode not in {'categorical', 'binary', 'sparse', 'regression', None}:
raise ValueError('Invalid class_mode:', class_mode,
'; expected one of "categorical", '
'"binary", "sparse", "regression", or None.')
self.class_mode = class_mode
self.save_to_dir = save_to_dir
self.save_prefix = save_prefix
self.save_format = save_format
white_list_formats = {'png', 'jpg', 'jpeg', 'bmp'}
self.samples = 0
if not classes:
classes = []
for subdir in sorted(os.listdir(directory)):
if os.path.isdir(os.path.join(directory, subdir)):
classes.append(subdir)
self.num_class = len(classes)
self.class_indices = dict(zip(classes, range(len(classes))))
def _recursive_list(subpath):
return sorted(os.walk(subpath, followlinks=follow_links), key=lambda tpl: tpl[0])
for subdir in classes:
subpath = os.path.join(directory, subdir)
for root, _, files in _recursive_list(subpath):
for fname in files:
is_valid = False
for extension in white_list_formats:
if fname.lower().endswith('.' + extension):
is_valid = True
break
if is_valid:
self.samples += 1
print('Found %d images belonging to %d classes.' % (self.samples, self.num_class))
self.filenames = []
self.classes = np.zeros((self.samples,), dtype='int32')
i = 0
for subdir in classes:
subpath = os.path.join(directory, subdir)
for root, _, files in _recursive_list(subpath):
files = sorted(files)
for fname in files:
is_valid = False
for extension in white_list_formats:
if fname.lower().endswith('.' + extension):
is_valid = True
break
if is_valid:
self.classes[i] = self.class_indices[subdir]
i += 1
absolute_path = os.path.join(root, fname)
self.filenames.append(os.path.relpath(absolute_path, directory))
super(DirectoryIterator, self).__init__(self.samples, batch_size, shuffle, seed)
def next(self):
with self.lock:
index_array, current_index, current_batch_size = next(self.index_generator)
batch_x = np.zeros((current_batch_size,) + self.image_shape, dtype=K.floatx())
grayscale = self.color_mode == 'grayscale'
for i, j in enumerate(index_array):
fname = self.filenames[j]
img = load_img(os.path.join(self.directory, fname),
grayscale=grayscale,
target_size=self.target_size)
x = img_to_array(img, data_format=self.data_format)
x = self.image_data_generator.random_transform(x)
x = self.image_data_generator.standardize(x)
batch_x[i] = x
if self.save_to_dir:
for i in range(current_batch_size):
img = array_to_img(batch_x[i], self.data_format, scale=True)
fname = '{prefix}_{index}_{hash}.{format}'.format(prefix=self.save_prefix,
index=current_index + i,
hash=np.random.randint(1e4),
format=self.save_format)
img.save(os.path.join(self.save_to_dir, fname))
if self.class_mode == 'sparse':
batch_y = self.classes[index_array]
elif self.class_mode == 'binary':
batch_y = self.classes[index_array].astype(K.floatx())
elif self.class_mode == 'categorical':
batch_y = np.zeros((len(batch_x), self.num_class), dtype=K.floatx())
for i, label in enumerate(self.classes[index_array]):
batch_y[i, label] = 1.
elif self.output_function:
return self.output_function(batch_x, self.filenames, index_array, self.file_name_to_y)
else:
return batch_x
return batch_x, batch_y
class ImageDataGenerator(object):
def __init__(self,
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=0.,
width_shift_range=0.,
height_shift_range=0.,
shear_range=0.,
zoom_range=0.,
channel_shift_range=0.,
fill_mode='nearest',
cval=0.,
horizontal_flip=False,
vertical_flip=False,
rescale=None,
preprocessing_function=None,
data_format=None):
if data_format is None:
data_format = K.image_data_format()
self.featurewise_center = featurewise_center
self.samplewise_center = samplewise_center
self.featurewise_std_normalization = featurewise_std_normalization
self.samplewise_std_normalization = samplewise_std_normalization
self.zca_whitening = zca_whitening
self.rotation_range = rotation_range
self.width_shift_range = width_shift_range
self.height_shift_range = height_shift_range
self.shear_range = shear_range
self.zoom_range = zoom_range
self.channel_shift_range = channel_shift_range
self.fill_mode = fill_mode
self.cval = cval
self.horizontal_flip = horizontal_flip
self.vertical_flip = vertical_flip
self.rescale = rescale
self.preprocessing_function = preprocessing_function
if data_format not in {'channels_last', 'channels_first'}:
raise ValueError('data_format should be "channels_last" (channel after row and '
'column) or "channels_first" (channel before row and column). '
'Received arg: ', data_format)
self.data_format = data_format
if data_format == 'channels_first':
self.channel_axis = 1
self.row_axis = 2
self.col_axis = 3
if data_format == 'channels_last':
self.channel_axis = 3
self.row_axis = 1
self.col_axis = 2
self.mean = None
self.std = None
self.principal_components = None
if np.isscalar(zoom_range):
self.zoom_range = [1 - zoom_range, 1 + zoom_range]
elif len(zoom_range) == 2:
self.zoom_range = [zoom_range[0], zoom_range[1]]
else:
raise ValueError('zoom_range should be a float or '
'a tuple or list of two floats. '
'Received arg: ', zoom_range)
def flow(self, x, y=None, batch_size=32, shuffle=True, seed=None,
save_to_dir=None, save_prefix='', save_format='jpeg'):
return NumpyArrayIterator(
x, y, self,
batch_size=batch_size,
shuffle=shuffle,
seed=seed,
data_format=self.data_format,
save_to_dir=save_to_dir,
save_prefix=save_prefix,
save_format=save_format)
def flow_from_directory(self, directory,
target_size=(256, 256), color_mode='rgb',
classes=None, class_mode='categorical',
batch_size=32, shuffle=True, seed=None,
save_to_dir=None,
save_prefix='',
save_format='jpeg',
follow_links=False,
file_name_to_y=None,
output_function=None,
):
return DirectoryIterator(
directory, self,
target_size=target_size, color_mode=color_mode,
classes=classes, class_mode=class_mode,
data_format=self.data_format,
batch_size=batch_size, shuffle=shuffle, seed=seed,
save_to_dir=save_to_dir,
save_prefix=save_prefix,
save_format=save_format,
follow_links=follow_links,
file_name_to_y=file_name_to_y,
output_function=output_function
)
def standardize(self, x):
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
img_channel_axis = self.channel_axis - 1
if self.samplewise_center:
x -= np.mean(x, axis=img_channel_axis, keepdims=True)
if self.samplewise_std_normalization:
x /= (np.std(x, axis=img_channel_axis, keepdims=True) + 1e-7)
if self.featurewise_center:
if self.mean is not None:
x -= self.mean
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_center`, but it hasn\'t'
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.featurewise_std_normalization:
if self.std is not None:
x /= (self.std + 1e-7)
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_std_normalization`, but it hasn\'t'
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.zca_whitening:
if self.principal_components is not None:
flatx = np.reshape(x, (x.size))
whitex = np.dot(flatx, self.principal_components)
x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))
else:
warnings.warn('This ImageDataGenerator specifies '
'`zca_whitening`, but it hasn\'t'
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
return x
def random_transform(self, x):
img_row_axis = self.row_axis - 1
img_col_axis = self.col_axis - 1
img_channel_axis = self.channel_axis - 1
if self.rotation_range:
theta = np.pi / 180 * np.random.uniform(-self.rotation_range, self.rotation_range)
else:
theta = 0
if self.height_shift_range:
tx = np.random.uniform(-self.height_shift_range, self.height_shift_range) * x.shape[img_row_axis]
else:
tx = 0
if self.width_shift_range:
ty = np.random.uniform(-self.width_shift_range, self.width_shift_range) * x.shape[img_col_axis]
else:
ty = 0
if self.shear_range:
shear = np.random.uniform(-self.shear_range, self.shear_range)
else:
shear = 0
if self.zoom_range[0] == 1 and self.zoom_range[1] == 1:
zx, zy = 1, 1
else:
zx, zy = np.random.uniform(self.zoom_range[0], self.zoom_range[1], 2)
transform_matrix = None
if theta != 0:
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
transform_matrix = rotation_matrix
if tx != 0 or ty != 0:
shift_matrix = np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)
if shear != 0:
shear_matrix = np.array([[1, -np.sin(shear), 0],
[0, np.cos(shear), 0],
[0, 0, 1]])
transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)
if zx != 1 or zy != 1:
zoom_matrix = np.array([[zx, 0, 0],
[0, zy, 0],
[0, 0, 1]])
transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix)
if transform_matrix is not None:
h, w = x.shape[img_row_axis], x.shape[img_col_axis]
transform_matrix = transform_matrix_offset_center(transform_matrix, h, w)
x = apply_transform(x, transform_matrix, img_channel_axis,
fill_mode=self.fill_mode, cval=self.cval)
if self.channel_shift_range != 0:
x = random_channel_shift(x,
self.channel_shift_range,
img_channel_axis)
if self.horizontal_flip:
if np.random.random() < 0.5:
x = flip_axis(x, img_col_axis)
if self.vertical_flip:
if np.random.random() < 0.5:
x = flip_axis(x, img_row_axis)
return x
|
MIT License
|
ros-industrial/robodk_postprocessors
|
ABB_RAPID_S4C.py
|
RobotPost.setTool
|
python
|
def setTool(self, pose, tool_id=None, tool_name=None):
if self.TOOL_REF_FIRST is None:
self.TOOL_REF_FIRST = pose
else:
self.addline('%s := [TRUE,[%s],[2,[0,0,50],[1,0,0,0],0,0,0.005]];' % (self.TOOL_NAME, pose_2_str(pose)))
|
Change the robot TCP
|
https://github.com/ros-industrial/robodk_postprocessors/blob/d7e6c1c07758d67d2906cfd638049bdff88cca72/ABB_RAPID_S4C.py#L256-L265
|
from robodk import *
ONETAB = ' '
CUSTOM_HEADER = '''
! -------------------------------
! Define your variables here
! ...
'''
CUSTOM_FUNCTIONS = '''
! -------------------------------
! Define your functions here
! ...
'''
def pose_2_str(pose):
[x,y,z,q1,q2,q3,q4] = Pose_2_ABB(pose)
return ('[%.3f,%.3f,%.3f],[%.6f,%.6f,%.6f,%.6f]' % (x,y,z,q1,q2,q3,q4))
def angles_2_str(angles):
njoints = len(angles)
if njoints < 6:
angles.extend([0]*(6-njoints))
return '[%s]' % (','.join(format(ji, ".6f") for ji in angles[0:6]))
def extaxes_2_str(angles):
njoints = len(angles)
if njoints <= 6:
return '[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]'
extaxes_str = (','.join(format(ji, ".6f") for ji in angles[6:njoints]))
if njoints < 12:
extaxes_str = extaxes_str + ',' + ','.join(['9E9']*(12-njoints))
return '[%s]' % extaxes_str
class RobotPost(object):
PROG_EXT = 'prg'
ROBOT_POST = 'unset'
ROBOT_NAME = 'generic'
PROG_FILES = []
nPROGS = 0
PROG = ''
TAB = ''
LOG = ''
FRAME_REF = eye(4)
TOOL_REF_FIRST = None
MOD_NAME = 'module'
ZONEDATA = 'fine'
SPEEDDATA = '[500,500,5000,1000]'
FRAME_NAME = 'rdkWObj'
TOOL_NAME = 'rdkTool'
def __init__(self, robotpost=None, robotname=None, robot_axes = 6, **kwargs):
self.ROBOT_POST = robotpost
self.ROBOT_NAME = robotname
self.PROG = ''
self.LOG = ''
def ProgStart(self, progname):
self.nPROGS = self.nPROGS + 1
if self.nPROGS == 1:
self.MOD_NAME = progname
self.TAB = ONETAB
self.addline('PROC %s()' % progname)
else:
self.TAB = ONETAB
self.addline('PROC %s()' % progname)
self.TAB = ONETAB + ONETAB
def ProgFinish(self, progname):
self.TAB = ONETAB
self.addline('ENDPROC')
def ProgSave(self, folder, progname, ask_user = False, show_result = False):
self.addline('')
self.TAB = ''
self.addline('ENDMODULE')
progname = progname + '.' + self.PROG_EXT
if ask_user or not DirExists(folder):
filesave = getSaveFile(folder, progname, 'Save program as...')
if filesave is not None:
filesave = filesave.name
else:
return
else:
filesave = folder + '/' + progname
fid = open(filesave, "w")
fid.write('%%%\n')
fid.write(' VERSION:1\n')
fid.write(' LANGUAGE:ENGLISH\n')
fid.write('%%%\n')
fid.write('\n')
fid.write('MODULE MOD_%s\n' % self.MOD_NAME)
fid.write(' \n')
if self.TOOL_REF_FIRST is None:
self.TOOL_REF_FIRST = eye(4)
fid.write(' PERS tooldata rdkTool := [TRUE,[%s],[2,[0,0,15],[1,0,0,0],0,0,0.005]];\n' % pose_2_str(self.TOOL_REF_FIRST))
fid.write(' PERS wobjdata rdkWObj := [FALSE, TRUE, "", [[0,0,0],[1,0,0,0]],[[0,0,0],[1,0,0,0]]];\n')
fid.write(' \n')
fid.write(self.PROG)
fid.close()
print('SAVED: %s\n' % filesave)
self.PROG_FILES = filesave
if show_result:
if type(show_result) is str:
import subprocess
p = subprocess.Popen([show_result, filesave])
elif type(show_result) is list:
import subprocess
p = subprocess.Popen(show_result + [filesave])
else:
import os
os.startfile(filesave)
if len(self.LOG) > 0:
mbox('Program generation LOG:\n\n' + self.LOG)
def ProgSendRobot(self, robot_ip, remote_path, ftp_user, ftp_pass):
UploadFTP(self.PROG_FILES, robot_ip, remote_path, ftp_user, ftp_pass)
def MoveJ(self, pose, joints, conf_RLF=None):
self.addline('MoveAbsJ [%s,%s],%s,%s,%s,\WObj:=rdkWObj;' % (angles_2_str(joints), extaxes_2_str(joints), self.SPEEDDATA, self.ZONEDATA, self.TOOL_NAME))
def MoveL(self, pose, joints, conf_RLF=None):
if conf_RLF is None:
conf_RLF = [0,0,0]
[REAR, LOWERARM, FLIP] = conf_RLF
cf1 = math.floor(joints[0]/90.0)
cf4 = math.floor(joints[3]/90.0)
cf6 = math.floor(joints[5]/90.0)
cfx = 4*REAR + 2*LOWERARM + FLIP
self.addline('MoveL [%s,[%i,%i,%i,%i],%s],%s,%s,%s,\WObj:=rdkWObj;' % (pose_2_str(self.FRAME_REF*pose), cf1, cf4, cf6,cfx, extaxes_2_str(joints), self.SPEEDDATA, self.ZONEDATA, self.TOOL_NAME))
def MoveC(self, pose1, joints1, pose2, joints2, conf_RLF_1=None, conf_RLF_2=None):
if conf_RLF_1 is None:
conf_RLF_1 = [0,0,0]
if conf_RLF_2 is None:
conf_RLF_2 = [0,0,0]
cf1_1 = 0
cf4_1 = 0
cf6_1 = 0
if joints1 is not None:
cf1_1 = math.floor(joints1[0]/90.0)
cf4_1 = math.floor(joints1[3]/90.0)
cf6_1 = math.floor(joints1[5]/90.0)
[REAR, LOWERARM, FLIP] = conf_RLF_1
cfx_1 = 4*REAR + 2*LOWERARM + FLIP
cf1_2 = 0
cf4_2 = 0
cf6_2 = 0
if joints2 is not None:
cf1_2 = math.floor(joints2[0]/90.0)
cf4_2 = math.floor(joints2[3]/90.0)
cf6_2 = math.floor(joints2[5]/90.0)
[REAR, LOWERARM, FLIP] = conf_RLF_2
cfx_2 = 4*REAR + 2*LOWERARM + FLIP
self.addline('MoveC [%s,[%i,%i,%i,%i],%s],[%s,[%i,%i,%i,%i],%s],%s,%s,rdkTool,\WObj:=rdkWObj;' % (pose_2_str(pose1), cf1_1, cf4_1, cf6_1,cfx_1, extaxes_2_str(joints1), pose_2_str(pose2), cf1_2, cf4_2, cf6_2,cfx_2, extaxes_2_str(joints2), self.SPEEDDATA, self.ZONEDATA))
def setFrame(self, pose, frame_id=None, frame_name=None):
self.FRAME_REF = pose
|
Apache License 2.0
|
atmtools/typhon
|
typhon/retrieval/qrnn/models/keras.py
|
quantile_loss
|
python
|
def quantile_loss(y_true, y_pred, taus):
e = skewed_absolute_error(K.flatten(y_true), K.flatten(y_pred[:, 0]), taus[0])
for i, tau in enumerate(taus[1:]):
e += skewed_absolute_error(K.flatten(y_true), K.flatten(y_pred[:, i + 1]), tau)
return e
|
The quantiles loss for a list of quantiles. Sums up the error contribution
from the each of the quantile loss functions.
|
https://github.com/atmtools/typhon/blob/815dcb1d7cb2718ffe81cd08386739438e7782cc/typhon/retrieval/qrnn/models/keras.py#L78-L86
|
import logging
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, deserialize
from keras.optimizers import SGD
import keras.backend as K
def save_model(f, model):
keras.models.save_model(model, f)
def load_model(f, quantiles):
def make_fully_connected(layers=None, **kwargs):
layers = list(map(deserialize, layers))
input_dimensions = layers[0].batch_input_shape[1]
return FullyConnected(input_dimensions, quantiles, (), layers)
custom_objects = {
"FullyConnected": make_fully_connected,
"QuantileLoss": QuantileLoss,
}
model = keras.models.load_model(f, custom_objects=custom_objects)
return model
LOGGER = logging.getLogger(__name__)
def skewed_absolute_error(y_true, y_pred, tau):
dy = y_pred - y_true
return K.mean((1.0 - tau) * K.relu(dy) + tau * K.relu(-dy), axis=-1)
|
MIT License
|
mindspore-ai/mindarmour
|
examples/model_security/model_attacks/cv/yolov3_darknet53/src/transforms.py
|
_choose_candidate_by_constraints
|
python
|
def _choose_candidate_by_constraints(max_trial, input_w, input_h, image_w, image_h, jitter, box, use_constraints):
if use_constraints:
constraints = (
(0.1, None),
(0.3, None),
(0.5, None),
(0.7, None),
(0.9, None),
(None, 1),
)
else:
constraints = (
(None, None),
)
candidates = [(0, 0, input_w, input_h)]
for constraint in constraints:
min_iou, max_iou = constraint
min_iou = -np.inf if min_iou is None else min_iou
max_iou = np.inf if max_iou is None else max_iou
for _ in range(max_trial):
new_ar = float(input_w) / float(input_h) * _rand(1 - jitter, 1 + jitter) / _rand(1 - jitter, 1 + jitter)
scale = _rand(0.25, 2)
if new_ar < 1:
nh = int(scale * input_h)
nw = int(nh * new_ar)
else:
nw = int(scale * input_w)
nh = int(nw / new_ar)
dx = int(_rand(0, input_w - nw))
dy = int(_rand(0, input_h - nh))
if box.size > 0:
t_box = copy.deepcopy(box)
t_box[:, [0, 2]] = t_box[:, [0, 2]] * float(nw) / float(image_w) + dx
t_box[:, [1, 3]] = t_box[:, [1, 3]] * float(nh) / float(image_h) + dy
crop_box = np.array((0, 0, input_w, input_h))
if not _is_iou_satisfied_constraint(min_iou, max_iou, t_box, crop_box[np.newaxis]):
continue
else:
candidates.append((dx, dy, nw, nh))
else:
raise Exception("!!! annotation box is less than 1")
return candidates
|
Choose candidate by constraints.
|
https://github.com/mindspore-ai/mindarmour/blob/df44e3de733cdfc568d856d120bd8a53e6f25cc1/examples/model_security/model_attacks/cv/yolov3_darknet53/src/transforms.py#L280-L329
|
import random
import threading
import copy
import numpy as np
from PIL import Image
import cv2
def _rand(a=0., b=1.):
return np.random.rand() * (b - a) + a
def bbox_iou(bbox_a, bbox_b, offset=0):
if bbox_a.shape[1] < 4 or bbox_b.shape[1] < 4:
raise IndexError("Bounding boxes axis 1 must have at least length 4")
tl = np.maximum(bbox_a[:, None, :2], bbox_b[:, :2])
br = np.minimum(bbox_a[:, None, 2:4], bbox_b[:, 2:4])
area_i = np.prod(br - tl + offset, axis=2) * (tl < br).all(axis=2)
area_a = np.prod(bbox_a[:, 2:4] - bbox_a[:, :2] + offset, axis=1)
area_b = np.prod(bbox_b[:, 2:4] - bbox_b[:, :2] + offset, axis=1)
return area_i / (area_a[:, None] + area_b - area_i)
def statistic_normalize_img(img, statistic_norm):
if isinstance(img, Image.Image):
img = np.array(img)
img = img/255.
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
if statistic_norm:
img = (img - mean) / std
return img
def get_interp_method(interp, sizes=()):
if interp == 9:
if sizes:
assert len(sizes) == 4
oh, ow, nh, nw = sizes
if nh > oh and nw > ow:
return 2
if nh < oh and nw < ow:
return 0
return 1
return 2
if interp == 10:
return random.randint(0, 4)
if interp not in (0, 1, 2, 3, 4):
raise ValueError('Unknown interp method %d' % interp)
return interp
def pil_image_reshape(interp):
reshape_type = {
0: Image.NEAREST,
1: Image.BILINEAR,
2: Image.BICUBIC,
3: Image.NEAREST,
4: Image.LANCZOS,
}
return reshape_type[interp]
def _preprocess_true_boxes(true_boxes, anchors, in_shape, num_classes,
max_boxes, label_smooth, label_smooth_factor=0.1):
anchors = np.array(anchors)
num_layers = anchors.shape[0] // 3
anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
true_boxes = np.array(true_boxes, dtype='float32')
input_shape = np.array(in_shape, dtype='int32')
boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2.
boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2]
true_boxes[..., 0:2] = boxes_xy / input_shape[::-1]
true_boxes[..., 2:4] = boxes_wh / input_shape[::-1]
grid_shapes = [input_shape // 32, input_shape // 16, input_shape // 8]
y_true = [np.zeros((grid_shapes[l][0], grid_shapes[l][1], len(anchor_mask[l]),
5 + num_classes), dtype='float32') for l in range(num_layers)]
anchors = np.expand_dims(anchors, 0)
anchors_max = anchors / 2.
anchors_min = -anchors_max
valid_mask = boxes_wh[..., 0] > 0
wh = boxes_wh[valid_mask]
if wh.size > 0:
wh = np.expand_dims(wh, -2)
boxes_max = wh / 2.
boxes_min = -boxes_max
intersect_min = np.maximum(boxes_min, anchors_min)
intersect_max = np.minimum(boxes_max, anchors_max)
intersect_wh = np.maximum(intersect_max - intersect_min, 0.)
intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]
box_area = wh[..., 0] * wh[..., 1]
anchor_area = anchors[..., 0] * anchors[..., 1]
iou = intersect_area / (box_area + anchor_area - intersect_area)
best_anchor = np.argmax(iou, axis=-1)
for t, n in enumerate(best_anchor):
for l in range(num_layers):
if n in anchor_mask[l]:
i = np.floor(true_boxes[t, 0] * grid_shapes[l][1]).astype('int32')
j = np.floor(true_boxes[t, 1] * grid_shapes[l][0]).astype('int32')
k = anchor_mask[l].index(n)
c = true_boxes[t, 4].astype('int32')
y_true[l][j, i, k, 0:4] = true_boxes[t, 0:4]
y_true[l][j, i, k, 4] = 1.
if label_smooth:
sigma = label_smooth_factor/(num_classes-1)
y_true[l][j, i, k, 5:] = sigma
y_true[l][j, i, k, 5+c] = 1-label_smooth_factor
else:
y_true[l][j, i, k, 5 + c] = 1.
pad_gt_box0 = np.zeros(shape=[max_boxes, 4], dtype=np.float32)
pad_gt_box1 = np.zeros(shape=[max_boxes, 4], dtype=np.float32)
pad_gt_box2 = np.zeros(shape=[max_boxes, 4], dtype=np.float32)
mask0 = np.reshape(y_true[0][..., 4:5], [-1])
gt_box0 = np.reshape(y_true[0][..., 0:4], [-1, 4])
gt_box0 = gt_box0[mask0 == 1]
pad_gt_box0[:gt_box0.shape[0]] = gt_box0
mask1 = np.reshape(y_true[1][..., 4:5], [-1])
gt_box1 = np.reshape(y_true[1][..., 0:4], [-1, 4])
gt_box1 = gt_box1[mask1 == 1]
pad_gt_box1[:gt_box1.shape[0]] = gt_box1
mask2 = np.reshape(y_true[2][..., 4:5], [-1])
gt_box2 = np.reshape(y_true[2][..., 0:4], [-1, 4])
gt_box2 = gt_box2[mask2 == 1]
pad_gt_box2[:gt_box2.shape[0]] = gt_box2
return y_true[0], y_true[1], y_true[2], pad_gt_box0, pad_gt_box1, pad_gt_box2
def _reshape_data(image, image_size):
if not isinstance(image, Image.Image):
image = Image.fromarray(image)
ori_w, ori_h = image.size
ori_image_shape = np.array([ori_w, ori_h], np.int32)
h, w = image_size
interp = get_interp_method(interp=9, sizes=(ori_h, ori_w, h, w))
image = image.resize((w, h), pil_image_reshape(interp))
image_data = statistic_normalize_img(image, statistic_norm=True)
if len(image_data.shape) == 2:
image_data = np.expand_dims(image_data, axis=-1)
image_data = np.concatenate([image_data, image_data, image_data], axis=-1)
image_data = image_data.astype(np.float32)
return image_data, ori_image_shape
def color_distortion(img, hue, sat, val, device_num):
hue = _rand(-hue, hue)
sat = _rand(1, sat) if _rand() < .5 else 1 / _rand(1, sat)
val = _rand(1, val) if _rand() < .5 else 1 / _rand(1, val)
if device_num != 1:
cv2.setNumThreads(1)
x = cv2.cvtColor(img, cv2.COLOR_RGB2HSV_FULL)
x = x / 255.
x[..., 0] += hue
x[..., 0][x[..., 0] > 1] -= 1
x[..., 0][x[..., 0] < 0] += 1
x[..., 1] *= sat
x[..., 2] *= val
x[x > 1] = 1
x[x < 0] = 0
x = x * 255.
x = x.astype(np.uint8)
image_data = cv2.cvtColor(x, cv2.COLOR_HSV2RGB_FULL)
return image_data
def filp_pil_image(img):
return img.transpose(Image.FLIP_LEFT_RIGHT)
def convert_gray_to_color(img):
if len(img.shape) == 2:
img = np.expand_dims(img, axis=-1)
img = np.concatenate([img, img, img], axis=-1)
return img
def _is_iou_satisfied_constraint(min_iou, max_iou, box, crop_box):
iou = bbox_iou(box, crop_box)
return min_iou <= iou.min() and max_iou >= iou.max()
|
Apache License 2.0
|
hosford42/xcs
|
xcs/algorithms/xcs.py
|
XCSAlgorithm.action_selection_strategy
|
python
|
def action_selection_strategy(self):
return (
self.exploration_strategy or
EpsilonGreedySelectionStrategy(self.exploration_probability)
)
|
The action selection strategy used to govern the trade-off
between exploration (acquiring new experience) and exploitation
(utilizing existing experience to maximize reward).
|
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/algorithms/xcs.py#L374-L381
|
import random
from .. import bitstrings
from ..framework import ClassifierRule, LCSAlgorithm, EpsilonGreedySelectionStrategy, MatchSet, ClassifierSet
class XCSClassifierRule(ClassifierRule):
def __init__(self, condition, action, algorithm, time_stamp):
assert isinstance(algorithm, XCSAlgorithm)
assert isinstance(time_stamp, int)
self._algorithm = algorithm
self._condition = condition
self._action = action
self.time_stamp = time_stamp
self.average_reward = algorithm.initial_prediction
self.error = algorithm.initial_error
self.fitness = algorithm.initial_fitness
self.experience = 0
self.action_set_size = 1
self.numerosity = 1
def __str__(self):
return (
str(self.condition) + ' => ' + str(self.action) + '\n ' +
'\n '.join(
key.replace('_', ' ').title() + ': ' +
str(getattr(self, key))
for key in (
'time_stamp',
'average_reward',
'error',
'fitness',
'experience',
'action_set_size',
'numerosity'
)
)
)
def __lt__(self, other):
if not isinstance(other, XCSClassifierRule):
return NotImplemented
attribute_order = (
'numerosity',
'fitness',
'experience',
'error',
'average_reward',
'action_set_size',
'time_stamp'
)
for attribute in attribute_order:
my_key = getattr(self, attribute)
other_key = getattr(other, attribute)
if my_key < other_key:
return attribute not in ('error', 'action_set_size')
if my_key > other_key:
return attribute in ('error', 'action_set_size')
return False
@property
def algorithm(self):
return self._algorithm
@property
def condition(self):
return self._condition
@property
def action(self):
return self._action
@property
def prediction(self):
return self.average_reward
@property
def prediction_weight(self):
return self.fitness
class XCSAlgorithm(LCSAlgorithm):
max_population_size = 200
learning_rate = .15
accuracy_coefficient = .1
error_threshold = .01
accuracy_power = 5
discount_factor = .71
ga_threshold = 35
crossover_probability = .75
mutation_probability = .03
deletion_threshold = 20
fitness_threshold = .1
subsumption_threshold = 20
wildcard_probability = .33
initial_prediction = .00001
initial_error = .00001
initial_fitness = .00001
exploration_probability = .5
minimum_actions = None
do_ga_subsumption = False
do_action_set_subsumption = False
exploration_strategy = None
idealization_factor = 0
@property
|
BSD 3-Clause New or Revised License
|
opensourceeconomics/respy
|
respy/state_space.py
|
create_is_inadmissible
|
python
|
def create_is_inadmissible(df, optim_paras, options):
df = df.copy()
for choice in optim_paras["choices"]:
df[f"_{choice}"] = False
for formula in options["negative_choice_set"][choice]:
try:
df[f"_{choice}"] |= df.eval(formula)
except pd.core.computation.ops.UndefinedVariableError:
pass
return df
|
Compute is_inadmissible for passed states.
|
https://github.com/opensourceeconomics/respy/blob/19b9602c6f34f39034b00a88f36219ed3c4cfe5a/respy/state_space.py#L699-L711
|
import itertools
import numba as nb
import numpy as np
import pandas as pd
from numba.typed import Dict
from respy._numba import sum_over_numba_boolean_unituple
from respy.exogenous_processes import create_transit_choice_set
from respy.exogenous_processes import create_transition_objects
from respy.exogenous_processes import weight_continuation_values
from respy.parallelization import parallelize_across_dense_dimensions
from respy.shared import apply_law_of_motion_for_core
from respy.shared import compute_covariates
from respy.shared import convert_dictionary_keys_to_dense_indices
from respy.shared import create_base_draws
from respy.shared import create_core_state_space_columns
from respy.shared import create_dense_state_space_columns
from respy.shared import downcast_to_smallest_dtype
from respy.shared import dump_objects
from respy.shared import load_objects
from respy.shared import map_states_to_core_key_and_core_index
from respy.shared import prepare_cache_directory
from respy.shared import return_core_dense_key
def create_state_space_class(optim_paras, options):
prepare_cache_directory(options)
core = _create_core_state_space(optim_paras, options)
dense_grid = _create_dense_state_space_grid(optim_paras)
core = compute_covariates(core, options["covariates_core"])
core = core.apply(downcast_to_smallest_dtype)
dense = _create_dense_state_space_covariates(dense_grid, optim_paras, options)
core_period_choice = _create_core_period_choice(core, optim_paras, options)
core_key_to_complex = dict(enumerate(core_period_choice))
core_key_to_core_indices = {
i: core_period_choice[complex_] for i, complex_ in core_key_to_complex.items()
}
indexer = _create_indexer(core, core_key_to_core_indices, optim_paras)
dense_period_choice = _create_dense_period_choice(
core, dense, core_key_to_core_indices, core_key_to_complex, optim_paras, options
)
state_space = StateSpace(
core,
indexer,
dense,
dense_period_choice,
core_key_to_complex,
core_key_to_core_indices,
optim_paras,
options,
)
return state_space
class StateSpace:
def __init__(
self,
core,
indexer,
dense,
dense_period_cores,
core_key_to_complex,
core_key_to_core_indices,
optim_paras,
options,
):
self.core = core
self.indexer = indexer
self.dense_period_cores = dense_period_cores
self.dense = dense
self.core_key_to_complex = core_key_to_complex
self.core_key_to_core_indices = core_key_to_core_indices
self.optim_paras = optim_paras
self.options = options
self.n_periods = options["n_periods"]
self._create_conversion_dictionaries()
self.base_draws_sol = self.create_draws(options)
self.create_arrays_for_expected_value_functions()
if len(self.optim_paras["exogenous_processes"]) > 0:
self.create_objects_for_exogenous_processes()
self.child_indices = self.collect_child_indices()
def _create_conversion_dictionaries(self):
self.dense_key_to_complex = {
i: k for i, k in enumerate(self.dense_period_cores)
}
self.dense_key_to_core_key = {
i: self.dense_period_cores[self.dense_key_to_complex[i]]
for i in self.dense_key_to_complex
}
self.dense_key_to_choice_set = {
i: self.dense_key_to_complex[i][1] for i in self.dense_key_to_complex
}
self.dense_key_to_core_indices = {
i: np.array(self.core_key_to_core_indices[self.dense_key_to_core_key[i]])
for i in self.dense_key_to_complex
}
self.core_key_and_dense_index_to_dense_key = Dict.empty(
key_type=nb.types.UniTuple(nb.types.int64, 2),
value_type=nb.types.int64,
)
for i in self.dense_key_to_complex:
self.core_key_and_dense_index_to_dense_key[
return_core_dense_key(
self.dense_key_to_core_key[i],
*self.dense_key_to_complex[i][2:],
)
] = i
if self.dense is False:
self.dense_covariates_to_dense_index = {}
self.dense_key_to_dense_covariates = {
i: {} for i in self.dense_key_to_complex
}
else:
n_dense = len(create_dense_state_space_columns(self.optim_paras))
self.dense_covariates_to_dense_index = Dict.empty(
key_type=nb.types.UniTuple(nb.types.int64, n_dense),
value_type=nb.types.int64,
)
for i, k in enumerate(self.dense):
self.dense_covariates_to_dense_index[k] = i
self.dense_key_to_dense_covariates = {
i: list(self.dense.keys())[self.dense_key_to_complex[i][2]]
for i in self.dense_key_to_complex
}
def create_arrays_for_expected_value_functions(self):
self.expected_value_functions = Dict.empty(
key_type=nb.types.int64, value_type=nb.types.float64[:]
)
for index, indices in self.dense_key_to_core_indices.items():
self.expected_value_functions[index] = np.zeros(len(indices))
def create_objects_for_exogenous_processes(self):
exogenous_processes = self.optim_paras["exogenous_processes"]
n_exog = len(exogenous_processes)
levels_of_processes = [range(len(i)) for i in exogenous_processes.values()]
self.exogenous_grid = list(itertools.product(*levels_of_processes))
self.dense_key_to_transit_keys = create_transition_objects(
self.dense_key_to_dense_covariates,
self.dense_key_to_core_key,
self.exogenous_grid,
n_exog,
bypass={
"dense_covariates_to_dense_index": self.dense_covariates_to_dense_index,
"core_key_and_dense_index_to_dense_key": self.core_key_and_dense_index_to_dense_key,
},
)
self.transit_key_to_choice_set = create_transit_choice_set(
self.dense_key_to_transit_keys, self.dense_key_to_choice_set
)
def get_continuation_values(self, period):
if period == self.n_periods - 1:
shapes = self.get_attribute_from_period("base_draws_sol", period)
states = self.get_attribute_from_period("dense_key_to_core_indices", period)
continuation_values = {
key: np.zeros((states[key].shape[0], shapes[key].shape[1]))
for key in shapes
}
else:
child_indices = self.get_attribute_from_period("child_indices", period)
expected_value_functions = self.get_attribute_from_period(
"expected_value_functions", period + 1
)
subset_expected_value_functions = Dict.empty(
key_type=nb.types.int64, value_type=nb.types.float64[:]
)
for key, value in expected_value_functions.items():
subset_expected_value_functions[key] = value
transit_choice_sets = (
"transit_key_to_choice_set"
if hasattr(self, "transit_key_to_choice_set")
else "dense_key_to_choice_set"
)
continuation_values = _get_continuation_values(
self.get_attribute_from_period("dense_key_to_complex", period),
self.get_attribute_from_period(transit_choice_sets, period),
self.get_attribute_from_period("dense_key_to_core_indices", period),
child_indices,
self.core_key_and_dense_index_to_dense_key,
bypass={"expected_value_functions": subset_expected_value_functions},
)
if len(self.optim_paras["exogenous_processes"]) > 0:
continuation_values = weight_continuation_values(
self.get_attribute_from_period("dense_key_to_complex", period),
self.options,
bypass={
"continuation_values": continuation_values,
"transit_key_to_choice_set": self.get_attribute_from_period(
transit_choice_sets, period
),
},
)
return continuation_values
def collect_child_indices(self):
if self.n_periods == 1:
child_indices = None
else:
dense_key_to_complex_except_last_period = {
k: v
for k, v in self.dense_key_to_complex.items()
if v[0] < self.n_periods - 1
}
transit_choice_sets = (
"transit_key_to_choice_set"
if hasattr(self, "transit_key_to_choice_set")
else "dense_key_to_choice_set"
)
dense_key_to_choice_set_except_last_period = {
k: getattr(self, transit_choice_sets)[k]
for k in dense_key_to_complex_except_last_period
}
child_indices = _collect_child_indices(
dense_key_to_complex_except_last_period,
dense_key_to_choice_set_except_last_period,
self.indexer,
self.optim_paras,
self.options,
)
return child_indices
def create_draws(self, options):
n_choices_in_sets = list(set(map(sum, self.dense_key_to_choice_set.values())))
shocks_sets = []
for n_choices in n_choices_in_sets:
draws = create_base_draws(
(options["n_periods"], options["solution_draws"], n_choices),
next(options["solution_seed_startup"]),
options["monte_carlo_sequence"],
)
shocks_sets.append(draws)
draws = {}
for dense_idx, complex_ix in self.dense_key_to_complex.items():
period = complex_ix[0]
n_choices = sum(complex_ix[1])
idx = n_choices_in_sets.index(n_choices)
draws[dense_idx] = shocks_sets[idx][period]
return draws
def get_dense_keys_from_period(self, period):
return [
dense_index
for dense_index, complex_ in self.dense_key_to_complex.items()
if complex_[0] == period
]
def get_attribute_from_period(self, attribute, period):
dense_indices_in_period = self.get_dense_keys_from_period(period)
return {
dense_index: attr
for dense_index, attr in getattr(self, attribute).items()
if dense_index in dense_indices_in_period
}
def set_attribute_from_keys(self, attribute, value):
for key in value:
getattr(self, attribute)[key][:] = value[key]
def _create_core_state_space(optim_paras, options):
core = _create_core_from_choice_experiences(optim_paras)
core = _add_lagged_choice_to_core_state_space(core, optim_paras)
core = _filter_core_state_space(core, options)
core = _add_initial_experiences_to_core_state_space(core, optim_paras)
core = core.sort_values("period").reset_index(drop=True)
return core
def _create_core_from_choice_experiences(optim_paras):
choices_w_exp = list(optim_paras["choices_w_exp"])
minimal_initial_experience = np.array(
[min(optim_paras["choices"][choice]["start"]) for choice in choices_w_exp],
dtype=np.uint8,
)
maximum_exp = np.array(
[optim_paras["choices"][choice]["max"] for choice in choices_w_exp],
dtype=np.uint8,
)
additional_exp = maximum_exp - minimal_initial_experience
exp_cols = [f"exp_{choice}" for choice in choices_w_exp]
container = []
for period in np.arange(optim_paras["n_periods"], dtype=np.uint8):
data = _create_core_state_space_per_period(
period,
additional_exp,
optim_paras,
np.zeros(len(choices_w_exp), dtype=np.uint8),
)
df_ = pd.DataFrame.from_records(data, columns=exp_cols)
df_.insert(0, "period", period)
container.append(df_)
df = pd.concat(container, axis="rows", sort=False)
return df
def _create_core_state_space_per_period(
period, additional_exp, optim_paras, experiences, pos=0
):
yield experiences
if pos < experiences.shape[0]:
remaining_time = period - experiences.sum()
max_experience = additional_exp[pos]
for i in np.arange(min(remaining_time, max_experience) + 1, dtype=np.uint8):
updated_experiences = experiences.copy()
updated_experiences[pos] += i
yield from _create_core_state_space_per_period(
period, additional_exp, optim_paras, updated_experiences, pos + 1
)
def _add_lagged_choice_to_core_state_space(df, optim_paras):
container = []
for lag in range(1, optim_paras["n_lagged_choices"] + 1):
for choice_code in range(len(optim_paras["choices"])):
df_ = df.copy()
df_[f"lagged_choice_{lag}"] = choice_code
container.append(df_)
df = pd.concat(container, axis="rows", sort=False) if container else df
return df
def _filter_core_state_space(df, options):
for definition in options["core_state_space_filters"]:
df = df.loc[~df.eval(definition)]
return df
def _add_initial_experiences_to_core_state_space(df, optim_paras):
choices = optim_paras["choices"]
initial_experiences_combinations = itertools.product(
*(choices[choice]["start"] for choice in optim_paras["choices_w_exp"])
)
maximum_exp = np.array(
[choices[choice]["max"] for choice in optim_paras["choices_w_exp"]]
)
exp_cols = df.filter(like="exp_").columns.tolist()
container = []
for initial_exp in initial_experiences_combinations:
df_ = df.copy()
df_[exp_cols] += initial_exp
df_ = df_.loc[df_[exp_cols].le(maximum_exp).all(axis="columns")].copy()
container.append(df_)
df = pd.concat(container, axis="rows", sort=False).drop_duplicates()
return df
def _create_dense_state_space_grid(optim_paras):
levels_of_observables = [range(len(i)) for i in optim_paras["observables"].values()]
types = [range(optim_paras["n_types"])] if optim_paras["n_types"] >= 2 else []
dense_state_space_grid = list(itertools.product(*levels_of_observables, *types))
if dense_state_space_grid == [()]:
dense_state_space_grid = False
return dense_state_space_grid
def _create_dense_state_space_covariates(dense_grid, optim_paras, options):
if dense_grid:
columns = create_dense_state_space_columns(optim_paras)
df = pd.DataFrame(data=dense_grid, columns=columns).set_index(
columns, drop=False
)
covariates = compute_covariates(df, options["covariates_dense"])
covariates = covariates.apply(downcast_to_smallest_dtype)
covariates = covariates.to_dict(orient="index")
covariates = convert_dictionary_keys_to_dense_indices(covariates)
else:
covariates = False
return covariates
|
MIT License
|
docusign/docusign-python-client
|
docusign_esign/models/brand_resource_urls.py
|
BrandResourceUrls.sending
|
python
|
def sending(self):
return self._sending
|
Gets the sending of this BrandResourceUrls. # noqa: E501
# noqa: E501
:return: The sending of this BrandResourceUrls. # noqa: E501
:rtype: str
|
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/brand_resource_urls.py#L90-L98
|
import pprint
import re
import six
from docusign_esign.client.configuration import Configuration
class BrandResourceUrls(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'email': 'str',
'sending': 'str',
'signing': 'str',
'signing_captive': 'str'
}
attribute_map = {
'email': 'email',
'sending': 'sending',
'signing': 'signing',
'signing_captive': 'signingCaptive'
}
def __init__(self, _configuration=None, **kwargs):
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._email = None
self._sending = None
self._signing = None
self._signing_captive = None
self.discriminator = None
setattr(self, "_{}".format('email'), kwargs.get('email', None))
setattr(self, "_{}".format('sending'), kwargs.get('sending', None))
setattr(self, "_{}".format('signing'), kwargs.get('signing', None))
setattr(self, "_{}".format('signing_captive'), kwargs.get('signing_captive', None))
@property
def email(self):
return self._email
@email.setter
def email(self, email):
self._email = email
@property
|
MIT License
|
tfukaza/harvest
|
harvest/storage/base_storage.py
|
BaseStorage._append
|
python
|
def _append(
self,
current_data: pd.DataFrame,
new_data: pd.DataFrame,
remove_duplicate: bool = True,
) -> pd.DataFrame:
new_df = current_data.append(new_data)
if remove_duplicate:
new_df = new_df[~new_df.index.duplicated(keep="last")].sort_index()
return new_df
|
Appends the data as best it can with gaps in the data for weekends
and time when no data is collected.
:current_data: the current data that we have on the stock for
the interval
:new_data: data coming from the the broker's API call
|
https://github.com/tfukaza/harvest/blob/cf82bcbb121cb97f4753b66c79eddc0e5f222d5c/harvest/storage/base_storage.py#L213-L230
|
from numpy import ERR_CALL
import pandas as pd
import datetime as dt
from threading import Lock
from typing import Tuple
import re
from harvest.utils import *
class BaseStorage:
def __init__(self, queue_size: int = 200, limit_size: bool = True):
self.storage_lock = Lock()
self.storage = {}
self.queue_size = int(queue_size)
self.limit_size = limit_size
def store(
self, symbol: str, interval: Interval, data: pd.DataFrame, remove_duplicate=True
) -> None:
if data.empty:
return None
self.storage_lock.acquire()
if symbol in self.storage:
intervals = self.storage[symbol]
if interval in intervals:
try:
intervals[interval] = self._append(
intervals[interval], data, remove_duplicate=remove_duplicate
)
if self.limit_size:
intervals[interval] = intervals[interval][-self.queue_size :]
except:
raise Exception("Append Failure, case not found!")
else:
intervals[interval] = data
else:
if self.limit_size:
data = data[-self.queue_size :]
if len(data) < self.queue_size:
debugger.warning(
f"Symbol {symbol}, interval {interval} initialized with only {len(data)} data points"
)
self.storage[symbol] = {interval: data}
cur_len = len(self.storage[symbol][interval])
if self.limit_size and cur_len > self.queue_size:
self.storage[symbol][interval] = self.storage[symbol][interval].iloc[
-self.queue_size :
]
self.storage_lock.release()
def aggregate(
self,
symbol: str,
base: Interval,
target: Interval,
remove_duplicate: bool = True,
):
self.storage_lock.acquire()
data = self.storage[symbol][base]
self.storage[symbol][target] = self._append(
self.storage[symbol][target], aggregate_df(data, target), remove_duplicate
)
cur_len = len(self.storage[symbol][target])
if self.limit_size and cur_len > self.queue_size:
self.storage[symbol][target] = self.storage[symbol][target].iloc[
-self.queue_size :
]
self.storage_lock.release()
def reset(self, symbol: str, interval: Interval):
self.storage_lock.acquire()
self.storage[symbol][interval] = pd.DataFrame()
self.storage_lock.release()
def load(
self,
symbol: str,
interval: Interval = None,
start: dt.datetime = None,
end: dt.datetime = None,
no_slice=False,
) -> pd.DataFrame:
self.storage_lock.acquire()
if symbol not in self.storage:
self.storage_lock.release()
return None
self.storage_lock.release()
if interval is None:
intervals = [
(interval, interval_to_timedelta(interval))
for interval in self.storage[symbol]
]
intervals.sort(key=lambda interval_timedelta: interval_timedelta[1])
for interval_timedelta in intervals:
data = self.load(symbol, interval_timedelta[0], start, end)
if data is not None:
return data
return None
data = self.storage[symbol][interval]
if no_slice:
return data
if start is None:
start = data.index[0]
if end is None:
end = data.index[-1]
return data.loc[start:end]
def data_range(self, symbol: str, interval: Interval) -> Tuple[dt.datetime]:
data = self.load(symbol, interval)
if data is None:
return None, None
return data.index[0], data.index[-1]
|
MIT License
|
42school/norminette
|
norminette/lexer/lexer.py
|
Lexer.is_string
|
python
|
def is_string(self):
if self.peek_sub_string(2) == 'L"' or self.peek_char() == '"':
return True
else:
return False
|
True if current character could start a string constant
|
https://github.com/42school/norminette/blob/6e77cfd80a76879e4a28c34dad65d749271d1dab/norminette/lexer/lexer.py#L74-L79
|
import string
import pdb
from norminette.lexer.dictionary import brackets
from norminette.lexer.dictionary import keywords
from norminette.lexer.dictionary import operators
from norminette.lexer.dictionary import preproc_keywords
from norminette.lexer.tokens import Token
def read_file(filename):
with open(filename) as f:
return f.read()
class TokenError(Exception):
def __init__(self, pos):
self.msg = f"Error: Unrecognized token line {pos[0]}, col {pos[1]}"
def __repr__(self):
return self.msg
class Lexer:
def __init__(self, source_code, starting_line=1):
self.src = source_code
self.len = len(source_code)
self.__char = self.src[0] if self.src != "" else None
self.__pos = int(0)
self.__line_pos = int(starting_line)
self.__line = int(starting_line)
self.tokens = []
def peek_sub_string(self, size):
return self.src[self.__pos : self.__pos + size]
def peek_char(self):
if self.__pos < self.len:
if self.src[self.__pos] == "\\":
self.__char = self.src[self.__pos : self.__pos + 2]
else:
self.__char = self.src[self.__pos]
else:
self.__char = None
return self.__char
def pop_char(self):
if self.peek_char() == "\t":
self.__line_pos = int((self.__line_pos + 4 - (self.__line_pos - 1) % 4) * 5 / 5)
else:
self.__line_pos += 1
if self.__pos < self.len and self.src[self.__pos] == "\\":
self.__pos += 1
self.__pos += 1
return self.peek_char()
def peek_token(self):
return self.tokens[-1]
def line_pos(self):
return self.__line, self.__line_pos
|
MIT License
|
cyberbotics/urdf2webots
|
tests/test_pep8.py
|
CustomReport.get_file_results
|
python
|
def get_file_results(self):
if self._deferred_print:
self._deferred_print.sort()
for line_number, offset, code, text, _ in self._deferred_print:
self.results.append({
'path': self.filename,
'row': self.line_offset + line_number,
'col': offset + 1,
'code': code,
'text': text,
})
return self.file_errors
|
Overload this function to collect the report.
|
https://github.com/cyberbotics/urdf2webots/blob/1d4ddbe3f0dc9b5a65edeed3249d91d5bf54b052/tests/test_pep8.py#L16-L28
|
import unittest
import glob
import pycodestyle
import os
packageDirectory = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
class CustomReport(pycodestyle.StandardReport):
results = []
|
Apache License 2.0
|
abel-research/ampscan
|
ampscan/core.py
|
AmpObject.calcStruct
|
python
|
def calcStruct(self, norm=True, edges=True,
edgeFaces=True, faceEdges=True, vNorm=False):
if norm is True:
self.calcNorm()
if edges is True:
self.calcEdges()
if edgeFaces is True:
self.calcEdgeFaces()
if faceEdges is True:
self.calcFaceEdges()
if vNorm is True:
self.calcVNorm()
|
r"""
Top level function to calculate the underlying structure of the
AmpObject
Parameters
----------
norm: boolean, default True
If true, the normals of each face in the mesh will be calculated
edges: boolean, default True
If true, the edges of the mesh will be calculated, the refers to
the vertex index that make up any edge
edgeFaces: boolean, default True
If true, the edgeFaces array of the mesh will be calculated, this
refers to the index of the three edges that make up each face
faceEdges: boolean, default True
If true, the faceEdges array will be calculated, this refers to
index of the faces that are coincident to each edge. Normally,
there are two faces per edge, if there is only one, then -99999
will be used to indicate this
vNorm: boolean, default False
If true, the normals of each vertex in the mesh will be calculated
|
https://github.com/abel-research/ampscan/blob/6a010b5be3f9dec1e7165f667ae47320ad758e97/ampscan/core.py#L166-L200
|
import numpy as np
import os
import struct
from ampscan.trim import trimMixin
from ampscan.smooth import smoothMixin
from ampscan.vis import visMixin
filename = os.path.join(os.getcwd(), "tests", "stl_file.stl")
class AmpObject(trimMixin, smoothMixin, visMixin):
def __init__(self, data=None, stype='limb', unify=True, struc=True):
self.stype = stype
self.createCMap()
if isinstance(data, str):
self.read_stl(data, unify, struc)
elif isinstance(data, dict):
for k, v in data.items():
setattr(self, k, v)
self.calcStruct()
elif isinstance(data, bytes):
self.read_bytes(data, unify, struc)
def read_stl(self, filename, unify=True, struc=True):
with open(filename, 'rb') as fh:
HEADER_SIZE = 80
COUNT_SIZE = 4
data_type = np.dtype([('normals', np.float32, (3, )),
('vertices', np.float32, (9, )),
('atttr', '<i2', (1, ))])
head = fh.read(HEADER_SIZE).lower()
NFaces, = struct.unpack('@i', fh.read(COUNT_SIZE))
data = np.fromfile(fh, data_type)
if str(head[:5], 'utf-8') == 'solid':
raise ValueError("ASCII files not supported")
tfcond = NFaces==data['vertices'].shape[0]
if not tfcond:
raise ValueError("File is corrupt")
vert = np.resize(np.array(data['vertices']), (NFaces*3, 3))
norm = np.array(data['normals'])
faces = np.reshape(range(NFaces*3), [NFaces,3])
self.faces = faces
self.vert = vert
self.norm = norm
if unify is True:
self.unifyVert()
if struc is True:
self.calcStruct()
self.values = np.zeros([len(self.vert)])
def read_bytes(self, data, unify=True, struc=True):
HEADER_SIZE = 80
COUNT_SIZE = 4
data_type = np.dtype([('normals', np.float32, (3, )),
('vertices', np.float32, (9, )),
('atttr', '<i2', (1, ))])
head = data[:HEADER_SIZE].lower()
NFaces, = struct.unpack('@i', data[HEADER_SIZE:HEADER_SIZE+COUNT_SIZE])
data = np.frombuffer(data[COUNT_SIZE+HEADER_SIZE:], data_type)
if str(head[:5], 'utf-8') == 'solid':
raise ValueError("ASCII files not supported")
tfcond = NFaces==data['vertices'].shape[0]
if not tfcond:
raise ValueError("File is corrupt")
vert = np.resize(np.array(data['vertices']), (NFaces*3, 3))
norm = np.array(data['normals'])
faces = np.reshape(range(NFaces*3), [NFaces,3])
self.faces = faces
self.vert = vert
self.norm = norm
if unify is True:
self.unifyVert()
if struc is True:
self.calcStruct()
self.values = np.zeros([len(self.vert)])
|
MIT License
|
carreau/papyri
|
papyri/gen.py
|
processed_example_data
|
python
|
def processed_example_data(example_section_data):
new_example_section_data = Section()
for in_out in example_section_data:
type_ = in_out.__class__.__name__
if type_ == "Text":
blocks = P2(in_out.value.split("\n"))
for b in blocks:
new_example_section_data.append(b)
elif type_ == "Code":
in_ = in_out.entries
if len(in_[0]) == 2:
text = "".join([x for x, y in in_])
classes = get_classes(text)
in_out.entries = [ii + (cc,) for ii, cc in zip(in_, classes)]
if type_ != "Text":
new_example_section_data.append(in_out)
return new_example_section_data
|
this should be no-op on already ingested
|
https://github.com/carreau/papyri/blob/cd8fe0a48da5645b78dde7c51b7ae026f642e36a/papyri/gen.py#L381-L401
|
from __future__ import annotations
import inspect
import io
import json
import os
import sys
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from types import FunctionType, ModuleType
from typing import Any, Dict, List, Optional, Tuple
import jedi
import toml
from pygments import lex
from pygments.formatters import HtmlFormatter
from pygments.lexers import PythonLexer
from rich.progress import BarColumn, Progress, ProgressColumn
from rich.progress import Text as RichText
from rich.progress import TextColumn
from there import print
from velin.examples_section_utils import InOut, splitblank, splitcode
from .take2 import (
Code,
Fig,
Lines,
Math,
Node,
Paragraph,
Ref,
Section,
SeeAlsoItem,
Text,
)
from .take2 import parse_rst_to_papyri_tree, Node, make_block_3
from .utils import dedent_but_first, pos_to_nl, progress
from .vref import NumpyDocString
from typing import Optional, Any
try:
from . import ts
except (ImportError, OSError):
print(
"Tree Sitter RST parser not available, you may need to do `papyri build-parser`"
)
ts
def paragraph(lines) -> List[Tuple[str, Any]]:
p = Paragraph.parse_lines(lines)
acc = []
for c in p.children:
if type(c).__name__ == "Directive":
if c.role == "math":
acc.append(Math(c.value))
else:
acc.append(c)
else:
acc.append(c)
p.children = acc
return p
def paragraphs(lines) -> List[Any]:
assert isinstance(lines, list)
for l in lines:
if isinstance(l, str):
assert "\n" not in l
else:
assert "\n" not in l._line
blocks_data = make_block_3(Lines(lines))
acc = []
for pre_blank_lines, blank_lines, post_blank_lines in blocks_data:
if pre_blank_lines:
acc.append(paragraph([x._line for x in pre_blank_lines]))
if post_blank_lines:
acc.append(paragraph([x._line for x in post_blank_lines]))
return acc
def parse_script(script, ns=None, infer=None, prev="", config=None):
jeds = []
import warnings
warnings.simplefilter("ignore", UserWarning)
l_delta = len(prev.split("\n"))
contextscript = prev + "\n" + script
if ns:
jeds.append(jedi.Interpreter(contextscript, namespaces=[ns]))
jeds.append(jedi.Script(prev + "\n" + script))
P = PythonLexer()
for index, type_, text in P.get_tokens_unprocessed(script):
line_n, col_n = pos_to_nl(script, index)
line_n += l_delta
try:
ref = None
for jed in jeds:
failed = ""
try:
if infer and (text not in (" .=()[],")) and text.isidentifier():
inf = jed.infer(line_n + 1, col_n)
if inf:
ref = inf[0].full_name
else:
ref = ""
except (AttributeError, TypeError, Exception) as e:
raise type(e)(
f"{contextscript}, {line_n=}, {col_n=}, {prev=}, {jed=}"
) from e
failed = "(jedi failed inference)"
print("failed inference on ", script, ns, jed, col_n, line_n + 1)
break
except IndexError:
raise
ref = ""
yield text + failed, ref
warnings.simplefilter("default", UserWarning)
class BlockExecutor:
def __init__(self, ns):
import matplotlib
matplotlib.use("agg")
self.ns = ns
pass
def __enter__(self):
assert (len(self.fig_man())) == 0, f"init fail in {len(self.fig_man())}"
def __exit__(self, *args, **kwargs):
import matplotlib.pyplot as plt
plt.close("all")
assert (len(self.fig_man())) == 0, f"init fail in {len(self.fig_man())}"
def fig_man(self):
from matplotlib import _pylab_helpers
return _pylab_helpers.Gcf.get_all_fig_managers()
def get_figs(self):
figs = []
for fig_man in self.fig_man():
buf = io.BytesIO()
fig_man.canvas.figure.savefig(buf, dpi=300)
buf.seek(0)
figs.append(buf.read())
return figs
def exec(self, text):
from matplotlib import _pylab_helpers, cbook
from matplotlib.backend_bases import FigureManagerBase
with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):
res = exec(text, self.ns)
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
return res, fig_managers
def get_example_data(doc, infer=True, obj=None, exec_=True, qa=None, *, config):
assert qa is not None
blocks = list(map(splitcode, splitblank(doc["Examples"])))
example_section_data = Section()
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
acc = ""
import numpy as np
counter = 0
ns = {"np": np, "plt": plt, obj.__name__: obj}
executor = BlockExecutor(ns)
figs = []
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
assert (len(fig_managers)) == 0, f"init fail in {qa} {len(fig_managers)}"
wait_for_show = config.get("wait_for_plt_show", True)
with executor:
for b in blocks:
for item in b:
if isinstance(item, InOut):
script = "\n".join(item.in_)
figname = None
ce_status = "None"
try:
compile(script, "<>", "exec")
ce_status = "compiled"
except SyntaxError:
ce_status = "syntax_error"
pass
raise_in_fig = "?"
did_except = False
if exec_ and ce_status == "compiled":
try:
if not wait_for_show:
assert len(fig_managers) == 0
try:
res, fig_managers = executor.exec(script)
ce_status = "execed"
except Exception:
ce_status = "exception_in_exec"
if config.get("exec_failure", "") != "fallback":
raise
if fig_managers and (
("plt.show" in script) or not wait_for_show
):
raise_in_fig = True
for fig in executor.get_figs():
counter += 1
figname = f"fig-{qa}-{counter}.png"
figs.append((figname, fig))
plt.close("all")
raise_in_fig = False
except Exception:
did_except = True
print(f"exception executing... {qa}")
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
if raise_in_fig:
raise
finally:
if not wait_for_show:
if fig_managers:
plt.close("all")
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
assert len(fig_managers) == 0, fig_managers + [
did_except,
]
infer_exclude = config.get("exclude_jedi", frozenset())
if qa in infer_exclude:
print("Turning off type inference for this function:", qa)
inf = False
else:
inf = infer
entries = list(
parse_script(script, ns=ns, infer=inf, prev=acc, config=config)
)
acc += "\n" + script
example_section_data.append(
Code(entries, "\n".join(item.out), ce_status)
)
if figname:
example_section_data.append(Fig(figname))
else:
assert isinstance(item.out, list)
example_section_data.append(Text("\n".join(item.out)))
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
if len(fig_managers) != 0:
plt.close("all")
return processed_example_data(example_section_data), figs
def get_classes(code):
list(lex(code, PythonLexer()))
FMT = HtmlFormatter()
classes = [FMT.ttype2class.get(x) for x, y in lex(code, PythonLexer())]
classes = [c if c is not None else "" for c in classes]
return classes
def P2(lines) -> List[Node]:
assert isinstance(lines, list)
for l in lines:
if isinstance(l, str):
assert "\n" not in l
else:
assert "\n" not in l._line
assert lines, lines
blocks_data = parse_rst_to_papyri_tree("\n".join(lines))
for block in blocks_data:
assert not block.__class__.__name__ == "Block", block
return blocks_data
|
MIT License
|
openschc/openschc
|
src/frag_send.py
|
FragmentAckOnError.ack_timeout
|
python
|
def ack_timeout(self, *args):
self.cancel_ack_wait_timer()
dprint("----------------------- ACK timeout ----------------------- ")
self.state = self.ACK_TIMEOUT
assert len(args) == 2
assert isinstance(args[0], frag_msg.frag_sender_tx)
assert isinstance(args[1], int)
schc_frag = args[0]
win = args[1]
self.ack_requests_counter += 1
dprint("ack_requests_counter -> {}".format(self.ack_requests_counter))
if self.ack_requests_counter > max_ack_requests:
schc_frag = frag_msg.frag_sender_tx_abort(self.rule, self.dtag)
args = (schc_frag.packet.get_content(), self._session_id[0])
dprint("MESSSAGE TYPE ----> Sent Sender-Abort.", schc_frag.__dict__)
if enable_statsct:
Statsct.set_msg_type("SCHC_SENDER_ABORT")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule))
self.protocol.scheduler.add_event(0,
self.protocol.layer2.send_packet, args)
return
self.event_id_ack_wait_timer = self.protocol.scheduler.add_event(
self.ack_wait_timer, self.ack_timeout, args)
dprint("*******event id {}".format(self.event_id_ack_wait_timer))
schc_frag = frag_msg.frag_sender_ack_req(self.rule, self.dtag, win)
if enable_statsct:
Statsct.set_msg_type("SCHC_ACK_REQ")
args = (schc_frag.packet.get_content(), self._session_id[0],
self.event_sent_frag)
dprint("MESSSAGE TYPE ----> SCHC ACK REQ frag:", schc_frag.__dict__)
self.protocol.scheduler.add_event(0, self.protocol.layer2.send_packet,
args)
|
waits for all the acks before sending the ack request
self.number_of_ack_waits += 1
dprint("number_of_ack_waits -> {}".format(self.number_of_ack_waits))
if self.number_of_ack_waits > self.num_of_windows:
schc_frag = frag_msg.frag_sender_ack_req(self.rule, self.dtag, win)
if enable_statsct:
Statsct.set_msg_type("SCHC_ACK_REQ")
# # retransmit MIC.
args = (schc_frag.packet.get_content(), self._session_id[0],
self.event_sent_frag)
dprint("SCHC ACK REQ frag:", schc_frag.__dict__)
# if enable_statsct:
# Statsct.set_msg_type("SCHC_FRAG")
# Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule))
self.protocol.scheduler.add_event(0, self.protocol.layer2.send_packet,
args)
self.number_of_ack_waits = 0
else:
dprint("Do no send ACK REQ, waiting for more ACKS") #the idea is that if the ack did not arrive, to send a SCHC ACK REQ
|
https://github.com/openschc/openschc/blob/7b0c165a27936d8f2732a90844a00c5ade23eea5/src/frag_send.py#L534-L592
|
import math
from gen_base_import import *
from gen_utils import dprint, dtrace
import protocol
import frag_msg
from frag_tile import TileList
from frag_bitmap import make_bit_list
try:
import utime as time
except ImportError:
import time
enable_statsct = True
if enable_statsct:
from stats.statsct import Statsct
from compr_core import *
max_ack_requests = 8
class FragmentBase():
def __init__(self, protocol, context, rule, dtag):
self.protocol = protocol
self.context = context
self.rule = rule
self.l2word = self.rule[T_FRAG][T_FRAG_PROF][T_FRAG_L2WORDSIZE]
self.dtag = dtag
self.mic_sent = None
self.event_id_ack_wait_timer = None
self.ack_wait_timer = 150
self.ack_requests_counter = 0
self.resend = False
self.all1_send = False
self.number_tiles_send = 0
self.all_tiles = None
self.state = "START"
self.ACK_SUCCESS = "ACK_SUCCESS"
self.ACK_FAILURE = "ACK_FAILURE"
self.RECEIVER_ABORT = "RECEIVER_ABORT"
self.SEND_ALL_1 = "SEND_ALL_1"
self.WAITING_FOR_ACK = "WAITING_FOR_ACK"
self.ACK_TIMEOUT = "ACK_TIMEOUT"
self.schc_all_1 = None
self.last_window_tiles = None
self.num_of_windows = 0
self.number_of_ack_waits = 0
def set_packet(self, packet_bbuf):
self.packet_bbuf = packet_bbuf.copy()
self.mic_base = packet_bbuf.copy()
def get_mic(self, mic_base, last_frag_base_size,
penultimate_size=0):
assert isinstance(mic_base, BitBuffer)
extra_bits = (frag_msg.roundup(last_frag_base_size, self.l2word) -
last_frag_base_size)
mic_base.add_bits(0, extra_bits)
if penultimate_size != 0:
extra_bits = (frag_msg.roundup(penultimate_size, self.l2word) -
penultimate_size)
mic_base.add_bits(0, frag_msg.roundup(extra_bits,
self.rule[T_FRAG][T_FRAG_PROF ][T_FRAG_MIC]))
mic = get_mic(mic_base.get_content()).to_bytes(4, "big")
dprint("Send MIC {}, base = {}, lenght = {}".format(mic.hex(), mic_base.get_content(), len(mic_base.get_content())))
return mic
def start_sending(self):
self.send_frag()
def send_frag(self):
raise NotImplementedError("it is implemented at the subclass.")
def get_session_type(self):
return "fragmentation"
def get_state_info(self, **kw):
return "<fragmentation session>"
class FragmentNoAck(FragmentBase):
def set_packet(self, packet_bbuf):
super().set_packet(packet_bbuf)
dprint(self.rule)
min_size = (frag_msg.get_sender_header_size(self.rule) +
frag_msg.get_mic_size(self.rule) + self.l2word)
if self.protocol.layer2.get_mtu_size() < min_size:
raise ValueError("the MTU={} is not enough to carry the SCHC fragment of No-ACK mode={}".format(self.protocol.layer2.get_mtu_size(), min_size))
def send_frag(self):
payload_size = (self.protocol.layer2.get_mtu_size() -
frag_msg.get_sender_header_size(self.rule))
remaining_data_size = self.packet_bbuf.count_remaining_bits()
if remaining_data_size >= payload_size:
dprint("----------------------- Fragmentation process -----------------------")
tile = self.packet_bbuf.get_bits_as_buffer(payload_size)
transmit_callback = self.event_sent_frag
fcn = 0
self.mic_sent = None
if enable_statsct:
Statsct.set_msg_type("SCHC_FRAG")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule))
elif remaining_data_size < payload_size:
dprint("----------------------- Fragmentation process -----------------------")
if remaining_data_size <= (
payload_size - frag_msg.get_mic_size(self.rule)):
tile = None
if remaining_data_size > 0:
tile = self.packet_bbuf.get_bits_as_buffer()
assert self.mic_sent is None
last_frag_base_size = 0
if tile is not None:
last_frag_base_size += (
frag_msg.get_sender_header_size(self.rule) +
frag_msg.get_mic_size(self.rule) +
remaining_data_size)
self.mic_sent = self.get_mic(self.mic_base, last_frag_base_size)
transmit_callback = None
fcn = frag_msg.get_fcn_all_1(self.rule)
if enable_statsct:
Statsct.set_msg_type("SCHC_ALL_1 ")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule) +
frag_msg.get_mic_size(self.rule))
else:
tile_size = (remaining_data_size -
(frag_msg.get_sender_header_size(self.rule) +
remaining_data_size) % self.l2word)
tile = self.packet_bbuf.get_bits_as_buffer(tile_size)
transmit_callback = self.event_sent_frag
fcn = 0
self.mic_sent = None
if enable_statsct:
Statsct.set_msg_type("SCHC_FRAG")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule))
schc_frag = frag_msg.frag_sender_tx(
self.rule, dtag=self.dtag,
win=None,
fcn=fcn,
mic=self.mic_sent,
payload=tile)
args = (schc_frag.packet.get_content(), self._session_id[0],
transmit_callback)
dprint("frag sent:", schc_frag.__dict__)
if self.rule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG] == 0:
w_dtag = '-'
else:
w_dtag = schc_frag.dtag
if self.rule[T_FRAG][T_FRAG_PROF][T_FRAG_W] == 0:
w_w = '-'
else:
w_w = schc_frag.win
all1 = 2**self.rule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN]-1
if schc_frag.fcn == all1:
w_fcn = "All-1"
elif schc_frag.fcn == 0:
w_fcn = "All-0"
else:
w_fcn = schc_frag.fcn
dtrace ("r:{}/{} (noA) DTAG={} W={} FCN={}".format(
self.rule[T_RULEID],
self.rule[T_RULEIDLENGTH],
w_dtag,
w_w,
w_fcn
))
dtrace ("|----{:3}------------->".format(len(schc_frag.packet._content)))
self.protocol.scheduler.add_event(0, self.protocol.layer2.send_packet,
args)
def event_sent_frag(self, status):
dprint("event_sent_frag")
delay = self.protocol.config.get("tx_interval", 0)
self.protocol.scheduler.add_event(delay, self.send_frag, {})
def receive_frag(self, schc_frag, dtag):
dprint("sender frag received:", schc_frag.__dict__)
if ((self.rule[T_FRAG][T_FRAG_PROF ][T_FRAG_W] == 0 or
schc_frag.win == frag_msg.get_win_all_1(self.rule)) and
schc_frag.cbit == 1 and schc_frag.remaining.allones() == True):
dprint("Receiver Abort rid={} dtag={}".format(
self.rule.ruleID, self.dtag))
return
else:
dprint("XXX Unacceptable message has been received.")
def get_state(self, **kw):
result = {
"type": "no-ack",
"state": "XXX - need to be added"
}
return result
class FragmentAckOnError(FragmentBase):
def set_packet(self, packet_bbuf):
super().set_packet(packet_bbuf)
self.all_tiles = TileList(self.rule, packet_bbuf, self.l2word)
a = self.all_tiles.get_all_tiles()
if (a[-1]["t-num"] == 0 and
a[-1]["tile"].count_added_bits() < self.l2word):
raise ValueError("The size {} of the last tile with the tile number 0 must be equal to or greater than L2 word size {}.".format(a[-1]["tile"].count_added_bits(), self.l2word))
dprint("----------------------- Fragmentation process -----------------------")
self.bit_list = make_bit_list(self.all_tiles.get_all_tiles(),
self.rule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN],
self.rule[T_FRAG][T_FRAG_PROF][T_FRAG_W])
dprint("bit_list:", self.bit_list)
for tile in self.all_tiles.get_all_tiles():
dprint("w: {}, t: {}, sent: {}".format(tile['w-num'],tile['t-num'],tile['sent']))
self.all1_send = False
self.num_of_windows = 0
for pos in self.bit_list:
dprint("bitmap: {}, length:{}".format(self.bit_list[pos], len(self.bit_list[pos])))
if len(self.bit_list[pos]) != 0:
self.num_of_windows += 1
dprint("number of windows = {}".format(self.num_of_windows))
def send_frag(self):
if self.state == self.ACK_SUCCESS:
dprint("-----------------------------------------------------------------------")
return
dprint("----------------------- Preparing to send a message -----------------------")
scheduler = self.protocol.system.get_scheduler()
dprint("{} send_frag!!!!!!!!!!!!!!!!!".format(scheduler.get_clock()))
dprint("all1_send-> {}, resend -> {}, state -> {}".format(self.all1_send, self.resend, self.state))
dprint("all tiles unsend -> {}".format(self.all_tiles.get_all_tiles()))
for tile in self.all_tiles.get_all_tiles():
dprint("w: {}, t: {}, sent: {}".format(tile['w-num'], tile['t-num'], tile['sent']))
dprint("")
mtu_size = self.protocol.layer2.get_mtu_size()
window_tiles, nb_remaining_tiles, remaining_size = self.all_tiles.get_tiles(mtu_size)
dprint("----window tiles to send: {}, nb_remaining_tiles: {}, remaining_size: {}".format(window_tiles,
nb_remaining_tiles,
remaining_size))
if window_tiles is None and self.resend:
dprint("no more tiles to resend")
if self.state == self.ACK_FAILURE and self.event_id_ack_wait_timer is None:
win = self.last_window_tiles[0]["w-num"] if self.last_window_tiles[0]["w-num"] is not None else 0
if self.last_window_tiles[0]["t-num"] == 0:
win += 1
schc_frag = frag_msg.frag_sender_tx(
self.rule, dtag=self.dtag, win=win,
fcn=frag_msg.get_fcn_all_1(self.rule),
mic=self.mic_sent)
args = (schc_frag, win,)
self.event_id_ack_wait_timer = self.protocol.scheduler.add_event(
self.ack_wait_timer, self.ack_timeout, args)
dprint("*******event id {}".format(self.event_id_ack_wait_timer))
if window_tiles is not None:
dprint("window_tiles is not None -> {}, resend -> {}".format(self.all1_send, self.resend))
dprint("")
if self.all1_send and self.state != self.ACK_FAILURE:
dprint('All-1 ones already send')
return
elif (nb_remaining_tiles == 0 and
len(window_tiles) == 1 and
remaining_size >= frag_msg.get_mic_size(self.rule)):
dprint("MESSSAGE TYPE ----> ALL-1 prepared")
fcn = frag_msg.get_fcn_all_1(self.rule)
last_frag_base_size = (
frag_msg.get_sender_header_size(self.rule) +
frag_msg.get_mic_size(self.rule) +
TileList.get_tile_size(window_tiles))
if self.mic_sent is None:
mic = self.get_mic(self.mic_base, last_frag_base_size)
self.mic_sent = mic
else:
mic = self.mic_sent
dprint("mic_sent -> {}".format(self.mic_sent))
if enable_statsct:
Statsct.set_msg_type("SCHC_ALL_1")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule) +
frag_msg.get_mic_size(self.rule))
self.all1_send = True
self.state = self.SEND_ALL_1
else:
dprint("MESSSAGE TYPE ----> regular SCHC frag")
dprint("")
fcn = window_tiles[0]["t-num"]
mic = None
if enable_statsct:
Statsct.set_msg_type("SCHC_FRAG")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule))
schc_frag = frag_msg.frag_sender_tx(
self.rule, dtag=self.dtag,
win=window_tiles[0]["w-num"],
fcn=fcn,
mic=mic,
payload=TileList.concat(window_tiles))
if mic is not None:
dprint("mic is not None")
if enable_statsct:
Statsct.set_msg_type("SCHC_FRAG")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule))
args = (schc_frag, window_tiles[0]["w-num"],)
dprint("all ones")
self.schc_all_1 = schc_frag
self.event_id_ack_wait_timer = self.protocol.scheduler.add_event(
self.ack_wait_timer, self.ack_timeout, args)
dprint("*******event id {}".format(self.event_id_ack_wait_timer))
self.last_window_tiles = window_tiles
dprint("self.last_window_tiles -> {}".format(self.last_window_tiles))
elif self.mic_sent is not None or self.all1_send:
dprint("self.mic_sent is not None state -> {}".format(self.state))
dprint("----------------------- all tiles have been sent -----------------------",
window_tiles, nb_remaining_tiles, remaining_size)
schc_frag = None
self.all1_send = True
if self.event_id_ack_wait_timer and self.state == self.ACK_SUCCESS:
self.cancel_ack_wait_timer()
return
else:
dprint("only mic all tiles send")
assert self.last_window_tiles is not None
last_frag_base_size = (frag_msg.get_sender_header_size(self.rule) +
TileList.get_tile_size(self.last_window_tiles))
self.mic_sent = self.get_mic(self.mic_base, last_frag_base_size)
win = self.last_window_tiles[0]["w-num"]
if self.last_window_tiles[0]["t-num"] == 0:
win += 1
schc_frag = frag_msg.frag_sender_tx(
self.rule, dtag=self.dtag, win=win,
fcn=frag_msg.get_fcn_all_1(self.rule),
mic=self.mic_sent)
args = (schc_frag, win,)
if enable_statsct:
Statsct.set_msg_type("SCHC_ALL_1")
Statsct.set_header_size(frag_msg.get_sender_header_size(self.rule) +
frag_msg.get_mic_size(self.rule))
self.schc_all_1 = schc_frag
self.state = self.SEND_ALL_1
self.event_id_ack_wait_timer = self.protocol.scheduler.add_event(
self.ack_wait_timer, self.ack_timeout, args)
dprint("*******event id {}".format(self.event_id_ack_wait_timer))
args = (schc_frag.packet.get_content(), self._session_id[0], self.event_sent_frag)
dprint("frag sent:", schc_frag.__dict__)
self.protocol.scheduler.add_event(0, self.protocol.layer2.send_packet, args)
def cancel_ack_wait_timer(self):
dprint('----------------------- cancel_ack_wait_timer -----------------------')
self.protocol.scheduler.cancel_event(self.event_id_ack_wait_timer)
self.event_id_ack_wait_timer = None
|
MIT License
|
markharwood/nanosessionkontrol
|
src/nanoSessionKontrol/ChannelStripController.py
|
ChannelStripController.__apply_meter_mode
|
python
|
def __apply_meter_mode(self):
enabled = self.__meters_enabled and self.__assignment_mode is CSM_VOLPAN
for s in self.__channel_strips:
s.enable_meter_mode(enabled)
self.__main_display_controller.enable_meters(enabled)
|
Update the meter mode in the displays and channel strips
|
https://github.com/markharwood/nanosessionkontrol/blob/2a898dfca38c149977ba90feb15e85f95c2c86bc/src/nanoSessionKontrol/ChannelStripController.py#L580-L586
|
from itertools import chain
from MHControlComponent import *
from _Generic.Devices import *
class ChannelStripController(MHControlComponent):
def __init__(self, main_script, channel_strips, master_strip, main_display_controller):
MHControlComponent.__init__(self, main_script)
self.__left_extensions = []
self.__right_extensions = []
self.__own_channel_strips = channel_strips
self.__master_strip = master_strip
self.__channel_strips = channel_strips
self.__main_display_controller = main_display_controller
self.__meters_enabled = False
self.__assignment_mode = CSM_VOLPAN
self.__sub_mode_in_io_mode = CSM_IO_FIRST_MODE
self.__plugin_mode = PCM_DEVICES
self.__plugin_mode_offsets = [ 0 for x in range(PCM_NUMMODES) ]
self.__chosen_plugin = None
self.__ordered_plugin_parameters = []
self.__displayed_plugins = []
self.__last_attached_selected_track = None
self.__send_mode_offset = 0
self.__flip = False
self.__view_returns = False
self.__bank_cha_offset = 0
self.__bank_cha_offset_returns = 0
self.__within_track_added_or_deleted = False
self.song().add_visible_tracks_listener(self.__on_tracks_added_or_deleted)
self.song().view.add_selected_track_listener(self.__on_selected_track_changed)
for t in chain(self.song().visible_tracks, self.song().return_tracks):
if not t.solo_has_listener(self.__update_rude_solo_led):
t.add_solo_listener(self.__update_rude_solo_led)
if not t.has_audio_output_has_listener(self.__on_any_tracks_output_type_changed):
t.add_has_audio_output_listener(self.__on_any_tracks_output_type_changed)
self.__on_selected_track_changed()
for s in self.__own_channel_strips:
s.set_channel_strip_controller(self)
self.__reassign_channel_strip_offsets()
self.__reassign_channel_strip_parameters(for_display_only=False)
def destroy(self):
self.song().remove_visible_tracks_listener(self.__on_tracks_added_or_deleted)
self.song().view.remove_selected_track_listener(self.__on_selected_track_changed)
for t in chain(self.song().visible_tracks, self.song().return_tracks):
if t.solo_has_listener(self.__update_rude_solo_led):
t.remove_solo_listener(self.__update_rude_solo_led)
if t.has_audio_output_has_listener(self.__on_any_tracks_output_type_changed):
t.remove_has_audio_output_listener(self.__on_any_tracks_output_type_changed)
st = self.__last_attached_selected_track
if st and st.devices_has_listener(self.__on_selected_device_chain_changed):
st.remove_devices_listener(self.__on_selected_device_chain_changed)
for note in channel_strip_assignment_switch_ids:
self.send_midi((NOTE_ON_STATUS, note, BUTTON_STATE_OFF))
for note in channel_strip_control_switch_ids:
self.send_midi((NOTE_ON_STATUS, note, BUTTON_STATE_OFF))
self.send_midi((NOTE_ON_STATUS, SELECT_RUDE_SOLO, BUTTON_STATE_OFF))
self.send_midi((CC_STATUS, 75, g7_seg_led_conv_table[' ']))
self.send_midi((CC_STATUS, 74, g7_seg_led_conv_table[' ']))
MHControlComponent.destroy(self)
def set_controller_extensions(self, left_extensions, right_extensions):
self.__left_extensions = left_extensions
self.__right_extensions = right_extensions
self.__channel_strips = []
stack_offset = 0
for le in left_extensions:
for s in le.channel_strips():
self.__channel_strips.append(s)
s.set_stack_offset(stack_offset)
stack_offset += NUM_CHANNEL_STRIPS
for s in self.__own_channel_strips:
self.__channel_strips.append(s)
s.set_stack_offset(stack_offset)
stack_offset += NUM_CHANNEL_STRIPS
for re in right_extensions:
for s in re.channel_strips():
self.__channel_strips.append(s)
s.set_stack_offset(stack_offset)
stack_offset += NUM_CHANNEL_STRIPS
for s in self.__channel_strips:
s.set_channel_strip_controller(self)
self.refresh_state()
def refresh_state(self):
self.__update_assignment_mode_leds()
self.__update_assignment_display()
self.__update_rude_solo_led()
self.__reassign_channel_strip_offsets()
self.__on_flip_changed()
self.__update_view_returns_mode()
def request_rebuild_midi_map(self):
MHControlComponent.request_rebuild_midi_map(self)
for ex in self.__left_extensions + self.__right_extensions:
ex.request_rebuild_midi_map()
def on_update_display_timer(self):
self.__update_channel_strip_strings()
def toggle_meter_mode(self):
self.__meters_enabled = not self.__meters_enabled
self.__apply_meter_mode()
def handle_assignment_switch_ids(self, switch_id, value):
if switch_id == SID_ASSIGNMENT_IO:
if value == BUTTON_PRESSED:
self.__set_assignment_mode(CSM_IO)
elif switch_id == SID_ASSIGNMENT_SENDS:
if value == BUTTON_PRESSED:
self.__set_assignment_mode(CSM_SENDS)
elif switch_id == SID_ASSIGNMENT_PAN:
if value == BUTTON_PRESSED:
self.__set_assignment_mode(CSM_VOLPAN)
elif switch_id == SID_ASSIGNMENT_PLUG_INS:
if value == BUTTON_PRESSED:
self.__set_assignment_mode(CSM_PLUGINS)
elif switch_id == SID_ASSIGNMENT_EQ:
if value == BUTTON_PRESSED:
self.__switch_to_prev_page()
elif switch_id == SID_ASSIGNMENT_DYNAMIC:
if value == BUTTON_PRESSED:
self.__switch_to_next_page()
elif switch_id == SID_FADERBANK_PREV_BANK:
if value == BUTTON_PRESSED:
print 'Previous scene'
self.song().undo()
elif switch_id == SID_FADERBANK_NEXT_BANK:
if value == BUTTON_PRESSED:
print 'Next scene'
self.song().redo()
elif switch_id == SID_FADERBANK_PREV_CH:
if value == BUTTON_PRESSED:
if self.shift_is_pressed():
self.__set_channel_offset(0)
else:
self.__set_channel_offset(self.__strip_offset() - 1)
elif switch_id == SID_FADERBANK_NEXT_CH:
if value == BUTTON_PRESSED:
if self.shift_is_pressed():
self.__set_channel_offset(self.__controlled_num_of_tracks() - len(self.__channel_strips))
elif self.__strip_offset() < self.__controlled_num_of_tracks() - len(self.__channel_strips):
self.__set_channel_offset(self.__strip_offset() + 1)
elif switch_id == SID_FADERBANK_FLIP:
if value == BUTTON_PRESSED:
self.__toggle_flip()
elif switch_id == SID_FADERBANK_EDIT:
if value == BUTTON_PRESSED:
self.__toggle_view_returns()
def handle_vpot_rotation(self, strip_index, stack_offset, cc_value):
if self.__assignment_mode == CSM_IO:
if cc_value >= 64:
direction = -1
else:
direction = 1
channel_strip = self.__channel_strips[stack_offset + strip_index]
current_routing = self.__routing_target(channel_strip)
available_routings = self.__available_routing_targets(channel_strip)
if current_routing and available_routings:
if current_routing in available_routings:
i = list(available_routings).index(current_routing)
if direction == 1:
new_i = min(len(available_routings) - 1, i + direction)
else:
new_i = max(0, i + direction)
new_routing = available_routings[new_i]
elif len(available_routings):
new_routing = available_routings[0]
self.__set_routing_target(channel_strip, new_routing)
elif self.__assignment_mode == CSM_PLUGINS:
pass
else:
channel_strip = self.__channel_strips[stack_offset + strip_index]
raise not channel_strip.assigned_track() or not channel_strip.assigned_track().has_audio_output or AssertionError, 'in every other mode, the midimap should handle the messages'
def handle_fader_touch(self, strip_offset, stack_offset, touched):
self.__reassign_channel_strip_parameters(for_display_only=True)
def handle_pressed_v_pot(self, strip_index, stack_offset):
if self.__assignment_mode == CSM_VOLPAN or self.__assignment_mode == CSM_SENDS or self.__assignment_mode == CSM_PLUGINS and self.__plugin_mode == PCM_PARAMETERS:
if stack_offset + strip_index in range(0, len(self.__channel_strips)):
param = self.__channel_strips[stack_offset + strip_index].v_pot_parameter()
if param and param.is_enabled:
if param.is_quantized:
if param.value + 1 > param.max:
param.value = param.min
else:
param.value = param.value + 1
else:
param.value = param.default_value
elif self.__assignment_mode == CSM_PLUGINS:
if self.__plugin_mode == PCM_DEVICES:
device_index = strip_index + stack_offset + self.__plugin_mode_offsets[PCM_DEVICES]
if device_index >= 0 and device_index < len(self.song().view.selected_track.devices):
if self.__chosen_plugin != None:
self.__chosen_plugin.remove_parameters_listener(self.__on_parameter_list_of_chosen_plugin_changed)
self.__chosen_plugin = self.song().view.selected_track.devices[device_index]
self.__chosen_plugin != None and self.__chosen_plugin.add_parameters_listener(self.__on_parameter_list_of_chosen_plugin_changed)
self.__reorder_parameters()
self.__plugin_mode_offsets[PCM_PARAMETERS] = 0
self.__set_plugin_mode(PCM_PARAMETERS)
def __strip_offset(self):
if self.__view_returns:
return self.__bank_cha_offset_returns
else:
return self.__bank_cha_offset
def __controlled_num_of_tracks(self):
if self.__view_returns:
return len(self.song().return_tracks)
else:
return len(self.song().visible_tracks)
def __send_parameter(self, strip_index, stack_index):
if not self.__assignment_mode == CSM_SENDS:
raise AssertionError
send_index = strip_index + stack_index + self.__send_mode_offset
p = send_index < len(self.song().view.selected_track.mixer_device.sends) and self.song().view.selected_track.mixer_device.sends[send_index]
return (p, p.name)
return (None, None)
def __plugin_parameter(self, strip_index, stack_index):
if not self.__assignment_mode == CSM_PLUGINS:
raise AssertionError
return self.__plugin_mode == PCM_DEVICES and (None, None)
elif not (self.__plugin_mode == PCM_PARAMETERS and self.__chosen_plugin):
raise AssertionError
parameters = self.__ordered_plugin_parameters
parameter_index = strip_index + stack_index + self.__plugin_mode_offsets[PCM_PARAMETERS]
if parameter_index >= 0 and parameter_index < len(parameters):
return parameters[parameter_index]
else:
return (None, None)
else:
raise 0 or AssertionError
def __any_slider_is_touched(self):
for s in self.__channel_strips:
if s.is_touched():
return True
return False
def __can_flip(self):
if self.__assignment_mode == CSM_PLUGINS and self.__plugin_mode == PCM_DEVICES:
return False
elif self.__assignment_mode == CSM_IO:
return False
return True
def __can_switch_to_prev_page(self):
if self.__assignment_mode == CSM_PLUGINS:
return self.__plugin_mode_offsets[self.__plugin_mode] > 0
elif self.__assignment_mode == CSM_SENDS:
return self.__send_mode_offset > 0
else:
return False
def __can_switch_to_next_page(self):
if self.__assignment_mode == CSM_PLUGINS:
sel_track = self.song().view.selected_track
if self.__plugin_mode == PCM_DEVICES:
return self.__plugin_mode_offsets[PCM_DEVICES] + len(self.__channel_strips) < len(sel_track.devices)
elif not (self.__plugin_mode == PCM_PARAMETERS and self.__chosen_plugin):
raise AssertionError
parameters = self.__ordered_plugin_parameters
return self.__plugin_mode_offsets[PCM_PARAMETERS] + len(self.__channel_strips) < len(parameters)
else:
raise 0 or AssertionError
elif self.__assignment_mode == CSM_SENDS:
return self.__send_mode_offset + len(self.__channel_strips) < len(self.song().return_tracks)
else:
return False
def __available_routing_targets(self, channel_strip):
raise self.__assignment_mode == CSM_IO or AssertionError
t = channel_strip.assigned_track()
if t:
if self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_MAIN:
return t.input_routings
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_SUB:
return t.input_sub_routings
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_MAIN:
return t.output_routings
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_SUB:
return t.output_sub_routings
else:
raise 0 or AssertionError
else:
return None
def __routing_target(self, channel_strip):
raise self.__assignment_mode == CSM_IO or AssertionError
t = channel_strip.assigned_track()
if t:
if self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_MAIN:
return t.current_input_routing
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_SUB:
return t.current_input_sub_routing
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_MAIN:
return t.current_output_routing
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_SUB:
return t.current_output_sub_routing
else:
raise 0 or AssertionError
else:
return None
def __set_routing_target(self, channel_strip, target_string):
raise self.__assignment_mode == CSM_IO or AssertionError
t = channel_strip.assigned_track()
if t:
if self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_MAIN:
t.current_input_routing = target_string
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_SUB:
t.current_input_sub_routing = target_string
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_MAIN:
t.current_output_routing = target_string
elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_SUB:
t.current_output_sub_routing = target_string
else:
raise 0 or AssertionError
def __set_channel_offset(self, new_offset):
if new_offset < 0:
new_offset = 0
elif new_offset >= self.__controlled_num_of_tracks():
new_offset = self.__controlled_num_of_tracks() - 1
if self.__view_returns:
self.__bank_cha_offset_returns = new_offset
else:
self.__bank_cha_offset = new_offset
self.__main_display_controller.set_channel_offset(new_offset)
self.__reassign_channel_strip_offsets()
self.__reassign_channel_strip_parameters(for_display_only=False)
self.__update_channel_strip_strings()
self.request_rebuild_midi_map()
def __set_assignment_mode(self, mode):
for plugin in self.__displayed_plugins:
if plugin != None:
plugin.remove_name_listener(self.__update_plugin_names)
self.__displayed_plugins = []
if mode == CSM_PLUGINS:
self.__assignment_mode = mode
self.__main_display_controller.set_show_parameter_names(True)
self.__set_plugin_mode(PCM_DEVICES)
elif mode == CSM_SENDS:
self.__main_display_controller.set_show_parameter_names(True)
self.__assignment_mode = mode
else:
if mode == CSM_IO:
for s in self.__channel_strips:
s.unlight_vpot_leds()
self.__main_display_controller.set_show_parameter_names(False)
if self.__assignment_mode != mode:
self.__assignment_mode = mode
elif self.__assignment_mode == CSM_IO:
self.__switch_to_next_io_mode()
self.__update_assignment_mode_leds()
self.__update_assignment_display()
self.__apply_meter_mode()
self.__reassign_channel_strip_parameters(for_display_only=False)
self.__update_channel_strip_strings()
self.__update_page_switch_leds()
if mode == CSM_PLUGINS:
self.__update_vpot_leds_in_plugins_device_choose_mode()
self.__update_flip_led()
self.request_rebuild_midi_map()
def __set_plugin_mode(self, new_mode):
if not (new_mode >= 0 and new_mode < PCM_NUMMODES):
raise AssertionError
if self.__plugin_mode != new_mode:
self.__plugin_mode = new_mode
self.__reassign_channel_strip_parameters(for_display_only=False)
self.request_rebuild_midi_map()
self.__plugin_mode == PCM_DEVICES and self.__update_vpot_leds_in_plugins_device_choose_mode()
else:
for plugin in self.__displayed_plugins:
if plugin != None:
plugin.remove_name_listener(self.__update_plugin_names)
self.__displayed_plugins = []
self.__update_page_switch_leds()
self.__update_flip_led()
self.__update_page_switch_leds()
def __switch_to_prev_page(self):
if self.__can_switch_to_prev_page():
if self.__assignment_mode == CSM_PLUGINS:
self.__plugin_mode_offsets[self.__plugin_mode] -= len(self.__channel_strips)
if self.__plugin_mode == PCM_DEVICES:
self.__update_vpot_leds_in_plugins_device_choose_mode()
elif self.__assignment_mode == CSM_SENDS:
self.__send_mode_offset -= len(self.__channel_strips)
self.__reassign_channel_strip_parameters(for_display_only=False)
self.__update_channel_strip_strings()
self.__update_page_switch_leds()
self.request_rebuild_midi_map()
def __switch_to_next_page(self):
if self.__can_switch_to_next_page():
if self.__assignment_mode == CSM_PLUGINS:
self.__plugin_mode_offsets[self.__plugin_mode] += len(self.__channel_strips)
if self.__plugin_mode == PCM_DEVICES:
self.__update_vpot_leds_in_plugins_device_choose_mode()
elif self.__assignment_mode == CSM_SENDS:
self.__send_mode_offset += len(self.__channel_strips)
else:
raise 0 or AssertionError
self.__reassign_channel_strip_parameters(for_display_only=False)
self.__update_channel_strip_strings()
self.__update_page_switch_leds()
self.request_rebuild_midi_map()
def __switch_to_next_io_mode(self):
self.__sub_mode_in_io_mode += 1
if self.__sub_mode_in_io_mode > CSM_IO_LAST_MODE:
self.__sub_mode_in_io_mode = CSM_IO_FIRST_MODE
def __reassign_channel_strip_offsets(self):
for s in self.__channel_strips:
s.set_bank_and_channel_offset(self.__strip_offset(), self.__view_returns, self.__within_track_added_or_deleted)
def __reassign_channel_strip_parameters(self, for_display_only):
display_parameters = []
for s in self.__channel_strips:
vpot_param = (None, None)
slider_param = (None, None)
vpot_display_mode = VPOT_DISPLAY_SINGLE_DOT
slider_display_mode = VPOT_DISPLAY_SINGLE_DOT
if self.__assignment_mode == CSM_VOLPAN:
if s.assigned_track() and s.assigned_track().has_audio_output:
vpot_param = (s.assigned_track().mixer_device.panning, 'Pan')
vpot_display_mode = VPOT_DISPLAY_BOOST_CUT
slider_param = (s.assigned_track().mixer_device.volume, 'Volume')
slider_display_mode = VPOT_DISPLAY_WRAP
elif self.__assignment_mode == CSM_PLUGINS:
vpot_param = self.__plugin_parameter(s.strip_index(), s.stack_offset())
vpot_display_mode = VPOT_DISPLAY_WRAP
if s.assigned_track() and s.assigned_track().has_audio_output:
slider_param = (s.assigned_track().mixer_device.volume, 'Volume')
slider_display_mode = VPOT_DISPLAY_WRAP
elif self.__assignment_mode == CSM_SENDS:
vpot_param = self.__send_parameter(s.strip_index(), s.stack_offset())
vpot_display_mode = VPOT_DISPLAY_WRAP
if s.assigned_track() and s.assigned_track().has_audio_output:
slider_param = (s.assigned_track().mixer_device.volume, 'Volume')
slider_display_mode = VPOT_DISPLAY_WRAP
elif self.__assignment_mode == CSM_IO:
if s.assigned_track() and s.assigned_track().has_audio_output:
slider_param = (s.assigned_track().mixer_device.volume, 'Volume')
if self.__flip and self.__can_flip():
if self.__any_slider_is_touched():
display_parameters.append(vpot_param)
else:
display_parameters.append(slider_param)
if not for_display_only:
s.set_v_pot_parameter(slider_param[0], slider_display_mode)
s.set_fader_parameter(vpot_param[0])
else:
if self.__any_slider_is_touched():
display_parameters.append(slider_param)
else:
display_parameters.append(vpot_param)
if not for_display_only:
s.set_v_pot_parameter(vpot_param[0], vpot_display_mode)
s.set_fader_parameter(slider_param[0])
self.__main_display_controller.set_channel_offset(self.__strip_offset())
if len(display_parameters):
self.__main_display_controller.set_parameters(display_parameters)
|
Apache License 2.0
|
parquery/icontract
|
icontract/_recompute.py
|
_translate_all_expression_to_a_module
|
python
|
def _translate_all_expression_to_a_module(generator_exp: ast.GeneratorExp, generated_function_name: str,
name_to_value: Mapping[str, Any]) -> ast.Module:
assert generated_function_name not in name_to_value
assert not hasattr(builtins, generated_function_name)
relevant_names = _collect_stored_names(generator.target for generator in generator_exp.generators)
assert generated_function_name not in relevant_names
result_id = 'icontract_tracing_all_result_{}'.format(uuid.uuid4().hex)
result_assignment = ast.Assign(targets=[ast.Name(id=result_id, ctx=ast.Store())], value=generator_exp.elt)
exceptional_return = ast.Return(
ast.Tuple(
elts=[
ast.Name(id=result_id, ctx=ast.Load()),
ast.Tuple(
elts=[
ast.Tuple(
elts=[
ast.Constant(value=relevant_name, kind=None),
ast.Name(id=relevant_name, ctx=ast.Load())
],
ctx=ast.Load()) for relevant_name in relevant_names
],
ctx=ast.Load())
],
ctx=ast.Load()))
happy_return = ast.Return(
ast.Tuple(elts=[ast.Name(id=result_id, ctx=ast.Load()),
ast.Constant(value=None, kind=None)], ctx=ast.Load()))
critical_if: If = ast.If(
test=ast.Name(id=result_id, ctx=ast.Load()), body=[ast.Pass()], orelse=[exceptional_return])
block = None
for i, comprehension in enumerate(reversed(generator_exp.generators)):
if i == 0:
block = [result_assignment, critical_if]
assert block is not None
for condition in reversed(comprehension.ifs):
block = [ast.If(test=condition, body=block, orelse=[])]
if not comprehension.is_async:
block = [ast.For(target=comprehension.target, iter=comprehension.iter, body=block, orelse=[])]
else:
block = [ast.AsyncFor(target=comprehension.target, iter=comprehension.iter, body=block, orelse=[])]
assert block is not None
block.append(happy_return)
is_async = any(comprehension.is_async for comprehension in generator_exp.generators)
args = [ast.arg(arg=name, annotation=None) for name in sorted(name_to_value.keys())]
if platform.python_version_tuple() < ('3', '5'):
raise NotImplementedError("Python versions below 3.5 not supported, got: {}".format(platform.python_version()))
if not is_async:
if platform.python_version_tuple() < ('3', '8'):
func_def_node = ast.FunctionDef(
name=generated_function_name,
args=ast.arguments(args=args, kwonlyargs=[], kw_defaults=[], defaults=[], vararg=None, kwarg=None),
decorator_list=[],
body=block)
module_node = ast.Module(body=[func_def_node])
else:
func_def_node = ast.FunctionDef(
name=generated_function_name,
args=ast.arguments(
args=args, posonlyargs=[], kwonlyargs=[], kw_defaults=[], defaults=[], vararg=None, kwarg=None),
decorator_list=[],
body=block)
module_node = ast.Module(body=[func_def_node], type_ignores=[])
else:
if platform.python_version_tuple() < ('3', '8'):
func_def_node = ast.AsyncFunctionDef(
name=generated_function_name,
args=ast.arguments(args=args, kwonlyargs=[], kw_defaults=[], defaults=[], vararg=None, kwarg=None),
decorator_list=[],
body=block)
module_node = ast.Module(body=[func_def_node])
else:
func_def_node = ast.AsyncFunctionDef(
name=generated_function_name,
args=ast.arguments(
args=args, posonlyargs=[], kwonlyargs=[], kw_defaults=[], defaults=[], vararg=None, kwarg=None),
decorator_list=[],
body=block)
module_node = ast.Module(body=[func_def_node], type_ignores=[])
ast.fix_missing_locations(module_node)
return module_node
|
Generate the AST of the module to trace an all quantifier on an generator expression.
:param generator_exp: generator expression to be translated
:param generated_function_name: UUID of the tracing function to be used in the code
:param name_to_value:
mapping of all resolved values to the variable names
(passed as arguments to the function so that the generation can access them)
:return: translation to a module
|
https://github.com/parquery/icontract/blob/8d3193144a0b92e96f548b2ee828eb36a405ed40/icontract/_recompute.py#L89-L208
|
import ast
import builtins
import copy
import functools
import inspect
import platform
import sys
import uuid
from typing import (Any, Mapping, Dict, List, Optional, Union, Tuple, Set, Callable, cast, Iterable, TypeVar)
from _ast import If
class Placeholder:
def __repr__(self) -> str:
return "<Placeholder>"
PLACEHOLDER = Placeholder()
class FirstExceptionInAll:
def __init__(self, result: Any, inputs: Tuple[Tuple[str, Any]]) -> None:
self.result = result
self.inputs = inputs
def __bool__(self) -> Any:
return self.result
ContextT = TypeVar('ContextT', bound=ast.expr_context)
class _CollectStoredNamesVisitor(ast.NodeVisitor):
def __init__(self) -> None:
self.names = []
self._name_set = set()
def visit_Name(self, node: ast.Name) -> Any:
if isinstance(node.ctx, ast.Store) and node.id not in self._name_set:
self.names.append(node.id)
self._name_set.add(node.id)
def _collect_stored_names(nodes: Iterable[ast.expr]) -> List[str]:
visitor = _CollectStoredNamesVisitor()
for node in nodes:
visitor.visit(node)
return visitor.names
class _CollectNameLoadsVisitor(ast.NodeVisitor):
def __init__(self) -> None:
self.nodes = []
def visit_Name(self, node: ast.Name) -> Any:
if isinstance(node.ctx, ast.Load):
self.nodes.append(node)
def _collect_name_loads(nodes: Iterable[ast.expr]) -> List[ast.expr]:
visitor = _CollectNameLoadsVisitor()
for node in nodes:
visitor.visit(node)
return visitor.nodes
|
MIT License
|
b6d/lima
|
lima/fields.py
|
Reference.pack
|
python
|
def pack(self, val):
return self._pack_func(val) if val is not None else None
|
Return value of reference field of marshalled representation of val.
Args:
val: The nested object to get the reference to.
Returns:
The value of the reference-field of the marshalled representation
of val (see ``field`` argument of constructor) or ``None`` if
``val`` is ``None``.
Note that the return value is determined using an (internal) dump field
*function* of the associated schema object. This means that overriding
the associated schema's :meth:`~lima.schema.Schema.dump` *method* has
no effect on the result of this method.
|
https://github.com/b6d/lima/blob/13c5d184f7e3a26fc468d2658664c91f577017d9/lima/fields.py#L380-L397
|
import datetime
import decimal
from lima import abc
from lima import registry
from lima import util
class Field(abc.FieldABC):
def __init__(self, *, attr=None, key=None, get=None, val=None):
if sum(v is not None for v in (attr, key, get, val)) > 1:
raise ValueError('attr, key, get and val are mutually exclusive.')
if attr is not None:
if not isinstance(attr, str) or not str.isidentifier(attr):
msg = 'attr is not a valid Python identifier: {}'.format(attr)
raise ValueError(msg)
self.attr = attr
elif key is not None:
self.key = key
elif get is not None:
if not callable(get):
raise ValueError('get is not callable.')
self.get = get
elif val is not None:
self.val = val
class Boolean(Field):
pass
class Decimal(Field):
@staticmethod
def pack(val):
return str(val) if val is not None else None
class Float(Field):
pass
class Integer(Field):
pass
class String(Field):
pass
class Date(Field):
@staticmethod
def pack(val):
return val.isoformat() if val is not None else None
class DateTime(Field):
@staticmethod
def pack(val):
return val.isoformat() if val is not None else None
class _LinkedObjectField(Field):
def __init__(self,
*,
schema,
attr=None,
key=None,
get=None,
val=None,
**kwargs):
super().__init__(attr=attr, key=key, get=get, val=val)
self._schema_arg = schema
self._schema_kwargs = kwargs
@util.reify
def _schema_inst(self):
with util.exception_context('Lazy evaluation of schema instance'):
schema = self._schema_arg
kwargs = self._schema_kwargs
if isinstance(schema, abc.SchemaABC):
if kwargs:
msg = ('No additional keyword args must be '
'supplied to field constructor if '
'schema already is a Schema object.')
raise ValueError(msg)
return schema
elif (isinstance(schema, type) and
issubclass(schema, abc.SchemaABC)):
return schema(**kwargs)
elif isinstance(schema, str):
cls = registry.global_registry.get(schema)
return cls(**kwargs)
msg = 'schema arg supplied to constructor has illegal type ({})'
raise TypeError(msg.format(type(schema)))
def pack(self, val):
raise NotImplementedError
class Embed(_LinkedObjectField):
@util.reify
def _pack_func(self):
return self._schema_inst._dump_fields
def pack(self, val):
return self._pack_func(val) if val is not None else None
class Reference(_LinkedObjectField):
def __init__(self,
*,
schema,
field,
attr=None,
key=None,
get=None,
val=None,
**kwargs):
super().__init__(schema=schema,
attr=attr, key=key, get=get, val=val, **kwargs)
self._field = field
@util.reify
def _pack_func(self):
return self._schema_inst._dump_field_func(self._field)
|
MIT License
|
intel/openfl
|
openfl/component/aggregator/aggregator.py
|
Aggregator.get_aggregated_tensor
|
python
|
def get_aggregated_tensor(self, collaborator_name, tensor_name,
round_number, report, tags, require_lossless):
self.logger.debug(f'Retrieving aggregated tensor {tensor_name},{round_number},{tags} '
f'for collaborator {collaborator_name}')
if 'compressed' in tags or require_lossless:
compress_lossless = True
else:
compress_lossless = False
if 'compressed' in tags:
tags.remove('compressed')
if 'lossy_compressed' in tags:
tags.remove('lossy_compressed')
tensor_key = TensorKey(
tensor_name, self.uuid, round_number, report, tuple(tags)
)
tensor_name, origin, round_number, report, tags = tensor_key
if 'aggregated' in tags and 'delta' in tags and round_number != 0:
agg_tensor_key = TensorKey(
tensor_name, origin, round_number, report, ('aggregated',)
)
else:
agg_tensor_key = tensor_key
nparray = self.tensor_db.get_tensor_from_cache(agg_tensor_key)
if nparray is None:
raise ValueError(f'Aggregator does not have an aggregated tensor for {tensor_key}')
named_tensor = self._nparray_to_named_tensor(
agg_tensor_key,
nparray,
send_model_deltas=True,
compress_lossless=compress_lossless
)
return named_tensor
|
RPC called by collaborator.
Performs local lookup to determine if there is an aggregated tensor available \
that matches the request.
Args:
collaborator_name : str
Requested tensor key collaborator name
tensor_name: str
require_lossless: bool
round_number: int
report: bool
tags: list[str]
Returns:
named_tensor : protobuf NamedTensor
the tensor requested by the collaborator
|
https://github.com/intel/openfl/blob/4bda3850b6bce7c904a5ac3ed56115bec00be2e0/openfl/component/aggregator/aggregator.py#L312-L375
|
import queue
from logging import getLogger
from openfl.component.aggregation_functions import WeightedAverage
from openfl.databases import TensorDB
from openfl.pipelines import NoCompressionPipeline
from openfl.pipelines import TensorCodec
from openfl.protocols import ModelProto
from openfl.protocols import utils
from openfl.utilities import TaskResultKey
from openfl.utilities import TensorKey
from openfl.utilities.logs import write_metric
class Aggregator:
def __init__(self,
aggregator_uuid,
federation_uuid,
authorized_cols,
init_state_path,
best_state_path,
last_state_path,
assigner,
rounds_to_train=256,
log_metric_callback=None,
single_col_cert_common_name=None,
compression_pipeline=None,
db_store_rounds=1,
**kwargs):
self.round_number = 0
self.single_col_cert_common_name = single_col_cert_common_name
if self.single_col_cert_common_name is not None:
self._log_big_warning()
else:
self.single_col_cert_common_name = ''
self.rounds_to_train = rounds_to_train
self.authorized_cols = authorized_cols
self.uuid = aggregator_uuid
self.federation_uuid = federation_uuid
self.assigner = assigner
self.quit_job_sent_to = []
self.tensor_db = TensorDB()
self.db_store_rounds = db_store_rounds
self.compression_pipeline = compression_pipeline or NoCompressionPipeline()
self.tensor_codec = TensorCodec(self.compression_pipeline)
self.logger = getLogger(__name__)
self.init_state_path = init_state_path
self.best_state_path = best_state_path
self.last_state_path = last_state_path
self.best_tensor_dict: dict = {}
self.last_tensor_dict: dict = {}
self.metric_queue = queue.Queue()
self.best_model_score = None
if kwargs.get('initial_tensor_dict', None) is not None:
self._load_initial_tensors_from_dict(kwargs['initial_tensor_dict'])
self.model = utils.construct_model_proto(
tensor_dict=kwargs['initial_tensor_dict'],
round_number=0,
tensor_pipe=self.compression_pipeline)
else:
self.model: ModelProto = utils.load_proto(self.init_state_path)
self._load_initial_tensors()
self.log_dir = f'logs/{self.uuid}_{self.federation_uuid}'
self.collaborator_tensor_results = {}
self.collaborator_tasks_results = {}
self.collaborator_task_weight = {}
self.log_metric = write_metric
def _load_initial_tensors(self):
tensor_dict, round_number = utils.deconstruct_model_proto(
self.model, compression_pipeline=self.compression_pipeline)
if round_number > self.round_number:
self.logger.info(
f'Starting training from round {round_number} of previously saved model'
)
self.round_number = round_number
tensor_key_dict = {
TensorKey(k, self.uuid, self.round_number, False, ('model',)):
v for k, v in tensor_dict.items()
}
self.tensor_db.cache_tensor(tensor_key_dict)
self.logger.debug(f'This is the initial tensor_db: {self.tensor_db}')
def _load_initial_tensors_from_dict(self, tensor_dict):
tensor_key_dict = {
TensorKey(k, self.uuid, self.round_number, False, ('model',)):
v for k, v in tensor_dict.items()
}
self.tensor_db.cache_tensor(tensor_key_dict)
self.logger.debug(f'This is the initial tensor_db: {self.tensor_db}')
def _save_model(self, round_number, file_path):
og_tensor_dict, _ = utils.deconstruct_model_proto(
self.model, compression_pipeline=self.compression_pipeline)
tensor_keys = [
TensorKey(
k, self.uuid, round_number, False, ('model',)
) for k, v in og_tensor_dict.items()
]
tensor_dict = {}
for tk in tensor_keys:
tk_name, _, _, _, _ = tk
tensor_dict[tk_name] = self.tensor_db.get_tensor_from_cache(tk)
if tensor_dict[tk_name] is None:
self.logger.info(f'Cannot save model for round {round_number}. Continuing...')
return
if file_path == self.best_state_path:
self.best_tensor_dict = tensor_dict
if file_path == self.last_state_path:
self.last_tensor_dict = tensor_dict
self.model = utils.construct_model_proto(
tensor_dict, round_number, self.compression_pipeline)
utils.dump_proto(self.model, file_path)
def valid_collaborator_cn_and_id(self, cert_common_name,
collaborator_common_name):
if self.single_col_cert_common_name == '':
return (cert_common_name == collaborator_common_name
and collaborator_common_name in self.authorized_cols)
else:
return (cert_common_name == self.single_col_cert_common_name
and collaborator_common_name in self.authorized_cols)
def all_quit_jobs_sent(self):
return set(self.quit_job_sent_to) == set(self.authorized_cols)
@staticmethod
def _get_sleep_time():
return 10
def _time_to_quit(self):
if self.round_number >= self.rounds_to_train:
return True
return False
def get_tasks(self, collaborator_name):
self.logger.debug(
f'Aggregator GetTasks function reached from collaborator {collaborator_name}...'
)
if self._time_to_quit():
self.logger.info(f'Sending signal to collaborator {collaborator_name} to shutdown...')
self.quit_job_sent_to.append(collaborator_name)
tasks = None
sleep_time = 0
time_to_quit = True
return tasks, self.round_number, sleep_time, time_to_quit
time_to_quit = False
tasks = self.assigner.get_tasks_for_collaborator(
collaborator_name,
self.round_number)
if len(tasks) == 0:
tasks = None
sleep_time = self._get_sleep_time()
return tasks, self.round_number, sleep_time, time_to_quit
tasks = [
t for t in tasks if not self._collaborator_task_completed(
collaborator_name, t, self.round_number)
]
if len(tasks) == 0:
tasks = None
sleep_time = self._get_sleep_time()
return tasks, self.round_number, sleep_time, time_to_quit
self.logger.info(
f'Sending tasks to collaborator {collaborator_name} for round {self.round_number}'
)
sleep_time = 0
return tasks, self.round_number, sleep_time, time_to_quit
|
Apache License 2.0
|
thehappydinoa/ashssdk
|
lambda/awscli/argprocess.py
|
unpack_cli_arg
|
python
|
def unpack_cli_arg(cli_argument, value):
return _unpack_cli_arg(cli_argument.argument_model, value,
cli_argument.cli_name)
|
Parses and unpacks the encoded string command line parameter
and returns native Python data structures that can be passed
to the Operation.
:type cli_argument: :class:`awscli.arguments.BaseCLIArgument`
:param cli_argument: The CLI argument object.
:param value: The value of the parameter. This can be a number of
different python types (str, list, etc). This is the value as
it's specified on the command line.
:return: The "unpacked" argument than can be sent to the `Operation`
object in python.
|
https://github.com/thehappydinoa/ashssdk/blob/d251a08ba6c35d81cf41b3267db666b08e875515/lambda/awscli/argprocess.py#L149-L166
|
import os
import logging
from awscli.compat import six
from botocore.compat import OrderedDict, json
from awscli import SCALAR_TYPES, COMPLEX_TYPES
from awscli.paramfile import get_paramfile, ResourceLoadingError
from awscli.paramfile import PARAMFILE_DISABLED
from awscli import shorthand
from awscli.utils import find_service_and_method_in_event_name
from botocore.utils import is_json_value_header
LOG = logging.getLogger('awscli.argprocess')
class ParamError(Exception):
def __init__(self, cli_name, message):
full_message = ("Error parsing parameter '%s': %s" %
(cli_name, message))
super(ParamError, self).__init__(full_message)
self.cli_name = cli_name
self.message = message
class ParamSyntaxError(Exception):
pass
class ParamUnknownKeyError(Exception):
def __init__(self, key, valid_keys):
valid_keys = ', '.join(valid_keys)
full_message = (
"Unknown key '%s', valid choices "
"are: %s" % (key, valid_keys))
super(ParamUnknownKeyError, self).__init__(full_message)
class TooComplexError(Exception):
pass
def unpack_argument(session, service_name, operation_name, cli_argument, value):
param_name = getattr(cli_argument, 'name', 'anonymous')
value_override = session.emit_first_non_none_response(
'load-cli-arg.%s.%s.%s' % (service_name,
operation_name,
param_name),
param=cli_argument, value=value, service_name=service_name,
operation_name=operation_name)
if value_override is not None:
value = value_override
return value
def uri_param(event_name, param, value, **kwargs):
cli_argument = param
qualified_param_name = '.'.join(event_name.split('.')[1:])
if qualified_param_name in PARAMFILE_DISABLED or getattr(cli_argument, 'no_paramfile', None):
return
else:
return _check_for_uri_param(cli_argument, value)
def _check_for_uri_param(param, value):
if isinstance(value, list) and len(value) == 1:
value = value[0]
try:
return get_paramfile(value)
except ResourceLoadingError as e:
raise ParamError(param.cli_name, six.text_type(e))
def detect_shape_structure(param):
stack = []
return _detect_shape_structure(param, stack)
def _detect_shape_structure(param, stack):
if param.name in stack:
return 'recursive'
else:
stack.append(param.name)
try:
if param.type_name in SCALAR_TYPES:
return 'scalar'
elif param.type_name == 'structure':
sub_types = [_detect_shape_structure(p, stack)
for p in param.members.values()]
if len(sub_types) == 1 and all(p == 'scalar' for p in sub_types):
return 'structure(scalar)'
elif len(sub_types) > 1 and all(p == 'scalar' for p in sub_types):
return 'structure(scalars)'
else:
return 'structure(%s)' % ', '.join(sorted(set(sub_types)))
elif param.type_name == 'list':
return 'list-%s' % _detect_shape_structure(param.member, stack)
elif param.type_name == 'map':
if param.value.type_name in SCALAR_TYPES:
return 'map-scalar'
else:
return 'map-%s' % _detect_shape_structure(param.value, stack)
finally:
stack.pop()
|
MIT License
|
ai4finance-llc/neofinrl
|
stable_baselines3/common/distributions.py
|
StateDependentNoiseDistribution.proba_distribution_net
|
python
|
def proba_distribution_net(
self, latent_dim: int, log_std_init: float = -2.0, latent_sde_dim: Optional[int] = None
) -> Tuple[nn.Module, nn.Parameter]:
mean_actions_net = nn.Linear(latent_dim, self.action_dim)
self.latent_sde_dim = latent_dim if latent_sde_dim is None else latent_sde_dim
log_std = th.ones(self.latent_sde_dim, self.action_dim) if self.full_std else th.ones(self.latent_sde_dim, 1)
log_std = nn.Parameter(log_std * log_std_init, requires_grad=True)
self.sample_weights(log_std)
return mean_actions_net, log_std
|
Create the layers and parameter that represent the distribution:
one output will be the deterministic action, the other parameter will be the
standard deviation of the distribution that control the weights of the noise matrix.
:param latent_dim: Dimension of the last layer of the policy (before the action layer)
:param log_std_init: Initial value for the log standard deviation
:param latent_sde_dim: Dimension of the last layer of the features extractor
for gSDE. By default, it is shared with the policy network.
:return:
|
https://github.com/ai4finance-llc/neofinrl/blob/51338dbb0ec86f74e4fc6cce90bc385a4639de79/stable_baselines3/common/distributions.py#L494-L519
|
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple, Union
import gym
import torch as th
from gym import spaces
from torch import nn
from torch.distributions import Bernoulli, Categorical, Normal
from stable_baselines3.common.preprocessing import get_action_dim
class Distribution(ABC):
def __init__(self):
super(Distribution, self).__init__()
self.distribution = None
@abstractmethod
def proba_distribution_net(self, *args, **kwargs) -> Union[nn.Module, Tuple[nn.Module, nn.Parameter]]:
@abstractmethod
def proba_distribution(self, *args, **kwargs) -> "Distribution":
@abstractmethod
def log_prob(self, x: th.Tensor) -> th.Tensor:
@abstractmethod
def entropy(self) -> Optional[th.Tensor]:
@abstractmethod
def sample(self) -> th.Tensor:
@abstractmethod
def mode(self) -> th.Tensor:
def get_actions(self, deterministic: bool = False) -> th.Tensor:
if deterministic:
return self.mode()
return self.sample()
@abstractmethod
def actions_from_params(self, *args, **kwargs) -> th.Tensor:
@abstractmethod
def log_prob_from_params(self, *args, **kwargs) -> Tuple[th.Tensor, th.Tensor]:
def sum_independent_dims(tensor: th.Tensor) -> th.Tensor:
if len(tensor.shape) > 1:
tensor = tensor.sum(dim=1)
else:
tensor = tensor.sum()
return tensor
class DiagGaussianDistribution(Distribution):
def __init__(self, action_dim: int):
super(DiagGaussianDistribution, self).__init__()
self.action_dim = action_dim
self.mean_actions = None
self.log_std = None
def proba_distribution_net(self, latent_dim: int, log_std_init: float = 0.0) -> Tuple[nn.Module, nn.Parameter]:
mean_actions = nn.Linear(latent_dim, self.action_dim)
log_std = nn.Parameter(th.ones(self.action_dim) * log_std_init, requires_grad=True)
return mean_actions, log_std
def proba_distribution(self, mean_actions: th.Tensor, log_std: th.Tensor) -> "DiagGaussianDistribution":
action_std = th.ones_like(mean_actions) * log_std.exp()
self.distribution = Normal(mean_actions, action_std)
return self
def log_prob(self, actions: th.Tensor) -> th.Tensor:
log_prob = self.distribution.log_prob(actions)
return sum_independent_dims(log_prob)
def entropy(self) -> th.Tensor:
return sum_independent_dims(self.distribution.entropy())
def sample(self) -> th.Tensor:
return self.distribution.rsample()
def mode(self) -> th.Tensor:
return self.distribution.mean
def actions_from_params(self, mean_actions: th.Tensor, log_std: th.Tensor, deterministic: bool = False) -> th.Tensor:
self.proba_distribution(mean_actions, log_std)
return self.get_actions(deterministic=deterministic)
def log_prob_from_params(self, mean_actions: th.Tensor, log_std: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
actions = self.actions_from_params(mean_actions, log_std)
log_prob = self.log_prob(actions)
return actions, log_prob
class SquashedDiagGaussianDistribution(DiagGaussianDistribution):
def __init__(self, action_dim: int, epsilon: float = 1e-6):
super(SquashedDiagGaussianDistribution, self).__init__(action_dim)
self.epsilon = epsilon
self.gaussian_actions = None
def proba_distribution(self, mean_actions: th.Tensor, log_std: th.Tensor) -> "SquashedDiagGaussianDistribution":
super(SquashedDiagGaussianDistribution, self).proba_distribution(mean_actions, log_std)
return self
def log_prob(self, actions: th.Tensor, gaussian_actions: Optional[th.Tensor] = None) -> th.Tensor:
if gaussian_actions is None:
gaussian_actions = TanhBijector.inverse(actions)
log_prob = super(SquashedDiagGaussianDistribution, self).log_prob(gaussian_actions)
log_prob -= th.sum(th.log(1 - actions ** 2 + self.epsilon), dim=1)
return log_prob
def entropy(self) -> Optional[th.Tensor]:
return None
def sample(self) -> th.Tensor:
self.gaussian_actions = super().sample()
return th.tanh(self.gaussian_actions)
def mode(self) -> th.Tensor:
self.gaussian_actions = super().mode()
return th.tanh(self.gaussian_actions)
def log_prob_from_params(self, mean_actions: th.Tensor, log_std: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
action = self.actions_from_params(mean_actions, log_std)
log_prob = self.log_prob(action, self.gaussian_actions)
return action, log_prob
class CategoricalDistribution(Distribution):
def __init__(self, action_dim: int):
super(CategoricalDistribution, self).__init__()
self.action_dim = action_dim
def proba_distribution_net(self, latent_dim: int) -> nn.Module:
action_logits = nn.Linear(latent_dim, self.action_dim)
return action_logits
def proba_distribution(self, action_logits: th.Tensor) -> "CategoricalDistribution":
self.distribution = Categorical(logits=action_logits)
return self
def log_prob(self, actions: th.Tensor) -> th.Tensor:
return self.distribution.log_prob(actions)
def entropy(self) -> th.Tensor:
return self.distribution.entropy()
def sample(self) -> th.Tensor:
return self.distribution.sample()
def mode(self) -> th.Tensor:
return th.argmax(self.distribution.probs, dim=1)
def actions_from_params(self, action_logits: th.Tensor, deterministic: bool = False) -> th.Tensor:
self.proba_distribution(action_logits)
return self.get_actions(deterministic=deterministic)
def log_prob_from_params(self, action_logits: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
actions = self.actions_from_params(action_logits)
log_prob = self.log_prob(actions)
return actions, log_prob
class MultiCategoricalDistribution(Distribution):
def __init__(self, action_dims: List[int]):
super(MultiCategoricalDistribution, self).__init__()
self.action_dims = action_dims
def proba_distribution_net(self, latent_dim: int) -> nn.Module:
action_logits = nn.Linear(latent_dim, sum(self.action_dims))
return action_logits
def proba_distribution(self, action_logits: th.Tensor) -> "MultiCategoricalDistribution":
self.distribution = [Categorical(logits=split) for split in th.split(action_logits, tuple(self.action_dims), dim=1)]
return self
def log_prob(self, actions: th.Tensor) -> th.Tensor:
return th.stack(
[dist.log_prob(action) for dist, action in zip(self.distribution, th.unbind(actions, dim=1))], dim=1
).sum(dim=1)
def entropy(self) -> th.Tensor:
return th.stack([dist.entropy() for dist in self.distribution], dim=1).sum(dim=1)
def sample(self) -> th.Tensor:
return th.stack([dist.sample() for dist in self.distribution], dim=1)
def mode(self) -> th.Tensor:
return th.stack([th.argmax(dist.probs, dim=1) for dist in self.distribution], dim=1)
def actions_from_params(self, action_logits: th.Tensor, deterministic: bool = False) -> th.Tensor:
self.proba_distribution(action_logits)
return self.get_actions(deterministic=deterministic)
def log_prob_from_params(self, action_logits: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
actions = self.actions_from_params(action_logits)
log_prob = self.log_prob(actions)
return actions, log_prob
class BernoulliDistribution(Distribution):
def __init__(self, action_dims: int):
super(BernoulliDistribution, self).__init__()
self.action_dims = action_dims
def proba_distribution_net(self, latent_dim: int) -> nn.Module:
action_logits = nn.Linear(latent_dim, self.action_dims)
return action_logits
def proba_distribution(self, action_logits: th.Tensor) -> "BernoulliDistribution":
self.distribution = Bernoulli(logits=action_logits)
return self
def log_prob(self, actions: th.Tensor) -> th.Tensor:
return self.distribution.log_prob(actions).sum(dim=1)
def entropy(self) -> th.Tensor:
return self.distribution.entropy().sum(dim=1)
def sample(self) -> th.Tensor:
return self.distribution.sample()
def mode(self) -> th.Tensor:
return th.round(self.distribution.probs)
def actions_from_params(self, action_logits: th.Tensor, deterministic: bool = False) -> th.Tensor:
self.proba_distribution(action_logits)
return self.get_actions(deterministic=deterministic)
def log_prob_from_params(self, action_logits: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
actions = self.actions_from_params(action_logits)
log_prob = self.log_prob(actions)
return actions, log_prob
class StateDependentNoiseDistribution(Distribution):
def __init__(
self,
action_dim: int,
full_std: bool = True,
use_expln: bool = False,
squash_output: bool = False,
learn_features: bool = False,
epsilon: float = 1e-6,
):
super(StateDependentNoiseDistribution, self).__init__()
self.action_dim = action_dim
self.latent_sde_dim = None
self.mean_actions = None
self.log_std = None
self.weights_dist = None
self.exploration_mat = None
self.exploration_matrices = None
self._latent_sde = None
self.use_expln = use_expln
self.full_std = full_std
self.epsilon = epsilon
self.learn_features = learn_features
if squash_output:
self.bijector = TanhBijector(epsilon)
else:
self.bijector = None
def get_std(self, log_std: th.Tensor) -> th.Tensor:
if self.use_expln:
below_threshold = th.exp(log_std) * (log_std <= 0)
safe_log_std = log_std * (log_std > 0) + self.epsilon
above_threshold = (th.log1p(safe_log_std) + 1.0) * (log_std > 0)
std = below_threshold + above_threshold
else:
std = th.exp(log_std)
if self.full_std:
return std
return th.ones(self.latent_sde_dim, self.action_dim).to(log_std.device) * std
def sample_weights(self, log_std: th.Tensor, batch_size: int = 1) -> None:
std = self.get_std(log_std)
self.weights_dist = Normal(th.zeros_like(std), std)
self.exploration_mat = self.weights_dist.rsample()
self.exploration_matrices = self.weights_dist.rsample((batch_size,))
|
MIT License
|
onshape-public/onshape-clients
|
python/onshape_client/oas/models/info.py
|
Info.openapi_types
|
python
|
def openapi_types():
return {
"contact": (contact.Contact,),
"description": (str,),
"extensions": (
{str: (bool, date, datetime, dict, float, int, list, str,)},
),
"license": (license.License,),
"terms_of_service": (str,),
"title": (str,),
"version": (str,),
}
|
This must be a class method so a model may have properties that are
of type self, this ensures that we don't create a cyclic import
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
|
https://github.com/onshape-public/onshape-clients/blob/20843a00c628e516e7219e17a23ec4ef2bf9f16f/python/onshape_client/oas/models/info.py#L74-L93
|
from __future__ import absolute_import
import re
import sys
import six
from onshape_client.oas.model_utils import (
ModelComposed,
ModelNormal,
ModelSimple,
date,
datetime,
file_type,
int,
none_type,
str,
validate_get_composed_info,
)
try:
from onshape_client.oas.models import contact
except ImportError:
contact = sys.modules["onshape_client.oas.models.contact"]
try:
from onshape_client.oas.models import license
except ImportError:
license = sys.modules["onshape_client.oas.models.license"]
class Info(ModelNormal):
allowed_values = {}
validations = {}
additional_properties_type = None
@staticmethod
|
MIT License
|
qiskit/qiskit-ibmq-provider
|
qiskit/providers/ibmq/job/ibmqjob.py
|
IBMQJob.name
|
python
|
def name(self) -> Optional[str]:
return self._name
|
Return the name assigned to this job.
Returns:
Job name or ``None`` if no name was assigned to this job.
|
https://github.com/qiskit/qiskit-ibmq-provider/blob/5e89e43eb7d97427946f3462cc6d814860c4a291/qiskit/providers/ibmq/job/ibmqjob.py#L606-L612
|
import logging
from typing import Dict, Optional, Tuple, Any, List, Callable, Union
import warnings
from datetime import datetime
from concurrent import futures
from threading import Event
from queue import Empty
import dateutil.parser
from qiskit.providers.job import JobV1 as Job
from qiskit.providers.jobstatus import JOB_FINAL_STATES, JobStatus
from qiskit.providers.models import BackendProperties
from qiskit.qobj import QasmQobj, PulseQobj
from qiskit.result import Result
from qiskit.providers.ibmq import ibmqbackend
from qiskit.assembler.disassemble import disassemble
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.pulse import Schedule
from ..apiconstants import ApiJobStatus, ApiJobKind
from ..api.clients import AccountClient
from ..api.exceptions import ApiError, UserTimeoutExceededError
from ..utils.utils import RefreshQueue, validate_job_tags, api_status_to_job_status
from ..utils.qobj_utils import dict_to_qobj
from ..utils.json_decoder import decode_backend_properties, decode_result
from ..utils.converters import utc_to_local, utc_to_local_all
from .exceptions import (IBMQJobApiError, IBMQJobFailureError,
IBMQJobTimeoutError, IBMQJobInvalidStateError)
from .queueinfo import QueueInfo
from .utils import build_error_report, api_to_job_error, get_cancel_status
logger = logging.getLogger(__name__)
class IBMQJob(Job):
_data = {}
_executor = futures.ThreadPoolExecutor()
def __init__(
self,
backend: 'ibmqbackend.IBMQBackend',
api_client: AccountClient,
job_id: str,
creation_date: str,
status: str,
kind: Optional[str] = None,
name: Optional[str] = None,
time_per_step: Optional[dict] = None,
result: Optional[dict] = None,
qobj: Optional[Union[dict, QasmQobj, PulseQobj]] = None,
error: Optional[dict] = None,
tags: Optional[List[str]] = None,
run_mode: Optional[str] = None,
share_level: Optional[str] = None,
client_info: Optional[Dict[str, str]] = None,
experiment_id: Optional[str] = None,
**kwargs: Any
) -> None:
self._backend = backend
self._api_client = api_client
self._job_id = job_id
self._creation_date = dateutil.parser.isoparse(creation_date)
self._api_status = status
self._kind = ApiJobKind(kind) if kind else None
self._name = name
self._time_per_step = time_per_step
if isinstance(qobj, dict):
qobj = dict_to_qobj(qobj)
self._qobj = qobj
self._error = error
self._tags = tags or []
self._run_mode = run_mode
self._status, self._queue_info = self._get_status_position(status, kwargs.pop('info_queue', None))
self._use_object_storage = (self._kind == ApiJobKind.QOBJECT_STORAGE)
self._share_level = share_level
self._set_client_version(client_info)
self._experiment_id = experiment_id
self._set_result(result)
self._data = {}
for key, value in kwargs.items():
self._data[key + '_'] = value
super().__init__(self.backend(), self.job_id())
self._cancelled = False
self._job_error_msg = None
self._refreshed = False
def qobj(self) -> Optional[Union[QasmQobj, PulseQobj]]:
warnings.warn("The ``IBMQJob.qobj()`` method is deprecated and will "
"be removed in a future release. You can now pass circuits "
"to ``IBMQBackend.run()`` and use ``IBMQJob.circuits()``, "
"``IBMQJob.backend_options()``, and ``IBMQJob.header()`` to retrieve "
"circuits, run configuration, and Qobj header, respectively.",
DeprecationWarning, stacklevel=2)
return self._get_qobj()
def properties(self) -> Optional[BackendProperties]:
with api_to_job_error():
properties = self._api_client.job_properties(job_id=self.job_id())
if not properties:
return None
decode_backend_properties(properties)
properties = utc_to_local_all(properties)
return BackendProperties.from_dict(properties)
def result(
self,
timeout: Optional[float] = None,
wait: float = 5,
partial: bool = False,
refresh: bool = False
) -> Result:
if not self._wait_for_completion(timeout=timeout, wait=wait,
required_status=(JobStatus.DONE,)):
if self._status is JobStatus.CANCELLED:
raise IBMQJobInvalidStateError('Unable to retrieve result for job {}. '
'Job was cancelled.'.format(self.job_id()))
if partial:
self._retrieve_result(refresh=refresh)
if not partial or not self._result or not self._result.results:
error_message = self.error_message()
if '\n' in error_message:
error_message = ". Use the error_message() method to get more details"
else:
error_message = ": " + error_message
raise IBMQJobFailureError(
'Unable to retrieve result for job {}. Job has failed{}'.format(
self.job_id(), error_message))
else:
self._retrieve_result(refresh=refresh)
return self._result
def cancel(self) -> bool:
try:
response = self._api_client.job_cancel(self.job_id())
self._cancelled = get_cancel_status(response)
logger.debug('Job %s cancel status is "%s". Response data: %s.',
self.job_id(), self._cancelled, response)
return self._cancelled
except ApiError as error:
self._cancelled = False
raise IBMQJobApiError('Unexpected error when cancelling job {}: {}'
.format(self.job_id(), str(error))) from error
def update_name(self, name: str) -> str:
if not isinstance(name, str):
raise IBMQJobInvalidStateError(
'"{}" of type "{}" is not a valid job name. '
'The job name needs to be a string.'.format(name, type(name)))
with api_to_job_error():
response = self._api_client.job_update_attribute(
job_id=self.job_id(), attr_name='name', attr_value=name)
updated_name = response.get('name', None)
if (updated_name is None) or (name != updated_name):
raise IBMQJobApiError('An unexpected error occurred when updating the '
'name for job {}. The name was not updated for '
'the job.'.format(self.job_id()))
self._name = updated_name
return self._name
def update_tags(
self,
replacement_tags: Optional[List[str]] = None,
additional_tags: Optional[List[str]] = None,
removal_tags: Optional[List[str]] = None
) -> List[str]:
if (replacement_tags is None) and (additional_tags is None) and (removal_tags is None):
raise IBMQJobInvalidStateError(
'The tags cannot be updated since none of the parameters are specified.')
tags_to_update = self._get_tags_to_update(replacement_tags=replacement_tags,
additional_tags=additional_tags,
removal_tags=removal_tags)
with api_to_job_error():
response = self._api_client.job_update_attribute(
job_id=self.job_id(), attr_name='tags', attr_value=tags_to_update)
updated_tags = response.get('tags', None)
if (updated_tags is None) or (set(updated_tags) != set(tags_to_update)):
raise IBMQJobApiError('An unexpected error occurred when updating the '
'tags for job {}. The tags were not updated for '
'the job.'.format(self.job_id()))
self._tags = updated_tags
return self._tags
def _get_tags_to_update(self,
replacement_tags: Optional[List[str]],
additional_tags: Optional[List[str]],
removal_tags: Optional[List[str]]) -> List[str]:
ibmq_jobset_prefix = 'ibmq_jobset_'
tags_to_update = set(self._tags or [])
if isinstance(replacement_tags, list):
validate_job_tags(replacement_tags, IBMQJobInvalidStateError)
tags_to_update = set(replacement_tags)
tags_to_update.update(
filter(lambda old_tag: old_tag.startswith(ibmq_jobset_prefix), self._tags))
if additional_tags:
validate_job_tags(additional_tags, IBMQJobInvalidStateError)
tags_to_update.update(additional_tags)
if removal_tags:
validate_job_tags(removal_tags, IBMQJobInvalidStateError)
for tag_to_remove in removal_tags:
if tag_to_remove.startswith(ibmq_jobset_prefix):
logger.warning('The tag "%s" for job %s will not be removed, because '
'it is used internally by the ibmq-provider.',
tag_to_remove, self.job_id())
continue
if tag_to_remove in tags_to_update:
tags_to_update.remove(tag_to_remove)
else:
logger.warning('The tag "%s" for job %s will not be removed, because it was '
'not found in the job tags to update %s',
tag_to_remove, self.job_id(), tags_to_update)
return list(tags_to_update)
def status(self) -> JobStatus:
if self._status in JOB_FINAL_STATES:
return self._status
with api_to_job_error():
api_response = self._api_client.job_status(self.job_id())
self._api_status = api_response['status']
self._status, self._queue_info = self._get_status_position(
self._api_status, api_response.get('info_queue', None))
if self._status in JOB_FINAL_STATES:
self.refresh()
return self._status
def error_message(self) -> Optional[str]:
if not self._wait_for_completion(required_status=(JobStatus.ERROR,)):
return None
if not self._job_error_msg:
self._retrieve_result()
if not self._job_error_msg:
if not self._error:
self.refresh()
if self._error:
self._job_error_msg = self._format_message_from_error(self._error)
elif self._api_status.startswith('ERROR'):
self._job_error_msg = self._api_status
else:
self._job_error_msg = "Unknown error."
return self._job_error_msg
def queue_position(self, refresh: bool = False) -> Optional[int]:
if refresh:
self.status()
if self._queue_info:
return self._queue_info.position
return None
def queue_info(self) -> Optional[QueueInfo]:
self.status()
if self._queue_info and any(
value is not None for attr, value in self._queue_info.__dict__.items()
if not attr.startswith('_') and attr != 'job_id'):
return self._queue_info
return None
def creation_date(self) -> datetime:
creation_date_local_dt = utc_to_local(self._creation_date)
return creation_date_local_dt
def job_id(self) -> str:
return self._job_id
|
Apache License 2.0
|
cigihub/opencanada
|
analytics/utils.py
|
get_analytics
|
python
|
def get_analytics(page):
analytics, _ = Analytics.objects.get_or_create(page=page)
return analytics
|
Ensure the analytics row exists for a given page
|
https://github.com/cigihub/opencanada/blob/6334ff412addc0562ac247080194e5d182e8e924/analytics/utils.py#L126-L131
|
from __future__ import absolute_import, division, unicode_literals
import httplib2
import os
import six
from analytics.models import Analytics
from apiclient.discovery import build
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from oauth2client.service_account import ServiceAccountCredentials
def get_creds_path():
message = 'Setting ANALYTICS_CREDS_PATH must be defined, exist and be a directory.'
try:
path = getattr(settings, 'ANALYTICS_CREDS_PATH')
except AttributeError:
raise ImproperlyConfigured(message)
if not os.path.isdir(path):
raise ImproperlyConfigured(message)
return path
def get_service_account_email():
message = 'Setting ANALYTICS_SERVICE_ACCOUNT_EMAIL must be defined and non empty'
try:
email = getattr(settings, 'ANALYTICS_SERVICE_ACCOUNT_EMAIL')
except AttributeError:
raise ImproperlyConfigured(message)
if email is None or email == '':
raise ImproperlyConfigured(message)
return email
def get_key_file_location():
creds_path = get_creds_path()
key_file_location = os.path.join(creds_path, 'open-canada-analytics.p12')
if not os.path.isfile(key_file_location):
raise ImproperlyConfigured(
'{} must be a file which contains your api key.'.format(key_file_location)
)
return key_file_location
def get_service(api_name, api_version, scopes, key_file_location, service_account_email):
credentials = ServiceAccountCredentials.from_p12_keyfile(
service_account_email,
key_file_location,
scopes=scopes
)
http = credentials.authorize(httplib2.Http())
service = build(api_name, api_version, http=http)
return service
def get_first_profile_id(service):
accounts = service.management().accounts().list().execute()
if not accounts.get('items'):
return None
account = accounts.get('items')[0].get('id')
properties = service.management().webproperties().list(
accountId=account
).execute()
if not properties.get('items'):
return None
property = properties.get('items')[0].get('id')
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property
).execute()
if not profiles.get('items'):
return None
return profiles.get('items')[0].get('id')
def reset_analytics(pages):
for url, page in six.iteritems(pages):
analytics = get_analytics(page)
analytics.last_period_views = 0
analytics.save()
|
MIT License
|
varianapis/pyesapi
|
pyesapi/Lot.py
|
Lot.Select
|
python
|
def Select(self, fxn):
if callable(fxn):
return Lot(list(filter(fxn, self.collection)))
else:
raise TypeError('fxn is not callable')
|
returns a new lot of objects where fxn(object) == True
|
https://github.com/varianapis/pyesapi/blob/c7b1d2986cab9387e85dbb4331a44e5b743b86ea/pyesapi/Lot.py#L14-L19
|
class Lot:
def __init__(self, some_collectable):
self.collection = some_collectable
def FirstOrDefault(self, fxn):
result = list(filter(fxn, self.collection))
if len(result) == 0:
return None
else:
return result[0]
|
MIT License
|
ufosc/swampymud
|
swampymud/inventory.py
|
ItemStack.__init__
|
python
|
def __init__(self, item_type, amount, data=None):
if data == {}:
data = None
self._type = item_type
self._amount = amount
self._data = data
|
create a new ItemStack with Item class [item_type], integer [amount]
Optionally, you can provide [data], where [data] is compatible with the .load
method provided by [item_type]
|
https://github.com/ufosc/swampymud/blob/2e28f9db1f0f4e1c4aafccdf7f58bf2a22b82366/swampymud/inventory.py#L31-L41
|
from collections import defaultdict
from swampymud.util import FindParams
def matching_subset(main, sub):
main_keys = set(main)
sub_keys = set(sub)
if not sub_keys.issubset(main_keys):
return False
for key in sub_keys:
if main[key] != sub[key]:
return False
return True
class ItemStack:
|
MIT License
|
xilinx/pyxir
|
python/pyxir/graph/ops/l2_convolution.py
|
upsampling2d_layout_transform
|
python
|
def upsampling2d_layout_transform(X: XLayer, target_layout: str) -> None:
layout = X.attrs["data_layout"]
axes_transpose = [layout.index(e) for e in target_layout]
X.attrs["data_layout"] = target_layout
X.shapes[:] = TensorShape([X.shapes[i] for i in axes_transpose])
|
Transform layout of provided Upsampling2D XLayer to target layout
|
https://github.com/xilinx/pyxir/blob/bef661d6d77adcdbd2cf4163f2cf3a1d31d40406/python/pyxir/graph/ops/l2_convolution.py#L867-L874
|
import math
import logging
import warnings
import numpy as np
from typing import Dict, List, Any
from pyxir.shapes import TensorShape
from ..layer.xlayer import defaultXLayer, XLayer, BatchData, ConvData, ScaleData
from ..layer.xlayer_factory import xop_register_factory, xop_register
from ..xop_registry import (
xop_register_op_layout_transform,
xop_register_op_transpose_transform,
)
logger = logging.getLogger("pyxir")
@xop_register("Flatten")
def batch_flatten(
attrs: Dict[str, Any], in_xlayers: List[XLayer]
) -> Dict[str, List[int]]:
assert len(in_xlayers) == 1, "Batch Flatten expects one input layer"
flattened_shape = TensorShape(
[list(in_xlayers[0].shapes)[0]] + [int(np.prod(list(in_xlayers[0].shapes)[1:]))]
)
return {"shape": flattened_shape}
@xop_register_factory("BatchNorm")
def batch_norm(
op_name: str,
input_layer: XLayer,
mean_layer: XLayer,
variance_layer: XLayer,
gamma_layer: XLayer,
beta_layer: XLayer,
axis: int,
epsilon: float = 1e-5,
**kwargs
) -> XLayer:
bottoms = [input_layer.name]
attrs = kwargs
attrs.update(
{
"epsilon": epsilon,
"axis": axis,
}
)
mean, variance = mean_layer.data[0], variance_layer.data[0]
gamma, beta = gamma_layer.data[0], beta_layer.data[0]
assert mean.shape == variance.shape
bn_data = BatchData(mu=mean, sigma_square=variance, gamma=gamma, beta=beta)
X = XLayer()
X = X._replace(
name=op_name,
type=["BatchNorm"],
shapes=input_layer.shapes[:],
sizes=input_layer.sizes[:],
data=bn_data,
layer=[op_name],
tops=[],
bottoms=bottoms,
attrs=attrs,
targets=[],
)
return X
@xop_register_op_transpose_transform("BatchNorm")
def batchnorm_transpose_transform(X: XLayer, axes: List[int]) -> None:
new_shape = TensorShape([X.shapes[i] for i in axes])
X.shapes = new_shape
X.attrs["axis"] = axes.index(X.attrs["axis"])
@xop_register_factory("Convolution")
def conv2d(
op_name: str,
input_layer: XLayer,
weights_layer: XLayer,
kernel_size: List[int],
strides: List[int] = [1, 1],
padding_hw: List[int] = [0, 0, 0, 0],
dilation: List[int] = [1, 1],
groups: int = 1,
channels: int = None,
data_layout: str = "NCHW",
kernel_layout: str = "OIHW",
target_kernel_layout: str = "OIHW",
**kwargs
) -> XLayer:
assert "Constant" in weights_layer.type
assert len(kernel_size) == 2
assert len(dilation) == 2
assert len(strides) == 2
assert len(padding_hw) in [2, 4]
layout_idx = tuple([data_layout.index(e) for e in "NCHW"])
layout_idx_transpose = tuple(["NCHW".index(e) for e in data_layout])
B_idx, C_idx, H_idx, W_idx = layout_idx
bottoms = [input_layer.name]
logger.debug("-- Conv2D Kernel layout: {}".format(kernel_layout))
logger.debug("-- Conv2D W shape: {}".format(weights_layer.data[0].shape))
if len(kernel_layout) != 4 or sorted(kernel_layout) != ["H", "I", "O", "W"]:
raise NotImplementedError(
"Unsupported kernel layout: {} for"
" convolution: {}, should be a permutation"
" of `OIHW`".format(kernel_layout, op_name)
)
transpose_axes = tuple([kernel_layout.index(e) for e in target_kernel_layout])
W = np.transpose(weights_layer.data[0], transpose_axes)
kernel_layout_idx = tuple([target_kernel_layout.index(e) for e in "OIHW"])
kO_idx, kI_idx, kH_idx, kW_idx = kernel_layout_idx
if len(padding_hw) == 4:
pad_ht, pad_hb, pad_wl, pad_wr = padding_hw
elif len(padding_hw) == 2:
pad_ht, pad_wl = padding_hw
pad_hb, pad_wr = padding_hw
else:
raise ValueError(
"'padding_hw' argument should be a list of length 2"
" but got: {}".format(len(padding_hw))
)
in_ch, out_ch = W.shape[kI_idx] * groups, W.shape[kO_idx]
logger.debug("-- in_ch: {}, out_ch: {}".format(in_ch, out_ch))
logger.debug("-- channels: {}".format(channels))
assert channels is None or out_ch == channels
channels = out_ch if channels is None else channels
B = np.zeros([out_ch], dtype=np.float32)
data = ConvData(W, B)
insize = [input_layer.shapes[H_idx], input_layer.shapes[W_idx]]
batches = input_layer.shapes[0]
logger.debug("-- in shape: {}".format(input_layer.shapes))
logger.debug("-- padding (t,b,l,r): {}".format((pad_ht, pad_hb, pad_wl, pad_wr)))
out_h = int(
(insize[0] + pad_ht + pad_hb - dilation[0] * (kernel_size[0] - 1) - 1)
/ strides[0]
+ 1
)
out_w = int(
(insize[1] + pad_wl + pad_wr - dilation[1] * (kernel_size[1] - 1) - 1)
/ strides[1]
+ 1
)
out_shape = TensorShape(
[[batches, out_ch, out_h, out_w][i] for i in layout_idx_transpose]
)
padding_hh = [pad_ht, pad_hb]
padding_ww = [pad_wl, pad_wr]
if data_layout == "NCHW":
granular_padding = [[0, 0], [0, 0], padding_hh, padding_ww]
else:
granular_padding = [[0, 0], padding_hh, padding_ww, [0, 0]]
logger.debug("-- out shape: {}".format(out_shape))
attrs = kwargs
attrs.update(
{
"padding": granular_padding,
"data_layout": data_layout,
"kernel_layout": target_kernel_layout,
"shape": out_shape.tolist(),
"kernel_size": kernel_size,
"strides": strides,
"groups": groups,
"dilation": dilation,
"channels": [in_ch, out_ch],
}
)
X = XLayer()
X = X._replace(
name=op_name,
type=["Convolution"],
shapes=out_shape,
sizes=out_shape.get_size(),
data=data,
layer=[op_name],
tops=[],
bottoms=bottoms,
attrs=attrs,
targets=[],
)
return X
@xop_register_op_layout_transform("Convolution")
def conv2d_layout_transform(X: XLayer, target_layout: str) -> None:
layout = X.attrs["data_layout"]
axes_transpose = [layout.index(e) for e in target_layout]
X.attrs["padding"] = [X.attrs["padding"][i] for i in axes_transpose]
X.attrs["data_layout"] = target_layout
X.shapes[:] = TensorShape([X.shapes[i] for i in axes_transpose])
@xop_register_factory("Conv2DTranspose")
def conv2d_transpose(
op_name: str,
input_layer: XLayer,
weights_layer: XLayer,
kernel_size: List[int],
strides: List[int] = [1, 1],
padding_hw: List[int] = [0, 0, 0, 0],
dilation: List[int] = [1, 1],
groups: int = 1,
channels: int = None,
data_layout: str = "NCHW",
kernel_layout: str = "OIHW",
target_kernel_layout: str = "OIHW",
**kwargs
) -> XLayer:
bottoms = [input_layer.name]
layout_idx = tuple([data_layout.index(e) for e in "NCHW"])
layout_idx_transpose = tuple(["NCHW".index(e) for e in data_layout])
B_idx, C_idx, H_idx, W_idx = layout_idx
logger.debug("-- Conv2DTranspose Kernel layout: {}".format(kernel_layout))
logger.debug("-- Conv2DTranspose W shape: {}".format(weights_layer.data[0].shape))
if len(kernel_layout) != 4 or sorted(kernel_layout) != ["H", "I", "O", "W"]:
raise NotImplementedError(
"Unsupported kernel layout: {} for"
" convolution: {}, should be a permutation"
" of `OIHW`".format(kernel_layout, op_name)
)
transpose_axes = tuple([kernel_layout.index(e) for e in target_kernel_layout])
W = np.transpose(weights_layer.data[0], transpose_axes)
kernel_layout_idx = tuple([target_kernel_layout.index(e) for e in "OIHW"])
kO_idx, kI_idx, kH_idx, kW_idx = kernel_layout_idx
assert len(padding_hw) in [2, 4]
if len(padding_hw) == 4:
pad_ht, pad_hb, pad_wl, pad_wr = padding_hw
elif len(padding_hw) == 2:
pad_ht, pad_wl = padding_hw
pad_hb, pad_wr = padding_hw
else:
raise ValueError(
"'padding_hw' argument should be a list of length 2"
" but got: {}".format(len(padding_hw))
)
in_ch, out_ch = W.shape[kI_idx] * groups, W.shape[kO_idx]
logger.debug("-- in_ch: {}, out_ch: {}".format(in_ch, out_ch))
logger.debug("-- channels: {}".format(channels))
assert channels is None or out_ch == channels
channels = out_ch if channels is None else channels
B = np.zeros([out_ch], dtype=np.float32)
data = ConvData(W, B)
insize = [input_layer.shapes[2], input_layer.shapes[3]]
batches = input_layer.shapes[0]
logger.debug("{} {}".format(input_layer.shapes, in_ch))
assert input_layer.shapes[C_idx] == in_ch
if (
(pad_ht + pad_hb) == (kernel_size[0] - strides[0])
and abs(pad_ht - pad_hb) <= 1
and (pad_wl + pad_wr) == (kernel_size[1] - strides[1])
and abs(pad_wl - pad_wr) <= 1
):
padding_type = "SAME"
elif pad_ht == 0 and pad_wl == 0:
padding_type = "VALID"
else:
raise NotImplementedError(
"Unsupported padding for Conv2DTranspose"
" Only Tensorflow padding 'SAME' and 'VALID'"
" are supported but got: {} which does not"
" translate to 'SAME' == [pad_ht + pad_hb = {}, pad_wl + pad_wr = {}] or 'VALID'"
" == [0, 0]".format(
(pad_ht, pad_hb, pad_wl, pad_wr),
(kernel_size[0] - strides[0]),
(kernel_size[1] - strides[1]),
)
)
if padding_type == "SAME":
out_h = insize[0] * strides[0]
out_w = insize[1] * strides[1]
elif padding_type == "VALID":
out_h = (insize[0] - 1) * strides[0] + kernel_size[0]
out_w = (insize[1] - 1) * strides[1] + kernel_size[1]
out_shape = TensorShape(
[[batches, out_ch, out_h, out_w][i] for i in layout_idx_transpose]
)
padding = [[0, 0], [0, 0], [pad_ht, pad_hb], [pad_wl, pad_wr]]
padding = [padding["NCHW".index(i)] for i in data_layout]
attrs = kwargs
attrs.update(
{
"padding": padding,
"data_layout": data_layout,
"kernel_layout": "OIHW",
"shape": out_shape.tolist(),
"kernel_size": kernel_size,
"strides": strides,
"groups": groups,
"dilation": dilation,
"channels": [in_ch, out_ch],
}
)
X = XLayer()
X = X._replace(
name=op_name,
type=["Conv2DTranspose"],
shapes=out_shape,
sizes=out_shape.get_size(),
data=data,
layer=[op_name],
tops=[],
bottoms=bottoms,
attrs=attrs,
targets=[],
)
return X
@xop_register_op_layout_transform("Conv2DTranspose")
def conv2d_transpose_layout_transform(X: XLayer, target_layout: str) -> None:
layout = X.attrs["data_layout"]
axes_transpose = [layout.index(e) for e in target_layout]
X.attrs["padding"] = [X.attrs["padding"][i] for i in axes_transpose]
X.attrs["data_layout"] = target_layout
X.shapes = TensorShape([X.shapes[i] for i in axes_transpose])
@xop_register_factory("GlobalPooling")
def global_pool2d(
op_name: str, input_layer: XLayer, pool_type: str, layout: str, **kwargs
) -> XLayer:
if pool_type not in ["Max", "Avg"]:
raise NotImplementedError(
"Invalid pooling type: {}, can either be"
" `Max` or `Avg`.".format(pool_type)
)
insize = [input_layer.shapes[2], input_layer.shapes[3]]
batches, channels = input_layer.shapes[0], input_layer.shapes[1]
strides = [1, 1]
padding = [0, 0]
pool_size = insize
out_h, out_w = 1, 1
attrs = kwargs
attrs.update(
{
"padding": [[0, 0], [0, 0], [0, 0], [0, 0]],
"insize": insize,
"outsize": [out_h, out_w],
"data_layout": layout,
"strides": strides,
"kernel_size": pool_size,
"pool_type": pool_type,
}
)
out_shape = TensorShape(
[batches, channels, out_h, out_w]
if layout == "NCHW"
else [batches, out_h, out_w, channels]
)
X = XLayer()
X = X._replace(
name=op_name,
type=["Pooling"],
shapes=out_shape,
sizes=out_shape.get_size(),
attrs=attrs,
layer=[op_name],
tops=[],
bottoms=[input_layer.name],
targets=[],
)
return X
@xop_register_factory("Pad")
def pad(
op_name: str, input_layer: XLayer, padding: List[int], pad_value: float, **kwargs
) -> XLayer:
if pad_value != 0:
raise NotImplementedError(
"Unsupported padding value: {}, only 0 is"
" supported for now.".format(pad_value)
)
if not len(input_layer.shapes) == 4:
raise NotImplementedError(
"Padding layer only supported after layer in"
" `NCHW` or `NHWC` format, but found layer"
" with {} dims".format(len(input_layer.shapes))
)
unpadded_dims = [[0, 0]] * len(input_layer.shapes[len(padding) :])
padding = unpadded_dims + [list(pad) for pad in padding]
shape = TensorShape([s + p[0] + p[1] for s, p in zip(input_layer.shapes, padding)])
logger.debug("-- Pad shape: {}".format(shape))
attrs = kwargs
attrs.update({"padding": padding})
X = XLayer()
X = X._replace(
name=op_name,
type=["Pad"],
shapes=shape,
sizes=shape.get_size(),
attrs=attrs,
layer=[op_name],
tops=[],
bottoms=[input_layer.name],
targets=[],
)
return X
@xop_register_op_transpose_transform("Pad")
def padding_transpose_transform(X: XLayer, axes: List[int]) -> None:
new_shape = [X.shapes[i] for i in axes]
X.shapes = TensorShape(new_shape)
new_padding = [X.attrs["padding"][i] for i in axes]
X.attrs["padding"] = new_padding
@xop_register_factory("Pooling")
def pool2d(
op_name: str,
input_layer: XLayer,
pool_type: str,
pool_size: List[int],
strides: List[int] = [1, 1],
padding: List[int] = [0, 0, 0, 0],
layout: str = "NCHW",
ceil_mode: bool = False,
count_include_pad: bool = False,
**kwargs
) -> XLayer:
if layout not in ["NCHW", "NHWC"]:
raise ValueError(
"Unsupported layout: {}, supported layouts are"
"NCHW and NHWC".format(layout)
)
if pool_type not in ["Max", "Avg"]:
raise NotImplementedError(
"Invalid pooling type: {}, can either be"
" `Max` or `Avg`.".format(pool_type)
)
def valid(x, k, p1, p2, s):
return math.floor((x + p1 + p2 - k) / s) + 1
def full(x, k, p1, p2, s):
return math.ceil((x + p1 + p2 - k) / s) + 1
if len(padding) == 4:
full_paddings = [
[0, 0],
[0, 0],
[padding[0], padding[2]],
[padding[1], padding[3]],
]
elif len(padding) == 2:
full_paddings = [
[0, 0],
[0, 0],
[padding[0], padding[0]],
[padding[1], padding[1]],
]
elif len(padding) == 1:
full_paddings = [[0, 0], [0, 0], [padding, padding], [padding, padding]]
else:
raise ValueError(
"Invalid padding size passed by Relay operator, "
" Sizes of 1, 2 and 4 are supported but not {}".format(len(padding))
)
padding = [
min(full_paddings[2][0], full_paddings[2][1]),
min(full_paddings[3][0], full_paddings[3][1]),
]
if layout == "NCHW":
insize = [input_layer.shapes[2], input_layer.shapes[3]]
batches, channels = input_layer.shapes[0], input_layer.shapes[1]
else:
insize = [input_layer.shapes[1], input_layer.shapes[2]]
batches, channels = input_layer.shapes[0], input_layer.shapes[3]
full_paddings = [full_paddings[i] for i in [0, 2, 3, 1]]
outsize = []
calc_func = full if ceil_mode else valid
outsize = [
calc_func(
insize[1],
pool_size[1],
full_paddings[3][0],
full_paddings[3][1],
strides[1],
),
calc_func(
insize[0],
pool_size[0],
full_paddings[2][0],
full_paddings[2][1],
strides[0],
),
]
attrs = kwargs
attrs.update(
{
"type": pool_type,
"padding": full_paddings,
"strides": strides,
"kernel_size": pool_size,
"insize": insize,
"outsize": [outsize[1], outsize[0]],
"data_layout": layout,
"pool_type": pool_type,
}
)
if pool_type == "Avg":
attrs["count_include_pad"] = count_include_pad
out_h, out_w = outsize[1], outsize[0]
out_shape = TensorShape(
[batches, channels, out_h, out_w]
if layout == "NCHW"
else [batches, out_h, out_w, channels]
)
X = XLayer()
X = X._replace(
name=op_name,
type=["Pooling"],
shapes=out_shape,
sizes=out_shape.get_size(),
attrs=attrs,
layer=[op_name],
tops=[],
bottoms=[input_layer.name],
targets=[],
)
return X
@xop_register_op_layout_transform("Pooling")
def pooling_layout_transform(X: XLayer, target_layout: str) -> None:
layout = X.attrs["data_layout"]
axes_transpose = [layout.index(e) for e in target_layout]
X.attrs["padding"] = [X.attrs["padding"][i] for i in axes_transpose]
X.attrs["data_layout"] = target_layout
X.shapes = TensorShape([X.shapes[i] for i in axes_transpose])
@xop_register("Upsampling2D")
def upsampling2d(
attrs: Dict[str, Any], in_xlayers: List[XLayer]
) -> Dict[str, List[int]]:
assert len(in_xlayers) == 1
assert "scale_h" in attrs
assert "scale_w" in attrs
assert "data_layout" in attrs
assert "method" in attrs
if "align_corners" not in attrs:
attrs["align_corners"] = False
scale_h = attrs["scale_h"]
scale_w = attrs["scale_w"]
layout = attrs["data_layout"]
assert sorted(layout) == ["C", "H", "N", "W"]
h_idx = layout.index("H")
w_idx = layout.index("W")
shape = in_xlayers[0].shapes[:]
shape[h_idx] = int(shape[h_idx] * scale_h)
shape[w_idx] = int(shape[w_idx] * scale_w)
return {"shape": shape}
@xop_register_op_layout_transform("Upsampling2D")
|
Apache License 2.0
|
bartoszj/mallet
|
mallet/UIKit/UITextField.py
|
UITextFieldSyntheticProvider.get_placeholder_label_summary
|
python
|
def get_placeholder_label_summary(provider):
value = provider.text_value
if value is not None:
return "placeholder={}".format(value)
return None
|
Placeholder label summary.
:param UILabel.UILabelSyntheticProvider provider: Label provider.
:return: Placeholder label summary.
:rtype: str
|
https://github.com/bartoszj/mallet/blob/0645b08c7eaea4b2f2769a0ca0d84fa8f0332357/mallet/UIKit/UITextField.py#L60-L71
|
from .. import helpers
import UIControl
import UILabel
class UITextFieldSyntheticProvider(UIControl.UIControlSyntheticProvider):
def __init__(self, value_obj, internal_dict):
super(UITextFieldSyntheticProvider, self).__init__(value_obj, internal_dict)
self.type_name = "UITextField"
self.register_child_value("display_label", ivar_name="_displayLabel",
provider_class=UILabel.UILabelSyntheticProvider,
summary_function=self.get_display_label_summary)
self.register_child_value("placeholder_label", ivar_name="_placeholderLabel",
provider_class=UILabel.UILabelSyntheticProvider,
summary_function=self.get_placeholder_label_summary)
@staticmethod
def get_display_label_summary(provider):
value = provider.text_value
if value is not None:
return "text={}".format(value)
return None
@staticmethod
|
MIT License
|
miroozyx/bert_with_keras
|
create_pretraining_data.py
|
create_masked_lm_predictions
|
python
|
def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng=random):
cand_indexes = []
for (i, token) in enumerate(tokens):
if token == "[CLS]" or token == "[SEP]":
continue
cand_indexes.append(i)
rng.shuffle(cand_indexes)
output_tokens = list(tokens)
masked_lm = collections.namedtuple("masked_lm", ["index", "label"])
num_to_predict = min(max_predictions_per_seq,
max(1, int(round(len(tokens) * masked_lm_prob))))
masked_lms = []
covered_indexes = set()
for index in cand_indexes:
if len(masked_lms) >= num_to_predict:
break
if index in covered_indexes:
continue
covered_indexes.add(index)
masked_token = None
if rng.random() < 0.8:
masked_token = "[MASK]"
else:
if rng.random() < 0.5:
masked_token = tokens[index]
else:
masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]
output_tokens[index] = masked_token
masked_lms.append(masked_lm(index=index, label=tokens[index]))
masked_lms = sorted(masked_lms, key=lambda x: x.index)
masked_lm_positions = []
masked_lm_labels = []
for p in masked_lms:
masked_lm_positions.append(p.index)
masked_lm_labels.append(p.label)
return (output_tokens, masked_lm_positions, masked_lm_labels)
|
Creates the predictions for the masked LM objective.
|
https://github.com/miroozyx/bert_with_keras/blob/fa65241a292fe1807b5271697cc3005ff9c4384b/create_pretraining_data.py#L6-L58
|
import collections
import random
import spacy
|
MIT License
|
pelioniot/mbed-cloud-sdk-python
|
src/mbed_cloud/_backends/connector_ca/models/server_credentials_response_data.py
|
ServerCredentialsResponseData.__eq__
|
python
|
def __eq__(self, other):
if not isinstance(other, ServerCredentialsResponseData):
return False
return self.__dict__ == other.__dict__
|
Returns true if both objects are equal
|
https://github.com/pelioniot/mbed-cloud-sdk-python/blob/71dc67fc2a8d1aff31e35ec781fb328e6a60639c/src/mbed_cloud/_backends/connector_ca/models/server_credentials_response_data.py#L240-L247
|
from pprint import pformat
from six import iteritems
import re
class ServerCredentialsResponseData(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'created_at': 'datetime',
'etag': 'str',
'id': 'str',
'object': 'str',
'server_certificate': 'str',
'server_uri': 'str'
}
attribute_map = {
'created_at': 'created_at',
'etag': 'etag',
'id': 'id',
'object': 'object',
'server_certificate': 'server_certificate',
'server_uri': 'server_uri'
}
def __init__(self, created_at=None, etag=None, id=None, object=None, server_certificate=None, server_uri=None):
self._created_at = created_at
self._etag = etag
self._id = id
self._object = object
self._server_certificate = server_certificate
self._server_uri = server_uri
self.discriminator = None
@property
def created_at(self):
return self._created_at
@created_at.setter
def created_at(self, created_at):
self._created_at = created_at
@property
def etag(self):
return self._etag
@etag.setter
def etag(self, etag):
self._etag = etag
@property
def id(self):
return self._id
@id.setter
def id(self, id):
self._id = id
@property
def object(self):
return self._object
@object.setter
def object(self, object):
self._object = object
@property
def server_certificate(self):
return self._server_certificate
@server_certificate.setter
def server_certificate(self, server_certificate):
self._server_certificate = server_certificate
@property
def server_uri(self):
return self._server_uri
@server_uri.setter
def server_uri(self, server_uri):
self._server_uri = server_uri
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
|
Apache License 2.0
|
trinity-project/trinity-eth
|
lightwallet/prompt.py
|
PromptInterface.show_wallet
|
python
|
def show_wallet(self, arguments):
if not self.Wallet:
print("please open a wallet")
return
item = get_arg(arguments)
if not item:
print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4))
return
else:
print("wallet: '{}' is an invalid parameter".format(item))
|
:param arguments:
:return:
|
https://github.com/trinity-project/trinity-eth/blob/a4e4fff1d1dbc0b422d7acc21ed95a308cf51967/lightwallet/prompt.py#L187-L207
|
import argparse
import json
import pprint
import traceback
from prompt_toolkit import print_formatted_text, PromptSession, ANSI
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import FileHistory
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.styles import Style
from prompt_toolkit import prompt
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
import os
import sys
import re
pythonpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(pythonpath)
from common.log import LOG
from common.number import TrinityNumber
from common.console import console_log
from lightwallet.Utils import get_arg, get_asset_id
from lightwallet.Settings import settings
from lightwallet.wallet import Wallet
from model.base_enum import EnumStatusCode
from blockchain.web3client import Client
from lightwallet.UserPreferences import preferences
import binascii
from model.statistics_model import APIStatistics
FILENAME_PROMPT_HISTORY = os.path.join(settings.DIR_CURRENT, '.prompt.py.history')
def command_wapper(command):
def handler(callback):
def wrapper(*args, **kwargs):
try:
callback(*args, **kwargs)
except Exception as error:
console_log.error('Error occurred to run command: {}. Please check logs for details.'.format(command))
LOG.exception('Error occurred to run command: {}. Exception: {}'.format(command, error))
return wrapper
return handler
class PromptInterface(object):
commands = [
'help',
'quit',
'create wallet {path}',
'open wallet {path}',
'close',
'wallet',
'send {asset} {address} {amount}',
'history',
'lock cli',
'unlock cli',
'gas configure {amount}',
'gas query'
]
go_on = True
Wallet=None
history = FileHistory(FILENAME_PROMPT_HISTORY)
locked = False
def __init__(self):
self.token_style = Style.from_dict({
"command": preferences.token_style['Command'],
"eth": preferences.token_style['Eth'],
"default": preferences.token_style['Default'],
"number": preferences.token_style['Number'],
})
def get_bottom_toolbar(self, cli=None):
return'[%s]' % (settings.NET_NAME if not PromptInterface.locked else settings.NET_NAME + " (Locked) ")
def quit(self):
self.go_on = False
def help(self):
tokens = []
for c in self.commands:
tokens.append(("class:command", "%s\n" % c))
print_formatted_text(FormattedText(tokens), style=self.token_style)
def do_create(self, arguments):
if self.Wallet:
self.do_close_wallet()
item = get_arg(arguments)
if self.Wallet:
self.do_close_wallet()
if item and item == 'wallet':
path = get_arg(arguments, 1)
if path:
if os.path.exists(path):
print("File already exists")
return
passwd1 = prompt("[Password 1]> ", is_password=True)
passwd2 = prompt("[Password 2]> ", is_password=True)
if passwd1 != passwd2 or len(passwd1) < 1:
print("please provide matching passwords that are at least 1 characters long")
return
try:
self.Wallet = Wallet.Create(path=path, password=passwd1)
print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4))
APIStatistics.add_statistics(self.Wallet.address)
except Exception as e:
print("Exception creating wallet: %s " % e)
self.Wallet = None
if os.path.isfile(path):
try:
os.remove(path)
except Exception as e:
print("Could not remove {}: {}".format(path, e))
return
else:
print("Please specify a path")
def do_open(self, arguments):
if self.Wallet:
self.do_close_wallet()
item = get_arg(arguments)
if item and item == 'wallet':
path = get_arg(arguments, 1)
if path:
if not os.path.exists(path):
print("wallet file not found")
return
passwd = prompt("[Password]> ", is_password=True)
try:
self.Wallet = Wallet.Open(path, passwd)
print("Opened wallet at %s" % path)
except Exception as e:
print("could not open wallet: %s " % e)
else:
print("Please specify a path")
else:
print("please specify something to open")
def do_close_wallet(self):
if self.Wallet:
path = self.Wallet._path
self.Wallet = None
print("closed wallet %s " % path)
@command_wapper("wallet")
|
MIT License
|
rgal/gym-2048
|
training_data.py
|
training_data.hflip
|
python
|
def hflip(self):
self._x = np.flip(self.get_x(), 2)
output_digits = self.get_y_digit()
temp = np.copy(output_digits)
temp[temp == 1] = 33
temp[temp == 3] = 1
temp[temp == 33] = 3
self._y_digit = temp
self._next_x = np.flip(self.get_next_x(), 2)
self._check_lengths()
|
Flip all the data horizontally
|
https://github.com/rgal/gym-2048/blob/fe0ef1f8d999847acd518237c44454e3607574f0/training_data.py#L257-L272
|
from __future__ import print_function
import copy
import numpy as np
def stack(flat, layers=16):
representation = 2 ** (np.arange(layers, dtype=int) + 1)
layered = np.repeat(flat[:,:,:,np.newaxis], layers, axis=-1)
layered = np.where(layered == representation, 1, 0)
return layered
class training_data(object):
def __init__(self):
self._x = np.empty([0, 4, 4], dtype=int)
self._y_digit = np.zeros([0, 1], dtype=int)
self._reward = np.zeros([0, 1], dtype=float)
self._next_x = np.empty([0, 4, 4], dtype=int)
self._done = np.empty([0, 1], dtype=bool)
def copy(self):
return copy.deepcopy(self)
def _check_lengths(self):
assert self._x.shape[0] == self._y_digit.shape[0]
assert self._x.shape[0] == self._reward.shape[0]
assert self._x.shape[0] == self._next_x.shape[0]
assert self._x.shape[0] == self._done.shape[0]
def get_x(self):
return self._x
def get_x_stacked(self):
return stack(self._x)
def get_y_digit(self):
return self._y_digit
def get_y_one_hot(self):
items = self.size()
one_hot = np.zeros((items, 4))
flat_y = np.reshape(self._y_digit, (-1, ))
one_hot[np.arange(items), flat_y] = 1
return one_hot
def get_reward(self):
return self._reward
def get_next_x(self):
return self._next_x
def get_done(self):
return self._done
def add(self, board, action, reward, next_board=None, done=False):
assert reward is not None
self._x = np.append(self._x, np.reshape(board, (1, 4, 4)), axis=0)
y_digit = np.zeros([1, 1], dtype=int)
y_digit[0, 0] = action
self._y_digit = np.append(self._y_digit, y_digit, axis=0)
r = np.zeros([1, 1], dtype=float)
r[0, 0] = reward
self._reward = np.append(self._reward, r, axis=0)
self._next_x = np.append(self._next_x, np.reshape(next_board, (1, 4, 4)), axis=0)
done_array = np.zeros([1, 1], dtype=bool)
done_array[0, 0] = done
self._done = np.append(self._done, done_array, axis=0)
self._check_lengths()
def get_n(self, n):
return self._x[n,:,:], self._y_digit[n,:], self._reward[n,:], self._next_x[n,:,:], self._done[n,:]
def get_total_reward(self):
return np.sum(self.get_reward())
def get_highest_tile(self):
return np.max(self.get_next_x())
def log2_rewards(self):
items = self.size()
rewards = np.reshape(self._reward, (items))
log_rewards = np.ma.log(rewards) / np.ma.log(2)
self._reward = np.reshape(np.array(log_rewards, float), (items, 1))
def get_discounted_return(self, gamma=0.9):
items = self.size()
rewards = list(np.reshape(self._reward, (items)))
done_list = list(np.reshape(self._done, (items)))
smoothed_rewards = list()
previous = None
rewards.reverse()
done_list.reverse()
for i, r in enumerate(rewards):
smoothed = r
if done_list[i]:
previous = None
if previous:
smoothed += gamma * previous
smoothed_rewards.append(smoothed)
previous = smoothed
smoothed_rewards.reverse()
return np.reshape(np.array(smoothed_rewards, float), (items, 1))
def normalize_boards(self, mean=None, sd=None):
boards = self._x
if mean is None:
mean = np.mean(boards)
if sd is None:
sd = np.std(boards)
norm_boards = (boards - mean) / sd
self._x = norm_boards
norm_next_boards = (self._next_x - mean) / sd
self._next_x = norm_next_boards
def normalize_rewards(self, mean=None, sd=None):
rewards = self._reward
if mean is None:
mean = np.mean(rewards)
if sd is None:
sd = np.std(rewards)
norm_rewards = (rewards - mean) / sd
self._reward = norm_rewards
def merge(self, other):
self._x = np.concatenate((self._x, other.get_x()))
self._y_digit = np.concatenate((self._y_digit, other.get_y_digit()))
self._reward = np.concatenate((self._reward, other.get_reward()))
self._next_x = np.concatenate((self._next_x, other.get_next_x()))
self._done = np.concatenate((self._done, other.get_done()))
self._check_lengths()
def split(self, split=0.5):
splitpoint = int(self.size() * split)
a = training_data()
b = training_data()
a._x = self._x[:splitpoint,:,:]
b._x = self._x[splitpoint:,:,:]
a._y_digit = self._y_digit[:splitpoint,:]
b._y_digit = self._y_digit[splitpoint:,:]
a._reward = self._reward[:splitpoint,:]
b._reward = self._reward[splitpoint:,:]
a._next_x = self._next_x[:splitpoint,:,:]
b._next_x = self._next_x[splitpoint:,:,:]
a._done = self._done[:splitpoint,:]
b._done = self._done[splitpoint:,:]
a._check_lengths()
b._check_lengths()
return a, b
def sample(self, index_list):
indexes = np.asarray(index_list)
sample = training_data()
sample._x = self._x[indexes]
sample._y_digit = self._y_digit[indexes]
sample._reward = self._reward[indexes]
sample._next_x = self._next_x[indexes]
sample._done = self._done[indexes]
sample._check_lengths()
return sample
def size(self):
return self._x.shape[0]
def import_csv(self, filename):
flat_data = np.loadtxt(filename, dtype=int, delimiter=',', skiprows=1, usecols=tuple(range(16)))
self._x = np.reshape(flat_data, (-1, 4, 4))
digits = np.loadtxt(filename, dtype=int, delimiter=',', skiprows=1, usecols=16)
self._y_digit = np.reshape(digits, (-1, 1))
reward_data = np.loadtxt(filename, delimiter=',', skiprows=1, usecols=17)
self._reward = reward_data.reshape(-1, 1)
flat_data = np.loadtxt(filename, dtype=int, delimiter=',', skiprows=1, usecols=tuple(range(18, 34)))
self._next_x = np.reshape(flat_data, (-1, 4, 4))
done_data = np.loadtxt(filename, dtype=bool, delimiter=',', skiprows=1, usecols=34)
self._done = done_data.reshape(-1, 1)
self._check_lengths()
def construct_header(self, add_returns=False):
header = list()
for m in range(1, 5):
for n in range(1, 5):
header.append('{}-{}'.format(m, n))
header.append('action')
header.append('reward')
for m in range(1, 5):
for n in range(1, 5):
header.append('next {}-{}'.format(m, n))
header.append('done')
if add_returns:
header.append('return')
return header
def export_csv(self, filename, add_returns=False):
items = self.size()
flat_x = np.reshape(self._x, (items, 16))
flat_data = np.concatenate((flat_x, self._y_digit), axis=1)
flat_data = np.concatenate((flat_data, self._reward), axis=1)
assert flat_data.shape[1] == 18
flat_next_x = np.reshape(self._next_x, (items, 16))
flat_data = np.concatenate((flat_data, flat_next_x), axis=1)
assert flat_data.shape[1] == 34
flat_data = np.concatenate((flat_data, self._done), axis=1)
if add_returns:
flat_data = np.concatenate((flat_data, self.get_discounted_return()), axis=1)
header = self.construct_header(add_returns)
fformat = '%d,' * 17 + '%f,' + '%d,' * 16 + '%i'
if add_returns:
fformat += ',%f'
np.savetxt(filename, flat_data, comments='', fmt=fformat, header=','.join(header))
def dump(self):
print(self._x)
print(self._y_digit)
print(self._reward)
print(self._next_x)
print(self._done)
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.