code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
schema_type = type(schema)
# Marker
if issubclass(schema_type, markers.Marker):
return const.COMPILED_TYPE.MARKER
# Marker Type
elif issubclass(schema_type, six.class_types) and issubclass(schema, markers.Marker):
return const.COMPILED_TYPE.MARKE... | def get_schema_type(cls, schema) | Get schema type for the argument
:param schema: Schema to analyze
:return: COMPILED_TYPE constant
:rtype: str|None | 4.085035 | 3.92378 | 1.041097 |
# Markers have priority set on the class
if self.compiled_type == const.COMPILED_TYPE.MARKER:
return self.compiled.priority
# Other types have static priority
return const.compiled_type_priorities[self.compiled_type] | def priority(self) | Get priority for this Schema.
Used to sort mapping keys
:rtype: int | 10.06942 | 10.425241 | 0.965869 |
return sorted(schemas_list,
key=lambda x: (
# Top-level priority:
# priority of the schema itself
x.priority,
# Second-level priority (for markers of the common type)
... | def sort_schemas(cls, schemas_list) | Sort the provided list of schemas according to their priority.
This also supports markers, and markers of a single type are also sorted according to the priority of the wrapped schema.
:type schemas_list: list[CompiledSchema]
:rtype: list[CompiledSchema] | 11.288535 | 9.187916 | 1.228628 |
return type(self)(
schema,
self.path + (path or []),
None,
None,
matcher
) | def sub_compile(self, schema, path=None, matcher=False) | Compile a sub-schema
:param schema: Validation schema
:type schema: *
:param path: Path to this schema, if any
:type path: list|None
:param matcher: Compile a matcher?
:type matcher: bool
:rtype: CompiledSchema | 6.610684 | 8.509415 | 0.776867 |
def InvalidPartial(provided, path=None, **info):
return Invalid(
message,
expected, #six.text_type(expected), # -- must be unicode
provided, #six.text_type(provided), # -- must be unicode
self.path + (path or [])... | def Invalid(self, message, expected) | Helper for Invalid errors.
Typical use:
err_type = self.Invalid(_(u'Message'), self.name)
raise err_type(<provided-value>)
Note: `provided` and `expected` are unicode-typecasted automatically
:type message: unicode
:type expected: unicode | 8.29703 | 8.833076 | 0.939314 |
# Schema type
schema_type = self.get_schema_type(schema)
if schema_type is None:
return None
# Compiler
compilers = {
const.COMPILED_TYPE.LITERAL: self._compile_literal,
const.COMPILED_TYPE.TYPE: self._compile_type,
const.... | def get_schema_compiler(self, schema) | Get compiler method for the provided schema
:param schema: Schema to analyze
:return: Callable compiled
:rtype: callable|None | 2.334504 | 2.29745 | 1.016129 |
compiler = self.get_schema_compiler(schema)
if compiler is None:
raise SchemaError(_(u'Unsupported schema data type {!r}').format(type(schema).__name__))
return compiler(schema) | def compile_schema(self, schema) | Compile the current schema into a callable validator
:return: Callable validator
:rtype: callable
:raises SchemaError: Schema compilation error | 5.286351 | 4.71166 | 1.121972 |
# Prepare self
self.compiled_type = const.COMPILED_TYPE.LITERAL
self.name = get_literal_name(schema)
# Error partials
schema_type = type(schema)
err_type = self.Invalid(_(u'Wrong value type'), get_type_name(schema_type))
err_value = self.Invalid(_(u'Inv... | def _compile_literal(self, schema) | Compile literal schema: type and value matching | 4.570645 | 4.450006 | 1.02711 |
# Prepare self
self.compiled_type = const.COMPILED_TYPE.TYPE
self.name = get_type_name(schema)
# Error partials
err_type = self.Invalid(_(u'Wrong type'), self.name)
# Type check function
if six.PY2 and schema is basestring:
# Relaxed rule fo... | def _compile_type(self, schema) | Compile type schema: plain type matching | 6.569929 | 6.445439 | 1.019314 |
assert self.matcher == schema.matcher
self.name = schema.name
self.compiled_type = schema.compiled_type
return schema.compiled | def _compile_schema(self, schema) | Compile another schema | 9.07014 | 7.616385 | 1.190872 |
# Prepare self
self.compiled_type = const.COMPILED_TYPE.CALLABLE
self.name = get_callable_name(schema)
# Error utils
enrich_exception = lambda e, value: e.enrich(
expected=self.name,
provided=get_literal_name(value),
path=self.path,
... | def _compile_callable(self, schema) | Compile callable: wrap exceptions with correct paths | 5.238951 | 5.028474 | 1.041857 |
# Compile each member as a schema
schema_type = type(schema)
schema_subs = tuple(map(self.sub_compile, schema))
# When the schema is an iterable with a single item (e.g. [dict(...)]),
# Invalid errors from schema members should be immediately used.
# This allows... | def _compile_iterable(self, schema) | Compile iterable: iterable of schemas treated as allowed values | 6.64187 | 6.548335 | 1.014284 |
# Prepare self
self.compiled_type = const.COMPILED_TYPE.MARKER
# If this marker is not instantiated -- do it with an identity callable which is valid for everything
if issubclass(type(schema), six.class_types):
schema = schema(Identity) \
.on_compil... | def _compile_marker(self, schema) | Compile marker: sub-schema with special type | 11.48167 | 10.814788 | 1.061664 |
w, s, _ = np.linalg.svd(x, full_matrices=False)
return w, s ** 2 | def pca_svd(x) | Calculate PCA using SVD.
Parameters
----------
x : ndarray, shape (channels, samples)
Two-dimensional input data.
Returns
-------
w : ndarray, shape (channels, channels)
Eigenvectors (principal components) (in columns).
s : ndarray, shape (channels,)
Eig... | 3.300344 | 3.457004 | 0.954684 |
s, w = np.linalg.eigh(x.dot(x.T))
return w, s | def pca_eig(x) | Calculate PCA using eigenvalue decomposition.
Parameters
----------
x : ndarray, shape (channels, samples)
Two-dimensional input data.
Returns
-------
w : ndarray, shape (channels, channels)
Eigenvectors (principal components) (in columns).
s : ndarray, shape (channels,... | 3.67965 | 5.001402 | 0.735724 |
x = np.asarray(x)
if x.ndim == 3:
x = cat_trials(x)
if reducedim:
sort_components = True
if subtract_mean:
x = x - np.mean(x, axis=1, keepdims=True)
k, l = None, None
if normalize:
l = np.std(x, axis=1, ddof=1)
k = np.diag(1.0 / l)
l = np.... | def pca(x, subtract_mean=False, normalize=False, sort_components=True,
reducedim=None, algorithm=pca_eig) | Calculate principal component analysis (PCA).
Parameters
----------
x : ndarray, shape (trials, channels, samples) or (channels, samples)
Input data.
subtract_mean : bool, optional
Subtract sample mean from x.
normalize : bool, optional
Normalize variances before applyin... | 2.631111 | 2.579565 | 1.019982 |
data = sploadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_keys(data) | def loadmat(filename) | This function should be called instead of direct spio.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files. It calls the function check keys to cure all entries
which are still mat-objects | 3.457622 | 5.104978 | 0.677304 |
for key in dictionary:
if isinstance(dictionary[key], matlab.mio5_params.mat_struct):
dictionary[key] = _todict(dictionary[key])
return dictionary | def _check_keys(dictionary) | checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries | 3.399876 | 2.324846 | 1.462409 |
dictionary = {}
#noinspection PyProtectedMember
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, matlab.mio5_params.mat_struct):
dictionary[strg] = _todict(elem)
else:
dictionary[strg] = elem
return dictionary | def _todict(matobj) | a recursive function which constructs from matobjects nested dictionaries | 2.014293 | 1.77272 | 1.136272 |
x = atleast_3d(x)
t, m, l = np.shape(x)
if backend is None:
backend = scotbackend
# pre-transform the data with PCA
if reducedim == 'no pca':
c = np.eye(m)
d = np.eye(m)
xpca = x
else:
c, d, xpca = backend['pca'](x, reducedim)
# run on residua... | def plainica(x, reducedim=0.99, backend=None, random_state=None) | Source decomposition with ICA.
Apply ICA to the data x, with optional PCA dimensionality reduction.
Parameters
----------
x : array, shape (n_trials, n_channels, n_samples) or (n_channels, n_samples)
data set
reducedim : {int, float, 'no_pca'}, optional
A number of less than 1 in i... | 8.113329 | 7.987554 | 1.015746 |
t, m, l = data.shape
d = None
j, k = 0, 0
nt = np.ceil(t / skipstep)
for trainset, testset in xvschema(t, skipstep):
a, b = _construct_var_eqns(atleast_3d(data[trainset, :, :]), p)
c, d = _construct_var_eqns(atleast_3d(data[testset, :, :]), p)
e = sp.linalg.inv(np.eye(... | def _msge_with_gradient_underdetermined(data, delta, xvschema, skipstep, p) | Calculate mean squared generalization error and its gradient for
underdetermined equation system. | 3.859555 | 3.743504 | 1.031001 |
t, m, l = data.shape
d = None
l, k = 0, 0
nt = np.ceil(t / skipstep)
for trainset, testset in xvschema(t, skipstep):
a, b = _construct_var_eqns(atleast_3d(data[trainset, :, :]), p)
c, d = _construct_var_eqns(atleast_3d(data[testset, :, :]), p)
e = sp.linalg.inv(np.eye(... | def _msge_with_gradient_overdetermined(data, delta, xvschema, skipstep, p) | Calculate mean squared generalization error and its gradient for
overdetermined equation system. | 3.984783 | 3.877078 | 1.02778 |
t, m, l = shape
n = (l - p) * t
underdetermined = n < m * p
if underdetermined:
return _msge_with_gradient_underdetermined
else:
return _msge_with_gradient_overdetermined | def _get_msge_with_gradient_func(shape, p) | Select which function to use for MSGE calculation (over- or
underdetermined). | 5.349001 | 4.091753 | 1.307264 |
t, m, l = data.shape
n = (l - p) * t
underdetermined = n < m * p
if underdetermined:
return _msge_with_gradient_underdetermined(data, delta, xvschema,
skipstep, p)
else:
return _msge_with_gradient_overdetermined(data, delta, x... | def _get_msge_with_gradient(data, delta, xvschema, skipstep, p) | Calculate mean squared generalization error and its gradient,
automatically selecting the best function. | 3.194364 | 3.199509 | 0.998392 |
data = atleast_3d(data)
if self.delta == 0 or self.delta is None:
# ordinary least squares
x, y = self._construct_eqns(data)
else:
# regularized least squares (ridge regression)
x, y = self._construct_eqns_rls(data)
b, res, rank,... | def fit(self, data) | Fit VAR model to data.
Parameters
----------
data : array, shape (trials, channels, samples) or (channels, samples)
Epoched or continuous data set.
Returns
-------
self : :class:`VAR`
The :class:`VAR` object to facilitate meth... | 4.939467 | 5.324926 | 0.927612 |
data = np.asarray(data)
if data.shape[0] < 2:
raise ValueError("At least two trials are required.")
msge, prange = [], []
par, func = parallel_loop(_get_msge_with_gradient, n_jobs=self.n_jobs,
verbose=self.verbose)
if self.... | def optimize_order(self, data, min_p=1, max_p=None) | Determine optimal model order by minimizing the mean squared
generalization error.
Parameters
----------
data : array, shape (n_trials, n_channels, n_samples)
Epoched data set on which to optimize the model order. At least two
trials are required.
min_p :... | 3.694458 | 3.629197 | 1.017982 |
data = atleast_3d(data)
if data.shape[0] < 2:
raise ValueError("At least two trials are required.")
if verbose is None:
verbose = config.getboolean('scot', 'verbose')
maxsteps = 10
maxdelta = 1e50
a = -10
b = 10
trform ... | def optimize_delta_bisection(self, data, skipstep=1, verbose=None) | Find optimal ridge penalty with bisection search.
Parameters
----------
data : array, shape (n_trials, n_channels, n_samples)
Epoched data set. At least two trials are required.
skipstep : int, optional
Speed up calculation by skipping samples during cost... | 3.456882 | 3.477009 | 0.994211 |
w = v.normalized()
return cls(w.x, w.y, w.z) | def fromvector(cls, v) | Initialize from euclidean vector | 4.429187 | 4.347332 | 1.018829 |
return [self._pos3d.x, self._pos3d.y, self._pos3d.z] | def list(self) | position in 3d space | 5.124357 | 2.893315 | 1.771103 |
return math.acos(self._pos3d.dot(other.vector)) | def distance(self, other) | Distance to another point on the sphere | 18.85453 | 12.852798 | 1.466959 |
return [math.acos(self._pos3d.dot(p.vector)) for p in points] | def distances(self, points) | Distance to other points on the sphere | 13.482297 | 10.599425 | 1.271984 |
x, y, z = itr
return cls(x, y, z) | def fromiterable(cls, itr) | Initialize from iterable | 5.366428 | 4.859117 | 1.104404 |
return cls(v.x, v.y, v.z) | def fromvector(cls, v) | Copy another vector | 3.851953 | 3.556285 | 1.083139 |
return self.x * self.x + self.y * self.y + self.z * self.z | def norm2(self) | Squared norm of the vector | 2.960178 | 2.606359 | 1.135752 |
cl = math.cos(l)
sl = math.sin(l)
x = (cl + u.x * u.x * (1 - cl)) * self.x + (u.x * u.y * (1 - cl) - u.z * sl) * self.y + (
u.x * u.z * (1 - cl) + u.y * sl) * self.z
y = (u.y * u.x * (1 - cl) + u.z * sl) * self.x + (cl + u.y * u.y * (1 - cl)) * self.y + (
u.y * u... | def rotate(self, l, u) | rotate l radians around axis u | 1.432664 | 1.341639 | 1.067846 |
x = np.asarray(x)
cl = np.asarray(cl).ravel()
if x.ndim != 3 or x.shape[0] < 2:
raise AttributeError('CSP requires at least two trials.')
t, m, n = x.shape
if t != cl.size:
raise AttributeError('CSP only works with multiple classes. Number of '
... | def csp(x, cl, numcomp=None) | Calculate common spatial patterns (CSP).
Parameters
----------
x : array, shape (trials, channels, samples) or (channels, samples)
EEG data set.
cl : list of valid dict keys
Class labels associated with each trial. Currently, only two classes
are supported.
numcomp : int, op... | 2.561027 | 2.402445 | 1.066008 |
matrix = np.atleast_2d(matrix)
n, m = matrix.shape
assert(n == m)
# make sure the matrix is really symmetric. This is equivalent to
# converting a directed adjacency matrix into a undirected adjacency matrix.
matrix = np.logical_or(matrix, matrix.T)
degree = np.sum(matrix, 0)
orde... | def cuthill_mckee(matrix) | Implementation of the Cuthill-McKee algorithm.
Permute a symmetric binary matrix into a band matrix form with a small bandwidth.
Parameters
----------
matrix : ndarray, dtype=bool, shape = [n, n]
The matrix is internally converted to a symmetric matrix by setting each element [i,j] to True if ... | 2.756734 | 2.929948 | 0.940882 |
con = Connectivity(b, c, nfft)
try:
return getattr(con, measure_names)()
except TypeError:
return dict((m, getattr(con, m)()) for m in measure_names) | def connectivity(measure_names, b, c=None, nfft=512) | Calculate connectivity measures.
Parameters
----------
measure_names : str or list of str
Name(s) of the connectivity measure(s) to calculate. See
:class:`Connectivity` for supported measures.
b : array, shape (n_channels, n_channels * model_order)
VAR model coefficients. See :r... | 3.518466 | 5.216379 | 0.674503 |
try:
return np.linalg.inv(self.c)
except np.linalg.linalg.LinAlgError:
print('Warning: non-invertible noise covariance matrix c.')
return np.eye(self.c.shape[0]) | def Cinv(self) | Inverse of the noise covariance. | 3.49142 | 3.004056 | 1.162235 |
return fft(np.dstack([np.eye(self.m), -self.b]),
self.nfft * 2 - 1)[:, :, :self.nfft] | def A(self) | Spectral VAR coefficients.
.. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)}
\mathrm{e}^{-2\pi f} | 9.055758 | 9.143247 | 0.990431 |
if self.c is None:
raise RuntimeError('Cross-spectral density requires noise '
'covariance matrix c.')
H = self.H()
# TODO: can we do that more efficiently?
S = np.empty(H.shape, dtype=H.dtype)
for f in range(H.shape[2]):
... | def S(self) | Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) | 4.297768 | 3.830646 | 1.121943 |
if self.c is None:
raise RuntimeError('Inverse cross spectral density requires '
'invertible noise covariance matrix c.')
A = self.A()
# TODO: can we do that more efficiently?
G = np.einsum('ji..., jk... ->ik...', A.conj(), self.Cinv())... | def G(self) | Inverse cross-spectral density.
.. math:: \mathbf{G}(f) = \mathbf{A}(f) \mathbf{C}^{-1} \mathbf{A}'(f) | 7.298398 | 5.765892 | 1.265788 |
S = self.S()
# TODO: can we do that more efficiently?
return S / np.sqrt(np.einsum('ii..., jj... ->ij...', S, S.conj())) | def COH(self) | Coherence.
.. math:: \mathrm{COH}_{ij}(f) = \\frac{S_{ij}(f)}
{\sqrt{S_{ii}(f) S_{jj}(f)}}
References
----------
P. L. Nunez, R. Srinivasan, A. F. Westdorp, R. S. Wijesinghe,
D. M. Tucker, R. B. Silverstein, P. J. Cadusch. EEG cohe... | 10.775684 | 10.985371 | 0.980912 |
G = self.G()
# TODO: can we do that more efficiently?
return G / np.sqrt(np.einsum('ii..., jj... ->ij...', G, G)) | def pCOH(self) | Partial coherence.
.. math:: \mathrm{pCOH}_{ij}(f) = \\frac{G_{ij}(f)}
{\sqrt{G_{ii}(f) G_{jj}(f)}}
References
----------
P. J. Franaszczuk, K. J. Blinowska, M. Kowalczyk. The application of
parametric multichannel spectral estima... | 12.20465 | 11.161736 | 1.093436 |
A = self.A()
return np.abs(A / np.sqrt(np.sum(A.conj() * A, axis=0, keepdims=True))) | def PDC(self) | Partial directed coherence.
.. math:: \mathrm{PDC}_{ij}(f) = \\frac{A_{ij}(f)}
{\sqrt{A_{:j}'(f) A_{:j}(f)}}
References
----------
L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept
in neural structure determina... | 4.779167 | 5.106126 | 0.935967 |
A = self.A()
return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2),
keepdims=True))) | def ffPDC(self) | Full frequency partial directed coherence.
.. math:: \mathrm{ffPDC}_{ij}(f) =
\\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} | 6.598233 | 5.531483 | 1.192851 |
A = self.A()
# TODO: can we do that more efficiently?
return np.abs(A / np.sqrt(np.einsum('aj..., ab..., bj... ->j...',
A.conj(), self.Cinv(), A))) | def PDCF(self) | Partial directed coherence factor.
.. math:: \mathrm{PDCF}_{ij}(f) =
\\frac{A_{ij}(f)}{\sqrt{A_{:j}'(f) \mathbf{C}^{-1} A_{:j}(f)}}
References
----------
L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept
in neural structure determination. Biol. Cybe... | 9.945999 | 9.116983 | 1.090931 |
A = self.A()
tmp = A / np.sqrt(np.einsum('aj..., a..., aj..., ii... ->ij...',
A.conj(), 1 / np.diag(self.c), A, self.c))
return np.abs(tmp) | def GPDC(self) | Generalized partial directed coherence.
.. math:: \mathrm{GPDC}_{ij}(f) = \\frac{|A_{ij}(f)|}
{\sigma_i \sqrt{A_{:j}'(f) \mathrm{diag}(\mathbf{C})^{-1} A_{:j}(f)}}
References
----------
L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear
multivariate processes:... | 9.378983 | 9.555778 | 0.981499 |
H = self.H()
return np.abs(H / np.sqrt(np.sum(H * H.conj(), axis=1, keepdims=True))) | def DTF(self) | Directed transfer function.
.. math:: \mathrm{DTF}_{ij}(f) = \\frac{H_{ij}(f)}
{\sqrt{H_{i:}(f) H_{i:}'(f)}}
References
----------
M. J. Kaminski, K. J. Blinowska. A new method of the description of the
information flow in the brai... | 5.079385 | 4.945866 | 1.026996 |
H = self.H()
return np.abs(H * self.nfft / np.sqrt(np.sum(H * H.conj(), axis=(1, 2),
keepdims=True))) | def ffDTF(self) | Full frequency directed transfer function.
.. math:: \mathrm{ffDTF}_{ij}(f) =
\\frac{H_{ij}(f)}{\sqrt{\sum_f H_{i:}(f) H_{i:}'(f)}}
References
----------
A. Korzeniewska, M. Mańczak, M. Kaminski, K. J. Blinowska, S. Kasicki.
Determination of information flow d... | 6.653909 | 5.820096 | 1.143265 |
H = self.H()
tmp = H / np.sqrt(np.einsum('ia..., aa..., ia..., j... ->ij...',
H.conj(), self.c, H,
1 / self.c.diagonal()))
return np.abs(tmp) | def GDTF(self) | Generalized directed transfer function.
.. math:: \mathrm{GPDC}_{ij}(f) = \\frac{\sigma_j |H_{ij}(f)|}
{\sqrt{H_{i:}(f) \mathrm{diag}(\mathbf{C}) H_{i:}'(f)}}
References
----------
L. Faes, S. Erla, G. Nollo. Measuring connectivity in linear
multivariate processes: ... | 10.563435 | 10.663055 | 0.990657 |
for e in self:
# defaults on fields
if e.expected is None and expected is not None:
e.expected = expected
if e.provided is None and provided is not None:
e.provided = provided
if e.validator is None and validator is not Non... | def enrich(self, expected=None, provided=None, path=None, validator=None) | Enrich this error with additional information.
This works with both Invalid and MultipleInvalid (thanks to `Invalid` being iterable):
in the latter case, the defaults are applied to all collected errors.
The specified arguments are only set on `Invalid` errors which do not have any value on th... | 2.996669 | 2.713144 | 1.104501 |
ers = []
for e in errors:
if isinstance(e, MultipleInvalid):
ers.extend(cls.flatten(e.errors))
else:
ers.append(e)
return ers | def flatten(cls, errors) | Unwind `MultipleErrors` to have a plain list of `Invalid`
:type errors: list[Invalid|MultipleInvalid]
:rtype: list[Invalid] | 3.056639 | 2.546471 | 1.200343 |
locations = np.asarray(locations)
if y_center is None:
c, r = _fit_ellipsoid_full(locations)
else:
c, r = _fit_ellipsoid_partial(locations, y_center)
elliptic_locations = _project_on_ellipsoid(c, r, locations)
if verbose:
print('Head ellipsoid center:', c)
pri... | def warp_locations(locations, y_center=None, return_ellipsoid=False, verbose=False) | Warp EEG electrode locations to spherical layout.
EEG Electrodes are warped to a spherical layout in three steps:
1. An ellipsoid is least-squares-fitted to the electrode locations.
2. Electrodes are displaced to the nearest point on the ellipsoid's surface.
3. The ellipsoid is transformed ... | 2.408739 | 2.287288 | 1.053099 |
a = np.hstack([locations*2, locations**2])
lsq = sp.linalg.lstsq(a, np.ones(locations.shape[0]))
x = lsq[0]
c = -x[:3] / x[3:]
gam = 1 + np.sum(x[:3]**2 / x[3:])
r = np.sqrt(gam / x[3:])
return c, r | def _fit_ellipsoid_full(locations) | identify all 6 ellipsoid parametes (center, radii) | 4.350481 | 4.124618 | 1.05476 |
a = np.vstack([locations[:, 0]**2,
locations[:, 1]**2 - 2 * locations[:, 1] * cy,
locations[:, 2]**2,
locations[:, 0]*2,
locations[:, 2]*2]).T
x = sp.linalg.lstsq(a, np.ones(locations.shape[0]))[0]
c = [-x[3] / x[0], cy, -x[4] ... | def _fit_ellipsoid_partial(locations, cy) | identify only 5 ellipsoid parameters (y-center determined by e.g. Cz) | 3.055486 | 2.963629 | 1.030995 |
p0 = locations - c # original locations
l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True)
p = p0 * np.sqrt(l2) # initial approximation (projection of points towards center of ellipsoid)
fun = lambda x: np.sum((x.reshape(p0.shape) - p0)**2) # minimize distance between new and old... | def _project_on_ellipsoid(c, r, locations) | displace locations to the nearest point on ellipsoid surface | 4.006894 | 3.89285 | 1.029296 |
if start != int(start):
raise ValueError("start index must be an integer")
if stop != int(stop):
raise ValueError("stop index must be an integer")
x2d = np.atleast_2d(x2d)
tr = np.asarray(tr, dtype=int).ravel()
win = np.arange(start, stop, dtype=int)
return np.concatenate([... | def cut_segments(x2d, tr, start, stop) | Cut continuous signal into segments.
Parameters
----------
x2d : array, shape (m, n)
Input data with m signals and n samples.
tr : list of int
Trigger positions.
start : int
Window start (offset relative to trigger).
stop : int
Window end (offset relative to trig... | 2.895257 | 3.365155 | 0.860364 |
x3d = atleast_3d(x3d)
t = x3d.shape[0]
return np.concatenate(np.split(x3d, t, 0), axis=2).squeeze(0) | def cat_trials(x3d) | Concatenate trials along time axis.
Parameters
----------
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samples.
Returns
-------
x2d : array, shape (m, t * n)
Trials are concatenated along the second axis.
See also
--------
cut_s... | 3.265018 | 4.190327 | 0.77918 |
x3d = atleast_3d(x3d)
x2d = np.atleast_2d(x2d)
return np.concatenate([x2d.dot(x3d[i, ...])[np.newaxis, ...]
for i in range(x3d.shape[0])]) | def dot_special(x2d, x3d) | Segment-wise dot product.
This function calculates the dot product of x2d with each trial of x3d.
Parameters
----------
x2d : array, shape (p, m)
Input argument.
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samples. The dot
product with ... | 2.589105 | 3.338102 | 0.775622 |
rng = check_random_state(random_state)
data = np.asarray(data)
data_freq = np.fft.rfft(data)
data_freq = np.abs(data_freq) * np.exp(1j*rng.random_sample(data_freq.shape)*2*np.pi)
return np.fft.irfft(data_freq, data.shape[-1]) | def randomize_phase(data, random_state=None) | Phase randomization.
This function randomizes the spectral phase of the input data along the
last dimension.
Parameters
----------
data : array
Input array.
Returns
-------
out : array
Array of same shape as data.
Notes
-----
The algorithm randomizes the p... | 2.226138 | 2.733012 | 0.814536 |
x = atleast_3d(x)
if l > x.shape[2]-1:
raise AttributeError("lag exceeds data length")
## subtract mean from each trial
#for t in range(x.shape[2]):
# x[:, :, t] -= np.mean(x[:, :, t], axis=0)
if l == 0:
a, b = x, x
else:
a = x[:, :, l:]
b = x[:, :,... | def acm(x, l) | Compute autocovariance matrix at lag l.
This function calculates the autocovariance matrix of `x` at lag `l`.
Parameters
----------
x : array, shape (n_trials, n_channels, n_samples)
Signal data (2D or 3D for multiple trials)
l : int
Lag
Returns
-------
c : ndarray, sh... | 2.968083 | 2.831163 | 1.048362 |
par, func = parallel_loop(_calc_surrogate, n_jobs=n_jobs, verbose=verbose)
output = par(func(randomize_phase(data, random_state=random_state), var,
measure_names, nfft) for _ in range(repeats))
return convert_output_(output, measure_names) | def surrogate_connectivity(measure_names, data, var, nfft=512, repeats=100,
n_jobs=1, verbose=0, random_state=None) | Calculate surrogate connectivity for a multivariate time series by phase
randomization [1]_.
.. note:: Parameter `var` will be modified by the function. Treat as
undefined after the function returns.
Parameters
----------
measures : str or list of str
Name(s) of the connectivity measur... | 5.583218 | 5.57794 | 1.000946 |
data = atleast_3d(data)
t, m, n = data.shape
assert(t > 1)
if leaveout < 1:
leaveout = int(leaveout * t)
num_blocks = t // leaveout
mask = lambda block: [i for i in range(t) if i < block*leaveout or
i >= (block + 1) * leaveout]
... | def jackknife_connectivity(measures, data, var, nfft=512, leaveout=1, n_jobs=1,
verbose=0) | Calculate jackknife estimates of connectivity.
For each jackknife estimate a block of trials is left out. This is repeated
until each trial was left out exactly once. The number of estimates depends
on the number of trials and the value of `leaveout`. It is calculated by
repeats = `n_trials` // `leaveo... | 4.237829 | 4.983608 | 0.850354 |
rng = check_random_state(random_state)
data = atleast_3d(data)
n, m, t = data.shape
assert(t > 1)
if num_samples is None:
num_samples = t
mask = lambda r: rng.random_integers(0, data.shape[0]-1, num_samples)
par, func = parallel_loop(_calc_bootstrap, n_jobs=n_jobs, verbose=v... | def bootstrap_connectivity(measures, data, var, nfft=512, repeats=100,
num_samples=None, n_jobs=1, verbose=0,
random_state=None) | Calculate bootstrap estimates of connectivity.
To obtain a bootstrap estimate trials are sampled randomly with replacement
from the data set.
.. note:: Parameter `var` will be modified by the function. Treat as
undefined after the function returns.
Parameters
----------
measures : str or ... | 3.599377 | 4.252496 | 0.846415 |
i = np.argsort(p, axis=None)
m = i.size - np.sum(np.isnan(p))
j = np.empty(p.shape, int)
j.flat[i] = np.arange(1, i.size + 1)
mask = p <= alpha * j / m
if np.sum(mask) == 0:
return mask
# find largest k so that p_k <= alpha*k/m
k = np.max(j[mask])
# reject all H_i f... | def significance_fdr(p, alpha) | Calculate significance by controlling for the false discovery rate.
This function determines which of the p-values in `p` can be considered
significant. Correction for multiple comparisons is performed by
controlling the false discovery rate (FDR). The FDR is the maximum fraction
of p-values that are w... | 4.913302 | 4.826022 | 1.018085 |
assert isinstance(t, type)
assert isinstance(name, unicode)
__type_names[t] = name | def register_type_name(t, name) | Register a human-friendly name for the given type. This will be used in Invalid errors
:param t: The type to register
:type t: type
:param name: Name for the type
:type name: unicode | 4.283421 | 4.123529 | 1.038775 |
# Lookup in the mapping
try:
return __type_names[t]
except KeyError:
# Specific types
if issubclass(t, six.integer_types):
return _(u'Integer number')
# Get name from the Type itself
return six.text_type(t.__name__).capitalize() | def get_type_name(t) | Get a human-friendly name for the given type.
:type t: type|None
:rtype: unicode | 6.92167 | 6.82201 | 1.014609 |
if hasattr(c, 'name'):
return six.text_type(c.name)
elif hasattr(c, '__name__'):
return six.text_type(c.__name__) + u'()'
else:
return six.text_type(c) | def get_callable_name(c) | Get a human-friendly name for the given callable.
:param c: The callable to get the name for
:type c: callable
:rtype: unicode | 2.52744 | 2.689905 | 0.939602 |
try:
return {
const.COMPILED_TYPE.LITERAL: six.text_type,
const.COMPILED_TYPE.TYPE: get_type_name,
const.COMPILED_TYPE.ENUM: get_type_name,
const.COMPILED_TYPE.CALLABLE: get_callable_name,
const.COMPILED_TYPE.ITERABLE: lambda x: _(u'{type}[{co... | def get_primitive_name(schema) | Get a human-friendly name for the given primitive.
:param schema: Schema
:type schema: *
:rtype: unicode | 3.066009 | 3.017237 | 1.016164 |
schema_type = type(schema)
# Literal
if schema_type in const.literal_types:
return const.COMPILED_TYPE.LITERAL
# Enum
elif Enum is not None and isinstance(schema, (EnumMeta, Enum)):
return const.COMPILED_TYPE.ENUM
# Type
elif issubclass(schema_type, six.class_types):
... | def primitive_type(schema) | Get schema type for the primitive argument.
Note: it does treats markers & schemas as callables!
:param schema: Value of a primitive type
:type schema: *
:return: const.COMPILED_TYPE.*
:rtype: str|None | 2.711426 | 2.386702 | 1.136056 |
return _(u',').join((six.text_type(i) for i in iterable)) | def commajoin_as_strings(iterable) | Join the given iterable with ',' | 8.07716 | 7.860752 | 1.02753 |
values = np.atleast_2d(values)
topomaps = []
for i in range(values.shape[0]):
topo.set_values(values[i, :])
topo.create_map()
topomaps.append(topo.get_map())
return topomaps | def prepare_topoplots(topo, values) | Prepare multiple topo maps for cached plotting.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_values`.
Parameters
----------
topo : :class:`~eegtopo.topoplot.Topoplot`
Scalp maps are created with this class
values : array, shape = [... | 2.660612 | 2.784025 | 0.955671 |
topo.set_map(topomap)
h = topo.plot_map(axis, crange=crange, offset=offset)
if plot_locations:
topo.plot_locations(axis, offset=offset)
if plot_head:
topo.plot_head(axis, offset=offset)
return h | def plot_topo(axis, topo, topomap, crange=None, offset=(0,0),
plot_locations=True, plot_head=True) | Draw a topoplot in given axis.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
axis : axis
Axis to draw into.
topo : :class:`~eegtopo.topoplot.Topoplot`
This object draws the topo plot
topomap :... | 2.292456 | 2.318409 | 0.988806 |
urange, mrange = None, None
m = len(mixmaps)
if global_scale:
tmp = np.asarray(unmixmaps)
tmp = tmp[np.logical_not(np.isnan(tmp))]
umax = np.percentile(np.abs(tmp), global_scale)
umin = -umax
urange = [umin, umax]
tmp = np.asarray(mixmaps)
tmp ... | def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None) | Plot all scalp projections of mixing- and unmixing-maps.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
topo : :class:`~eegtopo.topoplot.Topoplot`
This object draws the topo plot
mixmaps : array, shape = [... | 2.117401 | 2.146422 | 0.98648 |
m = len(topomaps)
if fig is None:
fig = new_figure()
if layout == 'diagonal':
for i in range(m):
ax = fig.add_subplot(m, m, i*(1+m) + 1)
plot_topo(ax, topo, topomaps[i])
ax.set_yticks([])
ax.set_xticks([])
ax.set_frame_on(Fa... | def plot_connectivity_topos(layout='diagonal', topo=None, topomaps=None, fig=None) | Place topo plots in a figure suitable for connectivity visualization.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
layout : str
'diagonal' -> place topo plots on diagonal.
otherwise -> place topo plo... | 1.97134 | 2.050565 | 0.961364 |
a = np.atleast_3d(s)
[_, m, f] = a.shape
freq = np.linspace(0, fs / 2, f)
left = max(freq_range[0], freq[0])
right = min(freq_range[1], freq[-1])
imext = (freq[0], freq[-1], -1e25, 1e25)
if fig is None:
fig = new_figure()
axes = []
for i in range(m):
if diag... | def plot_connectivity_significance(s, fs=2, freq_range=(-np.inf, np.inf), diagonal=0, border=False, fig=None) | Plot significance.
Significance is drawn as a background image where dark vertical stripes indicate freuquencies where a evaluates to
True.
Parameters
----------
a : array, shape (n_channels, n_channels, n_fft), dtype bool
Significance
fs : float
Sampling frequency
freq_ran... | 2.426484 | 2.485113 | 0.976408 |
a = np.asarray(a)
[_, m, _, t] = a.shape
if crange is None:
crange = [np.min(a), np.max(a)]
if time_range is None:
t0 = 0
t1 = t
else:
t0, t1 = time_range
f0, f1 = fs / 2, 0
extent = [t0, t1, f0, f1]
ymin = max(freq_range[0], f1)
ymax = min(fr... | def plot_connectivity_timespectrum(a, fs=2, crange=None, freq_range=(-np.inf, np.inf), time_range=None, diagonal=0, border=False, fig=None) | Draw time/frequency connectivity plots.
Parameters
----------
a : array, shape (n_channels, n_channels, n_fft, n_timesteps)
Values to draw
fs : float
Sampling frequency
crange : [int, int], optional
Range of values covered by the colormap.
If set to None, [min(a), ma... | 2.042251 | 2.086984 | 0.978566 |
pr, q0, q = var.test_whiteness(h, repeats, True)
if axis is None:
axis = current_axis()
pdf, _, _ = axis.hist(q0, 30, normed=True, label='surrogate distribution')
axis.plot([q,q], [0,np.max(pdf)], 'r-', label='fitted model')
#df = m*m*(h-p)
#x = np.linspace(np.min(q0)*0.0, np.max... | def plot_whiteness(var, h, repeats=1000, axis=None) | Draw distribution of the Portmanteu whiteness test.
Parameters
----------
var : :class:`~scot.var.VARBase`-like object
Vector autoregressive model (VAR) object whose residuals are tested for whiteness.
h : int
Maximum lag to include in the test.
repeats : int, optional
Numbe... | 4.752419 | 4.780303 | 0.994167 |
for t in range(0, num_trials, skipstep):
trainset = [t]
testset = [i for i in range(trainset[0])] + \
[i for i in range(trainset[-1] + 1, num_trials)]
testset = sort([t % num_trials for t in testset])
yield trainset, testset | def singletrial(num_trials, skipstep=1) | Single-trial cross-validation schema
Use one trial for training, all others for testing.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
only use every `skipstep` trial for training
Returns
-------
gen : generator object
the generat... | 3.37775 | 3.201314 | 1.055114 |
split = num_trials // 2
a = list(range(0, split))
b = list(range(split, num_trials))
yield a, b
yield b, a | def splitset(num_trials, skipstep=None) | Split-set cross validation
Use half the trials for training, and the other half for testing. Then
repeat the other way round.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
unused
Returns
-------
gen : generator object
the gene... | 3.630341 | 3.835025 | 0.946628 |
self.data_ = atleast_3d(data)
self.cl_ = np.asarray(cl if cl is not None else [None]*self.data_.shape[0])
self.time_offset_ = time_offset
self.var_model_ = None
self.var_cov_ = None
self.connectivity_ = None
self.trial_mask_ = np.ones(self.cl_.size, dtyp... | def set_data(self, data, cl=None, time_offset=0) | Assign data to the workspace.
This function assigns a new data set to the workspace. Doing so invalidates currently fitted VAR models,
connectivity estimates, and activations.
Parameters
----------
data : array-like, shape = [n_trials, n_channels, n_samples] or [n_channels, n_s... | 3.997325 | 3.542642 | 1.128346 |
mask = np.zeros(self.cl_.size, dtype=bool)
for l in labels:
mask = np.logical_or(mask, self.cl_ == l)
self.trial_mask_ = mask
return self | def set_used_labels(self, labels) | Specify which trials to use in subsequent analysis steps.
This function masks trials based on their class labels.
Parameters
----------
labels : list of class labels
Marks all trials that have a label that is in the `labels` list for further processing.
Returns
... | 4.262944 | 4.042011 | 1.054659 |
if self.data_ is None:
raise RuntimeError("MVARICA requires data to be set")
result = mvarica(x=self.data_[self.trial_mask_, :, :],
cl=self.cl_[self.trial_mask_], var=self.var_,
reducedim=self.reducedim_, backend=self.backend_,
... | def do_mvarica(self, varfit='ensemble', random_state=None) | Perform MVARICA
Perform MVARICA source decomposition and VAR model fitting.
Parameters
----------
varfit : string
Determines how to calculate the residuals for source decomposition.
'ensemble' (default) fits one model to the whole data set,
'class' f... | 4.482447 | 4.829106 | 0.928215 |
if self.data_ is None:
raise RuntimeError("CSPVARICA requires data to be set")
try:
sorted(self.cl_)
for c in self.cl_:
assert(c is not None)
except (TypeError, AssertionError):
raise RuntimeError("CSPVARICA requires ordera... | def do_cspvarica(self, varfit='ensemble', random_state=None) | Perform CSPVARICA
Perform CSPVARICA source decomposition and VAR model fitting.
Parameters
----------
varfit : string
Determines how to calculate the residuals for source decomposition.
'ensemble' (default) fits one model to the whole data set,
'clas... | 4.742218 | 4.859331 | 0.9759 |
if self.data_ is None:
raise RuntimeError("ICA requires data to be set")
result = plainica(x=self.data_[self.trial_mask_, :, :], reducedim=self.reducedim_, backend=self.backend_, random_state=random_state)
self.mixing_ = result.mixing
self.unmixing_ = result.unmixing... | def do_ica(self, random_state=None) | Perform ICA
Perform plain ICA source decomposition.
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain data. | 4.821514 | 4.997585 | 0.964769 |
if self.unmixing_ is None or self.mixing_ is None:
raise RuntimeError("No sources available (run do_mvarica first)")
self.mixing_ = np.delete(self.mixing_, sources, 0)
self.unmixing_ = np.delete(self.unmixing_, sources, 1)
if self.activations_ is not None:
... | def remove_sources(self, sources) | Remove sources from the decomposition.
This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and
connectivity estimates.
Parameters
----------
sources : {slice, int, array of ints}
Indices of components to remove.
... | 3.548695 | 3.315871 | 1.070215 |
if self.unmixing_ is None or self.mixing_ is None:
raise RuntimeError("No sources available (run do_mvarica first)")
n_sources = self.mixing_.shape[0]
self.remove_sources(np.setdiff1d(np.arange(n_sources), np.array(keep)))
return self | def keep_sources(self, keep) | Keep only the specified sources in the decomposition. | 5.933728 | 5.194071 | 1.142404 |
if self.activations_ is None:
raise RuntimeError("VAR fitting requires source activations (run do_mvarica first)")
self.var_.fit(data=self.activations_[self.trial_mask_, :, :])
self.connectivity_ = Connectivity(self.var_.coef, self.var_.rescov, self.nfft_)
return sel... | def fit_var(self) | Fit a VAR model to the source activations.
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source activations. | 12.903 | 11.309984 | 1.14085 |
if self.activations_ is None:
raise RuntimeError("VAR fitting requires source activations (run do_mvarica first)")
self.var_.optimize(self.activations_[self.trial_mask_, :, :])
return self | def optimize_var(self) | Optimize the VAR model's hyperparameters (such as regularization).
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source activations. | 19.356541 | 13.977059 | 1.384879 |
if self.connectivity_ is None:
raise RuntimeError("Connectivity requires a VAR model (run do_mvarica or fit_var first)")
cm = getattr(self.connectivity_, measure_name)()
cm = np.abs(cm) if np.any(np.iscomplex(cm)) else cm
if plot is None or plot:
fig =... | def get_connectivity(self, measure_name, plot=False) | Calculate spectral connectivity measure.
Parameters
----------
measure_name : str
Name of the connectivity measure to calculate. See :class:`Connectivity` for supported measures.
plot : {False, None, Figure object}, optional
Whether and where to plot the connecti... | 5.17095 | 4.865818 | 1.062709 |
cs = surrogate_connectivity(measure_name, self.activations_[self.trial_mask_, :, :],
self.var_, self.nfft_, repeats, random_state=random_state)
if plot is None or plot:
fig = plot
if self.plot_diagonal == 'fill':
diago... | def get_surrogate_connectivity(self, measure_name, repeats=100, plot=False, random_state=None) | Calculate spectral connectivity measure under the assumption of no actual connectivity.
Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity
distribution if there was no causal structure in the data.
Parameters
----------
measu... | 5.03304 | 5.467741 | 0.920497 |
if num_samples is None:
num_samples = np.sum(self.trial_mask_)
cb = bootstrap_connectivity(measure_names, self.activations_[self.trial_mask_, :, :],
self.var_, self.nfft_, repeats, num_samples, random_state=random_state)
if plot is None ... | def get_bootstrap_connectivity(self, measure_names, repeats=100, num_samples=None, plot=False, random_state=None) | Calculate bootstrap estimates of spectral connectivity measures.
Bootstrapping is performed on trial level.
Parameters
----------
measure_names : {str, list of str}
Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures.
... | 3.40519 | 3.601665 | 0.945449 |
if self.unmixing_ is None and self.mixing_ is None:
raise RuntimeError("No sources available (run do_mvarica first)")
self._prepare_plots(True, True)
self.plotting.plot_sources(self.topo_, self.mixmaps_, self.unmixmaps_, common_scale) | def plot_source_topos(self, common_scale=None) | Plot topography of the Source decomposition.
Parameters
----------
common_scale : float, optional
If set to None, each topoplot's color axis is scaled individually. Otherwise specifies the percentile
(1-99) of values in all plot. This value is taken as the maximum color ... | 11.102979 | 12.220854 | 0.908527 |
self._prepare_plots(True, False)
if self.plot_outside_topo:
fig = self.plotting.plot_connectivity_topos('outside', self.topo_, self.mixmaps_, fig)
elif self.plot_diagonal == 'topo':
fig = self.plotting.plot_connectivity_topos('diagonal', self.topo_, self.mixmaps_... | def plot_connectivity_topos(self, fig=None) | Plot scalp projections of the sources.
This function only plots the topos. Use in combination with connectivity plotting.
Parameters
----------
fig : {None, Figure object}, optional
Where to plot the topos. f set to **None**, a new figure is created. Otherwise plot into the... | 5.764449 | 6.612945 | 0.871692 |
cb = self.get_surrogate_connectivity(measure_name, repeats)
self._prepare_plots(True, False)
cu = np.percentile(cb, 95, axis=0)
fig = self.plotting.plot_connectivity_spectrum([cu], self.fs_, freq_range=self.plot_f_range, fig=fig)
return fig | def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None) | Plot spectral connectivity measure under the assumption of no actual connectivity.
Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity
distribution if there was no causal structure in the data.
Parameters
----------
measure_na... | 6.492731 | 8.531453 | 0.761035 |
if n_jobs:
try:
from joblib import Parallel, delayed
except ImportError:
try:
from sklearn.externals.joblib import Parallel, delayed
except ImportError:
n_jobs = None
if not n_jobs:
if verbose:
print('r... | def parallel_loop(func, n_jobs=1, verbose=1) | run loops in parallel, if joblib is available.
Parameters
----------
func : function
function to be executed in parallel
n_jobs : int | None
Number of jobs. If set to None, do not attempt to use joblib.
verbose : int
verbosity level
Notes
-----
Execution of the ... | 2.492114 | 2.832131 | 0.879943 |
cast_Invalid = lambda e: Invalid(
u"{message}, expected {expected}".format(
message=e.message,
expected=e.expected)
if e.expected != u'-none-' else e.message,
e.path,
six.text_type(e))
@wraps(func)
def wrapper(*args, **kwargs):
try:
... | def _convert_errors(func) | Decorator to convert throws errors to Voluptuous format. | 4.492773 | 4.127944 | 1.08838 |
if self.name is None:
self.name = name
if self.key_schema is None:
self.key_schema = key_schema
if self.value_schema is None:
self.value_schema = value_schema
if as_mapping_key:
self.as_mapping_key = True
return self | def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None) | When CompiledSchema compiles this marker, it sets informational values onto it.
Note that arguments may be provided in two incomplete sets,
e.g. (name, key_schema, None) and then (None, None, value_schema).
Thus, all assignments must be handled individually.
It is possible that a marke... | 1.67171 | 1.89652 | 0.881462 |
try:
from rainbow_logging_handler import RainbowLoggingHandler
import sys
# setup `RainbowLoggingHandler`
logger = logging.root
# same as default
if format == "short":
fmt = "%(message)s "
else:
fmt = "[%(asctime)s] %(name)s %(func... | def colorlogs(format="short") | Append a rainbow logging handler and a formatter to the root logger | 3.983902 | 3.873658 | 1.02846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.