hexsha stringlengths 40 40 | size int64 3 1.03M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 972 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 972 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 972 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 3 1.03M | avg_line_length float64 1.13 941k | max_line_length int64 2 941k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c6329045412e41f2f17e5a9133e88f0e2022bda2 | 29,067 | py | Python | shenfun/jacobi/bases.py | spectralDNS/shenfun | 956633aa0f1638db5ebdc497ff68a438aa22b932 | [
"BSD-2-Clause"
] | 138 | 2017-06-17T13:30:27.000Z | 2022-03-20T02:33:47.000Z | shenfun/jacobi/bases.py | spectralDNS/shenfun | 956633aa0f1638db5ebdc497ff68a438aa22b932 | [
"BSD-2-Clause"
] | 73 | 2017-05-16T06:53:04.000Z | 2022-02-04T10:40:44.000Z | shenfun/jacobi/bases.py | spectralDNS/shenfun | 956633aa0f1638db5ebdc497ff68a438aa22b932 | [
"BSD-2-Clause"
] | 38 | 2018-01-31T14:37:01.000Z | 2022-03-31T15:07:27.000Z | """
Module for function spaces of generalized Jacobi type
Note the configuration setting
from shenfun.config import config
config['bases']['jacobi']['mode']
Setting this to 'mpmath' can make use of extended precision.
The precision can also be set in the configuration.
from mpmath import mp
mp.dps = config['jacobi'][precision]
where mp.dps is the number of significant digits.
Note that extended precision is costly, but for some of the
matrices that can be created with the Jacobi bases it is necessary.
Also note the the higher precision is only used for assembling
matrices comuted with :func:`evaluate_basis_derivative_all`.
It has no effect for the matrices that are predifined in the
matrices.py module. Also note that the final matrix will be
in regular double precision. So the higher precision is only used
for the intermediate assembly.
"""
import functools
import numpy as np
import sympy as sp
from scipy.special import eval_jacobi, roots_jacobi #, gamma
from mpi4py_fft import fftw
from shenfun.config import config
from shenfun.spectralbase import SpectralBase, Transform, islicedict, slicedict
from shenfun.chebyshev.bases import BCBiharmonic, BCDirichlet
try:
import quadpy
from mpmath import mp
mp.dps = config['bases']['jacobi']['precision']
has_quadpy = True
except:
has_quadpy = False
mp = None
mode = config['bases']['jacobi']['mode']
mode = mode if has_quadpy else 'numpy'
xp = sp.Symbol('x', real=True)
#pylint: disable=method-hidden,no-else-return,not-callable,abstract-method,no-member,cyclic-import
__all__ = ['JacobiBase', 'Orthogonal', 'ShenDirichlet', 'ShenBiharmonic',
'ShenOrder6', 'mode', 'has_quadpy', 'mp']
class JacobiBase(SpectralBase):
"""Base class for all Jacobi spaces
Parameters
----------
N : int
Number of quadrature points
quad : str, optional
Type of quadrature
- JG - Jacobi-Gauss
alpha : number, optional
Parameter of the Jacobi polynomial
beta : number, optional
Parameter of the Jacobi polynomial
domain : 2-tuple of floats, optional
The computational domain
padding_factor : float, optional
Factor for padding backward transforms.
dealias_direct : bool, optional
Set upper 1/3 of coefficients to zero before backward transform
dtype : data-type, optional
Type of input data in real physical space. Will be overloaded when
basis is part of a :class:`.TensorProductSpace`.
coordinates: 2- or 3-tuple (coordinate, position vector (, sympy assumptions)), optional
Map for curvilinear coordinatesystem.
The new coordinate variable in the new coordinate system is the first item.
Second item is a tuple for the Cartesian position vector as function of the
new variable in the first tuple. Example::
theta = sp.Symbols('x', real=True, positive=True)
rv = (sp.cos(theta), sp.sin(theta))
"""
def __init__(self, N, quad="JG", alpha=0, beta=0, domain=(-1., 1.), dtype=float,
padding_factor=1, dealias_direct=False, coordinates=None):
SpectralBase.__init__(self, N, quad=quad, domain=domain, dtype=dtype,
padding_factor=padding_factor, dealias_direct=dealias_direct,
coordinates=coordinates)
self.alpha = alpha
self.beta = beta
self.forward = functools.partial(self.forward, fast_transform=False)
self.backward = functools.partial(self.backward, fast_transform=False)
self.scalar_product = functools.partial(self.scalar_product, fast_transform=False)
self.plan(int(N*padding_factor), 0, dtype, {})
@staticmethod
def family():
return 'jacobi'
def reference_domain(self):
return (-1, 1)
def get_orthogonal(self):
return Orthogonal(self.N,
quad=self.quad,
domain=self.domain,
dtype=self.dtype,
padding_factor=self.padding_factor,
dealias_direct=self.dealias_direct,
coordinates=self.coors.coordinates,
alpha=0,
beta=0)
def points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if N is None:
N = self.shape(False)
assert self.quad == "JG"
points, weights = roots_jacobi(N, self.alpha, self.beta)
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def mpmath_points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if mode == 'numpy' or not has_quadpy:
return self.points_and_weights(N=N, map_true_domain=map_true_domain, weighted=weighted, **kw)
if N is None:
N = self.shape(False)
pw = quadpy.c1.gauss_jacobi(N, self.alpha, self.beta, 'mpmath')
points = pw.points_symbolic
weights = pw.weights_symbolic
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def jacobi(self, x, alpha, beta, N):
V = np.zeros((x.shape[0], N))
if mode == 'numpy':
for n in range(N):
V[:, n] = eval_jacobi(n, alpha, beta, x)
else:
for n in range(N):
V[:, n] = sp.lambdify(xp, sp.jacobi(n, alpha, beta, xp), 'mpmath')(x)
return V
def derivative_jacobi(self, x, alpha, beta, k=1):
V = self.jacobi(x, alpha+k, beta+k, self.N)
if k > 0:
Vc = np.zeros_like(V)
for j in range(k, self.N):
dj = np.prod(np.array([j+alpha+beta+1+i for i in range(k)]))
#dj = gamma(j+alpha+beta+1+k) / gamma(j+alpha+beta+1)
Vc[:, j] = (dj/2**k)*V[:, j-k]
V = Vc
return V
def vandermonde(self, x):
return self.jacobi(x, self.alpha, self.beta, self.shape(False))
def plan(self, shape, axis, dtype, options):
if shape in (0, (0,)):
return
if isinstance(axis, tuple):
assert len(axis) == 1
axis = axis[0]
if isinstance(self.forward, Transform):
if self.forward.input_array.shape == shape and self.axis == axis:
# Already planned
return
U = fftw.aligned(shape, dtype=dtype)
V = fftw.aligned(shape, dtype=dtype)
U.fill(0)
V.fill(0)
self.axis = axis
if self.padding_factor > 1.+1e-8:
trunc_array = self._get_truncarray(shape, V.dtype)
self.scalar_product = Transform(self.scalar_product, None, U, V, trunc_array)
self.forward = Transform(self.forward, None, U, V, trunc_array)
self.backward = Transform(self.backward, None, trunc_array, V, U)
else:
self.scalar_product = Transform(self.scalar_product, None, U, V, V)
self.forward = Transform(self.forward, None, U, V, V)
self.backward = Transform(self.backward, None, V, V, U)
self.si = islicedict(axis=self.axis, dimensions=self.dimensions)
self.sl = slicedict(axis=self.axis, dimensions=self.dimensions)
class Orthogonal(JacobiBase):
"""Function space for regular (orthogonal) Jacobi functions
Parameters
----------
N : int
Number of quadrature points
quad : str, optional
Type of quadrature
- JG - Jacobi-Gauss
padding_factor : float, optional
Factor for padding backward transforms.
dealias_direct : bool, optional
Set upper 1/3 of coefficients to zero before backward transform
dtype : data-type, optional
Type of input data in real physical space. Will be overloaded when
basis is part of a :class:`.TensorProductSpace`.
coordinates: 2- or 3-tuple (coordinate, position vector (, sympy assumptions)), optional
Map for curvilinear coordinatesystem.
The new coordinate variable in the new coordinate system is the first item.
Second item is a tuple for the Cartesian position vector as function of the
new variable in the first tuple. Example::
theta = sp.Symbols('x', real=True, positive=True)
rv = (sp.cos(theta), sp.sin(theta))
"""
def __init__(self, N, quad="JG", alpha=-0.5, beta=-0.5, domain=(-1., 1.),
dtype=float, padding_factor=1, dealias_direct=False, coordinates=None):
JacobiBase.__init__(self, N, quad=quad, alpha=alpha, beta=beta, domain=domain, dtype=dtype,
padding_factor=padding_factor, dealias_direct=dealias_direct,
coordinates=coordinates)
@property
def is_orthogonal(self):
return True
#def get_orthogonal(self):
# return self
@staticmethod
def short_name():
return 'J'
def sympy_basis(self, i=0, x=xp):
return sp.jacobi(i, self.alpha, self.beta, x)
def evaluate_basis(self, x, i=0, output_array=None):
x = np.atleast_1d(x)
if output_array is None:
output_array = np.zeros(x.shape)
if mode == 'numpy':
output_array = eval_jacobi(i, self.alpha, self.beta, x, out=output_array)
else:
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f, 'mpmath')(x)
return output_array
def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
if x is None:
x = self.points_and_weights(mode=mode)[0]
#x = np.atleast_1d(x)
if output_array is None:
output_array = np.zeros(x.shape, dtype=self.dtype)
if mode == 'numpy':
dj = np.prod(np.array([i+self.alpha+self.beta+1+j for j in range(k)]))
output_array[:] = dj/2**k*eval_jacobi(i-k, self.alpha+k, self.beta+k, x)
else:
f = sp.jacobi(i, self.alpha, self.beta, xp)
output_array[:] = sp.lambdify(xp, f.diff(xp, k), 'mpmath')(x)
return output_array
def evaluate_basis_derivative_all(self, x=None, k=0, argument=0):
if x is None:
x = self.mpmath_points_and_weights(mode=mode)[0]
#if x.dtype == 'O':
# x = np.array(x, dtype=self.dtype)
if mode == 'numpy':
return self.derivative_jacobi(x, self.alpha, self.beta, k)
else:
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N):
V[:, i] = self.evaluate_basis_derivative(x, i, k, output_array=V[:, i])
return V
def evaluate_basis_all(self, x=None, argument=0):
if x is None:
x = self.mpmath_points_and_weights()[0]
return self.vandermonde(x)
class ShenDirichlet(JacobiBase):
"""Jacobi function space for Dirichlet boundary conditions
Parameters
----------
N : int
Number of quadrature points
quad : str, optional
Type of quadrature
- JG - Jacobi-Gauss
bc : tuple of numbers
Boundary conditions at edges of domain
domain : 2-tuple of floats, optional
The computational domain
padding_factor : float, optional
Factor for padding backward transforms.
dealias_direct : bool, optional
Set upper 1/3 of coefficients to zero before backward transform
dtype : data-type, optional
Type of input data in real physical space. Will be overloaded when
basis is part of a :class:`.TensorProductSpace`.
coordinates: 2- or 3-tuple (coordinate, position vector (, sympy assumptions)), optional
Map for curvilinear coordinatesystem.
The new coordinate variable in the new coordinate system is the first item.
Second item is a tuple for the Cartesian position vector as function of the
new variable in the first tuple. Example::
theta = sp.Symbols('x', real=True, positive=True)
rv = (sp.cos(theta), sp.sin(theta))
"""
def __init__(self, N, quad='JG', bc=(0, 0), domain=(-1., 1.), dtype=float,
padding_factor=1, dealias_direct=False, coordinates=None, alpha=-1, beta=-1):
assert alpha == -1 and beta == -1
JacobiBase.__init__(self, N, quad=quad, alpha=-1, beta=-1, domain=domain, dtype=dtype,
padding_factor=padding_factor, dealias_direct=dealias_direct,
coordinates=coordinates)
assert bc in ((0, 0), 'Dirichlet')
from shenfun.tensorproductspace import BoundaryValues
self._bc_basis = None
self.bc = BoundaryValues(self, bc=bc)
@staticmethod
def boundary_condition():
return 'Dirichlet'
@staticmethod
def short_name():
return 'SD'
def is_scaled(self):
return False
def slice(self):
return slice(0, self.N-2)
def evaluate_basis_derivative_all(self, x=None, k=0, argument=0):
if x is None:
x = self.mpmath_points_and_weights()[0]
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N-2):
V[:, i] = self.evaluate_basis_derivative(x, i, k, output_array=V[:, i])
return V
def sympy_basis(self, i=0, x=xp):
return (1-x**2)*sp.jacobi(i, 1, 1, x)
#return (1-x)**(-self.alpha)*(1+x)**(-self.beta)*sp.jacobi(i, -self.alpha, -self.beta, x)
def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
if x is None:
x = self.mpmath_points_and_weights()[0]
if output_array is None:
output_array = np.zeros(x.shape, dtype=self.dtype)
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f.diff(xp, k), mode)(x)
return output_array
def evaluate_basis(self, x, i=0, output_array=None):
x = np.atleast_1d(x)
if output_array is None:
output_array = np.zeros(x.shape, dtype=self.dtype)
if mode == 'numpy':
output_array = (1-x**2)*eval_jacobi(i, -self.alpha, -self.beta, x, out=output_array)
else:
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f, 'mpmath')(x)
return output_array
def evaluate_basis_all(self, x=None, argument=0):
if mode == 'numpy':
if x is None:
x = self.mesh(False, False)
V = np.zeros((x.shape[0], self.N))
V[:, :-2] = self.jacobi(x, 1, 1, self.N-2)*(1-x**2)[:, np.newaxis]
else:
if x is None:
x = self.mpmath_points_and_weights()[0]
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N-2):
V[:, i] = self.evaluate_basis(x, i, output_array=V[:, i])
return V
def points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if N is None:
N = self.shape(False)
assert self.quad == "JG"
points, weights = roots_jacobi(N, self.alpha+1, self.beta+1)
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def mpmath_points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if mode == 'numpy' or not has_quadpy:
return self.points_and_weights(N=N, map_true_domain=map_true_domain, weighted=weighted, **kw)
if N is None:
N = self.shape(False)
assert self.quad == "JG"
pw = quadpy.c1.gauss_jacobi(N, self.alpha+1, self.beta+1, mode)
points = pw.points_symbolic
weights = pw.weights_symbolic
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def to_ortho(self, input_array, output_array=None):
assert self.alpha == -1 and self.beta == -1
if output_array is None:
output_array = np.zeros_like(input_array)
else:
output_array.fill(0)
k = self.wavenumbers().astype(float)
s0 = self.sl[slice(0, -2)]
s1 = self.sl[slice(2, None)]
z = input_array[s0]*2*(k+1)/(2*k+3)
output_array[s0] = z
output_array[s1] -= z
return output_array
def _evaluate_scalar_product(self, fast_transform=True):
SpectralBase._evaluate_scalar_product(self)
self.scalar_product.tmp_array[self.sl[slice(-2, None)]] = 0
def get_bc_basis(self):
if self._bc_basis:
return self._bc_basis
self._bc_basis = BCDirichlet(self.N, quad=self.quad, domain=self.domain,
coordinates=self.coors.coordinates)
return self._bc_basis
class ShenBiharmonic(JacobiBase):
"""Function space for Biharmonic boundary conditions
Parameters
----------
N : int
Number of quadrature points
quad : str, optional
Type of quadrature
- JG - Jacobi-Gauss
domain : 2-tuple of floats, optional
The computational domain
padding_factor : float, optional
Factor for padding backward transforms.
dealias_direct : bool, optional
Set upper 1/3 of coefficients to zero before backward transform
dtype : data-type, optional
Type of input data in real physical space. Will be overloaded when
basis is part of a :class:`.TensorProductSpace`.
coordinates: 2- or 3-tuple (coordinate, position vector (, sympy assumptions)), optional
Map for curvilinear coordinatesystem.
The new coordinate variable in the new coordinate system is the first item.
Second item is a tuple for the Cartesian position vector as function of the
new variable in the first tuple. Example::
theta = sp.Symbols('x', real=True, positive=True)
rv = (sp.cos(theta), sp.sin(theta))
Note
----
The generalized Jacobi function j^{alpha=-2, beta=-2} is used as basis. However,
inner products are computed without weights, for alpha=beta=0.
"""
def __init__(self, N, quad='JG', bc=(0, 0, 0, 0), domain=(-1., 1.), dtype=float,
padding_factor=1, dealias_direct=False, coordinates=None,
alpha=-2, beta=-2):
assert alpha == -2 and beta == -2
JacobiBase.__init__(self, N, quad=quad, alpha=-2, beta=-2, domain=domain, dtype=dtype,
padding_factor=padding_factor, dealias_direct=dealias_direct,
coordinates=coordinates)
assert bc in ((0, 0, 0, 0), 'Biharmonic')
from shenfun.tensorproductspace import BoundaryValues
self._bc_basis = None
self.bc = BoundaryValues(self, bc=bc)
@staticmethod
def boundary_condition():
return 'Biharmonic'
@staticmethod
def short_name():
return 'SB'
def slice(self):
return slice(0, self.N-4)
def sympy_basis(self, i=0, x=xp):
return (1-x**2)**2*sp.jacobi(i, 2, 2, x)
def evaluate_basis_derivative_all(self, x=None, k=0, argument=0):
if x is None:
x = self.mpmath_points_and_weights()[0]
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N-4):
V[:, i] = self.evaluate_basis_derivative(x, i, k, output_array=V[:, i])
return V
def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
if x is None:
x = self.mpmath_points_and_weights()[0]
if output_array is None:
output_array = np.zeros(x.shape, dtype=self.dtype)
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f.diff(xp, k), mode)(x)
return output_array
def evaluate_basis(self, x, i=0, output_array=None):
x = np.atleast_1d(x)
if output_array is None:
output_array = np.zeros(x.shape)
if mode == 'numpy':
output_array[:] = (1-x**2)**2*eval_jacobi(i, 2, 2, x, out=output_array)
else:
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f, 'mpmath')(x)
return output_array
def evaluate_basis_all(self, x=None, argument=0):
if mode == 'numpy':
if x is None:
x = self.mesh(False, False)
N = self.shape(False)
V = np.zeros((x.shape[0], N))
V[:, :-4] = self.jacobi(x, 2, 2, N-4)*((1-x**2)**2)[:, np.newaxis]
else:
if x is None:
x = self.mpmath_points_and_weights()[0]
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N-4):
V[:, i] = self.evaluate_basis(x, i, output_array=V[:, i])
return V
def _evaluate_scalar_product(self, fast_transform=True):
SpectralBase._evaluate_scalar_product(self)
self.scalar_product.tmp_array[self.sl[slice(-4, None)]] = 0
def points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if N is None:
N = self.shape(False)
assert self.quad == "JG"
points, weights = roots_jacobi(N, 0, 0)
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def mpmath_points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if mode == 'numpy' or not has_quadpy:
return self.points_and_weights(N=N, map_true_domain=map_true_domain, weighted=weighted, **kw)
if N is None:
N = self.shape(False)
assert self.quad == "JG"
pw = quadpy.c1.gauss_jacobi(N, 0, 0, 'mpmath')
points = pw.points_symbolic
weights = pw.weights_symbolic
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def to_ortho(self, input_array, output_array=None):
if output_array is None:
output_array = np.zeros_like(input_array)
else:
output_array.fill(0)
k = self.wavenumbers().astype(float)
_factor0 = 4*(k+2)*(k+1)/(2*k+5)/(2*k+3)
_factor1 = (-2*(2*k+5)/(2*k+7))
_factor2 = ((2*k+3)/(2*k+7))
s0 = self.sl[slice(0, -4)]
z = _factor0*input_array[s0]
output_array[s0] = z
output_array[self.sl[slice(2, -2)]] += z*_factor1
output_array[self.sl[slice(4, None)]] += z*_factor2
return output_array
def get_bc_basis(self):
if self._bc_basis:
return self._bc_basis
self._bc_basis = BCBiharmonic(self.N, quad=self.quad, domain=self.domain,
coordinates=self.coors.coordinates)
return self._bc_basis
class ShenOrder6(JacobiBase):
"""Function space for 6th order equation
Parameters
----------
N : int
Number of quadrature points
quad : str, optional
Type of quadrature
- JG - Jacobi-Gauss
domain : 2-tuple of floats, optional
The computational domain
padding_factor : float, optional
Factor for padding backward transforms.
dealias_direct : bool, optional
Set upper 1/3 of coefficients to zero before backward transform
dtype : data-type, optional
Type of input data in real physical space. Will be overloaded when
basis is part of a :class:`.TensorProductSpace`.
coordinates: 2- or 3-tuple (coordinate, position vector (, sympy assumptions)), optional
Map for curvilinear coordinatesystem.
The new coordinate variable in the new coordinate system is the first item.
Second item is a tuple for the Cartesian position vector as function of the
new variable in the first tuple. Example::
theta = sp.Symbols('x', real=True, positive=True)
rv = (sp.cos(theta), sp.sin(theta))
Note
----
The generalized Jacobi function j^{alpha=-3, beta=-3} is used as basis. However,
inner products are computed without weights, for alpha=beta=0.
"""
def __init__(self, N, quad='JG', domain=(-1., 1.), dtype=float, padding_factor=1, dealias_direct=False,
coordinates=None, bc=(0, 0, 0, 0, 0, 0), alpha=-3, beta=-3):
assert alpha == -3 and beta == -3
JacobiBase.__init__(self, N, quad=quad, alpha=-3, beta=-3, domain=domain, dtype=dtype,
padding_factor=padding_factor, dealias_direct=dealias_direct,
coordinates=coordinates)
from shenfun.tensorproductspace import BoundaryValues
self.bc = BoundaryValues(self, bc=bc)
@staticmethod
def boundary_condition():
return '6th order'
@staticmethod
def short_name():
return 'SS'
def slice(self):
return slice(0, self.N-6)
def sympy_basis(self, i=0, x=xp):
return (1-x**2)**3*sp.jacobi(i, 3, 3, x)
def evaluate_basis_derivative(self, x=None, i=0, k=0, output_array=None):
if x is None:
x = self.mpmath_points_and_weights()[0]
if output_array is None:
output_array = np.zeros(x.shape)
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f.diff(xp, k), mode)(x)
return output_array
def evaluate_basis_derivative_all(self, x=None, k=0, argument=0):
if x is None:
x = self.mpmath_points_and_weights()[0]
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N-6):
V[:, i] = self.evaluate_basis_derivative(x, i, k, output_array=V[:, i])
return V
def evaluate_basis(self, x, i=0, output_array=None):
x = np.atleast_1d(x)
if output_array is None:
output_array = np.zeros(x.shape)
if mode == 'numpy':
output_array[:] = (1-x**2)**3*eval_jacobi(i, 3, 3, x, out=output_array)
else:
f = self.sympy_basis(i, xp)
output_array[:] = sp.lambdify(xp, f, 'mpmath')(x)
return output_array
def evaluate_basis_all(self, x=None, argument=0):
if mode == 'numpy':
if x is None:
x = self.mesh(False, False)
N = self.shape(False)
V = np.zeros((x.shape[0], N))
V[:, :-6] = self.jacobi(x, 3, 3, N-6)*((1-x**2)**3)[:, np.newaxis]
else:
if x is None:
x = self.mpmath_points_and_weights()[0]
N = self.shape(False)
V = np.zeros((x.shape[0], N))
for i in range(N-6):
V[:, i] = self.evaluate_basis(x, i, output_array=V[:, i])
return V
def points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if N is None:
N = self.shape(False)
assert self.quad == "JG"
points, weights = roots_jacobi(N, 0, 0)
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def mpmath_points_and_weights(self, N=None, map_true_domain=False, weighted=True, **kw):
if mode == 'numpy' or not has_quadpy:
return self.points_and_weights(N=N, map_true_domain=map_true_domain, weighted=weighted, **kw)
if N is None:
N = self.shape(False)
assert self.quad == "JG"
pw = quadpy.c1.gauss_jacobi(N, 0, 0, 'mpmath')
points = pw.points_symbolic
weights = pw.weights_symbolic
if map_true_domain is True:
points = self.map_true_domain(points)
return points, weights
def get_orthogonal(self):
return Orthogonal(self.N, alpha=0, beta=0, dtype=self.dtype, domain=self.domain, coordinates=self.coors.coordinates)
def _evaluate_scalar_product(self, fast_transform=True):
SpectralBase._evaluate_scalar_product(self)
self.scalar_product.tmp_array[self.sl[slice(-6, None)]] = 0
#def to_ortho(self, input_array, output_array=None):
# if output_array is None:
# output_array = np.zeros_like(input_array.v)
# k = self.wavenumbers().astype(float)
# _factor0 = 4*(k+2)*(k+1)/(2*k+5)/(2*k+3)
# _factor1 = (-2*(2*k+5)/(2*k+7))
# _factor2 = ((2*k+3)/(2*k+7))
# s0 = self.sl[slice(0, -4)]
# z = _factor0*input_array[s0]
# output_array[s0] = z
# output_array[self.sl[slice(2, -2)]] -= z*_factor1
# output_array[self.sl[slice(4, None)]] += z*_factor2
# return output_array
| 38.756 | 124 | 0.593491 |
4400e4440740d531181034ce0ec825c4151d52f1 | 2,304 | py | Python | tools/update_cli_readme_documentation.py | howardjohn/nighthawk | dafeb17e4a191eaff396cd54873d46d78c69d7c4 | [
"Apache-2.0"
] | null | null | null | tools/update_cli_readme_documentation.py | howardjohn/nighthawk | dafeb17e4a191eaff396cd54873d46d78c69d7c4 | [
"Apache-2.0"
] | null | null | null | tools/update_cli_readme_documentation.py | howardjohn/nighthawk | dafeb17e4a191eaff396cd54873d46d78c69d7c4 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# Tool to automatically update README.md files that contain --help output of c++ TCLAP binaries
import logging
import argparse
import os
import pathlib
import re
import sys
import subprocess
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tool to update README.md CLI documentation.")
parser.add_argument(
"--binary",
required=True,
help="Relative path to the target binary, for example: \"bazel-bin/nighthawk_client\".")
parser.add_argument(
"--readme",
required=True,
help="Relative path to the target documentation file, for example: \"README.md\"")
parser.add_argument(
"--mode",
default="check",
required=True,
choices={"check", "fix"},
help="Either \"check\" or \"fix\"")
args = parser.parse_args()
logging.getLogger().setLevel(logging.INFO)
project_root = os.path.join(os.path.dirname(os.path.join(os.path.realpath(__file__))), "../")
# Change directory to avoid TCLAP outputting a full path specification to the binary
# in its help output.
os.chdir(os.path.realpath(project_root))
readme_md_path = os.path.join(project_root, args.readme)
process = subprocess.run([args.binary, "--help"], stdout=subprocess.PIPE, check=True)
# Avoid trailing spaces, as they introduce markdown linting errors.
cli_help = [s.strip() for s in process.stdout.decode().splitlines()]
target_path = pathlib.Path(readme_md_path)
with target_path.open("r", encoding="utf-8") as f:
original_contents = target_path.read_text(encoding="utf-8")
replaced = re.sub("\nUSAGE\:[^.]*.*%s[^```]*" % args.binary, str.join("\n", cli_help),
original_contents)
# Avoid check_format flagging "over-enthousiastic" whitespace
replaced = replaced.replace("... [", "... [")
if replaced != original_contents:
if args.mode == "check":
logging.info(
"CLI documentation in /%s needs to be updated for %s" % (args.readme, args.binary))
sys.exit(-1)
elif args.mode == "fix":
with target_path.open("w", encoding="utf-8") as f:
logging.error(
"CLI documentation in /%s needs to be updated for %s" % (args.readme, args.binary))
f.write("%s" % replaced)
logging.info("Done")
sys.exit(0)
| 36.571429 | 95 | 0.667101 |
f4ad55897db3f07236ea6c8a505eb68352dc3ad8 | 1,101 | py | Python | scripts/prisecon_prototype.py | glieb/dilemma | f61d564314f3f5494da19fb4212d9dd04d77b284 | [
"MIT"
] | null | null | null | scripts/prisecon_prototype.py | glieb/dilemma | f61d564314f3f5494da19fb4212d9dd04d77b284 | [
"MIT"
] | null | null | null | scripts/prisecon_prototype.py | glieb/dilemma | f61d564314f3f5494da19fb4212d9dd04d77b284 | [
"MIT"
] | null | null | null | import pickle
import sys
sys.path.append("../dilemma")
from biases import bias_dict
def save_prototype(biases, filename):
open(filename, "w+") # creates the file
with open(filename, "wb") as prototype:
pickle.dump(biases, prototype)
def load_prototype(file):
with open(file, "rb") as prototype:
return pickle.load(prototype)
def create_prototype(**kwargs):
biases = kwargs
remainder = check_biases(biases) # list of biases not included
for bias in remainder:
biases[bias] = 0 # do not factor unmentioned bases
return biases
def check_biases(biases):
return [bias for bias in bias_dict if bias not in biases]
if __name__ == "__main__":
print("Enter the name of your new prototype, or EXIT to cancel.")
name = input(">>")
if name == "EXIT":
exit()
filename = "../prototypes/" + name + ".pkl"
biases = {}
for bias in bias_dict:
biases[bias] = float(input(
"Enter {} value for {}: ".format(bias, name)))
save_prototype(biases, filename)
| 26.214286 | 70 | 0.621253 |
c3b6e95ec4810f8754247281ab6a5842c1902d02 | 4,236 | py | Python | benchmark/startQiskit1350.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | benchmark/startQiskit1350.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | benchmark/startQiskit1350.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | # qubit number=5
# total number=52
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
oracle = QuantumCircuit(controls, name="Zf")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.h(controls[n])
if n >= 2:
oracle.mcu1(pi, controls[1:], controls[0])
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[0]) # number=3
prog.h(input_qubit[1]) # number=4
prog.h(input_qubit[2]) # number=5
prog.h(input_qubit[3]) # number=6
prog.h(input_qubit[4]) # number=21
prog.h(input_qubit[0]) # number=43
prog.cz(input_qubit[4],input_qubit[0]) # number=44
prog.h(input_qubit[0]) # number=45
prog.cx(input_qubit[4],input_qubit[0]) # number=46
prog.z(input_qubit[4]) # number=47
prog.cx(input_qubit[4],input_qubit[0]) # number=48
prog.h(input_qubit[0]) # number=37
prog.cz(input_qubit[4],input_qubit[0]) # number=38
prog.h(input_qubit[0]) # number=39
Zf = build_oracle(n, f)
repeat = floor(sqrt(2 ** n) * pi / 4)
for i in range(repeat):
prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])
prog.h(input_qubit[0]) # number=1
prog.rx(-1.0430087609918113,input_qubit[4]) # number=36
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=7
prog.h(input_qubit[3]) # number=8
prog.cx(input_qubit[1],input_qubit[0]) # number=40
prog.x(input_qubit[0]) # number=41
prog.h(input_qubit[0]) # number=49
prog.cz(input_qubit[1],input_qubit[0]) # number=50
prog.h(input_qubit[0]) # number=51
prog.x(input_qubit[1]) # number=10
prog.rx(-0.06597344572538572,input_qubit[3]) # number=27
prog.cx(input_qubit[0],input_qubit[2]) # number=22
prog.x(input_qubit[2]) # number=23
prog.h(input_qubit[2]) # number=28
prog.cz(input_qubit[0],input_qubit[2]) # number=29
prog.h(input_qubit[2]) # number=30
prog.x(input_qubit[3]) # number=12
if n>=2:
prog.mcu1(pi,input_qubit[1:],input_qubit[0])
prog.x(input_qubit[0]) # number=13
prog.x(input_qubit[1]) # number=14
prog.x(input_qubit[2]) # number=15
prog.x(input_qubit[3]) # number=16
prog.h(input_qubit[4]) # number=35
prog.h(input_qubit[0]) # number=17
prog.rx(2.4912829742967055,input_qubit[2]) # number=26
prog.h(input_qubit[1]) # number=18
prog.h(input_qubit[2]) # number=19
prog.h(input_qubit[2]) # number=25
prog.h(input_qubit[3]) # number=20
# circuit end
for i in range(n):
prog.measure(input_qubit[i], classical[i])
return prog
if __name__ == '__main__':
key = "00000"
f = lambda rep: str(int(rep == key))
prog = make_circuit(5,f)
backend = BasicAer.get_backend('qasm_simulator')
sample_shot =7924
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit1350.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| 31.849624 | 82 | 0.614023 |
176307982b4e78c64531286b754de3308cdd7243 | 6,751 | py | Python | lib/base_wizard.py | Andymeows/electrum-doge | e5e8c8e3e301cccb53de58445445e9e7fd0e9665 | [
"MIT"
] | 1 | 2017-02-21T17:52:54.000Z | 2017-02-21T17:52:54.000Z | lib/base_wizard.py | Andymeows/electrum-doge | e5e8c8e3e301cccb53de58445445e9e7fd0e9665 | [
"MIT"
] | null | null | null | lib/base_wizard.py | Andymeows/electrum-doge | e5e8c8e3e301cccb53de58445445e9e7fd0e9665 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2016 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
from electrum_ltc.wallet import Wallet, Multisig_Wallet
from electrum_ltc_gui.kivy.i18n import _
class BaseWizard(object):
def __init__(self, config, network, storage):
super(BaseWizard, self).__init__()
self.config = config
self.network = network
self.storage = storage
self.wallet = None
def run(self, action, *args):
'''Entry point of our Installation wizard'''
if not action:
return
if hasattr(self, action):
f = getattr(self, action)
apply(f, *args)
else:
raise BaseException("unknown action", action)
def new(self):
name = os.path.basename(self.storage.path)
msg = "\n".join([
_("Welcome to the Electrum installation wizard."),
_("The wallet '%s' does not exist.") % name,
_("What kind of wallet do you want to create?")
])
choices = [
(_('Standard wallet'), 'create_standard'),
(_('Multi-signature wallet'), 'create_multisig'),
]
self.choice_dialog(msg=msg, choices=choices, run_prev=self.cancel, run_next=self.run)
def choose_seed(self):
msg = ' '.join([
_("Do you want to create a new seed, or to restore a wallet using an existing seed?")
])
choices = [
(_('Create a new seed'), 'create_seed'),
(_('I already have a seed'), 'restore_seed'),
(_('Watching-only wallet'), 'restore_xpub')
]
self.choice_dialog(msg=msg, choices=choices, run_prev=self.new, run_next=self.run)
def create_multisig(self):
def f(m, n):
self.wallet_type = "%dof%d"%(m, n)
self.run('choose_seed')
name = os.path.basename(self.storage.path)
self.multisig_dialog(run_prev=self.new, run_next=f)
def restore_seed(self):
msg = _('Please type your seed phrase using the virtual keyboard.')
self.restore_seed_dialog(run_prev=self.new, run_next=self.enter_pin, test=Wallet.is_seed, message=msg)
def restore_xpub(self):
title = "MASTER PUBLIC KEY"
message = _('To create a watching-only wallet, paste your master public key, or scan it using the camera button.')
self.add_xpub_dialog(run_prev=self.new, run_next=lambda xpub: self.create_wallet(xpub, None), title=title, message=message, test=Wallet.is_mpk)
def create_standard(self):
self.wallet_type = 'standard'
self.run('choose_seed')
def create_wallet(self, text, password):
if self.wallet_type == 'standard':
self.wallet = Wallet.from_text(text, password, self.storage)
self.run('create_addresses')
else:
self.storage.put('wallet_type', self.wallet_type)
self.wallet = Multisig_Wallet(self.storage)
self.wallet.add_seed(text, password)
self.wallet.create_master_keys(password)
action = self.wallet.get_action()
self.run(action)
def add_cosigners(self):
xpub = self.wallet.master_public_keys.get('x1/')
self.show_xpub_dialog(run_prev=self.create_multisig, run_next=self.add_cosigner, xpub=xpub, test=Wallet.is_xpub)
def add_cosigner(self):
def on_xpub(xpub):
self.wallet.add_cosigner(xpub)
i = self.wallet.get_missing_cosigner()
action = 'add_cosigner' if i else 'create_main_account'
self.run(action)
title = "ADD COSIGNER"
message = _('Please paste your cosigners master public key, or scan it using the camera button.')
self.add_xpub_dialog(run_prev=self.add_cosigners, run_next=on_xpub, title=title, message=message, test=Wallet.is_xpub)
def create_main_account(self):
self.wallet.create_main_account()
self.run('create_addresses')
def create_addresses(self):
def task():
self.wallet.create_main_account()
self.wallet.synchronize()
msg= _("Electrum is generating your addresses, please wait.")
self.waiting_dialog(task, msg, on_complete=self.terminate)
def create_seed(self):
from electrum_ltc.wallet import BIP32_Wallet
seed = BIP32_Wallet.make_seed()
msg = _("If you forget your PIN or lose your device, your seed phrase will be the "
"only way to recover your funds.")
self.show_seed_dialog(run_prev=self.new, run_next=self.confirm_seed, message=msg, seed_text=seed)
def confirm_seed(self, seed):
assert Wallet.is_seed(seed)
msg = _('Please retype your seed phrase, to confirm that you properly saved it')
self.restore_seed_dialog(run_prev=self.create_seed, run_next=self.enter_pin, test=lambda x: x==seed, message=msg)
def enter_pin(self, seed):
def callback(pin):
action = 'confirm_pin' if pin else 'create_wallet'
self.run(action, (seed, pin))
self.password_dialog('Choose a PIN code', callback)
def confirm_pin(self, seed, pin):
def callback(conf):
if conf == pin:
self.run('create_wallet', (seed, pin))
else:
self.show_error(_('PIN mismatch'))
self.run('enter_pin', (seed,))
self.password_dialog('Confirm your PIN code', callback)
def terminate(self):
self.wallet.start_threads(self.network)
self.dispatch('on_wizard_complete', self.wallet)
def cancel(self):
self.dispatch('on_wizard_complete', None)
return True
| 40.184524 | 151 | 0.653088 |
070fb86171845062c7fc24a28acd90660006212e | 521 | py | Python | ufdl-core-app/src/ufdl/core_app/models/mixins/_UserRestrictedQuerySet.py | waikato-ufdl/ufdl-backend | 776fc906c61eba6c2f2e6324758e7b8a323e30d7 | [
"Apache-2.0"
] | null | null | null | ufdl-core-app/src/ufdl/core_app/models/mixins/_UserRestrictedQuerySet.py | waikato-ufdl/ufdl-backend | 776fc906c61eba6c2f2e6324758e7b8a323e30d7 | [
"Apache-2.0"
] | 85 | 2020-07-24T00:04:28.000Z | 2022-02-10T10:35:15.000Z | ufdl-core-app/src/ufdl/core_app/models/mixins/_UserRestrictedQuerySet.py | waikato-ufdl/ufdl-backend | 776fc906c61eba6c2f2e6324758e7b8a323e30d7 | [
"Apache-2.0"
] | null | null | null | from django.db import models
class UserRestrictedQuerySet(models.QuerySet):
"""
Query-set base class for models which apply per-instance permissions
based on the user accessing them.
"""
def for_user(self, user):
"""
Filters the query-set to those instances that the
given user is allowed to access.
:param user: The user.
:return: The filtered query-set.
"""
raise NotImplementedError(UserRestrictedQuerySet.for_user.__qualname__)
| 28.944444 | 79 | 0.658349 |
820a22153af701f5f54838c193be496175c25346 | 5,761 | py | Python | mne/channels/tests/test_interpolation.py | dokato/mne-python | a188859b57044fa158af05852bcce2870fabde91 | [
"BSD-3-Clause"
] | null | null | null | mne/channels/tests/test_interpolation.py | dokato/mne-python | a188859b57044fa158af05852bcce2870fabde91 | [
"BSD-3-Clause"
] | null | null | null | mne/channels/tests/test_interpolation.py | dokato/mne-python | a188859b57044fa158af05852bcce2870fabde91 | [
"BSD-3-Clause"
] | 1 | 2021-04-12T12:45:31.000Z | 2021-04-12T12:45:31.000Z | import os.path as op
import warnings
import numpy as np
from numpy.testing import (assert_allclose, assert_array_equal)
import pytest
from nose.tools import assert_raises, assert_equal, assert_true
from mne import io, pick_types, pick_channels, read_events, Epochs
from mne.channels.interpolation import _make_interpolation_matrix
from mne.utils import run_tests_if_main
base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
event_name = op.join(base_dir, 'test-eve.fif')
event_id, tmin, tmax = 1, -0.2, 0.5
event_id_2 = 2
def _load_data():
"""Helper function to load data."""
# It is more memory efficient to load data in a separate
# function so it's loaded on-demand
raw = io.read_raw_fif(raw_fname)
events = read_events(event_name)
picks_eeg = pick_types(raw.info, meg=False, eeg=True, exclude=[])
# select every second channel for faster speed but compensate by using
# mode='accurate'.
picks_meg = pick_types(raw.info, meg=True, eeg=False, exclude=[])[1::2]
picks = pick_types(raw.info, meg=True, eeg=True, exclude=[])
with warnings.catch_warnings(record=True): # proj
epochs_eeg = Epochs(raw, events, event_id, tmin, tmax, picks=picks_eeg,
preload=True, reject=dict(eeg=80e-6))
epochs_meg = Epochs(raw, events, event_id, tmin, tmax, picks=picks_meg,
preload=True,
reject=dict(grad=1000e-12, mag=4e-12))
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
preload=True, reject=dict(eeg=80e-6, grad=1000e-12,
mag=4e-12))
return raw, epochs, epochs_eeg, epochs_meg
@pytest.mark.slowtest
def test_interpolation():
"""Test interpolation"""
raw, epochs, epochs_eeg, epochs_meg = _load_data()
# It's a trade of between speed and accuracy. If every second channel is
# selected the tests are more than 3x faster but the correlation
# drops to 0.8
thresh = 0.80
# create good and bad channels for EEG
epochs_eeg.info['bads'] = []
goods_idx = np.ones(len(epochs_eeg.ch_names), dtype=bool)
goods_idx[epochs_eeg.ch_names.index('EEG 012')] = False
bads_idx = ~goods_idx
evoked_eeg = epochs_eeg.average()
ave_before = evoked_eeg.data[bads_idx]
# interpolate bad channels for EEG
pos = epochs_eeg._get_channel_positions()
pos_good = pos[goods_idx]
pos_bad = pos[bads_idx]
interpolation = _make_interpolation_matrix(pos_good, pos_bad)
assert_equal(interpolation.shape, (1, len(epochs_eeg.ch_names) - 1))
ave_after = np.dot(interpolation, evoked_eeg.data[goods_idx])
epochs_eeg.info['bads'] = ['EEG 012']
evoked_eeg = epochs_eeg.average()
assert_array_equal(ave_after, evoked_eeg.interpolate_bads().data[bads_idx])
assert_allclose(ave_before, ave_after, atol=2e-6)
# check that interpolation fails when preload is False
epochs_eeg.preload = False
assert_raises(ValueError, epochs_eeg.interpolate_bads)
epochs_eeg.preload = True
# check that interpolation changes the data in raw
raw_eeg = io.RawArray(data=epochs_eeg._data[0], info=epochs_eeg.info)
raw_before = raw_eeg._data[bads_idx]
raw_after = raw_eeg.interpolate_bads()._data[bads_idx]
assert_equal(np.all(raw_before == raw_after), False)
# check that interpolation fails when preload is False
for inst in [raw, epochs]:
assert hasattr(inst, 'preload')
inst.preload = False
inst.info['bads'] = [inst.ch_names[1]]
assert_raises(ValueError, inst.interpolate_bads)
# check that interpolation works with few channels
raw_few = raw.copy().crop(0, 0.1).load_data()
raw_few.pick_channels(raw_few.ch_names[:1] + raw_few.ch_names[3:4])
assert_equal(len(raw_few.ch_names), 2)
raw_few.del_proj()
raw_few.info['bads'] = [raw_few.ch_names[-1]]
orig_data = raw_few[1][0]
raw_few.interpolate_bads(reset_bads=False)
new_data = raw_few[1][0]
assert_true((new_data == 0).mean() < 0.5)
assert_true(np.corrcoef(new_data, orig_data)[0, 1] > 0.1)
# check that interpolation works when non M/EEG channels are present
# before MEG channels
with warnings.catch_warnings(record=True): # change of units
raw.rename_channels({'MEG 0113': 'TRIGGER'})
raw.set_channel_types({'TRIGGER': 'stim'})
raw.info['bads'] = [raw.info['ch_names'][1]]
raw.load_data()
raw.interpolate_bads()
# check that interpolation works for MEG
epochs_meg.info['bads'] = ['MEG 0141']
evoked = epochs_meg.average()
pick = pick_channels(epochs_meg.info['ch_names'], epochs_meg.info['bads'])
# MEG -- raw
raw_meg = io.RawArray(data=epochs_meg._data[0], info=epochs_meg.info)
raw_meg.info['bads'] = ['MEG 0141']
data1 = raw_meg[pick, :][0][0]
raw_meg.info.normalize_proj()
data2 = raw_meg.interpolate_bads(reset_bads=False)[pick, :][0][0]
assert_true(np.corrcoef(data1, data2)[0, 1] > thresh)
# the same number of bads as before
assert_true(len(raw_meg.info['bads']) == len(raw_meg.info['bads']))
# MEG -- epochs
data1 = epochs_meg.get_data()[:, pick, :].ravel()
epochs_meg.info.normalize_proj()
epochs_meg.interpolate_bads()
data2 = epochs_meg.get_data()[:, pick, :].ravel()
assert_true(np.corrcoef(data1, data2)[0, 1] > thresh)
assert_true(len(epochs_meg.info['bads']) == 0)
# MEG -- evoked
data1 = evoked.data[pick]
evoked.info.normalize_proj()
data2 = evoked.interpolate_bads().data[pick]
assert_true(np.corrcoef(data1, data2)[0, 1] > thresh)
run_tests_if_main()
| 38.66443 | 79 | 0.676619 |
6ec772cc792badf7234d4904d0df1060a1ed45e1 | 856 | py | Python | analysis/plot_provide_latencies.py | dennis-tra/optimistic-provide | 6211073e56fafb8e8f141a49b3b914c48d67d964 | [
"Apache-2.0"
] | 1 | 2021-11-15T12:37:20.000Z | 2021-11-15T12:37:20.000Z | analysis/plot_provide_latencies.py | dennis-tra/optimistic-provide | 6211073e56fafb8e8f141a49b3b914c48d67d964 | [
"Apache-2.0"
] | null | null | null | analysis/plot_provide_latencies.py | dennis-tra/optimistic-provide | 6211073e56fafb8e8f141a49b3b914c48d67d964 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import seaborn as sns
from model_loader import ModelLoader
import matplotlib.pyplot as plt
def plot():
sns.set_theme()
provide_latencies = [m.provider.duration.total_seconds() for m in ModelLoader.open("../data")]
fig, ax = plt.subplots(figsize=(15, 6))
p50 = "%.2f" % np.percentile(provide_latencies, 50)
p90 = "%.2f" % np.percentile(provide_latencies, 90)
p95 = "%.2f" % np.percentile(provide_latencies, 95)
sns.histplot(ax=ax, x=provide_latencies, bins=np.arange(0, 200, 2))
ax.set_xlabel("Time in s")
ax.set_ylabel("Count")
ax.title.set_text(f"Provide Latency Distribution (Sample Size {len(provide_latencies)}), {p50}s (p50), {p90}s (p90), {p95}s (p95)")
plt.tight_layout()
plt.savefig("../plots/provide_latencies.png")
plt.show()
if __name__ == '__main__':
plot()
| 26.75 | 135 | 0.672897 |
9367066d25f7568f63c47c8fa0df5faccbfd974a | 8,712 | py | Python | orchestrator_object.py | UWB-C4D/droneport_traffic_control | a57169e092a5b2a8303bc039f28d0b1c7460a0ef | [
"BSD-3-Clause"
] | null | null | null | orchestrator_object.py | UWB-C4D/droneport_traffic_control | a57169e092a5b2a8303bc039f28d0b1c7460a0ef | [
"BSD-3-Clause"
] | null | null | null | orchestrator_object.py | UWB-C4D/droneport_traffic_control | a57169e092a5b2a8303bc039f28d0b1c7460a0ef | [
"BSD-3-Clause"
] | null | null | null | import numpy as np
class Battery(object):
"""Battery representation in DronePort system.
It can be placed in DronePort charging/storage station or drone.
Input:
id: Battery id number
max_cap: maximum capacity of battery
current_cap: current capacity of battery
"""
def __init__(self, id=-1, max_cap=1.0, current_cap=1.0):
self.id = id
self.max_capacity = max_cap # maximum capacity of battery
# Set current capacity.
if current_cap > self.max_capacity:
self.current_capacity = self.max_capacity
else:
self.current_capacity = current_cap
def charge(self):
"""Change the battery."""
self.current_capacity = self.max_capacity
self.print(f"Battery #{self.id} charged!")
def run(self, discharge=-0.01):
"""Discharge the battery."""
if discharge < 0:
self.current_capacity = self.current_capacity + discharge
if self.current_capacity < 0:
self.current_capacity = 0
self.print(f"Battery #{self.id} is empty!")
else:
self.print(f"Wrong value for discharge: {discharge}")
class STATE:
unknown = 0
start = 1
connected = 2
upload = 3
mission = 4
backup = 5
upload_dp = 6
mission_dp = 7
land_dp = 8
swap = 9
reupload = 10
error = 15
# desc = {
# unknown: "unknown",
# start: "waiting for connection",
# connected: "heartbeat acknowledged",
# upload: "receiving new mission",
# mission: "mission in progress",
# backup: "backing up mission and saving to file",
# upload_dp: "receiving mission to DronePort",
# mission_dp: "on mission to DronePort",
# land_dp: "landing on DronePort",
# swap: "DronePort is swapping the battery",
# reupload: "receiving original mission",
# error: "some error occured"
# }
desc = {
0: "unknown",
1: "waiting for HB",
2: "Clearing mission",
3: "uploading mission",
4: "mission started",
5: "mission in progress",
6: "RTL to DronePort",
7: "wait for land DronePort",
8: "wait for battery",
15: "some error occured"
}
class Drone(object):
"""Drone uses pyMAVLink library for communication.
Also, it contains Battery object and its current mission.
"""
def __init__(self, battery=Battery(),
source_system=254, source_component=1, target_system=1, target_component=1,
max_speed=5.0, max_flight_time=15*60, location=[.0, .0, .0]):
"""Establish connection with drone using MAVLink.
Input:
address: string with IP address
port: string with PORT
battery: object of Battery class
sys_id: id of Controlling system
id: id of component
"""
self.id = target_system
self.armed = False
# State of the drone state machine
self._state = STATE.unknown
# Init mission variables
self.mission_items = []
self.time_plan = []
self.resume_item = -1
self.mission_current = -1
self.mission_count = -1
self.mission_soc = []
self.wp = []
self.out_file = f"park_drone{self.id}_short_out.pkl"
self.in_file = f"park_drone{self.id}_short.pkl"
self.max_speed = max_speed # max speed in m/s
self.max_flight_time = max_flight_time # max flight time in s
# Drone status
self.battery = battery
self.location = location
self.landed_state = -1 # -1 unknown, 1 on ground, 2 in air, 3 takeoff, 4 landing
self.verbose = False
self.lock = None
def print(self, msg):
if self.verbose:
print(f'[Drone{self.id}] {msg}')
self.status_msg = msg
def fly2point(self, coordinates=[0, 0, 0], discharge=0.1):
self.location = coordinates
self.battery.run(discharge)
print(f'new coordinates: {self.location}')
def reset_battery(self):
"""Reset simulation of battery in drone."""
self.print('Reset battery requested')
self.battery.charge()
def new_mission(self, mission_items, time_plan, current=0):
"""
Assign a new mission to the drone and update additional variables accordingly.
For correct evaluation, the initial position of drone is included into the mission list.
"""
self.mission_items = np.vstack((self.location, mission_items))
self.time_plan = np.vstack((self.distance2time_arr(
self.distance(self.location[0], mission_items[0])), time_plan))
self.mission_current = current
self.mission_count = self.mission_items.shape[0]
self.mission_soc = self.time2soc()
def gen_circ_mission(self, t_max=10*60, samples=100, x=0, y=0, r_x=10, r_y=10):
"""
Return mission and time vector with random points given on ellipse.
Ellipse is given by its center x,y and radius r_x, r_y.
Time vector is randomly generated with given samples and t_max as max value.
"""
time = np.sort(t_max*np.random.random((samples, 1)), axis=0)
mission = np.hstack((r_x*np.cos(time)+x, r_y*np.sin(time)+y))
self.new_mission(mission, time)
return mission, time
def gen_circ_rand_mission(self, samples=100, min_r=10, var_r=10):
"""
Return mission and time vector with random points random on ellipse.
Ellipse is given by the location of drone in center x,y and random radius generated on interval [min_r, min_r+var_r].
Time vector is randomly generated with given samples and drone max flight time as max value.
"""
mission, time = self.gen_circ_mission(t_max=2.0*self.max_flight_time, samples=samples, x=self.location[0, 0],
y=self.location[0, 1], r_x=var_r*np.random.random()+min_r, r_y=var_r*np.random.random()+min_r)
return mission, time
def distance2time_arr(self, distance):
"""
Convert distance [m] array arr to time [s] array according to speed [m/s]
and return a time vector.
"""
return distance/self.max_speed
def time2soc(self):
"""
Returns State-of-Charge (SoC) [0-1] decrease based on mission flight time intervals
and maximum flight time [s] (when SoC is 1.0).
"""
return np.hstack((0, np.diff(self.time_plan[:, 0]/self.max_flight_time)))
def distance(self, a, b):
"""
Return euclidian distance between point a and b.
"""
return np.linalg.norm(b-a, 2)
def distances2point(self, point):
"""
Return euclidian distance between waipoints array and point.
waypoints: points are in rows of array
"""
d = np.zeros((self.mission_items.shape[0], 1))
for i, elem in enumerate(self.mission_items):
d[i] = self.distance(elem, point)
return d
def soc_and_time2point(self, point):
"""
Return State-of-Charge (SoC) [0-1] decrease array caused by travel from waypoint to point.
"""
d = self.distances2point(point)
t = self.distance2time_arr(d)
soc = t/self.max_flight_time
return soc, t
class Droneport(object):
"""DronePort landing platform with smart charging station and robotic manipulator.
Input:
drone: link to Drone object which occupies the DronePort
batteries: present batteries
sys_id: id of Controlling system
id: id of DronePort
location: array with latitude, longitude, altitude in degrees and meters
slots: number of slots
"""
def __init__(self, drone=None, batteries=None,
source_system=254, source_component=1, target_system=201, target_component=1, location=[.0, .0, .0],
slots=3, swap_time = 60):
self.sys_id = source_system
self.comp_id = source_component
self.id = target_system
# geo coordinates: latitude, longitude, altitude in degrees and meters
self.location = location
self.drone = drone # boolean value: Drone object occupying DronePort landing platform
self.batteries = batteries # array with Battery objects
self.slots = slots # number of DronePort battery slots
self.swap_status = 0
self.schedule = [] # time schedule for battery swapping
self.swap_time = swap_time # time needed for swapping the drone's battery
| 34.987952 | 140 | 0.613292 |
be192229bbc68180976a518419ad726550e6fb74 | 6,913 | py | Python | minihack/agent/common/models/embed.py | samvelyan/minihack-1 | 441eba33ba0d240b98aeabe1ff7a0c0b33cd236c | [
"Apache-2.0"
] | 217 | 2021-09-28T01:40:39.000Z | 2022-03-22T15:12:23.000Z | minihack/agent/common/models/embed.py | samvelyan/minihack-1 | 441eba33ba0d240b98aeabe1ff7a0c0b33cd236c | [
"Apache-2.0"
] | 10 | 2021-10-01T14:10:47.000Z | 2022-02-28T15:37:08.000Z | minihack/agent/common/models/embed.py | samvelyan/minihack-1 | 441eba33ba0d240b98aeabe1ff7a0c0b33cd236c | [
"Apache-2.0"
] | 24 | 2021-09-28T06:43:34.000Z | 2022-03-24T06:13:43.000Z | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from torch import nn
import torch
from nle import nethack as nh
from typing import NamedTuple, Union
from collections import namedtuple
from minihack.agent.common.util.id_pairs import id_pairs_table
import logging
Ratio = Union[int, bool]
class Targets(NamedTuple):
"""Class for configuring whch ids you want to embed into the single
GlyphEmbedding, and in what ratios. The ratio is only relevant if
do_linear_layer is false, and the embedding is pure concatenation.
"""
glyphs: Ratio = 0
groups: Ratio = 0
subgroup_ids: Ratio = 0
colors: Ratio = 0
chars: Ratio = 0
specials: Ratio = 0
do_linear_layer: bool = True
def count_matrices(self):
"""Count of matrices required"""
return sum(self) - int(self.do_linear_layer)
GLYPH_TYPE_STRATEGIES = {
"full": Targets(glyphs=True),
"group_id": Targets(groups=True, subgroup_ids=True),
"color_char": Targets(colors=True, chars=True, specials=True),
"all": Targets(
groups=True, subgroup_ids=True, colors=True, chars=True, specials=True
),
"all_cat": Targets(
groups=1,
subgroup_ids=3,
colors=1,
chars=2,
specials=1,
do_linear_layer=False,
),
}
class GlyphEmbedding(nn.Module):
"""Take the glyph information and return an embedding vector."""
def __init__(
self, glyph_type, dimension, device=None, use_index_select=None
):
super(GlyphEmbedding, self).__init__()
logging.debug("Emdedding on device: %s ", device)
self.glyph_type = glyph_type
self.use_index_select = use_index_select
self.device = device
self.dim = dimension
if glyph_type not in GLYPH_TYPE_STRATEGIES:
raise RuntimeError("unexpected glyph_type=%s" % self.glyph_type)
strategy = GLYPH_TYPE_STRATEGIES[glyph_type]
self.strategy = strategy
self._unit_dim = dimension // strategy.count_matrices()
self._remainder_dim = (
self.dim - self._unit_dim * strategy.count_matrices()
)
if self.requires_id_pairs_table:
self.register_buffer(
"_id_pairs_table", torch.from_numpy(id_pairs_table())
)
else:
self._id_pairs_table = None
# Build our custom embedding matrices
embed = {}
if strategy.glyphs:
embed["glyphs"] = nn.Embedding(
nh.MAX_GLYPH, self._dim(strategy.glyphs)
)
if strategy.colors:
embed["colors"] = nn.Embedding(16, self._dim(strategy.colors))
if strategy.chars:
embed["chars"] = nn.Embedding(256, self._dim(strategy.chars))
if strategy.specials:
embed["specials"] = nn.Embedding(256, self._dim(strategy.specials))
if strategy.groups:
num_groups = self.id_pairs_table.select(1, 1).max().item() + 1
embed["groups"] = nn.Embedding(
num_groups, self._dim(strategy.groups)
)
if strategy.subgroup_ids:
num_subgroup_ids = (
self.id_pairs_table.select(1, 0).max().item() + 1
)
embed["subgroup_ids"] = nn.Embedding(
num_subgroup_ids, self._dim(strategy.subgroup_ids)
)
self.embeddings = nn.ModuleDict(embed)
self.targets = list(embed.keys())
self.GlyphTuple = namedtuple("GlyphTuple", self.targets)
if strategy.do_linear_layer and strategy.count_matrices() > 1:
self.linear = nn.Linear(
strategy.count_matrices() * self.dim, self.dim
)
if device is not None:
self.to(device)
def _dim(self, units):
"""Decide the embedding size for a single matrix. If using a linear layer
at the end this is always the embedding dimension, otherwise it is a
fraction of the embedding dim"""
if self.strategy.do_linear_layer:
return self.dim
else:
dim = units * self._unit_dim + self._remainder_dim
self._remainder_dim = 0
return dim
@property
def requires_id_pairs_table(self):
return self.strategy.groups or self.strategy.subgroup_ids
@property
def id_pairs_table(self):
return self._id_pairs_table
def prepare_input(self, inputs):
"""Take the inputs to the network as dictionary and return a namedtuple
of the input/index tensors to be embedded (GlyphTuple)"""
embeddable_data = {}
# Only flatten the data we want
for key, value in inputs.items():
if key in self.embeddings:
# -- [ T x B x ...] -> [ B' x ... ]
embeddable_data[key] = torch.flatten(value, 0, 1).long()
# add our group id and subgroup id if we want them
if self.requires_id_pairs_table:
ids, groups = self.glyphs_to_idgroup(inputs["glyphs"])
embeddable_data["groups"] = groups
embeddable_data["subgroup_ids"] = ids
# convert embeddable_data to a named tuple
return self.GlyphTuple(**embeddable_data)
def forward(self, data_tuple):
"""Output the embdedded tuple prepared in in prepare input. This will be
a GlyphTuple."""
embs = []
for field, data in zip(self.targets, data_tuple):
embs.append(self._select(self.embeddings[field], data))
if len(embs) == 1:
return embs[0]
embedded = torch.cat(embs, dim=-1)
if self.strategy.do_linear_layer:
embedded = self.linear(embedded)
return embedded
def _select(self, embedding_layer, x):
if self.use_index_select:
out = embedding_layer.weight.index_select(0, x.view(-1))
# handle reshaping x to 1-d and output back to N-d
return out.view(x.shape + (-1,))
else:
return embedding_layer(x)
def glyphs_to_idgroup(self, glyphs):
T, B, H, W = glyphs.shape
ids_groups = self.id_pairs_table.index_select(
0, glyphs.view(-1).long()
)
ids = ids_groups.select(1, 0).view(T * B, H, W).long()
groups = ids_groups.select(1, 1).view(T * B, H, W).long()
return (ids, groups)
| 34.738693 | 82 | 0.623318 |
15f0123bc12372a4b42e7ac32923581c33b93a47 | 3,930 | py | Python | kuryr/tests/unit/segmentation_type_drivers/test_vlan.py | mail2nsrajesh/kuryr | df421a9b2e743f00ac27c030e5094f784f72599a | [
"Apache-2.0"
] | null | null | null | kuryr/tests/unit/segmentation_type_drivers/test_vlan.py | mail2nsrajesh/kuryr | df421a9b2e743f00ac27c030e5094f784f72599a | [
"Apache-2.0"
] | null | null | null | kuryr/tests/unit/segmentation_type_drivers/test_vlan.py | mail2nsrajesh/kuryr | df421a9b2e743f00ac27c030e5094f784f72599a | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
from oslo_config import cfg
from six import moves
from kuryr.lib import constants as const
from kuryr.lib import exceptions
from kuryr.tests.unit import base
from kuryr.lib.segmentation_type_drivers import vlan
class VlanSegmentationDriverTest(base.TestCase):
"""Unit tests for VLAN segmentation driver."""
def setUp(self):
super(VlanSegmentationDriverTest, self).setUp()
cfg.CONF.binding.driver = 'kuryr.lib.binding.drivers.vlan'
def test_allocate_segmentation_id(self):
vlan_seg_driver = vlan.SegmentationDriver()
allocated_ids = set([1, 2, 3])
vlan_id = vlan_seg_driver.allocate_segmentation_id(allocated_ids)
self.assertNotIn(vlan_id, vlan_seg_driver.available_local_vlans)
self.assertNotIn(allocated_ids, vlan_seg_driver.available_local_vlans)
def test_allocate_segmentation_id_only_1_available(self):
vlan_seg_driver = vlan.SegmentationDriver()
allocated_ids = set(moves.range(const.MIN_VLAN_TAG,
const.MAX_VLAN_TAG + 1))
allocated_ids.remove(const.MAX_VLAN_TAG)
vlan_id = vlan_seg_driver.allocate_segmentation_id(allocated_ids)
self.assertNotIn(vlan_id, vlan_seg_driver.available_local_vlans)
self.assertNotIn(allocated_ids, vlan_seg_driver.available_local_vlans)
self.assertEqual(vlan_id, const.MAX_VLAN_TAG)
def test_allocate_segmentation_id_no_allocated_ids(self):
vlan_seg_driver = vlan.SegmentationDriver()
vlan_id = vlan_seg_driver.allocate_segmentation_id()
self.assertNotIn(vlan_id, vlan_seg_driver.available_local_vlans)
def test_allocate_segmentation_id_no_available_vlans(self):
vlan_seg_driver = vlan.SegmentationDriver()
allocated_ids = set(moves.range(const.MIN_VLAN_TAG,
const.MAX_VLAN_TAG + 1))
self.assertRaises(exceptions.SegmentationIdAllocationFailure,
vlan_seg_driver.allocate_segmentation_id,
allocated_ids)
@mock.patch('random.choice')
def test_allocate_segmentation_id_max_retries(self, mock_choice):
mock_choice.side_effect = [1, 1, 1]
vlan_seg_driver = vlan.SegmentationDriver()
allocated_ids = set([1, 2, 3])
self.assertRaises(exceptions.SegmentationIdAllocationFailure,
vlan_seg_driver.allocate_segmentation_id,
allocated_ids)
self.assertEqual(len(mock_choice.mock_calls), 3)
@mock.patch('random.choice')
def test_allocate_segmentation_id_2_retries(self, mock_choice):
vlan_seg_driver = vlan.SegmentationDriver()
vlan_seg_driver.available_local_vlans = set(moves.range(1, 10))
allocated_ids = set([1, 2, 3])
mock_choice.side_effect = [1, 1, 5]
vlan_id = vlan_seg_driver.allocate_segmentation_id(allocated_ids)
self.assertEqual(len(mock_choice.mock_calls), 3)
self.assertEqual(vlan_id, 5)
def test_release_segmentation_id(self):
vlan_seg_driver = vlan.SegmentationDriver()
vlan_seg_driver.available_local_vlans = set(moves.range(1, 10))
vlan_id = 20
vlan_seg_driver.release_segmentation_id(vlan_id)
self.assertIn(vlan_id, vlan_seg_driver.available_local_vlans)
| 39.3 | 78 | 0.716031 |
d4df4869bcb0378b20bd2ed0f8e7237de841c74f | 7,022 | py | Python | examples/Al__eam__born_exp_fs/pareto_optimization_3.5NN/make_new_parallel_coordinates_plot.py | eragasa/pypospack | 21cdecaf3b05c87acc532d992be2c04d85bfbc22 | [
"MIT"
] | 4 | 2018-01-18T19:59:56.000Z | 2020-08-25T11:56:52.000Z | examples/Al__eam__born_exp_fs/pareto_optimization_3.5NN/make_new_parallel_coordinates_plot.py | eragasa/pypospack | 21cdecaf3b05c87acc532d992be2c04d85bfbc22 | [
"MIT"
] | 1 | 2018-04-22T23:02:13.000Z | 2018-04-22T23:02:13.000Z | examples/Al__eam__born_exp_fs/pareto_optimization_3.5NN/make_new_parallel_coordinates_plot.py | eragasa/pypospack | 21cdecaf3b05c87acc532d992be2c04d85bfbc22 | [
"MIT"
] | 1 | 2019-09-14T07:04:42.000Z | 2019-09-14T07:04:42.000Z | import copy,os
import numpy as np
import pandas as pd
from collections import OrderedDict
from pypospack.pyposmat.data import PyposmatDataFile
from pypospack.pyposmat.data import PyposmatConfigurationFile
results_PunMishin2015 = OrderedDict([
('sim_id','PunMishin2015'),
('Al_fcc.E_coh', -4.449999985713825),
('Al_fcc.a0', 3.52000004514173),
('Al_fcc.c11', 241.341629134211),
('Al_fcc.c12', 150.824244634751),
('Al_fcc.c44', 127.34413217099),
('Al_fcc.B', 180.996706134571),
('Al_fcc.G', 45.25869224972999),
('Al_fcc.vac', 1.5722909444763218),
('Al_fcc.100s', 0.12083783763315925),
('Al_fcc.110s', 0.1306411055698218),
('Al_fcc.111s', 0.1097944617790805),
('Al_fcc.esf', 4.50280507300032e-14),
('Al_fcc.isf', 0.008398360367557003),
('E_Al_fcc_hcp', 0.02213171443965045),
('E_Al_fcc_bcc', 0.06728584869762066),
('E_Al_fcc_sc', 0.7235998449031951),
('E_Al_fcc_dia', 1.4164289731208752)
])
results_Mishin1999 = OrderedDict([
('sim_id','Mishin1999'),
('Ni_fcc.E_coh', -4.449999998348875),
('Ni_fcc.a0', 3.51999943754043),
('Ni_fcc.c11', 247.862330912402),
('Ni_fcc.c12', 147.828379828392),
('Ni_fcc.c44', 124.838117591868),
('Ni_fcc.B', 181.17303018972868),
('Ni_fcc.G', 50.016975542005),
('Ni_fcc.vac', 1.601066770918635),
('Ni_fcc.100s', 0.11721226280222584),
('Ni_fcc.110s', 0.12813990050511612),
('Ni_fcc.111s', 0.10172841614230631),
('Ni_fcc.esf', -4.502806627505237e-14),
('Ni_fcc.isf', 0.007813859904327118),
('E_Ni_fcc_hcp', 0.020438536006599506),
('E_Ni_fcc_bcc', 0.11199380635944944),
('E_Ni_fcc_sc', 0.8330381769486048),
('E_Ni_fcc_dia', 0.010588663471387427)
])
results_Angelo1995 = OrderedDict([
('sim_id','Angelo1995'),
('Ni_fcc.E_coh', -4.4500000125938),
('Ni_fcc.a0', 3.52000035011041),
('Ni_fcc.c11', 246.715158886758),
('Ni_fcc.c12', 147.480621905903),
('Ni_fcc.c44', 124.960604806714),
('Ni_fcc.B', 180.55880089952134),
('Ni_fcc.G', 49.61726849042749),
('Ni_fcc.vac', 1.5938793445586157),
('Ni_fcc.100s', 0.1285743493399689),
('Ni_fcc.110s', 0.14781220704975925),
('Ni_fcc.111s', 0.12040311031473264),
('Ni_fcc.esf', 2.648708409963305e-15),
('Ni_fcc.isf', 0.005525903822777186),
('E_Ni_fcc_hcp', 0.012563864102899558),
('E_Ni_fcc_bcc', 0.07640412576407485),
('E_Ni_fcc_sc', 0.47501015461552987),
('E_Ni_fcc_dia', 0.012563864102899558)
])
ref_data = OrderedDict()
ref_data['PunMishin2015'] = results_PunMishin2015
# ref_data['Mishin1999'] = results_Mishin1999
# ref_data['Angelo1995'] = results_Angelo1995
ref_data_colors = OrderedDict()
ref_data_colors['PunMishin2015']= 'red'
# ref_data_colors['Mishin1999'] = 'blue'
# ref_data_colors['Angelo1995'] = 'green'
class PyposmatParallelCoordinates(object):
pass
if __name__ == "__main__":
# define the data directory
data_directory = 'data/no_hcp_positive_isf'
#data_directory = 'data/no_hcp_negative_isf'
# read configuration file
config_fn = os.path.join(data_directory,'pyposmat.config.in')
config=PyposmatConfigurationFile()
config.read(filename=config_fn)
# read the associated datafile
datafile_fn = os.path.join(data_directory,'pyposmat.kde.7.out')
datafile=PyposmatDataFile()
datafile.read(filename=datafile_fn)
plot_fn = 'parallelcoordinates_fs.png'
excluded_qoi_names = ['Al_fcc.esf', 'E_Al_fcc_hcp']
qoi_names = [q for q in config.qoi_names if q not in excluded_qoi_names]
print('qoi_names is length:{}'.format(len(qoi_names)))
error_names = ["{}.err".format(q) for q in qoi_names]
normed_error_names = ["{}.nerr".format(q) for q in qoi_names]
qoi_targets = config.qoi_targets
# calculate normalized error for sampled data
for iqn,qn in enumerate(qoi_names):
en = "{}.err".format(qn)
nen = "{}.nerr".format(qn)
q = qoi_targets[qn]
datafile.df[nen] = datafile.df[qn]/q-1
(nrows,ncols) = datafile.df.shape
normederr_names = ['{}.nerr'.format(q) for q in qoi_names]
datafile.df['d_metric'] = np.sqrt(np.square(datafile.df[normederr_names]).sum(axis=1))
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from pandas.plotting import parallel_coordinates
fig, ax = plt.subplots()
reference_df = pd.DataFrame(list(ref_data.values()))
for iqn,qn in enumerate(qoi_names):
en = "{}.err".format(qn)
nen = "{}.nerr".format(qn)
q = qoi_targets[qn]
reference_df[nen] = reference_df[qn]/q-1
reference_df.set_index('sim_id')
data_df = copy.deepcopy(datafile.df)
data_df.set_index('sim_id')
subselect_df = datafile.df.nsmallest(10,'d_metric')
subselect_df.set_index('sim_id')
is_plot_all_data = True
if is_plot_all_data:
parallel_coordinates(
data_df[normed_error_names],
'Al_fcc.E_coh.nerr',
color='grey'
)
parallel_coordinates(
subselect_df[normed_error_names],
'Al_fcc.E_coh.nerr',
color='k'
)
parallel_coordinates(
reference_df[normed_error_names],
'Al_fcc.E_coh.nerr',
)
plt.gca().legend_.remove()
#fig.savefig(plot_fn)
plt.xticks(rotation=80)
plt.tight_layout()
plt.show()
exit()
(nr,nc)=df.shape
print("We have {} potentials...".format(nr))
for iqn,qn in enumerate(qoi_names):
nen = '{}.nerr'.format(qn)
x = df[nen]
y = nr*[len(qoi_names)-iqn]
ax.scatter(x,y,
marker='|',
#s=10.,
color='grey')
for ref_data_name,ref_data_dict in ref_data.items():
for iqn,qn in enumerate(qoi_names):
q = qoi_targets[qn]
x = ref_data_dict[qn]/q-1
y = len(qoi_names)-iqn
ax.scatter(
x,
y,
s=300,
marker='|',
color=ref_data_colors[ref_data_name]
)
plt.axvline(0,color='k',linestyle='-',linewidth=.1)
ax.set_xlabel('Pct Error Difference')
yticks_labels = [config.latex_labels[qn]['name'] for qn in qoi_names]
print("length of yticks_labels:{}".format(len(yticks_labels)))
plt.sca(ax)
plt.yticks(
list(range(1,len(qoi_names)+1)),
list(reversed(yticks_labels))
)
#vals = ax.get_xticks()
#ax.set_xticklabels(
# ['{:.1%}'.format(int(x*100)) for x in vals]
# )
ax.set_xlim([-1,1])
ax.set_ylim([0,len(qoi_names)+1])
ax.legend(
handles = [
mpatches.Patch(
color=ref_data_colors[ref_data_name],
label=ref_data_name)
for ref_data_name in ref_data
] + [
mpatches.Patch(
color='grey',
label='best 50')
]
)
plt.show()
fig.savefig(plot_fn)
exit()
| 32.063927 | 90 | 0.627741 |
467d0521b6727d3af9a5c01bf15a0794e0321445 | 191 | py | Python | Thoron/thoron/auth/views.py | lvnar/Thorondor | b2d2887548c6ad8e00e1a872f0cb522e3a54f598 | [
"MIT"
] | null | null | null | Thoron/thoron/auth/views.py | lvnar/Thorondor | b2d2887548c6ad8e00e1a872f0cb522e3a54f598 | [
"MIT"
] | null | null | null | Thoron/thoron/auth/views.py | lvnar/Thorondor | b2d2887548c6ad8e00e1a872f0cb522e3a54f598 | [
"MIT"
] | null | null | null | from rest_framework.authentication import TokenAuthentication
from rest_auth.views import LogoutView
class CustomLogoutView(LogoutView):
authentication_classes = (TokenAuthentication,)
| 27.285714 | 61 | 0.853403 |
f49bebe46a7b91e86ab26a44c93c2d8d8d08a5c6 | 1,025 | py | Python | lib/dyson/keywords/__init__.py | luna-test/luna | 6d94439f2747daf96e295837684bdc6607f507dc | [
"Apache-2.0"
] | 3 | 2018-05-21T14:35:11.000Z | 2021-03-25T12:32:25.000Z | lib/dyson/keywords/__init__.py | dyson-framework/dyson | e5a2e12c7bb0ba21ff274feff34c184576d08ff5 | [
"Apache-2.0"
] | 13 | 2018-05-22T01:01:08.000Z | 2018-09-16T22:12:10.000Z | lib/dyson/keywords/__init__.py | luna-test/luna | 6d94439f2747daf96e295837684bdc6607f507dc | [
"Apache-2.0"
] | 1 | 2018-05-21T14:35:17.000Z | 2018-05-21T14:35:17.000Z | import glob
import os
from dyson.vars import merge_dict
def load_keywords(keywords_path=None):
all_keywords = dict()
keyword_paths = (
os.path.abspath("/etc/dyson/keywords"),
os.path.abspath(os.path.join(os.path.dirname(os.path.curdir), "keywords"))
)
if keywords_path is not None:
all_keywords = merge_dict(load_keywords(), _load_keywords_from_path(keywords_path))
else:
for keyword_path in keyword_paths:
all_keywords = merge_dict(all_keywords, _load_keywords_from_path(keyword_path))
return all_keywords
def _load_keywords_from_path(keywords_path):
all_keywords = dict()
if os.path.exists(keywords_path) and os.path.isdir(keywords_path):
for filename in glob.iglob("%s/**" % keywords_path, recursive=True):
if os.path.isfile(filename):
keyword_to_load = os.path.basename(os.path.splitext(filename)[0])
all_keywords[keyword_to_load] = os.path.abspath(filename)
return all_keywords
| 30.147059 | 91 | 0.693659 |
c6b65a205635f5147b9bedb2d9c18b572bb9705c | 48,093 | py | Python | spts/utils/eval.py | FilipeMaia/spts | de4eb2920b675537da611c7301d4d5a9565a1ab1 | [
"BSD-2-Clause"
] | null | null | null | spts/utils/eval.py | FilipeMaia/spts | de4eb2920b675537da611c7301d4d5a9565a1ab1 | [
"BSD-2-Clause"
] | 5 | 2021-03-26T11:37:40.000Z | 2021-03-31T09:20:40.000Z | spts/utils/eval.py | FilipeMaia/spts | de4eb2920b675537da611c7301d4d5a9565a1ab1 | [
"BSD-2-Clause"
] | 1 | 2021-03-24T11:07:41.000Z | 2021-03-24T11:07:41.000Z | import os
import numpy as np
import h5py
import scipy.interpolate
import itertools
import requests
from distutils.version import LooseVersion
import logging
logger = logging.getLogger('spts')
from matplotlib import pyplot as pypl
from matplotlib.patches import Circle
from matplotlib.colors import LogNorm
import seaborn as sns
sns.set_style("white")
import spts
from spts import config
adu_per_photon = {"Hamamatsu-C11440-22CU": 2.13}
pixel_size = {"Hamamatsu-C11440-22CU": 6.5E-6,
"Fastcam": 20E-6}
# Transmissions at
filter_transmission_530 = {
"": 1.,
"ND060": 21.18E-2,
"ND090": 9.69E-2,
"ND200": 0.97E-2,
"ND300": 0.13E-2,
"ND400": 0.01E-2,
}
evergreen_pulse_energy_L1 = {
1: 8.20,
2: 11.92,
3: 16.28,
4: 21.08,
5: 25.80,
6: 30.72,
7: 36.52,
8: 42.64,
9: 48.52,
10: 56.07,
11: 61.82,
12: 66.98,
13: 72.29,
14: 78.47,
15: 84.07,
16: 91.20,
17: 98.55,
18: 104.36,
19: 109.60,
20: 116.87,
}
evergreen_pulse_energy_L2 = {
1: 7.20,
2: 11.20,
3: 15.04,
4: 19.48,
5: 24.88,
6: 30.76,
7: 35.72,
8: 41.52,
9: 47.68,
10: 51.35,
11: 59.64,
12: 66.11,
13: 72.00,
14: 78.40,
15: 84.51,
16: 91.56,
17: 98.33,
18: 103.64,
19: 109.75,
20: 116.87,
}
PS_diameters_true = {
20: 23.,
40: 41.,
60: 60.,
70: 70.,
80: 81.,
100: 100.,
125: 125.,
220: 216.,
495: 496.,
}
PS_diameters_uncertainties = {
20: 2.,
40: 4.,
60: 4.,
70: 3.,
80: 3.,
100: 3.,
125: 3.,
220: 4.,
495: 8.,
}
PS_diameters_spread = {
20: None,
40: None,
60: 10.2,
70: 7.3,
80: 9.5,
100: 7.8,
125: 4.5,
220: 5.,
495: 8.6,
}
# http://www.thinksrs.com/downloads/PDFs/ApplicationNotes/IG1pggasapp.pdf
_p_N_reading = [1.33322,
2.66644,
3.99966,
5.33288,
6.6661,
7.99932,
9.33254,
10.66576,
11.99898,
13.3322,
14.66542]
_p_He_actual = [1.33322*1.1,
2.133152,
2.66644,
3.199728,
3.599694,
3.733016,
3.99966,
4.132982,
4.266304,
4.799592,
6.6661]
p_He = lambda p_N_reading: (np.where(p_N_reading < 1.33322, 1.1 * p_N_reading, np.interp(p_N_reading, _p_N_reading, _p_He_actual)))
#pix_to_um = lambda x, navitar_zoom, objective_zoom_factor, pixel_size: x * (5./objective_zoom_factor) * 7.2E-3*np.exp(-navitar_zoom/3714.)/1024. * (pixel_size/20E-6)
# All in unit meter
def pix_to_m(camera_pixel_size, navitar_zoom, objective_zoom_factor):
# Navitar Zoom Calibration. 5x Mitituyo objective insidet the vacuum chamber, coupled to outside navitar zoom lens connected to the fastcam.
z_vs_p = np.array([[0, 7.0423E-6],
[1000, 5.3957E-6],
[2000, 4.1322E-6],
[3000, 3.112E-6],
[4000, 2.3659E-6],
[4600, 2.0202E-6],
[5000, 1.8007E-6],
[6000, 1.4045E-6],
[7000, 1.0593E-6],
[8000, 0.8104E-6],
[8923, 0.6313E-6]])
p = np.interp(navitar_zoom, z_vs_p[:,0], z_vs_p[:,1])
# Correct for different objective if necessary
p *= 5./objective_zoom_factor
# Correct for different camera pixel size if necessary
p *= camera_pixel_size/20.E-6
return p
def read_datasets_table_old(filename, D=None):
if D is None:
D = {}
with open(filename, "r") as f:
lines = f.readlines()
if len(lines) > 1:
pass
# lines = [l[:-1] for l in lines]
else:
lines = lines[0].split("\r")
titles = lines[0].split(",")
# Remove newline in last title
titles[-1] = titles[-1][:-1]
data_lines = lines[1:]
for l in data_lines:
L = l.split(",")
# Remove newline in last item
L[-1] = L[-1][:-1]
name = L[titles.index("File")]
D[name] = {}
for t,d in zip(titles, L):
D[name][t] = d
return D
def read_datasets_table(filename=None, D=None, iddate=False):
# Read from www or file
if filename is None:
document_id = "1mPW6QQLEtdYdEtvMktHsFL25FxNpozOXKRr6ibfrZnA"
gid = "2081833535"
url = "https://docs.google.com/spreadsheets/d/%s/export?format=tsv&gid=%s" % (document_id, gid)
with requests.Session() as s:
download = s.get(url)
decoded_content = download.content.decode('utf-8')
lines = decoded_content.split("\n")
else:
with open(filename, "r") as f:
lines = f.readlines()
# Initialise if necessary
if D is None:
D = {}
# Clean up lines
lines = [l for l in lines if l[0] != "#"]
if len(lines) > 1:
for i in range(len(lines)):
while (lines[i].endswith("\n") or lines[i].endswith(" ") or lines[i].endswith("\r")):
lines[i] = lines[i][:-1]
else:
lines = lines[0].split("\r")
# Titles
titles = lines[0].split("\t")
for l in lines[1:3]:
for i,s in enumerate(l.split("\t")):
if len(s) > 0:
titles[i] += " " + s
# Interpret data type of all data fields and write into dict
data_lines = lines[3:]
for l in data_lines:
L = l.split("\t")
name = L[titles.index("File")]
if iddate:
name += "_" + L[titles.index("Date")]
D[name] = {}
for t,d in zip(titles, L):
D[name][t] = estimate_type(d)
return D
def find_datasets(D, option_name, option_value, decimals_precision=None):
found_dataset_names = []
for k,Dk in D.items():
if option_name not in Dk:
logger.error("Cannot find %s in D[%s]. Abort." % (option_name, k))
return
if (decimals_precision is None and Dk[option_name] == option_value) or \
(decimals_precision is not None and (round(Dk[option_name], decimals_precision) == round(option_value, decimals_precision))):
found_dataset_names.append(k)
return found_dataset_names
def sort_datasets(D, option_name):
values = []
keys_list = D.keys()
for k in keys_list:
Dk = D[k]
if option_name not in Dk:
logger.error("Cannot find %s in D[%s]. Abort." % (option_name, k))
return
values.append(Dk[option_name])
return [keys_list[i] for i in np.array(values).argsort()]
def estimate_type(var):
#first test bools
if var.lower() == 'true':
return True
elif var.lower() == 'false':
return False
elif var.lower() == 'none':
return None
else:
#int
try:
return int(var)
except ValueError:
pass
#float
try:
return float(var)
except ValueError:
pass
#string
try:
return str(var)
except ValueError:
raise NameError('Something messed up autocasting var %s (%s)' % (var, type(var)))
def read_data(D, root_dir="/scratch/fhgfs/hantke/spts", only_scalars=False, skip_thumbnails=True, verbose=True, data_prefix="", iddate=False):
ds_names = D.keys()
ds_names.sort()
for ds_name in ds_names:
D[ds_name] = read_data_single(ds_name, D[ds_name], root_dir=root_dir, only_scalars=only_scalars,
skip_thumbnails=skip_thumbnails, verbose=verbose, data_prefix=data_prefix, iddate=iddate)
return D
def read_data_single(ds_name, D, root_dir="/scratch/fhgfs/hantke/spts", only_scalars=False, skip_thumbnails=True, verbose=True, data_prefix="", iddate=False):
if iddate:
fn_root = ds_name.split("_")[0]
else:
fn_root = ds_name
if "Data Location" not in D.keys():
folder = "%s%s/%s/%s_analysis" % (data_prefix, root_dir, D["Date"], fn_root)
else:
folder = "%s%s/%s_analysis" % (data_prefix, D["Data Location"], fn_root)
D["filename"] = "%s/spts.cxi" % folder
D["conf_filename"] = "%s/spts.conf" % folder
if not os.path.isfile(D["filename"]):
if verbose:
print("Skipping %s - file does not exist" % D["filename"])
else:
# Read data
with h5py.File(D["filename"], "r") as f:
version = '0.0.1' if '__version__' not in f else str(f['__version__'])
if LooseVersion(version) > LooseVersion('0.0.1'):
t_raw = "1_raw"
t_process = "2_process"
t_process_image = "image"
t_denoise = "3_denoise"
t_threshold = "4_threshold"
t_detect = "5_detect"
t_analyse = "6_analyse"
t_peak_prefix = "peak_"
t_detect_dist_neighbor = "dist_neighbor"
t_dislocation = "dislocation"
else:
t_raw = "1_measure"
t_process = "1_measure"
t_process_image = "image"
t_denoise = "1_measure"
t_threshold = "1_measure"
t_detect = "2_detect"
t_analyse = "3_analyse"
t_peak_prefix = ""
t_detect_dist_neighbor = "dists_neighbor"
t_dislocation = None
D["sat_n"] = np.asarray(f["/%s/saturated_n_pixels" % t_raw])
D["x"] = np.asarray(f["/%s/x" % t_detect])
D["y"] = np.asarray(f["/%s/y" % t_detect])
sel = (D["x"] >= 0) * (D["y"] >= 0)
D["area"] = np.asarray(f["/%s/area" % t_detect])
D["circumference"] = np.asarray(f["/%s/%scircumference" % (t_analyse, t_peak_prefix)])
D["eccentricity"] = np.asarray(f["/%s/%seccentricity" % (t_analyse, t_peak_prefix)])
D["dists_neighbor"] = np.asarray(f["/%s/%s" % (t_detect, t_detect_dist_neighbor)])
D["sum"] = np.asarray(f["/%s/%ssum" % (t_analyse, t_peak_prefix)])
D["saturated"] = np.asarray(f["/%s/%ssaturated" % (t_analyse, t_peak_prefix)])
if t_dislocation is not None:
if ("/%s/%s" % (t_detect, t_dislocation)) in f:
D["dislocation"] = np.asarray(f["/%s/%s" % (t_detect, t_dislocation)])
if "/5_detect/peak_score" in f:
D["peak_score"] = np.asarray(f["/5_detect/peak_score"])
D["merged"] = np.asarray(f["/%s/merged" % (t_detect)])
t_peak_min = "%s/peak_min" % t_analyse
t_peak_max = "%s/peak_max" % t_analyse
t_peak_mean = "%s/peak_mean" % t_analyse
t_peak_median = "%s/peak_median" % t_analyse
for kp,tp in zip(["min", "max", "mean", "median"], [t_peak_min, t_peak_max, t_peak_mean, t_peak_median]):
if tp in f:
D[kp] = np.asarray(f[tp])
if not only_scalars:
t_image = "/%s/%s" % (t_process, t_process_image)
if t_image in f:
D["image1"] = np.asarray(f[t_image][1,:,:])
D["image2"] = np.asarray(f[t_image][2,:,:])
if "/2_detect/image_labels" in f:
D["labels1"] = np.asarray(f["/%s/image_labels" % t_detect][1,:,:])
t_thumbnails = ("/%s/peak_thumbnails" % (t_analyse))
if t_thumbnails in f:
D["thumbnails1"] = np.asarray(f["%s/peak_thumbnails" % (t_analyse)][1,:,:,:])
if not skip_thumbnails:
D["thumbnails"] = []
for i in range(sel.shape[0]):
if sel[i].sum() == 0:
D["thumbnails"].append(np.asarray([]))
else:
tmp_shape = f["%s/peak_thumbnails" % (t_analyse)][i,0].shape
D["thumbnails"].append(np.asarray(f["%s/peak_thumbnails" % (t_analyse)][i, np.where(sel[i])[0], :, :]).reshape(sel[i].sum(), tmp_shape[0], tmp_shape[1]))
if verbose:
print("Read %s" % D["filename"])
# Read config file
if os.path.isfile(D["conf_filename"]):
D["conf"] = config.read_configfile(D["conf_filename"])
else:
if verbose:
print("Skipping %s - file does not exist" % D["conf_filename"])
return D
def mask_data(D, exclude_saturated_frames=False, verbose=True):
keys = D.keys()
keys.sort()
for k in keys:
x = D[k]["x"]
y = D[k]["y"]
# VALID PARTICLES
v = (x > 0) * (y > 0)
if exclude_saturated_frames:
for i,sat_n in enumerate(D[k]["sat_n"]):
if sat_n > 0:
v[i,:] = False
D[k]["valid_particles"] = v
# VALID PARTICLES / FRAME
n_frame = np.array([v_frame.sum() for v_frame in v])
D[k]["particles_per_frame"] = n_frame
# NOT SATURATED
n = D[k]["saturated"] == 0
D[k]["not_saturated_particles"] = n
n_fract = (n*v).sum()/float(v.sum())
if "cx_focus" in D[k] and "cy_focus" in D[k] and "r_focus" in D[k]:
# CENTERED PARTICLES (IN X AND Y, NOT IN Z)
c = ((x-D[k]["cx_focus"])**2 + (y-D[k]["cy_focus"])**2) <= D[k]["r_focus"]**2
else:
c = np.ones(shape=v.shape, dtype='bool')
if verbose:
print("WARNING: No masking of centered particles for %s" % k)
D[k]["centered_particles"] = c
c_fract = (c*v).sum()/float(v.sum())
# CIRCULAR PARTICLES
circ = D[k]["circumference"]
area = D[k]["area"]
D[k]["circularity"] = (area/np.pi) / (np.finfo(np.float64).eps + (circ/(2*np.pi))**2)
t = D[k]["circularity_threshold"] # 0.6 typically fine
r = D[k]["circularity"] > t
D[k]["circular_particles"] = r
r_fract = (r*v).sum()/float(v.sum())
# ISOLATED PARTICLES
d_min = D[k]["dists_min"]
i = D[k]["dists_neighbor"] >= d_min
D[k]["isolated_particles"] = i
i_fract = (i*v).sum()/float(v.sum())
# SOME OUTPUT
if verbose:
print("%s: %.1f part. rate\t %i part.\t (%i %% not sat.; %i %% centered; %i %% circ.; %i %% isol.)" % (k, round(n_frame.mean(),1), v.sum(), 100.*n_fract, 100.*c_fract, 100.*r_fract, 100.*i_fract))
return D
def read_thumbnails(D, k, index_mask, root_dir="/scratch/fhgfs/hantke/spts", Nmax=None):
if "Data Location" not in D[k].keys():
D[k]["filename"] = "%s/%s/%s_analysis/spts.cxi" % (root_dir,D[k]["Date"],k)
else:
D[k]["filename"] = "%s/%s_analysis/spts.cxi" % (D[k]["Data Location"],k)
with h5py.File(D[k]["filename"], "r") as f:
ni = index_mask.shape[0]
nj = index_mask.shape[1]
if ni != f["/3_analyse/thumbnails"].shape[0] or nj != f["/3_analyse/thumbnails"].shape[1]:
print("ERROR: Shapes of index_mask (%s) and the h5dataset of thumbnails (%s) do not match!" % (str(index_mask.shape), str(f["/3_analyse/thumbnails"].shape)))
return
J,I = np.meshgrid(np.arange(nj), np.arange(ni))
I = I[index_mask]
J = J[index_mask]
N = index_mask.sum()
if Nmax is not None:
N = min([Nmax, N])
thumbnails = np.zeros(shape=(N, f["/3_analyse/thumbnails"].shape[2], f["/3_analyse/thumbnails"].shape[3]), dtype=f["/3_analyse/thumbnails"].dtype)
for k,i,j in zip(range(N),I[:N],J[:N]):
thumbnails[k,:,:] = np.asarray(f["/3_analyse/thumbnails"][i,j,:,:])
return thumbnails
def fqls_to_mJ(fqls_us):
tab_fqls = np.array([182, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290,
300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410], dtype=np.float64)
tab_mJ = np.array([53.60, 53.75, 53.25, 51.95, 49.98, 47.19, 44.30, 40.80, 37.30, 33.15, 29.38, 25.54,
21.58, 18.23, 15.18, 12.22, 9.65, 7.30, 5.37, 3.61, 2.33, 1.31, 0.58, 0.23], dtype=np.float64)
if fqls_us < tab_fqls[0]:
print("WARNING: given FQLS=%f out of range (min.: %f)" % (fqls_us, tab_fqls[0]))
return tab_mJ[0]
elif fqls_us > tab_fqls[-1]:
print("WARNING: given FQLS=%f out of range (max.: %f)" % (fqls_us, tab_fqls[-1]))
return tab_mJ[-1]
else:
f = scipy.interpolate.interp1d(tab_fqls, tab_mJ)
return f(fqls_us)
def plot_focus(D, separate=False):
keys = D.keys()
keys.sort()
if not separate:
fig, (axs1, axs2, axs3) = pypl.subplots(3, len(keys), figsize=(2*len(keys),8))
for i,k in enumerate(keys):
if not separate:
ax1 = axs1[i]
ax2 = axs2[i]
ax3 = axs3[i]
else:
fig, (ax1, ax2, ax3) = pypl.subplots(1, 3, figsize=(8,2))
p_v = D[k]["valid_particles"]
p_n = D[k]["not_saturated_particles"]
p = p_v * p_n
x = D[k]["x"]
y = D[k]["y"]
s = D[k]["sum"]
cx = D[k]["cx_focus"]
cy = D[k]["cy_focus"]
r = D[k]["r_focus"]
Nbins = 20
xedges = np.linspace(0,1500,Nbins+1)
yedges = np.linspace(0,1500,Nbins+1)
N, xedges, yedges = np.histogram2d(y[p], x[p], bins=(xedges, yedges))
I, xedges, yedges = np.histogram2d(y[p], x[p], bins=(xedges, yedges), weights=s[p])
I = np.float64(I)/N
# 2D histogram weighted by intensity
ax1.imshow(I, interpolation="nearest", extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], origin='lower', cmap="hot", vmin=0)
ax1.add_patch(Circle(
(cx,cy), # (x,y)
r, # width
facecolor=(1,1,1,0),
edgecolor=(0.5,0.5,0.5,1.),
ls="--",
lw=3.5,
)
)
ax1.set_axis_off()
ax1.set_title(k)
# 2D histogram
ax2.imshow(N, interpolation="nearest", extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], origin='lower')
ax2.set_axis_off()
#ax3.hist(y[p], bins=yedges, weights=s[p])
s_median = np.zeros(Nbins)
s_mean = np.zeros(Nbins)
s_min = np.zeros(Nbins)
s_max = np.zeros(Nbins)
for yi,y0,y1 in zip(range(Nbins), yedges[:-1], yedges[1:]):
sel = (y0 <= y[p]) * (y[p] < y1)
if sel.any():
s_median[yi] = np.median(s[p][sel])
s_mean[yi] = np.mean(s[p][sel])
s_min[yi] = np.min(s[p][sel])
s_max[yi] = np.max(s[p][sel])
else:
s_median[yi] = np.nan
s_mean[yi] = np.nan
s_min[yi] = np.nan
s_max[yi] = np.nan
#ax3.plot(yedges[:-1]+(yedges[1]-yedges[0])/2., s_min, color="black", ls='--')
#ax3.plot(yedges[:-1]+(yedges[1]-yedges[0])/2., s_max, color="black", ls='--')
ax3.plot(yedges[:-1]+(yedges[1]-yedges[0])/2., s_median, color="blue")
#ax3.plot(yedges[:-1]+(yedges[1]-yedges[0])/2., s_mean, color="green")
ax3.axvline(cy-r, color=(0.5,0.5,0.5,1.), ls="--", lw=3.5)
ax3.axvline(cy+r, color=(0.5,0.5,0.5,1.), ls="--", lw=3.5)
def plot_positions(D, separate=False, ylim=None, xlim=None, ilim=None, Nslices=5, Nbins=50, pngout=None, recenter=False, um=True):
keys = D.keys()
keys.sort()
if not separate:
fig, axs1 = pypl.subplots(2, len(keys), figsize=(2*len(keys), 6))
for i,k in enumerate(keys):
if not separate:
(ax1, ax2, ax3, ax4, ax5, ax6) = axs1[i]
else:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = pypl.subplots(1, 6, figsize=(20,3))#, sharey=True)#, sharey=True)
fig.suptitle(k)
if "analysis" not in D[k]:
D[k]["analysis"] = {}
D[k]["analysis"]["plot_positions"] = {}
intensity = D[k]["sum"]
p_v = D[k]["valid_particles"]
p_n = D[k]["not_saturated_particles"]
p_p = intensity >= 0
p_c = D[k]["circular_particles"]
p = p_v * p_n * p_p * p_c
if ilim is None:
i0 = 0
i1 = intensity.max()
else:
i0 = ilim[0]
i1 = ilim[1]
i = intensity >= i0
i = intensity <= i1
if um:
camera_pixel_size = pixel_size[D[k]["Camera"]]
navitar_zoom = D[k]["Zoom"]
objective_zoom_factor = D[k]["Magn. Obj."]
c = pix_to_m(camera_pixel_size=camera_pixel_size, navitar_zoom=navitar_zoom, objective_zoom_factor=objective_zoom_factor)/1E-6
else:
c = 1.
x = D[k]["x"] * c
y = D[k]["y"] * c
if xlim is not None:
xmin = xlim[0]
xmax = xlim[1]
else:
xmin = 0 * c
xmax = 1500 * c
p *= x>=xmin
p *= x<=xmax
if ylim is not None:
ymin= ylim[0]
ymax= ylim[1]
else:
ymin = 0 * c
ymax = 1500 * c
p *= y>=ymin
p *= y<=ymax
xedges = np.linspace(xmin,xmax,Nbins+1)
dx = (xedges[1]-xedges[0])
yedges = np.linspace(ymin,ymax,Nslices+1)
dy = (yedges[1]-yedges[0])
ycenters = yedges[:-1] + dy/2.
H = np.zeros(shape=(Nslices, Nbins))
Hfit = np.zeros(shape=(Nslices, Nbins))
results = {
'success': np.zeros(Nslices, dtype='bool'),
'A0': np.zeros(Nslices),
'x0': np.zeros(Nslices),
'sigma': np.zeros(Nslices),
'fwhm': np.zeros(Nslices),
}
for si,y0,y1 in zip(range(Nslices), yedges[:-1], yedges[1:]):
s = (y >= y0) * (y < y1) * i
ydata, xdata = np.histogram(x[p*s], bins=xedges, normed=True)
xdata = xdata[:-1] + (xdata[1]-xdata[0])/2.
assert xdata.size == Nbins
p_init = None
p_result, nest = gaussian_fit(xdata=xdata,ydata=ydata,p_init=p_init)
A0, x0, sigma = p_result
if np.isfinite(A0) and np.isfinite(x0) and np.isfinite(sigma):
results['success'][si] = True
results['A0'][si] = A0
results['x0'][si] = x0
results['sigma'][si] = sigma
results['fwhm'][si] = sigma * 2 * np.sqrt(2*np.log(2))
H[si,:] = ydata
Hfit[si,:] = nest
xc = np.array(results['x0'][results['success']]).mean()
if recenter:
xic = abs(xdata-xc).argmin()
xi0 = xic-Nbins/8
xi1 = xic+Nbins/8
x0 = xdata[xi0]
x1 = xdata[xi1]
H = H[:,xi0:xi1+1]
Hfit = Hfit[:,xi0:xi1+1]
else:
x0 = xmin + dx/2.
x1 = xmax - dx/2.
extent = [x0-dx/2., x1+dx/2., ymin, ymax]
ax1.hist(intensity[p]**(1/6.), bins=100)
ax1.axvline(i0**(1/6.))
ax1.axvline(i1**(1/6.))
top = 0
tmp = p
if tmp.sum() > 0:
ax2.scatter(x[tmp], y[tmp], 2, color='blue')
hx, foo = np.histogram(x[tmp], bins=xedges)
p_result_out, nest = gaussian_fit(xdata=xdata,ydata=hx)#,p_init=p_init)
ax3.plot(xdata, hx, color='blue')
ax3.plot(xdata, nest, color='blue', ls='--')
top = max([top, nest.max(), hx.max()])
tmp = p*(i==1)
if tmp.sum() > 0:
ax2.scatter(x[tmp], y[tmp], 2, color='red')
hx, foo = np.histogram(x[tmp], bins=xedges)
p_result_in, nest = gaussian_fit(xdata=xdata,ydata=hx)#,p_init=p_init)
ax3.plot(xdata, hx, color='red')
ax3.plot(xdata, nest, color='red', ls='--')
top = max([top, nest.max(), hx.max()])
ax3.text(p_result_in[1], top*1.2, "FWHM=%.1f" % (p_result_in[2]*2*np.sqrt(2*np.log(2))), color='red', ha='center')
ax3.text(p_result_out[1], top*1.4, "FWHM=%.1f" % (p_result_out[2]*2*np.sqrt(2*np.log(2))), color='blue', ha='center')
ax3.set_ylim(0, top*1.6)
D[k]["analysis"]["plot_positions"]["sigma"] = p_result_in[2]
ax4.imshow(H, extent=extent, interpolation='nearest', origin='lower')
#ax4.plot(results['x0'][results['success']], ycenters[results['success']])
#ax4.plot(results['x0'][results['success']]-results['fwhm'][results['success']]/2., ycenters[results['success']], color='red')
#ax4.plot(results['x0'][results['success']]+results['fwhm'][results['success']]/2., ycenters[results['success']], color='red')
ax4.set_title("Measurement")
ax4.set_ylabel('y')
ax5.imshow(Hfit, extent=extent, interpolation='nearest', origin='lower')
ax5.plot(results['x0'][results['success']], ycenters[results['success']], color='green')
ax5.plot(results['x0'][results['success']]-results['fwhm'][results['success']]/2., ycenters[results['success']], color='red')
ax5.plot(results['x0'][results['success']]+results['fwhm'][results['success']]/2., ycenters[results['success']], color='red')
ax5.set_title("Fit")
ax6.plot(results['fwhm'][results['success']], ycenters[results['success']], color='red')
fwhm_min = results['fwhm'][results['success']].min()
fwhm_min_y = ycenters[results['success']][results['fwhm'][results['success']].argmin()]
ax6.plot(fwhm_min, fwhm_min_y, 'o', color='red')
ax6.text(0.8*fwhm_min, fwhm_min_y, "%.1f" % fwhm_min, ha='right')
ax6.set_xlabel('FWHM')
ax6.set_xlim(0, (x1-x0)/2.)
ax6.set_aspect(1.0/2.)
ax6.set_title("FWHM")
for ax in [ax2, ax4, ax5]:
ax.set_xlim(x0, x1)
ax.set_xlabel('x')
for ax in [ax2, ax4, ax5]:
ax.set_aspect(1.0)
for ax in [ax2, ax4, ax5, ax6]:
ax.set_ylim(ymin, ymax)
ax.xaxis.set_ticks([ax.xaxis.get_ticklocs()[0], ax.xaxis.get_ticklocs()[-1]])
ax.yaxis.set_ticks([ymin, ymax])
pypl.tight_layout()
if pngout is None:
pypl.show()
else:
if separate:
tmp = "%s/%s.png" % (pngout, k)
else:
tmp = pngout
fig.savefig(tmp)
fig.clf()
def plot_circularities(D, separate=False):
keys = D.keys()
keys.sort()
if not separate:
fig, axs = pypl.subplots(1, len(keys), sharex='col', sharey='row', figsize=(3*len(keys),3))
for i,k in enumerate(keys):
if not separate:
ax = axs[i]
else:
fig, ax = pypl.subplots(1, 1, figsize=(3,3))
p_v = D[k]["valid_particles"]
p_n = D[k]["not_saturated_particles"]
p = p_v * p_n
c = D[k]["circularity"]
t = D[k]["circularity_threshold"]
H = ax.hist(c[p], 100, normed=True, range=(0,2))
ax.axvline(t, color="red", ls="--")
ax.set_title(k)
ax.set_xlabel("Circularity")
def plot_distances(D, separate=False):
keys = D.keys()
keys.sort()
if not separate:
fig, axs = pypl.subplots(1, len(keys), sharex='col', sharey='row', figsize=(3*len(keys),3))
for i,k in enumerate(keys):
if separate:
fig, ax = pypl.subplots(1, 1, sharex='col', sharey='row', figsize=(3,3))
else:
ax = axs[i]
p_v = D[k]["valid_particles"]
p_n = D[k]["not_saturated_particles"]
p = p_v * p_n
d = D[k]["dists_neighbor"]
d_min = D[k]["dists_min"]
H = ax.hist(d[p], 100, normed=True, range=(0,2*d_min))
ax.axvline(d_min, color="red", ls="--")
ax.set_title(k)
ax.set_xlabel("Distance [pixel]")
def plot_thumbnails(D, sizes=None, variable="size_nm", save_png=False):
keys = D.keys()
keys.sort()
if sizes is None:
sizes = np.arange(50, 625, 25)
for k in keys:
v = D[k]["valid_particles"] * D[k]["not_saturated_particles"] * D[k]["centered_particles"] * D[k]["circular_particles"] * D[k]["isolated_particles"]
obj = D[k]["Objective"]
fqls = float(D[k]["Laser FQLS"])
Epulse = fqls_to_mJ(fqls)
sum = D[k]["sum"] / Epulse
size = sum**(1/6.) / 2.98 * 100.
fig, axs = pypl.subplots(ncols=len(sizes)+2, figsize=((len(sizes)+2)*0.5,2.))
fig.suptitle("%s - %s - %.1f mJ" % (obj, k, round(Epulse, 1)))
shape = read_thumbnails(D, k, np.ones(v.shape, dtype=np.bool), Nmax=1)[0].shape
for ax, si in zip(axs[2:], sizes):
M = v*(abs(size - si) < 10)
if M.sum():
T = np.asarray(read_thumbnails(D, k, M, Nmax=1)[0], dtype=np.float64)
if variable == "size_nm":
t = str(int(si.round()))
st = "%i%%" % int(round(100.*float(T.max())/65536.,0))
sst = "%.1e" % int(round(T.sum()/2.13, 1))
#sst = "%i" % int(round(T.sum()/2.13, 0))
elif variable == "intensity_percent":
t = str(int(round(100.*T.max()/65500.)))
st = ""
sst = ""
else:
print("ERROR: Argument variable=%s is invalid." % variable)
return
else:
T = np.zeros(shape=shape)
if variable == "size_nm":
t = str(int(si.round()))
st = ""
sst = ""
else:
t = ""
st = ""
sst = ""
tn = "%i" % M.sum()
ax.text(float(T.shape[1]-1)/2., -T.shape[0]-float(T.shape[0]-1)/2., tn, ha="center", va="center")
ax.text(float(T.shape[1]-1)/2., -float(T.shape[0]-1)/2., t, ha="center", va="center")
ax.text(float(T.shape[1]-1)/2., T.shape[0]+float(T.shape[0]-1)/2., st, ha="center", va="center")
ax.text(float(T.shape[1]-1)/2., T.shape[0]*2.2+float(T.shape[0]-1)/2., sst, ha="center", va="center", rotation=45.)
ax.imshow(T, interpolation="nearest", cmap="gnuplot", norm=LogNorm(0.1,65536))
ax.set_axis_off()
T = np.zeros(shape=shape)
axs[0].imshow(T, interpolation="nearest", cmap="gnuplot", norm=LogNorm(0.1,65536))
axs[0].text(0, -T.shape[0]-float(T.shape[0]-1)/2., "# particles", ha="left", va="center")
axs[0].text(0, -float(T.shape[0]-1)/2., "Size [nm]", ha="left", va="center")
axs[0].text(0, float(T.shape[0]-1)/2., "Image", ha="left", va="center")
axs[0].text(0, T.shape[0]+float(T.shape[0]-1)/2., "Max./Sat.", ha="left", va="center")
axs[0].text(0, T.shape[0]*2.2+float(T.shape[0]-1)/2., "Signal [ph]", ha="left", va="center")
axs[0].set_axis_off()
axs[1].set_axis_off()
fig.subplots_adjust(hspace=5)
if save_png:
fig.savefig("./thumbnails_%s.png" % k, dpi=400)
def plot_hist(D, separate=False, projector=None, label="Scattering Intensity [adu]", Nbins=100, vmin=0, vmax=3E6, accumulate=False, fit=False, fit_p0=None, title=None, axvlines=None, particles_per_frame=False):
keys = D.keys()
keys.sort()
if not separate and not accumulate:
fig, axs = pypl.subplots(nrows=len(keys), ncols=1, figsize=(6,len(keys)*4), sharex=True)
if accumulate:
fig, axs = pypl.subplots(nrows=1, ncols=1, figsize=(6,4))
data_acc = []
ppf = np.array([])
for i,k in enumerate(keys):
if separate and not accumulate:
fig, ax = pypl.subplots(nrows=1, ncols=1, figsize=(6,4))
else:
if len(keys) == 1 or accumulate:
ax = axs
else:
ax = axs[i]
p_v = D[k]["valid_particles"]
p_n = D[k]["not_saturated_particles"]
p_i = D[k]["isolated_particles"]
p_c = D[k]["centered_particles"]
m = p_v * p_n * p_i * p_c
ppf = np.array(list(ppf) + list(D[k]["particles_per_frame"]))
if projector is None:
data = D[k]["sum"]
else:
data = projector(D[k]["sum"][m], D[k])
if accumulate:
data_acc.extend(list(data))
data = list(data_acc)
if not accumulate or (i+1) == len(keys):
H = np.histogram(data, bins=Nbins, range=(vmin, vmax))
s = (H[1][:-1]+H[1][1:])/2.
n = H[0]
ax.fill_between(s, n, np.zeros_like(n), lw=0)#1.8)
if separate or (i+1) == len(keys) or accumulate:
ax.set_xlabel(label)
ax.set_ylabel("Number of particles")
sns.despine()
if fit == 1:
p_init = fit_p0
p_result, nest = gaussian_fit(xdata=s,ydata=n,p_init=p_init)
ax.plot(s, nest)
((A1, m1, s1)) = p_result
ax.text(m1*1.1, A1*1.1, "%.3f (sigma = %.3f)" % (round(m1,3), round(s1,3)) , ha="left")
ax.legend(["measured", "fit"])
if fit == 2:
p_init = fit_p0
p_result, nest = double_gaussian_fit(xdata=s,ydata=n,p_init=p_init)
ax.plot(s, nest)
((A1, m1, s1), (A2, m2, s2)) = p_result
ax.text(m1*1.1, A1*1.1, "%.3f (sigma = %.3f)" % (round(m1,3), round(s1,3)) , ha="left")
ax.text(m2*1.1, A2*1.1, "%.3f (sigma = %.3f)" % (round(m2,3), round(s2,3)) , ha="left")
ax.legend(["measured", "fit"])
if axvlines is not None:
ax.set_ylim((0, 1.2*n.max()))
for pos,lab in axvlines:
ax.axvline(pos, ymin=0, ymax=0.9, color="black", ls="--")
ax.text(pos, 1.1*n.max(), lab, va="bottom", ha="center")
if particles_per_frame:
ax.text(1.0, 0.7, "%.1f particles / frame" % round(ppf.mean(),1), transform=ax.transAxes, ha="right")
if title is not None:
fig.suptitle(title)
def plot_hist_intensity(D, separate=False, fqls_normed=False, Nbins=100, vmin=0, vmax=3E6, accumulate=False, fit=False, fit_p0=None, title=None, axvlines=None, particles_per_frame=False):
if fqls_normed:
projector = lambda s, Dk: s/adu_per_photon / fqls_to_mJ(float(Dk["Laser FQLS"]))
label="Normed scattering Intensity [ph]"
else:
projector = lambda s, Dk: s/adu_per_photon
label="Scattering Intensity [ph]"
return plot_hist(D, separate=separate, projector=projector, label=label, Nbins=Nbins, vmin=vmin, vmax=vmax, accumulate=accumulate, fit=fit, fit_p0=fit_p0, title=title, axvlines=axvlines, particles_per_frame=particles_per_frame)
def plot_hist_size(D, separate=False, fqls_normed=False, scaling_constant=33.56, Nbins=100, vmin=0, vmax=300, accumulate=False, fit=False, fit_p0=None, title=None, axvlines=None, particles_per_frame=False):
projector = lambda s, Dk: (s / fqls_to_mJ(float(Dk["Laser FQLS"])))**(1/6.) * scaling_constant
label="Particle diameter [nm]"
return plot_hist(D, separate=separate, projector=projector, label=label, Nbins=Nbins, vmin=vmin, vmax=vmax, accumulate=accumulate, fit=fit, fit_p0=fit_p0, title=title, axvlines=axvlines, particles_per_frame=particles_per_frame)
gaussian = lambda x,A0,x0,sigma: A0*np.exp((-(x-x0)**2)/(2.*sigma**2))
double_gaussian = lambda x,p1,p2: gaussian(x,p1[0],p1[1],p1[2])+gaussian(x,p2[0],p2[1],p2[2])
def double_gaussian_fit(xdata=None,ydata=None,p_init=None,show=False):
from scipy.optimize import leastsq
if xdata == None and ydata == None:
# generate test data
A01,A02 = 7.5,10.4
mean1, mean2 = -5, 4.
std1, std2 = 7.5, 4.
xdata = np.linspace(-20, 20, 500)
ydata = double_gaussian(xdata,[A01,mean1,std1],[A02,mean2,std2])
if p_init == None:
p_A01, p_A02, p_mean1, p_mean2, p_sd1, p_sd2 = [ydata.max(),
ydata.max(),
xdata[len(xdata)/3],
xdata[2*len(xdata)/3],
(xdata.max()-xdata.min())/10.,
(xdata.max()-xdata.min())/10.]
p_init = [p_A01, p_mean1, p_sd1,p_A02, p_mean2, p_sd2] # Initial guesses for leastsq
else:
[p_A01, p_mean1, p_sd1,p_A02, p_mean2, p_sd2] = p_init # Initial guesses for leastsq
err = lambda p,x,y: abs(y-double_gaussian(x,[p[0],p[1],p[2]],[p[3],p[4],p[5]]))
plsq = leastsq(err, p_init, args = (xdata, ydata))
p_result = [[A1, mean1, s1], [A2, mean2, s2]] = [[plsq[0][0],plsq[0][1],abs(plsq[0][2])],[plsq[0][3],plsq[0][4],abs(plsq[0][5])]]
yest = double_gaussian(xdata,p_result[0],p_result[1])
if show:
import pylab
pylab.figure()
yinit = double_gaussian(xdata,[p_A01,p_mean1,p_sd1],[p_A02,p_mean2,p_sd2])
yest1 = gaussian(xdata,plsq[0][0],plsq[0][1],plsq[0][2])
yest2 = gaussian(xdata,plsq[0][3],plsq[0][4],plsq[0][5])
pylab.plot(xdata, ydata, 'r.',color='red', label='Data')
pylab.plot(xdata, yinit, 'r.',color='blue', label='Starting Guess')
pylab.plot(xdata, yest, '-',lw=3.,color='black', label='Fitted curve (2 gaussians)')
pylab.plot(xdata, yest1, '--',lw=1.,color='black', label='Fitted curve (2 gaussians)')
pylab.plot(xdata, yest2, '--',lw=1.,color='black', label='Fitted curve (2 gaussians)')
pylab.legend()
pylab.show()
return [p_result, yest]
def gaussian_fit(xdata=None,ydata=None,p_init=None,show=False):
from scipy.optimize import leastsq
if xdata is None and ydata is None:
# Generate test data
A0_test = 5.5
x0_test = -2.
s_test = 1.
xdata = np.linspace(-20., 20., 500)
ydata = gaussian(xdata,A0_test,x0_test,s_test)
if p_init is None:
# Guess parameters
# A0
A0_init = ydata.max()
# x0
x0_init = xdata[ydata.argmax()]
# Sigma
#s_init = (xdata.max()-xdata.min())/10.
dhalf = abs(ydata-ydata.max())
left = xdata < x0_init
right = xdata > x0_init
fwhm_init = []
if left.sum() > 0:
fwhm_init.append(abs(xdata[left][dhalf[left].argmin()]-x0_init)*2)
if right.sum() > 0:
fwhm_init.append(abs(xdata[right][dhalf[right].argmin()]-x0_init)*2)
fwhm_init = np.asarray(fwhm_init).mean()
s_init = fwhm_init / (2*np.sqrt(2*np.log(2)))
# p_init
p_init = [A0_init, x0_init, s_init]
else:
[A0_init, x0_init, s_init] = p_init
g = lambda A0, x0, s: gaussian(xdata, A0, x0, s)
err = lambda p: ydata-g(p[0],p[1],p[2])
plsq = leastsq(err, p_init)
p_result = [A0_result, x0_result, s_result] = [plsq[0][0],plsq[0][1],abs(plsq[0][2])]
yest = gaussian(xdata,A0_result, x0_result, s_result)
if show:
import pylab
pylab.figure()
yinit = gaussian(xdata,A0_init, x0_init, s_init)
pylab.plot(xdata, ydata, 'r.',color='red', label='Data')
pylab.plot(xdata, yinit, 'r.',color='blue', label='Starting Guess')
pylab.plot(xdata, yest, '-',lw=3.,color='black', label='Fitted curve')
pylab.legend()
pylab.show()
return [p_result, yest]
def bootstrap_gaussian_fit(xdata,ydata,p_init0=None,show=False,Nfract=0.5,n=100, p_init_variation=0.5):
if p_init0 == None:
p_init = gaussian_fit(xdata,ydata)[0]
else:
p_init = p_init0
ps = []
N = int(round(len(xdata)*Nfract))
for i in range(n):
random_pick = np.random.choice(np.arange(xdata.size), size=N)
xdata1 = xdata[random_pick]
ydata1 = ydata[random_pick]
p0 = np.array(p_init) * (1+((-0.5+np.random.rand(len(p_init)))*p_init_variation))
ps.append(gaussian_fit(xdata1,ydata1,tuple(p0),show)[0])
ps = np.array(ps)
p_result = ps.mean(0)
p_std = ps.std(0)
yest = gaussian(xdata,p_result[0], p_result[1], p_result[2])
return [p_result, yest, p_std]
def hist_gauss_fit(x, xmin, xmax, do_plot=False, ax=None, bootstrap=False, n_bootstrap=100, Nfract_bootstrap=0.75, p_init_variation_bootstrap=0., bins_max=500, bins_step=0.2):
bins = 10
success = False
H, xedges = np.histogram(x, range=(xmin, xmax), bins=bins)
while (H>0.5*H.max()).sum() < 3:
bins += 1
H, xedges = np.histogram(x, range=(xmin, xmax), bins=bins)
if bins > bins_max:
print("Fit failed.")
break
while not success:
H, xedges = np.histogram(x, range=(xmin, xmax), bins=bins)
dxedges = xedges[1]-xedges[0]
xcenters = xedges[:-1]+(dxedges)/2.
if bootstrap:
(A_fit, x0_fit, sigma_fit), H_fit, (A_fit_std, x0_fit_std, sigma_fit_std) = bootstrap_gaussian_fit(xcenters, np.asarray(H, dtype="float64"),
n=n_bootstrap, Nfract=Nfract_bootstrap,
p_init_variation=p_init_variation_bootstrap)
else:
(A_fit, x0_fit, sigma_fit), H_fit = gaussian_fit(xcenters, np.asarray(H, dtype="float64"))
fwhm = abs(2*np.sqrt(2*np.log(2)) * sigma_fit)
if fwhm/float(dxedges) > 5 and (not bootstrap or (np.array([A_fit_std, x0_fit_std, sigma_fit_std])/np.array([A_fit, x0_fit, sigma_fit]) < 1.).all()):
success = True
else:
bins *= 1+bins_step
bins = int(round(bins))
if bins > bins_max:
print("Fit failed.")
break
if do_plot:
if ax is None:
fig = pypl.figure(figsize=(2,3))
_ax = fig.add_subplot(111)
else:
_ax = ax
if success:
_ax.plot(xcenters, H_fit)
_ax.plot(xcenters, H, "o-")
_ax.set_ylim(0, H.max()*1.1)
if bootstrap:
return (A_fit, x0_fit, sigma_fit), (xcenters, H, H_fit), (A_fit_std, x0_fit_std, sigma_fit_std), success
else:
return (A_fit, x0_fit, sigma_fit), (xcenters, H, H_fit), success
def calc_all_vecs(x, y, rmax=40):
assert len(x) == len(y)
n_frames = len(x)
dx = []
dy = []
di1 = []
di2 = []
napp = 0
s = (x > 0) * (y > 0)
if not s.any():
print("WARNING: Not a single point is valid.")
return dx, dy, di1, di2
i = np.arange(x.shape[1])
for i_frame in range(n_frames):
dx.append([])
dy.append([])
di1.append([])
di2.append([])
si = s[i_frame,:]
ii = i[si]
n = len(ii)
xi = x[i_frame,:][si]
yi = y[i_frame,:][si]
combs = itertools.combinations(np.arange(n),2)
for c1,c2 in combs:
dxi = xi[c2]-xi[c1]
dyi = yi[c2]-yi[c1]
ri = np.sqrt(dxi**2 + dyi**2)
if ri <= rmax:
dx[-1].append(dxi)
dy[-1].append(dyi)
di1[-1].append(ii[c1])
di2[-1].append(ii[c2])
napp += 1
dx[-1] = np.asarray(dx[-1])
dy[-1] = np.asarray(dy[-1])
di1[-1] = np.asarray(di1[-1])
di2[-1] = np.asarray(di2[-1])
selfrac = float(napp) / float(s.sum())
if selfrac < 0.3:
print("WARNING: Selection fraction: %.2f%%" % (100*selfrac))
return dx, dy, di1, di2
def calc_mean_vec(dx, dy, rmax=40, ds=1, dxmax=None, dx0_guess=None, dy0_guess=None):
assert len(dx) == len(dy)
dx_flat = list(itertools.chain.from_iterable(dx))
dy_flat = list(itertools.chain.from_iterable(dy))
assert len(dx_flat) == len(dy_flat)
ranges = [[-rmax-0.5, rmax+0.5], [-0.5, rmax+0.5]]
bins = [2*rmax/ds+1, rmax/ds+1]
counts, xedges, yedges = np.histogram2d(dx_flat, dy_flat, bins=bins, range=ranges)
counts = counts.swapaxes(1,0)
X, Y = np.meshgrid(xedges[:-1] + (xedges[1]-xedges[0])/2.,
yedges[:-1] + (yedges[1]-yedges[0])/2.)
if dxmax is not None:
if dx0_guess is not None and dy0_guess is not None:
counts[np.sqrt((X-dx0_guess)**2+(Y-dy0_guess)**2)>dxmax] = 0
else:
counts[abs(X)>dxmax] = 0
i_max = counts.argmax()
x_max = X.flat[i_max]
y_max = Y.flat[i_max]
return x_max, y_max
from scipy.ndimage.measurements import center_of_mass
def calc_com_vec(dx, dy, rmax=40, ds=1):
assert len(dx) == len(dy)
dx_flat = list(itertools.chain.from_iterable(dx))
dy_flat = list(itertools.chain.from_iterable(dy))
assert len(dx_flat) == len(dy_flat)
ranges = [[-rmax-0.5, rmax+0.5], [-0.5, rmax+0.5]]
bins = [2*rmax/ds+1, rmax/ds+1]
counts, xedges, yedges = np.histogram2d(dx_flat, dy_flat, bins=bins, range=ranges)
counts = counts.swapaxes(1,0)
y_com, x_com = center_of_mass(counts)
return x_com, y_com
def identify_pairs(dx, dy, di1, di2, dx0, dy0, dI=None, length_err_max=0.1, angle_deg_max=45., verbose=False):
assert len(dx) == len(dy)
n_frames = len(dx)
di1_new = []
di2_new = []
dr0 = np.sqrt(dx0**2+dy0**2)
nsuc = 0
ntot = 0
for i_frame, di1_i, di2_i, dx_i, dy_i in zip(range(n_frames), di1, di2, dx, dy):
di1_new.append([])
di2_new.append([])
err_i = np.sqrt((dx_i-dx0)**2 + (dy_i-dy0)**2)/dr0
aerr_i = np.arccos( (dx_i * dx0 + dy_i * dy0) / np.sqrt(dx_i**2 + dy_i**2) / np.sqrt(dx0**2 + dy0**2) ) / (2.*np.pi) * 360.
sel = err_i <= length_err_max
sel *= aerr_i <= angle_deg_max
if dI is not None:
sel *= dI[i_frame] < 0.25
nsel = sel.sum()
if nsel == 0:
continue
order = err_i.argsort()
for i_pair in order[:nsel]:
i1_pair = di1[i_frame][i_pair]
i2_pair = di2[i_frame][i_pair]
if (i1_pair not in di1_new[-1]) and (i1_pair not in di2_new[-1]) and (i2_pair not in di1_new[-1]) and (i2_pair not in di2_new[-1]):
di1_new[-1].append(i1_pair)
di2_new[-1].append(i2_pair)
else:
continue
di1_new[-1] = np.asarray(di1_new[-1])
di2_new[-1] = np.asarray(di2_new[-1])
nsuc += len(di1_new[-1])
ntot += nsel
if verbose:
print("success %i/%i" % (nsuc, ntot))
return di1_new, di2_new
def filter_pairs(data, di1, di2, flat_output=False):
data1 = []
data2 = []
for (i_frame, (di1_i, di2_i)) in enumerate(zip(di1, di2)):
data1.append(data[i_frame, di1_i])
data2.append(data[i_frame, di2_i])
if flat_output:
data1 = np.array(list(itertools.chain.from_iterable(data1)))
data2 = np.array(list(itertools.chain.from_iterable(data2)))
return data1, data2
from scipy.optimize import least_squares
gaussian_beam = lambda y, y0, yR, w0: w0 * np.sqrt(1 + ((y-y0)/yR)**2)
def gaussian_beam_fit(y, fwhm, weights=1.):
fwhm_min = fwhm.min()
fwhm_min_y = y[fwhm.argmin()]
err = lambda v: (gaussian_beam(y, v[0], v[1], v[2]) - fwhm)*weights
v0 = np.asarray([fwhm_min_y, 0.2, fwhm_min])
if np.isnan(v0).any():
return None, None, None
else:
y0_fit, yR_fit, w0_fit = least_squares(err, x0=v0).x
return y0_fit, yR_fit, w0_fit
| 38.351675 | 234 | 0.524567 |
1bfc6c5c94183d49f2f9087102904ed10441fcbe | 5,475 | py | Python | tools/telemetry/telemetry/page/page_test_runner.py | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | tools/telemetry/telemetry/page/page_test_runner.py | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | tools/telemetry/telemetry/page/page_test_runner.py | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
from telemetry.core import browser_options
from telemetry.core import discover
from telemetry.core import profile_types
from telemetry.page import page_test
from telemetry.page import page_runner
from telemetry.page import page_set
def Main(test_dir, profile_creators_dir, page_set_filenames):
"""Turns a PageTest into a command-line program.
Args:
test_dir: Path to directory containing PageTests.
profile_creators_dir: Path to a directory containing ProfileCreators
"""
runner = PageTestRunner()
sys.exit(runner.Run(test_dir, profile_creators_dir, page_set_filenames))
class PageTestRunner(object):
def __init__(self):
self._parser = None
self._options = None
self._args = None
@property
def test_class(self):
return page_test.PageTest
@property
def test_class_name(self):
return 'test'
def Run(self, test_dir, profile_creators_dir, page_set_filenames):
test, ps = self.ParseCommandLine(
sys.argv, test_dir, profile_creators_dir, page_set_filenames)
results = page_runner.Run(test, ps, self._options)
results.PrintSummary()
return min(255, len(results.failures + results.errors))
def FindTestConstructors(self, test_dir):
return discover.DiscoverClasses(
test_dir, os.path.join(test_dir, '..'), self.test_class)
def FindTestName(self, test_constructors, args):
"""Find the test name in an arbitrary argument list.
We can't use the optparse parser, because the test may add its own
command-line options. If the user passed in any of those, the
optparse parsing will fail.
Returns:
test_name or None
"""
test_name = None
for arg in [self.GetModernizedTestName(a) for a in args]:
if arg in test_constructors:
test_name = arg
return test_name
def GetModernizedTestName(self, arg):
"""Sometimes tests change names but buildbots keep calling the old name.
If arg matches an old test name, return the new test name instead.
Otherwise, return the arg.
"""
return arg
def GetPageSet(self, test, page_set_filenames):
ps = test.CreatePageSet(self._args, self._options)
if ps:
return ps
if len(self._args) < 2:
page_set_list = ',\n'.join(
sorted([os.path.relpath(f) for f in page_set_filenames]))
self.PrintParseError(
'No page set, file, or URL specified.\n'
'Available page sets:\n'
'%s' % page_set_list)
page_set_arg = self._args[1]
# We've been given a URL. Create a page set with just that URL.
if (page_set_arg.startswith('http://') or
page_set_arg.startswith('https://')):
self._options.allow_live_sites = True
return page_set.PageSet.FromDict({
'pages': [{'url': page_set_arg}]
}, os.path.dirname(__file__))
# We've been given a page set JSON. Load it.
if page_set_arg.endswith('.json'):
return page_set.PageSet.FromFile(page_set_arg)
# We've been given a file or directory. Create a page set containing it.
if os.path.exists(page_set_arg):
page_set_dict = {'pages': []}
def _AddFile(file_path):
page_set_dict['pages'].append({'url': 'file://' + file_path})
def _AddDir(dir_path):
for path in os.listdir(dir_path):
path = os.path.join(dir_path, path)
_AddPath(path)
def _AddPath(path):
if os.path.isdir(path):
_AddDir(path)
else:
_AddFile(path)
_AddPath(page_set_arg)
return page_set.PageSet.FromDict(page_set_dict, os.getcwd() + os.sep)
raise Exception('Did not understand "%s". Pass a page set, file or URL.' %
page_set_arg)
def ParseCommandLine(self, args, test_dir, profile_creators_dir,
page_set_filenames):
# Need to collect profile creators before creating command line parser.
if profile_creators_dir:
profile_types.FindProfileCreators(profile_creators_dir)
self._options = browser_options.BrowserOptions()
self._parser = self._options.CreateParser(
'%%prog [options] %s page_set' % self.test_class_name)
test_constructors = self.FindTestConstructors(test_dir)
test_name = self.FindTestName(test_constructors, args)
test = None
if test_name:
test = test_constructors[test_name]()
test.AddOutputOptions(self._parser)
test.AddCommandLineOptions(self._parser)
page_runner.AddCommandLineOptions(self._parser)
_, self._args = self._parser.parse_args()
if len(self._args) < 1:
error_message = 'No %s specified.\nAvailable %ss:\n' % (
self.test_class_name, self.test_class_name)
test_list_string = ',\n'.join(sorted(test_constructors.keys()))
self.PrintParseError(error_message + test_list_string)
if not test:
error_message = 'No %s named %s.\nAvailable %ss:\n' % (
self.test_class_name, self._args[0], self.test_class_name)
test_list_string = ',\n'.join(sorted(test_constructors.keys()))
self.PrintParseError(error_message + test_list_string)
ps = self.GetPageSet(test, page_set_filenames)
if len(self._args) > 2:
self.PrintParseError('Too many arguments.')
return test, ps
def PrintParseError(self, message):
self._parser.error(message)
| 32.784431 | 78 | 0.691142 |
404fe6d651c29aa79456e71c72b0bb900e4728b8 | 12,718 | py | Python | kivy/uix/dropdown.py | quadropoly/kivy | 15a125c046b793c56406cafb47359245dfb6edd6 | [
"MIT"
] | 2 | 2020-06-19T13:59:23.000Z | 2020-09-08T17:08:35.000Z | kivy/uix/dropdown.py | quadropoly/kivy | 15a125c046b793c56406cafb47359245dfb6edd6 | [
"MIT"
] | null | null | null | kivy/uix/dropdown.py | quadropoly/kivy | 15a125c046b793c56406cafb47359245dfb6edd6 | [
"MIT"
] | 1 | 2020-03-06T07:08:30.000Z | 2020-03-06T07:08:30.000Z | '''
Drop-Down List
==============
.. image:: images/dropdown.gif
:align: right
.. versionadded:: 1.4.0
A versatile drop-down list that can be used with custom widgets. It allows you
to display a list of widgets under a displayed widget. Unlike other toolkits,
the list of widgets can contain any type of widget: simple buttons,
images etc.
The positioning of the drop-down list is fully automatic: we will always try to
place the dropdown list in a way that the user can select an item in the list.
Basic example
-------------
A button with a dropdown list of 10 possible values. All the buttons within the
dropdown list will trigger the dropdown :meth:`DropDown.select` method. After
being called, the main button text will display the selection of the
dropdown. ::
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.base import runTouchApp
# create a dropdown with 10 buttons
dropdown = DropDown()
for index in range(10):
# When adding widgets, we need to specify the height manually
# (disabling the size_hint_y) so the dropdown can calculate
# the area it needs.
btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
# for each button, attach a callback that will call the select() method
# on the dropdown. We'll pass the text of the button as the data of the
# selection.
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
# then add the button inside the dropdown
dropdown.add_widget(btn)
# create a big main button
mainbutton = Button(text='Hello', size_hint=(None, None))
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=dropdown.open)
# one last thing, listen for the selection in the dropdown list and
# assign the data to the button text.
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
runTouchApp(mainbutton)
Extending dropdown in Kv
------------------------
You could create a dropdown directly from your kv::
#:kivy 1.4.0
<CustomDropDown>:
Button:
text: 'My first Item'
size_hint_y: None
height: 44
on_release: root.select('item1')
Label:
text: 'Unselectable item'
size_hint_y: None
height: 44
Button:
text: 'My second Item'
size_hint_y: None
height: 44
on_release: root.select('item2')
And then, create the associated python class and use it::
class CustomDropDown(DropDown):
pass
dropdown = CustomDropDown()
mainbutton = Button(text='Hello', size_hint=(None, None))
mainbutton.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
'''
__all__ = ('DropDown', )
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.config import Config
_grid_kv = '''
GridLayout:
size_hint_y: None
height: self.minimum_size[1]
cols: 1
'''
class DropDownException(Exception):
'''DropDownException class.
'''
pass
class DropDown(ScrollView):
'''DropDown class. See module documentation for more information.
:Events:
`on_select`: data
Fired when a selection is done. The data of the selection is passed
in as the first argument and is what you pass in the :meth:`select`
method as the first argument.
`on_dismiss`:
.. versionadded:: 1.8.0
Fired when the DropDown is dismissed, either on selection or on
touching outside the widget.
'''
auto_width = BooleanProperty(True)
'''By default, the width of the dropdown will be the same as the width of
the attached widget. Set to False if you want to provide your own width.
:attr:`auto_width` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
'''
max_height = NumericProperty(None, allownone=True)
'''Indicate the maximum height that the dropdown can take. If None, it will
take the maximum height available until the top or bottom of the screen
is reached.
:attr:`max_height` is a :class:`~kivy.properties.NumericProperty` and
defaults to None.
'''
dismiss_on_select = BooleanProperty(True)
'''By default, the dropdown will be automatically dismissed when a
selection has been done. Set to False to prevent the dismiss.
:attr:`dismiss_on_select` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
'''
auto_dismiss = BooleanProperty(True)
'''By default, the dropdown will be automatically dismissed when a
touch happens outside of it, this option allows to disable this
feature
:attr:`auto_dismiss` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
.. versionadded:: 1.8.0
'''
min_state_time = NumericProperty(0)
'''Minimum time before the :class:`~kivy.uix.DropDown` is dismissed.
This is used to allow for the widget inside the dropdown to display
a down state or for the :class:`~kivy.uix.DropDown` itself to
display a animation for closing.
:attr:`min_state_time` is a :class:`~kivy.properties.NumericProperty`
and defaults to the `Config` value `min_state_time`.
.. versionadded:: 1.10.0
'''
attach_to = ObjectProperty(allownone=True)
'''(internal) Property that will be set to the widget to which the
drop down list is attached.
The :meth:`open` method will automatically set this property whilst
:meth:`dismiss` will set it back to None.
'''
container = ObjectProperty()
'''(internal) Property that will be set to the container of the dropdown
list. It is a :class:`~kivy.uix.gridlayout.GridLayout` by default.
'''
_touch_started_inside = None
__events__ = ('on_select', 'on_dismiss')
def __init__(self, **kwargs):
self._win = None
if 'min_state_time' not in kwargs:
self.min_state_time = float(
Config.get('graphics', 'min_state_time'))
if 'container' not in kwargs:
c = self.container = Builder.load_string(_grid_kv)
else:
c = None
if 'do_scroll_x' not in kwargs:
self.do_scroll_x = False
if 'size_hint' not in kwargs:
if 'size_hint_x' not in kwargs:
self.size_hint_x = None
if 'size_hint_y' not in kwargs:
self.size_hint_y = None
super(DropDown, self).__init__(**kwargs)
if c is not None:
super(DropDown, self).add_widget(c)
self.on_container(self, c)
Window.bind(
on_key_down=self.on_key_down,
size=self._reposition)
self.fbind('size', self._reposition)
def on_key_down(self, instance, key, scancode, codepoint, modifiers):
if key == 27 and self.get_parent_window():
self.dismiss()
return True
def on_container(self, instance, value):
if value is not None:
self.container.bind(minimum_size=self._reposition)
def open(self, widget):
'''Open the dropdown list and attach it to a specific widget.
Depending on the position of the widget within the window and
the height of the dropdown, the dropdown might be above or below
that widget.
'''
# ensure we are not already attached
if self.attach_to is not None:
self.dismiss()
# we will attach ourself to the main window, so ensure the
# widget we are looking for have a window
self._win = widget.get_parent_window()
if self._win is None:
raise DropDownException(
'Cannot open a dropdown list on a hidden widget')
self.attach_to = widget
widget.bind(pos=self._reposition, size=self._reposition)
self._reposition()
# attach ourself to the main window
self._win.add_widget(self)
def dismiss(self, *largs):
'''Remove the dropdown widget from the window and detach it from
the attached widget.
'''
Clock.schedule_once(self._real_dismiss, self.min_state_time)
def _real_dismiss(self, *largs):
if self.parent:
self.parent.remove_widget(self)
if self.attach_to:
self.attach_to.unbind(pos=self._reposition, size=self._reposition)
self.attach_to = None
self.dispatch('on_dismiss')
def on_dismiss(self):
pass
def select(self, data):
'''Call this method to trigger the `on_select` event with the `data`
selection. The `data` can be anything you want.
'''
self.dispatch('on_select', data)
if self.dismiss_on_select:
self.dismiss()
def on_select(self, data):
pass
def add_widget(self, *largs):
if self.container:
return self.container.add_widget(*largs)
return super(DropDown, self).add_widget(*largs)
def remove_widget(self, *largs):
if self.container:
return self.container.remove_widget(*largs)
return super(DropDown, self).remove_widget(*largs)
def clear_widgets(self):
if self.container:
return self.container.clear_widgets()
return super(DropDown, self).clear_widgets()
def on_touch_down(self, touch):
self._touch_started_inside = self.collide_point(*touch.pos)
if not self.auto_dismiss or self._touch_started_inside:
super(DropDown, self).on_touch_down(touch)
return True
def on_touch_move(self, touch):
if not self.auto_dismiss or self._touch_started_inside:
super(DropDown, self).on_touch_move(touch)
return True
def on_touch_up(self, touch):
if self.auto_dismiss and not self._touch_started_inside:
self.dismiss()
return True
super(DropDown, self).on_touch_up(touch)
return True
def _reposition(self, *largs):
# calculate the coordinate of the attached widget in the window
# coordinate system
win = self._win
widget = self.attach_to
if not widget or not win:
return
wx, wy = widget.to_window(*widget.pos)
wright, wtop = widget.to_window(widget.right, widget.top)
# set width and x
if self.auto_width:
self.width = wright - wx
# ensure the dropdown list doesn't get out on the X axis, with a
# preference to 0 in case the list is too wide.
x = wx
if x + self.width > win.width:
x = win.width - self.width
if x < 0:
x = 0
self.x = x
# determine if we display the dropdown upper or lower to the widget
if self.max_height is not None:
height = min(self.max_height, self.container.minimum_height)
else:
height = self.container.minimum_height
h_bottom = wy - height
h_top = win.height - (wtop + height)
if h_bottom > 0:
self.top = wy
self.height = height
elif h_top > 0:
self.y = wtop
self.height = height
else:
# none of both top/bottom have enough place to display the
# widget at the current size. Take the best side, and fit to
# it.
if h_top < h_bottom:
self.top = self.height = wy
else:
self.y = wtop
self.height = win.height - wtop
if __name__ == '__main__':
from kivy.uix.button import Button
from kivy.base import runTouchApp
def show_dropdown(button, *largs):
dp = DropDown()
dp.bind(on_select=lambda instance, x: setattr(button, 'text', x))
for i in range(10):
item = Button(text='hello %d' % i, size_hint_y=None, height=44)
item.bind(on_release=lambda btn: dp.select(btn.text))
dp.add_widget(item)
dp.open(button)
def touch_move(instance, touch):
instance.center = touch.pos
btn = Button(text='SHOW', size_hint=(None, None), pos=(300, 200))
btn.bind(on_release=show_dropdown, on_touch_move=touch_move)
runTouchApp(btn)
| 32.948187 | 79 | 0.637758 |
c9513246fb891acca7c9d10673dd08b11ba2ed75 | 2,343 | py | Python | PreprocessData/all_class_files/InternetCafe.py | wkid-neu/Schema | 4854720a15894dd814691a55e03329ecbbb6f558 | [
"MIT"
] | 3 | 2021-11-06T12:29:05.000Z | 2022-03-22T12:48:55.000Z | PreprocessData/all_class_files/InternetCafe.py | DylanNEU/Schema | 4854720a15894dd814691a55e03329ecbbb6f558 | [
"MIT"
] | null | null | null | PreprocessData/all_class_files/InternetCafe.py | DylanNEU/Schema | 4854720a15894dd814691a55e03329ecbbb6f558 | [
"MIT"
] | 1 | 2021-11-06T12:29:12.000Z | 2021-11-06T12:29:12.000Z | from PreprocessData.all_class_files.LocalBusiness import LocalBusiness
import global_data
class InternetCafe(LocalBusiness):
def __init__(self, additionalType=None, alternateName=None, description=None, disambiguatingDescription=None, identifier=None, image=None, mainEntityOfPage=None, name=None, potentialAction=None, sameAs=None, url=None, address=None, aggregateRating=None, alumni=None, areaServed=None, award=None, brand=None, contactPoint=None, department=None, dissolutionDate=None, duns=None, email=None, employee=None, event=None, faxNumber=None, founder=None, foundingDate=None, foundingLocation=None, funder=None, globalLocationNumber=None, hasOfferCatalog=None, hasPOS=None, isicV4=None, legalName=None, leiCode=None, location=None, logo=None, makesOffer=None, member=None, memberOf=None, naics=None, numberOfEmployees=None, owns=None, parentOrganization=None, publishingPrinciples=None, review=None, seeks=None, sponsor=None, subOrganization=None, taxID=None, telephone=None, vatID=None, additionalProperty=None, amenityFeature=None, branchCode=None, containedInPlace=None, containsPlace=None, geo=None, hasMap=None, isAccessibleForFree=None, maximumAttendeeCapacity=None, openingHoursSpecification=None, photo=None, publicAccess=None, smokingAllowed=None, specialOpeningHoursSpecification=None, currenciesAccepted=None, openingHours=None, paymentAccepted=None, priceRange=None):
LocalBusiness.__init__(self, additionalType, alternateName, description, disambiguatingDescription, identifier, image, mainEntityOfPage, name, potentialAction, sameAs, url, address, aggregateRating, alumni, areaServed, award, brand, contactPoint, department, dissolutionDate, duns, email, employee, event, faxNumber, founder, foundingDate, foundingLocation, funder, globalLocationNumber, hasOfferCatalog, hasPOS, isicV4, legalName, leiCode, location, logo, makesOffer, member, memberOf, naics, numberOfEmployees, owns, parentOrganization, publishingPrinciples, review, seeks, sponsor, subOrganization, taxID, telephone, vatID, additionalProperty, amenityFeature, branchCode, containedInPlace, containsPlace, geo, hasMap, isAccessibleForFree, maximumAttendeeCapacity, openingHoursSpecification, photo, publicAccess, smokingAllowed, specialOpeningHoursSpecification, currenciesAccepted, openingHours, paymentAccepted, priceRange)
| 292.875 | 1,273 | 0.832266 |
380aaf05b421d94ca36de64cc8a9ec3d81460520 | 437 | py | Python | apps/keyboard/core/load.py | ZhuoZhuoCrayon/AcousticKeyBoard-Web | 0a0ead78aec7ed03898fd51e076aa57df966508c | [
"MIT"
] | null | null | null | apps/keyboard/core/load.py | ZhuoZhuoCrayon/AcousticKeyBoard-Web | 0a0ead78aec7ed03898fd51e076aa57df966508c | [
"MIT"
] | null | null | null | apps/keyboard/core/load.py | ZhuoZhuoCrayon/AcousticKeyBoard-Web | 0a0ead78aec7ed03898fd51e076aa57df966508c | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import logging
import pickle
from djangocli.constants import LogModule
from in_python.core.pre.load import DataSetUnit
logger = logging.getLogger(LogModule.APPS)
def load_dataset_unit(save_path: str) -> DataSetUnit:
with open(file=save_path, mode="rb") as ds_unit_reader:
dataset_unit = pickle.load(ds_unit_reader)
logger.info(f"read dataset_unit: {dataset_unit}")
return dataset_unit
| 27.3125 | 59 | 0.748284 |
527fd484b89a3114848d859efed578496371a8af | 5,998 | py | Python | gdata/calendar_resource/data.py | gitdaniel228/realtor | 4366d57b064be87b31c8a036b3ed7a99b2036461 | [
"BSD-3-Clause"
] | 2 | 2015-05-15T20:28:45.000Z | 2017-07-23T20:35:59.000Z | lib/gdata/calendar_resource/data.py | motord/Motorcycle-Diaries | bb5e5e2d4d79573b4231e760d7662db26c03a55e | [
"BSD-3-Clause"
] | null | null | null | lib/gdata/calendar_resource/data.py | motord/Motorcycle-Diaries | bb5e5e2d4d79573b4231e760d7662db26c03a55e | [
"BSD-3-Clause"
] | 2 | 2021-05-03T01:30:32.000Z | 2022-03-23T19:53:08.000Z | #!/usr/bin/python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data model for parsing and generating XML for the Calendar Resource API."""
__author__ = 'Vic Fryzel <vf@google.com>'
import atom.core
import atom.data
import gdata.apps
import gdata.apps_property
import gdata.data
# This is required to work around a naming conflict between the Google
# Spreadsheets API and Python's built-in property function
pyproperty = property
# The apps:property name of the resourceId property
RESOURCE_ID_NAME = 'resourceId'
# The apps:property name of the resourceCommonName property
RESOURCE_COMMON_NAME_NAME = 'resourceCommonName'
# The apps:property name of the resourceDescription property
RESOURCE_DESCRIPTION_NAME = 'resourceDescription'
# The apps:property name of the resourceType property
RESOURCE_TYPE_NAME = 'resourceType'
class CalendarResourceEntry(gdata.data.GDEntry):
"""Represents a Calendar Resource entry in object form."""
property = [gdata.apps_property.AppsProperty]
def _GetProperty(self, name):
"""Get the apps:property value with the given name.
Args:
name: string Name of the apps:property value to get.
Returns:
The apps:property value with the given name, or None if the name was
invalid.
"""
for p in self.property:
if p.name == name:
return p.value
return None
def _SetProperty(self, name, value):
"""Set the apps:property value with the given name to the given value.
Args:
name: string Name of the apps:property value to set.
value: string Value to give the apps:property value with the given name.
"""
for i in range(len(self.property)):
if self.property[i].name == name:
self.property[i].value = value
return
self.property.append(gdata.apps_property.AppsProperty(name=name, value=value))
def GetResourceId(self):
"""Get the resource ID of this Calendar Resource object.
Returns:
The resource ID of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_ID_NAME)
def SetResourceId(self, value):
"""Set the resource ID of this Calendar Resource object.
Args:
value: string The new resource ID value to give this object.
"""
self._SetProperty(RESOURCE_ID_NAME, value)
resource_id = pyproperty(GetResourceId, SetResourceId)
def GetResourceCommonName(self):
"""Get the common name of this Calendar Resource object.
Returns:
The common name of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_COMMON_NAME_NAME)
def SetResourceCommonName(self, value):
"""Set the common name of this Calendar Resource object.
Args:
value: string The new common name value to give this object.
"""
self._SetProperty(RESOURCE_COMMON_NAME_NAME, value)
resource_common_name = pyproperty(
GetResourceCommonName,
SetResourceCommonName)
def GetResourceDescription(self):
"""Get the description of this Calendar Resource object.
Returns:
The description of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_DESCRIPTION_NAME)
def SetResourceDescription(self, value):
"""Set the description of this Calendar Resource object.
Args:
value: string The new description value to give this object.
"""
self._SetProperty(RESOURCE_DESCRIPTION_NAME, value)
resource_description = pyproperty(
GetResourceDescription,
SetResourceDescription)
def GetResourceType(self):
"""Get the type of this Calendar Resource object.
Returns:
The type of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_TYPE_NAME)
def SetResourceType(self, value):
"""Set the type value of this Calendar Resource object.
Args:
value: string The new type value to give this object.
"""
self._SetProperty(RESOURCE_TYPE_NAME, value)
resource_type = pyproperty(GetResourceType, SetResourceType)
def __init__(self, resource_id=None, resource_common_name=None,
resource_description=None, resource_type=None, *args, **kwargs):
"""Constructs a new CalendarResourceEntry object with the given arguments.
Args:
resource_id: string (optional) The resource ID to give this new object.
resource_common_name: string (optional) The common name to give this new
object.
resource_description: string (optional) The description to give this new
object.
resource_type: string (optional) The type to give this new object.
args: The other parameters to pass to gdata.entry.GDEntry constructor.
kwargs: The other parameters to pass to gdata.entry.GDEntry constructor.
"""
super(CalendarResourceEntry, self).__init__(*args, **kwargs)
if resource_id:
self.resource_id = resource_id
if resource_common_name:
self.resource_common_name = resource_common_name
if resource_description:
self.resource_description = resource_description
if resource_type:
self.resource_type = resource_type
class CalendarResourceFeed(gdata.data.GDFeed):
"""Represents a feed of CalendarResourceEntry objects."""
# Override entry so that this feed knows how to type its list of entries.
entry = [CalendarResourceEntry]
| 30.917526 | 82 | 0.722908 |
295ea072dcd126aedc9cbfdde389f959429e528e | 5,815 | py | Python | test_ms.py | Spritea/pytorch-semseg-fp16-one-titan | 33dcd61b1f703f52a5f7ba4ac758c3a1726e4273 | [
"MIT"
] | null | null | null | test_ms.py | Spritea/pytorch-semseg-fp16-one-titan | 33dcd61b1f703f52a5f7ba4ac758c3a1726e4273 | [
"MIT"
] | null | null | null | test_ms.py | Spritea/pytorch-semseg-fp16-one-titan | 33dcd61b1f703f52a5f7ba4ac758c3a1726e4273 | [
"MIT"
] | null | null | null | import sys, os
import torch
import argparse
import timeit
import numpy as np
import scipy.misc as misc
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.utils import data
from tqdm import tqdm
from ptsemseg.models import get_model
from ptsemseg.loader import get_loader, get_data_path
from ptsemseg.utils import convert_state_dict
import yaml
from pathlib import Path
import natsort
import cv2 as cv
def test(args,cfg):
# os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# device=torch.device("cuda:0")
# device_1=torch.device("cpu")
model_file_name = os.path.split(args.model_path)[1]
model_name = model_file_name[: model_file_name.find("_")]
IMG_Path=Path(args.img_path)
IMG_File=natsort.natsorted(list(IMG_Path.glob("*.png")),alg=natsort.PATH)
IMG_Str=[]
for i in IMG_File:
IMG_Str.append(str(i))
# Setup image
print("Read Input Image from : {}".format(args.img_path))
data_loader = get_loader(args.dataset)
data_path = get_data_path(args.dataset,config_file=cfg)
loader = data_loader(data_path, is_transform=True, img_norm=args.img_norm)
n_classes = loader.n_classes
# Setup Model
model = get_model(cfg['model'], n_classes)
state = convert_state_dict(torch.load(args.model_path)["model_state"])
# state=torch.load(args.model_path)["model_state"]
model.load_state_dict(state)
model.eval()
model.to(device)
for j in tqdm(range(len(IMG_Str))):
img_path=IMG_Str[j]
img_input = misc.imread(img_path)
sp=list(img_input.shape)
#shape height*width*channel
sp=sp[0:2]
ori_size=tuple(sp)
# img = img[:, :, ::-1]
# multiscale
# img_125=cv.resize(img,dsize=(0,0),fx=1.25,fy=1.25,interpolation=cv.INTER_LINEAR)
# img_075=cv.resize(img,dsize=(0,0),fx=0.75,fy=0.75,interpolation=cv.INTER_LINEAR)
# scale_list=[2.0,1.75,1.5,1.25,1,0.75,0.5]
scale_list=[1.5,1.25,1,0.75,0.5]
# scale_list=[2.0]
multi_avg=torch.zeros((1,6,512,512),dtype=torch.float32).to(device)
# torch.zeros(batch-size,num-classes,height,width)
for scale in scale_list:
if scale!=1:
img=cv.resize(img_input,dsize=(0,0),fx=scale,fy=scale,interpolation=cv.INTER_LINEAR)
else:
img=img_input
img = img.astype(np.float64)
# img -= loader.mean
if args.img_norm:
img = img.astype(float) / 255.0
# NHWC -> NCHW
img = img.transpose(2, 0, 1)
img = np.expand_dims(img, 0)
img = torch.from_numpy(img).float()
images = img.to(device)
outputs = model(images)
# del images
# bilinear is ok for both upsample and downsample
if scale!=1:
outputs=F.upsample(outputs,ori_size,mode='bilinear',align_corners=False)
# outputs=outputs.to(device)
multi_avg=multi_avg+outputs
# del outputs
outputs=multi_avg/len(scale_list)
# out_path="test_out/mv3_1_true_2_res50_data10_MS/mv3_1_true_2_res50_data10_MS_7/"+Path(img_path).stem+"_S5_ave.pt"
# torch.save(outputs,out_path)
pred = np.squeeze(outputs.data.max(1)[1].cpu().numpy(), axis=0)
decoded = loader.decode_segmap(pred)
out_path="test_out/mv3_1_true_2_res50_data15/ms5/"+Path(img_path).name
decoded_bgr = cv.cvtColor(decoded, cv.COLOR_RGB2BGR)
# misc.imsave(out_path, decoded)
cv.imwrite(out_path, decoded_bgr)
# print("Classes found: ", np.unique(pred))
# print("Segmentation Mask Saved at: {}".format(args.out_path))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Params")
parser.add_argument(
"--model_path",
nargs="?",
type=str,
default="pretrain/data15/mv3_res50_my_best_model.pkl",
help="Path to the saved model",
)
parser.add_argument(
"--dataset",
nargs="?",
type=str,
default="my",
help="Dataset to use ['pascal, camvid, ade20k etc']",
)
parser.add_argument(
"--img_norm",
dest="img_norm",
action="store_true",
help="Enable input image scales normalization [0, 1] \
| True by default",
)
parser.add_argument(
"--no-img_norm",
dest="img_norm",
action="store_false",
help="Disable input image scales normalization [0, 1] |\
True by default",
)
parser.set_defaults(img_norm=True)
parser.add_argument(
"--dcrf",
dest="dcrf",
action="store_true",
help="Enable DenseCRF based post-processing | \
False by default",
)
parser.add_argument(
"--no-dcrf",
dest="dcrf",
action="store_false",
help="Disable DenseCRF based post-processing | \
False by default",
)
parser.set_defaults(dcrf=False)
parser.add_argument(
"--img_path", nargs="?", type=str,
default="dataset/15-Postdam-train24/val", help="Path of the input image"
)
parser.add_argument(
"--out_path",
nargs="?",
type=str,
default="tk.png",
help="Path of the output segmap",
)
parser.add_argument(
"--config",
nargs="?",
type=str,
default="configs/mv3_1_true_2_res50_data15.yml",
help="Configuration file to use"
)
args = parser.parse_args()
with open(args.config) as fp:
cfg = yaml.load(fp)
test(args,cfg)
| 31.775956 | 123 | 0.607911 |
3728628b015a560c85154e4feb29a1d119f61e8b | 1,949 | py | Python | read_data/read_TCGA_data.py | fuhrmanj/TRANSACT_manuscript | 71ca2ec42bdd5d547d4b965aa7f84838bfd5b812 | [
"MIT"
] | 5 | 2020-10-26T13:18:40.000Z | 2022-02-21T10:03:09.000Z | read_data/read_TCGA_data.py | fuhrmanj/TRANSACT_manuscript | 71ca2ec42bdd5d547d4b965aa7f84838bfd5b812 | [
"MIT"
] | 1 | 2022-03-21T09:55:53.000Z | 2022-03-23T13:48:47.000Z | read_data/read_TCGA_data.py | fuhrmanj/TRANSACT_manuscript | 71ca2ec42bdd5d547d4b965aa7f84838bfd5b812 | [
"MIT"
] | 2 | 2020-11-04T15:40:58.000Z | 2021-01-26T09:37:33.000Z | # -*- coding: utf-8 -*-
"""
@author: Soufiane Mourragui
2020/01/16
READ TCGA DATA
"""
import os
import pandas as pd
import numpy as np
from functools import reduce
def read_one_TCGA_modality(tissues,
projects,
data_type,
folder):
if type(tissues) != list:
tissues = [tissues]
if type(projects) != list:
projects = [projects]
folders = np.array(['%s/%s/TCGA_%s_data.pkl'%(folder,
data_type,
data_type)
for t in tissues for p in projects])
folders = folders[[os.path.exists(f) for f in folders]]
if folders.shape[0] == 0:
return pd.DataFrame()
data_df = [pd.read_pickle(f, compression='gzip') for f in folders]
# Take same features
unique_features = reduce(np.intersect1d, [df.columns for df in data_df])
data_df = pd.concat([df[unique_features] for df in data_df])
return data_df
def read_TCGA_data(data_types=['rnaseq'],
tissues=None,
projects=None,
folder='/DATA/s.mourragui/data/2020_01_TCGA_data'):
# If folder is None, set to default
data_folder = folder or '/DATA/s.mourragui/data/2020_01_TCGA_data'
if type(tissues) == str:
tissues = [tissues]
data_df = {'%s_%s'%('-'.join(tissues),d):read_one_TCGA_modality(tissues, projects, d, data_folder)\
for d in data_types}
data_df = {d:data_df[d] for d in data_df if not data_df[d].empty}
for i in data_df:
data_df[i].index = [e[:19] for e in data_df[i].index]
# Merge samples since correlations are very good
data_df[i] = data_df[i].reset_index().groupby('index').agg('mean')
unique_samples = reduce(np.intersect1d, [data_df[i].index for i in data_df])
return {d:data_df[d].loc[unique_samples] for d in data_df} | 30.453125 | 103 | 0.590559 |
363e6578718b4b4025ce68c6890669884631b5da | 2,861 | py | Python | neurotic/nlp/twitter/test.py | necromuralist/Neurotic-Networking | 20f46dec5d890bd57abd802b6ebf219f0e8e7611 | [
"MIT"
] | null | null | null | neurotic/nlp/twitter/test.py | necromuralist/Neurotic-Networking | 20f46dec5d890bd57abd802b6ebf219f0e8e7611 | [
"MIT"
] | 3 | 2021-01-11T01:42:31.000Z | 2021-11-10T19:44:25.000Z | neurotic/nlp/twitter/test.py | necromuralist/Neurotic-Networking | 20f46dec5d890bd57abd802b6ebf219f0e8e7611 | [
"MIT"
] | null | null | null | # from pypi
import attr
import numpy
# this project
from .counter import WordCounter
from .sentiment import TweetSentiment
from .vectorizer import TweetVectorizer
@attr.s(auto_attribs=True)
class LogisticRegression:
"""train and predict tweet sentiment
Args:
iterations: number of times to run gradient descent
learning_rate: how fast to change the weights during training
"""
iterations: int
learning_rate: float
_weights: numpy.array
final_loss: float=None
@property
def weights(self) -> numpy.array:
"""The weights for the regression
Initially this will be an array of zeros.
"""
if self._weights is None:
self._weights = numpy.zeros((3, 1))
return self._weights
def gradient_descent(self, x: numpy.ndarray, y: numpy.ndarray):
"""Finds the weights for the model
Args:
x: the tweet vectors
y: the positive/negative labels
"""
assert len(x) == len(y)
rows = len(x)
self.learning_rate /= rows
for iteration in range(self.iterations):
y_hat = sigmoid(x.dot(self.weights))
# average loss
loss = numpy.squeeze(-((y.T.dot(numpy.log(y_hat))) +
(1 - y.T).dot(numpy.log(1 - y_hat))))/rows
gradient = ((y_hat - y).T.dot(x)).sum(axis=0, keepdims=True)
self.weights -= self.learning_rate * gradient.T
return loss
def fit(self, x_train: numpy.ndarray, y_train:numpy.ndarray):
"""fits the weights for the logistic regression
Note:
as a side effect this also sets counter, loss, and sentimenter attributes
Args:
x_train: the training tweets
y_train: the training labels
"""
self.counter = WordCounter(x_train, y_train)
vectorizer = TweetVectorizer(x_train, self.counter.counts, processed=False)
y = y_train.values.reshape((-1, 1))
self.loss = self.gradient_descent(vectorizer.vectors, y)
return
def predict(self, x: numpy.ndarray) -> numpy.ndarray:
"""Predict the labels for the inputs
Args:
x: a list or array of tweets
Returns:
array of predicted labels for the tweets
"""
vectorizer = TweetVectorizer(x, self.counter.counts, processed=False)
sentimenter = TweetSentiment(vectorizer, self.weights)
return sentimenter()
def score(self, x: numpy.ndarray, y: numpy.ndarray) -> float:
"""Get the mean accuracy
Args:
x: arrray of tweets
y: labels for the tweets
Returns:
mean accuracy
"""
predictions = self.predict(x)
correct = sum(predictions.T[0] == y)
return correct/len(x)
| 30.43617 | 83 | 0.600839 |
1b15caf66808765a4050212986decaeff4b41fd3 | 140 | py | Python | skgpytorch/models/__init__.py | palak-purohit/skgpytorch | f1143a0f6a4858be4485ff465b3d6da7b28067f0 | [
"MIT"
] | 5 | 2022-01-16T00:12:48.000Z | 2022-03-04T12:59:26.000Z | skgpytorch/models/__init__.py | palak-purohit/skgpytorch | f1143a0f6a4858be4485ff465b3d6da7b28067f0 | [
"MIT"
] | 3 | 2022-02-25T10:52:46.000Z | 2022-03-18T12:30:51.000Z | skgpytorch/models/__init__.py | palak-purohit/skgpytorch | f1143a0f6a4858be4485ff465b3d6da7b28067f0 | [
"MIT"
] | null | null | null | from .exact_gp import ExactGPRegressor
from .base import BaseRegressor
from .sv_gp import SVGPRegressor
from .sparse_gp import SGPRegressor
| 28 | 38 | 0.857143 |
d80e1874aa88f7518eef457b71615679cc74f1a7 | 1,058 | py | Python | BugTracker/bugzillaProjectBugs.py | luisibanez/CommunityAnalyzer | dc408405cf00d189ec764e37a45f83f09d2710ce | [
"Apache-2.0"
] | 2 | 2019-01-20T21:49:03.000Z | 2019-04-28T17:56:24.000Z | BugTracker/bugzillaProjectBugs.py | luisibanez/CommunityAnalyzer | dc408405cf00d189ec764e37a45f83f09d2710ce | [
"Apache-2.0"
] | null | null | null | BugTracker/bugzillaProjectBugs.py | luisibanez/CommunityAnalyzer | dc408405cf00d189ec764e37a45f83f09d2710ce | [
"Apache-2.0"
] | 3 | 2015-04-27T16:49:18.000Z | 2019-05-19T01:26:38.000Z | import requests
import sys
import json
import time
import pymongo
import dateutil
base_url = sys.argv[1]
project = sys.argv[2]
output_host = sys.argv[3]
output_db = sys.argv[4]
output_collection = sys.argv[5]
# output_file = sys.argv[3]
coll = pymongo.MongoClient(output_host)[output_db][output_collection]
url = base_url + '/rest/bug?product=' + project
offset = 0
batch = 1000
done = False
while done == False:
print '%06d' % offset
content = requests.get(url + '&limit=' + str(batch) + '&offset=' + str(offset)).content
loaded = json.loads(content)
if len(loaded["bugs"]) > 0:
for d in loaded["bugs"]:
if isinstance(d['creation_time'], (str, unicode)):
d['creation_time'] = dateutil.parser.parse(d['creation_time'])
if isinstance(d['last_change_time'], (str, unicode)):
d['last_change_time'] = dateutil.parser.parse(d['last_change_time'])
coll.insert(loaded["bugs"])
else:
done = True
offset += batch
print 'sleeping 10s...'
time.sleep(10)
| 28.594595 | 91 | 0.642722 |
c5c1254e925b6d85a1d87eeda4555bdb2da29f1e | 622 | py | Python | src/probnum/quad/policies/sample_measure.py | NinaEffenberger/probnum | 595f55f9f235fd0396d02b9a6f828aba2383dceb | [
"MIT"
] | 4 | 2020-12-07T11:56:48.000Z | 2021-04-16T14:50:40.000Z | src/probnum/quad/policies/sample_measure.py | NinaEffenberger/probnum | 595f55f9f235fd0396d02b9a6f828aba2383dceb | [
"MIT"
] | 42 | 2021-04-12T08:11:41.000Z | 2022-03-28T00:21:55.000Z | src/probnum/quad/policies/sample_measure.py | NinaEffenberger/probnum | 595f55f9f235fd0396d02b9a6f828aba2383dceb | [
"MIT"
] | null | null | null | """Randomly draw nodes from the measure to use for integration."""
import numpy as np
from probnum.quad._integration_measures import IntegrationMeasure
def sample_from_measure(nevals: int, measure: IntegrationMeasure) -> np.ndarray:
r"""Acquisition policy: Draw random samples from the integration measure.
Parameters
----------
nevals : int
Number of function evaluations.
measure :
The integration measure :math:`\mu`.
Returns
-------
x : np.ndarray
Nodes where the integrand will be evaluated.
"""
return measure.sample(nevals).reshape(nevals, -1)
| 24.88 | 80 | 0.680064 |
a2a0483b595091f311315b13580c1d9c13ff4eef | 10,903 | py | Python | camd3/infrastructure/component/component.py | mamrhein/CAmD3 | d20f62295771a297c3fbb314beef314e5ec7a2b5 | [
"BSD-2-Clause"
] | null | null | null | camd3/infrastructure/component/component.py | mamrhein/CAmD3 | d20f62295771a297c3fbb314beef314e5ec7a2b5 | [
"BSD-2-Clause"
] | null | null | null | camd3/infrastructure/component/component.py | mamrhein/CAmD3 | d20f62295771a297c3fbb314beef314e5ec7a2b5 | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Name: component
# Purpose: Basic component infrastructure
#
# Author: Michael Amrhein (michael@adrhinum.de)
#
# Copyright: (c) 2014 Michael Amrhein
# License: This program is part of a larger application. For license
# details please read the file LICENSE.TXT provided together
# with the application.
# ----------------------------------------------------------------------------
# $Source$
# $Revision$
"""Basic component infrastructure"""
# standard lib imports
from abc import ABCMeta, abstractmethod
from itertools import chain
from typing import (Any, Callable, Iterable, MutableMapping,
MutableSequence, Sequence, Tuple)
# local imports
from .attribute import Attribute
from .exceptions import ComponentLookupError
from .immutable import Immutable
from .signature import _is_instance, _is_subclass, signature
from ...gbbs.tools import iter_subclasses
Adapter = Callable[[Any], 'Component']
_AdapterRegistry = MutableMapping[type, MutableSequence[Adapter]]
class _ABCSet(set):
def __init__(self, it: Iterable[type] = ()) -> None:
for elem in it:
self.add(elem)
def add(self, abc: type) -> None:
to_be_removed = []
for cls in self:
if _is_subclass(cls, abc):
return # we already have a more specific type
if _is_subclass(abc, cls):
# replace type by more specific one
# (we can't do that directly while iterating over the set)
to_be_removed.append(cls)
super().add(abc)
for cls in to_be_removed:
self.remove(cls)
INIT_MARKER = '@'
class ComponentMeta(ABCMeta):
"""Meta class to create components.
Args:
cls_name(str): name of new component
bases(Tuple[type, ...]): base classes
namespace(Mapping[str, Any]): namespace of new component
**kwds (Any): additional class statement args
Returns:
ComponentMeta: new component class
"""
def __new__(metacls, cls_name: str, bases: Tuple[type, ...],
namespace: MutableMapping[str, Any],
**kwds: Any) -> 'ComponentMeta':
# force __slots__ for attribute of immutable components
if any(issubclass(cls, Immutable) for cls in bases):
all_bases = set(chain(*(cls.__mro__[:-1] for cls in bases
if cls is not object)))
if any('__slots__' not in cls.__dict__
for cls in all_bases):
raise TypeError("All base classes of '" + cls_name +
"' must have an attribute '__slots__'.")
slots = namespace.get('__slots__', ())
new_slots = []
for name, attr in namespace.items():
if isinstance(attr, Attribute):
# type.__new__ will call __set_name__ later, but we
# need to do it here in order to get the private member
# names
attr.__set_name__(None, name)
priv_member = attr._priv_member
if priv_member not in slots:
new_slots.append(priv_member)
namespace['__slots__'] = tuple(chain(slots, new_slots))
# create class
cls = super().__new__(metacls, cls_name, bases, namespace, **kwds)
# now the new class is ready
return cls
@classmethod
def __prepare__(metacls, name: str, bases: Tuple[type, ...],
**kwds: Any) -> MutableMapping:
namespace = {}
# additional class attributes
adapter_registry = {} # type: _AdapterRegistry
namespace['__virtual_bases__'] = _ABCSet()
namespace['__adapters__'] = adapter_registry
return namespace
def __call__(cls, *args, **kwds) -> 'Component':
"""Return new instance of `cls`."""
comp = cls.__new__(cls, *args, **kwds)
if isinstance(comp, cls):
# mark instance as 'not yet initialized' (if it has a __dict__)
try:
comp.__dict__[INIT_MARKER] = True
except AttributeError:
pass
comp.__init__(*args, **kwds)
# remove marker
try:
del comp.__dict__[INIT_MARKER]
except AttributeError:
pass
return comp
def __dir__(cls) -> Sequence[str]:
"""dir(cls)"""
return sorted(set(chain(dir(type(cls)), *(ns.__dict__.keys()
for ns in cls.__mro__))))
def __getitem__(cls, obj: Any) -> 'Component':
"""Shortcut for cls.adapt(obj)."""
return cls.adapt(obj)
def adapt(cls, obj: Any) -> 'Component':
"""Return an object adapting `obj` to the interface defined by
`cls`."""
if isinstance(obj, cls):
# obj provides the interface, so just return it
return obj
# look for adapter adapting obj to interface
try:
adapter = cls.get_adapter(obj)
except ComponentLookupError:
raise TypeError(f"Cannot adapt instance of type '{type(obj)}' "
f"to '{cls.__name__ }'.")
else:
try:
return adapter(obj)
except TypeError:
raise TypeError(f"Cannot adapt instance of type '{type(obj)}'"
f" to '{cls.__name__ }'.")
except Exception:
raise ValueError(f"Cannot adapt given object '{repr(obj)}' "
f"to '{cls.__name__}'.")
@property
def attr_names(cls) -> Tuple[str, ...]:
"""Return the names of all attributes defined by the component (in
definition order).
"""
return tuple(name for name, item in cls.__dict__.items()
if isinstance(item, Attribute))
@property
def all_attr_names(cls) -> Tuple[str, ...]:
"""Return the names of all attributes defined by the component and its
base components (in definition order).
"""
seen = {}
return tuple(seen.setdefault(name, name)
for name in chain(*(acls.attr_names
for acls
in reversed(cls.__mro__[:-1])
if issubclass(acls, Component)))
if name not in seen)
def register(cls, subcls: type):
"""Register a virtual subclass of the component."""
try:
subcls.__virtual_bases__.add(cls)
except AttributeError: # `subcls` is not a component,
pass # so go without a back reference
return super().register(subcls)
def add_adapter(cls, adapter: Adapter) -> Adapter:
"""Add `adapter` to the list of adapters providing an instance of
`cls`."""
sgn = signature(adapter)
return_type = sgn.return_type
assert _is_subclass(return_type, cls), \
"Adapter returns instance of '{}', not a subclass of '{}'".format(
return_type, cls)
arg_types, var_arg_type = sgn.arg_types, sgn.var_arg_type
assert var_arg_type is None and len(arg_types) == 1, \
"Adapter must have exactly 1 argument."
arg_type = arg_types[0]
try:
adapters = cls.__adapters__[arg_type]
except KeyError:
cls.__adapters__[arg_type] = [adapter]
else:
if adapter not in adapters:
adapters.append(adapter)
return adapter
def _iter_adapters(cls) -> Iterable[Tuple[type, Adapter]]:
"""Return an iterable of type / adapter pairs"""
for required, adapters in cls.__adapters__.items():
if adapters:
yield required, adapters[-1]
for subcls in iter_subclasses(cls):
try:
items = subcls.__adapters__.items()
except AttributeError:
pass
else:
for required, adapters in items:
if adapters:
yield required, adapters[-1]
def get_adapter(cls, obj: Any) -> Adapter:
"""Return an adapter adapting `obj` to the interface defined by `cls`.
"""
type_found = None
adapter_found = None
for required, adapter in cls._iter_adapters():
if _is_instance(obj, required):
if not type_found or _is_subclass(required, type_found):
# required is more specific
type_found, adapter_found = required, adapter
if type_found:
return adapter_found
raise ComponentLookupError(f"'{cls.__name__}: no adapter for "
f"'{repr(obj)}' found.")
def __repr__(cls):
"""repr(cls)"""
return f"{cls.__module__}.{cls.__qualname__}"
class Component(metaclass=ComponentMeta):
"""Abstract base class for components."""
__slots__ = ()
@abstractmethod
def __init__(self, *args, **kwds) -> None:
"""Initialize instance of component."""
@property
def initialized(self):
"""Return `True` if `self` is initialized, `False` otherwise.
Initialized means that either
* `self.__init__` has been called and has returned, or
* the components subclass `__new__` method did not return an instance
of that class (and `self.__init__` therefor has not been called).
"""
try:
self.__dict__[INIT_MARKER]
except (AttributeError, KeyError):
return True
else:
return False
def implementer(*interfaces: type) -> Callable[[type], type]:
"""Class decorator registering a class that implements the given
interfaces.
It also sets doc strings of methods of the class having no doc string to
the doc string of the corresponding method from interfaces.
"""
def _register_cls(cls: type) -> type:
for interface in interfaces:
interface.register(cls)
it = ((name, member) for name, member in cls.__dict__.items()
if callable(member) and member.__doc__ is None)
for name, member in it:
for interface in interfaces:
try:
doc = getattr(interface, name).__doc__
except AttributeError:
pass
else:
member.__doc__ = doc
break
return cls
return _register_cls
__all__ = [
'Component',
'implementer',
]
| 36.102649 | 78 | 0.553976 |
a02dc0264a1b64bccc54ee514aaed9c471dee560 | 230 | py | Python | lang.py | wongalvis/WiktionaryCrawler | 4a61e5f28d4bca591b10f9bcc2b3c0d29138fc15 | [
"Unlicense"
] | null | null | null | lang.py | wongalvis/WiktionaryCrawler | 4a61e5f28d4bca591b10f9bcc2b3c0d29138fc15 | [
"Unlicense"
] | null | null | null | lang.py | wongalvis/WiktionaryCrawler | 4a61e5f28d4bca591b10f9bcc2b3c0d29138fc15 | [
"Unlicense"
] | 1 | 2019-03-28T00:25:46.000Z | 2019-03-28T00:25:46.000Z | import config
if config.lang == "zh":
from filters import zh as filter
from parsers import zh as parser
## the list goes on
def can(page):
return filter.can(page)
def parse(page, htmldoc):
return parser.parse(page, htmldoc) | 19.166667 | 35 | 0.734783 |
b46060daff2c376ad61cd828f5f2709f4c2fb195 | 776 | py | Python | db_cassandra.py | Sparab16/Flask-API-Demonstration | 19c0d82fe5ea22cdf83b3c7603a2a2a55707027c | [
"MIT"
] | 1 | 2022-02-23T03:45:04.000Z | 2022-02-23T03:45:04.000Z | db_cassandra.py | KrishAleti/Flask-API-Demonstration | 19c0d82fe5ea22cdf83b3c7603a2a2a55707027c | [
"MIT"
] | null | null | null | db_cassandra.py | KrishAleti/Flask-API-Demonstration | 19c0d82fe5ea22cdf83b3c7603a2a2a55707027c | [
"MIT"
] | 2 | 2021-11-20T10:43:08.000Z | 2022-02-23T03:09:09.000Z | from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster
from flask import render_template
from Logging import Log
# Init the log
log = Log().create_log()
class Cassandra:
def create_connection(self, username, password, secure_bundle_path):
try:
cloud_config = {
'secure_connect_bundle': secure_bundle_path
}
auth_provider = PlainTextAuthProvider(username, password)
cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider)
session = cluster.connect()
return session
except Exception as e:
log.exception(e)
render_template('error.html', e=e)
return [e, False]
| 28.740741 | 79 | 0.630155 |
3abe12eb013018d9f079a43204667e9f67d0bbe5 | 4,495 | py | Python | normalize/property/json.py | mattrowe/normalize | 1034e9a2660c7ae7aaa09993ef9ff27a981e0396 | [
"MIT"
] | null | null | null | normalize/property/json.py | mattrowe/normalize | 1034e9a2660c7ae7aaa09993ef9ff27a981e0396 | [
"MIT"
] | null | null | null | normalize/property/json.py | mattrowe/normalize | 1034e9a2660c7ae7aaa09993ef9ff27a981e0396 | [
"MIT"
] | null | null | null | #
# This file is a part of the normalize python library
#
# normalize is free software: you can redistribute it and/or modify
# it under the terms of the MIT License.
#
# normalize is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
#
# You should have received a copy of the MIT license along with
# normalize. If not, refer to the upstream repository at
# http://github.com/hearsaycorp/normalize
#
from __future__ import absolute_import
from normalize.property import Property
from normalize.property import SafeProperty
from normalize.property.coll import DictProperty
from normalize.property.coll import ListProperty
class _Default(object):
def __repr__(self):
return "<prop.name>"
_default = _Default()
class JsonProperty(Property):
'''Object property wrapper for record json data'''
__trait__ = 'json'
def __init__(self, json_name=_default, json_in=None, json_out=None,
**kwargs):
"""Create a new property with JSON mapping overrides. You
generally don't need to use this directly; simply specifying the
options using ``json_``\ *X* to a superclass like ``Property()``
is sufficient.
Arguments:
``json_name=``\ *STR*
Specify the key in the input/output dictionary to use
for this property when marshalling to/from JSON.
``json_in=``\ *FUNCTION*
Specify a function which converts the JSON form of this
property to the python form. This is called *before* the
``isa=`` check and ``coerce=`` function, and is always
called if the key exists on the marshaled in structure.
This function can recurse into
:py:func:`normalize.record.from_json` if required.
``json_out=``\ *FUNCTION*
Specify a function which converts a property from the
python form to a form which your JSON library can handle.
You'll probably want to convert native python objects to
strings, in a form which can be reversed by the
``json_in`` function.
This function should recurse into
:py:func:`normalize.record.to_json` if required.
"""
super(JsonProperty, self).__init__(**kwargs)
self._json_name = json_name
self.json_in = json_in
self.json_out = json_out
@property
def json_name(self):
"""Key name for this attribute in JSON dictionary. Defaults to
the attribute name in the class it is bound to."""
return self.name if self._json_name is _default else self._json_name
def to_json(self, propval, extraneous=False, to_json_func=None):
"""This function calls the ``json_out`` function, if it was specified,
otherwise continues with JSON conversion of the value in the slot by
calling ``to_json_func`` on it.
"""
if self.json_out:
return self.json_out(propval)
else:
if not to_json_func:
from normalize.record.json import to_json
to_json_func = to_json
return to_json_func(propval, extraneous)
def from_json(self, json_data):
"""This function calls the ``json_in`` function, if it was
specified, otherwise passes through."""
return self.json_in(json_data) if self.json_in else json_data
class SafeJsonProperty(JsonProperty, SafeProperty):
pass
# late imports to allow circular dependencies to proceed
from normalize.record.json import JsonRecordDict # noqa
from normalize.record.json import JsonRecordList # noqa
class JsonListProperty(ListProperty, JsonProperty):
"""A property which map to a list of a known item type in JSON.
It can also map a dictionary with some top level keys (eg, streaming
information) and a key with the actual list contents. See
:py:mod:`normalize.record.json` for more details.
"""
coll_type = JsonRecordList
class JsonDictProperty(DictProperty, JsonProperty):
"""A property which map to a dictionary of a known item type in JSON.
Currently the key type is not enforced.
"""
coll_type = JsonRecordDict
# deprecated compatibility exports
JsonCollectionProperty = JsonListProperty
| 35.674603 | 78 | 0.671413 |
d2a7fb13201480f6050d1e371099d369938bc05d | 798 | py | Python | src/frontend/authenticator/authenticator.py | Marco9412/PyMusicServer3 | fa264c4344a56ff15d08ec5ffdc9b24cc61db29e | [
"Apache-2.0"
] | null | null | null | src/frontend/authenticator/authenticator.py | Marco9412/PyMusicServer3 | fa264c4344a56ff15d08ec5ffdc9b24cc61db29e | [
"Apache-2.0"
] | null | null | null | src/frontend/authenticator/authenticator.py | Marco9412/PyMusicServer3 | fa264c4344a56ff15d08ec5ffdc9b24cc61db29e | [
"Apache-2.0"
] | null | null | null | #
# Marco Panato
# 2016-03-11
# Authenticator for frontend
#
# Each user has a role
# 1 -> min privileges
# 5 -> max privileges
from hashlib import md5
import logging
from database.DataManager import DataManager
class Authenticator(object):
def authenticate(self, user, password):
"""
Returns the user's role, or 0 if wrong login occured
"""
d = DataManager.get_instance().getUsers().get(user.lower())
if d is not None:
return d[1] if d[0] == md5(password.encode()).hexdigest() else 0
return 0
def adduser(self, user, password, role):
if role < 1 or role > 5:
logging.debug('Cannot add role %d!' % role)
return
DataManager.get_instance().addUser(user.lower(), password, role)
| 24.9375 | 76 | 0.617794 |
f3ca6757fa62088634f55db7787b65856891dd36 | 7,004 | py | Python | Unibooks/models.py | forbesmiyasato/Unibooks | a56c810b751db7296f8540e4729270d3e28ed007 | [
"PostgreSQL"
] | null | null | null | Unibooks/models.py | forbesmiyasato/Unibooks | a56c810b751db7296f8540e4729270d3e28ed007 | [
"PostgreSQL"
] | 3 | 2020-10-16T06:59:39.000Z | 2021-09-08T01:40:13.000Z | Unibooks/models.py | forbesmiyasato/Unibooks | a56c810b751db7296f8540e4729270d3e28ed007 | [
"PostgreSQL"
] | null | null | null | from . import db, login_manager
from datetime import datetime
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return Users.query.get(int(user_id))
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(320), nullable=False) #unique=True
image_file = db.Column(db.String(50), nullable=False,
default='default.jpg')
password = db.Column(db.String(100), nullable=False)
items = db.relationship('Item', backref='owner', lazy=True, cascade="all, delete", passive_deletes=True)
confirmed = db.Column(db.Boolean, default=False, nullable=False)
listings = db.Column(db.Integer, default=0)
school = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)
last_confirm_email_sent = db.Column(db.DateTime, nullable=True)
last_buy_message_sent = db.Column(db.DateTime, nullable=True)
num_buy_message_sent = db.Column(db.Integer, nullable=True, default=0)
last_contact_message_sent = db.Column(db.DateTime, nullable=True)
num_contact_message_sent = db.Column(db.Integer, nullable=True, default=0)
num_reports = db.Column(db.Integer, nullable=True, default=0)
total_listings = db.Column(db.Integer, nullable=True, default=0)
date_created = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
def __repr__(self):
return f"Users('{self.username}', '{self.email}', '{self.image_file}')"
class ItemClass(db.Model):
__tablename__ = 'itemclass'
id = db.Column(db.Integer, primary_key=True)
abbreviation = db.Column(db.String(15), nullable=False)
class_name = db.Column(db.String(100), nullable=False)
department_id = db.Column(db.Integer, db.ForeignKey(
'itemdepartment.id'), nullable=False)
school = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)
count = db.Column(db.Integer, nullable=True, default=0)
class ItemCategory(db.Model):
__tablename__ = 'itemcategory'
id = db.Column(db.Integer, primary_key=True)
category_name = db.Column(db.String(100), nullable=False)
abbreviation = db.Column(db.String(20), nullable=True)
school = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)
count = db.Column(db.Integer, nullable=True, default=0)
class ItemDepartment(db.Model):
__tablename__ = 'itemdepartment'
id = db.Column(db.Integer, primary_key=True)
department_name = db.Column(db.String(100), nullable=False)
abbreviation = db.Column(db.String(20), nullable=True)
classes = db.relationship('ItemClass', backref='parent', lazy='dynamic')
school = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)
count = db.Column(db.Integer, nullable=True, default=0)
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
description = db.Column(db.Text, nullable=True)
price = db.Column(db.DECIMAL(10, 2), nullable=False)
thumbnail = db.Column(db.String, nullable=False,
default='No_picture_available.png')
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete="CASCADE"), nullable=False)
class_id = db.Column(db.Integer, db.ForeignKey(
'itemclass.id'), nullable=True)
department_id = db.Column(db.Integer, db.ForeignKey(
'itemdepartment.id'), nullable=True)
category_id = db.Column(db.Integer, db.ForeignKey(
'itemcategory.id'), nullable=True)
images = db.relationship(
'ItemImage', cascade="all,delete", backref='owner', lazy=True, passive_deletes=True)
saved_by = db.relationship(
'SaveForLater', cascade="all, delete", passive_deletes=True)
isbn = db.Column(db.String(15), nullable=True)
author = db.Column(db.String(30), nullable=True)
school = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)
def __repr__(self):
return f"Post('{self.name}', '{self.date_posted}')"
class ItemImage(db.Model):
id = db.Column(db.Integer, primary_key=True)
image_file = db.Column(db.String(100), nullable=False)
item_id = db.Column(db.Integer, db.ForeignKey('item.id', ondelete="CASCADE"), nullable=False)
image_name = db.Column(db.String(30), nullable=True)
image_size = db.Column(db.String(20), nullable=True)
class SaveForLater(db.Model):
__tablename__ = 'saveforlater'
id = db.Column(db.Integer, primary_key=True)
item_id = db.Column(db.Integer, db.ForeignKey(
'item.id', ondelete='CASCADE'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete="CASCADE"), nullable=False)
messaged_date = db.Column(db.DateTime, nullable=True)
class School(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
departments = db.relationship(
'ItemDepartment', backref='parent', lazy=True)
items = db.relationship('Item', backref='parent', lazy=True)
users = db.relationship('Users', backref='parent', lazy=True)
email_pattern = db.Column(db.String(150), nullable=True)
email_domain = db.Column(db.String(15), nullable=True)
class Inappropriate(db.Model):
id = db.Column(db.Integer, db.ForeignKey('item.id', ondelete="CASCADE"), primary_key=True)
count = db.Column(db.Integer, nullable=True)
class Statistics(db.Model):
id = db.Column(db.Integer, primary_key=True)
total_registrations = db.Column(db.Integer, nullable=True, default=0)
total_listings = db.Column(db.Integer, nullable=True, default=0)
current_listings = db.Column(db.Integer, nullable=True, default=0)
non_textbooks = db.Column(db.Integer, nullable=True, default=0)
school = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)
# class PastItem(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(100), nullable=False)
# date_posted = db.Column(db.DateTime, nullable=False,
# default=datetime.utcnow)
# description = db.Column(db.Text, nullable=False)
# price = db.Column(db.DECIMAL(10, 2), nullable=False)
# thumbnail = db.Column(db.String, nullable=False,
# default='No_picture_available.png')
# user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
# class_id = db.Column(db.Integer, db.ForeignKey('itemclass.id'), nullable=False)
# department_id = db.Column(db.Integer, db.ForeignKey('itemdepartment.id'), nullable=False)
# images = db.relationship('ItemImage', cascade="all,delete", backref='owner', lazy=True)
# saved_by = db.relationship('SaveForLater', cascade="all, delete", passive_deletes=True)
# def __repr__(self):
# return f"Post('{self.name}', '{self.date_posted}')"
| 47.006711 | 108 | 0.691605 |
e0a1c01672330e13f510a9e1c505facac76535f4 | 5,671 | py | Python | igit/models/reference.py | jmosbacher/igit | 62b613fd5bed28b603160dc998c02106ee4fdef0 | [
"Apache-2.0"
] | null | null | null | igit/models/reference.py | jmosbacher/igit | 62b613fd5bed28b603160dc998c02106ee4fdef0 | [
"Apache-2.0"
] | 107 | 2021-06-28T02:10:11.000Z | 2022-03-30T02:38:03.000Z | igit/models/reference.py | jmosbacher/igit | 62b613fd5bed28b603160dc998c02106ee4fdef0 | [
"Apache-2.0"
] | null | null | null | import time
from collections.abc import Iterable
from datetime import datetime
from typing import ClassVar, List, Mapping, Optional, Sequence, Tuple
from pydantic import BaseModel, Field
from ..utils import assign_branches, hierarchy_pos, min_ch, roundrobin
from .base import BaseObject
from .user import User
class SymbolicRef(BaseObject):
pass
class Reference(BaseObject):
pass
class ObjectRef(Reference):
key: str
otype: ClassVar = 'object'
size: int = -1
def walk(self, store, objects=True):
yield self
obj = self.deref(store, recursive=True)
if objects:
yield obj
if isinstance(obj, ObjectRef):
for ref in obj.walk(store):
yield ref
elif isinstance(obj, BaseObject):
for attr in obj.__dict__.values():
if isinstance(attr, ObjectRef):
for ref in attr.walk(store):
yield ref
elif isinstance(attr, Iterable):
for ref in roundrobin(*[
a.walk(store) for a in attr
if isinstance(a, ObjectRef)
]):
yield ref
def __eq__(self, other):
if isinstance(other, Reference):
return self.key == other.key
if isinstance(other, str):
return self.key == other
return False
@staticmethod
def _deref(key, store):
obj = store.cat_object(key)
return obj
def deref(self, store, recursive=True):
obj = self._deref(self.key, store)
if recursive and hasattr(obj, "deref"):
obj = obj.deref(store, recursive)
return obj
def __str__(self):
return self.key
def __hash__(self):
return hash(self.key)
def __dask_tokenize__(self):
return self.key
class BlobRef(ObjectRef):
otype: ClassVar = "blob"
class TreeRef(ObjectRef):
otype: ClassVar = "tree"
tree_class: str = "BaseTree"
class CommitRef(ObjectRef):
otype: ClassVar = "commit"
def walk_parents(self, store):
c = self.deref(store)
yield self
for pref in c.parents:
for p in pref.walk_parents(store):
yield p
def deref_tree(self, store):
commit = self.deref(store)
return commit.tree.deref(store)
def deref_parents(self, store):
commit = self.deref(store)
return [cref.deref(store) for cref in commit.parents]
def _to_digraph(self, db, dg, max_char=40):
commit = self.deref(db)
dg.add_node(self.key[:max_char],
is_root=commit.is_root,
**commit.dict())
if commit.is_root:
return
for parent in commit.parents:
dg.add_edge(self.key[:max_char], parent.key[:max_char])
parent._to_digraph(db, dg, max_char=max_char)
def digraph(self, db, max_char=None):
if max_char is None:
max_char = min_ch(db)
import networkx as nx
dg = nx.DiGraph()
self._to_digraph(db, dg, max_char)
return dg
def visualize_heritage(self, db):
import pandas as pd
import holoviews as hv
import networkx as nx
import panel as pn
dag = self.digraph(db)
branches = assign_branches(dag)
layout = []
for i, k in enumerate(nx.topological_sort(dag)):
node = dag.nodes[k]
layout.append({
"name": k,
"col": branches[k],
"row": i,
"message": node["message"]
})
df = pd.DataFrame(layout)
df["message_col"] = df.col.max() + 2
df["message_col_end"] = df.col.max() + 10
plot = hv.Points(df, ["col", "row"]).opts(
size=25,
alpha=0.8,
hover_alpha=0.7,
hover_line_color="black",
hover_fill_color="magenta",
tools=["hover"]) * hv.Labels(df, ["col", "row"], "name")
plot = plot * hv.Labels(df, ["message_col", "row"], ["message"]).opts(
text_align="left", xoffset=0)
plot = plot * hv.Segments(
df, ["col", "row", "message_col_end", "row"]).opts(
line_width=30, alpha=0.3, line_cap="round", color="grey")
return pn.panel(plot.opts(responsive=True,
xaxis=None,
yaxis=None,
toolbar=None,
show_grid=False),
width=400,
height=400)
class Tag(CommitRef):
otype: ClassVar = "commit"
class AnnotatedTag(Tag):
otype: ClassVar = "commit"
tagger: User
tag: str
message: str
class Branch(CommitRef):
name: str
class MergeCommitRef(CommitRef):
otype: ClassVar = "merge"
def deref_parents(self, store):
commit = self.deref(store)
return [ref.deref(store) for ref in commit.parents]
class RefLog:
pass
class HEAD(SymbolicRef):
pass
class Commit(Reference):
otype: ClassVar = "commit"
tree: TreeRef
parents: Sequence[CommitRef]
author: User = None
commiter: User = None
message: str
timestamp: int
def __hash__(self):
return hash(
(self.otype, self.tree.key, tuple(p.key for p in self.parents),
self.author, self.commiter, self.message, self.timestamp))
@property
def is_root(self):
return not self.parents
def is_merge(self):
return len(self.parents) > 1
| 26.5 | 78 | 0.554047 |
9d29bc931d16d646edfc75474e241c71afaf814b | 16,450 | py | Python | fastflix/widgets/panels/queue_panel.py | ObviousInRetrospect/FastFlix | 26c53d10fb9b2d9e73382a78a7276bb2389bd5c5 | [
"MIT"
] | 388 | 2019-03-11T12:45:36.000Z | 2022-03-29T19:18:21.000Z | fastflix/widgets/panels/queue_panel.py | neoOpus/FastFlix | 26c53d10fb9b2d9e73382a78a7276bb2389bd5c5 | [
"MIT"
] | 239 | 2019-02-19T20:05:59.000Z | 2022-03-30T23:27:49.000Z | fastflix/widgets/panels/queue_panel.py | neoOpus/FastFlix | 26c53d10fb9b2d9e73382a78a7276bb2389bd5c5 | [
"MIT"
] | 44 | 2019-08-22T21:41:29.000Z | 2022-03-03T08:16:39.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import sys
import logging
import reusables
from box import Box
from PySide6 import QtCore, QtGui, QtWidgets
from fastflix.language import t
from fastflix.models.fastflix_app import FastFlixApp
from fastflix.models.video import Video
from fastflix.ff_queue import get_queue, save_queue
from fastflix.resources import get_icon, get_bool_env
from fastflix.shared import no_border, open_folder, yes_no_message
from fastflix.widgets.panels.abstract_list import FlixList
logger = logging.getLogger("fastflix")
done_actions = {
"linux": {
"shutdown": 'shutdown -h 1 "FastFlix conversion complete, shutting down"',
"restart": 'shutdown -r 1 "FastFlix conversion complete, rebooting"',
"logout": "logout",
"sleep": "pm-suspend",
"hibernate": "pm-hibernate",
},
"windows": {
"shutdown": "shutdown /s",
"restart": "shutdown /r",
"logout": "shutdown /l",
"hibernate": "shutdown /h",
},
}
class EncodeItem(QtWidgets.QTabWidget):
def __init__(self, parent, video: Video, index, first=False):
self.loading = True
super().__init__(parent)
self.parent = parent
self.index = index
self.first = first
self.last = False
self.video = video.copy()
self.setFixedHeight(60)
self.widgets = Box(
up_button=QtWidgets.QPushButton(
QtGui.QIcon(get_icon("up-arrow", self.parent.app.fastflix.config.theme)), ""
),
down_button=QtWidgets.QPushButton(
QtGui.QIcon(get_icon("down-arrow", self.parent.app.fastflix.config.theme)), ""
),
cancel_button=QtWidgets.QPushButton(
QtGui.QIcon(get_icon("black-x", self.parent.app.fastflix.config.theme)), ""
),
reload_button=QtWidgets.QPushButton(
QtGui.QIcon(get_icon("edit-box", self.parent.app.fastflix.config.theme)), ""
),
retry_button=QtWidgets.QPushButton(
QtGui.QIcon(get_icon("undo", self.parent.app.fastflix.config.theme)), ""
),
)
for widget in self.widgets.values():
widget.setStyleSheet(no_border)
title = QtWidgets.QLabel(
video.video_settings.video_title
if video.video_settings.video_title
else video.video_settings.output_path.name
)
title.setFixedWidth(300)
settings = Box(copy.deepcopy(video.video_settings.dict()))
settings.output_path = str(settings.output_path)
for i, o in enumerate(settings.attachment_tracks):
if o.get("file_path"):
o["file_path"] = str(o["file_path"])
del settings.conversion_commands
title.setToolTip(settings.to_yaml())
open_button = QtWidgets.QPushButton(
QtGui.QIcon(get_icon("play", self.parent.app.fastflix.config.theme)), t("Open Directory")
)
open_button.setLayoutDirection(QtCore.Qt.RightToLeft)
open_button.setIconSize(QtCore.QSize(14, 14))
open_button.clicked.connect(lambda: open_folder(video.video_settings.output_path.parent))
view_button = QtWidgets.QPushButton(
QtGui.QIcon(get_icon("play", self.parent.app.fastflix.config.theme)), t("Watch")
)
view_button.setLayoutDirection(QtCore.Qt.RightToLeft)
view_button.setIconSize(QtCore.QSize(14, 14))
view_button.clicked.connect(
lambda: QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(str(video.video_settings.output_path)))
)
open_button.setStyleSheet(no_border)
view_button.setStyleSheet(no_border)
add_retry = False
status = t("Ready to encode")
if video.status.error:
status = t("Encoding errored")
elif video.status.complete:
status = f"{t('Encoding complete')}"
elif video.status.running:
status = (
f"{t('Encoding command')} {video.status.current_command + 1} {t('of')} "
f"{len(video.video_settings.conversion_commands)}"
)
elif video.status.cancelled:
status = t("Cancelled")
add_retry = True
if not self.video.status.running:
self.widgets.cancel_button.clicked.connect(lambda: self.parent.remove_item(self.video))
self.widgets.reload_button.clicked.connect(lambda: self.parent.reload_from_queue(self.video))
self.widgets.cancel_button.setFixedWidth(25)
self.widgets.reload_button.setFixedWidth(25)
else:
self.widgets.cancel_button.hide()
self.widgets.reload_button.hide()
grid = QtWidgets.QGridLayout()
grid.addLayout(self.init_move_buttons(), 0, 0)
# grid.addWidget(self.widgets.track_number, 0, 1)
grid.addWidget(title, 0, 1, 1, 3)
grid.addWidget(QtWidgets.QLabel(f"{video.video_settings.video_encoder_settings.name}"), 0, 4)
grid.addWidget(QtWidgets.QLabel(f"{t('Audio Tracks')}: {len(video.video_settings.audio_tracks)}"), 0, 5)
grid.addWidget(QtWidgets.QLabel(f"{t('Subtitles')}: {len(video.video_settings.subtitle_tracks)}"), 0, 6)
grid.addWidget(QtWidgets.QLabel(status), 0, 7)
if video.status.complete and not get_bool_env("FF_DOCKERMODE"):
grid.addWidget(view_button, 0, 8)
grid.addWidget(open_button, 0, 9)
elif add_retry:
grid.addWidget(self.widgets.retry_button, 0, 8)
self.widgets.retry_button.setFixedWidth(25)
self.widgets.retry_button.clicked.connect(lambda: self.parent.retry_video(self.video))
right_buttons = QtWidgets.QHBoxLayout()
right_buttons.addWidget(self.widgets.reload_button)
right_buttons.addWidget(self.widgets.cancel_button)
grid.addLayout(right_buttons, 0, 10, alignment=QtCore.Qt.AlignRight)
self.setLayout(grid)
self.loading = False
self.updating_burn = False
def init_move_buttons(self):
layout = QtWidgets.QVBoxLayout()
layout.setSpacing(0)
self.widgets.up_button.setFixedWidth(20)
self.widgets.up_button.clicked.connect(lambda: self.parent.move_up(self))
self.widgets.down_button.setFixedWidth(20)
self.widgets.down_button.clicked.connect(lambda: self.parent.move_down(self))
layout.addWidget(self.widgets.up_button)
layout.addWidget(self.widgets.down_button)
return layout
def set_first(self, first=True):
self.first = first
def set_last(self, last=True):
self.last = last
def set_outdex(self, outdex):
pass
@property
def enabled(self):
return True
def update_enable(self):
pass
def page_update(self):
if not self.loading:
return self.parent.main.page_update(build_thumbnail=False)
class EncodingQueue(FlixList):
def __init__(self, parent, app: FastFlixApp):
self.main = parent.main
self.app = app
self.paused = False
self.encode_paused = False
self.encoding = False
top_layout = QtWidgets.QHBoxLayout()
top_layout.addWidget(QtWidgets.QLabel(t("Queue")))
top_layout.addStretch(1)
self.clear_queue = QtWidgets.QPushButton(
QtGui.QIcon(get_icon("onyx-clear-queue", self.app.fastflix.config.theme)), t("Clear Completed")
)
self.clear_queue.clicked.connect(self.clear_complete)
self.clear_queue.setFixedWidth(120)
self.clear_queue.setToolTip(t("Remove completed tasks"))
self.pause_queue = QtWidgets.QPushButton(
QtGui.QIcon(get_icon("onyx-pause", self.app.fastflix.config.theme)), t("Pause Queue")
)
self.pause_queue.clicked.connect(self.pause_resume_queue)
# pause_queue.setFixedHeight(40)
self.pause_queue.setFixedWidth(120)
self.pause_queue.setToolTip(
t("Wait for the current command to finish," " and stop the next command from processing")
)
self.pause_encode = QtWidgets.QPushButton(
QtGui.QIcon(get_icon("onyx-pause", self.app.fastflix.config.theme)), t("Pause Encode")
)
self.pause_encode.clicked.connect(self.pause_resume_encode)
# pause_queue.setFixedHeight(40)
self.pause_encode.setFixedWidth(120)
self.pause_encode.setToolTip(t("Pause / Resume the current command"))
self.after_done_combo = QtWidgets.QComboBox()
self.after_done_combo.addItem("None")
actions = set()
if reusables.win_based:
actions.update(done_actions["windows"].keys())
elif sys.platform == "darwin":
actions.update(["shutdown", "restart"])
else:
actions.update(done_actions["linux"].keys())
if self.app.fastflix.config.custom_after_run_scripts:
actions.update(self.app.fastflix.config.custom_after_run_scripts)
self.after_done_combo.addItems(sorted(actions))
self.after_done_combo.setToolTip("Run a command after conversion completes")
self.after_done_combo.currentIndexChanged.connect(lambda: self.set_after_done())
self.after_done_combo.setMaximumWidth(150)
top_layout.addWidget(QtWidgets.QLabel(t("After Conversion")))
top_layout.addWidget(self.after_done_combo, QtCore.Qt.AlignRight)
top_layout.addWidget(self.pause_encode, QtCore.Qt.AlignRight)
top_layout.addWidget(self.pause_queue, QtCore.Qt.AlignRight)
top_layout.addWidget(self.clear_queue, QtCore.Qt.AlignRight)
super().__init__(app, parent, t("Queue"), "queue", top_row_layout=top_layout)
try:
self.queue_startup_check()
except Exception:
logger.exception("Could not load queue as it is outdated or malformed. Deleting for safety.")
save_queue([], queue_file=self.app.fastflix.queue_path, config=self.app.fastflix.config)
def queue_startup_check(self):
new_queue = get_queue(self.app.fastflix.queue_path, self.app.fastflix.config)
# self.app.fastflix.queue.append(item)
reset_vids = []
remove_vids = []
for i, video in enumerate(new_queue):
if video.status.running:
reset_vids.append(i)
if video.status.complete:
remove_vids.append(video)
for index in reset_vids:
vid: Video = new_queue.pop(index)
vid.status.clear()
new_queue.insert(index, vid)
for video in remove_vids:
new_queue.remove(video)
if new_queue:
if yes_no_message(
f"{t('Not all items in the queue were completed')}\n"
f"{t('Would you like to keep them in the queue?')}",
title="Recover Queue Items",
):
with self.app.fastflix.queue_lock:
for item in new_queue:
self.app.fastflix.queue.append(item)
# self.app.fastflix.queue = []
with self.app.fastflix.queue_lock:
save_queue(self.app.fastflix.queue, self.app.fastflix.queue_path, self.app.fastflix.config)
self.new_source()
def reorder(self, update=True):
super().reorder(update=update)
with self.app.fastflix.queue_lock:
for i in range(len(self.app.fastflix.queue)):
self.app.fastflix.queue.pop()
for track in self.tracks:
self.app.fastflix.queue.append(track.video)
for track in self.tracks:
track.widgets.up_button.setDisabled(False)
track.widgets.down_button.setDisabled(False)
if self.tracks:
self.tracks[0].widgets.up_button.setDisabled(True)
self.tracks[-1].widgets.down_button.setDisabled(True)
def new_source(self):
for track in self.tracks:
track.close()
self.tracks = []
for i, video in enumerate(self.app.fastflix.queue, start=1):
self.tracks.append(EncodeItem(self, video, index=i))
if self.tracks:
self.tracks[0].widgets.up_button.setDisabled(True)
self.tracks[-1].widgets.down_button.setDisabled(True)
super()._new_source(self.tracks)
def clear_complete(self):
for queued_item in self.tracks:
if queued_item.video.status.complete:
self.remove_item(queued_item.video, part_of_clear=True)
with self.app.fastflix.queue_lock:
save_queue(self.app.fastflix.queue, self.app.fastflix.queue_path, self.app.fastflix.config)
self.new_source()
def remove_item(self, video, part_of_clear=False):
with self.app.fastflix.queue_lock:
for i, vid in enumerate(self.app.fastflix.queue):
if vid.uuid == video.uuid:
pos = i
break
else:
logger.error("No matching video found to remove from queue")
return
self.app.fastflix.queue.pop(pos)
if not part_of_clear:
save_queue(self.app.fastflix.queue, self.app.fastflix.queue_path, self.app.fastflix.config)
if not part_of_clear:
self.new_source()
def reload_from_queue(self, video):
self.main.reload_video_from_queue(video)
self.remove_item(video)
def reset_pause_encode(self):
self.pause_encode.setText(t("Pause Encode"))
self.pause_encode.setIcon(self.app.style().standardIcon(QtWidgets.QStyle.SP_MediaPause))
self.encode_paused = False
def pause_resume_queue(self):
if self.paused:
self.pause_queue.setText(t("Pause Queue"))
self.pause_queue.setIcon(self.app.style().standardIcon(QtWidgets.QStyle.SP_MediaPause))
for i, video in enumerate(self.app.fastflix.queue):
if video.status.ready:
self.main.converting = True
self.main.set_convert_button(False)
break
self.app.fastflix.worker_queue.put(["resume queue"])
else:
self.pause_queue.setText(t("Resume Queue"))
self.pause_queue.setIcon(self.app.style().standardIcon(QtWidgets.QStyle.SP_MediaPlay))
self.app.fastflix.worker_queue.put(["pause queue"])
self.paused = not self.paused
def pause_resume_encode(self):
if self.encode_paused:
self.pause_encode.setText(t("Pause Encode"))
self.pause_encode.setIcon(self.app.style().standardIcon(QtWidgets.QStyle.SP_MediaPause))
self.app.fastflix.worker_queue.put(["resume encode"])
else:
self.pause_encode.setText(t("Resume Encode"))
self.pause_encode.setIcon(self.app.style().standardIcon(QtWidgets.QStyle.SP_MediaPlay))
self.app.fastflix.worker_queue.put(["pause encode"])
self.encode_paused = not self.encode_paused
@reusables.log_exception("fastflix", show_traceback=False)
def set_after_done(self):
option = self.after_done_combo.currentText()
if option == "None":
command = ""
elif option in self.app.fastflix.config.custom_after_run_scripts:
command = self.app.fastflix.config.custom_after_run_scripts[option]
elif reusables.win_based:
command = done_actions["windows"][option]
else:
command = done_actions["linux"][option]
self.app.fastflix.worker_queue.put(["set after done", command])
def retry_video(self, current_video):
with self.app.fastflix.queue_lock:
for i, video in enumerate(self.app.fastflix.queue):
if video.uuid == current_video.uuid:
video_pos = i
break
else:
logger.error(f"Can't find video {current_video.uuid} in queue to update its status")
return
video = self.app.fastflix.queue.pop(video_pos)
video.status.cancelled = False
video.status.current_command = 0
self.app.fastflix.queue.insert(video_pos, video)
save_queue(self.app.fastflix.queue, self.app.fastflix.queue_path, self.app.fastflix.config)
self.new_source()
| 40.41769 | 116 | 0.636049 |
96149676fec352db0b2196b4965d170e58a06d61 | 8,442 | py | Python | badger/feeds.py | lmorchard/badges.mozilla.org | 2f00782eb40f187b9c0cd70763090b8c46ec448e | [
"BSD-3-Clause"
] | 21 | 2015-01-04T22:30:46.000Z | 2017-09-12T03:03:27.000Z | badger/feeds.py | lmorchard/badges.mozilla.org | 2f00782eb40f187b9c0cd70763090b8c46ec448e | [
"BSD-3-Clause"
] | 76 | 2015-01-04T21:23:35.000Z | 2019-03-28T12:36:17.000Z | badger/feeds.py | lmorchard/badges.mozilla.org | 2f00782eb40f187b9c0cd70763090b8c46ec448e | [
"BSD-3-Clause"
] | 41 | 2015-01-08T04:47:10.000Z | 2019-03-28T04:12:57.000Z | """Feeds for badge"""
import datetime
import hashlib
import urllib
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils.feedgenerator import (SyndicationFeed, Rss201rev2Feed,
Atom1Feed, get_tag_uri)
import json
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.conf import settings
try:
from tower import ugettext_lazy as _
except ImportError:
from django.utils.translation import ugettext_lazy as _
try:
from commons.urlresolvers import reverse
except ImportError:
from django.core.urlresolvers import reverse
from . import validate_jsonp
from .models import (Badge, Award, Nomination, Progress,
BadgeAwardNotAllowedException,
DEFAULT_BADGE_IMAGE)
MAX_FEED_ITEMS = getattr(settings, 'BADGER_MAX_FEED_ITEMS', 15)
class BaseJSONFeedGenerator(SyndicationFeed):
"""JSON feed generator"""
# TODO:liberate - Can this class be a generally-useful lib?
mime_type = 'application/json'
def _encode_complex(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
def build_item(self, item):
"""Simple base item formatter.
Omit some named keys and any keys with false-y values"""
omit_keys = ('obj', 'unique_id', )
return dict((k, v) for k, v in item.items()
if v and k not in omit_keys)
def build_feed(self):
"""Simple base feed formatter.
Omit some named keys and any keys with false-y values"""
omit_keys = ('obj', 'request', 'id', )
feed_data = dict((k, v) for k, v in self.feed.items()
if v and k not in omit_keys)
feed_data['items'] = [self.build_item(item) for item in self.items]
return feed_data
def write(self, outfile, encoding):
request = self.feed['request']
# Check for a callback param, validate it before use
callback = request.GET.get('callback', None)
if callback is not None:
if not validate_jsonp.is_valid_jsonp_callback_value(callback):
callback = None
# Build the JSON string, wrapping it in a callback param if necessary.
json_string = json.dumps(self.build_feed(),
default=self._encode_complex)
if callback:
outfile.write('%s(%s)' % (callback, json_string))
else:
outfile.write(json_string)
class BaseFeed(Feed):
"""Base feed for all of badger, allows switchable generator from URL route
and other niceties"""
# TODO:liberate - Can this class be a generally-useful lib?
json_feed_generator = BaseJSONFeedGenerator
rss_feed_generator = Rss201rev2Feed
atom_feed_generator = Atom1Feed
def __call__(self, request, *args, **kwargs):
self.request = request
return super(BaseFeed, self).__call__(request, *args, **kwargs)
def get_object(self, request, format):
self.link = request.build_absolute_uri('/')
if format == 'json':
self.feed_type = self.json_feed_generator
elif format == 'rss':
self.feed_type = self.rss_feed_generator
else:
self.feed_type = self.atom_feed_generator
return super(BaseFeed, self).get_object(request)
def feed_extra_kwargs(self, obj):
return {'request': self.request, 'obj': obj, }
def item_extra_kwargs(self, obj):
return {'obj': obj, }
def item_pubdate(self, obj):
return obj.created
def item_author_link(self, obj):
if not obj.creator or not hasattr(obj.creator, 'get_absolute_url'):
return None
else:
return self.request.build_absolute_uri(
obj.creator.get_absolute_url())
def item_author_name(self, obj):
if not obj.creator:
return None
else:
return '%s' % obj.creator
def item_description(self, obj):
if obj.image:
image_url = obj.image.url
else:
image_url = '%simg/default-badge.png' % settings.MEDIA_URL
return """
<div>
<a href="%(href)s"><img alt="%(alt)s" src="%(image_url)s" /></a>
</div>
""" % dict(
alt=unicode(obj),
href=self.request.build_absolute_uri(obj.get_absolute_url()),
image_url=self.request.build_absolute_uri(image_url)
)
class AwardActivityStreamJSONFeedGenerator(BaseJSONFeedGenerator):
pass
class AwardActivityStreamAtomFeedGenerator(Atom1Feed):
pass
class AwardsFeed(BaseFeed):
"""Base class for all feeds listing awards"""
title = _(u'Recently awarded badges')
subtitle = None
json_feed_generator = AwardActivityStreamJSONFeedGenerator
atom_feed_generator = AwardActivityStreamAtomFeedGenerator
def item_title(self, obj):
return _(u'{badgetitle} awarded to {username}').format(
badgetitle=obj.badge.title, username=obj.user.username)
def item_author_link(self, obj):
if not obj.creator:
return None
else:
return self.request.build_absolute_uri(
reverse('badger.views.awards_by_user',
args=(obj.creator.username,)))
def item_link(self, obj):
return self.request.build_absolute_uri(
reverse('badger.views.award_detail',
args=(obj.badge.slug, obj.pk, )))
class AwardsRecentFeed(AwardsFeed):
"""Feed of all recent badge awards"""
def items(self):
return (Award.objects
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
class AwardsByUserFeed(AwardsFeed):
"""Feed of recent badge awards for a user"""
def get_object(self, request, format, username):
super(AwardsByUserFeed, self).get_object(request, format)
user = get_object_or_404(User, username=username)
self.title = _(u'Badges recently awarded to {username}').format(
username=user.username)
self.link = request.build_absolute_uri(
reverse('badger.views.awards_by_user', args=(user.username,)))
return user
def items(self, user):
return (Award.objects
.filter(user=user)
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
class AwardsByBadgeFeed(AwardsFeed):
"""Feed of recent badge awards for a badge"""
def get_object(self, request, format, slug):
super(AwardsByBadgeFeed, self).get_object(request, format)
badge = get_object_or_404(Badge, slug=slug)
self.title = _(u'Recent awards of "{badgetitle}"').format(
badgetitle=badge.title)
self.link = request.build_absolute_uri(
reverse('badger.views.awards_list', args=(badge.slug,)))
return badge
def items(self, badge):
return (Award.objects
.filter(badge=badge).order_by('-created')
.all()[:MAX_FEED_ITEMS])
class BadgesJSONFeedGenerator(BaseJSONFeedGenerator):
pass
class BadgesFeed(BaseFeed):
"""Base class for all feeds listing badges"""
title = _(u'Recently created badges')
json_feed_generator = BadgesJSONFeedGenerator
def item_title(self, obj):
return obj.title
def item_link(self, obj):
return self.request.build_absolute_uri(
reverse('badger.views.detail',
args=(obj.slug, )))
class BadgesRecentFeed(BadgesFeed):
def items(self):
return (Badge.objects
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
class BadgesByUserFeed(BadgesFeed):
"""Feed of badges recently created by a user"""
def get_object(self, request, format, username):
super(BadgesByUserFeed, self).get_object(request, format)
user = get_object_or_404(User, username=username)
self.title = _(u'Badges recently created by {username}').format(
username=user.username)
self.link = request.build_absolute_uri(
reverse('badger.views.badges_by_user', args=(user.username,)))
return user
def items(self, user):
return (Badge.objects
.filter(creator=user)
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
| 32.098859 | 80 | 0.630419 |
81cb876348e3aa306dc50cecd333dd5845fa8e8b | 1,053 | py | Python | application/application/models/Event.py | Terkea/kiosk | 86a6520f9d91d7bacca915d3740da802e3efb510 | [
"MIT"
] | null | null | null | application/application/models/Event.py | Terkea/kiosk | 86a6520f9d91d7bacca915d3740da802e3efb510 | [
"MIT"
] | null | null | null | application/application/models/Event.py | Terkea/kiosk | 86a6520f9d91d7bacca915d3740da802e3efb510 | [
"MIT"
] | null | null | null | from sqlalchemy import Column, Integer, String, ForeignKey, Sequence, Text, Boolean
from sqlalchemy.orm import relationship
from application.database import Base
class Event(Base):
__tablename__ = 'event'
id = Column(Integer, Sequence('id_seq'), primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
category_id = Column(Integer, ForeignKey('category.id'), nullable=False)
name = Column(String(255), nullable=False)
venue = Column(String(255), nullable=False)
datetime = Column(String(255), nullable=False)
entry_price = Column(String(255), nullable=False)
description = Column(Text(), nullable=False)
event_type = Column(String(255), nullable=False)
slots_available = Column(String(255), nullable=False)
picture = Column(String(255))
is_visible = Column(Boolean(), default=True)
# add the foreign keys
booking = relationship("Booking", backref="event")
autoload = True
def __repr__(self):
return str(self.__dict__) | 40.5 | 84 | 0.695157 |
adf85bff0b5153c9ff057d0c11fceafed14d01a2 | 4,021 | py | Python | hubspot/crm/extensions/accounting/models/import_invoice_feature.py | fakepop/hubspot-api-python | f04103a09f93f5c26c99991b25fa76801074f3d3 | [
"Apache-2.0"
] | null | null | null | hubspot/crm/extensions/accounting/models/import_invoice_feature.py | fakepop/hubspot-api-python | f04103a09f93f5c26c99991b25fa76801074f3d3 | [
"Apache-2.0"
] | null | null | null | hubspot/crm/extensions/accounting/models/import_invoice_feature.py | fakepop/hubspot-api-python | f04103a09f93f5c26c99991b25fa76801074f3d3 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Accounting Extension
These APIs allow you to interact with HubSpot's Accounting Extension. It allows you to: * Specify the URLs that HubSpot will use when making webhook requests to your external accounting system. * Respond to webhook calls made to your external accounting system by HubSpot # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from hubspot.crm.extensions.accounting.configuration import Configuration
class ImportInvoiceFeature(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
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 = {"enabled": "bool"}
attribute_map = {"enabled": "enabled"}
def __init__(self, enabled=None, local_vars_configuration=None): # noqa: E501
"""ImportInvoiceFeature - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._enabled = None
self.discriminator = None
self.enabled = enabled
@property
def enabled(self):
"""Gets the enabled of this ImportInvoiceFeature. # noqa: E501
Indicates if importing invoices from the external account system into HubSpot. # noqa: E501
:return: The enabled of this ImportInvoiceFeature. # noqa: E501
:rtype: bool
"""
return self._enabled
@enabled.setter
def enabled(self, enabled):
"""Sets the enabled of this ImportInvoiceFeature.
Indicates if importing invoices from the external account system into HubSpot. # noqa: E501
:param enabled: The enabled of this ImportInvoiceFeature. # noqa: E501
:type: bool
"""
if (
self.local_vars_configuration.client_side_validation and enabled is None
): # noqa: E501
raise ValueError(
"Invalid value for `enabled`, must not be `None`"
) # noqa: E501
self._enabled = enabled
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_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):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ImportInvoiceFeature):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ImportInvoiceFeature):
return True
return self.to_dict() != other.to_dict()
| 31.912698 | 290 | 0.59612 |
7b45363e6eba306c519b5deeca2bc38d6535cec8 | 13,445 | py | Python | detectron2/modeling/meta_arch/rcnn.py | mmabrouk/detectron2 | 158e395acdb8ca6ed6d488b43475f9ef9d200405 | [
"Apache-2.0"
] | 21,274 | 2019-10-10T17:50:46.000Z | 2022-03-31T17:58:45.000Z | detectron2/modeling/meta_arch/rcnn.py | mmabrouk/detectron2 | 158e395acdb8ca6ed6d488b43475f9ef9d200405 | [
"Apache-2.0"
] | 3,253 | 2019-10-10T20:39:47.000Z | 2022-03-31T22:27:53.000Z | detectron2/modeling/meta_arch/rcnn.py | mmabrouk/detectron2 | 158e395acdb8ca6ed6d488b43475f9ef9d200405 | [
"Apache-2.0"
] | 6,288 | 2019-10-10T18:00:27.000Z | 2022-03-31T21:22:58.000Z | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from typing import Dict, List, Optional, Tuple
import torch
from torch import nn
from detectron2.config import configurable
from detectron2.data.detection_utils import convert_image_to_rgb
from detectron2.structures import ImageList, Instances
from detectron2.utils.events import get_event_storage
from detectron2.utils.logger import log_first_n
from ..backbone import Backbone, build_backbone
from ..postprocessing import detector_postprocess
from ..proposal_generator import build_proposal_generator
from ..roi_heads import build_roi_heads
from .build import META_ARCH_REGISTRY
__all__ = ["GeneralizedRCNN", "ProposalNetwork"]
@META_ARCH_REGISTRY.register()
class GeneralizedRCNN(nn.Module):
"""
Generalized R-CNN. Any models that contains the following three components:
1. Per-image feature extraction (aka backbone)
2. Region proposal generation
3. Per-region feature extraction and prediction
"""
@configurable
def __init__(
self,
*,
backbone: Backbone,
proposal_generator: nn.Module,
roi_heads: nn.Module,
pixel_mean: Tuple[float],
pixel_std: Tuple[float],
input_format: Optional[str] = None,
vis_period: int = 0,
):
"""
Args:
backbone: a backbone module, must follow detectron2's backbone interface
proposal_generator: a module that generates proposals using backbone features
roi_heads: a ROI head that performs per-region computation
pixel_mean, pixel_std: list or tuple with #channels element, representing
the per-channel mean and std to be used to normalize the input image
input_format: describe the meaning of channels of input. Needed by visualization
vis_period: the period to run visualization. Set to 0 to disable.
"""
super().__init__()
self.backbone = backbone
self.proposal_generator = proposal_generator
self.roi_heads = roi_heads
self.input_format = input_format
self.vis_period = vis_period
if vis_period > 0:
assert input_format is not None, "input_format is required for visualization!"
self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False)
self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False)
assert (
self.pixel_mean.shape == self.pixel_std.shape
), f"{self.pixel_mean} and {self.pixel_std} have different shapes!"
@classmethod
def from_config(cls, cfg):
backbone = build_backbone(cfg)
return {
"backbone": backbone,
"proposal_generator": build_proposal_generator(cfg, backbone.output_shape()),
"roi_heads": build_roi_heads(cfg, backbone.output_shape()),
"input_format": cfg.INPUT.FORMAT,
"vis_period": cfg.VIS_PERIOD,
"pixel_mean": cfg.MODEL.PIXEL_MEAN,
"pixel_std": cfg.MODEL.PIXEL_STD,
}
@property
def device(self):
return self.pixel_mean.device
def visualize_training(self, batched_inputs, proposals):
"""
A function used to visualize images and proposals. It shows ground truth
bounding boxes on the original image and up to 20 top-scoring predicted
object proposals on the original image. Users can implement different
visualization functions for different models.
Args:
batched_inputs (list): a list that contains input to the model.
proposals (list): a list that contains predicted proposals. Both
batched_inputs and proposals should have the same length.
"""
from detectron2.utils.visualizer import Visualizer
storage = get_event_storage()
max_vis_prop = 20
for input, prop in zip(batched_inputs, proposals):
img = input["image"]
img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)
v_gt = Visualizer(img, None)
v_gt = v_gt.overlay_instances(boxes=input["instances"].gt_boxes)
anno_img = v_gt.get_image()
box_size = min(len(prop.proposal_boxes), max_vis_prop)
v_pred = Visualizer(img, None)
v_pred = v_pred.overlay_instances(
boxes=prop.proposal_boxes[0:box_size].tensor.cpu().numpy()
)
prop_img = v_pred.get_image()
vis_img = np.concatenate((anno_img, prop_img), axis=1)
vis_img = vis_img.transpose(2, 0, 1)
vis_name = "Left: GT bounding boxes; Right: Predicted proposals"
storage.put_image(vis_name, vis_img)
break # only visualize one image in a batch
def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]):
"""
Args:
batched_inputs: a list, batched outputs of :class:`DatasetMapper` .
Each item in the list contains the inputs for one image.
For now, each item in the list is a dict that contains:
* image: Tensor, image in (C, H, W) format.
* instances (optional): groundtruth :class:`Instances`
* proposals (optional): :class:`Instances`, precomputed proposals.
Other information that's included in the original dicts, such as:
* "height", "width" (int): the output resolution of the model, used in inference.
See :meth:`postprocess` for details.
Returns:
list[dict]:
Each dict is the output for one input image.
The dict contains one key "instances" whose value is a :class:`Instances`.
The :class:`Instances` object has the following keys:
"pred_boxes", "pred_classes", "scores", "pred_masks", "pred_keypoints"
"""
if not self.training:
return self.inference(batched_inputs)
images = self.preprocess_image(batched_inputs)
if "instances" in batched_inputs[0]:
gt_instances = [x["instances"].to(self.device) for x in batched_inputs]
else:
gt_instances = None
features = self.backbone(images.tensor)
if self.proposal_generator is not None:
proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)
else:
assert "proposals" in batched_inputs[0]
proposals = [x["proposals"].to(self.device) for x in batched_inputs]
proposal_losses = {}
_, detector_losses = self.roi_heads(images, features, proposals, gt_instances)
if self.vis_period > 0:
storage = get_event_storage()
if storage.iter % self.vis_period == 0:
self.visualize_training(batched_inputs, proposals)
losses = {}
losses.update(detector_losses)
losses.update(proposal_losses)
return losses
def inference(
self,
batched_inputs: List[Dict[str, torch.Tensor]],
detected_instances: Optional[List[Instances]] = None,
do_postprocess: bool = True,
):
"""
Run inference on the given inputs.
Args:
batched_inputs (list[dict]): same as in :meth:`forward`
detected_instances (None or list[Instances]): if not None, it
contains an `Instances` object per image. The `Instances`
object contains "pred_boxes" and "pred_classes" which are
known boxes in the image.
The inference will then skip the detection of bounding boxes,
and only predict other per-ROI outputs.
do_postprocess (bool): whether to apply post-processing on the outputs.
Returns:
When do_postprocess=True, same as in :meth:`forward`.
Otherwise, a list[Instances] containing raw network outputs.
"""
assert not self.training
images = self.preprocess_image(batched_inputs)
features = self.backbone(images.tensor)
if detected_instances is None:
if self.proposal_generator is not None:
proposals, _ = self.proposal_generator(images, features, None)
else:
assert "proposals" in batched_inputs[0]
proposals = [x["proposals"].to(self.device) for x in batched_inputs]
results, _ = self.roi_heads(images, features, proposals, None)
else:
detected_instances = [x.to(self.device) for x in detected_instances]
results = self.roi_heads.forward_with_given_boxes(features, detected_instances)
if do_postprocess:
assert not torch.jit.is_scripting(), "Scripting is not supported for postprocess."
return GeneralizedRCNN._postprocess(results, batched_inputs, images.image_sizes)
else:
return results
def preprocess_image(self, batched_inputs: List[Dict[str, torch.Tensor]]):
"""
Normalize, pad and batch the input images.
"""
images = [x["image"].to(self.device) for x in batched_inputs]
images = [(x - self.pixel_mean) / self.pixel_std for x in images]
images = ImageList.from_tensors(images, self.backbone.size_divisibility)
return images
@staticmethod
def _postprocess(instances, batched_inputs: List[Dict[str, torch.Tensor]], image_sizes):
"""
Rescale the output instances to the target size.
"""
# note: private function; subject to changes
processed_results = []
for results_per_image, input_per_image, image_size in zip(
instances, batched_inputs, image_sizes
):
height = input_per_image.get("height", image_size[0])
width = input_per_image.get("width", image_size[1])
r = detector_postprocess(results_per_image, height, width)
processed_results.append({"instances": r})
return processed_results
@META_ARCH_REGISTRY.register()
class ProposalNetwork(nn.Module):
"""
A meta architecture that only predicts object proposals.
"""
@configurable
def __init__(
self,
*,
backbone: Backbone,
proposal_generator: nn.Module,
pixel_mean: Tuple[float],
pixel_std: Tuple[float],
):
"""
Args:
backbone: a backbone module, must follow detectron2's backbone interface
proposal_generator: a module that generates proposals using backbone features
pixel_mean, pixel_std: list or tuple with #channels element, representing
the per-channel mean and std to be used to normalize the input image
"""
super().__init__()
self.backbone = backbone
self.proposal_generator = proposal_generator
self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False)
self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False)
@classmethod
def from_config(cls, cfg):
backbone = build_backbone(cfg)
return {
"backbone": backbone,
"proposal_generator": build_proposal_generator(cfg, backbone.output_shape()),
"pixel_mean": cfg.MODEL.PIXEL_MEAN,
"pixel_std": cfg.MODEL.PIXEL_STD,
}
@property
def device(self):
return self.pixel_mean.device
def forward(self, batched_inputs):
"""
Args:
Same as in :class:`GeneralizedRCNN.forward`
Returns:
list[dict]:
Each dict is the output for one input image.
The dict contains one key "proposals" whose value is a
:class:`Instances` with keys "proposal_boxes" and "objectness_logits".
"""
images = [x["image"].to(self.device) for x in batched_inputs]
images = [(x - self.pixel_mean) / self.pixel_std for x in images]
images = ImageList.from_tensors(images, self.backbone.size_divisibility)
features = self.backbone(images.tensor)
if "instances" in batched_inputs[0]:
gt_instances = [x["instances"].to(self.device) for x in batched_inputs]
elif "targets" in batched_inputs[0]:
log_first_n(
logging.WARN, "'targets' in the model inputs is now renamed to 'instances'!", n=10
)
gt_instances = [x["targets"].to(self.device) for x in batched_inputs]
else:
gt_instances = None
proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)
# In training, the proposals are not useful at all but we generate them anyway.
# This makes RPN-only models about 5% slower.
if self.training:
return proposal_losses
processed_results = []
for results_per_image, input_per_image, image_size in zip(
proposals, batched_inputs, images.image_sizes
):
height = input_per_image.get("height", image_size[0])
width = input_per_image.get("width", image_size[1])
r = detector_postprocess(results_per_image, height, width)
processed_results.append({"proposals": r})
return processed_results
| 40.990854 | 98 | 0.635552 |
c812451c2d8d122df7957dc13014ffc333c7af5c | 19,607 | py | Python | lego/apps/events/views.py | ion05/lego | 873f6898e35ed2d9a33bdfb8339eaf6c9a61470c | [
"MIT"
] | null | null | null | lego/apps/events/views.py | ion05/lego | 873f6898e35ed2d9a33bdfb8339eaf6c9a61470c | [
"MIT"
] | null | null | null | lego/apps/events/views.py | ion05/lego | 873f6898e35ed2d9a33bdfb8339eaf6c9a61470c | [
"MIT"
] | null | null | null | from django.db import transaction
from django.db.models import Count, Prefetch, Q
from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import decorators, filters, mixins, permissions, status, viewsets
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
from celery import chain
from lego.apps.events import constants
from lego.apps.events.exceptions import (
APIEventNotFound,
APIEventNotPriced,
APINoSuchPool,
APINoSuchRegistration,
APIPaymentDenied,
APIPaymentExists,
APIRegistrationExists,
APIRegistrationsExistsInPool,
NoSuchPool,
NoSuchRegistration,
RegistrationExists,
RegistrationsExistInPool,
)
from lego.apps.events.filters import EventsFilterSet
from lego.apps.events.models import Event, Pool, Registration
from lego.apps.events.serializers.events import (
EventAdministrateSerializer,
EventCreateAndUpdateSerializer,
EventReadAuthUserDetailedSerializer,
EventReadSerializer,
EventReadUserDetailedSerializer,
EventUserRegSerializer,
populate_event_registration_users_with_grade,
)
from lego.apps.events.serializers.pools import PoolCreateAndUpdateSerializer
from lego.apps.events.serializers.registrations import (
AdminRegistrationCreateAndUpdateSerializer,
AdminUnregisterSerializer,
RegistrationConsentSerializer,
RegistrationCreateAndUpdateSerializer,
RegistrationPaymentReadSerializer,
RegistrationReadDetailedSerializer,
RegistrationReadSerializer,
RegistrationSearchReadSerializer,
RegistrationSearchSerializer,
StripePaymentIntentSerializer,
)
from lego.apps.events.tasks import (
async_cancel_payment,
async_initiate_payment,
async_register,
async_retrieve_payment,
async_unregister,
check_for_bump_on_pool_creation_or_expansion,
save_and_notify_payment,
)
from lego.apps.permissions.api.filters import LegoPermissionFilter
from lego.apps.permissions.api.views import AllowedPermissionsMixin
from lego.apps.permissions.utils import get_permission_handler
from lego.apps.users.models import User
from lego.utils.functions import verify_captcha
class EventViewSet(AllowedPermissionsMixin, viewsets.ModelViewSet):
filter_class = EventsFilterSet
filter_backends = (
DjangoFilterBackend,
filters.OrderingFilter,
LegoPermissionFilter,
)
ordering_fields = ("start_time", "end_time", "title")
ordering = "start_time"
pagination_class = None
def get_queryset(self):
user = self.request.user
if self.action in ["list", "upcoming"]:
queryset = Event.objects.select_related("company").prefetch_related(
"pools", "pools__registrations", "tags"
)
elif self.action == "retrieve":
queryset = Event.objects.select_related(
"company", "responsible_group"
).prefetch_related("pools", "pools__permission_groups", "tags")
if user and user.is_authenticated:
reg_queryset = self.get_registrations(user)
queryset = queryset.prefetch_related(
"can_edit_users",
"can_edit_groups",
Prefetch("pools__registrations", queryset=reg_queryset),
Prefetch("registrations", queryset=reg_queryset),
)
else:
queryset = Event.objects.all()
return queryset
def get_registrations(self, user):
current_user_groups = user.all_groups
query = Q()
for group in current_user_groups:
query |= Q(user__abakus_groups=group)
registrations = Registration.objects.select_related("user").annotate(
shared_memberships=Count("user__abakus_groups", filter=query)
)
return registrations
def get_serializer_class(self):
if self.action in ["create", "partial_update", "update"]:
return EventCreateAndUpdateSerializer
if self.action == "list":
return EventReadSerializer
if self.action == "retrieve":
user = self.request.user
event = Event.objects.get(id=self.kwargs.get("pk", None))
if (
event
and user
and user.is_authenticated
and event.user_should_see_regs(user)
):
return EventReadAuthUserDetailedSerializer
return EventReadUserDetailedSerializer
return super().get_serializer_class()
def update(self, request, *args, **kwargs):
""" If the capacity of the event increases we have to bump waiting users. """
try:
event_id = self.kwargs.get("pk", None)
instance = super().update(request, *args, **kwargs)
check_for_bump_on_pool_creation_or_expansion.delay(event_id)
return instance
except RegistrationsExistInPool:
raise APIRegistrationsExistsInPool()
def perform_update(self, serializer):
"""
We set the is_ready flag on update to lock the event for bumping waiting registrations.
This is_ready flag is set to True when the bumping is finished
"""
serializer.save(is_ready=False)
@decorators.action(
detail=True, methods=["GET"], serializer_class=EventAdministrateSerializer
)
def administrate(self, request, *args, **kwargs):
event_id = self.kwargs.get("pk", None)
queryset = Event.objects.filter(pk=event_id).prefetch_related(
"pools__permission_groups",
Prefetch(
"pools__registrations",
queryset=Registration.objects.select_related("user").prefetch_related(
"user__abakus_groups"
),
),
Prefetch(
"registrations", queryset=Registration.objects.select_related("user")
),
)
event = queryset.first()
event_data = self.get_serializer(event).data
event_data = populate_event_registration_users_with_grade(event_data)
return Response(event_data)
@decorators.action(detail=True, methods=["POST"], serializer_class=BaseSerializer)
def payment(self, request, *args, **kwargs):
event_id = self.kwargs.get("pk", None)
event = Event.objects.get(id=event_id)
registration = event.get_registration(request.user)
if not event.is_priced or not event.use_stripe:
raise APIEventNotPriced()
if registration is None or not registration.can_pay:
raise APIPaymentDenied()
if registration.has_paid():
raise APIPaymentExists()
if registration.payment_intent_id is None:
# If the payment_intent was not created when registering
chain(
async_initiate_payment.s(registration.id),
save_and_notify_payment.s(registration.id),
).delay()
else:
async_retrieve_payment.delay(registration.id)
payment_serializer = RegistrationPaymentReadSerializer(
registration, context={"request": request}
)
response_data = payment_serializer.data
return Response(data=response_data, status=status.HTTP_202_ACCEPTED)
@decorators.action(
detail=False,
serializer_class=EventUserRegSerializer,
permission_classes=[permissions.IsAuthenticated],
)
def previous(self, request):
queryset = (
self.get_queryset()
.filter(
registrations__status=constants.SUCCESS_REGISTER,
registrations__user=request.user,
start_time__lt=timezone.now(),
)
.prefetch_related(
Prefetch(
"registrations",
queryset=Registration.objects.filter(
user=request.user
).select_related("user", "pool"),
to_attr="user_reg",
),
Prefetch(
"pools",
queryset=Pool.objects.filter(
permission_groups__in=self.request.user.all_groups
),
to_attr="possible_pools",
),
)
)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
@decorators.action(
detail=False,
serializer_class=EventUserRegSerializer,
permission_classes=[permissions.IsAuthenticated],
)
def upcoming(self, request):
queryset = (
self.get_queryset()
.filter(
registrations__status=constants.SUCCESS_REGISTER,
registrations__user=request.user,
start_time__gt=timezone.now(),
)
.prefetch_related(
Prefetch(
"registrations",
queryset=Registration.objects.filter(
user=request.user
).select_related("user", "pool"),
to_attr="user_reg",
),
Prefetch(
"pools",
queryset=Pool.objects.filter(
permission_groups__in=self.request.user.all_groups
),
to_attr="possible_pools",
),
)
)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
class PoolViewSet(
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
queryset = Pool.objects.all()
serializer_class = PoolCreateAndUpdateSerializer
def get_queryset(self):
event_id = self.kwargs.get("event_pk", None)
return Pool.objects.filter(event=event_id).prefetch_related(
"permission_groups", "registrations"
)
def destroy(self, request, *args, **kwargs):
try:
return super().destroy(request, *args, **kwargs)
except ValueError:
raise APIRegistrationsExistsInPool
class RegistrationViewSet(
AllowedPermissionsMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
serializer_class = RegistrationReadSerializer
ordering = "registration_date"
def get_serializer_class(self):
if self.action in ["create", "update", "partial_update"]:
return RegistrationCreateAndUpdateSerializer
if self.action == "retrieve":
return RegistrationReadDetailedSerializer
return super().get_serializer_class()
def get_queryset(self):
event_id = self.kwargs.get("event_pk", None)
return Registration.objects.filter(event=event_id).prefetch_related("user")
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
event_id = self.kwargs.get("event_pk", None)
event = Event.objects.get(id=event_id)
if event.use_captcha and not verify_captcha(
serializer.data.get("captcha_response", None)
):
raise ValidationError({"error": "Bad captcha"})
current_user = request.user
with transaction.atomic():
registration = Registration.objects.get_or_create(
event_id=event_id,
user_id=current_user.id,
defaults={"updated_by": current_user, "created_by": current_user},
)[0]
feedback = serializer.data.get("feedback", "")
if registration.event.feedback_required and not feedback:
raise ValidationError({"error": "Feedback is required"})
registration.status = constants.PENDING_REGISTER
registration.feedback = feedback
registration.save(current_user=current_user)
transaction.on_commit(lambda: async_register.delay(registration.id))
registration.refresh_from_db()
registration_serializer = RegistrationReadSerializer(
registration, context={"user": registration.user}
)
return Response(
data=registration_serializer.data, status=status.HTTP_202_ACCEPTED
)
def destroy(self, request, *args, **kwargs):
with transaction.atomic():
instance = self.get_object()
instance.status = constants.PENDING_UNREGISTER
instance.save()
transaction.on_commit(lambda: async_unregister.delay(instance.id))
serializer = RegistrationReadSerializer(instance)
return Response(data=serializer.data, status=status.HTTP_202_ACCEPTED)
def update(self, request, *args, **kwargs):
registration = self.get_object()
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
if (
serializer.validated_data.get("payment_status", None)
== constants.PAYMENT_MANUAL
):
async_cancel_payment.delay(registration.id)
return super().update(request, *args, **kwargs)
@decorators.action(
detail=False,
methods=["POST"],
serializer_class=AdminRegistrationCreateAndUpdateSerializer,
)
def admin_register(self, request, *args, **kwargs):
admin_user = request.user
event_id = self.kwargs.get("event_pk", None)
try:
event = Event.objects.get(id=event_id)
except Event.DoesNotExist:
raise APIEventNotFound()
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
registration = event.admin_register(
admin_user=admin_user, **serializer.validated_data
)
except NoSuchPool:
raise APINoSuchPool()
except RegistrationExists:
raise APIRegistrationExists()
reg_data = RegistrationReadDetailedSerializer(registration).data
return Response(data=reg_data, status=status.HTTP_201_CREATED)
@decorators.action(
detail=False, methods=["POST"], serializer_class=AdminUnregisterSerializer
)
def admin_unregister(self, request, *args, **kwargs):
admin_user = request.user
event_id = self.kwargs.get("event_pk", None)
event = Event.objects.get(id=event_id)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
registration = event.admin_unregister(
admin_user=admin_user, **serializer.validated_data
)
if (
registration.payment_intent_id
and registration.payment_status != constants.PAYMENT_SUCCESS
):
async_cancel_payment.delay(registration.id)
except NoSuchRegistration:
raise APINoSuchRegistration()
except RegistrationExists:
raise APIRegistrationExists()
reg_data = RegistrationReadDetailedSerializer(registration).data
return Response(data=reg_data, status=status.HTTP_200_OK)
class RegistrationSearchViewSet(
AllowedPermissionsMixin, mixins.CreateModelMixin, viewsets.GenericViewSet
):
serializer_class = RegistrationSearchSerializer
ordering = "registration_date"
def get_queryset(self):
event_id = self.kwargs.get("event_pk", None)
return Registration.objects.filter(event=event_id).prefetch_related("user")
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
username = serializer.data["username"]
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise ValidationError(
{
"error": f"There is no user with username {username}",
"error_code": "no_user",
}
)
try:
reg = self.get_queryset().get(user=user)
except Registration.DoesNotExist:
raise ValidationError(
{
"error": "The registration does not exist",
"error_code": "not_registered",
}
)
if not get_permission_handler(Event).has_perm(
request.user, "EDIT", obj=reg.event
):
raise PermissionDenied()
if reg.status != constants.SUCCESS_REGISTER:
raise ValidationError(
{
"error": f"User {reg.user.username} is _not_ properly registerd. "
f"The registration status for the user is: {reg.status}",
"error_code": "already_present",
}
)
if reg.pool is None:
raise ValidationError(
{
"error": f"User {reg.user.username} is on the waiting list... "
"You can set the presence manualy on the 'Påmeldinger' tab",
"error_code": "already_present",
}
)
if reg.presence != constants.UNKNOWN:
raise ValidationError(
{
"error": f"User {reg.user.username} is already present.",
"error_code": "already_present",
}
)
reg.presence = constants.PRESENT
reg.save()
data = RegistrationSearchReadSerializer(reg).data
return Response(data=data, status=status.HTTP_200_OK)
class RegistrationConsentViewSet(
AllowedPermissionsMixin, mixins.CreateModelMixin, viewsets.GenericViewSet
):
serializer_class = RegistrationConsentSerializer
ordering = "registration_date"
def get_queryset(self):
event_id = self.kwargs.get("event_pk", None)
return Registration.objects.filter(event=event_id).prefetch_related("user")
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
username = serializer.data["username"]
photo_consent = serializer.data["photo_consent"]
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise ValidationError(
{
"error": f"There is no user with username {username}",
"error_code": "no_user",
}
)
try:
reg = self.get_queryset().get(user=user)
except Registration.DoesNotExist:
raise ValidationError(
{
"error": "The registration does not exist",
"error_code": "not_registered",
}
)
if not get_permission_handler(Event).has_perm(
request.user, "EDIT", obj=reg.event
):
raise PermissionDenied()
reg.photo_consent = photo_consent
reg.save()
data = RegistrationSearchReadSerializer(reg).data
return Response(data=data, status=status.HTTP_200_OK)
| 36.648598 | 95 | 0.627582 |
693c3b79d60a21355f60dc7e2e7131f438f67c8d | 629 | py | Python | src/blog_posts/api/serializers.py | rooneyrulz/django_blog_post_api | 33335074fa3ed78ba0f3a371093552cb7381528c | [
"MIT"
] | 3 | 2019-10-29T08:45:22.000Z | 2020-04-15T05:10:58.000Z | src/blog_posts/api/serializers.py | rooneyrulz/django_blog_post_api | 33335074fa3ed78ba0f3a371093552cb7381528c | [
"MIT"
] | 5 | 2020-06-06T00:02:31.000Z | 2021-06-10T19:09:56.000Z | src/blog_posts/api/serializers.py | rooneyrulz/django_blog_post_api | 33335074fa3ed78ba0f3a371093552cb7381528c | [
"MIT"
] | null | null | null | from rest_framework import serializers
from blog_posts.models import BlogPost
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = ['id', 'title', 'body', 'author', 'created_at']
def validate_title(self, value):
qs = BlogPost.objects.filter(title__iexact=value)
if qs.exists():
raise serializers.ValidationError('title has already been used!')
return value
def validate_body(self, value):
qs = BlogPost.objects.filter(body__iexact=value)
if qs.exists():
raise serializers.ValidationError('post body has already been used!')
return value | 33.105263 | 75 | 0.72814 |
6144244d2e296ebe6b8acb89fa9507140b280986 | 9,895 | py | Python | plugins/modules/oci_waas_address_list_facts.py | A7rMtWE57x/oci-ansible-collection | 80548243a085cd53fd5dddaa8135b5cb43612c66 | [
"Apache-2.0"
] | null | null | null | plugins/modules/oci_waas_address_list_facts.py | A7rMtWE57x/oci-ansible-collection | 80548243a085cd53fd5dddaa8135b5cb43612c66 | [
"Apache-2.0"
] | null | null | null | plugins/modules/oci_waas_address_list_facts.py | A7rMtWE57x/oci-ansible-collection | 80548243a085cd53fd5dddaa8135b5cb43612c66 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
# Copyright (c) 2017, 2020 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
# GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_waas_address_list_facts
short_description: Fetches details about one or multiple AddressList resources in Oracle Cloud Infrastructure
description:
- Fetches details about one or multiple AddressList resources in Oracle Cloud Infrastructure
- Gets a list of address lists that can be used in a WAAS policy.
- If I(address_list_id) is specified, the details of a single AddressList will be returned.
version_added: "2.9"
author: Oracle (@oracle)
options:
address_list_id:
description:
- The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the address list. This number is generated when the address
list is added to the compartment.
- Required to get a specific address_list.
type: str
aliases: ["id"]
compartment_id:
description:
- The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. This number is generated when the
compartment is created.
- Required to list multiple address_lists.
type: str
sort_by:
description:
- The value by which address lists are sorted in a paginated 'List' call. If unspecified, defaults to `timeCreated`.
type: str
choices:
- "id"
- "name"
- "timeCreated"
sort_order:
description:
- The value of the sorting direction of resources in a paginated 'List' call. If unspecified, defaults to `DESC`.
type: str
choices:
- "ASC"
- "DESC"
name:
description:
- Filter address lists using a list of names.
type: list
lifecycle_state:
description:
- Filter address lists using a list of lifecycle states.
type: list
choices:
- "CREATING"
- "ACTIVE"
- "FAILED"
- "UPDATING"
- "DELETING"
- "DELETED"
time_created_greater_than_or_equal_to:
description:
- A filter that matches address lists created on or after the specified date-time.
type: str
time_created_less_than:
description:
- A filter that matches address lists created before the specified date-time.
type: str
extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_display_name_option ]
"""
EXAMPLES = """
- name: List address_lists
oci_waas_address_list_facts:
compartment_id: ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx
- name: Get a specific address_list
oci_waas_address_list_facts:
address_list_id: ocid1.addresslist.oc1..xxxxxxEXAMPLExxxxxx
"""
RETURN = """
address_lists:
description:
- List of AddressList resources
returned: on success
type: complex
contains:
id:
description:
- The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the address list.
returned: on success
type: string
sample: ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx
compartment_id:
description:
- The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the address list's compartment.
returned: on success
type: string
sample: ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx
display_name:
description:
- The user-friendly name of the address list.
returned: on success
type: string
sample: display_name_example
address_count:
description:
- The total number of unique IP addresses in the address list.
returned: on success
type: float
sample: 10
addresses:
description:
- The list of IP addresses or CIDR notations.
returned: on success
type: list
sample: []
freeform_tags:
description:
- Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see L(Resource Tags,https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Department\\": \\"Finance\\"}`"
returned: on success
type: dict
sample: {'Department': 'Finance'}
defined_tags:
description:
- Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see L(Resource Tags,https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`"
returned: on success
type: dict
sample: {'Operations': {'CostCenter': 'US'}}
lifecycle_state:
description:
- The current lifecycle state of the address list.
returned: on success
type: string
sample: CREATING
time_created:
description:
- The date and time the address list was created, expressed in RFC 3339 timestamp format.
returned: on success
type: string
sample: 2018-11-16T21:10:29Z
sample: [{
"id": "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx",
"compartment_id": "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx",
"display_name": "display_name_example",
"address_count": 10,
"addresses": [],
"freeform_tags": {'Department': 'Finance'},
"defined_tags": {'Operations': {'CostCenter': 'US'}},
"lifecycle_state": "CREATING",
"time_created": "2018-11-16T21:10:29Z"
}]
"""
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils
from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (
OCIResourceFactsHelperBase,
get_custom_class,
)
try:
from oci.waas import WaasClient
HAS_OCI_PY_SDK = True
except ImportError:
HAS_OCI_PY_SDK = False
class AddressListFactsHelperGen(OCIResourceFactsHelperBase):
"""Supported operations: get, list"""
def get_required_params_for_get(self):
return [
"address_list_id",
]
def get_required_params_for_list(self):
return [
"compartment_id",
]
def get_resource(self):
return oci_common_utils.call_with_backoff(
self.client.get_address_list,
address_list_id=self.module.params.get("address_list_id"),
)
def list_resources(self):
optional_list_method_params = [
"sort_by",
"sort_order",
"name",
"lifecycle_state",
"time_created_greater_than_or_equal_to",
"time_created_less_than",
"display_name",
]
optional_kwargs = dict(
(param, self.module.params[param])
for param in optional_list_method_params
if self.module.params.get(param) is not None
)
return oci_common_utils.list_all_resources(
self.client.list_address_lists,
compartment_id=self.module.params.get("compartment_id"),
**optional_kwargs
)
AddressListFactsHelperCustom = get_custom_class("AddressListFactsHelperCustom")
class ResourceFactsHelper(AddressListFactsHelperCustom, AddressListFactsHelperGen):
pass
def main():
module_args = oci_common_utils.get_common_arg_spec()
module_args.update(
dict(
address_list_id=dict(aliases=["id"], type="str"),
compartment_id=dict(type="str"),
sort_by=dict(type="str", choices=["id", "name", "timeCreated"]),
sort_order=dict(type="str", choices=["ASC", "DESC"]),
name=dict(type="list"),
lifecycle_state=dict(
type="list",
choices=[
"CREATING",
"ACTIVE",
"FAILED",
"UPDATING",
"DELETING",
"DELETED",
],
),
time_created_greater_than_or_equal_to=dict(type="str"),
time_created_less_than=dict(type="str"),
display_name=dict(type="str"),
)
)
module = AnsibleModule(argument_spec=module_args)
if not HAS_OCI_PY_SDK:
module.fail_json(msg="oci python sdk required for this module.")
resource_facts_helper = ResourceFactsHelper(
module=module,
resource_type="address_list",
service_client_class=WaasClient,
namespace="waas",
)
result = []
if resource_facts_helper.is_get():
result = [resource_facts_helper.get()]
elif resource_facts_helper.is_list():
result = resource_facts_helper.list()
else:
resource_facts_helper.fail()
module.exit_json(address_lists=result)
if __name__ == "__main__":
main()
| 34.238754 | 159 | 0.616069 |
a9cec3ca05fc6dcc8528166758b86d678386c916 | 4,893 | py | Python | methods/VQVAE2/test.py | IvanNik17/Seasonal-Changes-in-Thermal-Surveillance-Imaging | 753ecd2751ac318d4a304c28404ae60dd8e3060c | [
"MIT"
] | 2 | 2021-11-30T06:26:21.000Z | 2022-02-26T10:57:55.000Z | methods/VQVAE2/test.py | IvanNik17/Seasonal-Changes-in-Thermal-Surveillance-Imaging | 753ecd2751ac318d4a304c28404ae60dd8e3060c | [
"MIT"
] | null | null | null | methods/VQVAE2/test.py | IvanNik17/Seasonal-Changes-in-Thermal-Surveillance-Imaging | 753ecd2751ac318d4a304c28404ae60dd8e3060c | [
"MIT"
] | null | null | null | import argparse
import os, sys
import cv2
import numpy as np
import csv
import torch
import pytorch_lightning as pl
#from torchsummary import summary
import torch.nn.functional as F
from torchvision import transforms
from models.vqvae2 import VQVAE2
from config import hparams
from glob import glob
sys.path.append('../../loaders/pytorch_lightning/')
from dataset import Dataset
import albumentations as Augment
import torchvision.utils as vutils
if hparams.in_channels == 3:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
else:
#mean, std = [0.5], [0.5]
mean, std = [0.0], [1.0]
test_t = Augment.Compose([Augment.Normalize(mean, std)])
def normalize(img):
print(hparams.in_channels)
if hparams.in_channels == 3:
img[0] = (img[0] - 0.5) / 0.5
img[1] = (img[1] - 0.5) / 0.5
img[2] = (img[2] - 0.5) / 0.5
else:
img[0] = (img[0] - 0.5) / 0.5
return img
'''
data_val = Dataset(img_dir=hparams.img_dir,
selection=hparams.train_selection,
return_metadata = hparams.get_metadata,
transforms=test_t)
'''
def process_video(video_path, net):
cap = cv2.VideoCapture(video_path)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
key = predict(img, net)
if key == 27:
break
def process_img(img_path, net):
if os.path.isfile(img_path):
output_path = os.path.join('output','x_'+os.path.basename(img_path))
#if hparams.in_channels == 1:
# img = cv2.imread(img_path, -1)
# img = img[:, :, np.newaxis]
#else:
img = cv2.imread(img_path,-1)
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(img.shape)
key = predict(img, net)
else:
print("file not found")
print(img_path)
def process_img_dir(img_dir, net):
img_list = sorted([y for y in glob(os.path.join(img_dir, 'val/*/*/*.jpg'))])
if len(img_list):
print("Found {} files".format(len(img_list)))
else:
print("did not find any files")
for img_path in img_list:
if os.path.isfile(img_path):
print(img_path)
output_path = os.path.join('output','x_'+os.path.basename(img_path))
if hparams.in_channels == 1:
img = cv2.imread(img_path, -1)
else:
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
key = predict(img, net)
if key == 27:
break
def predict(img, net):
if hparams.in_channels == 1:
img = img[:, :, np.newaxis]
x = img.transpose((2, 0, 1))/255.0
#x = normalize(x)
x = torch.as_tensor(x, dtype=torch.float32)
rec, diffs, encs, recs = net(x.unsqueeze(0))
rec = rec[0]
#
diff = x - rec
diff = torch.abs(diff)
diff = torch.clamp(diff, min=0.0, max=1.0)
diff = diff.mul(255).permute(1, 2, 0).byte().numpy()
#cv2.imwrite(output_path.replace('x_','diff'),diff)
diff = cv2.applyColorMap(diff, cv2.COLORMAP_JET)
cv2.imshow("diff",diff)
#rec = rec * 0.5 + 0.5
rec = torch.clamp(rec, min=0.0, max=1.0)
rec = rec.mul(255).permute(1, 2, 0).byte().numpy()
cv2.imshow("rec",rec)
cv2.imwrite("examples/rec.jpg",rec)
#x = x * 0.5 + 0.5
input = x.mul(255).permute(1, 2, 0).byte().numpy()
cv2.imshow("input",input)
cv2.imwrite("examples/input.jpg",input)
img_stack = cv2.vconcat([cv2.cvtColor(input, cv2.COLOR_GRAY2BGR), cv2.cvtColor(rec, cv2.COLOR_GRAY2BGR), diff])
#cv2.imwrite(output_path.replace('x_','input_rec_diff'),img_stack)
#cv2.imshow("test",img)
return cv2.waitKey()
if __name__ == '__main__':
"""
Trains an autoencoder from patches of thermal imaging.
Command:
python main.py
"""
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--checkpoint", type=str,
default='trained_models/feb_month/autoencoder.pt', help="path to the model file")
args = vars(ap.parse_args())
with torch.no_grad():
model = VQVAE2(in_channels=hparams.in_channels,
hidden_channels=hparams.hidden_channels,
embed_dim=hparams.embed_dim,
nb_entries=hparams.nb_entries,
nb_levels=hparams.nb_levels,
scaling_rates=hparams.scaling_rates)
model.load_state_dict(torch.load(args['checkpoint']))
model.eval()
#process_img("examples/elephant.jpg", model)
process_img("examples/thermal.jpg", model)
#process_video("03-03-2016 10_00_28 (UTC+01_00).mkv", net)
#process_img_dir(img_dir, net)
| 28.447674 | 115 | 0.595953 |
428ecd4e949e1519fb5d46643583d2e6c261ad8a | 5,322 | py | Python | sdks/python/apache_beam/io/gcp/tests/utils.py | hengfengli/beam | 83a8855e5997e0311e6274c03bcb38f94efbf8ef | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2022-01-11T19:43:12.000Z | 2022-01-15T15:45:20.000Z | sdks/python/apache_beam/io/gcp/tests/utils.py | hengfengli/beam | 83a8855e5997e0311e6274c03bcb38f94efbf8ef | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 8 | 2021-04-15T02:46:05.000Z | 2022-01-17T02:19:04.000Z | sdks/python/apache_beam/io/gcp/tests/utils.py | hengfengli/beam | 83a8855e5997e0311e6274c03bcb38f94efbf8ef | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 17 | 2021-12-15T19:31:54.000Z | 2022-01-31T18:54:23.000Z | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Utility methods for testing on GCP."""
# pytype: skip-file
import logging
import random
import time
from apache_beam.io import filesystems
from apache_beam.io.gcp.pubsub import PubsubMessage
from apache_beam.utils import retry
# Protect against environments where bigquery library is not available.
try:
from google.api_core import exceptions as gexc
from google.cloud import bigquery
except ImportError:
gexc = None
bigquery = None
_LOGGER = logging.getLogger(__name__)
class GcpTestIOError(retry.PermanentException):
"""Basic GCP IO error for testing. Function that raises this error should
not be retried."""
pass
@retry.with_exponential_backoff(
num_retries=3, retry_filter=retry.retry_on_server_errors_filter)
def create_bq_dataset(project, dataset_base_name):
"""Creates an empty BigQuery dataset.
Args:
project: Project to work in.
dataset_base_name: Prefix for dataset id.
Returns:
A ``google.cloud.bigquery.dataset.DatasetReference`` object pointing to the
new dataset.
"""
client = bigquery.Client(project=project)
unique_dataset_name = '%s%s%d' % (
dataset_base_name, str(int(time.time())), random.randint(0, 10000))
dataset_ref = client.dataset(unique_dataset_name, project=project)
dataset = bigquery.Dataset(dataset_ref)
client.create_dataset(dataset)
return dataset_ref
@retry.with_exponential_backoff(
num_retries=3, retry_filter=retry.retry_on_server_errors_filter)
def delete_bq_dataset(project, dataset_ref):
"""Deletes a BigQuery dataset and its contents.
Args:
project: Project to work in.
dataset_ref: A ``google.cloud.bigquery.dataset.DatasetReference`` object
pointing to the dataset to delete.
"""
client = bigquery.Client(project=project)
client.delete_dataset(dataset_ref, delete_contents=True)
@retry.with_exponential_backoff(
num_retries=3, retry_filter=retry.retry_on_server_errors_filter)
def delete_bq_table(project, dataset_id, table_id):
"""Delete a BiqQuery table.
Args:
project: Name of the project.
dataset_id: Name of the dataset where table is.
table_id: Name of the table.
"""
_LOGGER.info(
'Clean up a BigQuery table with project: %s, dataset: %s, '
'table: %s.',
project,
dataset_id,
table_id)
client = bigquery.Client(project=project)
table_ref = client.dataset(dataset_id).table(table_id)
try:
client.delete_table(table_ref)
except gexc.NotFound:
raise GcpTestIOError('BigQuery table does not exist: %s' % table_ref)
@retry.with_exponential_backoff(
num_retries=3, retry_filter=retry.retry_on_server_errors_filter)
def delete_directory(directory):
"""Delete a directory in a filesystem.
Args:
directory: Full path to a directory supported by Beam filesystems (e.g.
"gs://mybucket/mydir/", "s3://...", ...)
"""
filesystems.FileSystems.delete([directory])
def write_to_pubsub(
pub_client,
topic_path,
messages,
with_attributes=False,
chunk_size=100,
delay_between_chunks=0.1):
for start in range(0, len(messages), chunk_size):
message_chunk = messages[start:start + chunk_size]
if with_attributes:
futures = [
pub_client.publish(topic_path, message.data, **message.attributes)
for message in message_chunk
]
else:
futures = [
pub_client.publish(topic_path, message) for message in message_chunk
]
for future in futures:
future.result()
time.sleep(delay_between_chunks)
def read_from_pubsub(
sub_client,
subscription_path,
with_attributes=False,
number_of_elements=None,
timeout=None):
if number_of_elements is None and timeout is None:
raise ValueError("Either number_of_elements or timeout must be specified.")
messages = []
start_time = time.time()
while ((number_of_elements is None or len(messages) < number_of_elements) and
(timeout is None or (time.time() - start_time) < timeout)):
try:
response = sub_client.pull(
subscription_path, max_messages=1000, retry=None, timeout=10)
except (gexc.RetryError, gexc.DeadlineExceeded):
continue
ack_ids = [msg.ack_id for msg in response.received_messages]
sub_client.acknowledge(subscription=subscription_path, ack_ids=ack_ids)
for msg in response.received_messages:
message = PubsubMessage._from_message(msg.message)
if with_attributes:
messages.append(message)
else:
messages.append(message.data)
return messages
| 31.491124 | 79 | 0.734686 |
74928b04474e53c61ba41643a520e641fc3b3b09 | 506 | py | Python | code/pose-invariant-face-recognition/test.py | FRH-Code-Data/Appendix | 106a7c65c178d2b446e3bd8fb192ac2f4b7e323f | [
"CC-BY-4.0"
] | 5 | 2020-02-28T09:28:55.000Z | 2021-06-03T02:15:42.000Z | code/pose-invariant-face-recognition/test.py | FRH-Code-Data/Appendix | 106a7c65c178d2b446e3bd8fb192ac2f4b7e323f | [
"CC-BY-4.0"
] | 6 | 2020-03-08T22:58:13.000Z | 2022-03-12T00:15:14.000Z | code/pose-invariant-face-recognition/test.py | FRH-Code-Data/Appendix | 106a7c65c178d2b446e3bd8fb192ac2f4b7e323f | [
"CC-BY-4.0"
] | 3 | 2020-02-28T09:29:03.000Z | 2020-03-09T05:08:07.000Z | import torch
import sys
sys.path.append('/home/zhangjunhao/options')
from test_options import TestOptions
sys.path.append('/home/zhangjunhao/data')
from data_loader import CreateDataLoader
sys.path.append('/home/zhangjunhao/model')
from model_Loader import CreateModel
opt = TestOptions().parse()
data_loader = CreateDataLoader(opt)
model = CreateModel(opt)
total_steps = 0
for i, data in enumerate(data_loader):
total_steps += len(data)
model.forward(data)
print(i)
model.save_result()
| 24.095238 | 44 | 0.768775 |
cbb9fa43399478010745d4262b5b07ec32029991 | 337 | py | Python | profiles_api/migrations/0002_auto_20200213_2002.py | TanishqGupta11/profiles-rest-api | 60e6fff08844a5c34897f189eb9b76d475781180 | [
"MIT"
] | 1 | 2020-01-27T14:21:51.000Z | 2020-01-27T14:21:51.000Z | profiles_api/migrations/0002_auto_20200213_2002.py | TanishqGupta11/profiles-rest-api | 60e6fff08844a5c34897f189eb9b76d475781180 | [
"MIT"
] | 5 | 2020-06-06T01:24:34.000Z | 2022-02-10T12:55:38.000Z | profiles_api/migrations/0002_auto_20200213_2002.py | TanishqGupta11/profiles-rest-api | 60e6fff08844a5c34897f189eb9b76d475781180 | [
"MIT"
] | null | null | null | # Generated by Django 2.2 on 2020-02-13 20:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('profiles_api', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='userprofile',
managers=[
],
),
]
| 17.736842 | 45 | 0.566766 |
38b497be13a693e5dcb84c0e1d9fe4b68e4981d0 | 1,896 | py | Python | stdplugins/antivirus.py | ppppspsljdhdd/Pepe | 1e57825ddb0ab3ba15a19cad0ecfbf2622f6b851 | [
"Apache-2.0"
] | 20 | 2020-01-25T05:08:26.000Z | 2022-01-18T07:37:53.000Z | stdplugins/antivirus.py | ishaizz/PepeBot | 7440cadc8228106d221fc8e436a0809a86be5159 | [
"Apache-2.0"
] | 15 | 2019-11-07T07:53:56.000Z | 2022-01-23T09:21:17.000Z | stdplugins/antivirus.py | ishaizz/PepeBot | 7440cadc8228106d221fc8e436a0809a86be5159 | [
"Apache-2.0"
] | 62 | 2019-10-20T06:35:19.000Z | 2021-01-23T17:26:05.000Z | # Lots of lub to @r4v4n4 for gibing the base <3
# copied from @A_Dark_Prince3
"""Type .scan
\nReply to a file/media."""
import logging
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from uniborg.util import admin_cmd
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.WARN
)
@borg.on(admin_cmd(pattern="scan ?(.*)"))
async def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await event.edit("```Reply to a file to Scan !```")
return
reply_message = await event.get_reply_message()
if not reply_message.media:
await event.edit("```Reply to a media message```")
return
chat = "@DrWebBot"
reply_message.sender
if reply_message.sender.bot:
await event.edit("```Reply to actual users message.```")
return
await event.edit(" `Sliding my tip, of fingers over it`")
async with borg.conversation(chat) as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=161163358)
)
await borg.forward_messages(chat, reply_message)
response = await response
except YouBlockedUserError:
await event.reply("```Please unblock @DrWebBot and try again```")
return
if response.text.startswith("Forward"):
await event.edit(
"```can you kindly disable your forward privacy settings for good?```"
)
else:
if response.text.startswith("Select"):
await event.edit("`Please go to` @DrWebBot `and select your language.`")
else:
await event.edit(
f"**Antivirus scan was completed. I got dem final results.**\n {response.message.message}"
)
| 33.857143 | 110 | 0.613397 |
9c6f4a3fe4c260ba9047a7631b676fd6d6987086 | 2,896 | py | Python | libs/GoodOvernight.py | bioinformagic/monica | a9e8c7b75ce6cb4294f3c5e1d772a5acc980cc6a | [
"MIT"
] | 7 | 2018-11-20T21:10:52.000Z | 2019-04-17T05:49:30.000Z | libs/GoodOvernight.py | bioinformagic/monica | a9e8c7b75ce6cb4294f3c5e1d772a5acc980cc6a | [
"MIT"
] | 7 | 2018-12-07T06:50:28.000Z | 2018-12-11T23:40:35.000Z | libs/GoodOvernight.py | bioinformagic/monica | a9e8c7b75ce6cb4294f3c5e1d772a5acc980cc6a | [
"MIT"
] | null | null | null | import subprocess
import os
import xml.etree.ElementTree as parXML
import wget
from src.piper_pan import shell_runner
# TODO add documentation to your code!
class GoodOvernight():
def __init__(self):
pass
def unmapped_extractor(self, exp_output, unmapped_path): # this creates fasta files over unmapped bam sequences
list_bam_files = []
for file in os.listdir(exp_output):
if file.endswith('.bam'):
list_bam_files.append(file)
for element in list_bam_files:
subprocess.Popen(
'samtools fasta -f 4 ' + exp_output + '/' + element + ' > ' + unmapped_path + '/' + element[
:-4] + '_unmapped.fasta',
shell=True)
def biomarter(list):
wget.download('https://biodbnet-abcc.ncifcrf.gov/webServices/rest.php/biodbnetRestApi.xml?method=db2db&format=row&input=geneid&inputValues=' + ','.join(list) + '&outputs=refseqgenomicgi')#This line of code downloads from db2db a xml file with a specific filename
#that is biodbnetRestApi.xml
file = 'biodbnetRestApi.xml'
root = parXML.parse(file).getroot() # this line initializes the xml file so to be parsed
levels = root.findall('.//item')
ee = dict()
for level in levels:
GeneId = level.find('InputValue').text
Transformed = filter(None, str(level.find('RefSeqGenomicGI').text).split('//'))
ee[GeneId] = Transformed
# the previous for loop for every level so 'Gene' we may have 1 or different outputs from the sitethat are stored into Transformed and I create a dictionary knowing this datas
with open(file[:-4] + '_biomarter_output.txt', 'w') as out:
for gene in ee.keys():
for value in ee[gene]:
out.write(gene + ' ' + value + '\n')
os.remove(file)
# This creates a txt file as Gene and Ids
# example GoodOvernight.unmapped_extractor('/home/pepsi/Documents/Università/Bioinformatics2/mapped', '/home/pepsi/Documents/Università/Bioinformatics2/unmapped')
# example GoodOvernight.biomarter([])
def master_blaster(self):
"""
Blast the unmapped reads and returns the GenBank IDs
"""
id_list = []
# os.chdir("~Desktop/unmmaped_fasta")
# TODO fix parallel jobs with multiprocess.Pool()
blasting = shell_runner(
"ls *.fa | parallel 'blastn -query {} -db nt -remote -num_alignments 1 -outfmt 6 -out {.}.out'")
get_id = shell_runner("cut -f 2 *.out > list_ids.txt")
with open("list_ids.txt") as file:
output = [id_list.append(line.strip()) for line in file]
return id_list
if __name__ == "__main__":
goodOvernight = GoodOvernight()
| 43.223881 | 271 | 0.609461 |
0808c13e49de9e055666da4435be6921ecf21227 | 1,765 | py | Python | esnpy/init.py | NiZiL/esnpy | 8a29b5fefb67d5fd2f1f3efcbd1dbcd4b8cb6e7f | [
"MIT"
] | 6 | 2018-04-19T21:25:41.000Z | 2021-06-03T10:19:06.000Z | esnpy/init.py | NiZiL/esnpy | 8a29b5fefb67d5fd2f1f3efcbd1dbcd4b8cb6e7f | [
"MIT"
] | 2 | 2021-01-18T16:14:58.000Z | 2021-03-12T11:38:49.000Z | esnpy/init.py | NiZiL/esnpy | 8a29b5fefb67d5fd2f1f3efcbd1dbcd4b8cb6e7f | [
"MIT"
] | 3 | 2018-07-23T10:15:06.000Z | 2021-06-03T09:24:52.000Z | # -*- coding: utf-8 -*-
import numpy as np
import scipy.sparse
def _uniform(shape, bmin, bmax):
return np.random.rand(*shape).dot(bmax-bmin) + bmin
def _normal(shape, mu, sigma):
return np.random.randn(*shape).dot(sigma) + mu
class CompositeInit():
def __init__(self, *args):
self.args = args
def init(self, srow, scol):
#assert srow == np.sum(arg[1] for arg in self.args)
return np.vstack(arg[0].init(arg[1], scol) for arg in self.args)
class UniformDenseInit():
def __init__(self, bmin, bmax):
self._min = bmin
self._max = bmax
def init(self, srow, scol):
return _uniform((srow, scol), self._min, self._max)
class NormalDenseInit():
def __init__(self, mu, sigma):
self._sigma = sigma
self._mu = mu
def init(self, srow, scol):
return _normal((srow, scol), self._mu, self._sigma)
class SparseInit():
def __init__(self, density):
self._d = density
def init(self, srow, scol):
m = scipy.sparse.rand(srow, scol, density=self._d)
m.data = self._rand_data(len(m.data))
return m.tocsr()
def _rand_data(self, size):
raise NotImplementedError()
class UniformSparseInit(SparseInit):
def __init__(self, bmin, bmax, density):
super(UniformSparseInit, self).__init__(density)
self._min = bmin
self._max = bmax
def _rand_data(self, size):
return _uniform((size,), self._max, self._min)
class NormalSparseInit(SparseInit):
def __init__(self, mu, sigma, density):
super(NormalSparseInit, self).__init__(density)
self._mu = mu
self._sigma = sigma
def _rand_data(self, size):
return _normal((size,), self._mu, self._sigma)
| 24.513889 | 72 | 0.627762 |
66c477ff18e3593164694dfce08278578f4c6c6a | 12,452 | py | Python | qnapstats/qnap_stats.py | colinodell/python-qnapstats | 1e4a130aa178e11c1fdb21aca95ee9d60d128cdb | [
"MIT"
] | 42 | 2017-04-28T13:35:43.000Z | 2022-02-03T06:53:36.000Z | qnapstats/qnap_stats.py | colinodell/python-qnapstats | 1e4a130aa178e11c1fdb21aca95ee9d60d128cdb | [
"MIT"
] | 60 | 2017-02-12T09:09:36.000Z | 2022-03-26T11:59:57.000Z | qnapstats/qnap_stats.py | colinodell/python-qnapstats | 1e4a130aa178e11c1fdb21aca95ee9d60d128cdb | [
"MIT"
] | 17 | 2017-02-12T08:12:50.000Z | 2021-12-26T09:52:36.000Z | """Module containing multiple classes to obtain QNAP system stats via cgi calls."""
# -*- coding:utf-8 -*-
import base64
import json
import xmltodict
import requests
# pylint: disable=too-many-instance-attributes
class QNAPStats:
"""Class containing the main functions."""
# pylint: disable=too-many-arguments
def __init__(self, host, port, username, password, debugmode=False, verify_ssl=True, timeout=5):
"""Instantiate a new qnap_stats object."""
self._username = username
self._password = base64.b64encode(password.encode('utf-8')).decode('ascii')
self._sid = None
self._debugmode = debugmode
self._session_error = False
self._session = None # type: requests.Session
if not (host.startswith("http://") or host.startswith("https://")):
host = "http://" + host
self._verify_ssl = verify_ssl
self._timeout = timeout
self._base_url = '%s:%s/cgi-bin/' % (host, port)
def _debuglog(self, message):
"""Output message if debug mode is enabled."""
if self._debugmode:
print("DEBUG: " + message)
def _init_session(self):
if self._sid is None or self._session is None or self._session_error:
# Clear sid and reset error
self._sid = None
self._session_error = False
if self._session is not None:
self._session = None
self._debuglog("Creating new session")
self._session = requests.Session()
# We created a new session so login
if self._login() is False:
self._session_error = True
self._debuglog("Login failed, unable to process request")
return
def _login(self):
"""Log into QNAP and obtain a session id."""
data = {"user": self._username, "pwd": self._password}
result = self._execute_post_url("authLogin.cgi", data, False)
if result is None or not result.get("authSid"):
# Another method to login
suffix_url = "authLogin.cgi?user=" + self._username + "&pwd=" + self._password
result = self._execute_get_url(suffix_url, False)
if result is None:
return False
self._sid = result["authSid"]
return True
def _get_url(self, url, retry_on_error=True, **kwargs):
"""High-level function for making GET requests."""
self._init_session()
result = self._execute_get_url(url, **kwargs)
if (self._session_error or result is None) and retry_on_error:
self._debuglog("Error occured, retrying...")
self._get_url(url, False, **kwargs)
return result
def _execute_get_url(self, url, append_sid=True, **kwargs):
"""Low-level function to execute a GET request."""
url = self._base_url + url
self._debuglog("GET from URL: " + url)
if append_sid:
self._debuglog("Appending access_token (SID: " + self._sid + ") to url")
url = "%s&sid=%s" % (url, self._sid)
resp = self._session.get(url, timeout=self._timeout, verify=self._verify_ssl)
return self._handle_response(resp, **kwargs)
def _execute_post_url(self, url, data, append_sid=True, **kwargs):
"""Low-level function to execute a POST request."""
url = self._base_url + url
self._debuglog("POST to URL: " + url)
if append_sid:
self._debuglog("Appending access_token (SID: " + self._sid + ") to url")
data["sid"] = self._sid
resp = self._session.post(url, data, timeout=self._timeout, verify=self._verify_ssl)
return self._handle_response(resp, **kwargs)
def _handle_response(self, resp, force_list=None):
"""Ensure response is successful and return body as XML."""
self._debuglog("Request executed: " + str(resp.status_code))
if resp.status_code != 200:
return None
if resp.headers["Content-Type"] != "text/xml":
# JSON requests not currently supported
return None
self._debuglog("Headers: " + json.dumps(dict(resp.headers)))
self._debuglog("Cookies: " + json.dumps(dict(resp.cookies)))
self._debuglog("Response Text: " + resp.text)
data = xmltodict.parse(resp.content, force_list=force_list)['QDocRoot']
auth_passed = data.get('authPassed')
if auth_passed is not None and len(auth_passed) == 1 and auth_passed == "0":
self._session_error = True
return None
return data
def get_system_health(self):
"""Obtain the system's overall health."""
resp = self._get_url("management/manaRequest.cgi?subfunc=sysinfo&sysHealth=1")
if resp is None:
return None
status = resp["func"]["ownContent"]["sysHealth"]["status"]
if status is None or len(status) == 0:
return None
return status
def get_volumes(self):
"""Obtain information about volumes and shared directories."""
resp = self._get_url(
"management/chartReq.cgi?chart_func=disk_usage&disk_select=all&include=all",
force_list=("volume", "volumeUse", "folder_element")
)
if resp is None:
return None
if resp["volumeList"] is None or resp["volumeUseList"] is None:
return {}
volumes = {}
id_map = {}
for vol in resp["volumeList"]["volume"]:
key = vol["volumeValue"]
label = vol["volumeLabel"] if "volumeLabel" in vol else "Volume " + vol["volumeValue"]
volumes[label] = {
"id": key,
"label": label
}
id_map[key] = label
for vol in resp["volumeUseList"]["volumeUse"]:
id_number = vol["volumeValue"]
# Skip any system reserved volumes
if id_number not in id_map.keys():
continue
key = id_map[id_number]
volumes[key]["free_size"] = int(vol["free_size"])
volumes[key]["total_size"] = int(vol["total_size"])
folder_elements = vol["folder_element"]
if len(folder_elements) > 0:
volumes[key]["folders"] = []
for folder in folder_elements:
try:
sharename = folder["sharename"]
used_size = int(folder["used_size"])
volumes[key]["folders"].append({"sharename": sharename, "used_size": used_size})
except Exception as e:
print(e.args)
return volumes
def get_smart_disk_health(self):
"""Obtain SMART information about each disk."""
resp = self._get_url("disk/qsmart.cgi?func=all_hd_data", force_list=("entry"))
if resp is None:
return None
disks = {}
for disk in resp["Disk_Info"]["entry"]:
if disk["Model"]:
disks[disk["HDNo"]] = {
"drive_number": disk["HDNo"],
"health": disk["Health"],
"temp_c": int(disk["Temperature"]["oC"]) if disk["Temperature"]["oC"] is not None else None,
"temp_f": int(disk["Temperature"]["oF"]) if disk["Temperature"]["oF"] is not None else None,
"capacity": disk["Capacity"],
"model": disk["Model"],
"serial": disk["Serial"],
"type": "ssd" if ("hd_is_ssd" in disk and int(disk["hd_is_ssd"])) else "hdd",
}
return disks
def get_system_stats(self):
"""Obtain core system information and resource utilization."""
resp = self._get_url(
"management/manaRequest.cgi?subfunc=sysinfo&hd=no&multicpu=1",
force_list=("DNS_LIST")
)
if resp is None:
return None
root = resp["func"]["ownContent"]["root"]
details = {
"system": {
"name": root["server_name"],
"model": resp["model"]["displayModelName"],
"serial_number": root["serial_number"],
"temp_c": int(root["sys_tempc"]),
"temp_f": int(root["sys_tempf"]),
"timezone": root["timezone"],
},
"firmware": {
"version": resp["firmware"]["version"],
"build": resp["firmware"]["build"],
"patch": resp["firmware"]["patch"],
"build_time": resp["firmware"]["buildTime"],
},
"uptime": {
"days": int(root["uptime_day"]),
"hours": int(root["uptime_hour"]),
"minutes": int(root["uptime_min"]),
"seconds": int(root["uptime_sec"]),
},
"cpu": {
"model": root["cpu_model"] if "cpu_model" in root else None,
"usage_percent": float(root["cpu_usage"].replace("%", "")),
"temp_c": int(root["cpu_tempc"]) if "cpu_tempc" in root else None,
"temp_f": int(root["cpu_tempf"]) if "cpu_tempf" in root else None,
},
"memory": {
"total": float(root["total_memory"]),
"free": float(root["free_memory"]),
},
"nics": {},
"dns": [],
}
nic_count = int(root["nic_cnt"])
for nic_index in range(nic_count):
i = str(nic_index + 1)
interface = "eth" + str(nic_index)
status = root["eth_status" + i]
details["nics"][interface] = {
"link_status": "Up" if status == "1" else "Down",
"max_speed": int(root["eth_max_speed" + i]),
"ip": root["eth_ip" + i],
"mask": root["eth_mask" + i],
"mac": root["eth_mac" + i],
"usage": root["eth_usage" + i],
"rx_packets": int(root["rx_packet" + i]),
"tx_packets": int(root["tx_packet" + i]),
"err_packets": int(root["err_packet" + i])
}
dnsInfo = root.get("dnsInfo")
if dnsInfo:
for dns in dnsInfo["DNS_LIST"]:
details["dns"].append(dns)
return details
def get_bandwidth(self):
"""Obtain the current bandwidth usage speeds."""
resp = self._get_url(
"management/chartReq.cgi?chart_func=QSM40bandwidth",
force_list="item"
)
if resp and "bandwidth_info" not in resp:
# changes in API since QTS 4.5.4, old query returns no values
resp = self._get_url("management/chartReq.cgi?chart_func=bandwidth")
if resp is None:
return None
details = {}
interfaces = []
bandwidth_info = resp["bandwidth_info"]
default = resp.get("df_gateway") or bandwidth_info.get("df_gateway")
if "item" in bandwidth_info:
interfaces.extend(bandwidth_info["item"])
else:
interfaceIds = []
if bandwidth_info["eth_index_list"]:
for num in bandwidth_info["eth_index_list"].split(','):
interfaceIds.append("eth" + num)
if bandwidth_info["wlan_index_list"]:
for num in bandwidth_info["wlan_index_list"].split(','):
interfaceIds.append("wlan" + num)
for interfaceId in interfaceIds:
interface = bandwidth_info[interfaceId]
interface["id"] = interfaceId
interfaces.extend([interface])
for item in interfaces:
details[item["id"]] = {
"name": item["dname"] if "dname" in item else item["name"],
"rx": round(int(item["rx"]) / 5),
"tx": round(int(item["tx"]) / 5),
"is_default": item["id"] == default
}
return details
def get_firmware_update(self):
"""Get firmware update version if available."""
resp = self._get_url("sys/sysRequest.cgi?subfunc=firm_update")
if resp is None:
return None
new_version = resp["func"]["ownContent"]["newVersion"]
if new_version is None or len(new_version) == 0:
return None
return new_version
| 36.409357 | 112 | 0.543768 |
de433a5cd93247f39d27204045e395c7d44e45cc | 2,538 | py | Python | xadmin/plugins/portal.py | charles820/django-xadmin | 605a8657ede430a458dfb1980db14414cac9fb0e | [
"BSD-3-Clause"
] | 1 | 2015-07-02T13:15:40.000Z | 2015-07-02T13:15:40.000Z | xadmin/plugins/portal.py | charles820/django-xadmin | 605a8657ede430a458dfb1980db14414cac9fb0e | [
"BSD-3-Clause"
] | null | null | null | xadmin/plugins/portal.py | charles820/django-xadmin | 605a8657ede430a458dfb1980db14414cac9fb0e | [
"BSD-3-Clause"
] | null | null | null | #coding:utf-8
from xadmin.sites import site
from xadmin.models import UserSettings
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, DetailAdminView
from xadmin.layout import Fieldset, Column
class BasePortalPlugin(BaseAdminPlugin):
# Media
def get_media(self, media):
return media + self.vendor('xadmin.plugin.portal.js')
def get_layout_objects(layout, clz, objects):
for i, layout_object in enumerate(layout.fields):
if layout_object.__class__ is clz or issubclass(layout_object.__class__, clz):
objects.append(layout_object)
elif hasattr(layout_object, 'get_field_names'):
get_layout_objects(layout_object, clz, objects)
class ModelFormPlugin(BasePortalPlugin):
def _portal_key(self):
return '%s_%s_editform_portal' % (self.opts.app_label, self.opts.module_name)
def get_form_helper(self, helper):
cs = []
layout = helper.layout
get_layout_objects(layout, Column, cs)
for i, c in enumerate(cs):
if not getattr(c, 'css_id', None):
c.css_id = 'column-%d' % i
# make fieldset index
fs = []
get_layout_objects(layout, Fieldset, fs)
fs_map = {}
for i, f in enumerate(fs):
if not getattr(f, 'css_id', None):
f.css_id = 'box-%d' % i
fs_map[f.css_id] = f
try:
layout_pos = UserSettings.objects.get(
user=self.user, key=self._portal_key()).value
layout_cs = layout_pos.split('|')
for i, c in enumerate(cs):
c.fields = [fs_map.pop(j) for j in layout_cs[i].split(
',') if j in fs_map] if len(layout_cs) > i else []
if fs_map and cs:
cs[0].fields.extend(fs_map.values())
except Exception:
pass
return helper
def block_form_top(self, context, node):
# put portal key and submit url to page
return "<input type='hidden' id='_portal_key' value='%s' />" % self._portal_key()
class ModelDetailPlugin(ModelFormPlugin):
def _portal_key(self):
return '%s_%s_detail_portal' % (self.opts.app_label, self.opts.module_name)
def block_after_fieldsets(self, context, node):
# put portal key and submit url to page
return "<input type='hidden' id='_portal_key' value='%s' />" % self._portal_key()
site.register_plugin(ModelFormPlugin, ModelFormAdminView)
site.register_plugin(ModelDetailPlugin, DetailAdminView)
| 33.84 | 89 | 0.635146 |
223d7893c9cb5ff5e66ae5b796895baa31b7c2c6 | 4,910 | py | Python | test/swe2d/test_standing_wave.py | jrper/thetis | 3c08a2e6947552119232fefd7380fa61b2a9b84b | [
"MIT"
] | null | null | null | test/swe2d/test_standing_wave.py | jrper/thetis | 3c08a2e6947552119232fefd7380fa61b2a9b84b | [
"MIT"
] | null | null | null | test/swe2d/test_standing_wave.py | jrper/thetis | 3c08a2e6947552119232fefd7380fa61b2a9b84b | [
"MIT"
] | null | null | null | # Test for temporal convergence of CrankNicolson and pressureprojection picard timesteppers,
# tests convergence of a single period of a standing wave in a rectangular channel.
# This only tests against a linear solution, so does not really test whether the splitting
# in PressureProjectionPicard between nonlinear momentum and linearized wave equation terms is correct.
# PressureProjectionPicard does need two iterations to ensure 2nd order convergence
from thetis import *
import pytest
import math
import h5py
@pytest.mark.parametrize("timesteps,max_rel_err", [
(10, 0.02), (20, 5e-3), (40, 1.25e-3)])
# with nonlin=True and nx=100 this converges for the series
# (10,0.02), (20,5e-3), (40, 1.25e-3)
# with nonlin=False further converge is possible
@pytest.mark.parametrize("timestepper", [
'CrankNicolson', 'PressureProjectionPicard', ])
def test_standing_wave_channel(timesteps, max_rel_err, timestepper, tmpdir, do_export=False):
lx = 5e3
ly = 1e3
nx = 100
mesh2d = RectangleMesh(nx, 1, lx, ly)
n = timesteps
depth = 100.
g = physical_constants['g_grav'].dat.data[0]
c = math.sqrt(g*depth)
period = 2*lx/c
dt = period/n
t_end = period-0.1*dt # make sure we don't overshoot
x = SpatialCoordinate(mesh2d)
elev_init = cos(pi*x[0]/lx)
# bathymetry
p1_2d = FunctionSpace(mesh2d, 'CG', 1)
bathymetry_2d = Function(p1_2d, name="bathymetry")
bathymetry_2d.assign(depth)
# --- create solver ---
solver_obj = solver2d.FlowSolver2d(mesh2d, bathymetry_2d)
solver_obj.options.timestep = dt
solver_obj.options.simulation_export_time = dt
solver_obj.options.simulation_end_time = t_end
solver_obj.options.no_exports = not do_export
solver_obj.options.timestepper_type = timestepper
solver_obj.options.output_directory = str(tmpdir)
if timestepper == 'CrankNicolson':
solver_obj.options.element_family = 'dg-dg'
# Crank Nicolson stops being 2nd order if we linearise
# (this is not the case for PressureProjectionPicard, as we do 2 Picard iterations)
solver_obj.options.timestepper_options.use_semi_implicit_linearization = False
elif timestepper == 'PressureProjectionPicard':
# this approach currently only works well with dg-cg, because in dg-dg
# the pressure gradient term puts an additional stabilisation term in the velocity block
# (even without that term this approach is not as fast, as the stencil for the assembled schur system
# is a lot bigger for dg-dg than dg-cg)
solver_obj.options.element_family = 'dg-cg'
solver_obj.options.timestepper_options.use_semi_implicit_linearization = True
solver_obj.options.timestepper_options.picard_iterations = 2
if hasattr(solver_obj.options.timestepper_options, 'use_automatic_timestep'):
solver_obj.options.timestepper_options.use_automatic_timestep = False
# boundary conditions
solver_obj.bnd_functions['shallow_water'] = {}
solver_obj.create_equations()
solver_obj.assign_initial_conditions(elev=elev_init)
# first two detector locations are outside domain
xy = [[-2*lx, ly/2.], [-lx/2, ly/2.], [lx/4., ly/2.], [3*lx/4., ly/2.]]
# but second one can be moved with dist<lx
xy = select_and_move_detectors(mesh2d, xy, maximum_distance=lx)
# thus we should end up with only the first one removed
assert len(xy)==3
np.testing.assert_almost_equal(xy[0][0], lx/nx/3.)
# first set of detectors
cb1 = DetectorsCallback(solver_obj, xy, ['elev_2d', 'uv_2d'], name='set1', append_to_log=True)
# same set in reverse order, now with named detectors and only elevations
cb2 = DetectorsCallback(solver_obj, xy[::-1], ['elev_2d',], name='set2',
detector_names=['two', 'one', 'zero'], append_to_log=True)
solver_obj.add_callback(cb1)
solver_obj.add_callback(cb2)
solver_obj.iterate()
uv, eta = solver_obj.fields.solution_2d.split()
area = lx*ly
rel_err = errornorm(elev_init, eta)/math.sqrt(area)
print_output(rel_err)
assert(rel_err < max_rel_err)
print_output("PASSED")
with h5py.File(str(tmpdir) + '/diagnostic_set1.hdf5', 'r') as df:
assert all(df.attrs['field_dims'][:]==[1,2])
trange = np.arange(n+1)*dt
np.testing.assert_almost_equal(df['time'][:,0], trange)
x = lx/4. # location of detector1
np.testing.assert_allclose(df['detector1'][:][:,0], np.cos(pi*x/lx)*np.cos(2*pi*trange/period), atol=5e-2, rtol=0.5)
with h5py.File(str(tmpdir) + '/diagnostic_set2.hdf5', 'r') as df:
assert all(df.attrs['field_dims'][:]==[1,])
x = lx/4. # location of detector1
np.testing.assert_allclose(df['one'][:][:,0], np.cos(pi*x/lx)*np.cos(2*pi*trange/period), atol=5e-2, rtol=0.5)
if __name__ == '__main__':
test_standing_wave_channel(do_export=True)
| 43.839286 | 124 | 0.698778 |
6a6fe2e1db2848d378ee72e0101bcd9f884e95c5 | 10,394 | py | Python | mnelab/utils/io.py | stralu/mnelab | 3165fa40e137cf4369b11bdcb47ca70afaf0c2fd | [
"BSD-3-Clause"
] | 1 | 2020-02-16T16:39:00.000Z | 2020-02-16T16:39:00.000Z | mnelab/utils/io.py | stralu/mnelab | 3165fa40e137cf4369b11bdcb47ca70afaf0c2fd | [
"BSD-3-Clause"
] | null | null | null | mnelab/utils/io.py | stralu/mnelab | 3165fa40e137cf4369b11bdcb47ca70afaf0c2fd | [
"BSD-3-Clause"
] | null | null | null | # Authors: Clemens Brunner <clemens.brunner@gmail.com>
#
# License: BSD (3-clause)
from pathlib import Path
import gzip
import struct
import xml.etree.ElementTree as ETree
from collections import defaultdict
import numpy as np
import mne
from ..utils import have
IMPORT_FORMATS = {"BioSemi Data Format": ".bdf",
"European Data Format": ".edf",
"General Data Format": ".gdf",
"Elekta Neuromag": [".fif", ".fif.gz"],
"BrainVision": ".vhdr",
"EEGLAB": ".set",
"Neuroscan": ".cnt",
"EGI Netstation": ".mff",
"Nexstim eXimia": ".nxe"}
if have["pyxdf"]:
IMPORT_FORMATS["Extensible Data Format"] = [".xdf", ".xdfz", ".xdf.gz"]
EXPORT_FORMATS = {"Elekta Neuromag": ".fif",
"Elekta Neuromag compressed": ".fif.gz",
"EEGLAB": ".set"}
if have["pyedflib"]:
EXPORT_FORMATS["European Data Format"] = ".edf"
EXPORT_FORMATS["BioSemi Data Format"] = ".bdf"
if have["pybv"]:
EXPORT_FORMATS["BrainVision"] = ".eeg"
def image_path(fname):
"""Return absolute path to image fname."""
root = Path(__file__).parent.parent
return str((root / "images" / Path(fname)).resolve())
def split_fname(fname, ffilter):
"""Split file name into name and known extension parts.
Parameters
----------
fname : str or pathlib.Path
File name (can include full path).
ffilter : dict
Known file types. The keys contain descriptions (names), whereas the
values contain the corresponding file extension(s).
Returns
-------
name : str
File name without extension.
ext : str
File extension (including the leading dot).
ftype : str
File type (empty string if unknown).
"""
path = Path(fname)
if not path.suffixes:
return path.stem, "", ""
ftype = _match_suffix(path.suffixes[-1], ffilter)
if ftype is not None:
return path.stem, path.suffixes[-1], ftype
ftype = _match_suffix("".join(path.suffixes[-2:]), ffilter)
if ftype is not None:
name = ".".join(path.stem.split(".")[:-1])
return name, "".join(path.suffixes[-2:]), ftype
return path.stem, path.suffix, ""
def _match_suffix(suffix, ffilter):
"""Return file type (textual description) for a given suffix.
Parameters
----------
suffix : str
File extension to check (must include the leading dot).
ffilter : dict
ffilter : dict
Known file types. The keys contain descriptions (names), whereas the
values contain the corresponding file extension(s).
Returns
-------
ftype : str | None
File type (None if unknown file type).
"""
for ftype, ext in ffilter.items():
if suffix in ext:
return ftype
def read_raw_xdf(fname, stream_id):
"""Read XDF file.
Parameters
----------
fname : str
Name of the XDF file.
stream_id : int
ID (number) of the stream to load.
Returns
-------
raw : mne.io.Raw
XDF file data.
"""
from pyxdf import load_xdf
streams, header = load_xdf(fname)
for stream in streams:
if stream["info"]["stream_id"] == stream_id:
break # stream found
n_chans = int(stream["info"]["channel_count"][0])
fs = float(stream["info"]["nominal_srate"][0])
labels, types, units = [], [], []
try:
for ch in stream["info"]["desc"][0]["channels"][0]["channel"]:
labels.append(str(ch["label"][0]))
if ch["type"]:
types.append(ch["type"][0])
if ch["unit"]:
units.append(ch["unit"][0])
except (TypeError, IndexError): # no channel labels found
pass
if not labels:
labels = [str(n) for n in range(n_chans)]
if not units:
units = ["NA" for _ in range(n_chans)]
info = mne.create_info(ch_names=labels, sfreq=fs, ch_types="eeg")
# convert from microvolts to volts if necessary
scale = np.array([1e-6 if u == "microvolts" else 1 for u in units])
raw = mne.io.RawArray((stream["time_series"] * scale).T, info)
first_samp = stream["time_stamps"][0]
markers = match_streaminfos(resolve_streams(fname), [{"type": "Markers"}])
for stream_id in markers:
for stream in streams:
if stream["info"]["stream_id"] == stream_id:
break
onsets = stream["time_stamps"] - first_samp
descriptions = [item for sub in stream["time_series"] for item in sub]
raw.annotations.append(onsets, [0] * len(onsets), descriptions)
return raw
def match_streaminfos(stream_infos, parameters):
"""Find stream IDs matching specified criteria.
Parameters
----------
stream_infos : list of dicts
List of dicts containing information on each stream. This information
can be obtained using the function resolve_streams.
parameters : list of dicts
List of dicts containing key/values that should be present in streams.
Examples: [{"name": "Keyboard"}] matches all streams with a "name"
field equal to "Keyboard".
[{"name": "Keyboard"}, {"type": "EEG"}] matches all streams
with a "name" field equal to "Keyboard" and all streams with
a "type" field equal to "EEG".
"""
matches = []
for request in parameters:
for info in stream_infos:
for key in request.keys():
match = info[key] == request[key]
if not match:
break
if match:
matches.append(info['stream_id'])
return list(set(matches)) # return unique values
def resolve_streams(fname):
"""Resolve streams in given XDF file.
Parameters
----------
fname : str
Name of the XDF file.
Returns
-------
stream_infos : list of dicts
List of dicts containing information on each stream.
"""
return parse_chunks(parse_xdf(fname))
def parse_xdf(fname):
"""Parse and return chunks contained in an XDF file.
Parameters
----------
fname : str
Name of the XDF file.
Returns
-------
chunks : list
List of all chunks contained in the XDF file.
"""
chunks = []
with _open_xdf(fname) as f:
for chunk in _read_chunks(f):
chunks.append(chunk)
return chunks
def parse_chunks(chunks):
"""Parse chunks and extract information on individual streams."""
streams = []
for chunk in chunks:
if chunk["tag"] == 2: # stream header chunk
streams.append(dict(stream_id=chunk["stream_id"],
name=chunk.get("name"), # optional
type=chunk.get("type"), # optional
source_id=chunk.get("source_id"), # optional
created_at=chunk.get("created_at"), # optional
uid=chunk.get("uid"), # optional
session_id=chunk.get("session_id"), # optional
hostname=chunk.get("hostname"), # optional
channel_count=int(chunk["channel_count"]),
channel_format=chunk["channel_format"],
nominal_srate=float(chunk["nominal_srate"])))
return streams
def _read_chunks(f):
"""Read and yield XDF chunks.
Parameters
----------
f : file handle
File handle of XDF file.
Yields
------
chunk : dict
XDF chunk.
"""
while True:
chunk = dict()
try:
chunk["nbytes"] = _read_varlen_int(f)
except EOFError:
return
chunk["tag"] = struct.unpack('<H', f.read(2))[0]
if chunk["tag"] in [2, 3, 4, 6]:
chunk["stream_id"] = struct.unpack("<I", f.read(4))[0]
if chunk["tag"] == 2: # parse StreamHeader chunk
xml = ETree.fromstring(f.read(chunk["nbytes"] - 6).decode())
chunk = {**chunk, **_parse_streamheader(xml)}
else: # skip remaining chunk contents
f.seek(chunk["nbytes"] - 6, 1)
else:
f.seek(chunk["nbytes"] - 2, 1) # skip remaining chunk contents
yield chunk
def _parse_streamheader(xml):
"""Parse stream header XML."""
return {el.tag: el.text for el in xml if el.tag != "desc"}
def _read_varlen_int(f):
"""Read a variable-length integer."""
nbytes = f.read(1)
if nbytes == b"\x01":
return ord(f.read(1))
elif nbytes == b"\x04":
return struct.unpack("<I", f.read(4))[0]
elif nbytes == b"\x08":
return struct.unpack("<Q", f.read(8))[0]
elif not nbytes: # EOF
raise EOFError
else:
raise RuntimeError("Invalid variable-length integer")
def _open_xdf(filename):
"""Open XDF file for reading."""
filename = Path(filename) # convert to pathlib object
if filename.suffix == ".xdfz" or filename.suffixes == [".xdf", ".gz"]:
f = gzip.open(filename, "rb")
else:
f = open(filename, "rb")
if f.read(4) != b"XDF:": # magic bytes
raise IOError(f"Invalid XDF file {filename}")
return f
def get_xml(fname):
"""Get XML stream headers and footers from all streams.
Parameters
----------
fname : str
Name of the XDF file.
Returns
-------
xml : dict
XML stream headers and footers.
"""
with _open_xdf(fname) as f:
xml = defaultdict(dict)
while True:
try:
nbytes = _read_varlen_int(f)
except EOFError:
return xml
tag = struct.unpack('<H', f.read(2))[0]
if tag in [2, 3, 4, 6]:
stream_id = struct.unpack("<I", f.read(4))[0]
if tag in [2, 6]: # parse StreamHeader/StreamFooter chunk
string = f.read(nbytes - 6).decode()
xml[stream_id][tag] = ETree.fromstring(string)
else: # skip remaining chunk contents
f.seek(nbytes - 6, 1)
else:
f.seek(nbytes - 2, 1) # skip remaining chunk contents
| 30.934524 | 79 | 0.556956 |
8db6656e9ae0cb0333ff8f5e9e1d7b6a427a8b6f | 8,046 | py | Python | pyflux/arma/tests/test_arima_skewt.py | ThomasHoppe/pyflux | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | [
"BSD-3-Clause"
] | 2,091 | 2016-04-01T02:52:10.000Z | 2022-03-29T11:38:15.000Z | pyflux/arma/tests/test_arima_skewt.py | EricSchles/pyflux | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | [
"BSD-3-Clause"
] | 160 | 2016-04-26T14:52:18.000Z | 2022-03-15T02:09:07.000Z | pyflux/arma/tests/test_arima_skewt.py | EricSchles/pyflux | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | [
"BSD-3-Clause"
] | 264 | 2016-05-02T14:03:31.000Z | 2022-03-29T07:48:20.000Z | import numpy as np
from pyflux.arma import ARIMA
from pyflux.families import Skewt
noise = np.random.normal(0,1,300)
data = np.zeros(300)
for i in range(1,len(data)):
data[i] = 0.9*data[i-1] + noise[i]
def test_no_terms():
"""
Tests an ARIMA model with no AR or MA terms, and that
the latent variable list length is correct, and that the estimated
latent variables are not nan
"""
model = ARIMA(data=data, ar=0, ma=0, family=Skewt())
x = model.fit()
assert(len(model.latent_variables.z_list) == 4)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_couple_terms():
"""
Tests an ARIMA model with 1 AR and 1 MA term and that
the latent variable list length is correct, and that the estimated
latent variables are not nan
"""
model = ARIMA(data=data, ar=1, ma=1, family=Skewt())
x = model.fit()
assert(len(model.latent_variables.z_list) == 6)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_couple_terms_integ():
"""
Tests an ARIMA model with 1 AR and 1 MA term, integrated once, and that
the latent variable list length is correct, and that the estimated
latent variables are not nan
"""
model = ARIMA(data=data, ar=1, ma=1, integ=1, family=Skewt())
x = model.fit()
assert(len(model.latent_variables.z_list) == 6)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_predict_length():
"""
Tests that the prediction dataframe length is equal to the number of steps h
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
assert(model.predict(h=5).shape[0] == 5)
def test_predict_is_length():
"""
Tests that the prediction IS dataframe length is equal to the number of steps h
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
assert(model.predict_is(h=5).shape[0] == 5)
def test_predict_nans():
"""
Tests that the predictions are not nans
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
assert(len(model.predict(h=5).values[np.isnan(model.predict(h=5).values)]) == 0)
def test_predict_is_nans():
"""
Tests that the in-sample predictions are not nans
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
assert(len(model.predict_is(h=5).values[np.isnan(model.predict_is(h=5).values)]) == 0)
def test_predict_nonconstant():
"""
We should not really have predictions that are constant (should be some difference)...
This captures bugs with the predict function not iterating forward
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
predictions = model.predict(h=10, intervals=False)
assert(not np.all(predictions.values==predictions.values[0]))
def test_predict_is_nonconstant():
"""
We should not really have predictions that are constant (should be some difference)...
This captures bugs with the predict function not iterating forward
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
predictions = model.predict_is(h=10, intervals=False)
assert(not np.all(predictions.values==predictions.values[0]))
# Uncomment once RV speedup in place
"""
def test_predict_intervals():
Tests prediction intervals are ordered correctly
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values > predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values > predictions[model.data_name].values))
assert(np.all(predictions[model.data_name].values > predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values > predictions['1% Prediction Interval'].values))
def test_predict_is_intervals():
Tests prediction intervals are ordered correctly
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit()
predictions = model.predict_is(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values > predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values > predictions[model.data_name].values))
assert(np.all(predictions[model.data_name].values > predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values > predictions['1% Prediction Interval'].values))
def test_predict_intervals_bbvi():
Tests prediction intervals are ordered correctly
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit('BBVI', iterations=100, quiet_progress=True)
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values > predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values > predictions[model.data_name].values))
assert(np.all(predictions[model.data_name].values > predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values > predictions['1% Prediction Interval'].values))
def test_predict_is_intervals_bbvi():
Tests prediction intervals are ordered correctly
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit('BBVI', iterations=100, quiet_progress=True)
predictions = model.predict_is(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values > predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values > predictions[model.data_name].values))
assert(np.all(predictions[model.data_name].values > predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values > predictions['1% Prediction Interval'].values))
def test_predict_intervals_mh():
Tests prediction intervals are ordered correctly
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit('M-H', nsims=400)
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values > predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values > predictions[model.data_name].values))
assert(np.all(predictions[model.data_name].values > predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values > predictions['1% Prediction Interval'].values))
def test_predict_is_intervals_mh():
Tests prediction intervals are ordered correctly
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit('M-H', nsims=400)
predictions = model.predict_is(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values > predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values > predictions[model.data_name].values))
assert(np.all(predictions[model.data_name].values > predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values > predictions['1% Prediction Interval'].values))
"""
def test_sample_model():
"""
Tests sampling function
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit('BBVI', iterations=100, quiet_progress=True)
sample = model.sample(nsims=40)
assert(sample.shape[0]==40)
assert(sample.shape[1]==len(data)-2)
def test_ppc():
"""
Tests PPC value
"""
model = ARIMA(data=data, ar=2, ma=2, family=Skewt())
x = model.fit('BBVI', iterations=100, quiet_progress=True)
p_value = model.ppc(nsims=40)
assert(0.0 <= p_value <= 1.0)
| 43.491892 | 113 | 0.697241 |
1a0c3de4b35e98f9e342719bd87e6a0fd0c1af19 | 23,488 | py | Python | py3/nn/experiments/recurrent_gan/rnn_gan_lm.py | fr42k/gap-wgan-gp | 4e373c43d606a1b83f76893d93f9cf8be8cd460d | [
"MIT"
] | null | null | null | py3/nn/experiments/recurrent_gan/rnn_gan_lm.py | fr42k/gap-wgan-gp | 4e373c43d606a1b83f76893d93f9cf8be8cd460d | [
"MIT"
] | null | null | null | py3/nn/experiments/recurrent_gan/rnn_gan_lm.py | fr42k/gap-wgan-gp | 4e373c43d606a1b83f76893d93f9cf8be8cd460d | [
"MIT"
] | null | null | null | """Generative Adversarial Network for MNIST."""
# Ideas:
# Penalize information retention by the discriminator (to prevent time-wise sparse gradients); i.e. encourage forget-gate activation
# EBGAN
import os, sys
sys.path.append(os.getcwd())
try: # This only matters on Ishaan's computer
import experiment_tools
experiment_tools.wait_for_gpu(tf=True)
except ImportError:
pass
import tflib as lib
import tflib.debug
import tflib.ops.linear
# import tflib.ops.rnn
# import tflib.ops.gru
import tflib.ops.conv1d
import tflib.ops.batchnorm
import tflib.plot
import data_tools
import tflib.save_images
import numpy as np
import tensorflow as tf
import scipy.misc
from scipy.misc import imsave
import time
import functools
BATCH_SIZE = 64
ITERS = 200000
SEQ_LEN = 32
lib.print_model_settings(locals().copy())
ALL_SETTINGS = {
'minibatch_discrim': [True, False], # False works best
'generator_output_mode': ['softmax', 'st_argmax', 'softmax_st_argmax', 'st_sampler', 'gumbel_sampler'], # gumbel_sampler works best, followde by softmax_st_argmax
'ngram_discrim': [None, 1, 2, 4], # can't tell the difference between [1], [2], [2,4]. None is bad.
'dim': [128, 256, 512],
'noise': ['normal', 'uniform'], # can't tell the difference. normal might have a slight edge?
'input_noise_std': 0.0, # seems to hurt; 0.1 might help; TODO try annealing down over time
'ngram_input_noise_std': 0.0, # also seems to hurt; TODO try annealing down over time
'one_sided_label_smoothing': False # seems to hurt
}
# SETTINGS = experiment_tools.pick_settings(ALL_SETTINGS)
SETTINGS = {
'minibatch_discrim': False,
'generator_output_mode': 'softmax',
'ngram_discrim': None,
'dim': 512,
'dim_g': 512,
'noise': 'normal',
'input_noise_std': 0.,
'ngram_input_noise_std': 0.0,
'one_sided_label_smoothing': False,
'disc_lm': False,
'extra_disc_steps': 4,
'rnn_discrim': True,
'simultaneous_update': False,
'feature_matching': False, # seems to work surprisingly well, but theoretically I don't like it?
'word_dropout': 0.,
'2layer_generator': False,
'wgan': True,
'gen_lm': False # doesn't help
}
MOMENTUM_G = 0.5
MOMENTUM_D = 0.
DEPTH = 5
MULTIPLICATIVE_D = False
MULTIPLICATIVE_G = False
GEN_BS_MULTIPLE = 8
LR = 2e-4
DECAY = True
lib.print_model_settings(locals().copy())
lib.print_model_settings_dict(SETTINGS)
get_epoch, charmap, inv_charmap = data_tools.load_dataset_big(BATCH_SIZE, SEQ_LEN)
# lib.ops.linear.enable_default_weightnorm()
def LeakyReLU(x, alpha=.20):
return tf.maximum(alpha*x, x)
def ReLULayer(name, n_in, n_out, inputs, alpha=0.):
output = lib.ops.linear.Linear(name+'.Linear', n_in, n_out, inputs)
return LeakyReLU(output, alpha=alpha)
def MinibatchLayer(name, n_in, dim_b, dim_c, inputs):
"""Salimans et al. 2016"""
# input: batch_size, n_in
# M: batch_size, dim_b, dim_c
m = lib.ops.linear.Linear(name+'.M', n_in, dim_b*dim_c, inputs)
m = tf.reshape(m, [-1, dim_b, dim_c])
# c: batch_size, batch_size, dim_b
c = tf.abs(tf.expand_dims(m, 0) - tf.expand_dims(m, 1))
c = tf.reduce_sum(c, reduction_indices=[3])
c = tf.exp(-c)
# o: batch_size, dim_b
o = tf.reduce_mean(c, reduction_indices=[1])
o -= 1 # to account for the zero L1 distance of each example with itself
# result: batch_size, n_in+dim_b
return tf.concat(1, [o, inputs])
def softmax(logits):
softmax = tf.reshape(tf.nn.softmax(tf.reshape(logits, [-1, len(charmap)])), tf.shape(logits))
return softmax
def st_argmax(logits):
"""straight-through argmax"""
argmax = tf.argmax(logits, logits.get_shape().ndims-1)
onehot = tf.one_hot(argmax, len(charmap))
residual = onehot - logits
onehot = logits + tf.stop_gradient(residual)
return onehot
def softmax_st_argmax(logits):
"""softmax -> straight-through argmax"""
return st_argmax(softmax(logits))
def st_sampler(logits):
"""straight-through stochastic sampler"""
flat_samples = tf.reshape(tf.multinomial(tf.reshape(logits, [-1, len(charmap)]), 1), [-1])
onehot = tf.reshape(tf.one_hot(flat_samples, len(charmap)), tf.shape(logits))
residual = onehot - logits
onehot = logits + tf.stop_gradient(residual)
return onehot
def gumbel_sampler(logits):
"""gumbel-softmax -> straight-through argmax"""
gumbel_noise = -tf.log(-tf.log(tf.random_uniform(tf.shape(logits))))
logits += gumbel_noise
logits /= 0.1 # gumbel temp
gumbel_softmax = tf.reshape(tf.nn.softmax(tf.reshape(logits, [-1, len(charmap)])), tf.shape(logits))
return st_argmax(gumbel_softmax)
def make_noise(shape):
if SETTINGS['noise'] == 'uniform':
return tf.random_uniform(shape=shape, minval=-np.sqrt(3), maxval=np.sqrt(3))
elif SETTINGS['noise'] == 'normal':
return tf.random_normal(shape)
else:
raise Exception()
def SubpixelConv1D(*args, **kwargs):
kwargs['output_dim'] = 2*kwargs['output_dim']
output = lib.ops.conv1d.Conv1D(*args, **kwargs)
output = tf.transpose(output, [0,2,1])
output = tf.reshape(output, [output.get_shape()[0], -1, kwargs['output_dim']])
output = tf.transpose(output, [0,2,1])
return output
def Generator(n_samples, prev_outputs=None):
output = make_noise(
shape=[n_samples, 128]
)
output = lib.ops.linear.Linear('Generator.Input', 128, SEQ_LEN*SETTINGS['dim_g'], output)
output = tf.reshape(output, [-1, SETTINGS['dim_g'], SEQ_LEN])
for i in xrange(DEPTH):
output = ResBlockG('Generator.Res{}'.format(i), output)
output = lib.ops.conv1d.Conv1D('Generator.Output', SETTINGS['dim_g'], len(charmap), 1, output)
output = tf.transpose(output, [0, 2, 1])
output = softmax(output)
return output, None
# def Generator(n_samples, prev_outputs=None):
# noise = make_noise(
# shape=[n_samples, SEQ_LEN, 8]
# )
# h0_noise = make_noise(
# shape=[n_samples, SETTINGS['dim_g']]
# )
# h0_noise_2 = make_noise(
# shape=[n_samples, SETTINGS['dim_g']]
# )
# rnn_outputs = []
# rnn_logits = []
# last_state = h0_noise
# last_state_2 = h0_noise_2
# for i in xrange(SEQ_LEN):
# if len(rnn_outputs) > 0:
# if prev_outputs is not None:
# inputs = tf.concat(1, [noise[:,i], prev_outputs[:,i-1]])
# else:
# inputs = tf.concat(1, [noise[:,i], rnn_outputs[-1]])
# else:
# inputs = tf.concat(1, [noise[:,i], tf.zeros([n_samples, len(charmap)])])
# # print "WARNING FORCING INDEPENDENT OUTPUTS"
# # inputs *= 0.
# last_state = lib.ops.gru.GRUStep('Generator.1', 8+len(charmap), SETTINGS['dim_g'], inputs, last_state)
# last_state_2 = lib.ops.gru.GRUStep('Generator.2', SETTINGS['dim_g'], SETTINGS['dim_g'], last_state, last_state_2)
# if SETTINGS['2layer_generator']:
# output = lib.ops.linear.Linear('Generator.Out', SETTINGS['dim_g'], len(charmap), last_state_2)
# else:
# output = lib.ops.linear.Linear('Generator.Out', SETTINGS['dim_g'], len(charmap), last_state)
# rnn_logits.append(output)
# if SETTINGS['generator_output_mode']=='softmax':
# output = softmax(output)
# elif SETTINGS['generator_output_mode']=='st_argmax':
# output = st_argmax(output)
# elif SETTINGS['generator_output_mode']=='softmax_st_argmax':
# output = softmax_st_argmax(output)
# elif SETTINGS['generator_output_mode']=='st_sampler':
# output = st_sampler(output)
# elif SETTINGS['generator_output_mode']=='gumbel_sampler':
# output = gumbel_sampler(output)
# else:
# raise Exception()
# rnn_outputs.append(output)
# return tf.transpose(tf.pack(rnn_outputs), [1,0,2]), tf.transpose(tf.pack(rnn_logits), [1,0,2])
# def NgramDiscrim(n, inputs):
# inputs += SETTINGS['ngram_input_noise_std']*tf.random_normal(tf.shape(inputs))
# output = tf.reshape(inputs, [-1, n*len(charmap)])
# output = ReLULayer('Discriminator.CharDiscrim_{}.FC'.format(n), n*len(charmap), SETTINGS['dim'], output)
# # output = MinibatchLayer('Discriminator.CharDiscrim.Minibatch', SETTINGS['dim'], 32, 16, output)
# # output = ReLULayer('Discriminator.CharDiscrim.FC2', SETTINGS['dim']+32, SETTINGS['dim'], output)
# output = lib.ops.linear.Linear('Discriminator.CharDiscrim_{}.Output'.format(n), SETTINGS['dim'], 1, output)
# return output
def NgramDiscrim(n, inputs):
inputs += SETTINGS['ngram_input_noise_std']*tf.random_normal(tf.shape(inputs))
output = tf.reshape(inputs, [-1, n, len(charmap)])
output = lib.ops.gru.GRU('Discriminator.GRU', len(charmap), SETTINGS['dim'], output)
features = output
output = output[:, -1, :] # last hidden state
output = lib.ops.linear.Linear('Discriminator.Output', SETTINGS['dim'], 1, output)
return output, features
def GatedResBlock(name, inputs):
output = inputs
dim = SETTINGS['dim']
output = LeakyReLU(output)
output_a = lib.ops.conv1d.Conv1D(name+'.A', dim, dim, 5, output)
output_b = lib.ops.conv1d.Conv1D(name+'.B', dim, dim, 5, output)
output = tf.nn.sigmoid(output_a) * tf.tanh(output_b)
output = lib.ops.conv1d.Conv1D(name+'.2', dim, dim, 5, output)
return inputs + output
def ResBlock(name, inputs, filter_size=5):
output = inputs
dim = SETTINGS['dim']
if MULTIPLICATIVE_D:
output = tf.nn.relu(output)
output = lib.ops.conv1d.Conv1D(name+'.1', dim, dim, filter_size, output)
output = tf.tanh(output[:,::2]) * tf.nn.sigmoid(output[:,1::2])
output = lib.ops.conv1d.Conv1D(name+'.2', dim/2, dim, filter_size, output)
else:
output = tf.nn.relu(output)
output = lib.ops.conv1d.Conv1D(name+'.1', dim, dim, filter_size, output)
output = tf.nn.relu(output)
output = lib.ops.conv1d.Conv1D(name+'.2', dim, dim, filter_size, output)
# output = lib.ops.batchnorm.Batchnorm(name+'.BN', [0,2], output)
return inputs + (0.3*output)
def Normalize(name, inputs):
if MODE == 'wgan-gp':
if ('Discriminator' in name) and NORMALIZATION_D:
return lib.ops.layernorm.Layernorm(name,[1,2,3],inputs)
elif ('Generator' in name) and NORMALIZATION_G:
return lib.ops.batchnorm.Batchnorm(name,[0,2,3],inputs,fused=True)
else:
return inputs
else:
return lib.ops.batchnorm.Batchnorm(name,[0,2,3],inputs,fused=True)
def ResBlockG(name, inputs):
output = inputs
dim = SETTINGS['dim_g']
if MULTIPLICATIVE_G:
output = tf.nn.relu(output)
output = lib.ops.conv1d.Conv1D(name+'.1', dim, dim, 5, output)
output = tf.tanh(output[:,::2]) * tf.nn.sigmoid(output[:,1::2])
output = lib.ops.conv1d.Conv1D(name+'.2', dim/2, dim, 5, output)
else:
output = tf.nn.relu(output)
output = lib.ops.conv1d.Conv1D(name+'.1', dim, dim, 5, output)
output = tf.nn.relu(output)
output = lib.ops.conv1d.Conv1D(name+'.2', dim, dim, 5, output)
return inputs + (0.3*output)
def ResBlockUpsample(name, dim_in, dim_out, inputs):
output = inputs
output = tf.nn.relu(output)
output_a = SubpixelConv1D(name+'.1', input_dim=dim_in, output_dim=dim_out, filter_size=3, inputs=output)
output = tf.nn.relu(output_a)
output = lib.ops.conv1d.Conv1D(name+'.2', dim_out, dim_out, 3, output)
# output = lib.ops.batchnorm.Batchnorm(name+'.BN', [0,2], output)
return output + SubpixelConv1D(name+'.skip', input_dim=dim_in, output_dim=dim_out, filter_size=1, inputs=inputs)
def ResBlockDownsample(name, dim_in, dim_out, inputs):
output = inputs
output = tf.nn.relu(output)
output_a = lib.ops.conv1d.Conv1D(name+'.1', dim_in, dim_out, 3, output)
output = tf.nn.relu(output_a)
output = lib.ops.conv1d.Conv1D(name+'.2', dim_out, dim_out, 3, output, stride=2)
# output = lib.ops.batchnorm.Batchnorm(name+'.BN', [0,2], output)
return output + lib.ops.conv1d.Conv1D(name+'.skip', dim_in, dim_out, 1, inputs, stride=2)
def Discriminator(inputs):
inputs += SETTINGS['input_noise_std']*tf.random_normal(tf.shape(inputs))
output = tf.transpose(inputs, [0,2,1])
output = lib.ops.conv1d.Conv1D('Discriminator.1', len(charmap), SETTINGS['dim'], 1, output)
for i in xrange(DEPTH):
output = ResBlock('Discriminator.Res{}'.format(i), output)
# output = tf.reduce_mean(output, reduction_indices=[2])
output = tf.reshape(output, [-1, SEQ_LEN*SETTINGS['dim']])
# output = MinibatchLayer('Discriminator.Minibatch', SETTINGS['dim'], 32, 16, output)
# output = ReLULayer('Discriminator.FC', SETTINGS['dim']+32, SETTINGS['dim'], output)
output = lib.ops.linear.Linear('Discriminator.Output', SEQ_LEN*SETTINGS['dim'], 1, output)
return output, None, None
# def Discriminator(inputs):
# inputs += SETTINGS['input_noise_std']*tf.random_normal(tf.shape(inputs))
# if SETTINGS['word_dropout'] > 0.001:
# inputs = tf.nn.dropout(inputs, keep_prob=SETTINGS['word_dropout'], noise_shape=[BATCH_SIZE, SEQ_LEN, 1])
# output = inputs
# output = lib.ops.gru.GRU('Discriminator.GRU', len(charmap), SETTINGS['dim'], output)
# features = [output]
# # Auxiliary language model
# language_model_output = lib.ops.linear.Linear('Discriminator.LMOutput', SETTINGS['dim'], len(charmap), output[:, :-1, :])
# # output = tf.reduce_mean(output, reduction_indices=[1]) # global-average-pool
# output = output[:, SEQ_LEN-1, :] # last hidden state
# # # Auxiliary autoencoder
# # autoencoder_hiddens = []
# # last_state = output
# # for i in xrange(SEQ_LEN):
# # inputs = tf.zeros([n_samples, 1])
# # last_state = lib.ops.gru.GRUStep('Discriminator.Autoencoder', 1, SETTINGS['dim'], inputs, last_state)
# # autoencoder_hiddens.append(last_state)
# # autoencoder_hiddens = tf.pack(autoencoder_hiddens)
# if SETTINGS['minibatch_discrim']:
# output = MinibatchLayer('Discriminator.Minibatch', SETTINGS['dim'], 32, 16, output)
# output = ReLULayer('Discriminator.FC', SETTINGS['dim']+32, SETTINGS['dim'], output)
# output = lib.ops.linear.Linear('Discriminator.Output1', SETTINGS['dim'], SETTINGS['dim'], output)
# output = LeakyReLU(output)
# output = lib.ops.linear.Linear('Discriminator.Output', SETTINGS['dim'], 1, output)
# outputs = []
# if SETTINGS['ngram_discrim'] is not None:
# for i in SETTINGS['ngram_discrim']:
# ngram_output, ngram_features = NgramDiscrim(i, inputs)
# outputs.append(ngram_output)
# features.append(ngram_features)
# if SETTINGS['rnn_discrim']:
# outputs.append(output)
# return tf.concat(0, outputs), language_model_output, features # we apply the sigmoid later
_iteration = tf.placeholder(tf.int32, shape=None)
real_inputs_discrete = tf.placeholder(tf.int32, shape=[BATCH_SIZE, SEQ_LEN])
real_inputs = tf.one_hot(real_inputs_discrete, len(charmap))
fake_inputs, _ = Generator(BATCH_SIZE)
fake_inputs_discrete = tf.argmax(fake_inputs, fake_inputs.get_shape().ndims-1)
disc_real, disc_real_lm, disc_real_features = Discriminator(real_inputs)
disc_fake, disc_fake_lm, disc_fake_features = Discriminator(fake_inputs)
# disc_out = Discriminator(tf.concat([real_inputs, fake_inputs], 0))[0]
disc_out = Discriminator(lib.concat([real_inputs, fake_inputs], 0))[0]
disc_real = disc_out[:BATCH_SIZE]
disc_fake = disc_out[BATCH_SIZE:]
# Gen objective: push D(fake) to one
if SETTINGS['feature_matching']:
gen_costs = [tf.reduce_mean((tf.reduce_mean(real_features, reduction_indices=[0]) - tf.reduce_mean(fake_features, reduction_indices=[0]))**2) for real_features, fake_features in zip(disc_real_features, disc_fake_features)]
gen_cost = 0.
for gc in gen_costs:
gen_cost = gen_cost + gc
elif SETTINGS['wgan']:
gen_cost = -tf.reduce_mean(Discriminator(Generator(GEN_BS_MULTIPLE*BATCH_SIZE)[0])[0])
else:
if SETTINGS['one_sided_label_smoothing']:
raise Exception('check this implementation')
gen_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.ones_like(disc_fake)))
else:
# gen_cost = -tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.zeros_like(disc_fake)))
gen_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.ones_like(disc_fake)))
# Discrim objective: push D(fake) to zero, and push D(real) to onehot
if SETTINGS['wgan']:
disc_cost = tf.reduce_mean(disc_fake) - tf.reduce_mean(disc_real)
# WGAN lipschitz-penalty
# epsilon = 1
alpha = tf.random_uniform(
shape=[BATCH_SIZE,1,1],
minval=0.,
maxval=1.
)
differences = fake_inputs - real_inputs
interpolates = real_inputs + (alpha*differences)
gradients = tf.gradients(Discriminator(interpolates)[0], [interpolates])[0]
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1,2]))
# print slopes.get_shape()
# interpolates_1 = real_data + ((alpha-epsilon)*differences)
# interpolates_2 = real_data + ((alpha+epsilon)*differences)
# slopes = tf.abs((Discriminator(interpolates_2)-Discriminator(interpolates_1))/(2*epsilon))
# lipschitz_penalty = tf.reduce_mean(tf.maximum(10000000.,slopes))
# lipschitz_penalty = tf.reduce_mean(tf.maximum(0.,(slopes-1.)**1))
# lipschitz_penalty = tf.reduce_mean((slopes-10.))
lipschitz_penalty = tf.reduce_mean((slopes-1.)**2)
disc_cost += 10*lipschitz_penalty
lipschitz_penalty = tf.reduce_mean(slopes)
else:
disc_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.zeros_like(disc_fake)))
if SETTINGS['one_sided_label_smoothing']:
disc_cost += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_real, 0.9*tf.ones_like(disc_real)))
else:
disc_cost += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_real, tf.ones_like(disc_real)))
disc_cost /= 2.
lipschitz_penalty = tf.constant(0.) # to make the logging code work
if SETTINGS['disc_lm']:
disc_cost += tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(
tf.reshape(disc_real_lm, [-1, len(charmap)]),
tf.reshape(real_inputs_discrete[:, 1:], [-1])
)
)
# disc_cost += tf.reduce_mean(
# tf.nn.sparse_softmax_cross_entropy_with_logits(
# tf.reshape(disc_fake_lm, [-1, len(charmap)]),
# tf.reshape(fake_inputs_discrete[:, 1:], [-1])
# )
# )
if SETTINGS['gen_lm']:
gen_cost += tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(
tf.reshape(Generator(BATCH_SIZE, real_inputs[:, :-1])[1], [-1, len(charmap)]),
tf.reshape(real_inputs_discrete, [-1])
)
)
if SETTINGS['wgan']:
# gen_train_op = tf.train.RMSPropOptimizer(learning_rate=5e-4).minimize(gen_cost, var_list=lib.params_with_name('Generator'))
# disc_train_op = tf.train.RMSPropOptimizer(learning_rate=5e-4).minimize(disc_cost, var_list=lib.params_with_name('Discriminator'))
# disc_train_op_nopenalty = tf.train.RMSPropOptimizer(learning_rate=5e-4).minimize(wgan_disc_cost, var_list=lib.params_with_name('Discriminator'))
if DECAY:
decay = tf.maximum(0., 1.-(tf.cast(_iteration, tf.float32)/ITERS))
else:
decay = 1.
gen_train_op = tf.train.AdamOptimizer(learning_rate=LR*decay, beta1=MOMENTUM_G, beta2=0.9).minimize(gen_cost, var_list=lib.params_with_name('Generator'))
disc_train_op = tf.train.AdamOptimizer(learning_rate=LR*decay, beta1=MOMENTUM_D, beta2=0.9).minimize(disc_cost, var_list=lib.params_with_name('Discriminator'))
assigns = []
for var in lib.params_with_name('Discriminator'):
if ('.b' not in var.name) and ('Bias' not in var.name) and ('.BN' not in var.name):
print "Clipping {}".format(var.name)
clip_bounds = [-.01, .01]
assigns.append(tf.assign(var, tf.clip_by_value(var, clip_bounds[0], clip_bounds[1])))
if '.BN.scale' in var.name:
print "Clipping {}".format(var.name)
clip_bounds = [0, 1]
assigns.append(tf.assign(var, tf.clip_by_value(var, clip_bounds[0], clip_bounds[1])))
clip_disc_weights = tf.group(*assigns)
else:
gen_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(gen_cost, var_list=lib.params_with_name('Generator'))
disc_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(disc_cost, var_list=lib.params_with_name('Discriminator'))
def iterate_dataset():
while True:
for mb in get_epoch():
yield np.array([[charmap[c] for c in l] for l in mb], dtype='int32')
lines = []
for i, mb in enumerate(get_epoch()):
lines.extend(mb)
if i == 1000:
break
true_char_ngram_lms = [data_tools.NgramLanguageModel(i+1, lines[10*BATCH_SIZE:], tokenize=False) for i in xrange(4)]
validation_char_ngram_lms = [data_tools.NgramLanguageModel(i+1, lines[:10*BATCH_SIZE], tokenize=False) for i in xrange(4)]
for i in xrange(4):
print "validation JS for n={}: {}".format(i+1, true_char_ngram_lms[i].js_with(validation_char_ngram_lms[i]))
# generator_word_lm = data_tools.NgramLanguageModel(1, lines[:3*BATCH_SIZE], tokenize=True)
# print "word precision: {}".format(true_word_lm.precision_wrt(generator_word_lm))
# tf.add_check_numerics_ops()
with tf.Session() as session:
session.run(tf.initialize_all_variables())
def generate_samples():
samples = session.run(fake_inputs)
samples = np.argmax(samples, axis=2)
decoded_samples = []
for i in xrange(len(samples)):
decoded = []
for j in xrange(len(samples[i])):
decoded.append(inv_charmap[samples[i][j]])
decoded_samples.append(''.join(decoded))
return decoded_samples
def save_samples_and_get_jses(iteration):
samples = []
for i in xrange(10):
samples.extend(generate_samples())
with open('samples_{}.txt'.format(iteration), 'w') as f:
for s in samples:
s = "".join(s)
f.write(s + "\n")
jses = []
for i in xrange(4):
lm = data_tools.NgramLanguageModel(i+1, samples, tokenize=False)
jses.append(lm.js_with(true_char_ngram_lms[i]))
return jses
gen = iterate_dataset()
disc_iters = SETTINGS['extra_disc_steps']+1
for iteration in xrange(ITERS):
start_time = time.time()
for i in xrange(disc_iters):
_data = gen.next()
_disc_cost, _ = session.run([disc_cost, disc_train_op], feed_dict={real_inputs_discrete:_data,_iteration:iteration})
lib.plot.plot('cost', _disc_cost)
_data = gen.next()
_ = session.run(gen_train_op, feed_dict={real_inputs_discrete:_data,_iteration:iteration})
if iteration % 10 == 0:
lib.plot.plot('time', time.time() - start_time)
if iteration % 100 == 99:
jses = save_samples_and_get_jses(iteration)
for i, js in enumerate(jses):
lib.plot.plot('js{}'.format(i+1), js)
if iteration % 1000 == 999:
lib.plot.flush()
lib.plot.tick() | 40.150427 | 226 | 0.665702 |
981f3f9780c8c3b1ab82d5c65def948c329f92b5 | 4,035 | py | Python | netket/hilbert/spin.py | yannra/netket | 7adc7ba04ff8e912629952cf4fa0e3f27148c424 | [
"Apache-2.0"
] | null | null | null | netket/hilbert/spin.py | yannra/netket | 7adc7ba04ff8e912629952cf4fa0e3f27148c424 | [
"Apache-2.0"
] | 9 | 2022-01-14T10:25:14.000Z | 2022-03-30T10:19:59.000Z | netket/hilbert/spin.py | yannra/netket | 7adc7ba04ff8e912629952cf4fa0e3f27148c424 | [
"Apache-2.0"
] | null | null | null | from .custom_hilbert import CustomHilbert
from ._deprecations import graph_to_N_depwarn
from fractions import Fraction
import numpy as _np
from netket import random as _random
from netket.graph import AbstractGraph
from numba import jit
from typing import Optional, List
class Spin(CustomHilbert):
r"""Hilbert space obtained as tensor product of local spin states."""
def __init__(
self,
s: float,
N: int = 1,
total_sz: Optional[float] = None,
graph: Optional[AbstractGraph] = None,
):
r"""Hilbert space obtained as tensor product of local spin states.
Args:
s: Spin at each site. Must be integer or half-integer.
N: Number of sites (default=1)
total_sz: If given, constrains the total spin of system to a particular value.
Examples:
Simple spin hilbert space.
>>> from netket.hilbert import Spin
>>> g = Hypercube(length=10,n_dim=2,pbc=True)
>>> hi = Spin(s=0.5, N=4)
>>> print(hi.size)
4
"""
N = graph_to_N_depwarn(N=N, graph=graph)
local_size = round(2 * s + 1)
local_states = _np.empty(local_size)
assert int(2 * s + 1) == local_size
for i in range(local_size):
local_states[i] = -round(2 * s) + 2 * i
local_states = local_states.tolist()
self._check_total_sz(total_sz, N)
if total_sz is not None:
def constraints(x):
return self._sum_constraint(x, total_sz)
else:
constraints = None
self._total_sz = total_sz if total_sz is None else int(total_sz)
self._s = s
self._local_size = local_size
super().__init__(local_states, N, constraints)
def _random_state_with_constraint(self, out, rgen):
sites = list(range(self.size))
out.fill(-round(2 * self._s))
ss = self.size
for i in range(round(self._s * self.size) + self._total_sz):
s = rgen.randint(0, ss, size=())
out[sites[s]] += 2
if out[sites[s]] > round(2 * self._s - 1):
sites.pop(s)
ss -= 1
def random_state(self, size=None, *, out=None, rgen=None):
if isinstance(size, int):
size = (size,)
shape = (*size, self._size) if size is not None else (self._size,)
if out is None:
out = _np.empty(shape=shape)
if rgen is None:
rgen = _random
if self._total_sz is None:
out[:] = rgen.choice(self.local_states, size=shape)
else:
# TODO: this can most likely be done more efficiently
if size is not None:
out_r = out.reshape(-1, self._size)
for b in range(out_r.shape[0]):
self._random_state_with_constraint(out_r[b], rgen)
else:
self._random_state_with_constraint(out, rgen)
return out
@staticmethod
@jit(nopython=True)
def _sum_constraint(x, total_sz):
return _np.sum(x, axis=1) == round(2 * total_sz)
def _check_total_sz(self, total_sz, size):
if total_sz is None:
return
m = round(2 * total_sz)
if _np.abs(m) > size:
raise Exception(
"Cannot fix the total magnetization: 2|M| cannot " "exceed Nspins."
)
if (size + m) % 2 != 0:
raise Exception(
"Cannot fix the total magnetization: Nspins + " "totalSz must be even."
)
def __pow__(self, n):
if self._total_sz is None:
total_sz = None
else:
total_sz = total_sz * n
return Spin(self._s, self.size * n, total_sz=total_sz)
def __repr__(self):
total_sz = (
", total_sz={}".format(self._total_sz) if self._total_sz is not None else ""
)
return "Spin(s={}{}, N={})".format(Fraction(self._s), total_sz, self._size)
| 29.452555 | 89 | 0.563569 |
61f8f0415723fbacd0fbff36296572eb05862375 | 3,426 | py | Python | blasteroids/client/world.py | smallarmyofnerds/blasteroids | 082bc010ed6d2ec6098a8848edcbee433a5b6961 | [
"MIT"
] | null | null | null | blasteroids/client/world.py | smallarmyofnerds/blasteroids | 082bc010ed6d2ec6098a8848edcbee433a5b6961 | [
"MIT"
] | 7 | 2021-09-04T18:49:13.000Z | 2021-09-05T19:37:39.000Z | blasteroids/client/world.py | smallarmyofnerds/blasteroids | 082bc010ed6d2ec6098a8848edcbee433a5b6961 | [
"MIT"
] | null | null | null | from blasteroids.lib.constants import ANIMATION_OBJECT_ID, ASTEROID_OBJECT_ID, PICKUP_OBJECT_ID, PROJECTILE_OBJECT_ID, SHIP_OBJECT_ID, SOUND_OBJECT_ID
from .game_objects import AnimationObject, ProjectileObject, AsteroidObject, PickupObject, ShipObject, SoundEffectObject
from .hud import Hud
class World:
def __init__(self, sprite_library, sound_library):
self.sprite_library = sprite_library
self.sound_library = sound_library
self.my_ship = None
self.game_objects = []
self.game_objects_by_id = {}
self.hud = Hud(sprite_library)
def draw(self, screen):
for object in self.game_objects:
object.draw(screen, self.my_ship.position if self.my_ship is not None else None)
if self.my_ship:
self.my_ship.draw(screen, None)
self.hud.draw(screen)
def _destroy_objects(self, server_world):
objects_to_remove = []
for object in self.game_objects:
server_object = server_world.objects_by_id.get(object.object_id)
if server_object:
pass
else:
objects_to_remove.append(object)
for object in objects_to_remove:
self.game_objects.remove(object)
del self.game_objects_by_id[object.object_id]
def _create_new_objects(self, server_world):
for object in server_world.objects:
existing_object = self.game_objects_by_id.get(object.object_id)
if existing_object:
existing_object.update(object)
else:
if object.type_id == SHIP_OBJECT_ID:
new_object = ShipObject(object, self.sprite_library)
elif object.type_id == PROJECTILE_OBJECT_ID:
new_object = ProjectileObject(object, self.sprite_library)
elif object.type_id == ASTEROID_OBJECT_ID:
new_object = AsteroidObject(object, self.sprite_library)
elif object.type_id == PICKUP_OBJECT_ID:
new_object = PickupObject(object, self.sprite_library)
elif object.type_id == SOUND_OBJECT_ID:
new_object = SoundEffectObject(object, self.sound_library)
elif object.type_id == ANIMATION_OBJECT_ID:
new_object = AnimationObject(object, self.sprite_library)
else:
raise Exception(f'Unrecognized object type {object.type_id} from server')
self.game_objects.append(new_object)
self.game_objects_by_id[new_object.object_id] = new_object
def _sync_my_ship(self, server_world):
if self.my_ship:
if server_world.my_ship:
self.my_ship.update(server_world.my_ship)
else:
self.my_ship = None
else:
if server_world.my_ship:
self.my_ship = ShipObject(server_world.my_ship, self.sprite_library)
else:
pass
def _sync_hud(self, server_world):
if server_world.my_ship:
self.hud.update(server_world.my_ship.health, server_world.my_ship.shield, server_world.my_ship.active_weapon_id)
def update(self, server_world):
self._sync_hud(server_world)
self._destroy_objects(server_world)
self._create_new_objects(server_world)
self._sync_my_ship(server_world)
| 43.367089 | 150 | 0.644191 |
e88e63b6b129694c2fa8ce54b1560ae10dde5955 | 512 | py | Python | get_handler.py | Ginkooo/maillogger | def0a9184eb034b8afe3ca59aacac0f529aaebd0 | [
"MIT"
] | null | null | null | get_handler.py | Ginkooo/maillogger | def0a9184eb034b8afe3ca59aacac0f529aaebd0 | [
"MIT"
] | null | null | null | get_handler.py | Ginkooo/maillogger | def0a9184eb034b8afe3ca59aacac0f529aaebd0 | [
"MIT"
] | null | null | null | import os
def get_logs(logdir):
currdir = os.path.abspath(os.path.curdir)
os.chdir(logdir)
ret = ''
files = os.listdir()
for f_name in files:
try:
year, month, day = f_name.split('-')
except:
pass
with open(f_name, 'r') as f:
for line in f:
time, ip, msg = line.strip().split(';')
ret += f_name + ';' + time + ';' + ip +\
';' + msg + '\r\n'
os.chdir(currdir)
return ret
| 24.380952 | 56 | 0.455078 |
3dff6fe799fe1071479ff50e0b1f06b3a628e5ca | 1,715 | py | Python | update_meta.py | skratchdot/media-tools | bca0c683fb637aeefda1c49454a118f809047d97 | [
"MIT"
] | null | null | null | update_meta.py | skratchdot/media-tools | bca0c683fb637aeefda1c49454a118f809047d97 | [
"MIT"
] | null | null | null | update_meta.py | skratchdot/media-tools | bca0c683fb637aeefda1c49454a118f809047d97 | [
"MIT"
] | 1 | 2021-05-25T08:11:10.000Z | 2021-05-25T08:11:10.000Z | # -*- coding: utf-8 -*-
import argparse
from lib.io_utils import *
from lib.math_utils import *
from lib.processing_utils import *
import os
from pprint import pprint
import re
import sys
# input
parser = argparse.ArgumentParser()
parser.add_argument('-in', dest="INPUT_FILE", default="tmp/samples.csv", help="Input file")
parser.add_argument('-key', dest="COLUMN_KEY", default="filename", help="Column key to match against")
parser.add_argument('-find', dest="FIND_PATTERN", default="(.*)\.wav", help="Find pattern")
parser.add_argument('-rkey', dest="UPDATE_COLUMN_KEY", default="", help="Column key to replace; leave blank if the same column key")
parser.add_argument('-repl', dest="REPLACE_PATTERN", default="\\1.mp3", help="Replace pattern")
parser.add_argument('-out', dest="OUTPUT_FILE", default="", help="CSV output file; leave blank if update the same file")
parser.add_argument('-probe', dest="PROBE", action="store_true", help="Just show info?")
a = parser.parse_args()
# Parse arguments
OUTPUT_FILE = a.OUTPUT_FILE if len(a.OUTPUT_FILE) > 0 else a.INPUT_FILE
FIND_PATTERN = a.FIND_PATTERN.strip()
REPLACE_PATTERN = a.REPLACE_PATTERN.strip()
UPDATE_COLUMN_KEY = a.UPDATE_COLUMN_KEY.strip() if len(a.UPDATE_COLUMN_KEY) > 0 else a.COLUMN_KEY
# Read data
headings, rows = readCsv(a.INPUT_FILE)
if UPDATE_COLUMN_KEY not in headings:
headings.append(UPDATE_COLUMN_KEY)
# Make sure output dirs exist
makeDirectories(OUTPUT_FILE)
for i, row in enumerate(rows):
value = row[a.COLUMN_KEY]
newValue = re.sub(FIND_PATTERN, REPLACE_PATTERN, value)
rows[i][UPDATE_COLUMN_KEY] = newValue
if a.PROBE:
print(newValue)
if a.PROBE:
sys.exit()
writeCsv(OUTPUT_FILE, rows, headings)
| 35 | 132 | 0.741691 |
424aa31b6c00eb74e13c8f89facdb2e61816cd79 | 81 | py | Python | ivipcv/ivipcv/ops/__init__.py | QiuHeqian/CrossDet | 2781006d1cafb42bd059fed0f8d14aca885fb6c8 | [
"Apache-2.0"
] | 27 | 2021-08-10T08:33:24.000Z | 2022-03-07T12:16:50.000Z | ivipcv/ivipcv/ops/__init__.py | QiuHeqian/CrossDet | 2781006d1cafb42bd059fed0f8d14aca885fb6c8 | [
"Apache-2.0"
] | 3 | 2021-08-10T08:35:37.000Z | 2021-12-10T12:28:00.000Z | ivipcv/ivipcv/ops/__init__.py | QiuHeqian/CrossDet | 2781006d1cafb42bd059fed0f8d14aca885fb6c8 | [
"Apache-2.0"
] | 1 | 2022-02-15T06:40:36.000Z | 2022-02-15T06:40:36.000Z | from .cross_pool import CrossPool
__all__ = [
'CrossPool', 'cross_pool'
]
| 13.5 | 33 | 0.679012 |
63c6f8cc24a8646b5a3aad33b6c044d98aba357e | 3,631 | py | Python | tests/connectors/test_opcua_connector.py | MarcelMann/thingsboard-gateway | 87fe9ba1f20c6b1e1e7920db56f7d9b3db6b178d | [
"Apache-2.0"
] | 1,123 | 2017-02-07T13:09:40.000Z | 2022-03-30T10:40:48.000Z | tests/connectors/test_opcua_connector.py | MarcelMann/thingsboard-gateway | 87fe9ba1f20c6b1e1e7920db56f7d9b3db6b178d | [
"Apache-2.0"
] | 655 | 2017-03-07T17:25:55.000Z | 2022-03-31T07:59:53.000Z | tests/connectors/test_opcua_connector.py | MarcelMann/thingsboard-gateway | 87fe9ba1f20c6b1e1e7920db56f7d9b3db6b178d | [
"Apache-2.0"
] | 648 | 2017-02-07T13:32:30.000Z | 2022-03-31T05:17:55.000Z | # Copyright 2021. ThingsBoard
# #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import uuid
from threading import Thread
from time import sleep, time
from math import sin
from thingsboard_gateway.tb_utility.tb_utility import TBUtility
from tests.connectors.connector_tests_base import ConnectorTestBase, log
try:
from opcua.ua import NodeId, NodeIdType
from opcua import ua, uamethod, Server
except ImportError:
log.error("OpcUa library - not found. Installing...")
TBUtility.install_package("opcua")
from opcua.ua import NodeId, NodeIdType
from opcua import ua, uamethod, Server
class OpcUaConnectorGeneralTest(ConnectorTestBase):
def test_number_one(self):
self._create_connector("connection_test.json")
self.assertTrue(self.connector is not None)
self.check_or_create_server()
self.connector.open()
def check_or_create_server(self):
if not hasattr(self, "test_server"):
self.test_server = Server()
self.__server_thread = Thread(target=self.__server_run, name="Test OPC UA server", args=(self.test_server,))
self.assertTrue(self.test_server is not None)
def __server_run(self, test_server):
self.test_server = test_server
class SubHandler(object):
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val)
def event_notification(self, event):
print("Python: New event", event)
@uamethod
def multiply(parent, x, y):
return x * y
self.test_server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
self.test_server.set_server_name("Test Server")
self.test_server.set_security_policy([
ua.SecurityPolicyType.NoSecurity,
ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt,
ua.SecurityPolicyType.Basic256Sha256_Sign])
uri = "http://127.0.0.1"
idx = self.test_server.register_namespace(uri)
device = self.test_server.nodes.objects.add_object(idx, "Device1")
name = self.test_server.nodes.objects.add_variable(idx, "serialNumber", "TEST")
name.set_writable()
temperature_and_humidity = device.add_object(idx, "TemperatureAndHumiditySensor")
temperature = temperature_and_humidity.add_variable(idx, "Temperature", 56.7)
humidity = temperature_and_humidity.add_variable(idx, "Humidity", 68.7)
battery = device.add_object(idx, "Battery")
battery_level = battery.add_variable(idx, "batteryLevel", 24)
device.add_method(idx, "multiply", multiply, [ua.VariantType.Int64, ua.VariantType.Int64], [ua.VariantType.Int64])
self.test_server.start()
try:
while self.server_running:
sleep(.1)
finally:
self.test_server.stop()
def stop_test_server(self):
self.server_running = False
def tearDown(self):
super().tearDown()
self.stop_test_server()
| 37.822917 | 122 | 0.675021 |
771a700679a7c6fbc8d0272f01df135ba8f55bfe | 10,071 | py | Python | pytorch_DQNdrone.py | subinlab/dqn | e1b9175a5c9dc2fb7b633b4df54c33fbba7e1e15 | [
"MIT"
] | 1 | 2021-01-11T14:42:42.000Z | 2021-01-11T14:42:42.000Z | pytorch_DQNdrone.py | subinlab/dqn | e1b9175a5c9dc2fb7b633b4df54c33fbba7e1e15 | [
"MIT"
] | null | null | null | pytorch_DQNdrone.py | subinlab/dqn | e1b9175a5c9dc2fb7b633b4df54c33fbba7e1e15 | [
"MIT"
] | null | null | null | import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
# TODO: Import new environment
# env = gym.make('CartPole-v0').unwrapped
# set up matplotlib
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython:
from IPython import display
plt.ion()
# if gpu is to be used
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
###############
# Replay Memory
###############
Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward'))
class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
"""Saves a transition."""
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
self.position = (self.position+1)%self.capacity
def sample(self, batch_size):
"""Select a random batch of transitions for training"""
return random.sample(self.memory, batch_size)
def __len__(self):
"""Return length of replay memory"""
return len(self.memory)
###############
# DQN algorithm
###############
class DQN(nn.Module):
def __init__(self, h, w, outputs):
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)
self.bn1 = nn.BatchNorm2d(16)
self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)
self.bn2 = nn.BatchNorm2d(32)
self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
self.bn3 = nn.BatchNorm2d(32)
# Number of Linear input connections depends on output of conv2d layers
# and therefore the input image size, so compute it.
def conv2d_size_out(size, kernel_size = 5, stride = 2):
return (size - (kernel_size - 1) - 1) // stride + 1
convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w)))
convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h)))
linear_input_size = convw * convh * 32
self.head = nn.Linear(linear_input_size, outputs)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
return self.head(x.view(x.size(0), -1))
##################
# Input extraction
##################
# The code below are utilies for extracting and processing rendered images from environment.
resize = T.Compose([T.ToPILImage(),
T.Resize(40, interpolation=Image.CUBIC),
T.ToTensor()])
def get_cart_location(screen_width):
world_width = env.x_threshold * 2
scale = screen_width / world_width
return int(env.state[0] * scale + screen_width / 2.0) # MIDDLE OF CART
def get_screen():
# Returned screen requested by gym is 400x600x3, but is sometimes larger
# such as 800x1200x3. Transpose it into torch order (CHW).
# TODO: Get width and heigth of images
screen = env.render(mode='rgb_array').transpose((2, 0, 1))
# Cart is in the lower half, so strip off the top and bottom of the screen
_, screen_height, screen_width = screen.shape
screen = screen[:, int(screen_height*0.4):int(screen_height * 0.8)]
view_width = int(screen_width * 0.6)
cart_location = get_cart_location(screen_width)
if cart_location < view_width // 2:
slice_range = slice(view_width)
elif cart_location > (screen_width - view_width // 2):
slice_range = slice(-view_width, None)
else:
slice_range = slice(cart_location - view_width // 2,
cart_location + view_width // 2)
# Strip off the edges, so that we have a square image centered on a cart
screen = screen[:, :, slice_range]
# Convert to float, rescale, convert to torch tensor
# (this doesn't require a copy)
screen = np.ascontiguousarray(screen, dtype=np.float32) / 255
screen = torch.from_numpy(screen)
# Resize, and add a batch dimension (BCHW)
return resize(screen).unsqueeze(0).to(device)
env.reset()
plt.figure()
plt.imshow(get_screen().cpu().squeeze(0).permute(1, 2, 0).numpy(),
interpolation='none')
plt.title('Example extracted screen')
plt.show()
# Training Hyperparameters an utilities
BATCH_SIZE = 128
GAMMA = 0.999
EPS_START = 0.9
EPS_END = 0.05
EPS_DECAY = 200
TARGET_UPDATE = 10
# Get screen size so that we can initialize layers correctly based on shape
# returned from AI gym. Typical dimensions at this point are close to 3x40x90
# which is the result of a clamped and down-scaled render buffer in get_screen()
init_screen = get_screen()
_, _, screen_height, screen_width = init_screen.shape
# Get number of actions from gym action space
# TODO: Get action space of multirotor environment
n_actions = env.action_space.n
policy_net = DQN(screen_height, screen_width, n_actions).to(device)
target_net = DQN(screen_height, screen_width, n_actions).to(device)
target_net.load_state_dict(policy_net.state_dict())
target_net.eval()
optimizer = optim.RMSprop(policy_net.parameters())
memory = ReplayMemory(10000)
steps_done = 0
def select_action(state):
global steps_done
sample = random.random()
eps_threshold = EPS_END + (EPS_START - EPS_END) * \
math.exp(-1. * steps_done / EPS_DECAY)
steps_done += 1
if sample > eps_threshold:
with torch.no_grad():
# t.max(1) will return largest column value of each row.
# second column on max result is index of where max element was
# found, so we pick action with the larger expected reward.
return policy_net(state).max(1)[1].view(1, 1)
else:
return torch.tensor([[random.randrange(n_actions)]], device=device, dtype=torch.long)
episode_durations = []
def plot_durations():
plt.figure(2)
plt.clf()
durations_t = torch.tensor(episode_durations, dtype=torch.float)
plt.title('Training...')
plt.xlabel('Episode')
plt.ylabel('Duration')
plt.plot(durations_t.numpy())
# Take 100 episode averages and plot them too
if len(durations_t) >= 100:
means = durations_t.unfold(0, 100, 1).mean(1).view(-1)
means = torch.cat((torch.zeros(99), means))
plt.plot(means.numpy())
plt.pause(0.001) # pause a bit so that plots are updated
if is_ipython:
display.clear_output(wait=True)
display.display(plt.gcf())
# Training loop
def optimize_model():
if len(memory) < BATCH_SIZE:
return
transitions = memory.sample(BATCH_SIZE)
# Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for
# detailed explanation). This converts batch-array of Transitions
# to Transition of batch-arrays.
batch = Transition(*zip(*transitions))
# Compute a mask of non-final states and concatenate the batch elements
# (a final state would've been the one after which simulation ended)
non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
batch.next_state)), device=device, dtype=torch.uint8)
non_final_next_states = torch.cat([s for s in batch.next_state
if s is not None])
state_batch = torch.cat(batch.state)
action_batch = torch.cat(batch.action)
reward_batch = torch.cat(batch.reward)
# Compute Q(s_t, a) - the model computes Q(s_t), then we select the
# columns of actions taken. These are the actions which would've been taken
# for each batch state according to policy_net
state_action_values = policy_net(state_batch).gather(1, action_batch)
# Compute V(s_{t+1}) for all next states.
# Expected values of actions for non_final_next_states are computed based
# on the "older" target_net; selecting their best reward with max(1)[0].
# This is merged based on the mask, such that we'll have either the expected
# state value or 0 in case the state was final.
next_state_values = torch.zeros(BATCH_SIZE, device=device)
next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()
# Compute the expected Q values
expected_state_action_values = (next_state_values * GAMMA) + reward_batch
# Compute Huber loss
loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))
# Optimize the model
optimizer.zero_grad()
loss.backward()
for param in policy_net.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
num_episodes = 50
for i_episode in range(num_episodes):
# Initialize the environment and state
env.reset()
last_screen = get_screen()
current_screen = get_screen()
state = current_screen - last_screen
for t in count():
# Select and perform an action
action = select_action(state)
_, reward, done, _ = env.step(action.item())
reward = torch.tensor([reward], device=device)
# Observe new state
last_screen = current_screen
current_screen = get_screen()
if not done:
next_state = current_screen - last_screen
else:
next_state = None
# Store the transition in memory
memory.push(state, action, next_state, reward)
# Move to the next state
state = next_state
# Perform one step of the optimization (on the target network)
optimize_model()
if done:
episode_durations.append(t + 1)
plot_durations()
break
# Update the target network, copying all weights and biases in DQN
if i_episode % TARGET_UPDATE == 0:
target_net.load_state_dict(policy_net.state_dict())
print('Complete')
env.render()
env.close()
plt.ioff()
plt.show()
| 34.372014 | 95 | 0.666468 |
8b6d38bb003def29c15e126b2f7f1218a47585e1 | 400 | py | Python | redirecttest/redirecttest/urls.py | spothero/django-robust-redirects | 14e13c2765315d0eb214791ba03a5588a0dd9953 | [
"Apache-2.0"
] | 2 | 2015-09-02T11:01:19.000Z | 2020-07-02T19:01:27.000Z | redirecttest/redirecttest/urls.py | spothero/django-robust-redirects | 14e13c2765315d0eb214791ba03a5588a0dd9953 | [
"Apache-2.0"
] | 1 | 2017-06-14T21:47:36.000Z | 2017-06-14T21:47:36.000Z | redirecttest/redirecttest/urls.py | spothero/django-robust-redirects | 14e13c2765315d0eb214791ba03a5588a0dd9953 | [
"Apache-2.0"
] | 3 | 2015-05-30T12:12:23.000Z | 2020-07-02T19:47:21.000Z | from django.contrib import admin
from django.urls import re_path
from django.http import HttpResponse
from django.views.generic import View
class TestView(View):
def dispatch(self, request, *args, **kwargs):
return HttpResponse('Testing')
admin.autodiscover()
urlpatterns = [
re_path(r'^partialtest/(?P<pk>\d+)/', TestView.as_view()),
re_path(r'^admin/', admin.site.urls),
]
| 22.222222 | 62 | 0.7125 |
d32b9b58307fa9e2e271baed7ab3ee671fc52a86 | 2,482 | py | Python | cirq/contrib/qcircuit/qcircuit_diagram_info_test.py | jlmayfield/Cirq | dc1294f54118a9a4f92546ca13780b91615dd675 | [
"Apache-2.0"
] | null | null | null | cirq/contrib/qcircuit/qcircuit_diagram_info_test.py | jlmayfield/Cirq | dc1294f54118a9a4f92546ca13780b91615dd675 | [
"Apache-2.0"
] | null | null | null | cirq/contrib/qcircuit/qcircuit_diagram_info_test.py | jlmayfield/Cirq | dc1294f54118a9a4f92546ca13780b91615dd675 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cirq
import cirq.contrib.qcircuit as ccq
def test_get_qcircuit_diagram_info():
qubits = cirq.NamedQubit('x'), cirq.NamedQubit('y')
gate = cirq.SwapPowGate(exponent=0.5)
op = gate(*qubits)
qubit_map = {q: i for i, q in enumerate(qubits)}
args = cirq.CircuitDiagramInfoArgs(
known_qubits=qubits,
known_qubit_count=None,
use_unicode_characters=True,
precision=3,
qubit_map=qubit_map)
actual_info = ccq.get_qcircuit_diagram_info(op, args)
name = '{\\text{SWAP}^{0.5}}'
expected_info = cirq.CircuitDiagramInfo(
('\multigate{1}' + name, '\ghost' + name),
exponent=0.5,
connected=False)
assert actual_info == expected_info
gate = cirq.SWAP
op = gate(*qubits)
qubit_map = {q: i for q, i in zip(qubits, (4, 3))}
args = cirq.CircuitDiagramInfoArgs(
known_qubits=qubits,
known_qubit_count=None,
use_unicode_characters=True,
precision=3,
qubit_map=qubit_map)
actual_info = ccq.get_qcircuit_diagram_info(op, args)
expected_info = cirq.CircuitDiagramInfo(
('\ghost{\\text{SWAP}}', '\multigate{1}{\\text{SWAP}}'),
connected=False)
assert actual_info == expected_info
qubit_map = {q: i for q, i in zip(qubits, (2, 5))}
args = cirq.CircuitDiagramInfoArgs(
known_qubits=qubits,
known_qubit_count=None,
use_unicode_characters=True,
precision=3,
qubit_map=qubit_map)
actual_info = ccq.get_qcircuit_diagram_info(op, args)
expected_info = cirq.CircuitDiagramInfo(('\\gate{\\text{swap}}',) * 2)
assert actual_info == expected_info
actual_info = ccq.get_qcircuit_diagram_info(op,
cirq.CircuitDiagramInfoArgs.UNINFORMED_DEFAULT)
assert actual_info == expected_info
| 36.5 | 74 | 0.662772 |
178e8362863742bac4cedb70e932b5ea5e0ee1b2 | 311 | py | Python | dev/modules/physics/continuum_mechanics/beam_problems-10.py | oscarbenjamin/sympy_doc | a31c46735370f4ed24540d020791cacc598d5a51 | [
"BSD-3-Clause"
] | null | null | null | dev/modules/physics/continuum_mechanics/beam_problems-10.py | oscarbenjamin/sympy_doc | a31c46735370f4ed24540d020791cacc598d5a51 | [
"BSD-3-Clause"
] | null | null | null | dev/modules/physics/continuum_mechanics/beam_problems-10.py | oscarbenjamin/sympy_doc | a31c46735370f4ed24540d020791cacc598d5a51 | [
"BSD-3-Clause"
] | null | null | null | b.shear_force()
# -1 0 1 -1 1 0
# - 258⋅<x> + 52⋅<x> - 8⋅<x> + 50⋅<x - 5> + 8⋅<x - 5> - 12⋅<x - 9>
b.bending_moment()
# 0 1 2 0 2 1
# - 258⋅<x> + 52⋅<x> - 4⋅<x> + 50⋅<x - 5> + 4⋅<x - 5> - 12⋅<x - 9>
| 44.428571 | 73 | 0.254019 |
b6c8ebb15bf1b63d7bb88adf83898974335b624b | 8,438 | py | Python | scripts/lib/wic/plugins/source/syslinux-alix.py | klihub/meta-alix | 46853c83c0bde12053a8d6288e1a038363448d38 | [
"MIT"
] | 2 | 2017-11-13T21:00:40.000Z | 2017-11-16T18:57:57.000Z | scripts/lib/wic/plugins/source/syslinux-alix.py | klihub/meta-alix | 46853c83c0bde12053a8d6288e1a038363448d38 | [
"MIT"
] | null | null | null | scripts/lib/wic/plugins/source/syslinux-alix.py | klihub/meta-alix | 46853c83c0bde12053a8d6288e1a038363448d38 | [
"MIT"
] | null | null | null | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2014, Intel Corporation.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# DESCRIPTION
# This implements the 'syslinux-alix' source plugin class for 'wic'.
# This plugin is a modified version of bootimg-pcbios by Tomi Zanussi.
#
# AUTHORS
# Tom Zanussi <tom.zanussi (at] linux.intel.com>
# modified by Krisztian Litkey <krisztian litkey@intel.com>
#
import logging
import os
from wic import WicError
from wic.engine import get_custom_config
from wic.pluginbase import SourcePlugin
from wic.misc import (exec_cmd, exec_native_cmd,
get_bitbake_var, BOOTDD_EXTRA_SPACE)
logger = logging.getLogger('wic')
class SyslinuxAlixPlugin(SourcePlugin):
"""
Create MBR boot partition and install syslinux on it.
"""
name = 'syslinux-alix'
@classmethod
def _get_bootimg_dir(cls, bootimg_dir, dirname):
"""
Check if dirname exists in default bootimg_dir or in STAGING_DIR.
"""
for result in (bootimg_dir, get_bitbake_var("STAGING_DATADIR")):
if os.path.exists("%s/%s" % (result, dirname)):
return result
raise WicError("Couldn't find correct bootimg_dir, exiting")
@classmethod
def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
bootimg_dir, kernel_dir, native_sysroot):
"""
Called after all partitions have been prepared and assembled into a
disk image. In this case, we install the MBR.
"""
bootimg_dir = cls._get_bootimg_dir(bootimg_dir, 'syslinux')
mbrfile = "%s/syslinux/" % bootimg_dir
if creator.ptable_format == 'msdos':
mbrfile += "mbr.bin"
elif creator.ptable_format == 'gpt':
mbrfile += "gptmbr.bin"
else:
raise WicError("Unsupported partition table: %s" %
creator.ptable_format)
if not os.path.exists(mbrfile):
raise WicError("Couldn't find %s. If using the -e option, do you "
"have the right MACHINE set in local.conf? If not, "
"is the bootimg_dir path correct?" % mbrfile)
full_path = creator._full_path(workdir, disk_name, "direct")
logger.debug("Installing MBR on disk %s as %s with size %s bytes",
disk_name, full_path, disk.min_size)
dd_cmd = "dd if=%s of=%s conv=notrunc" % (mbrfile, full_path)
exec_cmd(dd_cmd, native_sysroot)
@classmethod
def _syslinux_config(cls, bootloader):
"""
Generate syslinux configuration or take a custom one as such.
"""
custom = None
if bootloader.configfile:
custom = get_custom_config(bootloader.configfile)
if custom:
logger.debug("Using custom configuration file %s "
"for syslinux.cfg", bootloader.configfile)
return custom
else:
raise WicError("configfile is specified but failed to "
"get it from %s." % bootloader.configfile)
# We try to comply to the stock syslinux.bbclass for the basic
# configuration variables.
serial = get_bitbake_var("SYSLINUX_SERIAL")
serial_tty = get_bitbake_var("SYSLINUX_SERIAL_TTY")
prompt = get_bitbake_var("SYSLINUX_PROMPT")
timeout = get_bitbake_var("SYSLINUX_TIMEOUT")
allow_options = get_bitbake_var("SYSLINUX_ALLOWOPTIONS")
initrd = ("initrd=/initrd" if get_bitbake_var("INITRD") else "")
append = get_bitbake_var("APPEND")
cfg = "UI menu.c32\n"
cfg += "\n"
cfg += "PROMPT " + str(prompt or 0) + "\n"
cfg += "TIMEOUT " + str(timeout or 50) + "\n"
cfg += "\n"
cfg += "ALLOWOPTIONS " + str(allow_options or 1) + "\n"
cfg += "SERIAL " + str(serial or "0 38400") + "\n"
cfg += "DEFAULT rootfs1\n"
cfg += "\n"
cfg += "LABEL rootfs1\n"
cfg += " KERNEL /vmlinuz\n"
cfg += " APPEND label=rootfs1 rootwait root=LABEL=rootfs1"
cfg += " %s" % (serial_tty or "console=ttyS0,38400n8")
cfg += " " + initrd
cfg += "\n"
cfg += "LABEL rootfs2\n"
cfg += " KERNEL /vmlinuz\n"
cfg += " APPEND label=rootfs2 rootwait root=LABEL=rootfs2"
cfg += " %s" % (serial_tty or "console=ttyS0,38400n8")
cfg += " " + initrd
cfg += "\n"
return cfg
@classmethod
def do_configure_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
Called before do_prepare_partition(), creates syslinux config
"""
hdddir = "%s/hdd/boot" % cr_workdir
install_cmd = "install -d %s" % hdddir
exec_cmd(install_cmd)
cfg = cls._syslinux_config(creator.ks.bootloader)
logger.debug("Writing syslinux config %s/hdd/boot/syslinux.cfg",
cr_workdir)
f = open("%s/hdd/boot/syslinux.cfg" % cr_workdir, "w")
f.write(cfg)
f.close()
@classmethod
def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
rootfs_dir, native_sysroot):
"""
Called to do the actual content population for a partition i.e. it
'prepares' the partition to be incorporated into the image.
In this case, prepare content for legacy bios boot partition.
"""
bootimg_dir = cls._get_bootimg_dir(bootimg_dir, 'syslinux')
staging_kernel_dir = kernel_dir
hdddir = "%s/hdd/boot" % cr_workdir
cmds = ("install -m 0644 %s/bzImage %s/vmlinuz" %
(staging_kernel_dir, hdddir),
"install -m 444 %s/syslinux/ldlinux.sys %s/ldlinux.sys" %
(bootimg_dir, hdddir),
"install -m 0644 %s/syslinux/menu.c32 %s/menu.c32" %
(bootimg_dir, hdddir),
"install -m 444 %s/syslinux/libcom32.c32 %s/libcom32.c32" %
(bootimg_dir, hdddir),
"install -m 444 %s/syslinux/libutil.c32 %s/libutil.c32" %
(bootimg_dir, hdddir))
initrd = get_bitbake_var("INITRD")
if initrd:
cmds += (("install -m 0644 %s %s/initrd" % (initrd, hdddir)), )
for install_cmd in cmds:
exec_cmd(install_cmd)
du_cmd = "du -bks %s" % hdddir
out = exec_cmd(du_cmd)
blocks = int(out.split()[0])
extra_blocks = part.get_extra_block_count(blocks)
if extra_blocks < BOOTDD_EXTRA_SPACE:
extra_blocks = BOOTDD_EXTRA_SPACE
blocks += extra_blocks
logger.debug("Added %d extra blocks to %s to get to %d total blocks",
extra_blocks, part.mountpoint, blocks)
# dosfs image, created by mkdosfs
bootimg = "%s/boot%s.img" % (cr_workdir, part.lineno)
dosfs_cmd = "mkdosfs -n boot -S 512 -C %s %d" % (bootimg, blocks)
exec_native_cmd(dosfs_cmd, native_sysroot)
mcopy_cmd = "mcopy -i %s -s %s/* ::/" % (bootimg, hdddir)
exec_native_cmd(mcopy_cmd, native_sysroot)
syslinux_cmd = "syslinux %s" % bootimg
exec_native_cmd(syslinux_cmd, native_sysroot)
chmod_cmd = "chmod 644 %s" % bootimg
exec_cmd(chmod_cmd)
du_cmd = "du -Lbks %s" % bootimg
out = exec_cmd(du_cmd)
bootimg_size = out.split()[0]
part.size = int(bootimg_size)
part.source_file = bootimg
| 37.336283 | 80 | 0.600261 |
c38d932a0d7ecf237713c5d98a75847860b4d280 | 160 | py | Python | thumt/utils/sample.py | Demon-JieHao/Modeling-Structure-for-Transformer-Network | 329831964731ccb7361b847e0ff7c2d809ab7231 | [
"BSD-3-Clause"
] | 145 | 2018-12-03T05:47:26.000Z | 2022-02-25T07:55:52.000Z | thumt/utils/sample.py | Demon-JieHao/Modeling-Structure-for-Transformer-Network | 329831964731ccb7361b847e0ff7c2d809ab7231 | [
"BSD-3-Clause"
] | 11 | 2018-12-03T06:03:25.000Z | 2021-11-16T12:18:59.000Z | thumt/utils/sample.py | Demon-JieHao/Modeling-Structure-for-Transformer-Network | 329831964731ccb7361b847e0ff7c2d809ab7231 | [
"BSD-3-Clause"
] | 24 | 2018-12-16T08:42:38.000Z | 2021-07-13T04:08:47.000Z | # coding=utf-8
# Copyright 2018 The THUMT Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| 22.857143 | 38 | 0.84375 |
97c89c2dc27e82259fa6e9e4e2eaa156893e3c96 | 4,622 | py | Python | tests/pytracer/spectral/test_spectral.py | zjiayao/pyTracer | c2b4ef299ecbdca1c519059488f7cd2438943ee4 | [
"MIT"
] | 9 | 2017-11-20T18:17:27.000Z | 2022-01-27T23:00:31.000Z | tests/pytracer/spectral/test_spectral.py | zjiayao/pyTracer | c2b4ef299ecbdca1c519059488f7cd2438943ee4 | [
"MIT"
] | 4 | 2021-06-08T19:03:51.000Z | 2022-03-11T23:18:44.000Z | tests/pytracer/spectral/test_spectral.py | zjiayao/pyTracer | c2b4ef299ecbdca1c519059488f7cd2438943ee4 | [
"MIT"
] | 1 | 2017-11-20T22:48:01.000Z | 2017-11-20T22:48:01.000Z | """
test_spectral.py
A test script that (roughly) test
the implementation of various classes
Created by Jiayao on 15 Aug, 2017
"""
from __future__ import absolute_import
import numpy as np
from numpy.testing import assert_array_almost_equal
import pytest
from pytracer.spectral.spectrum import (xyz2rgb, rgb2xyz, SpectrumType,
CoefficientSpectrum, SampledSpectrum,
RGBSpectrum)
N_TEST_CASE = 10
EPS = 5
VAR = 10
np.random.seed(1)
rng = np.random.rand
rng_uniform = np.random.uniform
test_data = {
'triple': [np.array([rng_uniform(0., 1.), rng_uniform(0., 1.), rng_uniform(0., 1.)]) for _ in range(N_TEST_CASE)],
'type': [SpectrumType.REFLECTANCE, SpectrumType.ILLUMINANT]
}
@pytest.fixture
def lambda_smp():
return 350 + rng(50) * 900
@pytest.fixture
def value_smp():
return 20 + rng(50) * 10
def assert_almost_eq(a, b, thres=EPS):
assert_array_almost_equal(a, b, thres)
class TestUtil(object):
@pytest.mark.parametrize("arr", test_data['triple'])
def test_xyz_rgb(self, arr):
rgb = xyz2rgb(arr)
xyz = rgb2xyz(rgb)
assert_almost_eq(xyz, arr)
xyz = rgb2xyz(arr)
rgb = xyz2rgb(xyz)
assert_almost_eq(rgb, arr)
class TestCoefSpec(object):
def test_init_and_copy(self):
cs = CoefficientSpectrum(10)
assert np.shape(cs.c)[0] == 10
assert cs == [0.] * 10
cs = CoefficientSpectrum(10, 1.)
assert np.shape(cs.c)[0] == 10
assert cs == [1.] * 10
css = cs.copy()
assert cs == css
assert not cs != css
@pytest.mark.parametrize("arr", test_data['triple'])
def test_create(self, arr):
cs = CoefficientSpectrum.create(arr)
assert cs.c == arr
cs = CoefficientSpectrum.create(list(arr))
assert cs.c == arr
def test_is_black(self):
cs = CoefficientSpectrum(10)
assert cs.is_black()
cs.c[0] = 1
assert not cs.is_black()
@pytest.mark.parametrize("arr", test_data['triple'])
def test_arith(self, arr):
cs = CoefficientSpectrum.create(arr)
assert_almost_eq(cs.sqrt().c, np.sqrt(cs.c))
assert_almost_eq(cs.exp().c, np.exp(cs.c))
e = rng() * VAR
assert_almost_eq(cs.pow(e).c, np.power(cs.c, e))
@pytest.mark.parametrize("arr_1", test_data['triple'])
@pytest.mark.parametrize("arr_2", test_data['triple'])
def test_lerp(self, arr_1, arr_2):
cs_1 = CoefficientSpectrum.create(arr_1)
cs_2 = CoefficientSpectrum.create(arr_2)
t = rng()
cs = cs_1.lerp(t, cs_2)
c = (1. - t) * cs_1.c + t * cs_2.c
assert_almost_eq(cs.c, c)
class TestSampledAndRGBSpec(object):
@classmethod
def setup_class(cls):
SampledSpectrum.init()
@pytest.mark.parametrize("arr", test_data['triple'])
def test_init(self, arr):
from pytracer.spectral.spectrum import N_SPECTRAL_SAMPLES
ss = SampledSpectrum()
assert ss.n_samples == N_SPECTRAL_SAMPLES
assert ss == [0.] * N_SPECTRAL_SAMPLES
ss = SampledSpectrum(arr)
assert ss.n_samples == 3
assert ss == arr
rs = RGBSpectrum()
assert rs.n_samples == 3
assert rs == [0.] * 3
rs = RGBSpectrum(arr)
assert rs.n_samples == 3
assert rs == arr
def test_from_sampled(self, lambda_smp, value_smp):
ss = SampledSpectrum.from_sampled(lambda_smp, value_smp)
rs = RGBSpectrum.from_sampled(lambda_smp, value_smp)
assert_almost_eq(ss.to_rgb(), rs)
def test_avg_spec_smp(self):
assert_almost_eq(SampledSpectrum.average_spectrum_samples([1, 2, 3, 4], [3, 4, 5, 3], 1.5, 3.5), 4.3125)
assert_almost_eq(SampledSpectrum.average_spectrum_samples([1, 2, 3, 4], [3, 4, 5, 3], 0.5, 4), 3.8571428571428571)
assert_almost_eq(SampledSpectrum.average_spectrum_samples([1, 2, 3, 4], [3, 4, 5, 3], 0.5, 4.5), 3.75)
# TODO: Full spectrum
# @pytest.mark.parametrize("arr", test_data['triple'])
# @pytest.mark.parametrize("tp", test_data['type'])
# def test_conversion(self, arr, tp):
# rgb = arr
# xyz = rgb2xyz(rgb)
#
# ss = SampledSpectrum.from_rgb(rgb)
# rs = RGBSpectrum(rgb)
# rss = RGBSpectrum.from_xyz(xyz)
# assert_almost_eq(rs.to_rgb(), rs)
# assert_almost_eq(ss.to_rgb(), rs)
# assert_almost_eq(ss.to_xyz(), rs.to_xyz())
# assert_almost_eq(rss.to_rgb(), rss)
# assert_almost_eq(ss.to_rgb(), rss)
# assert_almost_eq(rss.to_xyz(), ss.to_xyz())
#
# ss = SampledSpectrum.from_rgb(rgb, tp)
# rs = RGBSpectrum.from_xyz(xyz, tp)
# assert_almost_eq(rs.to_rgb(), rs)
# assert_almost_eq(ss.to_rgb(), rs)
# assert_almost_eq(rs.to_xyz(), ss.to_xyz())
#
# sss = SampledSpectrum.from_xyz(xyz, tp)
# rrs = RGBSpectrum.from_rgb(rgb, tp)
# assert_almost_eq(rrs.to_rgb(), rrs)
# assert_almost_eq(sss.to_rgb(), rrs)
# assert_almost_eq(rrs.to_xyz(), sss.to_xyz())
#
| 25.119565 | 116 | 0.684119 |
e22937ab818d642c94ae0cde9de0472fc19c7e28 | 658 | py | Python | esphome/components/as3935_i2c/__init__.py | huhuhugo1/esphome | eb895d2095861a4d51f1a5fcd582a97389c27b4f | [
"MIT"
] | null | null | null | esphome/components/as3935_i2c/__init__.py | huhuhugo1/esphome | eb895d2095861a4d51f1a5fcd582a97389c27b4f | [
"MIT"
] | null | null | null | esphome/components/as3935_i2c/__init__.py | huhuhugo1/esphome | eb895d2095861a4d51f1a5fcd582a97389c27b4f | [
"MIT"
] | null | null | null | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import as3935, i2c
from esphome.const import CONF_ID
AUTO_LOAD = ['as3935']
DEPENDENCIES = ['i2c']
as3935_i2c_ns = cg.esphome_ns.namespace('as3935_i2c')
I2CAS3935 = as3935_i2c_ns.class_('I2CAS3935Component', as3935.AS3935, i2c.I2CDevice)
CONFIG_SCHEMA = cv.All(as3935.AS3935_SCHEMA.extend({
cv.GenerateID(): cv.declare_id(I2CAS3935),
}).extend(cv.COMPONENT_SCHEMA).extend(i2c.i2c_device_schema(0x03)))
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield as3935.setup_as3935(var, config)
yield i2c.register_i2c_device(var, config)
| 31.333333 | 84 | 0.778116 |
28d430ae2909bba60e4acb342356c4641a19e7f8 | 19,541 | py | Python | torchio/transforms/transform.py | searobbersduck/torchio | 67f9e0d19cefa98d5efed9c3f712ae6e3d8af791 | [
"Apache-2.0"
] | 1 | 2021-04-29T05:08:58.000Z | 2021-04-29T05:08:58.000Z | torchio/transforms/transform.py | searobbersduck/torchio | 67f9e0d19cefa98d5efed9c3f712ae6e3d8af791 | [
"Apache-2.0"
] | null | null | null | torchio/transforms/transform.py | searobbersduck/torchio | 67f9e0d19cefa98d5efed9c3f712ae6e3d8af791 | [
"Apache-2.0"
] | null | null | null | import copy
import numbers
import warnings
from abc import ABC, abstractmethod
from contextlib import contextmanager
from typing import Union, Tuple, Optional, Dict
import torch
import numpy as np
import SimpleITK as sitk
from ..utils import to_tuple
from ..data.subject import Subject
from ..data.io import nib_to_sitk, sitk_to_nib
from ..data.image import LabelMap
from ..typing import (
TypeKeys,
TypeData,
TypeNumber,
TypeCallable,
TypeTripletInt,
)
from .interpolation import Interpolation, get_sitk_interpolator
from .data_parser import DataParser, TypeTransformInput
TypeSixBounds = Tuple[int, int, int, int, int, int]
TypeBounds = Union[
int,
TypeTripletInt,
TypeSixBounds,
]
TypeMaskingMethod = Union[str, TypeCallable, TypeBounds, None]
anat_axes = 'Left', 'Right', 'Anterior', 'Posterior', 'Inferior', 'Superior'
class Transform(ABC):
"""Abstract class for all TorchIO transforms.
All subclasses must overwrite
:meth:`~torchio.transforms.Transform.apply_transform`,
which takes some input, applies a transformation and returns the result.
The input can be an instance of
:class:`torchio.Subject`,
:class:`torchio.Image`,
:class:`numpy.ndarray`,
:class:`torch.Tensor`,
:class:`SimpleITK.Image`,
or :class:`dict`.
Args:
p: Probability that this transform will be applied.
copy: Make a shallow copy of the input before applying the transform.
include: Sequence of strings with the names of the only images to which
the transform will be applied.
Mandatory if the input is a :class:`dict`.
exclude: Sequence of strings with the names of the images to which the
the transform will not be applied, apart from the ones that are
excluded because of the transform type.
For example, if a subject includes an MRI, a CT and a label map,
and the CT is added to the list of exclusions of an intensity
transform such as :class:`~torchio.transforms.RandomBlur`,
the transform will be only applied to the MRI, as the label map is
excluded by default by spatial transforms.
keep: Dictionary with the names of the images that will be kept in the
subject and their new names.
"""
def __init__(
self,
p: float = 1,
copy: bool = True,
include: TypeKeys = None,
exclude: TypeKeys = None,
keys: TypeKeys = None,
keep: Optional[Dict[str, str]] = None,
):
self.probability = self.parse_probability(p)
self.copy = copy
if keys is not None:
message = (
'The "keys" argument is deprecated and will be removed in the'
' future. Use "include" instead.'
)
warnings.warn(message, DeprecationWarning)
include = keys
self.include, self.exclude = self.parse_include_and_exclude(
include, exclude)
self.keep = keep
# args_names is the sequence of parameters from self that need to be
# passed to a non-random version of a random transform. They are also
# used to invert invertible transforms
self.args_names = ()
def __call__(
self,
data: TypeTransformInput,
) -> TypeTransformInput:
"""Transform data and return a result of the same type.
Args:
data: Instance of :class:`torchio.Subject`, 4D
:class:`torch.Tensor` or :class:`numpy.ndarray` with dimensions
:math:`(C, W, H, D)`, where :math:`C` is the number of channels
and :math:`W, H, D` are the spatial dimensions. If the input is
a tensor, the affine matrix will be set to identity. Other
valid input types are a SimpleITK image, a
:class:`torchio.Image`, a NiBabel Nifti1 image or a
:class:`dict`. The output type is the same as the input type.
"""
if torch.rand(1).item() > self.probability:
return data
data_parser = DataParser(data, keys=self.include)
subject = data_parser.get_subject()
if self.keep is not None:
images_to_keep = {}
for name, new_name in self.keep.items():
images_to_keep[new_name] = copy.copy(subject[name])
if self.copy:
subject = copy.copy(subject)
with np.errstate(all='raise'):
transformed = self.apply_transform(subject)
if self.keep is not None:
for name, image in images_to_keep.items():
transformed.add_image(image, name)
self.add_transform_to_subject_history(transformed)
for image in transformed.get_images(intensity_only=False):
ndim = image.data.ndim
assert ndim == 4, f'Output of {self.name} is {ndim}D'
output = data_parser.get_output(transformed)
return output
def __repr__(self):
if hasattr(self, 'args_names'):
names = self.args_names
args_strings = [f'{arg}={getattr(self, arg)}' for arg in names]
if hasattr(self, 'invert_transform') and self.invert_transform:
args_strings.append('invert=True')
args_string = ', '.join(args_strings)
return f'{self.name}({args_string})'
else:
return super().__repr__()
@property
def name(self):
return self.__class__.__name__
@abstractmethod
def apply_transform(self, subject: Subject) -> Subject:
raise NotImplementedError
def add_transform_to_subject_history(self, subject):
from .augmentation import RandomTransform
from . import Compose, OneOf, CropOrPad, RandomCropOrPad, EnsureShapeMultiple
from .preprocessing import SequentialLabels
call_others = (
RandomTransform,
Compose,
OneOf,
CropOrPad,
EnsureShapeMultiple,
SequentialLabels,
)
if not isinstance(self, call_others):
subject.add_transform(self, self._get_reproducing_arguments())
@staticmethod
def to_range(n, around):
if around is None:
return 0, n
else:
return around - n, around + n
def parse_params(self, params, around, name, make_ranges=True, **kwargs):
params = to_tuple(params)
# d or (a, b)
if len(params) == 1 or (len(params) == 2 and make_ranges):
params *= 3 # (d, d, d) or (a, b, a, b, a, b)
if len(params) == 3 and make_ranges: # (a, b, c)
items = [self.to_range(n, around) for n in params]
# (-a, a, -b, b, -c, c) or (1-a, 1+a, 1-b, 1+b, 1-c, 1+c)
params = [n for prange in items for n in prange]
if make_ranges:
if len(params) != 6:
message = (
f'If "{name}" is a sequence, it must have length 2, 3 or'
f' 6, not {len(params)}'
)
raise ValueError(message)
for param_range in zip(params[::2], params[1::2]):
self._parse_range(param_range, name, **kwargs)
return tuple(params)
@staticmethod
def _parse_range(
nums_range: Union[TypeNumber, Tuple[TypeNumber, TypeNumber]],
name: str,
min_constraint: TypeNumber = None,
max_constraint: TypeNumber = None,
type_constraint: type = None,
) -> Tuple[TypeNumber, TypeNumber]:
r"""Adapted from :class:`torchvision.transforms.RandomRotation`.
Args:
nums_range: Tuple of two numbers :math:`(n_{min}, n_{max})`,
where :math:`n_{min} \leq n_{max}`.
If a single positive number :math:`n` is provided,
:math:`n_{min} = -n` and :math:`n_{max} = n`.
name: Name of the parameter, so that an informative error message
can be printed.
min_constraint: Minimal value that :math:`n_{min}` can take,
default is None, i.e. there is no minimal value.
max_constraint: Maximal value that :math:`n_{max}` can take,
default is None, i.e. there is no maximal value.
type_constraint: Precise type that :math:`n_{max}` and
:math:`n_{min}` must take.
Returns:
A tuple of two numbers :math:`(n_{min}, n_{max})`.
Raises:
ValueError: if :attr:`nums_range` is negative
ValueError: if :math:`n_{max}` or :math:`n_{min}` is not a number
ValueError: if :math:`n_{max} \lt n_{min}`
ValueError: if :attr:`min_constraint` is not None and
:math:`n_{min}` is smaller than :attr:`min_constraint`
ValueError: if :attr:`max_constraint` is not None and
:math:`n_{max}` is greater than :attr:`max_constraint`
ValueError: if :attr:`type_constraint` is not None and
:math:`n_{max}` and :math:`n_{max}` are not of type
:attr:`type_constraint`.
"""
if isinstance(nums_range, numbers.Number): # single number given
if nums_range < 0:
raise ValueError(
f'If {name} is a single number,'
f' it must be positive, not {nums_range}')
if min_constraint is not None and nums_range < min_constraint:
raise ValueError(
f'If {name} is a single number, it must be greater'
f' than {min_constraint}, not {nums_range}'
)
if max_constraint is not None and nums_range > max_constraint:
raise ValueError(
f'If {name} is a single number, it must be smaller'
f' than {max_constraint}, not {nums_range}'
)
if type_constraint is not None:
if not isinstance(nums_range, type_constraint):
raise ValueError(
f'If {name} is a single number, it must be of'
f' type {type_constraint}, not {nums_range}'
)
min_range = -nums_range if min_constraint is None else nums_range
return (min_range, nums_range)
try:
min_value, max_value = nums_range
except (TypeError, ValueError):
raise ValueError(
f'If {name} is not a single number, it must be'
f' a sequence of len 2, not {nums_range}'
)
min_is_number = isinstance(min_value, numbers.Number)
max_is_number = isinstance(max_value, numbers.Number)
if not min_is_number or not max_is_number:
message = (
f'{name} values must be numbers, not {nums_range}')
raise ValueError(message)
if min_value > max_value:
raise ValueError(
f'If {name} is a sequence, the second value must be'
f' equal or greater than the first, but it is {nums_range}')
if min_constraint is not None and min_value < min_constraint:
raise ValueError(
f'If {name} is a sequence, the first value must be greater'
f' than {min_constraint}, but it is {min_value}'
)
if max_constraint is not None and max_value > max_constraint:
raise ValueError(
f'If {name} is a sequence, the second value must be smaller'
f' than {max_constraint}, but it is {max_value}'
)
if type_constraint is not None:
min_type_ok = isinstance(min_value, type_constraint)
max_type_ok = isinstance(max_value, type_constraint)
if not min_type_ok or not max_type_ok:
raise ValueError(
f'If "{name}" is a sequence, its values must be of'
f' type "{type_constraint}", not "{type(nums_range)}"'
)
return nums_range
@staticmethod
def parse_interpolation(interpolation: str) -> str:
if not isinstance(interpolation, str):
itype = type(interpolation)
raise TypeError(f'Interpolation must be a string, not {itype}')
interpolation = interpolation.lower()
is_string = isinstance(interpolation, str)
supported_values = [key.name.lower() for key in Interpolation]
is_supported = interpolation.lower() in supported_values
if is_string and is_supported:
return interpolation
message = (
f'Interpolation "{interpolation}" of type {type(interpolation)}'
f' must be a string among the supported values: {supported_values}'
)
raise ValueError(message)
@staticmethod
def parse_probability(probability: float) -> float:
is_number = isinstance(probability, numbers.Number)
if not (is_number and 0 <= probability <= 1):
message = (
'Probability must be a number in [0, 1],'
f' not {probability}'
)
raise ValueError(message)
return probability
@staticmethod
def parse_include_and_exclude(
include: TypeKeys = None,
exclude: TypeKeys = None,
) -> Tuple[TypeKeys, TypeKeys]:
if include is not None and exclude is not None:
raise ValueError('Include and exclude cannot both be specified')
return include, exclude
@staticmethod
def nib_to_sitk(data: TypeData, affine: TypeData) -> sitk.Image:
return nib_to_sitk(data, affine)
@staticmethod
def sitk_to_nib(image: sitk.Image) -> Tuple[torch.Tensor, np.ndarray]:
return sitk_to_nib(image)
def _get_reproducing_arguments(self):
"""
Return a dictionary with the arguments that would be necessary to
reproduce the transform exactly.
"""
reproducing_arguments = {
'include': self.include,
'exclude': self.exclude,
'copy': self.copy,
}
args_names = {name: getattr(self, name) for name in self.args_names}
reproducing_arguments.update(args_names)
return reproducing_arguments
def is_invertible(self):
return hasattr(self, 'invert_transform')
def inverse(self):
if not self.is_invertible():
raise RuntimeError(f'{self.name} is not invertible')
new = copy.deepcopy(self)
new.invert_transform = not self.invert_transform
return new
@staticmethod
@contextmanager
def _use_seed(seed):
"""Perform an operation using a specific seed for the PyTorch RNG"""
torch_rng_state = torch.random.get_rng_state()
torch.manual_seed(seed)
yield
torch.random.set_rng_state(torch_rng_state)
@staticmethod
def get_sitk_interpolator(interpolation: str) -> int:
return get_sitk_interpolator(interpolation)
@staticmethod
def parse_bounds(bounds_parameters: TypeBounds) -> TypeSixBounds:
try:
bounds_parameters = tuple(bounds_parameters)
except TypeError:
bounds_parameters = (bounds_parameters,)
# Check that numbers are integers
for number in bounds_parameters:
if not isinstance(number, (int, np.integer)) or number < 0:
message = (
'Bounds values must be integers greater or equal to zero,'
f' not "{bounds_parameters}" of type {type(number)}'
)
raise ValueError(message)
bounds_parameters = tuple(int(n) for n in bounds_parameters)
bounds_parameters_length = len(bounds_parameters)
if bounds_parameters_length == 6:
return bounds_parameters
if bounds_parameters_length == 1:
return 6 * bounds_parameters
if bounds_parameters_length == 3:
return tuple(np.repeat(bounds_parameters, 2).tolist())
message = (
'Bounds parameter must be an integer or a tuple of'
f' 3 or 6 integers, not {bounds_parameters}'
)
raise ValueError(message)
@staticmethod
def ones(tensor: torch.Tensor) -> torch.Tensor:
return torch.ones_like(tensor, dtype=torch.bool)
@staticmethod
def mean(tensor: torch.Tensor) -> torch.Tensor:
mask = tensor > tensor.float().mean()
return mask
def get_mask_from_masking_method(
self,
masking_method: TypeMaskingMethod,
subject: Subject,
tensor: torch.Tensor,
) -> torch.Tensor:
if masking_method is None:
return self.ones(tensor)
elif callable(masking_method):
return masking_method(tensor)
elif type(masking_method) is str:
in_subject = masking_method in subject
if in_subject and isinstance(subject[masking_method], LabelMap):
return subject[masking_method].data.bool()
masking_method = masking_method.capitalize()
if masking_method in anat_axes:
return self.get_mask_from_anatomical_label(
masking_method, tensor)
elif type(masking_method) in (tuple, list, int):
return self.get_mask_from_bounds(masking_method, tensor)
message = (
'Masking method parameter must be a function, a label map name,'
f' an anatomical label: {anat_axes}, or a bounds parameter'
' (an int, tuple of 3 ints, or tuple of 6 ints),'
f' not "{masking_method}" of type "{type(masking_method)}"'
)
raise ValueError(message)
@staticmethod
def get_mask_from_anatomical_label(
anatomical_label: str,
tensor: torch.Tensor,
) -> torch.Tensor:
anatomical_label = anatomical_label.title()
if anatomical_label.title() not in anat_axes:
message = (
f'Anatomical label must be one of {anat_axes}'
f' not {anatomical_label}'
)
raise ValueError(message)
mask = torch.zeros_like(tensor, dtype=torch.bool)
_, width, height, depth = tensor.shape
if anatomical_label == 'Right':
mask[:, width // 2:] = True
elif anatomical_label == 'Left':
mask[:, :width // 2] = True
elif anatomical_label == 'Anterior':
mask[:, :, height // 2:] = True
elif anatomical_label == 'Posterior':
mask[:, :, :height // 2] = True
elif anatomical_label == 'Superior':
mask[:, :, :, depth // 2:] = True
elif anatomical_label == 'Inferior':
mask[:, :, :, :depth // 2] = True
return mask
@staticmethod
def get_mask_from_bounds(
self,
bounds_parameters: TypeBounds,
tensor: torch.Tensor,
) -> torch.Tensor:
bounds_parameters = self.parse_bounds(bounds_parameters)
low = bounds_parameters[::2]
high = bounds_parameters[1::2]
i0, j0, k0 = low
i1, j1, k1 = np.array(tensor.shape[1:]) - high
mask = torch.zeros_like(tensor, dtype=torch.bool)
mask[:, i0:i1, j0:j1, k0:k1] = True
return mask
| 39.961145 | 85 | 0.591116 |
8ac97637073b5038f3c9453a6c1e7e581d9602b6 | 10,344 | py | Python | docs/examples/use_cases/tensorflow/resnet-n/nvutils/runner.py | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2022-02-17T19:54:05.000Z | 2022-02-17T19:54:08.000Z | docs/examples/use_cases/tensorflow/resnet-n/nvutils/runner.py | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | docs/examples/use_cases/tensorflow/resnet-n/nvutils/runner.py | L-Net-1992/DALI | 982224d8b53e1156ae092f73f5a7d600982a1eb9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from builtins import range
from nvutils import image_processing
from nvutils import common
import tensorflow as tf
import tensorflow.keras as keras
import os
import time
import re
import numpy as np
import horovod.tensorflow.keras as hvd
from tensorflow.python.keras.optimizer_v2 import (gradient_descent as
gradient_descent_v2)
from tensorflow.python.keras import backend
print(tf.__version__)
if tf.__version__ > "2.1.0":
if tf.__version__ >= "2.4.0":
from tensorflow.python.keras.mixed_precision import device_compatibility_check
else:
from tensorflow.python.keras.mixed_precision.experimental import device_compatibility_check
device_compatibility_check._logged_compatibility_check = True
class _ProfileKerasFitCallback(keras.callbacks.Callback):
def __init__(self, batch_size, display_every=10):
self.batch_size = batch_size * hvd.size()
self.log_steps = display_every
self.global_steps = 0
def on_batch_begin(self, batch, logs=None):
self.global_steps += 1
if self.global_steps == 1:
self.start_time = time.time()
def on_batch_end(self, batch, logs=None):
"""Records elapse time of the batch and calculates examples per second."""
if self.global_steps % self.log_steps == 0:
timestamp = time.time()
elapsed_time = timestamp - self.start_time
examples_per_second = (self.batch_size * self.log_steps) / elapsed_time
if hvd.rank() == 0:
print("global_step: %d images_per_sec: %.1f" % (self.global_steps,
examples_per_second))
self.start_time = timestamp
def on_epoch_begin(self, epoch, logs=None):
self.epoch_start = time.time()
def on_epoch_end(self, epoch, logs=None):
epoch_run_time = time.time() - self.epoch_start
if hvd.rank() == 0:
print("epoch: %d time_taken: %.1f" % (epoch, epoch_run_time))
def train(model_func, params):
image_width = params['image_width']
image_height = params['image_height']
image_format = params['image_format']
distort_color = params['distort_color']
momentum = params['momentum']
loss_scale = params['loss_scale']
data_dir = params['data_dir']
data_idx_dir = params['data_idx_dir']
batch_size = params['batch_size']
num_iter = params['num_iter']
iter_unit = params['iter_unit']
log_dir = params['log_dir']
export_dir = params['export_dir']
tensorboard_dir = params['tensorboard_dir']
display_every = params['display_every']
precision = params['precision']
dali_mode = params['dali_mode']
use_xla = params['use_xla']
if data_dir is not None:
file_format = os.path.join(data_dir, '%s-*')
train_files = sorted(tf.io.gfile.glob(file_format % 'train'))
valid_files = sorted(tf.io.gfile.glob(file_format % 'validation'))
num_train_samples = common.get_num_records(train_files)
num_valid_samples = common.get_num_records(valid_files)
else:
num_train_samples = 1281982
num_valid_samples = 5000
train_idx_files = None
valid_idx_files = None
if data_idx_dir is not None:
file_format = os.path.join(data_idx_dir, '%s-*')
train_idx_files = sorted(tf.io.gfile.glob(file_format % 'train'))
valid_idx_files = sorted(tf.io.gfile.glob(file_format % 'validation'))
if iter_unit.lower() == 'epoch':
num_epochs = num_iter
nstep_per_epoch = num_train_samples // (batch_size * hvd.size())
nstep_per_valid = num_valid_samples // (batch_size * hvd.size())
else:
assert iter_unit.lower() == 'batch'
num_epochs = 1
nstep_per_epoch = min(num_iter,
num_train_samples // (batch_size * hvd.size()))
nstep_per_valid = min(10, num_valid_samples // (batch_size * hvd.size()))
initial_epoch = 0
if log_dir:
# We save check points only when using the real data.
assert data_dir, "--data_dir cannot be empty when using --log_dir"
assert os.path.exists(log_dir)
ckpt_format = log_dir +"/model-{epoch:02d}-{val_top1:.2f}.hdf5"
# Looks for the most recent checkpoint and sets the initial epoch from it.
for filename in os.listdir(log_dir):
if filename.startswith('model-'):
initial_epoch = max(int(re.findall(r'\d+', filename)[0]),
initial_epoch)
if tensorboard_dir:
assert os.path.exists(tensorboard_dir)
if export_dir:
assert os.path.exists(export_dir)
save_format = export_dir +"/saved_model_rn50.h5"
if use_xla:
tf.config.optimizer.set_jit(True)
# Horovod: pin GPU to be used to process local rank (one GPU per process)
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
if gpus:
tf.config.experimental.set_visible_devices(gpus[hvd.local_rank()], 'GPU')
if precision == 'fp16':
if tf.__version__ >= "2.4.0":
policy = keras.mixed_precision.Policy('mixed_float16')
keras.mixed_precision.set_global_policy(policy)
else:
policy = keras.mixed_precision.experimental.Policy('mixed_float16', loss_scale)
keras.mixed_precision.experimental.set_policy(policy)
lr_schedule = common.create_piecewise_constant_decay_with_warmup(
batch_size=batch_size * hvd.size(),
epoch_size=num_train_samples,
warmup_epochs=common.LR_SCHEDULE[0][1],
boundaries=list(p[1] for p in common.LR_SCHEDULE[1:]),
multipliers=list(p[0] for p in common.LR_SCHEDULE),
compute_lr_on_cpu=True)
opt = keras.optimizers.SGD(learning_rate=lr_schedule, momentum=momentum)
# Horovod: add Horovod DistributedOptimizer. We use a modified version to
# support the custom learning rate schedule.
opt = hvd.DistributedOptimizer(opt)
if tf.__version__ >= "2.4.0" and precision == 'fp16':
opt = keras.mixed_precision.LossScaleOptimizer(opt, dynamic=False,
initial_scale=loss_scale)
backend.set_image_data_format(image_format)
dtype='float16' if precision == 'fp16' else 'float32'
backend.set_floatx(dtype)
model = model_func(num_classes=image_processing.NUM_CLASSES)
loss_func ='sparse_categorical_crossentropy',
top5 = tf.keras.metrics.SparseTopKCategoricalAccuracy(k=5, name='top5')
top1 = tf.keras.metrics.SparseTopKCategoricalAccuracy(k=1, name='top1')
# Horovod: Specify `experimental_run_tf_function=False` to ensure TensorFlow
# uses hvd.DistributedOptimizer() to compute gradients. However, this option
# will disable the overlapping of the data loading and compute and hurt the
# performace if the model is not under the scope of distribution strategy
# scope.
model.compile(optimizer=opt, loss=loss_func, metrics=[top1, top5],
experimental_run_tf_function=False)
training_hooks = []
training_hooks.append(hvd.callbacks.BroadcastGlobalVariablesCallback(0))
training_hooks.append(_ProfileKerasFitCallback(batch_size, display_every))
if log_dir and hvd.rank() == 0:
ckpt_callback = keras.callbacks.ModelCheckpoint(ckpt_format,
monitor='val_top1', verbose=1, save_best_only=False,
save_weights_only=False, save_frequency=1)
training_hooks.append(ckpt_callback)
if tensorboard_dir and hvd.rank() == 0:
tensorboard_callback = tf.keras.callbacks.TensorBoard(
log_dir=tensorboard_dir)
training_hooks.append(tensorboard_callback)
if data_dir is not None:
num_preproc_threads = params['dali_threads'] if dali_mode else 10
train_input = image_processing.image_set(train_files, batch_size,
image_height, image_width, training=True, distort_color=distort_color,
deterministic=False, num_threads=num_preproc_threads,
use_dali=dali_mode, idx_filenames=train_idx_files)
valid_input = image_processing.image_set(valid_files, batch_size,
image_height, image_width, training=False, distort_color=False,
deterministic=False, num_threads=num_preproc_threads,
use_dali=dali_mode, idx_filenames=valid_idx_files)
if dali_mode:
train_input = train_input.get_device_dataset()
valid_input = valid_input.get_device_dataset()
valid_params = {'validation_data': valid_input,
'validation_steps': nstep_per_valid,
'validation_freq': 1}
else:
train_input = image_processing.fake_image_set(batch_size, image_height,
image_width)
valid_params = {}
try:
verbose = 2 if hvd.rank() == 0 else 0
model.fit(train_input, epochs=num_epochs, callbacks=training_hooks,
steps_per_epoch=nstep_per_epoch, verbose=verbose,
initial_epoch=initial_epoch, **valid_params)
except KeyboardInterrupt:
print("Keyboard interrupt")
if export_dir and hvd.rank() == 0:
model.save(save_format)
print(f"The model is saved to {save_format}")
def predict(params):
image_width = params['image_width']
image_height = params['image_height']
batch_size = params['batch_size']
export_dir = params['export_dir']
assert export_dir, "--export_dir must be given."
model_path = export_dir +"/saved_model_rn50.h5"
assert os.path.exists(model_path)
model = keras.models.load_model(model_path, custom_objects={
"PiecewiseConstantDecayWithWarmup":
common.PiecewiseConstantDecayWithWarmup})
predict_input = image_processing.fake_image_set(batch_size, image_height,
image_width, with_label=False)
results = model.predict(predict_input, verbose=1, steps=3)
print(f"The loaded model predicts {results.shape[0]} images.")
| 40.564706 | 95 | 0.70901 |
1e47f8e2697ec00ec8eabb0cc8739024b54f09b2 | 3,371 | py | Python | experiments/decision_tree.py | brenowca/comp-263-essay-on-explainability | 1c7024ed77eaec5d4bea2e9626084a5cd15b13a2 | [
"MIT"
] | null | null | null | experiments/decision_tree.py | brenowca/comp-263-essay-on-explainability | 1c7024ed77eaec5d4bea2e9626084a5cd15b13a2 | [
"MIT"
] | null | null | null | experiments/decision_tree.py | brenowca/comp-263-essay-on-explainability | 1c7024ed77eaec5d4bea2e9626084a5cd15b13a2 | [
"MIT"
] | null | null | null | """
Here we describe experiments with both "vanilla" decision trees and state of the art decision tree settings for the
CIFAR 10 dataset.
"""
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
from sklearn import tree
from sklearn.metrics import classification_report
from sklearn.model_selection import RandomizedSearchCV
from os.path import join as path_join
from os import makedirs
# Setting random seed for reproducibility of the results
torch.manual_seed(0)
np.random.seed(0)
IMG_TO_FILE = True # Set this oto true if you want to store the outputs in specific files
IMG_PATH = "."
def plot_fig(name=None, **args):
if IMG_TO_FILE and name is not None:
makedirs(IMG_PATH, exist_ok=True)
plt.savefig(path_join(IMG_PATH, name), **args)
else:
plt.show(**args)
# Download and process the dataset
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
batch_size = 4
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=len(trainset), # batch_size=batch_size,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=len(testset), # batch_size=batch_size,
shuffle=False, num_workers=2)
classes = trainset.classes
#%%
# functions to show an image
def imshow(img):
img = img / 2 + 0.5 # un-normalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
#%%
# # get some random training images
# dataiter = iter(trainloader)
# images, labels = dataiter.next()
#
# # show images
# imshow(torchvision.utils.make_grid(images))
# # print labels
# print(' '.join('%5s' % classes[labels[j]] for j in range(batch_size)))
#%%
X_train, y_train = next(iter(trainloader))
X_train = X_train.reshape((X_train.shape[0], np.prod(X_train.shape[1:])))
#%%
dt = tree.DecisionTreeClassifier()
dt_fit = dt.fit(X_train, y_train)
print(f"The depth of this tree is {dt_fit.get_depth()} and it has {dt_fit.get_n_leaves()} leaves")
tree.plot_tree(dt_fit)
plt.show()
#%%
X_test, y_test = next(iter(testloader))
X_test = X_test.reshape((X_test.shape[0], np.prod(X_test.shape[1:])))
#%%
print(classification_report(y_test, dt_fit.predict(X_test), target_names=classes))
parameters = {'max_depth': (5, 10, 15, 20, 30),
#'min_samples_split': (2,3,5,10,15,20),
'min_samples_leaf': (2,5,10,15,20),
'max_features': ('sqrt', 'log2', None)}
opt_dt = RandomizedSearchCV(tree.DecisionTreeClassifier(), parameters, cv=3, n_jobs=-1, refit=True, n_iter=20)
opt_dt_fit = opt_dt.fit(X_train, y_train) # Hyper-parameter optimized DT
print(f"The depth of this tree is {opt_dt_fit.best_estimator_.get_depth()} and it has {opt_dt_fit.best_estimator_.get_n_leaves()} leaves")
tree.plot_tree(opt_dt_fit.best_estimator_)
plot_fig("opt_dt_fitted.pdf")
print(classification_report(y_test, opt_dt_fit.predict(X_test), target_names=classes))
| 35.114583 | 138 | 0.694453 |
408952df71d6d29b621a43f71bc1b402367ff9f3 | 5,340 | py | Python | src/gtk3-libhandy/leaflet/LeafletsSync.py | alexandrebarbaruiva/gui-python-gtk | 7b8e8ab05645271ae55e1e2165eefc9c8f5b0250 | [
"MIT"
] | 42 | 2020-05-09T16:23:23.000Z | 2022-03-28T13:05:32.000Z | src/gtk3-libhandy/leaflet/LeafletsSync.py | alexandrebarbaruiva/gui-python-gtk | 7b8e8ab05645271ae55e1e2165eefc9c8f5b0250 | [
"MIT"
] | 2 | 2020-05-27T19:23:54.000Z | 2022-03-08T01:42:59.000Z | src/gtk3-libhandy/leaflet/LeafletsSync.py | alexandrebarbaruiva/gui-python-gtk | 7b8e8ab05645271ae55e1e2165eefc9c8f5b0250 | [
"MIT"
] | 8 | 2020-05-09T16:23:28.000Z | 2022-03-31T22:44:45.000Z | # -*- coding: utf-8 -*-
"""Handy.Leaflet() sync."""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Handy', '1')
from gi.repository import Gtk, Gio, GObject
from gi.repository import Handy
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_title(title='Handy.Leaflet sync')
self.set_default_size(width=1366 / 2, height=768 / 2)
self.set_position(position=Gtk.WindowPosition.CENTER)
self.set_default_icon_from_file(filename='../../assets/icons/icon.png')
# Para armazenar as barras de título.
hdy_leaflet_title = Handy.Leaflet.new()
hdy_title_bar = Handy.TitleBar.new()
hdy_title_bar.add(widget=hdy_leaflet_title)
self.set_titlebar(titlebar=hdy_title_bar)
# Para armazenar as páginas.
self.hdy_leaflet_content = Handy.Leaflet.new()
self.add(widget=self.hdy_leaflet_content)
# Página 1
# Barra de título.
header_bar_page_1 = Gtk.HeaderBar.new()
header_bar_page_1.set_title(title='Handy.Leaflet')
header_bar_page_1.set_subtitle(subtitle='Página 1')
header_bar_page_1.set_show_close_button(setting=True)
hdy_leaflet_title.add(widget=header_bar_page_1)
hdy_leaflet_title.child_set(child=header_bar_page_1, name='page_1')
# Widgets
page_1 = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
page_1.set_border_width(border_width=12)
text_page_1 = (
'<span size="xx-large" weight="bold">Leaflet (Folheto)</span>\n\n'
'<span size="large">Clique no botão para ir para a página 2.</span>'
)
lbl_page_1 = Gtk.Label.new()
lbl_page_1.set_line_wrap(wrap=True)
lbl_page_1.set_markup(str=text_page_1)
page_1.pack_start(child=lbl_page_1, expand=True, fill=True, padding=0)
btn_more = Gtk.Button.new_with_label(label='Leia mais…')
btn_more.set_halign(align=Gtk.Align.CENTER)
page_1.pack_start(child=btn_more, expand=False, fill=True, padding=0)
# SizeGroup é utilizadopara definir o conteúdo de cada página
group_page_1 = Gtk.SizeGroup.new(mode=Gtk.SizeGroupMode.HORIZONTAL)
group_page_1.add_widget(widget=header_bar_page_1)
group_page_1.add_widget(widget=page_1)
self.hdy_leaflet_content.add(widget=page_1)
self.hdy_leaflet_content.child_set(child=page_1, name='page_1')
# Página 2
header_bar_page_2 = Gtk.HeaderBar.new()
header_bar_page_2.set_title(title='Handy.Leaflet')
header_bar_page_2.set_subtitle(subtitle='Página 2')
header_bar_page_2.set_show_close_button(setting=True)
hdy_leaflet_title.add(widget=header_bar_page_2)
hdy_leaflet_title.child_set(child=header_bar_page_2, name='page_2')
page_2 = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
page_2.set_border_width(border_width=12)
text_page_2 = (
'<span size="xx-large" weight="bold">Página 2</span>\n\n'
'<span size="large">Para voltar clique no botão localizado '
'na barra de título</span>'
)
lbl_page_2 = Gtk.Label.new()
lbl_page_2.set_line_wrap(wrap=True)
lbl_page_2.set_markup(str=text_page_2)
page_2.pack_start(child=lbl_page_2, expand=True, fill=True, padding=6)
btn_back = Gtk.Button.new_from_icon_name(
icon_name='go-previous-symbolic',
size=Gtk.IconSize.BUTTON,
)
header_bar_page_2.add(widget=btn_back)
group_page_2 = Gtk.SizeGroup.new(mode=Gtk.SizeGroupMode.HORIZONTAL)
group_page_2.add_widget(widget=header_bar_page_2)
group_page_2.add_widget(widget=page_2)
self.hdy_leaflet_content.add(widget=page_2)
self.hdy_leaflet_content.child_set(child=page_2, name='page_2')
# Ação dos botões.
btn_back.connect('clicked', self._show_page, page_1)
btn_more.connect('clicked', self._show_page, page_2)
# Binding e Signals!
hdy_leaflet_title.bind_property(
'folded',
btn_back,
'visible',
GObject.BindingFlags.SYNC_CREATE
)
self.hdy_leaflet_content.bind_property(
'visible-child-name',
hdy_leaflet_title,
'visible-child-name',
GObject.BindingFlags.SYNC_CREATE
)
self.hdy_leaflet_content.bind_property(
'folded',
btn_more,
'visible',
GObject.BindingFlags.SYNC_CREATE
)
self.show_all()
def _show_page(self, button, page):
self.hdy_leaflet_content.set_visible_child(page)
class Application(Gtk.Application):
def __init__(self):
super().__init__(application_id='br.natorsc.Exemplo',
flags=Gio.ApplicationFlags.FLAGS_NONE)
def do_startup(self):
Gtk.Application.do_startup(self)
def do_activate(self):
win = self.props.active_window
if not win:
win = MainWindow(application=self)
win.present()
def do_shutdown(self):
Gtk.Application.do_shutdown(self)
if __name__ == '__main__':
import sys
app = Application()
app.run(sys.argv)
| 33.797468 | 80 | 0.657491 |
64779b0b04c368bf3e472aa79e1cecc180ed24cf | 1,370 | py | Python | pkg/workloads/cortex/lib/model/__init__.py | ourobouros/cortex | 1b3aaf909816b93f6a6e3edd0da8c10891e05be9 | [
"Apache-2.0"
] | 1 | 2022-02-23T08:45:19.000Z | 2022-02-23T08:45:19.000Z | pkg/workloads/cortex/lib/model/__init__.py | ourobouros/cortex | 1b3aaf909816b93f6a6e3edd0da8c10891e05be9 | [
"Apache-2.0"
] | null | null | null | pkg/workloads/cortex/lib/model/__init__.py | ourobouros/cortex | 1b3aaf909816b93f6a6e3edd0da8c10891e05be9 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Cortex Labs, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from cortex.lib.model.model import ModelsHolder, LockedGlobalModelsGC, LockedModel, ids_to_models
from cortex.lib.model.tfs import TensorFlowServingAPI, TensorFlowServingAPIClones
from cortex.lib.model.tree import (
ModelsTree,
LockedModelsTree,
find_all_cloud_models,
)
from cortex.lib.model.type import get_models_from_api_spec, CuratedModelResources
from cortex.lib.model.validation import (
validate_models_dir_paths,
validate_model_paths,
ModelVersion,
)
from cortex.lib.model.cron import (
FileBasedModelsTreeUpdater,
FileBasedModelsGC,
find_ondisk_models_with_lock,
find_ondisk_model_ids_with_lock,
find_ondisk_model_info,
TFSModelLoader,
TFSAPIServingThreadUpdater,
find_ondisk_models,
ModelsGC,
ModelTreeUpdater,
)
| 34.25 | 97 | 0.783212 |
9410f10d9938d94a04b8128c2bdf8752bca49d8e | 6,368 | py | Python | Python/kth-largest-element-in-a-stream.py | RideGreg/LeetCode | b70818b1e6947bf29519a24f78816e022ebab59e | [
"MIT"
] | 1 | 2022-01-30T06:55:28.000Z | 2022-01-30T06:55:28.000Z | Python/kth-largest-element-in-a-stream.py | RideGreg/LeetCode | b70818b1e6947bf29519a24f78816e022ebab59e | [
"MIT"
] | null | null | null | Python/kth-largest-element-in-a-stream.py | RideGreg/LeetCode | b70818b1e6947bf29519a24f78816e022ebab59e | [
"MIT"
] | 1 | 2021-12-31T03:56:39.000Z | 2021-12-31T03:56:39.000Z | '''
Design a class to find the kth largest element in a stream. Note that it is the kth largest element
in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums,
which contains initial elements from the stream. For each call to the method KthLargest.add,
return the element representing the kth largest element in the stream.
Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums' length >= k-1 and k >= 1.
'''
# not run in Leetcode. Maintain counter on BST node.
class MyTreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.rightCnt = 0
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.root = None
for n in nums:
self.root = self.insert(self.root, n)
def add(self, val):
"""
:type val: int
:rtype: int
"""
self.root = self.insert(self.root, val)
return self.kthLargest()
def insert(self, root, v):
if not root:
root = MyTreeNode(v)
return root
p = root
while p:
if v <= p.val:
if p.left:
p = p.left
else:
p.left = MyTreeNode(v)
return root
else:
p.rightCnt += 1
if p.right:
p = p.right
else:
p.right = MyTreeNode(v)
return root
def kthLargest(self):
p, kk = self.root, self.k
while p:
if kk < p.rightCnt + 1:
p = p.right
elif kk > p.rightCnt + 1:
kk -= (p.rightCnt + 1)
p = p.left
else:
return p.val
# TLE.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class KthLargest_bst(object): # good for balanced tree
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.root = None
for n in nums:
self.root = self.insert(self.root, n)
def add(self, val):
"""
:type val: int
:rtype: int
"""
self.root = self.insert(self.root, val)
return self.kthLargest()
def insert(self, root, v):
if not root:
root = TreeNode(v)
return root
p = root
while p:
if v < p.val:
if p.left: p = p.left
else:
p.left = TreeNode(v)
return root
else:
if p.right: p = p.right
else:
p.right = TreeNode(v)
return root
''' maximum recursion depth exceeded for more than 1000 levels
if not node:
return TreeNode(v)
if v <= node.val:
node.left = self.insert(node.left, v)
else:
node.right = self.insert(node.right, v)
return node
'''
def kthLargest(self):
def pushRight(node):
while node:
stack.append(node)
node = node.right
stack = []
pushRight(self.root)
m = 0
while stack and m < self.k:
cur = stack.pop()
m += 1
pushRight(cur.left)
return cur.val
# USE THIS
# TLE. Heap is size n, so when having more numbers, slower and slower, each add O(logn + nlogk).
# Unfortunately cannot use a size-k Heap, because all numbers stream in need to be kept to get kth largest correctly.
# https://stackoverflow.com/questions/38806202/whats-the-time-complexity-of-functions-in-heapq-library
# https://stackoverflow.com/questions/29109741/what-is-the-time-complexity-of-getting-first-n-largest-elements-in-min-heap?lq=1
import heapq
class KthLargest_heapSizeN(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.h = nums
heapq.heapify(self.h)
def add(self, val):
"""
:type val: int
:rtype: int
"""
heapq.heappush(self.h, val)
return heapq.nlargest(self.k, self.h)[-1]
# Your KthLargest object will be instantiated and called as such:
obj = KthLargest(3, [4,5,8,2])
print obj.add(3) #4
print obj.add(5) #5
print obj.add(10) #5
print obj.add(9) #8
print obj.add(4) #8
import timeit
# 1.76037311554 vs 1.70498609543 vs 0.570573806763
obj = KthLargest(20, range(500,510)+range(50,60))
obj2 = KthLargest_bst(20, range(500,510)+range(50,60))
obj3 = KthLargest_heapSizeN(20, range(500,510)+range(50,60))
print timeit.timeit("for x in range(1500): obj.add(x)", "from __main__ import obj", number=1)
print timeit.timeit("for x in range(1500): obj2.add(x)", "from __main__ import obj2", number=1)
print timeit.timeit("for x in range(1500): obj3.add(x)", "from __main__ import obj3", number=1)
# skewed tree, k = 1: 3.57821202278 vs. 3.08418989182 vs. 0.032653093338
obj = KthLargest(1, [])
obj2 = KthLargest_bst(1, [])
obj3 = KthLargest_heapSizeN(1, [])
print timeit.timeit("for x in range(1500): obj.add(x)", "from __main__ import obj", number=1)
print timeit.timeit("for x in range(1500): obj2.add(x)", "from __main__ import obj2", number=1)
print timeit.timeit("for x in range(1500): obj3.add(x)", "from __main__ import obj3", number=1)
# skewed tree, k = 2: 3.24866390228 vs. 3.1738409996 vs. 0.22509598732
obj = KthLargest(2, [1])
obj2 = KthLargest_bst(2, [1])
obj3 = KthLargest_heapSizeN(2, [1])
print timeit.timeit("for x in range(1500): obj.add(x)", "from __main__ import obj", number=1)
print timeit.timeit("for x in range(1500): obj2.add(x)", "from __main__ import obj2", number=1)
print timeit.timeit("for x in range(1500): obj3.add(x)", "from __main__ import obj3", number=1)
| 30.4689 | 127 | 0.564856 |
2aa02674fef9b6f3802a50d2b1184c95701917f4 | 378 | py | Python | include/build/toolchain/get_default_posix_goma_dir.py | jackz314/libgestures | 7a91f7cba9f0c5b6abde2f2b887bb7c6b70a6245 | [
"BSD-3-Clause"
] | 19 | 2015-02-19T21:08:27.000Z | 2021-11-19T07:16:49.000Z | include/build/toolchain/get_default_posix_goma_dir.py | jackz314/libgestures | 7a91f7cba9f0c5b6abde2f2b887bb7c6b70a6245 | [
"BSD-3-Clause"
] | 8 | 2015-08-31T06:39:59.000Z | 2021-12-04T14:53:28.000Z | include/build/toolchain/get_default_posix_goma_dir.py | jackz314/libgestures | 7a91f7cba9f0c5b6abde2f2b887bb7c6b70a6245 | [
"BSD-3-Clause"
] | 10 | 2015-08-28T16:44:03.000Z | 2019-07-17T17:37:34.000Z | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script returns the default goma directory for Posix systems, which is
# relative to the user's home directory. On Windows, goma.gypi hardcodes a
# value.
import os
print '"' + os.environ['HOME'] + '/goma"'
| 31.5 | 76 | 0.740741 |
afbef633996920f3ac5eb60521b9f78082a4430d | 146 | py | Python | website-backend/ava/test.py | kbladin/ava-capture | 2fc24f4a3712f721c3a229b499631e00697209a5 | [
"BSD-3-Clause"
] | 49 | 2017-08-18T15:25:09.000Z | 2022-02-20T19:07:00.000Z | website-backend/ava/test.py | kbladin/ava-capture | 2fc24f4a3712f721c3a229b499631e00697209a5 | [
"BSD-3-Clause"
] | 50 | 2021-11-07T18:24:34.000Z | 2022-03-19T01:16:48.000Z | website-backend/ava/test.py | samqws-marketing/electronicarts_ava-capture | a04e5f9a7ee817317d0d58ce800eefc6bf4bd150 | [
"BSD-3-Clause"
] | 13 | 2017-12-04T19:33:20.000Z | 2021-07-17T02:17:00.000Z |
# testing django
def application(env, start_response):
start_response('200 OK', [('Content-type', 'text/html')])
return ["hello prod!"]
| 20.857143 | 61 | 0.664384 |
094a25dde0496034c5b57c6b5ef09119e497817f | 146 | py | Python | geolocation/types/__init__.py | sourcerer0/geolocation | 21a2932e7d85897344f4a78c429f6c06691272f0 | [
"Apache-2.0"
] | 2 | 2021-04-16T16:42:23.000Z | 2021-06-17T09:45:51.000Z | geolocation/types/__init__.py | sourcerer0/geolocation | 21a2932e7d85897344f4a78c429f6c06691272f0 | [
"Apache-2.0"
] | 13 | 2021-03-30T22:14:36.000Z | 2022-03-04T23:36:15.000Z | geolocation/types/__init__.py | sourcerer0/geolocation | 21a2932e7d85897344f4a78c429f6c06691272f0 | [
"Apache-2.0"
] | null | null | null | from geolocation.types.coordinate import Coordinate
from geolocation.types.files import ReadOnlyFile
from geolocation.types.address import Address | 48.666667 | 51 | 0.883562 |
f4cab85c71ffeb99fa70dc2e9480e064f81de1ea | 127,795 | py | Python | src/transformers/tokenization_utils_base.py | poudro/transformers | b6b2f2270fe6c32852fc1b887afe354b7b79d18c | [
"Apache-2.0"
] | null | null | null | src/transformers/tokenization_utils_base.py | poudro/transformers | b6b2f2270fe6c32852fc1b887afe354b7b79d18c | [
"Apache-2.0"
] | null | null | null | src/transformers/tokenization_utils_base.py | poudro/transformers | b6b2f2270fe6c32852fc1b887afe354b7b79d18c | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Base classes common to both the slow and the fast tokenization classes:
PreTrainedTokenizerBase (host all the user fronting encoding methodes)
Special token mixing (host the special tokens logic) and
BatchEncoding (wrap the dictionnary of output with special method for the Fast tokenizers)
"""
import copy
import json
import logging
import os
import warnings
from collections import UserDict
from enum import Enum
from typing import Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
import numpy as np
from tokenizers import AddedToken
from tokenizers import Encoding as EncodingFast
from .file_utils import (
add_end_docstrings,
cached_path,
hf_bucket_url,
is_remote_url,
is_tf_available,
is_torch_available,
torch_required,
)
if is_tf_available():
import tensorflow as tf
if is_torch_available():
import torch
logger = logging.getLogger(__name__)
VERY_LARGE_INTEGER = int(1e30) # This is used to set the max input length for a model with infinite size input
LARGE_INTEGER = int(1e20) # This is used when we need something big but slightly smaller than VERY_LARGE_INTEGER
# Define type aliases and NamedTuples
TextInput = str
PreTokenizedInput = List[str]
EncodedInput = List[int]
TextInputPair = Tuple[str, str]
PreTokenizedInputPair = Tuple[List[str], List[str]]
EncodedInputPair = Tuple[List[int], List[int]]
# Slow tokenizers used to be saved in three separated files
SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
ADDED_TOKENS_FILE = "added_tokens.json"
TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
# Fast tokenizers (provided by HuggingFace tokenizer's library) can be saved in a single file
FULL_TOKENIZER_FILE = "tokenizer.json"
class ExplicitEnum(Enum):
"""
Enum with more explicit error message for missing values.
"""
@classmethod
def _missing_(cls, value):
raise ValueError(
"%r is not a valid %s, please select one of %s"
% (value, cls.__name__, str(list(cls._value2member_map_.keys())))
)
class TruncationStrategy(ExplicitEnum):
"""
Possible values for the ``truncation`` argument in :meth:`PreTrainedTokenizerBase.__call__`.
Useful for tab-completion in an IDE.
"""
ONLY_FIRST = "only_first"
ONLY_SECOND = "only_second"
LONGEST_FIRST = "longest_first"
DO_NOT_TRUNCATE = "do_not_truncate"
class PaddingStrategy(ExplicitEnum):
"""
Possible values for the ``padding`` argument in :meth:`PreTrainedTokenizerBase.__call__`.
Useful for tab-completion in an IDE.
"""
LONGEST = "longest"
MAX_LENGTH = "max_length"
DO_NOT_PAD = "do_not_pad"
class TensorType(ExplicitEnum):
"""
Possible values for the ``return_tensors`` argument in :meth:`PreTrainedTokenizerBase.__call__`.
Useful for tab-completion in an IDE.
"""
PYTORCH = "pt"
TENSORFLOW = "tf"
NUMPY = "np"
class CharSpan(NamedTuple):
"""
Character span in the original string.
Args:
start (:obj:`int`): Index of the first character in the original string.
end (:obj:`int`): Index of the character following the last character in the original string.
"""
start: int
end: int
class TokenSpan(NamedTuple):
"""
Token span in an encoded string (list of tokens).
Args:
start (:obj:`int`): Index of the first token in the span.
end (:obj:`int`): Index of the token following the last token in the span.
"""
start: int
end: int
class BatchEncoding(UserDict):
"""
Holds the output of the :meth:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase.encode_plus`
and :meth:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase.batch_encode` methods (tokens,
attention_masks, etc).
This class is derived from a python dictionary and can be used as a dictionary. In addition, this class exposes
utility methods to map from word/character space to token space.
Args:
data (:obj:`dict`):
Dictionary of lists/arrays/tensors returned by the encode/batch_encode methods ('input_ids',
'attention_mask', etc.).
encoding (:obj:`tokenizers.Encoding` or :obj:`Sequence[tokenizers.Encoding]`, `optional`):
If the tokenizer is a fast tokenizer which outputs additional informations like mapping from word/character
space to token space the :obj:`tokenizers.Encoding` instance or list of instance (for batches) hold these
informations.
tensor_type (:obj:`Union[None, str, TensorType]`, `optional`):
You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
initialization.
prepend_batch_axis (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to add a batch axis when converting to tensors (see :obj:`tensor_type` above).
"""
def __init__(
self,
data: Optional[Dict[str, Any]] = None,
encoding: Optional[Union[EncodingFast, Sequence[EncodingFast]]] = None,
tensor_type: Union[None, str, TensorType] = None,
prepend_batch_axis: bool = False,
):
super().__init__(data)
if isinstance(encoding, EncodingFast):
encoding = [encoding]
self._encodings = encoding
self.convert_to_tensors(tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis)
@property
def is_fast(self) -> bool:
"""
:obj:`bool`: Indicate whether this :class:`~transformers.BatchEncoding` was generated from the result of a
:class:`~transformers.PreTrainedTokenizerFast` or not.
"""
return self._encodings is not None
def __getitem__(self, item: Union[int, str]) -> Union[Any, EncodingFast]:
"""
If the key is a string, returns the value of the dict associated to :obj:`key` ('input_ids',
'attention_mask', etc.).
If the key is an integer, get the :obj:`tokenizers.Encoding` for batch item with index :obj:`key`.
"""
if isinstance(item, str):
return self.data[item]
elif self._encodings is not None:
return self._encodings[item]
else:
raise KeyError(
"Indexing with integers (to access backend Encoding for a given batch index) "
"is not available when using Python based tokenizers"
)
def __getattr__(self, item: str):
try:
return self.data[item]
except KeyError:
raise AttributeError
def __getstate__(self):
return {"data": self.data, "encodings": self._encodings}
def __setstate__(self, state):
if "data" in state:
self.data = state["data"]
if "encodings" in state:
self._encodings = state["encodings"]
def keys(self):
return self.data.keys()
def values(self):
return self.data.values()
def items(self):
return self.data.items()
# After this point:
# Extended properties and methods only available for fast (Rust-based) tokenizers
# provided by HuggingFace tokenizers library.
@property
def encodings(self) -> Optional[List[EncodingFast]]:
"""
:obj:`Optional[List[tokenizers.Encoding]]`: The list all encodings from the tokenization process.
Returns :obj:`None` if the input was tokenized through Python (i.e., not a fast) tokenizer.
"""
return self._encodings
def tokens(self, batch_index: int = 0) -> List[str]:
"""
Return the list of tokens (sub-parts of the input strings after word/subword splitting and before converstion
to integer indices) at a given batch index (only works for the output of a fast tokenizer).
Args:
batch_index (:obj:`int`, `optional`, defaults to 0): The index to access in the batch.
Returns:
:obj:`List[str]`: The list of tokens at that index.
"""
if not self._encodings:
raise ValueError("tokens() is not available when using Python-based tokenizers")
return self._encodings[batch_index].tokens
def words(self, batch_index: int = 0) -> List[Optional[int]]:
"""
Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.
Args:
batch_index (:obj:`int`, `optional`, defaults to 0): The index to access in the batch.
Returns:
:obj:`List[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by
the tokenizer are mapped to :obj:`None` and other tokens are mapped to the index of their corresponding
word (several tokens will be mapped to the same word index if they are parts of that word).
"""
if not self._encodings:
raise ValueError("words() is not available when using Python-based tokenizers")
return self._encodings[batch_index].words
def token_to_word(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int:
"""
Get the index of the word corresponding (i.e. comprising) to an encoded token
in a sequence of the batch.
Can be called as:
- ``self.token_to_word(token_index)`` if batch size is 1
- ``self.token_to_word(batch_index, token_index)`` if batch size is greater than 1
This method is particularly suited when the input sequences are provided as
pre-tokenized sequences (i.e., words are defined by the user). In this case it allows
to easily associate encoded tokens with provided tokenized words.
Args:
batch_or_token_index (:obj:`int`):
Index of the sequence in the batch. If the batch only comprise one sequence,
this can be the index of the token in the sequence.
token_index (:obj:`int`, `optional`):
If a batch index is provided in `batch_or_token_index`, this can be the index
of the token in the sequence.
Returns:
:obj:`int`: Index of the word in the input sequence.
"""
if not self._encodings:
raise ValueError("token_to_word() is not available when using Python based tokenizers")
if token_index is not None:
batch_index = batch_or_token_index
else:
batch_index = 0
token_index = batch_or_token_index
if batch_index < 0:
batch_index = self._batch_size + batch_index
if token_index < 0:
token_index = self._seq_len + token_index
return self._encodings[batch_index].token_to_word(token_index)
def word_to_tokens(self, batch_or_word_index: int, word_index: Optional[int] = None) -> TokenSpan:
"""
Get the encoded token span corresponding to a word in the sequence of the batch.
Token spans are returned as a :class:`~transformers.tokenization_utils_base.TokenSpan` with:
- **start** -- Index of the first token.
- **end** -- Index of the token following the last token.
Can be called as:
- ``self.word_to_tokens(word_index)`` if batch size is 1
- ``self.word_to_tokens(batch_index, word_index)`` if batch size is greater or equal to 1
This method is particularly suited when the input sequences are provided as
pre-tokenized sequences (i.e. words are defined by the user). In this case it allows
to easily associate encoded tokens with provided tokenized words.
Args:
batch_or_word_index (:obj:`int`):
Index of the sequence in the batch. If the batch only comprises one sequence,
this can be the index of the word in the sequence.
word_index (:obj:`int`, `optional`):
If a batch index is provided in `batch_or_token_index`, this can be the index
of the word in the sequence.
Returns:
:class:`~transformers.tokenization_utils_base.TokenSpan`
Span of tokens in the encoded sequence.
"""
if not self._encodings:
raise ValueError("word_to_tokens() is not available when using Python based tokenizers")
if word_index is not None:
batch_index = batch_or_word_index
else:
batch_index = 0
word_index = batch_or_word_index
if batch_index < 0:
batch_index = self._batch_size + batch_index
if word_index < 0:
word_index = self._seq_len + word_index
return TokenSpan(*(self._encodings[batch_index].word_to_tokens(word_index)))
def token_to_chars(self, batch_or_token_index: int, token_index: Optional[int] = None) -> CharSpan:
"""
Get the character span corresponding to an encoded token in a sequence of the batch.
Character spans are returned as a :class:`~transformers.tokenization_utils_base.CharSpan` with:
- **start** -- Index of the first character in the original string associated to the token.
- **end** -- Index of the character following the last character in the original string associated to the
token.
Can be called as:
- ``self.token_to_chars(token_index)`` if batch size is 1
- ``self.token_to_chars(batch_index, token_index)`` if batch size is greater or equal to 1
Args:
batch_or_token_index (:obj:`int`):
Index of the sequence in the batch. If the batch only comprise one sequence,
this can be the index of the token in the sequence.
token_index (:obj:`int`, `optional`):
If a batch index is provided in `batch_or_token_index`, this can be the index
of the token or tokens in the sequence.
Returns:
:class:`~transformers.tokenization_utils_base.CharSpan`:
Span of characters in the original string.
"""
if not self._encodings:
raise ValueError("token_to_chars() is not available when using Python based tokenizers")
if token_index is not None:
batch_index = batch_or_token_index
else:
batch_index = 0
token_index = batch_or_token_index
return CharSpan(*(self._encodings[batch_index].token_to_chars(token_index)))
def char_to_token(self, batch_or_char_index: int, char_index: Optional[int] = None) -> int:
"""
Get the index of the token in the encoded output comprising a character
in the original string for a sequence of the batch.
Can be called as:
- ``self.char_to_token(char_index)`` if batch size is 1
- ``self.char_to_token(batch_index, char_index)`` if batch size is greater or equal to 1
This method is particularly suited when the input sequences are provided as
pre-tokenized sequences (i.e. words are defined by the user). In this case it allows
to easily associate encoded tokens with provided tokenized words.
Args:
batch_or_char_index (:obj:`int`):
Index of the sequence in the batch. If the batch only comprise one sequence,
this can be the index of the word in the sequence
char_index (:obj:`int`, `optional`):
If a batch index is provided in `batch_or_token_index`, this can be the index
of the word in the sequence.
Returns:
:obj:`int`: Index of the token.
"""
if not self._encodings:
raise ValueError("char_to_token() is not available when using Python based tokenizers")
if char_index is not None:
batch_index = batch_or_char_index
else:
batch_index = 0
char_index = batch_or_char_index
return self._encodings[batch_index].char_to_token(char_index)
def word_to_chars(self, batch_or_word_index: int, word_index: Optional[int] = None) -> CharSpan:
"""
Get the character span in the original string corresponding to given word in a sequence
of the batch.
Character spans are returned as a CharSpan NamedTuple with:
- start: index of the first character in the original string
- end: index of the character following the last character in the original string
Can be called as:
- ``self.word_to_chars(word_index)`` if batch size is 1
- ``self.word_to_chars(batch_index, word_index)`` if batch size is greater or equal to 1
Args:
batch_or_word_index (:obj:`int`):
Index of the sequence in the batch. If the batch only comprise one sequence,
this can be the index of the word in the sequence
word_index (:obj:`int`, `optional`):
If a batch index is provided in `batch_or_token_index`, this can be the index
of the word in the sequence.
Returns:
:obj:`CharSpan` or :obj:`List[CharSpan]`:
Span(s) of the associated character or characters in the string.
CharSpan are NamedTuple with:
- start: index of the first character associated to the token in the original string
- end: index of the character following the last character associated to the token in the original string
"""
if not self._encodings:
raise ValueError("word_to_chars() is not available when using Python based tokenizers")
if word_index is not None:
batch_index = batch_or_word_index
else:
batch_index = 0
word_index = batch_or_word_index
return CharSpan(*(self._encodings[batch_index].word_to_chars(word_index)))
def char_to_word(self, batch_or_char_index: int, char_index: Optional[int] = None) -> int:
"""
Get the word in the original string corresponding to a character in the original string of
a sequence of the batch.
Can be called as:
- ``self.char_to_word(char_index)`` if batch size is 1
- ``self.char_to_word(batch_index, char_index)`` if batch size is greater than 1
This method is particularly suited when the input sequences are provided as
pre-tokenized sequences (i.e. words are defined by the user). In this case it allows
to easily associate encoded tokens with provided tokenized words.
Args:
batch_or_char_index (:obj:`int`):
Index of the sequence in the batch. If the batch only comprise one sequence,
this can be the index of the character in the orginal string.
char_index (:obj:`int`, `optional`):
If a batch index is provided in `batch_or_token_index`, this can be the index
of the character in the orginal string.
Returns:
:obj:`int` or :obj:`List[int]`:
Index or indices of the associated encoded token(s).
"""
if not self._encodings:
raise ValueError("char_to_word() is not available when using Python based tokenizers")
if char_index is not None:
batch_index = batch_or_char_index
else:
batch_index = 0
char_index = batch_or_char_index
return self._encodings[batch_index].char_to_word(char_index)
def convert_to_tensors(
self, tensor_type: Optional[Union[str, TensorType]] = None, prepend_batch_axis: bool = False
):
"""
Convert the inner content to tensors.
Args:
tensor_type (:obj:`str` or :class:`~transformers.tokenization_utils_base.TensorType`, `optional`):
The type of tensors to use. If :obj:`str`, should be one of the values of the enum
:class:`~transformers.tokenization_utils_base.TensorType`. If :obj:`None`, no modification is done.
prepend_batch_axis (:obj:`int`, `optional`, defaults to :obj:`False`):
Whether or not to add the batch dimension during the conversion.
"""
if tensor_type is None:
return self
# Convert to TensorType
if not isinstance(tensor_type, TensorType):
tensor_type = TensorType(tensor_type)
# Get a function reference for the correct framework
if tensor_type == TensorType.TENSORFLOW and is_tf_available():
as_tensor = tf.constant
elif tensor_type == TensorType.PYTORCH and is_torch_available():
as_tensor = torch.tensor
elif tensor_type == TensorType.NUMPY:
as_tensor = np.asarray
else:
raise ImportError(
"Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(
tensor_type
)
)
# Do the tensor conversion in batch
for key, value in self.items():
try:
if prepend_batch_axis:
value = [value]
tensor = as_tensor(value)
# at-least2d
if tensor.ndim > 2:
tensor = tensor.squeeze(0)
elif tensor.ndim < 2:
tensor = tensor[None, :]
self[key] = tensor
except: # noqa E722
if key == "overflowing_tokens":
raise ValueError(
"Unable to create tensor returning overflowing tokens of different lengths. "
"Please see if a fast version of this tokenizer is available to have this feature available."
)
raise ValueError(
"Unable to create tensor, you should probably activate truncation and/or padding "
"with 'padding=True' 'truncation=True' to have batched tensors with the same length."
)
return self
@torch_required
def to(self, device: str) -> "BatchEncoding":
"""
Send all values to device by calling :obj:`v.to(device)` (PyTorch only).
Args:
device (:obj:`str` or :obj:`torch.device`): The device to put the tensors on.
Returns:
:class:`~transformers.BatchEncoding`:
The same instance of :class:`~transformers.BatchEncoding` after modification.
"""
self.data = {k: v.to(device) for k, v in self.data.items()}
return self
# class AddedToken(UserString):
# """ AddedToken represents a token to be added to a Tokenizer
# An AddedToken can have special options defining the way it should behave.
# Args:
# content: str:
# The content of the token
# single_word: bool
# Whether this token should only match against single word. If True,
# this token will never match inside of a word.
# lstrip: bool
# Whether this token should strip all potential whitespaces on the left side.
# If True, this token will greedily match any whitespace on the left and then strip
# them out.
# rstrip: bool
# Whether this token should strip all potential whitespaces on the right side.
# If True, this token will greedily match any whitespace on the right and then strip
# them out.
# """
# def __init__(
# self, data: str, single_word: bool = False, lstrip: bool = False, rstrip: bool = False,
# ):
# super().__init__(data)
# self._single_word = single_word
# self._lstrip = lstrip
# self._rstrip = rstrip
# def lower(self):
# return AddedToken(self.data.lower(), self._single_word, self._lstrip, self._rstrip)
class SpecialTokensMixin:
"""
A mixin derived by :class:`~transformers.PreTrainedTokenizer` and :class:`~transformers.PreTrainedTokenizerFast`
to handle specific behaviors related to special tokens. In particular, this class hold the attributes which can be
used to directly access these special tokens in a model-independant manner and allow to set and update the special
tokens.
Args:
bos_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing the beginning of a sentence.
eos_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing the end of a sentence.
unk_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing an out-of-vocabulary token.
sep_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token separating two different sentences in the same input (used by BERT for instance).
pad_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
attention mechanisms or loss computation.
cls_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing the class of the input (used by BERT for instance).
mask_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing a masked token (used by masked-language modeling pretraining objectives, like
BERT).
additional_special_tokens (tuple or list of :obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A tuple or a list of additional special tokens.
"""
SPECIAL_TOKENS_ATTRIBUTES = [
"bos_token",
"eos_token",
"unk_token",
"sep_token",
"pad_token",
"cls_token",
"mask_token",
"additional_special_tokens",
]
def __init__(self, verbose=True, **kwargs):
self._bos_token = None
self._eos_token = None
self._unk_token = None
self._sep_token = None
self._pad_token = None
self._cls_token = None
self._mask_token = None
self._pad_token_type_id = 0
self._additional_special_tokens = []
self.verbose = verbose
# We directly set the hidden value to allow initialization with special tokens
# which are not yet in the vocabulary. Necesssary for serialization/de-serialization
# TODO clean this up at some point (probably by sitching to fast tokenizers)
for key, value in kwargs.items():
if key in self.SPECIAL_TOKENS_ATTRIBUTES:
if key == "additional_special_tokens":
assert isinstance(value, (list, tuple)), f"Value {value} is not a list or tuple"
assert all(isinstance(t, str) for t in value), "One of the tokens is not a string"
setattr(self, key, value)
elif isinstance(value, (str, AddedToken)):
setattr(self, key, value)
else:
raise TypeError(
"special token {} has to be either str or AddedToken but got: {}".format(key, type(value))
)
def sanitize_special_tokens(self) -> int:
"""
Make sure that all the special tokens attributes of the tokenizer (:obj:`tokenizer.mask_token`,
:obj:`tokenizer.cls_token`, etc.) are in the vocabulary.
Add the missing ones to the vocabulary if needed.
Return:
:obj:`int`: The number of tokens added in the vocaulary during the operation.
"""
return self.add_tokens(self.all_special_tokens_extended, special_tokens=True)
def add_special_tokens(self, special_tokens_dict: Dict[str, Union[str, AddedToken]]) -> int:
"""
Add a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If
special tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the
current vocabulary).
Using : obj:`add_special_tokens` will ensure your special tokens can be used in several ways:
- Special tokens are carefully handled by the tokenizer (they are never split).
- You can easily refer to special tokens using tokenizer class attributes like :obj:`tokenizer.cls_token`. This
makes it easy to develop model-agnostic training and fine-tuning scripts.
When possible, special tokens are already registered for provided pretrained models (for instance
:class:`~transformers.BertTokenizer` :obj:`cls_token` is already registered to be :obj`'[CLS]'` and XLM's one
is also registered to be :obj:`'</s>'`).
Args:
special_tokens_dict (dictionary `str` to `str` or :obj:`tokenizers.AddedToken`):
Keys should be in the list of predefined special attributes: [``bos_token``, ``eos_token``,
``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``, ``mask_token``,
``additional_special_tokens``].
Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer
assign the index of the ``unk_token`` to them).
Returns:
:obj:`int`: Number of tokens added to the vocabulary.
Examples::
# Let's see how to add a new classification token to GPT-2
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2Model.from_pretrained('gpt2')
special_tokens_dict = {'cls_token': '<CLS>'}
num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
print('We have added', num_added_toks, 'tokens')
# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))
assert tokenizer.cls_token == '<CLS>'
"""
if not special_tokens_dict:
return 0
added_tokens = 0
for key, value in special_tokens_dict.items():
assert key in self.SPECIAL_TOKENS_ATTRIBUTES, f"Key {key} is not a special token"
if self.verbose:
logger.info("Assigning %s to the %s key of the tokenizer", value, key)
setattr(self, key, value)
if key == "additional_special_tokens":
assert isinstance(value, (list, tuple)) and all(
isinstance(t, (str, AddedToken)) for t in value
), f"Tokens {value} for key {key} should all be str or AddedToken instances"
added_tokens += self.add_tokens(value, special_tokens=True)
else:
assert isinstance(
value, (str, AddedToken)
), f"Token {value} for key {key} should be a str or an AddedToken instance"
added_tokens += self.add_tokens([value], special_tokens=True)
return added_tokens
def add_tokens(
self, new_tokens: Union[str, AddedToken, List[Union[str, AddedToken]]], special_tokens: bool = False
) -> int:
"""
Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
it with indices starting from length of the current vocabulary.
Args:
new_tokens (:obj:`str`, :obj:`tokenizers.AddedToken` or a list of `str` or :obj:`tokenizers.AddedToken`):
Tokens are only added if they are not already in the vocabulary. :obj:`tokenizers.AddedToken` wraps a
string token to let you personalize its behavior: whether this token should only match against a single
word, whether this token should strip all potential whitespaces on the left side, whether this token
should strip all potential whitespaces on the right side, etc.
special_token (:obj:`bool`, `optional`, defaults to :obj:`False`):
Can be used to specify if the token is a special token. This mostly change the normalization behavior
(special tokens like CLS or [MASK] are usually not lower-cased for instance).
See details for :obj:`tokenizers.AddedToken` in HuggingFace tokenizers library.
Returns:
:obj:`int`: Number of tokens added to the vocabulary.
Examples::
# Let's see how to increase the vocabulary of Bert model and tokenizer
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
num_added_toks = tokenizer.add_tokens(['new_tok1', 'my_new-tok2'])
print('We have added', num_added_toks, 'tokens')
# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))
"""
if not new_tokens:
return 0
if not isinstance(new_tokens, (list, tuple)):
new_tokens = [new_tokens]
return self._add_tokens(new_tokens, special_tokens=special_tokens)
@property
def bos_token(self) -> str:
"""
:obj:`str`: Beginning of sentence token. Log an error if used while not having been set.
"""
if self._bos_token is None and self.verbose:
logger.error("Using bos_token, but it is not set yet.")
return None
return str(self._bos_token)
@property
def eos_token(self) -> str:
"""
:obj:`str`: End of sentence token. Log an error if used while not having been set.
"""
if self._eos_token is None and self.verbose:
logger.error("Using eos_token, but it is not set yet.")
return None
return str(self._eos_token)
@property
def unk_token(self) -> str:
"""
:obj:`str`: Unknown token. Log an error if used while not having been set.
"""
if self._unk_token is None and self.verbose:
logger.error("Using unk_token, but it is not set yet.")
return None
return str(self._unk_token)
@property
def sep_token(self) -> str:
"""
:obj:`str`: Separation token, to separate context and query in an input sequence.
Log an error if used while not having been set.
"""
if self._sep_token is None and self.verbose:
logger.error("Using sep_token, but it is not set yet.")
return None
return str(self._sep_token)
@property
def pad_token(self) -> str:
"""
:obj:`str`: Padding token. Log an error if used while not having been set.
"""
if self._pad_token is None and self.verbose:
logger.error("Using pad_token, but it is not set yet.")
return None
return str(self._pad_token)
@property
def cls_token(self) -> str:
"""
:obj:`str`: Classification token, to extract a summary of an input sequence leveraging self-attention along
the full depth of the model. Log an error if used while not having been set.
"""
if self._cls_token is None and self.verbose:
logger.error("Using cls_token, but it is not set yet.")
return None
return str(self._cls_token)
@property
def mask_token(self) -> str:
"""
:obj:`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while
not having been set.
"""
if self._mask_token is None and self.verbose:
logger.error("Using mask_token, but it is not set yet.")
return None
return str(self._mask_token)
@property
def additional_special_tokens(self) -> List[str]:
"""
:obj:`List[str]`: All the additional special tokens you may want to use. Log an error if used while not having
been set.
"""
if self._additional_special_tokens is None and self.verbose:
logger.error("Using additional_special_tokens, but it is not set yet.")
return None
return [str(tok) for tok in self._additional_special_tokens]
@bos_token.setter
def bos_token(self, value):
self._bos_token = value
@eos_token.setter
def eos_token(self, value):
self._eos_token = value
@unk_token.setter
def unk_token(self, value):
self._unk_token = value
@sep_token.setter
def sep_token(self, value):
self._sep_token = value
@pad_token.setter
def pad_token(self, value):
self._pad_token = value
@cls_token.setter
def cls_token(self, value):
self._cls_token = value
@mask_token.setter
def mask_token(self, value):
self._mask_token = value
@additional_special_tokens.setter
def additional_special_tokens(self, value):
self._additional_special_tokens = value
@property
def bos_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the beginning of sentence token in the vocabulary. Returns :obj:`None` if the token
has not been set.
"""
if self._bos_token is None:
return None
return self.convert_tokens_to_ids(self.bos_token)
@property
def eos_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the end of sentence token in the vocabulary. Returns :obj:`None` if the token has
not been set.
"""
if self._eos_token is None:
return None
return self.convert_tokens_to_ids(self.eos_token)
@property
def unk_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the unknown token in the vocabulary. Returns :obj:`None` if the token has not been
set.
"""
if self._unk_token is None:
return None
return self.convert_tokens_to_ids(self.unk_token)
@property
def sep_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the separation token in the vocabulary, to separate context and query in an input
sequence. Returns :obj:`None` if the token has not been set.
"""
if self._sep_token is None:
return None
return self.convert_tokens_to_ids(self.sep_token)
@property
def pad_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the padding token in the vocabulary. Returns :obj:`None` if the token has not been
set.
"""
if self._pad_token is None:
return None
return self.convert_tokens_to_ids(self.pad_token)
@property
def pad_token_type_id(self) -> int:
"""
:obj:`int`: Id of the padding token type in the vocabulary.
"""
return self._pad_token_type_id
@property
def cls_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the classification token in the vocabulary, to extract a summary of an input
sequence leveraging self-attention along the full depth of the model.
Returns :obj:`None` if the token has not been set.
"""
if self._cls_token is None:
return None
return self.convert_tokens_to_ids(self.cls_token)
@property
def mask_token_id(self) -> Optional[int]:
"""
:obj:`Optional[int]`: Id of the mask token in the vocabulary, used when training a model with masked-language
modeling. Returns :obj:`None` if the token has not been set.
"""
if self._mask_token is None:
return None
return self.convert_tokens_to_ids(self.mask_token)
@property
def additional_special_tokens_ids(self) -> List[int]:
"""
:obj:`List[int]`: Ids of all the additional special tokens in the vocabulary.
Log an error if used while not having been set.
"""
return self.convert_tokens_to_ids(self.additional_special_tokens)
@property
def special_tokens_map(self) -> Dict[str, Union[str, List[str]]]:
"""
:obj:`Dict[str, Union[str, List[str]]]`: A dictionary mapping special token class attributes
(:obj:`cls_token`, :obj:`unk_token`, etc.) to their values (:obj:`'<unk>'`, :obj:`'<cls>'`, etc.).
Convert potential tokens of :obj:`tokenizers.AddedToken` type to string.
"""
set_attr = {}
for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
attr_value = getattr(self, "_" + attr)
if attr_value:
set_attr[attr] = str(attr_value)
return set_attr
@property
def special_tokens_map_extended(self) -> Dict[str, Union[str, AddedToken, List[Union[str, AddedToken]]]]:
"""
:obj:`Dict[str, Union[str, tokenizers.AddedToken, List[Union[str, tokenizers.AddedToken]]]]`: A dictionary
mapping special token class attributes (:obj:`cls_token`, :obj:`unk_token`, etc.) to their values
(:obj:`'<unk>'`, :obj:`'<cls>'`, etc.).
Don't convert tokens of :obj:`tokenizers.AddedToken` type to string so they can be used to control more finely
how special tokens are tokenized.
"""
set_attr = {}
for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
attr_value = getattr(self, "_" + attr)
if attr_value:
set_attr[attr] = attr_value
return set_attr
@property
def all_special_tokens(self) -> List[str]:
"""
:obj:`List[str]`: All the special tokens (:obj:`'<unk>'`, :obj:`'<cls>'`, etc.) mapped to class attributes.
Convert tokens of :obj:`tokenizers.AddedToken` type to string.
"""
all_toks = [str(s) for s in self.all_special_tokens_extended]
return all_toks
@property
def all_special_tokens_extended(self) -> List[Union[str, AddedToken]]:
"""
:obj:`List[Union[str, tokenizers.AddedToken]]`: All the special tokens (:obj:`'<unk>'`, :obj:`'<cls>'`, etc.)
mapped to class attributes.
Don't convert tokens of :obj:`tokenizers.AddedToken` type to string so they can be used to control more finely
how special tokens are tokenized.
"""
all_toks = []
set_attr = self.special_tokens_map_extended
for attr_value in set_attr.values():
all_toks = all_toks + (list(attr_value) if isinstance(attr_value, (list, tuple)) else [attr_value])
all_toks = list(set(all_toks))
return all_toks
@property
def all_special_ids(self) -> List[int]:
"""
:obj:`List[int]`: List the ids of the special tokens(:obj:`'<unk>'`, :obj:`'<cls>'`, etc.) mapped to class
attributes.
"""
all_toks = self.all_special_tokens
all_ids = self.convert_tokens_to_ids(all_toks)
return all_ids
ENCODE_KWARGS_DOCSTRING = r"""
add_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether or not to encode the sequences with the special tokens relative to their model.
padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`False`):
Activates and controls padding. Accepts the following values:
* :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a
single sequence if provided).
* :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
maximum acceptable input length for the model if that argument is not provided.
* :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
different lengths).
truncation (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.TruncationStrategy`, `optional`, defaults to :obj:`False`):
Activates and controls truncation. Accepts the following values:
* :obj:`True` or :obj:`'longest_first'`: Truncate to a maximum length specified with the argument
:obj:`max_length` or to the maximum acceptable input length for the model if that argument is not
provided. This will truncate token by token, removing a token from the longest sequence in the pair
if a pair of sequences (or a batch of pairs) is provided.
* :obj:`'only_first'`: Truncate to a maximum length specified with the argument :obj:`max_length` or to
the maximum acceptable input length for the model if that argument is not provided. This will only
truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
* :obj:`'only_second'`: Truncate to a maximum length specified with the argument :obj:`max_length` or
to the maximum acceptable input length for the model if that argument is not provided. This will only
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
* :obj:`False` or :obj:`'do_not_truncate'` (default): No truncation (i.e., can output batch with
sequence lengths greater than the model maximum admissible input size).
max_length (:obj:`int`, `optional`):
Controls the maximum length to use by one of the truncation/padding parameters.
If left unset or set to :obj:`None`, this will use the predefined model maximum length if a maximum
length is required by one of the truncation/padding parameters. If the model has no specific maximum
input length (like XLNet) truncation/padding to a maximum length will be deactivated.
stride (:obj:`int`, `optional`, defaults to 0):
If set to a number along with :obj:`max_length`, the overflowing tokens returned when
:obj:`return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
returned to provide some overlap between truncated and overflowing sequences. The value of this
argument defines the number of overlapping tokens.
is_pretokenized (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not the input is already tokenized.
pad_to_multiple_of (:obj:`int`, `optional`):
If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).
return_tensors (:obj:`str` or :class:`~transformers.tokenization_utils_base.TensorType`, `optional`):
If set, will return tensors instead of list of python integers. Acceptable values are:
* :obj:`'tf'`: Return TensorFlow :obj:`tf.constant` objects.
* :obj:`'pt'`: Return PyTorch :obj:`torch.Tensor` objects.
* :obj:`'np'`: Return Numpy :obj:`np.ndarray` objects.
"""
ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
return_token_type_ids (:obj:`bool`, `optional`):
Whether to return token type IDs. If left to the default, will return the token type IDs according
to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
`What are token type IDs? <../glossary.html#token-type-ids>`__
return_attention_mask (:obj:`bool`, `optional`):
Whether to return the attention mask. If left to the default, will return the attention mask according
to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
`What are attention masks? <../glossary.html#attention-mask>`__
return_overflowing_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to return overflowing token sequences.
return_special_tokens_mask (:obj:`bool`, `optional`, defaults to :obj:`False`):
Wheter or not to return special tokens mask information.
return_offsets_mapping (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to return :obj:`(char_start, char_end)` for each token.
This is only available on fast tokenizers inheriting from
:class:`~transformers.PreTrainedTokenizerFast`, if using Python's tokenizer, this method will raise
:obj:`NotImplementedError`.
return_length (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to return the lengths of the encoded inputs.
verbose (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether or not to print informations and warnings.
**kwargs: passed to the :obj:`self.tokenize()` method
Return:
:class:`~transformers.BatchEncoding`: A :class:`~transformers.BatchEncoding` with the following fields:
- **input_ids** -- List of token ids to be fed to a model.
`What are input IDs? <../glossary.html#input-ids>`__
- **token_type_ids** -- List of token type ids to be fed to a model (when :obj:`return_token_type_ids=True`
or if `"token_type_ids"` is in :obj:`self.model_input_names`).
`What are token type IDs? <../glossary.html#token-type-ids>`__
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
:obj:`return_attention_mask=True` or if `"attention_mask"` is in :obj:`self.model_input_names`).
`What are attention masks? <../glossary.html#attention-mask>`__
- **overflowing_tokens** -- List of overflowing tokens sequences (when a :obj:`max_length` is specified and
:obj:`return_overflowing_tokens=True`).
- **num_truncated_tokens** -- Number of tokens truncated (when a :obj:`max_length` is specified and
:obj:`return_overflowing_tokens=True`).
- **special_tokens_mask** -- List of 0s and 1s, with 0 specifying added special tokens and 1 specifying
regual sequence tokens (when :obj:`add_special_tokens=True` and :obj:`return_special_tokens_mask=True`).
- **length** -- The length of the inputs (when :obj:`return_length=True`)
"""
INIT_TOKENIZER_DOCSTRING = r"""
Class attributes (overridden by derived classes)
- **vocab_files_names** (:obj:`Dict[str, str]`) -- A ditionary with, as keys, the ``__init__`` keyword name of
each vocabulary file required by the model, and as associated values, the filename for saving the associated
file (string).
- **pretrained_vocab_files_map** (:obj:`Dict[str, Dict[str, str]]`) -- A dictionary of dictionaries, with the
high-level keys being the ``__init__`` keyword name of each vocabulary file required by the model, the
low-level being the :obj:`short-cut-names` of the pretrained models with, as associated values, the
:obj:`url` to the associated pretrained vocabulary file.
- **max_model_input_sizes** (:obj:`Dict[str, Optinal[int]]`) -- A dictionary with, as keys, the
:obj:`short-cut-names` of the pretrained models, and as associated values, the maximum length of the sequence
inputs of this model, or :obj:`None` if the model has no maximum input size.
- **pretrained_init_configuration** (:obj:`Dict[str, Dict[str, Any]]`) -- A dictionary with, as keys, the
:obj:`short-cut-names` of the pretrained models, and as associated values, a dictionnary of specific
arguments to pass to the ``__init__`` method of the tokenizer class for this pretrained model when loading the
tokenizer with the :meth:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained`
method.
- **model_input_names** (:obj:`List[str]`) -- A list of inputs expected in the forward pass of the model.
- **padding_side** (:obj:`str`) -- The default value for the side on which the model should have padding
applied. Should be :obj:`'right'` or :obj:`'left'`.
Args:
model_max_length (:obj:`int`, `optional`):
The maximum length (in number of tokens) for the inputs to the transformer model.
When the tokenizer is loaded with
:meth:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained`, this will be set to
the value stored for the associated model in ``max_model_input_sizes`` (see above). If no value is
provided, will default to VERY_LARGE_INTEGER (:obj:`int(1e30)`).
padding_side: (:obj:`str`, `optional`):
The side on which the model should have padding applied. Should be selected between ['right', 'left'].
Default value is picked from the class attribute of the same name.
model_input_names (:obj:`List[string]`, `optional`):
The list of inputs accepted by the forward pass of the model (like :obj:`"token_type_ids"` or
:obj:`"attention_mask"`). Default value is picked from the class attribute of the same name.
bos_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing the beginning of a sentence. Will be associated to ``self.bos_token`` and
``self.bos_token_id``.
eos_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing the end of a sentence. Will be associated to ``self.eos_token`` and
``self.eos_token_id``.
unk_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing an out-of-vocabulary token. Will be associated to ``self.unk_token`` and
``self.unk_token_id``.
sep_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token separating two different sentences in the same input (used by BERT for instance). Will be
associated to ``self.sep_token`` and ``self.sep_token_id``.
pad_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
attention mechanisms or loss computation. Will be associated to ``self.pad_token`` and
``self.pad_token_id``.
cls_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing the class of the input (used by BERT for instance). Will be associated to
``self.cls_token`` and ``self.cls_token_id``.
mask_token (:obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A special token representing a masked token (used by masked-language modeling pretraining objectives, like
BERT). Will be associated to ``self.mask_token`` and ``self.mask_token_id``.
additional_special_tokens (tuple or list of :obj:`str` or :obj:`tokenizers.AddedToken`, `optional`):
A tuple or a list of additional special tokens. Add them here to ensure they won't be split by the
tokenization process. Will be associated to ``self.additional_special_tokens`` and
``self.additional_special_tokens_ids``.
"""
@add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
class PreTrainedTokenizerBase(SpecialTokensMixin):
"""
Base class for :class:`~transformers.PreTrainedTokenizer` and :class:`~transformers.PreTrainedTokenizerFast`.
Handles shared (mostly boiler plate) methods for those two classes.
"""
vocab_files_names: Dict[str, str] = {}
pretrained_vocab_files_map: Dict[str, Dict[str, str]] = {}
pretrained_init_configuration: Dict[str, Dict[str, Any]] = {}
max_model_input_sizes: Dict[str, Optional[int]] = {}
model_input_names: List[str] = ["token_type_ids", "attention_mask"]
padding_side: str = "right"
def __init__(self, **kwargs):
# inputs and kwargs for saving and re-loading (see ``from_pretrained`` and ``save_pretrained``)
self.init_inputs = ()
self.init_kwargs = kwargs
# For backward compatibility we fallback to set model_max_length from max_len if provided
model_max_length = kwargs.pop("model_max_length", kwargs.pop("max_len", None))
self.model_max_length = model_max_length if model_max_length is not None else VERY_LARGE_INTEGER
# Padding side is right by default and overridden in subclasses. If specified in the kwargs, it is changed.
self.padding_side = kwargs.pop("padding_side", self.padding_side)
assert self.padding_side in [
"right",
"left",
], f"Padding side should be selected between 'right' and 'left', current value: {self.padding_side}"
self.model_input_names = kwargs.pop("model_input_names", self.model_input_names)
super().__init__(**kwargs)
@property
def max_len(self) -> int:
"""
:obj:`int`: **Deprecated** Kept here for backward compatibility. Now renamed to :obj:`model_max_length` to
avoid ambiguity.
"""
warnings.warn(
"The `max_len` attribute has been deprecated and will be removed in a future version, use `model_max_length` instead.",
FutureWarning,
)
return self.model_max_length
@property
def max_len_single_sentence(self) -> int:
"""
:obj:`int`: The maximum length of a sentence that can be fed to the model.
"""
return self.model_max_length - self.num_special_tokens_to_add(pair=False)
@property
def max_len_sentences_pair(self) -> int:
"""
:obj:`int`: The maximum combined length of a pair of sentences that can be fed to the model.
"""
return self.model_max_length - self.num_special_tokens_to_add(pair=True)
@max_len_single_sentence.setter
def max_len_single_sentence(self, value) -> int:
# For backward compatibility, allow to try to setup 'max_len_single_sentence'.
if value == self.model_max_length - self.num_special_tokens_to_add(pair=False) and self.verbose:
logger.warning(
"Setting 'max_len_single_sentence' is now deprecated. " "This value is automatically set up."
)
else:
raise ValueError(
"Setting 'max_len_single_sentence' is now deprecated. " "This value is automatically set up."
)
@max_len_sentences_pair.setter
def max_len_sentences_pair(self, value) -> int:
# For backward compatibility, allow to try to setup 'max_len_sentences_pair'.
if value == self.model_max_length - self.num_special_tokens_to_add(pair=True) and self.verbose:
logger.warning(
"Setting 'max_len_sentences_pair' is now deprecated. " "This value is automatically set up."
)
else:
raise ValueError(
"Setting 'max_len_sentences_pair' is now deprecated. " "This value is automatically set up."
)
@classmethod
def from_pretrained(cls, *inputs, **kwargs):
r"""
Instantiate a :class:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase` (or a derived class) from
a predefined tokenizer.
Args:
pretrained_model_name_or_path (:obj:`str`):
Can be either:
- A string with the `shortcut name` of a predefined tokenizer to load from cache or download, e.g.,
``bert-base-uncased``.
- A string with the `identifier name` of a predefined tokenizer that was user-uploaded to our S3, e.g.,
``dbmdz/bert-base-german-cased``.
- A path to a `directory` containing vocabulary files required by the tokenizer, for instance saved
using the :meth:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase.save_pretrained`
method, e.g., ``./my_model_directory/``.
- (**Deprecated**, not applicable to all derived classes) A path or url to a single saved vocabulary
file (if and only if the tokenizer only requires a single vocabulary file like Bert or XLNet), e.g.,
``./my_model_directory/vocab.txt``.
cache_dir (:obj:`str`, `optional`):
Path to a directory in which a downloaded predefined tokenizer vocabulary files should be cached if the
standard cache should not be used.
force_download (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to force the (re-)download the vocabulary files and override the cached versions if they
exist.
resume_download (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to delete incompletely received files. Attempt to resume the download if such a file
exists.
proxies (:obj:`Dict[str, str], `optional`):
A dictionary of proxy servers to use by protocol or endpoint, e.g.,
:obj:`{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each
request.
inputs (additional positional arguments, `optional`):
Will be passed along to the Tokenizer ``__init__`` method.
kwargs (additional keyword arguments, `optional`):
Will be passed to the Tokenizer ``__init__`` method. Can be used to set special tokens like
``bos_token``, ``eos_token``, ``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``,
``mask_token``, ``additional_special_tokens``. See parameters in the ``__init__`` for more details.
Examples::
# We can't instantiate directly the base class `PreTrainedTokenizerBase` so let's show our examples on a derived class: BertTokenizer
# Download vocabulary from S3 and cache.
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# Download vocabulary from S3 (user-uploaded) and cache.
tokenizer = BertTokenizer.from_pretrained('dbmdz/bert-base-german-cased')
# If vocabulary files are in a directory (e.g. tokenizer was saved using `save_pretrained('./test/saved_model/')`)
tokenizer = BertTokenizer.from_pretrained('./test/saved_model/')
# If the tokenizer uses a single vocabulary file, you can point directly to this file
tokenizer = BertTokenizer.from_pretrained('./test/saved_model/my_vocab.txt')
# You can link tokens to special vocabulary when instantiating
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', unk_token='<unk>')
# You should be sure '<unk>' is in the vocabulary when doing that.
# Otherwise use tokenizer.add_special_tokens({'unk_token': '<unk>'}) instead)
assert tokenizer.unk_token == '<unk>'
"""
return cls._from_pretrained(*inputs, **kwargs)
@classmethod
def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs):
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
local_files_only = kwargs.pop("local_files_only", False)
s3_models = list(cls.max_model_input_sizes.keys())
vocab_files = {}
init_configuration = {}
if pretrained_model_name_or_path in s3_models:
# Get the vocabulary from AWS S3 bucket
for file_id, map_list in cls.pretrained_vocab_files_map.items():
vocab_files[file_id] = map_list[pretrained_model_name_or_path]
if (
cls.pretrained_init_configuration
and pretrained_model_name_or_path in cls.pretrained_init_configuration
):
init_configuration = cls.pretrained_init_configuration[pretrained_model_name_or_path].copy()
else:
# Get the vocabulary from local files
logger.info(
"Model name '{}' not found in model shortcut name list ({}). "
"Assuming '{}' is a path, a model identifier, or url to a directory containing tokenizer files.".format(
pretrained_model_name_or_path, ", ".join(s3_models), pretrained_model_name_or_path
)
)
if os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
if len(cls.vocab_files_names) > 1:
raise ValueError(
"Calling {}.from_pretrained() with the path to a single file or url is not supported."
"Use a model identifier or the path to a directory instead.".format(cls.__name__)
)
logger.warning(
"Calling {}.from_pretrained() with the path to a single file or url is deprecated".format(
cls.__name__
)
)
file_id = list(cls.vocab_files_names.keys())[0]
vocab_files[file_id] = pretrained_model_name_or_path
else:
# At this point pretrained_model_name_or_path is either a directory or a model identifier name
additional_files_names = {
"added_tokens_file": ADDED_TOKENS_FILE,
"special_tokens_map_file": SPECIAL_TOKENS_MAP_FILE,
"tokenizer_config_file": TOKENIZER_CONFIG_FILE,
"full_tokenizer_file": FULL_TOKENIZER_FILE,
}
# Look for the tokenizer files
for file_id, file_name in {**cls.vocab_files_names, **additional_files_names}.items():
if os.path.isdir(pretrained_model_name_or_path):
full_file_name = os.path.join(pretrained_model_name_or_path, file_name)
if not os.path.exists(full_file_name):
logger.info("Didn't find file {}. We won't load it.".format(full_file_name))
full_file_name = None
else:
full_file_name = hf_bucket_url(
pretrained_model_name_or_path, filename=file_name, use_cdn=False
)
vocab_files[file_id] = full_file_name
# Get files from url, cache, or disk depending on the case
try:
resolved_vocab_files = {}
for file_id, file_path in vocab_files.items():
if file_path is None:
resolved_vocab_files[file_id] = None
else:
resolved_vocab_files[file_id] = cached_path(
file_path,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
)
except EnvironmentError:
if pretrained_model_name_or_path in s3_models:
msg = "Couldn't reach server at '{}' to download vocabulary files."
else:
msg = (
"Model name '{}' was not found in tokenizers model name list ({}). "
"We assumed '{}' was a path or url to a directory containing vocabulary files "
"named {}, but couldn't find such vocabulary files at this path or url.".format(
pretrained_model_name_or_path,
", ".join(s3_models),
pretrained_model_name_or_path,
list(cls.vocab_files_names.values()),
)
)
raise EnvironmentError(msg)
if all(full_file_name is None for full_file_name in resolved_vocab_files.values()):
raise EnvironmentError(
"Model name '{}' was not found in tokenizers model name list ({}). "
"We assumed '{}' was a path, a model identifier, or url to a directory containing vocabulary files "
"named {} but couldn't find such vocabulary files at this path or url.".format(
pretrained_model_name_or_path,
", ".join(s3_models),
pretrained_model_name_or_path,
list(cls.vocab_files_names.values()),
)
)
for file_id, file_path in vocab_files.items():
if file_path == resolved_vocab_files[file_id]:
logger.info("loading file {}".format(file_path))
else:
logger.info("loading file {} from cache at {}".format(file_path, resolved_vocab_files[file_id]))
# Prepare tokenizer initialization kwargs
# Did we saved some inputs and kwargs to reload ?
tokenizer_config_file = resolved_vocab_files.pop("tokenizer_config_file", None)
if tokenizer_config_file is not None:
with open(tokenizer_config_file, encoding="utf-8") as tokenizer_config_handle:
init_kwargs = json.load(tokenizer_config_handle)
saved_init_inputs = init_kwargs.pop("init_inputs", ())
if not init_inputs:
init_inputs = saved_init_inputs
else:
init_kwargs = init_configuration
# Update with newly provided kwargs
init_kwargs.update(kwargs)
# Set max length if needed
if pretrained_model_name_or_path in cls.max_model_input_sizes:
# if we're using a pretrained model, ensure the tokenizer
# wont index sequences longer than the number of positional embeddings
model_max_length = cls.max_model_input_sizes[pretrained_model_name_or_path]
if model_max_length is not None and isinstance(model_max_length, (int, float)):
init_kwargs["model_max_length"] = min(init_kwargs.get("model_max_length", int(1e30)), model_max_length)
# Merge resolved_vocab_files arguments in init_kwargs.
added_tokens_file = resolved_vocab_files.pop("added_tokens_file", None)
for args_name, file_path in resolved_vocab_files.items():
if args_name not in init_kwargs:
init_kwargs[args_name] = file_path
# Instantiate tokenizer.
try:
tokenizer = cls(*init_inputs, **init_kwargs)
except OSError:
raise OSError(
"Unable to load vocabulary from file. "
"Please check that the provided vocabulary is accessible and not corrupted."
)
# Save inputs and kwargs for saving and re-loading with ``save_pretrained``
tokenizer.init_inputs = init_inputs
tokenizer.init_kwargs = init_kwargs
# If there is a complementary special token map, load it
special_tokens_map_file = resolved_vocab_files.pop("special_tokens_map_file", None)
if special_tokens_map_file is not None:
with open(special_tokens_map_file, encoding="utf-8") as special_tokens_map_handle:
special_tokens_map = json.load(special_tokens_map_handle)
for key, value in special_tokens_map.items():
if isinstance(value, dict):
value = AddedToken(**value)
setattr(tokenizer, key, value)
# Add supplementary tokens.
special_tokens = tokenizer.all_special_tokens
if added_tokens_file is not None:
with open(added_tokens_file, encoding="utf-8") as added_tokens_handle:
added_tok_encoder = json.load(added_tokens_handle)
# Sort added tokens by index
added_tok_encoder_sorted = list(sorted(added_tok_encoder.items(), key=lambda x: x[1]))
for token, index in added_tok_encoder_sorted:
assert index == len(tokenizer), (
f"Non-consecutive added token '{token}' found. "
f"Should have index {len(tokenizer)} but has index {index} in saved vocabulary."
)
tokenizer.add_tokens(token, special_tokens=bool(token in special_tokens))
# Check all our special tokens are registrered as "no split" token (we don't cut them) and are in the vocab
added_tokens = tokenizer.sanitize_special_tokens()
if added_tokens:
logger.warning(
"Special tokens have been added in the vocabulary, make sure the associated word emebedding are fine-tuned or trained."
)
return tokenizer
def save_pretrained(self, save_directory: str) -> Tuple[str]:
"""
Save the tokenizer vocabulary files together with:
- added tokens,
- special tokens to class attributes mapping,
- tokenizer instantiation positional and keywords inputs (e.g. do_lower_case for Bert).
This method make sure the full tokenizer can then be re-loaded using the
:meth:`~transformers.tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained` class method.
.. Warning::
This won't save modifications you may have applied to the tokenizer after the instantiation (for instance,
modifying :obj:`tokenizer.do_lower_case` after creation).
Args:
save_directory (:obj:`str`): The path to adirectory where the tokenizer will be saved.
Returns:
A tuple of :obj:`str`: The files saved.
"""
if os.path.isfile(save_directory):
logger.error("Provided path ({}) should be a directory, not a file".format(save_directory))
return
os.makedirs(save_directory, exist_ok=True)
special_tokens_map_file = os.path.join(save_directory, SPECIAL_TOKENS_MAP_FILE)
added_tokens_file = os.path.join(save_directory, ADDED_TOKENS_FILE)
tokenizer_config_file = os.path.join(save_directory, TOKENIZER_CONFIG_FILE)
tokenizer_config = copy.deepcopy(self.init_kwargs)
if len(self.init_inputs) > 0:
tokenizer_config["init_inputs"] = copy.deepcopy(self.init_inputs)
for file_id in self.vocab_files_names.keys():
tokenizer_config.pop(file_id, None)
with open(tokenizer_config_file, "w", encoding="utf-8") as f:
f.write(json.dumps(tokenizer_config, ensure_ascii=False))
with open(special_tokens_map_file, "w", encoding="utf-8") as f:
write_dict = {}
for key, value in self.special_tokens_map_extended.items():
if isinstance(value, AddedToken):
write_dict[key] = value.__getstate__()
else:
write_dict[key] = value
f.write(json.dumps(write_dict, ensure_ascii=False))
added_vocab = self.get_added_vocab()
if added_vocab:
with open(added_tokens_file, "w", encoding="utf-8") as f:
out_str = json.dumps(added_vocab, ensure_ascii=False)
f.write(out_str)
vocab_files = self.save_vocabulary(save_directory)
return vocab_files + (special_tokens_map_file, added_tokens_file)
@add_end_docstrings(
ENCODE_KWARGS_DOCSTRING,
"""
**kwargs: Passed along to the `.tokenize()` method.
""",
"""
Returns:
:obj:`List[int]`, :obj:`torch.Tensor`, :obj:`tf.Tensor` or :obj:`np.ndarray`:
The tokenized ids of the text.
""",
)
def encode(
self,
text: Union[TextInput, PreTokenizedInput, EncodedInput],
text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs
) -> List[int]:
"""
Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary.
Same as doing ``self.convert_tokens_to_ids(self.tokenize(text))``.
Args:
text (:obj:`str`, :obj:`List[str]` or :obj:`List[int]`):
The first sequence to be encoded. This can be a string, a list of strings (tokenized string using
the ``tokenize`` method) or a list of integers (tokenized string ids using the
``convert_tokens_to_ids`` method).
text_pair (:obj:`str`, :obj:`List[str]` or :obj:`List[int]`, `optional`):
Optional second sequence to be encoded. This can be a string, a list of strings (tokenized
string using the ``tokenize`` method) or a list of integers (tokenized string ids using the
``convert_tokens_to_ids`` method).
"""
encoded_inputs = self.encode_plus(
text,
text_pair=text_pair,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
return_tensors=return_tensors,
**kwargs,
)
return encoded_inputs["input_ids"]
def num_special_tokens_to_add(self, pair: bool = False) -> int:
raise NotImplementedError
def _get_padding_truncation_strategies(
self, padding=False, truncation=False, max_length=None, pad_to_multiple_of=None, verbose=True, **kwargs
):
"""
Find the correct padding/truncation strategy with backward compatibility
for old arguments (truncation_strategy and pad_to_max_length) and behaviors.
"""
old_truncation_strategy = kwargs.pop("truncation_strategy", "do_not_truncate")
old_pad_to_max_length = kwargs.pop("pad_to_max_length", False)
# Backward compatibility for previous behavior, maybe we should deprecate it:
# If you only set max_length, it activates truncation for max_length
if max_length is not None and padding is False and truncation is False:
if verbose:
logger.warning(
"Truncation was not explicitely activated but `max_length` is provided a specific value, "
"please use `truncation=True` to explicitely truncate examples to max length. "
"Defaulting to 'longest_first' truncation strategy. "
"If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy "
"more precisely by providing a specific strategy to `truncation`."
)
truncation = "longest_first"
# Get padding strategy
if padding is False and old_pad_to_max_length:
if verbose:
warnings.warn(
"The `pad_to_max_length` argument is deprecated and will be removed in a future version, "
"use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or "
"use `padding='max_length'` to pad to a max length. In this case, you can give a specific "
"length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the "
"maximal input size of the model (e.g. 512 for Bert).",
FutureWarning,
)
if max_length is None:
padding_strategy = PaddingStrategy.LONGEST
else:
padding_strategy = PaddingStrategy.MAX_LENGTH
elif padding is not False:
if padding is True:
padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch
elif not isinstance(padding, PaddingStrategy):
padding_strategy = PaddingStrategy(padding)
else:
padding_strategy = PaddingStrategy.DO_NOT_PAD
# Get truncation strategy
if truncation is False and old_truncation_strategy != "do_not_truncate":
if verbose:
warnings.warn(
"The `truncation_strategy` argument is deprecated and will be removed in a future version, "
"use `truncation=True` to truncate examples to a max length. You can give a specific "
"length with `max_length` (e.g. `max_length=45`) or leave max_length to None to truncate to the "
"maximal input size of the model (e.g. 512 for Bert). "
" If you have pairs of inputs, you can give a specific truncation strategy selected among "
"`truncation='only_first'` (will only truncate the first sentence in the pairs) "
"`truncation='only_second'` (will only truncate the second sentence in the pairs) "
"or `truncation='longest_first'` (will iteratively remove tokens from the longest sentence in the pairs).",
FutureWarning,
)
truncation_strategy = TruncationStrategy(old_truncation_strategy)
elif truncation is not False:
if truncation is True:
truncation_strategy = (
TruncationStrategy.LONGEST_FIRST
) # Default to truncate the longest sequences in pairs of inputs
elif not isinstance(truncation, TruncationStrategy):
truncation_strategy = TruncationStrategy(truncation)
else:
truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
# Set max length if needed
if max_length is None:
if padding_strategy == PaddingStrategy.MAX_LENGTH:
if self.model_max_length > LARGE_INTEGER:
if verbose:
logger.warning(
"Asking to pad to max_length but no maximum length is provided and the model has no predefined maximum length. "
"Default to no padding."
)
padding_strategy = PaddingStrategy.DO_NOT_PAD
else:
max_length = self.model_max_length
if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE:
if self.model_max_length > LARGE_INTEGER:
if verbose:
logger.warning(
"Asking to truncate to max_length but no maximum length is provided and the model has no predefined maximum length. "
"Default to no truncation."
)
truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
else:
max_length = self.model_max_length
# Test if we have a padding token
if padding_strategy != PaddingStrategy.DO_NOT_PAD and (not self.pad_token or self.pad_token_id < 0):
raise ValueError(
"Asking to pad but the tokenizer does not have a padding token. "
"Please select a token to use as `pad_token` `(tokenizer.pad_token = tokenizer.eos_token e.g.)` "
"or add a new pad token via `tokenizer.add_special_tokens({'pad_token': '[PAD]'})`."
)
# Check that we will truncate to a multiple of pad_to_multiple_of if both are provided
if (
truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE
and padding_strategy != PaddingStrategy.DO_NOT_PAD
and pad_to_multiple_of is not None
and max_length is not None
and (max_length % pad_to_multiple_of != 0)
):
raise ValueError(
f"Truncation and padding are both activated but "
f"truncation length ({max_length}) is not a multiple of pad_to_multiple_of ({pad_to_multiple_of})."
)
return padding_strategy, truncation_strategy, max_length, kwargs
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
def __call__(
self,
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
is_pretokenized: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
"""
Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
sequences.
Args:
text (:obj:`str`, :obj:`List[str]`, :obj:`List[List[str]]`):
The sequence or batch of sequences to be encoded.
Each sequence can be a string or a list of strings (pretokenized string).
If the sequences are provided as list of strings (pretokenized), you must set
:obj:`is_pretokenized=True` (to lift the ambiguity with a batch of sequences).
text_pair (:obj:`str`, :obj:`List[str]`, :obj:`List[List[str]]`):
The sequence or batch of sequences to be encoded.
Each sequence can be a string or a list of strings (pretokenized string).
If the sequences are provided as list of strings (pretokenized), you must set
:obj:`is_pretokenized=True` (to lift the ambiguity with a batch of sequences).
"""
# Input type checking for clearer error
assert isinstance(text, str) or (
isinstance(text, (list, tuple))
and (
len(text) == 0
or (
isinstance(text[0], str)
or (isinstance(text[0], (list, tuple)) and (len(text[0]) == 0 or isinstance(text[0][0], str)))
)
)
), (
"text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
"or `List[List[str]]` (batch of pretokenized examples)."
)
assert (
text_pair is None
or isinstance(text_pair, str)
or (
isinstance(text_pair, (list, tuple))
and (
len(text_pair) == 0
or (
isinstance(text_pair[0], str)
or (
isinstance(text_pair[0], (list, tuple))
and (len(text_pair[0]) == 0 or isinstance(text_pair[0][0], str))
)
)
)
)
), (
"text_pair input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
"or `List[List[str]]` (batch of pretokenized examples)."
)
is_batched = bool(
(not is_pretokenized and isinstance(text, (list, tuple)))
or (is_pretokenized and isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple)))
)
if is_batched:
batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
return self.batch_encode_plus(
batch_text_or_text_pairs=batch_text_or_text_pairs,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
is_pretokenized=is_pretokenized,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
**kwargs,
)
else:
return self.encode_plus(
text=text,
text_pair=text_pair,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
is_pretokenized=is_pretokenized,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
**kwargs,
)
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
def encode_plus(
self,
text: Union[TextInput, PreTokenizedInput, EncodedInput],
text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
is_pretokenized: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
"""
Tokenize and prepare for the model a sequence or a pair of sequences.
.. warning::
This method is deprecated, ``__call__`` should be used instead.
Args:
text (:obj:`str`, :obj:`List[str]` or :obj:`List[int]` (the latter only for not-fast tokenizers)):
The first sequence to be encoded. This can be a string, a list of strings (tokenized string using
the ``tokenize`` method) or a list of integers (tokenized string ids using the
``convert_tokens_to_ids`` method).
text_pair (:obj:`str`, :obj:`List[str]` or :obj:`List[int]`, `optional`):
Optional second sequence to be encoded. This can be a string, a list of strings (tokenized
string using the ``tokenize`` method) or a list of integers (tokenized string ids using the
``convert_tokens_to_ids`` method).
"""
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
padding=padding,
truncation=truncation,
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
verbose=verbose,
**kwargs,
)
return self._encode_plus(
text=text,
text_pair=text_pair,
add_special_tokens=add_special_tokens,
padding_strategy=padding_strategy,
truncation_strategy=truncation_strategy,
max_length=max_length,
stride=stride,
is_pretokenized=is_pretokenized,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
**kwargs,
)
def _encode_plus(
self,
text: Union[TextInput, PreTokenizedInput, EncodedInput],
text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
add_special_tokens: bool = True,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
max_length: Optional[int] = None,
stride: int = 0,
is_pretokenized: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
raise NotImplementedError
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
def batch_encode_plus(
self,
batch_text_or_text_pairs: Union[
List[TextInput],
List[TextInputPair],
List[PreTokenizedInput],
List[PreTokenizedInputPair],
List[EncodedInput],
List[EncodedInputPair],
],
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
is_pretokenized: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
"""
Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.
.. warning::
This method is deprecated, ``__call__`` should be used instead.
Args:
batch_text_or_text_pairs (:obj:`List[str]`, :obj:`List[Tuple[str, str]]`, :obj:`List[List[str]]`, :obj:`List[Tuple[List[str], List[str]]]`, and for not-fast tokenizers, also :obj:`List[List[int]]`, :obj:`List[Tuple[List[int], List[int]]]`):
Batch of sequences or pair of sequences to be encoded.
This can be a list of string/string-sequences/int-sequences or a list of pair of
string/string-sequences/int-sequence (see details in ``encode_plus``).
"""
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
padding=padding,
truncation=truncation,
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
verbose=verbose,
**kwargs,
)
return self._batch_encode_plus(
batch_text_or_text_pairs=batch_text_or_text_pairs,
add_special_tokens=add_special_tokens,
padding_strategy=padding_strategy,
truncation_strategy=truncation_strategy,
max_length=max_length,
stride=stride,
is_pretokenized=is_pretokenized,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
**kwargs,
)
def _batch_encode_plus(
self,
batch_text_or_text_pairs: Union[
List[TextInput],
List[TextInputPair],
List[PreTokenizedInput],
List[PreTokenizedInputPair],
List[EncodedInput],
List[EncodedInputPair],
],
add_special_tokens: bool = True,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
max_length: Optional[int] = None,
stride: int = 0,
is_pretokenized: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
raise NotImplementedError
def pad(
self,
encoded_inputs: Union[
BatchEncoding,
List[BatchEncoding],
Dict[str, EncodedInput],
Dict[str, List[EncodedInput]],
List[Dict[str, EncodedInput]],
],
padding: Union[bool, str, PaddingStrategy] = True,
max_length: Optional[int] = None,
pad_to_multiple_of: Optional[int] = None,
return_attention_mask: Optional[bool] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
verbose: bool = True,
) -> BatchEncoding:
"""
Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
in the batch.
Padding side (left/right) padding token ids are defined at the tokenizer level
(with ``self.padding_side``, ``self.pad_token_id`` and ``self.pad_token_type_id``)
Args:
encoded_inputs (:class:`~transformers.BatchEncoding`, list of :class:`~transformers.BatchEncoding`, :obj:`Dict[str, List[int]]`, :obj:`Dict[str, List[List[int]]` or :obj:`List[Dict[str, List[int]]]`):
Tokenized inputs. Can represent one input (:class:`~transformers.BatchEncoding` or
:obj:`Dict[str, List[int]]`) or a batch of tokenized inputs (list of
:class:`~transformers.BatchEncoding`, `Dict[str, List[List[int]]]` or `List[Dict[str, List[int]]]`) so
you can use this method during preprocessing as well as in a PyTorch Dataloader collate function.
padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`False`):
Select a strategy to pad the returned sequences (according to the model's padding side and padding
index) among:
* :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a
single sequence if provided).
* :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
maximum acceptable input length for the model if that argument is not provided.
* :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
different lengths).
max_length (:obj:`int`, `optional`):
Maximum length of the returned list and optionally padding length (see above).
pad_to_multiple_of (:obj:`int`, `optional`):
If set will pad the sequence to a multiple of the provided value.
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
>= 7.5 (Volta).
return_attention_mask (:obj:`bool`, `optional`):
Whether to return the attention mask. If left to the default, will return the attention mask according
to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
`What are attention masks? <../glossary.html#attention-mask>`__
return_tensors (:obj:`str` or :class:`~transformers.tokenization_utils_base.TensorType`, `optional`):
If set, will return tensors instead of list of python integers. Acceptable values are:
* :obj:`'tf'`: Return TensorFlow :obj:`tf.constant` objects.
* :obj:`'pt'`: Return PyTorch :obj:`torch.Tensor` objects.
* :obj:`'np'`: Return Numpy :obj:`np.ndarray` objects.
verbose (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether or not to print informations and warnings.
"""
# If we have a list of dicts, let's convert it in a dict of lists
if isinstance(encoded_inputs, (list, tuple)) and isinstance(encoded_inputs[0], (dict, BatchEncoding)):
encoded_inputs = {key: [example[key] for example in encoded_inputs] for key in encoded_inputs[0].keys()}
assert "input_ids" in encoded_inputs, (
"You should supply an encoding or a list of encodings to this method. "
"An encoding is the output of one the encoding methods of the tokenizer, i.e. "
"__call__/encode_plus/batch_encode_plus. "
)
if not encoded_inputs["input_ids"]:
if return_attention_mask:
encoded_inputs["attention_mask"] = []
return encoded_inputs
# Convert padding_strategy in PaddingStrategy
padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
padding=padding, max_length=max_length, verbose=verbose
)
if encoded_inputs["input_ids"] and not isinstance(encoded_inputs["input_ids"][0], (list, tuple)):
encoded_inputs = self._pad(
encoded_inputs,
max_length=max_length,
padding_strategy=padding_strategy,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
batch_size = len(encoded_inputs["input_ids"])
assert all(
len(v) == batch_size for v in encoded_inputs.values()
), "Some items in the output dictionnary have a different batch size than others."
if padding_strategy == PaddingStrategy.LONGEST:
max_length = max(len(inputs) for inputs in encoded_inputs["input_ids"])
padding_strategy = PaddingStrategy.MAX_LENGTH
batch_outputs = {}
for i in range(batch_size):
inputs = dict((k, v[i]) for k, v in encoded_inputs.items())
outputs = self._pad(
inputs,
max_length=max_length,
padding_strategy=padding_strategy,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
for key, value in outputs.items():
if key not in batch_outputs:
batch_outputs[key] = []
batch_outputs[key].append(value)
return BatchEncoding(batch_outputs, tensor_type=return_tensors)
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create the token type IDs corresponding to the sequences passed.
`What are token type IDs? <../glossary.html#token-type-ids>`__
Should be overriden in a subclass if the model has a special way of building those.
Args:
token_ids_0 (:obj:`List[int]`): The first tokenized sequence.
token_ids_1 (:obj:`List[int]`, `optional`): The second tokenized sequence.
Returns:
:obj:`List[int]`: The token type ids.
"""
if token_ids_1 is None:
return len(token_ids_0) * [0]
return [0] * len(token_ids_0) + [1] * len(token_ids_1)
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks
by concatenating and adding special tokens.
This implementation does not add special tokens and this method should be overriden in a subclass.
Args:
token_ids_0 (:obj:`List[int]`): The first tokenized sequence.
token_ids_1 (:obj:`List[int]`, `optional`): The second tokenized sequence.
Returns:
:obj:`List[int]`: The model input with special tokens.
"""
if token_ids_1 is None:
return token_ids_0
return token_ids_0 + token_ids_1
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
def prepare_for_model(
self,
ids: List[int],
pair_ids: Optional[List[int]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
prepend_batch_axis: bool = False,
**kwargs
) -> BatchEncoding:
"""
Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model.
It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
manages a moving window (with user defined stride) for overflowing tokens
Args:
ids (:obj:`List[int]`):
Tokenized input ids of the first sequence. Can be obtained from a string by chaining the
``tokenize`` and ``convert_tokens_to_ids`` methods.
pair_ids (:obj:`List[int]`, `optional`):
Tokenized input ids of the second sequence. Can be obtained from a string by chaining the
``tokenize`` and ``convert_tokens_to_ids`` methods.
"""
if "return_lengths" in kwargs:
if verbose:
warnings.warn(
"The PreTrainedTokenizerBase.prepare_for_model `return_lengths` parameter is deprecated. "
"Please use `return_length` instead.",
FutureWarning,
)
return_length = kwargs["return_lengths"]
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
padding=padding,
truncation=truncation,
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
verbose=verbose,
**kwargs,
)
pair = bool(pair_ids is not None)
len_ids = len(ids)
len_pair_ids = len(pair_ids) if pair else 0
# Load from model defaults
if return_token_type_ids is None:
return_token_type_ids = "token_type_ids" in self.model_input_names
if return_attention_mask is None:
return_attention_mask = "attention_mask" in self.model_input_names
encoded_inputs = {}
# Compute the total size of the returned encodings
total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
# Truncation: Handle max sequence length
if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
ids, pair_ids, overflowing_tokens = self.truncate_sequences(
ids,
pair_ids=pair_ids,
num_tokens_to_remove=total_len - max_length,
truncation_strategy=truncation_strategy,
stride=stride,
)
if return_overflowing_tokens:
encoded_inputs["overflowing_tokens"] = overflowing_tokens
encoded_inputs["num_truncated_tokens"] = total_len - max_length
# Add special tokens
if add_special_tokens:
sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
else:
sequence = ids + pair_ids if pair else ids
token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else [])
# Build output dictionnary
encoded_inputs["input_ids"] = sequence
if return_token_type_ids:
encoded_inputs["token_type_ids"] = token_type_ids
if return_special_tokens_mask:
if add_special_tokens:
encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
else:
encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
# Check lengths
if max_length is None and len(encoded_inputs["input_ids"]) > self.model_max_length and verbose:
logger.warning(
"Token indices sequence length is longer than the specified maximum sequence length "
"for this model ({} > {}). Running this sequence through the model will result in "
"indexing errors".format(len(ids), self.model_max_length)
)
# Padding
if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
encoded_inputs = self.pad(
encoded_inputs,
max_length=max_length,
padding=padding_strategy.value,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
if return_length:
encoded_inputs["length"] = len(encoded_inputs["input_ids"])
batch_outputs = BatchEncoding(
encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
)
return batch_outputs
def truncate_sequences(
self,
ids: List[int],
pair_ids: Optional[List[int]] = None,
num_tokens_to_remove: int = 0,
truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
stride: int = 0,
) -> Tuple[List[int], List[int], List[int]]:
"""
Truncates a sequence pair in-place following the strategy.
Args:
ids (:obj:`List[int]`):
Tokenized input ids of the first sequence. Can be obtained from a string by chaining the
``tokenize`` and ``convert_tokens_to_ids`` methods.
pair_ids (:obj:`List[int]`, `optional`):
Tokenized input ids of the second sequence. Can be obtained from a string by chaining the
``tokenize`` and ``convert_tokens_to_ids`` methods.
num_tokens_to_remove (:obj:`int`, `optional`, defaults to 0):
Number of tokens to remove using the truncation strategy.
truncation (:obj:`str` or :class:`~transformers.tokenization_utils_base.TruncationStrategy`, `optional`, defaults to :obj:`False`):
The strategy to follow for truncation. Can be:
* :obj:`'longest_first'`: Truncate to a maximum length specified with the argument
:obj:`max_length` or to the maximum acceptable input length for the model if that argument is not
provided. This will truncate token by token, removing a token from the longest sequence in the pair
if a pair of sequences (or a batch of pairs) is provided.
* :obj:`'only_first'`: Truncate to a maximum length specified with the argument :obj:`max_length` or to
the maximum acceptable input length for the model if that argument is not provided. This will only
truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
* :obj:`'only_second'`: Truncate to a maximum length specified with the argument :obj:`max_length` or
to the maximum acceptable input length for the model if that argument is not provided. This will only
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
* :obj:`'do_not_truncate'` (default): No truncation (i.e., can output batch with
sequence lengths greater than the model maximum admissible input size).
max_length (:obj:`int`, `optional`):
Controls the maximum length to use by one of the truncation/padding parameters.
If left unset or set to :obj:`None`, this will use the predefined model maximum length if a maximum
length is required by one of the truncation/padding parameters. If the model has no specific maximum
input length (like XLNet) truncation/padding to a maximum length will be deactivated.
stride (:obj:`int`, `optional`, defaults to 0):
If set to a positive number, the overflowing tokens returned will contain some tokens
from the main sequence returned. The value of this argument defines the number of additional tokens.
Returns:
:obj:`Tuple[List[int], List[int], List[int]]`:
The truncated ``ids``, the truncated ``pair_ids`` and the list of overflowing tokens.
"""
if num_tokens_to_remove <= 0:
return ids, pair_ids, []
if not isinstance(truncation_strategy, TruncationStrategy):
truncation_strategy = TruncationStrategy(truncation_strategy)
overflowing_tokens = []
if truncation_strategy == TruncationStrategy.LONGEST_FIRST:
for _ in range(num_tokens_to_remove):
if pair_ids is None or len(ids) > len(pair_ids):
if not overflowing_tokens:
window_len = min(len(ids), stride + 1)
else:
window_len = 1
overflowing_tokens.extend(ids[-window_len:])
ids = ids[:-1]
else:
if not overflowing_tokens:
window_len = min(len(pair_ids), stride + 1)
else:
window_len = 1
overflowing_tokens.extend(pair_ids[-window_len:])
pair_ids = pair_ids[:-1]
elif truncation_strategy == TruncationStrategy.ONLY_FIRST:
if len(ids) > num_tokens_to_remove:
window_len = min(len(ids), stride + num_tokens_to_remove)
overflowing_tokens = ids[-window_len:]
ids = ids[:-num_tokens_to_remove]
else:
logger.error(
f"We need to remove {num_tokens_to_remove} to truncate the input"
f"but the first sequence has a length {len(ids)}. "
f"Please select another truncation strategy than {truncation_strategy}, "
f"for instance 'longest_first' or 'only_second'."
)
elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
if len(pair_ids) > num_tokens_to_remove:
window_len = min(len(pair_ids), stride + num_tokens_to_remove)
overflowing_tokens = pair_ids[-window_len:]
pair_ids = pair_ids[:-num_tokens_to_remove]
else:
logger.error(
f"We need to remove {num_tokens_to_remove} to truncate the input"
f"but the second sequence has a length {len(pair_ids)}. "
f"Please select another truncation strategy than {truncation_strategy}, "
f"for instance 'longest_first' or 'only_first'."
)
return (ids, pair_ids, overflowing_tokens)
def _pad(
self,
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
max_length: Optional[int] = None,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
pad_to_multiple_of: Optional[int] = None,
return_attention_mask: Optional[bool] = None,
) -> dict:
"""
Pad encoded inputs (on left/right and up to predefined legnth or max length in the batch)
Args:
encoded_inputs: Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
max_length: maximum length of the returned list and optionally padding length (see below).
Will truncate by taking into account the special tokens.
padding_strategy: PaddingStrategy to use for padding.
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
- PaddingStrategy.DO_NOT_PAD: Do not pad
The tokenizer padding sides are defined in self.padding_side:
- 'left': pads on the left of the sequences
- 'right': pads on the right of the sequences
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
>= 7.5 (Volta).
return_attention_mask: (optional) Set to False to avoid returning attention mask (default: set to model specifics)
"""
# Load from model defaults
if return_attention_mask is None:
return_attention_mask = "attention_mask" in self.model_input_names
if padding_strategy == PaddingStrategy.LONGEST:
max_length = len(encoded_inputs["input_ids"])
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
needs_to_be_padded = (
padding_strategy != PaddingStrategy.DO_NOT_PAD and len(encoded_inputs["input_ids"]) != max_length
)
if needs_to_be_padded:
difference = max_length - len(encoded_inputs["input_ids"])
if self.padding_side == "right":
if return_attention_mask:
encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"]) + [0] * difference
if "token_type_ids" in encoded_inputs:
encoded_inputs["token_type_ids"] = (
encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
)
if "special_tokens_mask" in encoded_inputs:
encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
elif self.padding_side == "left":
if return_attention_mask:
encoded_inputs["attention_mask"] = [0] * difference + [1] * len(encoded_inputs["input_ids"])
if "token_type_ids" in encoded_inputs:
encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
"token_type_ids"
]
if "special_tokens_mask" in encoded_inputs:
encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
else:
raise ValueError("Invalid padding strategy:" + str(self.padding_side))
else:
if return_attention_mask:
encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
return encoded_inputs
def batch_decode(
self, sequences: List[List[int]], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True
) -> List[str]:
"""
Convert a list of lists of token ids into a list of strings by calling decode.
Args:
sequences (:obj:`List[List[int]]`):
List of tokenized input ids. Can be obtained using the ``__call__`` method.
skip_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to remove special tokens in the decoding.
clean_up_tokenization_spaces (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether or not to clean up the tokenization spaces.
Returns:
:obj:`List[str]`: The list of decoded sentences.
"""
return [
self.decode(
seq, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces
)
for seq in sequences
]
def decode(
self, token_ids: List[int], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True
) -> str:
"""
Converts a sequence of ids in a string, using the tokenizer and vocabulary
with options to remove special tokens and clean up tokenization spaces.
Similar to doing ``self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))``.
Args:
token_ids (:obj:`List[int]`):
List of tokenized input ids. Can be obtained using the ``__call__`` method.
skip_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to remove special tokens in the decoding.
clean_up_tokenization_spaces (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether or not to clean up the tokenization spaces.
Returns:
:obj:`str`: The decoded sentence.
"""
raise NotImplementedError
def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods.
Args:
token_ids_0 (:obj:`List[int]`):
List of ids of the first sequence.
token_ids_1 (:obj:`List[int]`, `optional`):
List of ids of the second sequence.
already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Wheter or not the token list is already formated with special tokens for the model.
Returns:
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
"""
assert already_has_special_tokens and token_ids_1 is None, (
"You cannot use ``already_has_special_tokens=False`` with this tokenizer. "
"Please use a slow (full python) tokenizer to activate this argument."
"Or set `return_special_token_mask=True` when calling the encoding method "
"to get the special tokens mask in any tokenizer. "
)
all_special_ids = self.all_special_ids # cache the property
special_tokens_mask = [1 if token in all_special_ids else 0 for token in token_ids_0]
return special_tokens_mask
@staticmethod
def clean_up_tokenization(out_string: str) -> str:
"""
Clean up a list of simple English tokenization artifacts like spaces before punctuations and abreviated forms.
Args:
out_string (:obj:`str`): The text to clean up.
Returns:
:obj:`str`: The cleaned-up string.
"""
out_string = (
out_string.replace(" .", ".")
.replace(" ?", "?")
.replace(" !", "!")
.replace(" ,", ",")
.replace(" ' ", "'")
.replace(" n't", "n't")
.replace(" 'm", "'m")
.replace(" 's", "'s")
.replace(" 've", "'ve")
.replace(" 're", "'re")
)
return out_string
| 47.436897 | 252 | 0.625361 |
b3a2b4779fc1bc0d6eeecf244571feca2ea6cb63 | 6,113 | py | Python | benchmarks/f3_wrong_hints/scaling_nonlinear_software/5-19_18.py | EnricoMagnago/F3 | c863215c318d7d5f258eb9be38c6962cf6863b52 | [
"MIT"
] | 3 | 2021-04-23T23:29:26.000Z | 2022-03-23T10:00:30.000Z | benchmarks/f3_wrong_hints/scaling_nonlinear_software/5-19_18.py | EnricoMagnago/F3 | c863215c318d7d5f258eb9be38c6962cf6863b52 | [
"MIT"
] | null | null | null | benchmarks/f3_wrong_hints/scaling_nonlinear_software/5-19_18.py | EnricoMagnago/F3 | c863215c318d7d5f258eb9be38c6962cf6863b52 | [
"MIT"
] | 1 | 2021-11-17T22:02:56.000Z | 2021-11-17T22:02:56.000Z | from typing import FrozenSet, Tuple
import pysmt.typing as types
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
FNode]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
pc = mgr.Symbol("pc", types.INT)
x = mgr.Symbol("x", types.INT)
y = mgr.Symbol("y", types.INT)
z = mgr.Symbol("z", types.INT)
x_pc = symb_to_next(mgr, pc)
x_x = symb_to_next(mgr, x)
x_y = symb_to_next(mgr, y)
x_z = symb_to_next(mgr, z)
symbols = frozenset([pc, x, y, z])
n_locs = 5
int_bound = n_locs
pcs = []
x_pcs = []
ints = [mgr.Int(i) for i in range(int_bound)]
for l in range(n_locs):
n = ints[l]
pcs.append(mgr.Equals(pc, n))
x_pcs.append(mgr.Equals(x_pc, n))
m_1 = mgr.Int(-1)
pcend = mgr.Equals(pc, m_1)
x_pcend = mgr.Equals(x_pc, m_1)
# initial location.
init = pcs[0]
# control flow graph.
cfg = mgr.And(
# pc = -1 : -1,
mgr.Implies(pcend, x_pcend),
# pc = 0 & !(y >= 1) : -1,
mgr.Implies(mgr.And(pcs[0], mgr.Not(mgr.GE(y, ints[1]))), x_pcend),
# pc = 0 & y >= 1 : 1,
mgr.Implies(mgr.And(pcs[0], mgr.GE(y, ints[1])), x_pcs[1]),
# pc = 1 & !(z >= 1) : -1,
mgr.Implies(mgr.And(pcs[1], mgr.Not(mgr.GE(z, ints[1]))), x_pcend),
# pc = 1 & z >= 1 : 2,
mgr.Implies(mgr.And(pcs[1], mgr.GE(z, ints[1])), x_pcs[2]),
# pc = 2 & !(x >= 0) : -1,
mgr.Implies(mgr.And(pcs[2], mgr.Not(mgr.GE(x, ints[0]))), x_pcend),
# pc = 2 & x >= 0 : 3,
mgr.Implies(mgr.And(pcs[2], mgr.GE(x, ints[0])), x_pcs[3]),
# pc = 3 : 4,
mgr.Implies(pcs[3], x_pcs[4]),
# pc = 4 : 2,
mgr.Implies(pcs[4], x_pcs[2]))
# transition labels.
labels = mgr.And(
# (pc = -1 & pc' = -1) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcend, x_pcend),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 0 & pc' = -1) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[0], x_pcend),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 0 & pc' = 1) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[0], x_pcs[1]),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 1 & pc' = -1) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[1], x_pcend),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 1 & pc' = 2) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[1], x_pcs[2]),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 2 & pc' = -1) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[2], x_pcend),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 2 & pc' = 3) -> (x' = x & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[2], x_pcs[3]),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y),
mgr.Equals(x_z, z))),
# (pc = 3 & pc' = 4) -> (x' = y*z - 1 & y' = y & z' = z),
mgr.Implies(
mgr.And(pcs[3], x_pcs[4]),
mgr.And(mgr.Equals(x_x, mgr.Minus(mgr.Times(y, z), ints[1])),
mgr.Equals(x_y, y), mgr.Equals(x_z, z))),
# (pc = 4 & pc' = 2) -> (x' = x & y' = y+1 & z' = z),
mgr.Implies(
mgr.And(pcs[4], x_pcs[2]),
mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, mgr.Plus(y, ints[1])),
mgr.Equals(x_z, z))))
# transition relation.
trans = mgr.And(cfg, labels)
# fairness.
fairness = mgr.Not(pcend)
return symbols, init, trans, fairness
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
pc = mgr.Symbol("pc", types.INT)
x = mgr.Symbol("x", types.INT)
y = mgr.Symbol("y", types.INT)
z = mgr.Symbol("z", types.INT)
symbs = frozenset([pc, x, y, z])
x_pc = symb_to_next(mgr, pc)
x_x = symb_to_next(mgr, x)
x_y = symb_to_next(mgr, y)
x_z = symb_to_next(mgr, z)
res = []
i_0 = mgr.Int(0)
i_1 = mgr.Int(1)
i_2 = mgr.Int(2)
i_3 = mgr.Int(3)
stutter = mgr.Equals(x_y, y)
loc = Location(env, mgr.TRUE(), mgr.LE(x, i_0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_y, mgr.Minus(y, i_1)))
h_y = Hint("h_y0", env, frozenset([y]), symbs)
h_y.set_locs([loc])
res.append(h_y)
loc = Location(env, mgr.LE(z, i_0))
loc.set_progress(0, mgr.Equals(x_z, z))
h_z = Hint("h_z0", env, frozenset([z]), symbs)
h_z.set_locs([loc])
res.append(h_z)
loc0 = Location(env, mgr.Equals(pc, i_1))
loc0.set_progress(1, mgr.Equals(x_pc, i_3))
loc1 = Location(env, mgr.Equals(pc, i_3))
loc1.set_progress(0, mgr.Equals(x_pc, i_1))
h_pc = Hint("h_pc2", env, frozenset([pc]), symbs)
h_pc.set_locs([loc0, loc1])
res.append(h_pc)
loc0 = Location(env, mgr.GE(z, i_3), mgr.GE(y, i_0))
loc0.set_progress(1, mgr.Equals(x_z, y))
loc1 = Location(env, mgr.GE(z, i_0), mgr.GE(x, i_3))
loc1.set_progress(0, mgr.GE(x_z, mgr.Plus(z, x)))
h_z = Hint("h_z3", env, frozenset([z]), symbs)
h_z.set_locs([loc0, loc1])
res.append(h_z)
loc0 = Location(env, mgr.GE(z, i_0))
loc0.set_progress(1, mgr.Equals(x_z, z))
loc1 = Location(env, mgr.GE(z, i_0))
loc1.set_progress(0, mgr.Equals(x_z, mgr.Plus(z, i_3)))
h_z = Hint("h_z4", env, frozenset([z]), symbs)
h_z.set_locs([loc0, loc1])
res.append(h_z)
return frozenset(res)
| 33.587912 | 78 | 0.50777 |
369160cc5ed10563874c306801da38068d1d0228 | 2,496 | py | Python | setup.py | barslmn/django-genome | bba8f5dd8795ebfa70ec8633cee01d7e9c0502c6 | [
"MIT"
] | 10 | 2018-03-07T09:40:55.000Z | 2022-01-24T12:31:30.000Z | setup.py | barslmn/django-genome | bba8f5dd8795ebfa70ec8633cee01d7e9c0502c6 | [
"MIT"
] | 236 | 2017-12-30T14:59:15.000Z | 2022-03-29T14:45:09.000Z | setup.py | barslmn/django-genome | bba8f5dd8795ebfa70ec8633cee01d7e9c0502c6 | [
"MIT"
] | 1 | 2021-01-18T09:48:43.000Z | 2021-01-18T09:48:43.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version(*file_paths):
"""Retrieves the version from genome/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
def parse_requirements():
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open('requirements.txt'))
return [line for line in lineiter if line and not line.startswith("#")]
version = get_version("genome", "__init__.py")
if sys.argv[-1] == 'publish':
try:
import wheel
print("Wheel version: ", wheel.__version__)
except ImportError:
print('Wheel library missing. Please run "pip install wheel"')
sys.exit()
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
if sys.argv[-1] == 'tag':
print("Tagging the version on git:")
os.system("git tag -a %s -m 'version %s'" % (version, version))
os.system("git push --tags")
sys.exit()
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='django-genome',
version=version,
description="""Django app for syncing and storing human genome reference data""",
long_description=readme + '\n\n' + history,
author='Michael A. Gonzalez',
author_email='GonzalezMA@email.chop.edu',
url='https://github.com/genomics-geek/django-genome',
packages=[
'genome',
],
include_package_data=True,
install_requires=parse_requirements(),
license="MIT",
zip_safe=False,
keywords='django-genome',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
)
| 30.439024 | 85 | 0.625801 |
edcdc1296013bcf2b88d383a5bf1a95fb1d4c9eb | 2,509 | py | Python | data/p4VQE/R4/benchmark/startQiskit_QC41.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p4VQE/R4/benchmark/startQiskit_QC41.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p4VQE/R4/benchmark/startQiskit_QC41.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | # qubit number=3
# total number=9
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
for edge in E:
k = edge[0]
l = edge[1]
prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])
prog.p(gamma, k)
prog.p(gamma, l)
prog.rx(2 * beta, range(len(V)))
prog.swap(input_qubit[3],input_qubit[0]) # number=5
prog.swap(input_qubit[3],input_qubit[0]) # number=6
prog.x(input_qubit[3]) # number=7
prog.x(input_qubit[3]) # number=8
# circuit end
return prog
if __name__ == '__main__':
n = 4
V = np.arange(0, n, 1)
E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]
G = nx.Graph()
G.add_nodes_from(V)
G.add_weighted_edges_from(E)
step_size = 0.1
a_gamma = np.arange(0, np.pi, step_size)
a_beta = np.arange(0, np.pi, step_size)
a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)
F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (
1 + np.cos(4 * a_gamma) ** 2)
result = np.where(F1 == np.amax(F1))
a = list(zip(result[0], result[1]))[0]
gamma = a[0] * step_size
beta = a[1] * step_size
prog = make_circuit(4)
sample_shot =5600
writefile = open("../data/startQiskit_QC41.csv", "w")
# prog.draw('mpl', filename=(kernel + '.png'))
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = provider.get_backend("ibmq_5_yorktown")
circuit1 = transpile(prog, FakeYorktown())
circuit1.measure_all()
prog = circuit1
info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()
print(info, file=writefile)
print("results end", file=writefile)
print(circuit1.depth(), file=writefile)
print(circuit1, file=writefile)
writefile.close()
| 27.271739 | 118 | 0.634516 |
87222aa805c7555a19dc95696014105de54a2a64 | 2,343 | py | Python | examples/exm2_mpl.py | opetlund/TMM4135-CALFEM | e15621a6fec3bef7f07cfbc9abb80ad10551d6d0 | [
"MIT"
] | null | null | null | examples/exm2_mpl.py | opetlund/TMM4135-CALFEM | e15621a6fec3bef7f07cfbc9abb80ad10551d6d0 | [
"MIT"
] | null | null | null | examples/exm2_mpl.py | opetlund/TMM4135-CALFEM | e15621a6fec3bef7f07cfbc9abb80ad10551d6d0 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Example 02
Creating geometry from B-Splines and circle arcs.
Also shows how to set ID numbers for geometry entities and how to specify element density.
'''
import matplotlib.pyplot as plt
import matplotlib.collections
import numpy as np
import calfem.geometry as cfg
import calfem.mesh as cfm
import calfem.vis_mpl as cfv
# ---- Define geometry ------------------------------------------------------
g = cfg.Geometry()
# Add points:
# In this example we set the IDs manually.
g.point([ -2, 0], ID=0)
g.point([ 0, 1], ID=1, elSize=5) # elSize determines the size of the elements near this point.
g.point([ 1, 0], 2, elSize=5) # elSize is 1 by default. Larger number means less dense mesh.
g.point([ 0, -2], 3) # Size means the length of the sides of the elements.
g.point([ 0, 0], 4, elSize=5)
g.point([ .5, .2], 5)
g.point([-.5, .5], 6)
g.point([-.7,-.5], 7)
# Add curves:
# The 3 points that define the circle arc are [start, center, end].
# The arc must be smaller than Pi.
g.circle([1, 4, 2], 2)
# BSplines are similar to Splines, but do not necessarily pass through the
# control points.
g.bspline([5,6,7,5], 5)
g.bspline([1,0,3,2], 4)
# Add surface:
g.surface([4,2], [[5]])
# Markers do not have to be set when the curve is created. It can be done afterwards.
# Set marker=80 for curves 2 and 4:
for curveID in [2, 4]:
g.curveMarker(curveID, 80)
# ---- Generate mesh --------------------------------------------------------
mesh = cfm.GmshMesh(g)
# Element type 2 is triangle. (3 is quad. See user manual for more element types)
mesh.el_type = 3
# Degrees of freedom per node.
mesh.dofs_per_node = 2
mesh.el_size_factor = 0.05
# mesh.gmsh_exec_path = "D:\\vsmn20-software\\gmsh\gmsh.exe"
coords, edof, dofs, bdofs, elementmarkers = mesh.create()
# ---- Visualise mesh -------------------------------------------------------
# Hold left mouse button to pan.
# Hold right mouse button to zoom.
# Draw the geometry.
cfv.draw_geometry(g, labelCurves=True)
# New figure window
cfv.figure()
# Draws the mesh.
cfv.draw_mesh(
coords=coords,
edof=edof,
dofs_per_node = mesh.dofs_per_node,
el_type=mesh.el_type,
filled=True,
title="Example 02"
)
# Show grid
#cfv.show_grid()
# Enter main loop
cfv.show_and_wait()
| 22.747573 | 98 | 0.624413 |
418c91eefdb42d8d6d224ad598479d7d452c2dc2 | 8,579 | py | Python | ydr/operators.py | Markus1812/Sollumz | 8d407bd04e47b5f1869930093ee7583b4e4fd3bf | [
"MIT"
] | 1 | 2022-02-10T20:50:20.000Z | 2022-02-10T20:50:20.000Z | ydr/operators.py | Markus1812/Sollumz | 8d407bd04e47b5f1869930093ee7583b4e4fd3bf | [
"MIT"
] | null | null | null | ydr/operators.py | Markus1812/Sollumz | 8d407bd04e47b5f1869930093ee7583b4e4fd3bf | [
"MIT"
] | null | null | null | from ..sollumz_helper import SOLLUMZ_OT_base
from ..sollumz_properties import SOLLUMZ_UI_NAMES, LightType, SollumType, TimeFlags
from ..sollumz_operators import SelectTimeFlagsRange, ClearTimeFlags
from ..ydr.shader_materials import create_shader, create_tinted_shader_graph, shadermats
from ..tools.drawablehelper import *
from ..resources.shader import ShaderManager
import traceback
import bpy
class SOLLUMZ_OT_create_drawable(SOLLUMZ_OT_base, bpy.types.Operator):
"""Create a sollumz drawable of the selected type."""
bl_idname = "sollumz.createdrawable"
bl_label = f"Create Drawable"
bl_action = "Create a Drawable"
bl_update_view = True
def run(self, context):
aobj = context.active_object
selected = context.selected_objects
drawable_type = context.scene.create_drawable_type
if drawable_type == SollumType.DRAWABLE and len(selected) > 0:
convert_selected_to_drawable(
selected, context.scene.use_mesh_name, context.scene.create_seperate_objects)
self.message(
f"Succesfully converted {', '.join([obj.name for obj in context.selected_objects])} to a {SOLLUMZ_UI_NAMES[SollumType.DRAWABLE]}.")
return True
else:
obj = create_drawable(drawable_type)
if aobj:
obj.parent = aobj
return True
class SOLLUMZ_OT_create_light(SOLLUMZ_OT_base, bpy.types.Operator):
bl_idname = "sollumz.create_light"
bl_label = "Create Light"
bl_action = bl_label
def run(self, context):
light_type = context.scene.create_light_type
blender_light_type = 'POINT'
if light_type == LightType.SPOT:
blender_light_type = 'SPOT'
light_data = bpy.data.lights.new(
name=SOLLUMZ_UI_NAMES[light_type], type=blender_light_type)
light_data.light_properties.type = light_type
obj = bpy.data.objects.new(
name=SOLLUMZ_UI_NAMES[light_type], object_data=light_data)
obj.sollum_type = SollumType.LIGHT
bpy.context.collection.objects.link(obj)
class SOLLUMZ_OT_auto_convert_material(SOLLUMZ_OT_base, bpy.types.Operator):
"""Convert material to a sollumz shader material"""
bl_idname = "sollumz.autoconvertmaterial"
bl_label = "Convert Material To Shader Material"
bl_action = "Convert a Material To a Shader Material"
def run(self, context):
for obj in context.selected_objects:
if len(obj.data.materials) == 0:
self.messages.append(
f"{obj.name} has no materials to convert.")
for material in obj.data.materials:
new_material = convert_material(material)
if new_material != None:
for ms in obj.material_slots:
if(ms.material == material):
ms.material = new_material
return True
class SOLLUMZ_OT_convert_material_to_selected(SOLLUMZ_OT_base, bpy.types.Operator):
"""Convert objects material to the selected sollumz shader"""
bl_idname = "sollumz.convertmaterialtoselected"
bl_label = "Convert Material To Selected Sollumz Shader"
bl_action = "Convert a Material To Selected Sollumz Shader"
def convert_material(self, shader, obj):
mat = obj.active_material
if mat == None:
self.message(f"No active material on {obj.name} will be skipped")
return
new_material = convert_material_to_selected(mat, shader)
if new_material != None:
for ms in obj.material_slots:
if(ms.material == mat):
ms.material = new_material
def run(self, context):
objs = bpy.context.selected_objects
if(len(objs) == 0):
self.warning(
f"Please select a object with materials.")
return False
shader = shadermats[context.scene.shader_material_index].value
for obj in objs:
self.convert_material(shader, obj)
return True
class SOLLUMZ_OT_create_shader_material(SOLLUMZ_OT_base, bpy.types.Operator):
"""Create a sollumz shader material"""
bl_idname = "sollumz.createshadermaterial"
bl_label = "Create Shader Material"
bl_action = "Create a Shader Material"
def create_material(self, context, obj, shader):
mat = create_shader(shader)
obj.data.materials.append(mat)
if mat.shader_properties.filename in ShaderManager.tinted_shaders():
create_tinted_shader_graph(obj)
for n in mat.node_tree.nodes:
if isinstance(n, bpy.types.ShaderNodeTexImage):
texture = bpy.data.images.new(
name="Texture", width=512, height=512)
n.image = texture
def run(self, context):
objs = bpy.context.selected_objects
if(len(objs) == 0):
self.warning(
f"Please select a object to add a shader material to.")
return False
for obj in objs:
shader = shadermats[context.scene.shader_material_index].value
try:
self.create_material(context, obj, shader)
self.message(f"Added a {shader} shader to {obj.name}.")
except:
self.message(
f"Failed adding {shader} to {obj.name} because : \n {traceback.format_exc()}")
return True
class SOLLUMZ_OT_set_all_textures_embedded(SOLLUMZ_OT_base, bpy.types.Operator):
"""Sets all textures to embedded on the selected objects active material"""
bl_idname = "sollumz.setallembedded"
bl_label = "Set all Textures Embedded"
bl_action = "Set all Textures Embedded"
def set_textures_embedded(self, obj):
mat = obj.active_material
if mat == None:
self.message(f"No active material on {obj.name} will be skipped")
return
if mat.sollum_type == MaterialType.SHADER:
for node in mat.node_tree.nodes:
if(isinstance(node, bpy.types.ShaderNodeTexImage)):
node.texture_properties.embedded = True
self.message(
f"Set {obj.name}s material {mat.name} textures to embedded.")
else:
self.message(
f"Skipping object {obj.name} because it does not have a sollumz shader active.")
def run(self, context):
objs = bpy.context.selected_objects
if(len(objs) == 0):
self.warning(
f"Please select a object to set all textures embedded.")
return False
for obj in objs:
self.set_textures_embedded(obj)
return True
class SOLLUMZ_OT_BONE_FLAGS_NewItem(SOLLUMZ_OT_base, bpy.types.Operator):
bl_idname = "sollumz.bone_flags_new_item"
bl_label = "Add a new item"
bl_action = "Add a Bone Flag"
def run(self, context):
bone = context.active_pose_bone.bone
bone.bone_properties.flags.add()
self.message(f"Added bone flag to bone: {bone.name}")
return True
class SOLLUMZ_OT_BONE_FLAGS_DeleteItem(SOLLUMZ_OT_base, bpy.types.Operator):
bl_idname = "sollumz.bone_flags_delete_item"
bl_label = "Deletes an item"
bl_action = "Delete a Bone Flag"
@ classmethod
def poll(cls, context):
if context.active_pose_bone:
return context.active_pose_bone.bone.bone_properties.flags
def run(self, context):
bone = context.active_pose_bone.bone
list = bone.bone_properties.flags
index = bone.bone_properties.ul_index
list.remove(index)
bone.bone_properties.ul_index = min(
max(0, index - 1), len(list) - 1)
self.message(f"Deleted bone flag from: {bone.name}")
return True
class SOLLUMZ_OT_LIGHT_TIME_FLAGS_select_range(SelectTimeFlagsRange, bpy.types.Operator):
bl_idname = "sollumz.light_time_flags_select_range"
@classmethod
def poll(cls, context):
return context.light and context.active_object.sollum_type == SollumType.LIGHT
def get_flags(self, context):
light = context.light
return light.time_flags
class SOLLUMZ_OT_LIGHT_TIME_FLAGS_clear(ClearTimeFlags, bpy.types.Operator):
bl_idname = "sollumz.light_time_flags_clear"
@classmethod
def poll(cls, context):
return context.light and context.active_object.sollum_type == SollumType.LIGHT
def get_flags(self, context):
light = context.light
return light.time_flags
| 36.198312 | 147 | 0.653689 |
940d9d10e10bd5ff5b1a1aef1da95c705a854a4a | 597 | py | Python | src/gazebo_server/__init__.py | mvukov/gazebo_server | e1a30fee043e14a31ca5a70d441f375d155f9a65 | [
"Apache-2.0"
] | null | null | null | src/gazebo_server/__init__.py | mvukov/gazebo_server | e1a30fee043e14a31ca5a70d441f375d155f9a65 | [
"Apache-2.0"
] | null | null | null | src/gazebo_server/__init__.py | mvukov/gazebo_server | e1a30fee043e14a31ca5a70d441f375d155f9a65 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Milan Vukov. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| 42.642857 | 74 | 0.763819 |
aaade5219f9d2ad2ff7a0b1fdf63f708214082b1 | 1,163 | py | Python | deprecated_examples/affect/humor_early_fusion.py | TianhaoFu/MultiBench | b174a3187124d6f92be1ff3b487eef292f7883bb | [
"MIT"
] | null | null | null | deprecated_examples/affect/humor_early_fusion.py | TianhaoFu/MultiBench | b174a3187124d6f92be1ff3b487eef292f7883bb | [
"MIT"
] | null | null | null | deprecated_examples/affect/humor_early_fusion.py | TianhaoFu/MultiBench | b174a3187124d6f92be1ff3b487eef292f7883bb | [
"MIT"
] | null | null | null | import sys
import os
sys.path.append(os.getcwd())
import torch
from training_structures.Simple_Early_Fusion import train, test
from fusions.common_fusions import ConcatEarly
from get_data import get_dataloader
from unimodals.common_models import GRU, MLP
traindata, validdata, testdata = get_dataloader('../affect/processed/humor_data.pkl')
# humor 371 81 300
encoders = GRU(752, 1128, dropout=True, has_padding=True).cuda()
head = MLP(1128, 512, 1).cuda()
# encoders=[GRU(35,70,dropout=True,has_padding=True).cuda(), \
# GRU(74,150,dropout=True,has_padding=True).cuda(),\
# GRU(300,600,dropout=True,has_padding=True).cuda()]
# head=MLP(820,400,1).cuda()
fusion = ConcatEarly().cuda()
# Support simple early_fusion and early_fusion with removing bias
train(encoders, fusion, head, traindata, validdata, 1000, True, True, \
task="classification", optimtype=torch.optim.AdamW, lr=1e-5, save='humor_ef_best.pt', \
weight_decay=0.01, criterion=torch.nn.MSELoss(), regularization=False)
print("Testing:")
model=torch.load('humor_ef_best.pt').cuda()
test(model, testdata, True, torch.nn.L1Loss(), "classification")
# test(model,testdata,True,)
| 33.228571 | 91 | 0.750645 |
043c34967b0578fa10c25bbf8dfbbcdc1521ef74 | 1,305 | py | Python | monk/system_unit_tests/keras/test_layer_max_pooling1d.py | Shreyashwaghe/monk_v1 | 4ee4d9483e8ffac9b73a41f3c378e5abf5fc799b | [
"Apache-2.0"
] | 7 | 2020-07-26T08:37:29.000Z | 2020-10-30T10:23:11.000Z | monk/system_unit_tests/keras/test_layer_max_pooling1d.py | mursalfk/monk_v1 | 62f34a52f242772186ffff7e56764e958fbcd920 | [
"Apache-2.0"
] | null | null | null | monk/system_unit_tests/keras/test_layer_max_pooling1d.py | mursalfk/monk_v1 | 62f34a52f242772186ffff7e56764e958fbcd920 | [
"Apache-2.0"
] | 1 | 2020-10-07T12:57:44.000Z | 2020-10-07T12:57:44.000Z | import os
import sys
sys.path.append("../../../monk/");
import psutil
from keras_prototype import prototype
from compare_prototype import compare
from common import print_start
from common import print_status
import tensorflow as tf
import numpy as np
def test_layer_max_pooling1d(system_dict):
forward = True;
test = "test_layer_max_pooling1d";
system_dict["total_tests"] += 1;
print_start(test, system_dict["total_tests"])
if(forward):
try:
gtf = prototype(verbose=0);
gtf.Prototype("sample-project-1", "sample-experiment-1");
network = [];
network.append(gtf.max_pooling1d(kernel_size=3));
gtf.Compile_Network(network, data_shape=(3, 32), use_gpu=False);
x = tf.placeholder(tf.float32, shape=(1, 32, 3))
y = gtf.system_dict["local"]["model"](x);
system_dict["successful_tests"] += 1;
print_status("Pass");
except Exception as e:
system_dict["failed_tests_exceptions"].append(e);
system_dict["failed_tests_lists"].append(test);
forward = False;
print_status("Fail");
else:
system_dict["skipped_tests_lists"].append(test);
print_status("Skipped");
return system_dict
| 27.765957 | 76 | 0.629885 |
8ab4ecd28e5704c59249a66883d3c3faca1bbd59 | 4,018 | py | Python | data_integration/logging/system_statistics.py | ierosodin/data-integration | f3ee414e8b8994e5b740a374c0594e40862ff6e9 | [
"MIT"
] | null | null | null | data_integration/logging/system_statistics.py | ierosodin/data-integration | f3ee414e8b8994e5b740a374c0594e40862ff6e9 | [
"MIT"
] | null | null | null | data_integration/logging/system_statistics.py | ierosodin/data-integration | f3ee414e8b8994e5b740a374c0594e40862ff6e9 | [
"MIT"
] | null | null | null | """Generation of system statistics events (cpu, io, net, ram)"""
import datetime
import multiprocessing
import time
from .. import config
from ..logging import events
class SystemStatistics(events.Event):
def __init__(self, timestamp: datetime.datetime, *, disc_read: float = None, disc_write: float = None,
net_recv: float = None, net_sent: float = None,
cpu_usage: float = None, mem_usage: float = None, swap_usage: float = None,
iowait: float = None) -> None:
"""
Statistics about the system which runs the pipeline
Individual statistics can be None
Args:
timestamp: The time when the statistics where gathered
disc_read: read IO for discs in MB/s (summed)
disc_write: write IO for discs in MB/s (summed)
net_recv: read IO on all network adapters in MB/s (summed)
net_sent: write IO on all network adapters in MB/s (summed)
cpu_usage: cpu load on all cores in percent (summed)
mem_usage: RAM used in percent of total ram
swap_usage: swap used in percent of total swap
iowait: How much time the CPU spends waiting for IO
"""
super().__init__()
self.timestamp = timestamp
self.disc_read = disc_read
self.disc_write = disc_write
self.net_recv = net_recv
self.net_sent = net_sent
self.cpu_usage = cpu_usage
self.mem_usage = mem_usage
self.swap_usage = swap_usage
self.iowait = iowait
def generate_system_statistics(event_queue: multiprocessing.Queue) -> None:
"""
Generates one SystemStatistics event per configurable period and puts them in to a queue
Ideas from
http://off-the-stack.moorman.nu/2013-09-28-gather-metrics-using-psutil.html
https://github.com/giampaolo/psutil/tree/master/scripts
:param event_queue: The queue to write the events to
"""
import psutil
def cpu_usage():
cpu_times = psutil.cpu_times_percent()
return cpu_times.user + cpu_times.system
def mem_usage():
mem = psutil.virtual_memory()
return 100.0 * mem.used / mem.total
def swap_usage():
swap = psutil.swap_memory()
return 100.0 * swap.used / swap.total if swap.total > 0 else None
# immediately send event for current cpu, mem and swap usage
event_queue.put(SystemStatistics(
datetime.datetime.now(), cpu_usage=cpu_usage(), mem_usage=mem_usage(), swap_usage=swap_usage()))
period = config.system_statistics_collection_period()
n = 0
# some counters on WSL1 return None because psutil thinks it's linux,
# but the linux kernel API is not implemented and fails
# This lets it always return 0 for all attributes on that counter and lets at least CPU show up
class _zero():
def __getattr__(self, item): return 0
zero = _zero()
# capture current disc and net state for later diff
discs_last = psutil.disk_io_counters() or zero
nets_last = psutil.net_io_counters() or zero
mb = 1024 * 1024
time.sleep(period)
while True:
discs_cur = psutil.disk_io_counters() or zero
nets_cur = psutil.net_io_counters() or zero
event_queue.put(SystemStatistics(
datetime.datetime.now(),
disc_read=(discs_cur.read_bytes - discs_last.read_bytes) / mb / period,
disc_write=(discs_cur.write_bytes - discs_last.write_bytes) / mb / period,
net_recv=(nets_cur.bytes_recv - nets_last.bytes_recv) / mb / period,
net_sent=(nets_cur.bytes_sent - nets_last.bytes_sent) / mb / period,
cpu_usage=cpu_usage(), mem_usage=mem_usage(), swap_usage=swap_usage()))
nets_last = nets_cur
discs_last = discs_cur
# double period every 100 measurements in order to avoid sending too many requests to frontend
n += 1
if n % 100 == 0:
period *= 2
time.sleep(period)
| 37.90566 | 106 | 0.655301 |
3f22d26e98dcf9da820b534beabdb31416905645 | 253 | py | Python | sample_app/manage.py | cpersico/django-objectcounters | 695e61d07ec4a07dea45164a876288b7bad30cea | [
"BSD-3-Clause"
] | null | null | null | sample_app/manage.py | cpersico/django-objectcounters | 695e61d07ec4a07dea45164a876288b7bad30cea | [
"BSD-3-Clause"
] | null | null | null | sample_app/manage.py | cpersico/django-objectcounters | 695e61d07ec4a07dea45164a876288b7bad30cea | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample_app.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| 23 | 74 | 0.774704 |
caa9c7f3a746d782ab10c84b81995f2e87199da6 | 111 | py | Python | go_space/go_types/action_lib.py | gaffney2010/go-space | 928a743ce913dec30db5226fb4588e056128725e | [
"Apache-2.0"
] | null | null | null | go_space/go_types/action_lib.py | gaffney2010/go-space | 928a743ce913dec30db5226fb4588e056128725e | [
"Apache-2.0"
] | null | null | null | go_space/go_types/action_lib.py | gaffney2010/go-space | 928a743ce913dec30db5226fb4588e056128725e | [
"Apache-2.0"
] | null | null | null | import enum
class Action(enum.Enum):
ACK = 1
# Should remove this chonk now, it's dead.
KILL = 2
| 13.875 | 46 | 0.621622 |
b4d51f6d1a0c59749e7feb27e427b53eb1b7b0da | 2,388 | py | Python | tensorflow_datasets/summarization/cnn_dailymail_test.py | daniel-trejobanos/tf-ds-321 | e3f5b1771a176dc552c3a99f51f3a5ffbe105852 | [
"Apache-2.0"
] | 2 | 2020-10-12T07:09:38.000Z | 2021-03-05T12:48:23.000Z | tensorflow_datasets/summarization/cnn_dailymail_test.py | javierespinozat/datasets | 1465d97b2e8b2a030f5df7872e8390b90dba8926 | [
"Apache-2.0"
] | null | null | null | tensorflow_datasets/summarization/cnn_dailymail_test.py | javierespinozat/datasets | 1465d97b2e8b2a030f5df7872e8390b90dba8926 | [
"Apache-2.0"
] | 1 | 2021-06-30T17:45:23.000Z | 2021-06-30T17:45:23.000Z | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for tensorflow_datasets.text.cnn_dailymail."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
from tensorflow_datasets import testing
import tensorflow_datasets.public_api as tfds
from tensorflow_datasets.summarization import cnn_dailymail
_STORY_FILE = b"""Some article.
This is some article text.
@highlight
highlight text
@highlight
Highlight two
@highlight
highlight Three
"""
class CnnDailymailTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = cnn_dailymail.CnnDailymail
SPLITS = {'train': 3, 'validation': 2, 'test': 2}
DL_EXTRACT_RESULT = {
'cnn_stories': '',
'dm_stories': '',
'test_urls': 'all_test.txt',
'train_urls': 'all_train.txt',
'val_urls': 'all_val.txt'
}
def test_get_art_abs(self):
with tempfile.NamedTemporaryFile(delete=True) as f:
f.write(_STORY_FILE)
f.flush()
article, abstract = cnn_dailymail._get_art_abs(f.name,
tfds.core.Version('1.0.0'))
self.assertEqual('Some article. This is some article text.', article)
# This is a bit weird, but the original code at
# https://github.com/abisee/cnn-dailymail/ adds space before period
# for abstracts and we retain this behavior.
self.assertEqual('highlight text . Highlight two . highlight Three .',
abstract)
article, abstract = cnn_dailymail._get_art_abs(f.name,
tfds.core.Version('2.0.0'))
self.assertEqual('highlight text .\nHighlight two .\nhighlight Three .',
abstract)
if __name__ == '__main__':
testing.test_main()
| 30.615385 | 80 | 0.688023 |
6c3aca7eddba39e30b9cac64b77985cb75f9243d | 25,506 | py | Python | src/compas_fea/fea/steps.py | franaudo/fea | e164256bac179116520d19d6fc54c98de0610896 | [
"MIT"
] | null | null | null | src/compas_fea/fea/steps.py | franaudo/fea | e164256bac179116520d19d6fc54c98de0610896 | [
"MIT"
] | null | null | null | src/compas_fea/fea/steps.py | franaudo/fea | e164256bac179116520d19d6fc54c98de0610896 | [
"MIT"
] | null | null | null | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import json
# Author(s): Andrew Liew (github.com/andrewliew)
__all__ = [
'Steps',
]
dofs = ['x', 'y', 'z', 'xx', 'yy', 'zz']
class Steps(object):
def __init__(self):
pass
def write_steps(self):
self.write_section('Steps')
self.blank_line()
displacements = self.structure.displacements
loads = self.structure.loads
steps = self.structure.steps
sets = self.structure.sets
fields = self.fields
# temp folder
temp = '{0}{1}/'.format(self.structure.path, self.structure.name)
try:
os.stat(temp)
for file in os.listdir(temp):
os.remove(os.path.join(temp, file))
except Exception:
os.mkdir(temp)
# Steps
for key in self.structure.steps_order[1:]:
step = steps[key]
stype = step.__name__
s_index = step.index
factor = getattr(step, 'factor', 1)
increments = getattr(step, 'increments', 100)
iterations = getattr(step, 'iterations', 100)
tolerance = getattr(step, 'tolerance', None)
method = getattr(step, 'type')
modes = getattr(step, 'modes', None)
modify = getattr(step, 'modify', None)
nlgeom = 'YES' if getattr(step, 'nlgeom', None) else 'NO'
op = 'MOD' if modify else 'NEW'
# =====================================================================================================
# =====================================================================================================
# HEADER
# =====================================================================================================
# =====================================================================================================
if stype in ['GeneralStep', 'BucklingStep', 'ModalStep']:
self.write_subsection(key)
# -------------------------------------------------------------------------------------------------
# OpenSees
# -------------------------------------------------------------------------------------------------
if self.software == 'opensees':
if stype != 'ModalStep':
self.write_line('timeSeries Constant {0} -factor 1.0'.format(s_index))
self.write_line('pattern Plain {0} {0} -fact {1} {2}'.format(s_index, 1, '{'))
self.blank_line()
# -------------------------------------------------------------------------------------------------
# Abaqus
# -------------------------------------------------------------------------------------------------
elif self.software == 'abaqus':
if stype == 'ModalStep':
self.write_line('*STEP, NAME={0}'.format(key))
self.write_line('*FREQUENCY, EIGENSOLVER=LANCZOS, NORMALIZATION=MASS')
self.write_line('{0}'.format(modes))
else:
p = ', PERTURBATION' if stype == 'BucklingStep' else ''
self.write_line('*STEP, NLGEOM={0}, NAME={1}{2}, INC={3}'.format(nlgeom, key, p, increments))
self.blank_line()
self.write_line('*{0}'.format(method.upper()))
self.blank_line()
if stype == 'BucklingStep':
self.write_line('{0}, {1}, {2}, {3}'.format(modes, modes, 5 * modes, increments))
self.blank_line()
# -------------------------------------------------------------------------------------------------
# Ansys
# -------------------------------------------------------------------------------------------------
elif self.software == 'ansys':
pass
# =====================================================================================================
# =====================================================================================================
# LOADS
# =====================================================================================================
# =====================================================================================================
if getattr(step, 'loads', None):
if isinstance(step.loads, str):
step.loads = [step.loads]
for k in step.loads:
self.write_subsection(k)
load = loads[k]
ltype = load.__name__
com = getattr(load, 'components', None)
axes = getattr(load, 'axes', None)
nodes = getattr(load, 'nodes', None)
fact = factor.get(k, 1.0) if isinstance(factor, dict) else factor
if com:
gx = com.get('x', 0)
gy = com.get('y', 0)
gz = com.get('z', 0)
if isinstance(nodes, str):
nodes = [nodes]
if isinstance(load.elements, str):
elements = [load.elements]
else:
elements = load.elements
# -------------------------------------------------------------------------------------------------
# OpenSees
# -------------------------------------------------------------------------------------------------
if self.software == 'opensees':
# PointLoad
# ---------
if ltype == 'PointLoad':
compnents = ' '.join([str(com[dof] * fact) for dof in dofs[:self.ndof]])
for node in nodes:
ns = sets[node].selection if isinstance(node, str) else node
for ni in [i + 1 for i in ns]:
self.write_line('load {0} {1}'.format(ni, compnents))
# Gravity
# -------
elif ltype == 'GravityLoad':
for nkey, node in self.structure.nodes.items():
W = - fact * node.mass * 9.81
self.write_line('load {0} {1} {2} {3} -0.0 -0.0 -0.0'.format(
nkey + 1, gx * W, gy * W, gz * W))
# LineLoad
# --------
elif ltype == 'LineLoad':
if axes == 'global':
raise NotImplementedError
elif axes == 'local':
elements = ' '.join([str(i + 1) for i in sets[k].selection])
lx = -com['x'] * fact
ly = -com['y'] * fact
self.write_line('eleLoad -ele {0} -type -beamUniform {1} {2}'.format(elements, ly, lx))
# -------------------------------------------------------------------------------------------------
# Abaqus
# -------------------------------------------------------------------------------------------------
elif self.software == 'abaqus':
# PointLoad
# ---------
if ltype == 'PointLoad':
self.write_line('*CLOAD, OP={0}'.format(op))
self.blank_line()
for node in nodes:
ni = node if isinstance(node, str) else node + 1
for c, dof in enumerate(dofs, 1):
if com[dof]:
self.write_line('{0}, {1}, {2}'.format(ni, c, com[dof] * fact))
# AreaLoad
# --------
elif ltype == 'AreaLoad':
for k in elements:
self.write_line('*DLOAD, OP={0}'.format(op))
self.blank_line()
if com['z']:
self.write_line('{0}, P, {1}'.format(k, fact * com['z']))
self.blank_line()
# PointLoads
# ----------
elif ltype == 'PointLoads':
self.write_line('*CLOAD, OP={0}'.format(op))
self.blank_line()
for node, coms in com.items():
for ci, value in coms.items():
index = dofs.index(ci) + 1
self.write_line('{0}, {1}, {2}'.format(node + 1, index, value * fact))
# Gravity
# -------
elif ltype == 'GravityLoad':
for k in elements:
self.write_line('*DLOAD, OP={0}'.format(op))
self.blank_line()
self.write_line('{0}, GRAV, {1}, {2}, {3}, {4}'.format(k, -9.81 * fact, gx, gy, gz))
self.blank_line()
# TributaryLoad
# -------------
elif ltype == 'TributaryLoad':
self.write_line('*CLOAD, OP={0}'.format(op))
self.blank_line()
for node in sorted(com, key=int):
ni = node + 1
for ci, dof in enumerate(dofs[:3], 1):
if com[node][dof]:
self.write_line('{0}, {1}, {2}'.format(ni, ci, com[node][dof] * fact))
# LineLoad
# --------
elif ltype == 'LineLoad':
for k in elements:
self.write_line('*DLOAD, OP={0}'.format(op))
self.blank_line()
if axes == 'global':
for dof in dofs[:3]:
if com[dof]:
self.write_line('{0}, P{1}, {2}'.format(k, dof.upper(), fact * com[dof]))
elif axes == 'local':
if com['x']:
self.write_line('{0}, P1, {1}'.format(k, fact * com['x']))
if com['y']:
self.write_line('{0}, P2, {1}'.format(k, fact * com['y']))
# Prestress
# ---------
elif ltype == 'PrestressLoad':
for k in elements:
stresses = ''
if com['sxx']:
stresses += str(com['sxx'] * fact)
self.write_line('*INITIAL CONDITIONS, TYPE=STRESS')
self.blank_line()
self.write_line('{0}, {1}'.format(k, stresses))
# -------------------------------------------------------------------------------------------------
# Ansys
# -------------------------------------------------------------------------------------------------
elif self.software == 'ansys':
pass
self.blank_line()
self.blank_line()
self.blank_line()
# =====================================================================================================
# =====================================================================================================
# DISPLACEMENTS
# =====================================================================================================
# =====================================================================================================
if getattr(step, 'displacements', None):
if isinstance(step.displacements, str):
step.displacements = [step.displacements]
for k in step.displacements:
displacement = displacements[k]
com = displacement.components
nodes = displacement.nodes
if isinstance(nodes, str):
nodes = [nodes]
fact = factor.get(k, 1.0) if isinstance(factor, dict) else factor
# -------------------------------------------------------------------------------------------------
# OpenSees
# -------------------------------------------------------------------------------------------------
if self.software == 'opensees':
for node in nodes:
ns = sets[node].selection if isinstance(node, str) else node
for ni in [i + 1 for i in ns]:
for c, dof in enumerate(dofs[:self.ndof], 1):
if com[dof] is not None:
self.write_line('sp {0} {1} {2}'.format(ni, c, com[dof]))
self.blank_line()
self.blank_line()
# -------------------------------------------------------------------------------------------------
# Abaqus
# -------------------------------------------------------------------------------------------------
elif self.software == 'abaqus':
if stype not in ['ModalStep', 'BucklingStep']:
self.write_line('*BOUNDARY')
self.blank_line()
for node in nodes:
ni = node if isinstance(node, str) else node + 1
for c, dof in enumerate(dofs, 1):
if com[dof] is not None:
self.write_line('{0}, {1}, {1}, {2}'.format(ni, c, com[dof] * fact))
self.blank_line()
self.blank_line()
# -------------------------------------------------------------------------------------------------
# Ansys
# -------------------------------------------------------------------------------------------------
elif self.software == 'ansys':
pass
# =====================================================================================================
# =====================================================================================================
# OUTPUT
# =====================================================================================================
# =====================================================================================================
self.write_subsection('Output')
# -------------------------------------------------------------------------------------------------
# OpenSees
# -------------------------------------------------------------------------------------------------
if self.software == 'opensees':
# Node recorders
node_output = {
'u': '1 2 3 disp',
'ur': '4 5 6 disp',
'rf': '1 2 3 reaction',
'rm': '4 5 6 reaction',
}
if stype != 'ModalStep':
self.write_line('}')
self.blank_line()
self.write_subsection('Node recorders')
prefix = 'recorder Node -file {0}{1}_'.format(temp, key)
n = self.structure.node_count()
for field in node_output:
if field in fields:
dof = node_output[field]
self.write_line('{0}{1}.out -time -nodeRange 1 {2} -dof {3}'.format(prefix, field, n, dof))
self.blank_line()
# Sort elements
truss_elements = ''
beam_elements = ''
spring_elements = ''
truss_ekeys = []
beam_ekeys = []
spring_ekeys = []
for ekey, element in self.structure.elements.items():
etype = element.__name__
n = '{0} '.format(ekey + 1)
if etype == 'TrussElement':
truss_elements += n
truss_ekeys.append(ekey)
elif etype == 'BeamElement':
beam_elements += n
beam_ekeys.append(ekey)
elif etype == 'SpringElement':
spring_elements += n
spring_ekeys.append(ekey)
# Element recorders
self.blank_line()
self.write_subsection('Element recorders')
prefix = 'recorder Element -file {0}{1}_'.format(temp, key)
if 'sf' in fields:
if truss_elements:
self.write_line('{0}sf_truss.out -time -ele {1} axialForce'.format(prefix, truss_elements))
if beam_elements:
self.write_line('{0}sf_beam.out -time -ele {1} localForce'.format(prefix, beam_elements))
if 'spf' in fields:
if spring_elements:
self.write_line('{0}spf_spring.out -time -ele {1} basicForces'.format(prefix,
spring_elements))
# ekeys
with open('{0}truss_ekeys.json'.format(temp), 'w') as file:
json.dump({'truss_ekeys': truss_ekeys}, file)
with open('{0}beam_ekeys.json'.format(temp), 'w') as file:
json.dump({'beam_ekeys': beam_ekeys}, file)
with open('{0}spring_ekeys.json'.format(temp), 'w') as file:
json.dump({'spring_ekeys': spring_ekeys}, file)
# Solver
self.blank_line()
self.write_subsection('Solver')
self.blank_line()
self.write_line('constraints Transformation')
self.write_line('numberer RCM')
self.write_line('system ProfileSPD')
self.write_line('test NormUnbalance {0} {1} 5'.format(tolerance, iterations))
self.write_line('algorithm NewtonLineSearch')
self.write_line('integrator LoadControl {0}'.format(1. / increments))
self.write_line('analysis Static')
self.write_line('analyze {0}'.format(increments))
else:
self.blank_line()
self.write_subsection('Node recorders')
for mode in range(modes):
prefix = 'recorder Node -file {0}{1}_u_mode-{2}'.format(temp, key, mode + 1)
n = self.structure.node_count()
self.write_line('{0}.out -nodeRange 1 {1} -dof 1 2 3 "eigen {2}"'.format(prefix, n, mode + 1))
self.blank_line()
self.write_subsection('Eigen analysis')
self.write_line('set lambda [eigen {0}]'.format(modes))
self.write_line('set omega {}')
self.write_line('set f {}')
self.write_line('set pi 3.141593')
self.blank_line()
self.write_line('foreach lam $lambda {')
self.write_line(' lappend omega [expr sqrt($lam)]')
self.write_line(' lappend f [expr sqrt($lam)/(2*$pi)]')
self.write_line('}')
self.blank_line()
self.write_line('puts "frequencies: $f"')
self.blank_line()
self.write_line('set file "{0}{1}_frequencies.txt"'.format(temp, key))
self.write_line('set File [open $file "w"]')
self.blank_line()
self.write_line('foreach t $f {')
self.write_line(' puts $File " $t"')
self.write_line('}')
self.write_line('close $File')
self.blank_line()
self.write_line('record')
# -------------------------------------------------------------------------------------------------
# Abaqus
# -------------------------------------------------------------------------------------------------
elif self.software == 'abaqus':
node_fields = ['rf', 'rm', 'u', 'ur', 'cf', 'cm']
element_fields = ['sf', 'sm', 'sk', 'se', 's', 'e', 'pe', 'rbfor', 'ctf']
if 'spf' in fields:
fields[fields.index('spf')] = 'ctf'
self.write_line('*OUTPUT, FIELD')
self.blank_line()
self.write_line('*NODE OUTPUT')
self.blank_line()
self.write_line(', '.join([i.upper() for i in node_fields if i in fields]))
self.blank_line()
self.write_line('*ELEMENT OUTPUT')
self.blank_line()
self.write_line(', '.join([i.upper() for i in element_fields if (i in fields and i != 'rbfor')]))
if 'rbfor' in fields:
self.write_line('*ELEMENT OUTPUT, REBAR')
self.write_line('RBFOR')
self.blank_line()
self.write_line('*END STEP')
self.blank_line()
self.blank_line()
# -------------------------------------------------------------------------------------------------
# Ansys
# -------------------------------------------------------------------------------------------------
elif self.software == 'ansys':
pass
# Thermal
# try:
# duration = step.duration
# except Exception:
# duration = 1
# temperatures = steps[key].temperatures
# if temperatures:
# file = misc[temperatures].file
# einc = str(misc[temperatures].einc)
# f.write('**\n')
# f.write('*TEMPERATURE, FILE={0}, BSTEP=1, BINC=1, ESTEP=1, EINC={1}, INTERPOLATE\n'.format(file, einc))
# elif stype == 'HeatStep':
# temp0 = step.temp0
# duration = step.duration
# deltmx = steps[key].deltmx
# interaction = interactions[step.interaction]
# amplitude = interaction.amplitude
# interface = interaction.interface
# sink_t = interaction.sink_t
# film_c = interaction.film_c
# ambient_t = interaction.ambient_t
# emissivity = interaction.emissivity
# # Initial T
# f.write('*INITIAL CONDITIONS, TYPE=TEMPERATURE\n')
# f.write('NSET_ALL, {0}\n'.format(temp0))
# f.write('**\n')
# # Interface
# f.write('*STEP, NAME={0}, INC={1}\n'.format(sname, increments))
# f.write('*{0}, END=PERIOD, DELTMX={1}\n'.format(method, deltmx))
# f.write('1, {0}, 5.4e-05, {0}\n'.format(duration))
# f.write('**\n')
# f.write('*SFILM, AMPLITUDE={0}\n'.format(amplitude))
# f.write('{0}, F, {1}, {2}\n'.format(interface, sink_t, film_c))
# f.write('**\n')
# f.write('*SRADIATE, AMPLITUDE={0}\n'.format(amplitude))
# f.write('{0}, R, {1}, {2}\n'.format(interface, ambient_t, emissivity))
# # fieldOutputs
# f.write('**\n')
# f.write('** OUTPUT\n')
# f.write('** ------\n')
# f.write('*OUTPUT, FIELD\n')
# f.write('**\n')
# f.write('*NODE OUTPUT\n')
# f.write('NT\n')
# f.write('**\n')
# f.write('*END STEP\n')
| 39.728972 | 119 | 0.336117 |
96c38e7386656952066f8d84052dad78df7a5579 | 2,084 | py | Python | examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py | beamc83/python-googleads | 6039d08e2d85850a46a70f24359d362ffde2f7ed | [
"Apache-2.0"
] | 2 | 2019-07-11T13:01:56.000Z | 2019-07-11T13:01:58.000Z | examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py | SoungMo/googleads-python-lib | fe86335c416e0571328c0a481c4b0cff863c01d9 | [
"Apache-2.0"
] | null | null | null | examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py | SoungMo/googleads-python-lib | fe86335c416e0571328c0a481c4b0cff863c01d9 | [
"Apache-2.0"
] | 1 | 2020-07-19T14:24:05.000Z | 2020-07-19T14:24:05.000Z | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example creates a product base rate.
To determine which base rates exist, run get_all_base_rates.py.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
def main(client, product_id, rate_card_id):
# Initialize appropriate service.
base_rate_service = client.GetService(
'BaseRateService', version='v201811')
# Create a product base rate.
product_base_rate = {
'xsi_type': 'ProductBaseRate',
# Set the rate card ID that the product base rate belongs to.
'rateCardId': rate_card_id,
# Set the product id the base rate will be applied to.
'productId': product_id,
# Set the rate to be $2.
'rate': {
'currencyCode': 'USD',
'microAmount': 2000000
}
}
# Create the product base rate on the server.
base_rates = base_rate_service.createBaseRates(
[product_base_rate])
if base_rates:
for base_rate in base_rates:
print ('A product base rate with ID "%s" and rate \'%.2f\' %s was '
'created.' % (base_rate['id'],
base_rate['rate']['microAmount'],
base_rate['rate']['currencyCode']))
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID)
| 31.575758 | 74 | 0.692898 |
656dade1b443384639d630f4e3ead902587fb4bb | 188 | py | Python | btcdet/models/backbones_3d/vfe/__init__.py | collector-m/BtcDet | 80bee34f2f40931600f812a6edbcb27e51cb7ec3 | [
"Apache-2.0"
] | 108 | 2021-12-03T09:42:32.000Z | 2022-03-30T03:22:13.000Z | btcdet/models/backbones_3d/vfe/__init__.py | collector-m/BtcDet | 80bee34f2f40931600f812a6edbcb27e51cb7ec3 | [
"Apache-2.0"
] | 22 | 2021-12-07T17:20:00.000Z | 2022-03-27T18:28:59.000Z | btcdet/models/backbones_3d/vfe/__init__.py | collector-m/BtcDet | 80bee34f2f40931600f812a6edbcb27e51cb7ec3 | [
"Apache-2.0"
] | 14 | 2021-12-07T03:37:59.000Z | 2022-03-29T03:35:47.000Z | from .mean_vfe import MeanVFE
from .occ_vfe import OccVFE
from .vfe_template import VFETemplate
__all__ = {
'VFETemplate': VFETemplate,
'MeanVFE': MeanVFE,
'OccVFE': OccVFE
}
| 18.8 | 37 | 0.723404 |
8bc4bf699d50d44b3e1a28eb6f0040b89be60923 | 3,352 | py | Python | neutron/extensions/extra_dhcp_opt.py | glove747/liberty-neutron | 35a4c85e781d10da4521565c3a367e4ecb50739d | [
"Apache-2.0"
] | null | null | null | neutron/extensions/extra_dhcp_opt.py | glove747/liberty-neutron | 35a4c85e781d10da4521565c3a367e4ecb50739d | [
"Apache-2.0"
] | null | null | null | neutron/extensions/extra_dhcp_opt.py | glove747/liberty-neutron | 35a4c85e781d10da4521565c3a367e4ecb50739d | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2013 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.common import exceptions
# ExtraDHcpOpts Exceptions
class ExtraDhcpOptNotFound(exceptions.NotFound):
message = _("ExtraDhcpOpt %(id)s could not be found")
class ExtraDhcpOptBadData(exceptions.InvalidInput):
message = _("Invalid data format for extra-dhcp-opt: %(data)s")
# Valid blank extra dhcp opts
VALID_BLANK_EXTRA_DHCP_OPTS = ('router', 'classless-static-route')
# Common definitions for maximum string field length
DHCP_OPT_NAME_MAX_LEN = 64
DHCP_OPT_VALUE_MAX_LEN = 255
EXTRA_DHCP_OPT_KEY_SPECS = {
'id': {'type:uuid': None, 'required': False},
'opt_name': {'type:not_empty_string': DHCP_OPT_NAME_MAX_LEN,
'required': True},
'opt_value': {'type:not_empty_string_or_none': DHCP_OPT_VALUE_MAX_LEN,
'required': True},
'ip_version': {'convert_to': attr.convert_to_int,
'type:values': [4, 6],
'required': False}
}
def _validate_extra_dhcp_opt(data, key_specs=None):
if data is not None:
if not isinstance(data, list):
raise ExtraDhcpOptBadData(data=data)
for d in data:
if d['opt_name'] in VALID_BLANK_EXTRA_DHCP_OPTS:
msg = attr._validate_string_or_none(d['opt_value'],
DHCP_OPT_VALUE_MAX_LEN)
else:
msg = attr._validate_dict(d, key_specs)
if msg:
raise ExtraDhcpOptBadData(data=msg)
attr.validators['type:list_of_extra_dhcp_opts'] = _validate_extra_dhcp_opt
# Attribute Map
EXTRADHCPOPTS = 'extra_dhcp_opts'
CLIENT_ID = "client-id"
EXTENDED_ATTRIBUTES_2_0 = {
'ports': {
EXTRADHCPOPTS: {
'allow_post': True,
'allow_put': True,
'is_visible': True,
'default': None,
'validate': {
'type:list_of_extra_dhcp_opts': EXTRA_DHCP_OPT_KEY_SPECS
}
}
}
}
class Extra_dhcp_opt(extensions.ExtensionDescriptor):
@classmethod
def get_name(cls):
return "Neutron Extra DHCP opts"
@classmethod
def get_alias(cls):
return "extra_dhcp_opt"
@classmethod
def get_description(cls):
return ("Extra options configuration for DHCP. "
"For example PXE boot options to DHCP clients can "
"be specified (e.g. tftp-server, server-ip-address, "
"bootfile-name)")
@classmethod
def get_updated(cls):
return "2013-03-17T12:00:00-00:00"
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
| 30.472727 | 75 | 0.648866 |
e46503d760967575d0d9e89a2960b2efbdbd3b81 | 7,199 | py | Python | selfdrive/controls/lib/driver_monitor.py | cron410/openpilot | 9d1201882fd9b97341de736a6f931b0caf50aeb5 | [
"MIT"
] | null | null | null | selfdrive/controls/lib/driver_monitor.py | cron410/openpilot | 9d1201882fd9b97341de736a6f931b0caf50aeb5 | [
"MIT"
] | null | null | null | selfdrive/controls/lib/driver_monitor.py | cron410/openpilot | 9d1201882fd9b97341de736a6f931b0caf50aeb5 | [
"MIT"
] | null | null | null | import numpy as np
from common.realtime import sec_since_boot
from selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET
from common.filter_simple import FirstOrderFilter
import selfdrive.kegman_conf as kegman
_DT = 0.01 # update runs at 100Hz
_DTM = 0.1 # DM runs at 10Hz
_AWARENESS_TIME = int(kegman.conf['wheelTouchSeconds']) # 3 minutes limit without user touching steering wheels make the car enter a terminal status
_AWARENESS_PRE_TIME = 200. # a first alert is issued 20s before expiration
_AWARENESS_PROMPT_TIME = 50. # a second alert is issued 5s before start decelerating the car
_DISTRACTED_TIME = 70.
_DISTRACTED_PRE_TIME = 40.
_DISTRACTED_PROMPT_TIME = 20.
# measured 1 rad in x FOV. 1152x864 is original image, 160x320 is a right crop for model
_CAMERA_FOV_X = 1. # rad
_CAMERA_FOV_Y = 0.75 # 4/3 aspect ratio
# model output refers to center of cropped image, so need to apply the x displacement offset
_PITCH_WEIGHT = 1.5 # pitch matters a lot more
_METRIC_THRESHOLD = 0.4
_PITCH_POS_ALLOWANCE = 0.08 # rad, to not be too sensitive on positive pitch
_PITCH_NATURAL_OFFSET = 0.1 # people don't seem to look straight when they drive relaxed, rather a bit up
_YAW_NATURAL_OFFSET = 0.08 # people don't seem to look straight when they drive relaxed, rather a bit to the right (center of car)
_STD_THRESHOLD = 0.1 # above this standard deviation consider the measurement invalid
_DISTRACTED_FILTER_TS = 0.25 # 0.6Hz
_VARIANCE_FILTER_TS = 20. # 0.008Hz
RESIZED_FOCAL = 320.0
H, W, FULL_W = 320, 160, 426
def head_orientation_from_descriptor(desc):
# the output of these angles are in device frame
# so from driver's perspective, pitch is up and yaw is right
# TODO this should be calibrated
pitch_prnet = desc[0]
yaw_prnet = desc[1]
roll_prnet = desc[2]
face_pixel_position = ((desc[3] + .5)*W - W + FULL_W, (desc[4]+.5)*H)
yaw_focal_angle = np.arctan2(face_pixel_position[0] - FULL_W/2, RESIZED_FOCAL)
pitch_focal_angle = np.arctan2(face_pixel_position[1] - H/2, RESIZED_FOCAL)
roll = roll_prnet
pitch = pitch_prnet + pitch_focal_angle
yaw = -yaw_prnet + yaw_focal_angle
return np.array([roll, pitch, yaw])
class _DriverPose():
def __init__(self):
self.yaw = 0.
self.pitch = 0.
self.roll = 0.
self.yaw_offset = 0.
self.pitch_offset = 0.
def _monitor_hysteresis(variance_level, monitor_valid_prev):
var_thr = 0.63 if monitor_valid_prev else 0.37
return variance_level < var_thr
class DriverStatus():
def __init__(self, monitor_on=False):
self.pose = _DriverPose()
self.monitor_on = monitor_on
self.monitor_param_on = monitor_on
self.monitor_valid = True # variance needs to be low
self.awareness = 1.
self.driver_distracted = False
self.driver_distraction_filter = FirstOrderFilter(0., _DISTRACTED_FILTER_TS, _DTM)
self.variance_high = False
self.variance_filter = FirstOrderFilter(0., _VARIANCE_FILTER_TS, _DTM)
self.ts_last_check = 0.
self.face_detected = False
self._set_timers()
def _reset_filters(self):
self.driver_distraction_filter.x = 0.
self.variance_filter.x = 0.
self.monitor_valid = True
def _set_timers(self):
if self.monitor_on:
self.threshold_pre = _DISTRACTED_PRE_TIME / _DISTRACTED_TIME
self.threshold_prompt = _DISTRACTED_PROMPT_TIME / _DISTRACTED_TIME
self.step_change = _DT / _DISTRACTED_TIME
else:
self.threshold_pre = _AWARENESS_PRE_TIME / _AWARENESS_TIME
self.threshold_prompt = _AWARENESS_PROMPT_TIME / _AWARENESS_TIME
self.step_change = _DT / _AWARENESS_TIME
def _is_driver_distracted(self, pose):
# to be tuned and to learn the driver's normal pose
pitch_error = pose.pitch - _PITCH_NATURAL_OFFSET
yaw_error = pose.yaw - _YAW_NATURAL_OFFSET
# add positive pitch allowance
if pitch_error > 0.:
pitch_error = max(pitch_error - _PITCH_POS_ALLOWANCE, 0.)
pitch_error *= _PITCH_WEIGHT
metric = np.sqrt(yaw_error**2 + pitch_error**2)
#print "%02.4f" % np.degrees(pose.pitch), "%02.4f" % np.degrees(pitch_error), "%03.4f" % np.degrees(pose.pitch_offset), metric
return 1 if metric > _METRIC_THRESHOLD else 0
def get_pose(self, driver_monitoring, params):
self.pose.roll, self.pose.pitch, self.pose.yaw = head_orientation_from_descriptor(driver_monitoring.descriptor)
# TODO: DM data should not be in a list if they are not homogeneous
if len(driver_monitoring.descriptor) > 6:
self.face_detected = driver_monitoring.descriptor[6] > 0.
else:
self.face_detected = True
self.driver_distracted = self._is_driver_distracted(self.pose)
# first order filters
self.driver_distraction_filter.update(self.driver_distracted)
self.variance_high = driver_monitoring.std > _STD_THRESHOLD
self.variance_filter.update(self.variance_high)
monitor_param_on_prev = self.monitor_param_on
monitor_valid_prev = self.monitor_valid
# don't check for param too often as it's a kernel call
ts = sec_since_boot()
if ts - self.ts_last_check > 1.:
self.monitor_param_on = params.get("IsDriverMonitoringEnabled") == "1"
self.ts_last_check = ts
self.monitor_valid = _monitor_hysteresis(self.variance_filter.x, monitor_valid_prev)
self.monitor_on = self.monitor_valid and self.monitor_param_on
if monitor_param_on_prev != self.monitor_param_on:
self._reset_filters()
self._set_timers()
def update(self, events, driver_engaged, ctrl_active, standstill):
driver_engaged |= (self.driver_distraction_filter.x < 0.37 and self.monitor_on)
if (driver_engaged and self.awareness > 0.) or not ctrl_active:
# always reset if driver is in control (unless we are in red alert state) or op isn't active
self.awareness = 1.
# only update if face is detected, driver is distracted and distraction filter is high
if (not self.monitor_on or (self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected)) and \
not (standstill and self.awareness - self.step_change <= self.threshold_prompt):
self.awareness = max(self.awareness - self.step_change, -0.1)
alert = None
if self.awareness <= 0.:
# terminal red alert: disengagement required
alert = 'driverDistracted' if self.monitor_on else 'driverUnresponsive'
elif self.awareness <= self.threshold_prompt:
# prompt orange alert
alert = 'promptDriverDistracted' if self.monitor_on else 'promptDriverUnresponsive'
elif self.awareness <= self.threshold_pre:
# pre green alert
alert = 'preDriverDistracted' if self.monitor_on else 'preDriverUnresponsive'
if alert is not None:
events.append(create_event(alert, [ET.WARNING]))
return events
if __name__ == "__main__":
ds = DriverStatus(True)
ds.driver_distraction_filter.x = 0.
ds.driver_distracted = 1
for i in range(10):
ds.update([], False, True, False)
print(ds.awareness, ds.driver_distracted, ds.driver_distraction_filter.x)
ds.update([], True, True, False)
print(ds.awareness, ds.driver_distracted, ds.driver_distraction_filter.x)
| 40.672316 | 154 | 0.733296 |
7b3c93fb88b7e3b0c633243bb58650d1925c634a | 241 | py | Python | .history/my_classes/basic/for_loop_20210430195415.py | minefarmer/deep-Dive-1 | b0675b853180c5b5781888266ea63a3793b8d855 | [
"Unlicense"
] | null | null | null | .history/my_classes/basic/for_loop_20210430195415.py | minefarmer/deep-Dive-1 | b0675b853180c5b5781888266ea63a3793b8d855 | [
"Unlicense"
] | null | null | null | .history/my_classes/basic/for_loop_20210430195415.py | minefarmer/deep-Dive-1 | b0675b853180c5b5781888266ea63a3793b8d855 | [
"Unlicense"
] | null | null | null | i = 0
while i < 5:
print(i)
i += 1
i = None # 0
# 1
# 2
# 3
# 4
for i in range(5):
print(i) # 0
# 1
# 2
# 3
# 4 | 14.176471 | 20 | 0.207469 |
0e152e4024b7a74f88791641cfa41754e6d4970f | 8,681 | py | Python | tests/notifier/notifier_test.py | perambulist/forseti-security | 5b87bc536f3d33fdeaa0c2a1f20eea3f56c79060 | [
"Apache-2.0"
] | 1 | 2018-10-06T23:16:59.000Z | 2018-10-06T23:16:59.000Z | tests/notifier/notifier_test.py | perambulist/forseti-security | 5b87bc536f3d33fdeaa0c2a1f20eea3f56c79060 | [
"Apache-2.0"
] | null | null | null | tests/notifier/notifier_test.py | perambulist/forseti-security | 5b87bc536f3d33fdeaa0c2a1f20eea3f56c79060 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests the notifier module."""
from datetime import datetime
import mock
import unittest
from google.cloud.forseti.notifier import notifier
from google.cloud.forseti.notifier.notifiers import email_violations
from google.cloud.forseti.notifier.notifiers import gcs_violations
from tests.notifier.notifiers.test_data import fake_violations
from tests.unittest_utils import ForsetiTestCase
class NotifierTest(ForsetiTestCase):
def setUp(self):
pass
def test_can_convert_created_at_datetime_to_timestamp_string(self):
violations = [
dict(created_at_datetime=datetime(1999, 12, 25, 1, 2, 3)),
dict(created_at_datetime=datetime(2010, 6, 8, 4, 5, 6))
]
expected_timestamps = ['1999-12-25T01:02:03Z',
'2010-06-08T04:05:06Z']
violations_with_converted_timestamp = (
notifier.convert_to_timestamp(violations))
converted_timestamps = []
for i in violations_with_converted_timestamp:
converted_timestamps.append(i['created_at_datetime'])
self.assertEquals(expected_timestamps,
converted_timestamps)
@mock.patch(
'google.cloud.forseti.notifier.notifier.find_notifiers', autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.scanner_dao', autospec=True)
def test_no_notifications_for_empty_violations(
self, mock_dao, mock_find_notifiers):
"""No notifiers are instantiated/run if there are no violations.
Setup:
Mock the scanner_dao and make its map_by_resource() function return
an empty violations map
Expected outcome:
The local find_notifiers() function is never called -> no notifiers
are looked up, istantiated or run."""
mock_dao.map_by_resource.return_value = dict()
mock_service_cfg = mock.MagicMock()
mock_service_cfg.get_global_config.return_value = fake_violations.GLOBAL_CONFIGS
mock_service_cfg.get_notifier_config.return_value = fake_violations.NOTIFIER_CONFIGS
notifier.run('iid-1-2-3', mock.MagicMock(), mock_service_cfg)
self.assertFalse(mock_find_notifiers.called)
@mock.patch(
('google.cloud.forseti.notifier.notifiers.email_violations'
'.EmailViolations'), autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifiers.gcs_violations.GcsViolations',
autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.find_notifiers', autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.scanner_dao', autospec=True)
def test_notifications_for_nonempty_violations(
self, mock_dao, mock_find_notifiers, mock_gcs_violations_cls, mock_email_violations_cls):
"""The email/GCS upload notifiers are instantiated/run.
Setup:
Mock the scanner_dao and make its map_by_resource() function return
the VIOLATIONS dict
Expected outcome:
The local find_notifiers() is called with with 'email_violations'
and 'gcs_violations' respectively. These 2 notifiers are
instantiated and run."""
mock_dao.map_by_resource.return_value = fake_violations.VIOLATIONS
mock_service_cfg = mock.MagicMock()
mock_service_cfg.get_global_config.return_value = fake_violations.GLOBAL_CONFIGS
mock_service_cfg.get_notifier_config.return_value = fake_violations.NOTIFIER_CONFIGS
mock_email_violations = mock.MagicMock(spec=email_violations.EmailViolations)
mock_email_violations_cls.return_value = mock_email_violations
mock_gcs_violations = mock.MagicMock(spec=gcs_violations.GcsViolations)
mock_gcs_violations_cls.return_value = mock_gcs_violations
mock_find_notifiers.side_effect = [mock_email_violations_cls, mock_gcs_violations_cls]
notifier.run('iid-1-2-3', mock.MagicMock(), mock_service_cfg)
# The notifiers were only run once i.e. for 'policy_violations'
self.assertTrue(mock_find_notifiers.called)
self.assertEquals(1, mock_email_violations_cls.call_count)
self.assertEquals(
'iam_policy_violations',
mock_email_violations_cls.call_args[0][0])
self.assertEquals(1, mock_email_violations.run.call_count)
self.assertEquals(1, mock_gcs_violations_cls.call_count)
self.assertEquals(
'iam_policy_violations',
mock_gcs_violations_cls.call_args[0][0])
self.assertEquals(1, mock_gcs_violations.run.call_count)
@mock.patch(
('google.cloud.forseti.notifier.notifiers.email_violations'
'.EmailViolations'), autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifiers.gcs_violations.GcsViolations',
autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.find_notifiers', autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.scanner_dao', autospec=True)
@mock.patch('google.cloud.forseti.notifier.notifier.LOGGER', autospec=True)
def test_notifications_are_not_sent_without_valid_scanner_index_id(
self, mock_logger, mock_dao, mock_find_notifiers,
mock_gcs_violations_cls, mock_email_violations_cls):
"""Without scanner index id, no notifications are sent.
Setup:
Mock the scanner_dao and make its map_by_resource() function return
the VIOLATIONS dict.
Make sure that no scanner index with a (SUCCESS, PARTIAL_SUCCESS)
completion state is found.
Expected outcome:
The local find_notifiers() function is never called -> no notifiers
are looked up, istantiated or run."""
mock_dao.get_latest_scanner_index_id.return_value = None
mock_service_cfg = mock.MagicMock()
mock_service_cfg.get_global_config.return_value = fake_violations.GLOBAL_CONFIGS
mock_service_cfg.get_notifier_config.return_value = fake_violations.NOTIFIER_CONFIGS
mock_email_violations = mock.MagicMock(spec=email_violations.EmailViolations)
mock_email_violations_cls.return_value = mock_email_violations
mock_gcs_violations = mock.MagicMock(spec=gcs_violations.GcsViolations)
mock_gcs_violations_cls.return_value = mock_gcs_violations
mock_find_notifiers.side_effect = [mock_email_violations_cls, mock_gcs_violations_cls]
notifier.run('iid-1-2-3', mock.MagicMock(), mock_service_cfg)
self.assertFalse(mock_find_notifiers.called)
self.assertFalse(mock_dao.map_by_resource.called)
self.assertTrue(mock_logger.error.called)
@mock.patch(
'google.cloud.forseti.notifier.notifier.InventorySummary',
autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.find_notifiers', autospec=True)
@mock.patch(
'google.cloud.forseti.notifier.notifier.scanner_dao', autospec=True)
def test_inventory_summary_is_called(
self, mock_dao, mock_find_notifiers, mock_inventor_summary):
"""No violation notifiers are run if there are no violations.
Setup:
Mock the scanner_dao and make its map_by_resource() function return
an empty violations map
Expected outcome:
The local find_notifiers() function is never called -> no notifiers
are looked up, istantiated or run.
The `run_inv_summary` function *is* called.
"""
mock_dao.map_by_resource.return_value = dict()
mock_service_cfg = mock.MagicMock()
mock_service_cfg.get_global_config.return_value = fake_violations.GLOBAL_CONFIGS
mock_service_cfg.get_notifier_config.return_value = fake_violations.NOTIFIER_CONFIGS
notifier.run('iid-1-2-3', mock.MagicMock(), mock_service_cfg)
self.assertFalse(mock_find_notifiers.called)
self.assertTrue(mock_inventor_summary.called)
if __name__ == '__main__':
unittest.main()
| 45.213542 | 97 | 0.718235 |
505b2bedcaa6d8b2b7546a376ac1fec47c1a7262 | 27,596 | py | Python | tools/conan/conans/client/manager.py | aversiveplusplus/aversiveplusplus | 5f5fe9faca50197fd6207e2c816efa7e9af6c804 | [
"BSD-3-Clause"
] | 29 | 2016-01-27T09:43:44.000Z | 2020-03-12T04:16:02.000Z | tools/conan/conans/client/manager.py | aversiveplusplus/aversiveplusplus | 5f5fe9faca50197fd6207e2c816efa7e9af6c804 | [
"BSD-3-Clause"
] | 20 | 2016-01-22T15:59:33.000Z | 2016-10-28T10:22:45.000Z | tools/conan/conans/client/manager.py | aversiveplusplus/aversiveplusplus | 5f5fe9faca50197fd6207e2c816efa7e9af6c804 | [
"BSD-3-Clause"
] | 6 | 2016-02-11T14:09:04.000Z | 2018-03-17T00:18:35.000Z | import os
import time
from collections import OrderedDict
from conans.paths import (CONANFILE, CONANINFO, CONANFILE_TXT, BUILD_INFO, CONANENV)
from conans.client.loader import ConanFileLoader
from conans.client.export import export_conanfile
from conans.client.deps_builder import DepsBuilder
from conans.client.userio import UserIO
from conans.client.installer import ConanInstaller
from conans.util.files import save, load, rmdir, normalize
from conans.util.log import logger
from conans.client.uploader import ConanUploader
from conans.client.printer import Printer
from conans.errors import NotFoundException, ConanException
from conans.client.generators import write_generators
from conans.client.importer import FileImporter
from conans.model.ref import ConanFileReference, PackageReference
from conans.client.remover import ConanRemover
from conans.model.info import ConanInfo
from conans.model.values import Values
from conans.model.options import OptionsValues
from conans.model.build_info import DepsCppInfo, CppInfo
from conans.client import packager
from conans.client.detect import detected_os
from conans.client.package_copier import PackageCopier
from conans.client.output import ScopedOutput
from conans.client.proxy import ConanProxy
from conans.client.remote_registry import RemoteRegistry
from conans.client.file_copier import report_copied_files
from conans.model.scope import Scopes
from conans.client.client_cache import ClientCache
from conans.client.source import config_source, config_source_local
from conans.client.manifest_manager import ManifestManager
from conans.model.env_info import EnvInfo, DepsEnvInfo
from conans.tools import environment_append
def get_user_channel(text):
tokens = text.split('/')
try:
user = tokens[0]
channel = tokens[1]
except IndexError:
channel = "testing"
return user, channel
class ConanManager(object):
""" Manage all the commands logic The main entry point for all the client
business logic
"""
def __init__(self, client_cache, user_io, runner, remote_manager, search_manager):
assert isinstance(user_io, UserIO)
assert isinstance(client_cache, ClientCache)
self._client_cache = client_cache
self._user_io = user_io
self._runner = runner
self._remote_manager = remote_manager
self._current_scopes = None
self._search_manager = search_manager
def _loader(self, current_path=None, user_settings_values=None, user_options_values=None,
scopes=None):
# The disk settings definition, already including the default disk values
settings = self._client_cache.settings
options = OptionsValues()
conaninfo_scopes = Scopes()
if current_path:
conan_info_path = os.path.join(current_path, CONANINFO)
if os.path.exists(conan_info_path):
existing_info = ConanInfo.load_file(conan_info_path)
settings.values = existing_info.full_settings
options = existing_info.full_options # Take existing options from conaninfo.txt
conaninfo_scopes = existing_info.scope
if user_settings_values:
aux_values = Values.from_list(user_settings_values)
settings.values = aux_values
if user_options_values is not None: # Install will pass an empty list []
# Install OVERWRITES options, existing options in CONANINFO are not taken
# into account, just those from CONANFILE + user command line
options = OptionsValues.from_list(user_options_values)
if scopes:
conaninfo_scopes.update_scope(scopes)
self._current_scopes = conaninfo_scopes
return ConanFileLoader(self._runner, settings, options=options, scopes=conaninfo_scopes)
def export(self, user, conan_file_path, keep_source=False):
""" Export the conans
param conanfile_path: the original source directory of the user containing a
conanfile.py
param user: user under this package will be exported
param channel: string (stable, testing,...)
"""
assert conan_file_path
logger.debug("Exporting %s" % conan_file_path)
user_name, channel = get_user_channel(user)
conan_file = self._loader().load_class(os.path.join(conan_file_path, CONANFILE))
url = getattr(conan_file, "url", None)
license_ = getattr(conan_file, "license", None)
if not url:
self._user_io.out.warn("Conanfile doesn't have 'url'.\n"
"It is recommended to add your repo URL as attribute")
if not license_:
self._user_io.out.warn("Conanfile doesn't have a 'license'.\n"
"It is recommended to add the package license as attribute")
conan_ref = ConanFileReference(conan_file.name, conan_file.version, user_name, channel)
conan_ref_str = str(conan_ref)
# Maybe a platform check could be added, but depends on disk partition
refs = self._search_manager.search(conan_ref_str, ignorecase=True)
if refs and conan_ref not in refs:
raise ConanException("Cannot export package with same name but different case\n"
"You exported '%s' but already existing '%s'"
% (conan_ref_str, " ".join(str(s) for s in refs)))
output = ScopedOutput(str(conan_ref), self._user_io.out)
export_conanfile(output, self._client_cache, conan_file.exports, conan_file_path,
conan_ref, conan_file.short_paths, keep_source)
def download(self, reference, package_ids, remote=None):
""" Download conanfile and specified packages to local repository
@param reference: ConanFileReference
@param package_ids: Package ids or empty for download all
@param remote: install only from that remote
"""
assert(isinstance(reference, ConanFileReference))
remote_proxy = ConanProxy(self._client_cache, self._user_io, self._remote_manager, remote)
if package_ids:
remote_proxy.download_packages(reference, package_ids)
else: # Not specified packages, download all
packages_props = remote_proxy.search_packages(reference, None)
if not packages_props: # No filter by properties
raise ConanException("'%s' not found in remote" % str(reference))
remote_proxy.download_packages(reference, list(packages_props.keys()))
def _get_graph(self, reference, current_path, remote, options, settings, filename, update,
check_updates, manifest_manager, scopes):
loader = self._loader(current_path, settings, options, scopes)
# Not check for updates for info command, it'll be checked when dep graph is built
remote_proxy = ConanProxy(self._client_cache, self._user_io, self._remote_manager, remote,
update=update, check_updates=check_updates,
manifest_manager=manifest_manager)
if isinstance(reference, ConanFileReference):
project_reference = None
conanfile = loader.load_virtual(reference, current_path)
is_txt = True
else:
conanfile_path = reference
project_reference = "PROJECT"
output = ScopedOutput(project_reference, self._user_io.out)
try:
if filename and filename.endswith(".txt"):
raise NotFoundException("")
conan_file_path = os.path.join(conanfile_path, filename or CONANFILE)
conanfile = loader.load_conan(conan_file_path, output, consumer=True)
is_txt = False
if conanfile.name is not None and conanfile.version is not None:
project_reference = "%s/%s@" % (conanfile.name, conanfile.version)
project_reference += "PROJECT"
except NotFoundException: # Load requirements.txt
conan_path = os.path.join(conanfile_path, filename or CONANFILE_TXT)
conanfile = loader.load_conan_txt(conan_path, output)
is_txt = True
# build deps graph and install it
builder = DepsBuilder(remote_proxy, self._user_io.out, loader)
deps_graph = builder.load(None, conanfile)
# These lines are so the conaninfo stores the correct complete info
if is_txt:
conanfile.info.settings = loader._settings.values
conanfile.info.full_settings = loader._settings.values
conanfile.info.scope = self._current_scopes
conanfile.cpp_info = CppInfo(current_path)
conanfile.env_info = EnvInfo(current_path)
registry = RemoteRegistry(self._client_cache.registry, self._user_io.out)
return (builder, deps_graph, project_reference, registry, conanfile,
remote_proxy, loader)
def info(self, reference, current_path, remote=None, options=None, settings=None,
info=None, filename=None, update=False, check_updates=False, scopes=None,
build_order=None):
""" Fetch and build all dependencies for the given reference
@param reference: ConanFileReference or path to user space conanfile
@param current_path: where the output files will be saved
@param remote: install only from that remote
@param options: list of tuples: [(optionname, optionvalue), (optionname, optionvalue)...]
@param settings: list of tuples: [(settingname, settingvalue), (settingname, value)...]
"""
objects = self._get_graph(reference, current_path, remote, options, settings, filename,
update, check_updates, None, scopes)
(builder, deps_graph, project_reference, registry, _, _, _) = objects
if build_order:
result = deps_graph.build_order(build_order)
self._user_io.out.info(", ".join(str(s) for s in result))
return
if check_updates:
graph_updates_info = builder.get_graph_updates_info(deps_graph)
else:
graph_updates_info = {}
Printer(self._user_io.out).print_info(deps_graph, project_reference,
info, registry, graph_updates_info,
remote)
def _read_profile(self, profile_name):
if profile_name:
try:
profile = self._client_cache.load_profile(profile_name)
return profile
except ConanException as exc:
raise ConanException("Error reading '%s' profile: %s" % (profile_name, exc))
return None
def _mix_settings_and_profile(self, settings, profile):
'''Mix the specified settings with the specified profile.
Specified settings are prioritized to profile'''
if profile:
profile.update_settings(dict(settings))
return profile.settings.items()
return settings
def _mix_scopes_and_profile(self, scopes, profile):
if profile:
profile.update_scopes(scopes)
return profile.scopes
return scopes
def _read_profile_env_vars(self, profile):
if profile:
return profile.env
return {}
def install(self, reference, current_path, remote=None, options=None, settings=None,
build_mode=False, filename=None, update=False, check_updates=False,
manifest_folder=None, manifest_verify=False, manifest_interactive=False,
scopes=None, generators=None, profile_name=None, no_imports=False):
""" Fetch and build all dependencies for the given reference
@param reference: ConanFileReference or path to user space conanfile
@param current_path: where the output files will be saved
@param remote: install only from that remote
@param options: list of tuples: [(optionname, optionvalue), (optionname, optionvalue)...]
@param settings: list of tuples: [(settingname, settingvalue), (settingname, value)...]
@param profile: name of the profile to use
"""
generators = generators or []
if manifest_folder:
manifest_manager = ManifestManager(manifest_folder, user_io=self._user_io,
client_cache=self._client_cache,
verify=manifest_verify,
interactive=manifest_interactive)
else:
manifest_manager = None
profile = self._read_profile(profile_name)
settings = self._mix_settings_and_profile(settings, profile)
scopes = self._mix_scopes_and_profile(scopes, profile)
env_vars = self._read_profile_env_vars(profile)
objects = self._get_graph(reference, current_path, remote, options, settings, filename,
update, check_updates, manifest_manager, scopes)
(_, deps_graph, _, registry, conanfile, remote_proxy, loader) = objects
Printer(self._user_io.out).print_graph(deps_graph, registry)
# Warn if os doesn't match
try:
if detected_os() != loader._settings.os:
message = '''You are building this package with settings.os='%s' on a '%s' system.
If this is your intention, you can ignore this message.
If not:
- Check the passed settings (-s)
- Check your global settings in ~/.conan/conan.conf
- Remove conaninfo.txt to avoid bad cached settings
''' % (loader._settings.os, detected_os())
self._user_io.out.warn(message)
except ConanException: # Setting os doesn't exist
pass
installer = ConanInstaller(self._client_cache, self._user_io, remote_proxy)
# Append env_vars to execution environment and clear when block code ends
with environment_append(env_vars):
installer.install(deps_graph, build_mode)
prefix = "PROJECT" if not isinstance(reference, ConanFileReference) else str(reference)
output = ScopedOutput(prefix, self._user_io.out)
# Write generators
tmp = list(conanfile.generators) # Add the command line specified generators
tmp.extend(generators)
conanfile.generators = tmp
write_generators(conanfile, current_path, output)
if not isinstance(reference, ConanFileReference):
content = normalize(conanfile.info.dumps())
save(os.path.join(current_path, CONANINFO), content)
output.info("Generated %s" % CONANINFO)
if not no_imports:
local_installer = FileImporter(deps_graph, self._client_cache, current_path)
conanfile.copy = local_installer
conanfile.imports()
copied_files = local_installer.execute()
import_output = ScopedOutput("%s imports()" % output.scope, output)
report_copied_files(copied_files, import_output)
if manifest_manager:
manifest_manager.print_log()
def _load_deps_info(self, current_path, conanfile, output):
build_info_file = os.path.join(current_path, BUILD_INFO)
if os.path.exists(build_info_file):
try:
deps_cpp_info = DepsCppInfo.loads(load(build_info_file))
conanfile.deps_cpp_info = deps_cpp_info
except:
output.error("Parse error in '%s' file in %s" % (BUILD_INFO, current_path))
else:
output.warn("%s file not found in %s\nIt is recommended for source, build and package "
"commands\nYou can generate it using 'conan install -g env -g txt'"
% (BUILD_INFO, current_path))
env_file = os.path.join(current_path, CONANENV)
if os.path.exists(env_file):
try:
deps_env_info = DepsEnvInfo.loads(load(env_file))
conanfile.deps_env_info = deps_env_info
except:
output.error("Parse error in '%s' file in %s" % (CONANENV, current_path))
else:
output.warn("%s file not found in %s\nIt is recommended for source, build and package "
"commands\nYou can generate it using 'conan install -g env -g txt'"
% (CONANENV, current_path))
def source(self, current_path, reference, force):
if not isinstance(reference, ConanFileReference):
output = ScopedOutput("PROJECT", self._user_io.out)
conan_file_path = os.path.join(reference, CONANFILE)
conanfile = self._loader().load_conan(conan_file_path, output, consumer=True)
self._load_deps_info(current_path, conanfile, output)
export_folder = reference
config_source_local(export_folder, current_path, conanfile, output)
else:
output = ScopedOutput(str(reference), self._user_io.out)
conan_file_path = self._client_cache.conanfile(reference)
conanfile = self._loader().load_conan(conan_file_path, output)
self._load_deps_info(current_path, conanfile, output)
src_folder = self._client_cache.source(reference, conanfile.short_paths)
export_folder = self._client_cache.export(reference)
config_source(export_folder, src_folder, conanfile, output, force)
def local_package(self, current_path, build_folder):
if current_path == build_folder:
raise ConanException("Cannot 'conan package' to the build folder. "
"Please move to another folder and try again")
output = ScopedOutput("PROJECT", self._user_io.out)
conan_file_path = os.path.join(build_folder, CONANFILE)
conanfile = self._loader().load_conan(conan_file_path, output, consumer=True)
self._load_deps_info(build_folder, conanfile, output)
packager.create_package(conanfile, build_folder, current_path, output, local=True)
def package(self, reference, package_id):
# Package paths
conan_file_path = self._client_cache.conanfile(reference)
if not os.path.exists(conan_file_path):
raise ConanException("Package recipe '%s' does not exist" % str(reference))
if not package_id:
packages = [PackageReference(reference, packid)
for packid in self._client_cache.conan_builds(reference)]
if not packages:
raise NotFoundException("%s: Package recipe has not been built locally\n"
"Please read the 'conan package' command help\n"
"Use 'conan install' or 'conan test_package' to build and "
"create binaries" % str(reference))
else:
packages = [PackageReference(reference, package_id)]
for package_reference in packages:
build_folder = self._client_cache.build(package_reference, short_paths=None)
if not os.path.exists(build_folder):
raise NotFoundException("%s: Package binary '%s' folder doesn't exist\n"
"Please read the 'conan package' command help\n"
"Use 'conan install' or 'conan test_package' to build and "
"create binaries"
% (str(reference), package_reference.package_id))
# The package already exist, we can use short_paths if they were defined
package_folder = self._client_cache.package(package_reference, short_paths=None)
# Will read current conaninfo with specified options and load conanfile with them
output = ScopedOutput(str(reference), self._user_io.out)
output.info("Re-packaging %s" % package_reference.package_id)
loader = self._loader(build_folder)
conanfile = loader.load_conan(conan_file_path, self._user_io.out)
self._load_deps_info(build_folder, conanfile, output)
rmdir(package_folder)
packager.create_package(conanfile, build_folder, package_folder, output)
def build(self, conanfile_path, current_path, test=False, filename=None, profile_name=None):
""" Call to build() method saved on the conanfile.py
param conanfile_path: the original source directory of the user containing a
conanfile.py
"""
logger.debug("Building in %s" % current_path)
logger.debug("Conanfile in %s" % conanfile_path)
if filename and filename.endswith(".txt"):
raise ConanException("A conanfile.py is needed to call 'conan build'")
conanfile_file = os.path.join(conanfile_path, filename or CONANFILE)
try:
output = ScopedOutput("Project", self._user_io.out)
conan_file = self._loader(current_path).load_conan(conanfile_file, output,
consumer=True)
except NotFoundException:
# TODO: Auto generate conanfile from requirements file
raise ConanException("'%s' file is needed for build.\n"
"Create a '%s' and move manually the "
"requirements and generators from '%s' file"
% (CONANFILE, CONANFILE, CONANFILE_TXT))
try:
self._load_deps_info(current_path, conan_file, output)
os.chdir(current_path)
conan_file._conanfile_directory = conanfile_path
# Append env_vars to execution environment and clear when block code ends
profile = self._read_profile(profile_name)
env_vars = self._read_profile_env_vars(profile)
with environment_append(env_vars):
conan_file.build()
if test:
conan_file.test()
except ConanException:
raise # Raise but not let to reach the Exception except (not print traceback)
except Exception:
import traceback
trace = traceback.format_exc().split('\n')
raise ConanException("Unable to build it successfully\n%s" % '\n'.join(trace[3:]))
def upload(self, conan_reference, package_id=None, remote=None, all_packages=None,
force=False):
t1 = time.time()
remote_proxy = ConanProxy(self._client_cache, self._user_io, self._remote_manager, remote)
uploader = ConanUploader(self._client_cache, self._user_io, remote_proxy)
# Load conanfile to check if the build policy is set to always
try:
conanfile_path = self._client_cache.conanfile(conan_reference)
conan_file = self._loader().load_class(conanfile_path)
except NotFoundException:
raise NotFoundException("There is no local conanfile exported as %s"
% str(conan_reference))
# Can't use build_policy_always here because it's not loaded (only load_class)
if conan_file.build_policy == "always" and (all_packages or package_id):
raise ConanException("Conanfile has build_policy='always', "
"no packages can be uploaded")
if package_id: # Upload package
uploader.upload_package(PackageReference(conan_reference, package_id))
else: # Upload conans
uploader.upload_conan(conan_reference, all_packages=all_packages, force=force)
logger.debug("====> Time manager upload: %f" % (time.time() - t1))
def search(self, pattern_or_reference=None, remote=None, ignorecase=True, packages_query=None):
""" Print the single information saved in conan.vars about all the packages
or the packages which match with a pattern
Attributes:
pattern = string to match packages
remote = search on another origin to get packages info
packages_pattern = String query with binary
packages properties: "arch=x86 AND os=Windows"
"""
printer = Printer(self._user_io.out)
if remote:
remote_proxy = ConanProxy(self._client_cache, self._user_io, self._remote_manager,
remote)
adapter = remote_proxy
else:
adapter = self._search_manager
if isinstance(pattern_or_reference, ConanFileReference):
packages_props = adapter.search_packages(pattern_or_reference, packages_query)
ordered_packages = OrderedDict(sorted(packages_props.items()))
try:
recipe_hash = self._client_cache.load_manifest(pattern_or_reference).summary_hash
except IOError: # It could not exist in local
recipe_hash = None
printer.print_search_packages(ordered_packages, pattern_or_reference,
recipe_hash, packages_query)
else:
references = adapter.search(pattern_or_reference, ignorecase)
printer.print_search_recipes(references, pattern_or_reference)
def copy(self, reference, package_ids, username, channel, force=False):
""" Copy or move conanfile (exported) and packages to another user and or channel
@param reference: ConanFileReference containing the packages to be moved
@param package_ids: list of ids or [] for all list
@param username: Destination username
@param channel: Destination channel
@param remote: install only from that remote
"""
output = ScopedOutput(str(reference), self._user_io.out)
conan_file_path = self._client_cache.conanfile(reference)
conanfile = self._loader().load_conan(conan_file_path, output)
copier = PackageCopier(self._client_cache, self._user_io, conanfile.short_paths)
if not package_ids:
packages = self._client_cache.packages(reference)
if os.path.exists(packages):
package_ids = os.listdir(packages)
else:
package_ids = []
copier.copy(reference, package_ids, username, channel, force)
def remove(self, pattern, src=False, build_ids=None, package_ids_filter=None, force=False,
remote=None):
""" Remove conans and/or packages
@param pattern: string to match packages
@param package_ids: list of ids or [] for all list
@param remote: search on another origin to get packages info
@param force: if True, it will be deleted without requesting anything
"""
remote_proxy = ConanProxy(self._client_cache, self._user_io, self._remote_manager, remote)
remover = ConanRemover(self._client_cache, self._search_manager, self._user_io,
remote_proxy)
remover.remove(pattern, src, build_ids, package_ids_filter, force=force)
def user(self, remote=None, name=None, password=None):
remote_proxy = ConanProxy(self._client_cache, self._user_io, self._remote_manager, remote)
return remote_proxy.authenticate(name, password)
| 50.542125 | 99 | 0.648282 |
c873f3d9458fa2eb40491f0582969e3c472218be | 7,141 | py | Python | examples/python_scripts/plot_sf_and_necr.py | kamilrakoczy/j-pet-gate-tools | 0bd40b42dd333d742f34f9c2134737bfd5612281 | [
"Apache-2.0"
] | 2 | 2019-01-29T15:11:07.000Z | 2020-07-28T21:51:35.000Z | examples/python_scripts/plot_sf_and_necr.py | kamilrakoczy/j-pet-gate-tools | 0bd40b42dd333d742f34f9c2134737bfd5612281 | [
"Apache-2.0"
] | 15 | 2017-07-05T08:15:46.000Z | 2022-02-02T01:32:10.000Z | examples/python_scripts/plot_sf_and_necr.py | kamilrakoczy/j-pet-gate-tools | 0bd40b42dd333d742f34f9c2134737bfd5612281 | [
"Apache-2.0"
] | 11 | 2017-06-27T06:40:11.000Z | 2022-01-02T16:00:19.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt2
from numpy import *
from scipy import interpolate
from matplotlib import rcParams, rcParamsDefault
import argparse
from nema_common import *
outputformat = ""
def plot_rates(geometry,float_activity,N_true,N_dsca,N_psca,N_acci,time):
rcParams['font.size'] = 20
rcParams['legend.fontsize'] = 16
fig, axs = plt2.subplots(nrows=1, ncols=1, sharex=True)
plt2.subplots_adjust(left=0.2, right=0.95, top=0.95, bottom=0.17)
plt2.plot(float_activity,N_true/time/1000.,'o-',label="true", markersize=4)
plt2.plot(float_activity,N_dsca/time/1000.,'o-',label="dsca", markersize=4)
plt2.plot(float_activity,N_psca/time/1000.,'o-',label="psca", markersize=4)
plt2.plot(float_activity,N_acci/time/1000.,'o-',label="acci", markersize=4)
plt2.legend(loc=2)
plt2.xlim(0,90)
plt2.ylim(ymin=0)
plt2.xlabel("Activity concentration [kBq/cc]")
plt2.ylabel("Rate [kcps]")
plt2.savefig(workdir_NECR + geometry + "_rates." + outputformat)
plt2.clf()
plt2.close()
rcParams.update(rcParamsDefault)
def plot_necrs(float_activities, NECRs, colors, labels, necr_type, lstyles):
fig, axs = plt.subplots(nrows=1, ncols=1, sharex=True)
for i in xrange(len(NECRs)):
plt.plot(float_activities[i], NECRs[i], lstyles[i], color=colors[i], label=labels[i], markersize=4)
rcParams.update(rcParamsDefault)
rcParams['legend.fontsize'] = 11
rcParams['font.size'] = 20
FONTSIZE = 20
plt.subplots_adjust(left=0.2, right=0.95, top=0.95, bottom=0.17)
plt.legend(loc=1)
plt.xlim(0,90)
plt.ylim(0,1.1*NECR_sin_max)
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.xlabel("Activity concentration [kBq/cc]", fontsize=FONTSIZE)
plt.ylabel("NECR [kcps]", fontsize=FONTSIZE)
plt.savefig(workdir_NECR + "NECR_all_geometries_" + necr_type + '.' + outputformat)
plt.clf()
plt.close()
def calculate_reduction_for_necr_simulations(necr_simulations):
for g in geometries_NECR:
sls_file = workdir_NECR + g + "/second_lvl_selection.txt"
if os.path.exists(sls_file):
os.system('rm ' + sls_file)
for a in activities_NECR:
coincidences_file = necr_simulations + "/" + g + "_" + a + "_NECR_COINCIDENCES_short"
tmp = loadtxt(coincidences_file)
posX1 = tmp[:,0]
posY1 = tmp[:,1]
times1 = tmp[:,3]
posX2 = tmp[:,4]
posY2 = tmp[:,5]
times2 = tmp[:,7]
[tim_diffs, ang_diffs] = calculate_differences(times1, times2, posX1, posY1, posX2, posY2)
[counter_above, counter_below] = calculate_counters(tim_diffs, ang_diffs)
with open(sls_file, "a") as myfile:
myfile.write("{0}\t{1}\t{2}\n".format(counter_above, counter_below, counter_above+counter_below))
print g + "\t" + a + "\t" + str(counter_above) + "\t" + str(counter_below) + "\t" + str(counter_above+counter_below)
def plot_reduction_for_necr_simulations():
rcParams['font.size'] = 24
rcParams['legend.fontsize'] = 18
activities = []
for a in activities_NECR:
activities.append(float(a)/22000.*1000) # in kBq/cc
new_activities = linspace(activities[0],activities[-1],100)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
plt.ylim(ymin=0,ymax=80)
plt.xlim(xmin=0,xmax=90)
for g in geometries_NECR:
lab = ""
c = ""
l = ""
if "1lay" in g:
lab += "1 layer, "
c = 'k'
elif "2lay" in g:
lab += "2 layers, "
c = 'r'
if "L020" in g:
lab += "L = 20 cm"
l = '--'
elif "L050" in g:
lab += "L = 50 cm"
l = '-'
elif "L100" in g:
lab += "L = 100 cm"
l = '-.'
elif "L200" in g:
lab += "L = 200 cm"
l = ':'
sls_file = workdir_NECR + g + "/second_lvl_selection.txt"
if os.path.exists(sls_file):
tmp = loadtxt(sls_file)
counter_above = tmp[:,0]
counter_below = tmp[:,1]
reduction = counter_below/(counter_above+counter_below)*100.
new_reduction = interpolate.splev(new_activities, interpolate.splrep(activities, reduction, s=5), der=0)
plt.plot(new_activities, new_reduction, linestyle=l, color=c, label=lab)
plt.legend(loc=4)
plt.xlabel("Activity concentration [kBq/cc]")
plt.ylabel("Reduction [%]")
plt.savefig(workdir_NECR + "second_lvl_selection" + outputformat, bbox_inches='tight')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Plot NECR.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-of', '--outputformat',
type=str,
default="png",
help='output format of images')
parser.add_argument('-r', '--reduction',
dest='reduction',
action='store_true',
help='set if you want to calculate and plot the reduction ' +
'given by the 2nd level of the reduction method in case ' +
'of the NECR simulations (must be used with -ns option)')
parser.add_argument('-ns', '--necr-simulations',
dest='necr_simulations',
type=str,
help='path to the base directory of the NECR simulations')
args = parser.parse_args()
outputformat = args.outputformat
if args.reduction:
create_work_directories()
calculate_reduction_for_necr_simulations(args.necr_simulations)
plot_reduction_for_necr_simulations()
else:
plt.subplots(nrows=1, ncols=1, sharex=True)
float_activities = []
NECRs_sin = []
NECRs_ctr = []
colors = []
labels = []
lstyles = []
for geometry in geometries_NECR:
tmp = loadtxt(workdir_NECR + geometry + "/necr_dependency.txt")
float_activity = tmp[:,0]
SF_sin = tmp[:,1]
SF_crt = tmp[:,2]
NECR_sin = tmp[:,3]
NECR_sin_max = max(NECR_sin)
NECR_ctr = tmp[:,4]
T = tmp[:,5]
S = tmp[:,6]
N_true = tmp[:,7]
N_dsca = tmp[:,8]
N_psca = tmp[:,9]
N_acci = tmp[:,10]
time = tmp[:,11]
plot_rates(geometry,float_activity,N_true,N_dsca,N_psca,N_acci,time)
new_label = ""
if "1lay" in geometry:
linestyle='o-'
new_label += "1 layer"
else:
linestyle = 'o--'
new_label += "2 layers"
if "L020" in geometry:
datacolor = 'r'
new_label += ", L = 20 cm"
elif "L050" in geometry:
datacolor = 'b'
new_label += ", L = 50 cm"
elif "L100" in geometry:
datacolor = 'y'
new_label += ", L = 100 cm"
elif "L200" in geometry:
datacolor = 'g'
new_label += ", L = 200 cm"
float_activities.append(float_activity)
NECRs_sin.append(NECR_sin)
NECRs_ctr.append(NECR_ctr)
colors.append(datacolor)
labels.append(new_label)
lstyles.append(linestyle)
plot_necrs(float_activities, NECRs_sin, colors, labels, "sin", lstyles)
plot_necrs(float_activities, NECRs_ctr, colors, labels, "ctr", lstyles)
| 31.45815 | 122 | 0.622462 |
3624dcc70fad1fe3bc52c117811fb6ebf7980d4b | 93 | py | Python | pymt_heatc/lib/__init__.py | mdpiper/pymt-heatc | 4492bd0ed967f09fc9979d273c48f8d912ff966f | [
"MIT"
] | null | null | null | pymt_heatc/lib/__init__.py | mdpiper/pymt-heatc | 4492bd0ed967f09fc9979d273c48f8d912ff966f | [
"MIT"
] | 1 | 2021-09-01T20:37:33.000Z | 2021-09-01T20:38:24.000Z | pymt_heatc/lib/__init__.py | mdpiper/pymt_heatc | 4492bd0ed967f09fc9979d273c48f8d912ff966f | [
"MIT"
] | null | null | null | #! /usr/bin/env python
from .heatmodelc import HeatModelC
__all__ = [
"HeatModelC",
]
| 10.333333 | 34 | 0.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.