code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def watermark(self, image, options):
watermark_img = options.get("watermark", settings.THUMBNAIL_WATERMARK)
if not watermark_img:
raise AttributeError("No THUMBNAIL_WATERMARK defined or set on tag.")
watermark_path = find(watermark_img)
if not watermark_path:
... | Wrapper for ``_watermark``
Takes care of all the options handling. |
def _get_new_watermark_size(self, size, mark_default_size):
if hasattr(size, "__getitem__"):
# a tuple or any iterable already
mark_size = size
elif isinstance(size, float):
mark_size = map(lambda coord: int(coord * size), mark_default_size)
else:
... | New size can be passed as a pair of valuer (tuple) or
a fsloat (persentage case) |
def make_funcs(dataset, setdir, store):
return {
'cat': lambda *lists: [x for lst in lists for x in lst],
'comments': lambda: None,
'detail_route': detail_route,
'format': lambda fmt, *args: fmt.format(*args),
'get': partial(getnode, dataset, setdir, store),
'joi... | Functions available for listing columns and filters. |
def make_summary_funcs(rows, ids):
return {
'len': len,
'list': lambda *x: filter(None, list(x)),
'max': max,
'min': min,
'rows': partial(summary_rows, rows, ids),
'sum': sum,
'trace': print_trace
} | Functions available for listing summary fields. |
def cached_property(func):
@functools.wraps(func)
def cached_func(self):
cacheattr = '_{}'.format(func.func_name)
try:
return getattr(self, cacheattr)
except AttributeError:
value = func(self)
setattr(self, cacheattr, value)
return val... | Create read-only property that caches its function's value |
def create_stream(name, **header):
assert isinstance(name, basestring), name
return CreateStream(parent=None, name=name, group=False, header=header) | Create a stream for publishing messages.
All keyword arguments will be used to form the header. |
def pull(handle, enumerate=False):
assert isinstance(handle, Handle), handle
return Pull(handle, enumerate) | Pulls next message for handle.
Args:
handle: A :class:`.stream.Handle` or GroupHandle.
enumerate (bool): boolean to indicate whether a tuple ``(idx, msg)``
should be returned, not unlike Python's enumerate().
Returns:
A :class:`Pull` task to be yielded. Marv will send the
... |
def add_endpoint(self, ep):
assert ep.name not in self.endpoints, ep
self.endpoints[ep.name] = ep | endpoints and groups are all the same (for now) |
def parse_geometry(geometry, ratio=None):
if "%" not in geometry:
# fall back to old parser
return xy_geometry_parser(geometry, ratio)
# parse with float so geometry strings like "42.11%" are possible
return float(geometry.strip("%")) / 100.0 | Enhanced parse_geometry parser with percentage support. |
def image(cam):
# Set output stream title and pull first message
yield marv.set_header(title=cam.topic)
msg = yield marv.pull(cam)
if msg is None:
return
# Deserialize raw ros message
pytype = get_message_type(cam)
rosmsg = pytype()
rosmsg.deserialize(msg.data)
# Write... | Extract first image of input stream to jpg file.
Args:
cam: Input stream of raw rosbag messages.
Returns:
File instance for first image of input stream. |
def image_section(image, title):
# pull first image
img = yield marv.pull(image)
if img is None:
return
# create image widget and section containing it
widget = {'title': image.title, 'image': {'src': img.relpath}}
section = {'title': title, 'widgets': [widget]}
yield marv.push... | Create detail section with one image.
Args:
title (str): Title to be displayed for detail section.
image: marv image file.
Returns
One detail section. |
def images(cam):
# Set output stream title and pull first message
yield marv.set_header(title=cam.topic)
# Fetch and process first 20 image messages
name_template = '%s-{}.jpg' % cam.topic.replace('/', ':')[1:]
while True:
idx, msg = yield marv.pull(cam, enumerate=True)
if msg ... | Extract images from input stream to jpg files.
Args:
cam: Input stream of raw rosbag messages.
Returns:
File instances for images of input stream. |
def gallery_section(images, title):
# pull all images
imgs = []
while True:
img = yield marv.pull(images)
if img is None:
break
imgs.append({'src': img.relpath})
if not imgs:
return
# create gallery widget and section containing it
widget = {'tit... | Create detail section with gallery.
Args:
title (str): Title to be displayed for detail section.
images: stream of marv image files
Returns
One detail section. |
def filesizes(images):
# Pull each image and push its filesize
while True:
img = yield marv.pull(images)
if img is None:
break
yield marv.push(img.size) | Stat filesize of files.
Args:
images: stream of marv image files
Returns:
Stream of filesizes |
def input(name, default=None, foreach=None):
assert default is None or foreach is None
value = foreach if foreach is not None else default
value = StreamSpec(value) if isinstance(value, Node) else value
foreach = foreach is not None
spec = InputSpec(name, value, foreach)
def deco(func):
... | Decorator to declare input for a node.
Plain inputs, that is plain python objects, are directly passed to
the node. Whereas streams generated by other nodes are requested
and once the handles of all input streams are available the node
is instantiated.
Args:
name (str): Name of the node fu... |
def node(schema=None, header=None, group=None, version=None):
def deco(func):
"""Turn function into node with given arguments.
:func:`node`(schema={!r}, header={!r}, group={!r})
""".format(schema, header, group)
if isinstance(func, Node):
raise TypeError('Attempted... | Turn function into node.
Args:
schema: capnproto schema describing the output messages format
header: This parameter is currently not supported and only for
internal usage.
group (bool): A boolean indicating whether the default stream
of the node is a group, meaning ... |
def message(message, name=None):
def decorator(func):
wf = update_wrapper(Msg(func, message), func)
if name:
wf.name = name
return wf
return decorator | Convenience decorator that applies [`Msg()`](#msg) to a callable.
```python
from good import Schema, message
@message(u'Need a number')
def intify(v):
return int(v)
```
:param message: Error message to use instead
:type message: unicode
:param name: Override schema name as wel... |
def name(name, validator=None):
# Decorator mode
if validator is None:
def decorator(f):
f.name = name
return f
return decorator
# Direct mode
validator.name = name
return validator | Set a name on a validator callable.
Useful for user-friendly reporting when using lambdas to populate the [`Invalid.expected`](#invalid) field:
```python
from good import Schema, name
Schema(lambda x: int(x))('a')
#-> Invalid: invalid literal for int(): expected <lambda>(), got
Schema(name('i... |
def truth(message, expected=None):
def decorator(func):
return update_wrapper(Check(func, message, expected), func)
return decorator | Convenience decorator that applies [`Check`](#check) to a callable.
```python
from good import truth
@truth(u'Must be an existing directory')
def isDir(v):
return os.path.isdir(v)
```
:param message: Validation error message
:type message: unicode
:param expected: Expected val... |
def stringmethod(func):
method_name = func()
@wraps(func)
def factory():
def validator(v):
if not isinstance(v, six.string_types):
raise Invalid(_(u'Not a string'), get_type_name(six.text_type), get_type_name(type(v)))
return getattr(v, method_name)()
... | Validator factory which call a single method on the string. |
def parse_z(cls, offset):
assert len(offset) == 5, 'Invalid offset string format, must be "+HHMM"'
return timedelta(hours=int(offset[:3]), minutes=int(offset[0] + offset[3:])) | Parse %z offset into `timedelta` |
def format_z(cls, offset):
sec = offset.total_seconds()
return '{s}{h:02d}{m:02d}'.format(s='-' if sec<0 else '+', h=abs(int(sec/3600)), m=int((sec%3600)/60)) | Format `timedelta` into %z |
def preprocess(self, dt):
# Process
try: # this block should not raise errors, and if it does -- they should not be wrapped with `Invalid`
# localize
if self.localize and dt.tzinfo is None:
dt = self.localize(dt)
# astimezone
if ... | Preprocess the `dt` with `localize()` and `astz()` |
def strptime(cls, value, format):
# Simplest case: direct parsing
if cls.python_supports_z or '%z' not in format:
return datetime.strptime(value, format)
else:
# %z emulation case
assert format[-2:] == '%z', 'For performance, %z is only supported at t... | Parse a datetime string using the provided format.
This also emulates `%z` support on Python 2.
:param value: Datetime string
:type value: str
:param format: Format to use for parsing
:type format: str
:rtype: datetime
:raises ValueError: Invalid format
... |
def generate_random_type(valid):
type = choice(['int', 'str'])
r = lambda: randrange(-1000000000, 1000000000)
if type == 'int':
return int, (r() if valid else str(r()) for i in itertools.count())
elif type == 'str':
return str, (str(r()) if valid else r() for i in itertools.count... | Generate a random type and samples for it.
:param valid: Generate valid samples?
:type valid: bool
:return: type, sample-generator
:rtype: type, generator |
def generate_random_schema(valid):
schema_type = choice(['literal', 'type'])
if schema_type == 'literal':
type, gen = generate_random_type(valid)
value = next(gen)
return value, (value if valid else None for i in itertools.count())
elif schema_type == 'type':
return gen... | Generate a random plain schema, and a sample generation function.
:param valid: Generate valid samples?
:type valid: bool
:returns: schema, sample-generator
:rtype: *, generator |
def generate_dict_schema(size, valid):
schema = {}
generator_items = []
# Generate schema
for i in range(0, size):
while True:
key_schema, key_generator = generate_random_schema(valid)
if key_schema not in schema:
break
value_schema, val... | Generate a schema dict of size `size` using library `lib`.
In addition, it returns samples generator
:param size: Schema size
:type size: int
:param samples: The number of samples to generate
:type samples: int
:param valid: Generate valid samples?
:type valid: bool
:returns |
def ignore_patterns(*patterns):
import fnmatch
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns | Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files |
def has_envconfig() -> bool:
if (os.getenv("VAULT_TOKEN", None) or
(os.getenv("VAULT_APPID", None) and os.getenv("VAULT_USERID", None)) or
(os.getenv("VAULT_SSLCERT", None) and os.getenv("VAULT_SSLKEY", None)) or
(os.getenv("VAULT_ROLEID", None) and os.ge... | (static)
:return: True if enough information is available in the environment to authenticate to Vault |
def fromenv() -> 'VaultAuth12Factor':
i = None # type: VaultAuth12Factor
if os.getenv("VAULT_TOKEN", None):
i = VaultAuth12Factor.token(os.getenv("VAULT_TOKEN"))
elif os.getenv("VAULT_APPID", None) and os.getenv("VAULT_USERID", None):
i = VaultAuth12Factor.app_i... | :return: Load configuration from the environment and return a configured instance |
def topoplot(values, locations, axes=None, offset=(0, 0), plot_locations=True,
plot_head=True, **kwargs):
topo = Topoplot(**kwargs)
topo.set_locations(locations)
topo.set_values(values)
topo.create_map()
topo.plot_map(axes=axes, offset=offset)
if plot_locations:
topo.pl... | Wrapper function for :class:`Topoplot. |
def _construct_var_eqns(data, p, delta=None):
t, m, l = np.shape(data)
n = (l - p) * t # number of linear relations
rows = n if delta is None else n + m * p
# Construct matrix x (predictor variables)
x = np.zeros((rows, m * p))
for i in range(m):
fo... | Construct VAR equation system (optionally with RLS constraint). |
def _calc_q_statistic(x, h, nt):
t, m, n = x.shape
# covariance matrix of x
c0 = acm(x, 0)
# LU factorization of covariance matrix
c0f = sp.linalg.lu_factor(c0, overwrite_a=False, check_finite=True)
q = np.zeros((3, h + 1))
for l in range(1, h + 1):
cl = acm(x, l)
# ... | Calculate Portmanteau statistics up to a lag of h. |
def _calc_q_h0(n, x, h, nt, n_jobs=1, verbose=0, random_state=None):
rng = check_random_state(random_state)
par, func = parallel_loop(_calc_q_statistic, n_jobs, verbose)
q = par(func(rng.permutation(x.T).T, h, nt) for _ in range(n))
return np.array(q) | Calculate q under the null hypothesis of whiteness. |
def copy(self):
other = self.__class__(self.p)
other.coef = self.coef.copy()
other.residuals = self.residuals.copy()
other.rescov = self.rescov.copy()
return other | Create a copy of the VAR model. |
def from_yw(self, acms):
if len(acms) != self.p + 1:
raise ValueError("Number of autocorrelation matrices ({}) does not"
" match model order ({}) + 1.".format(len(acms),
self.p))
n_chann... | Determine VAR model from autocorrelation matrices by solving the
Yule-Walker equations.
Parameters
----------
acms : array, shape (n_lags, n_channels, n_channels)
acms[l] contains the autocorrelation matrix at lag l. The highest
lag must equal the model order.
... |
def simulate(self, l, noisefunc=None, random_state=None):
m, n = np.shape(self.coef)
p = n // m
try:
l, t = l
except TypeError:
t = 1
if noisefunc is None:
rng = check_random_state(random_state)
noisefunc = lambda: rng.no... | Simulate vector autoregressive (VAR) model.
This function generates data from the VAR model.
Parameters
----------
l : int or [int, int]
Number of samples to generate. Can be a tuple or list, where l[0]
is the number of samples and l[1] is the number of trials.
... |
def predict(self, data):
data = atleast_3d(data)
t, m, l = data.shape
p = int(np.shape(self.coef)[1] / m)
y = np.zeros(data.shape)
if t > l - p: # which takes less loop iterations
for k in range(1, p + 1):
bp = self.coef[:, (k - 1)::p]
... | Predict samples on actual data.
The result of this function is used for calculating the residuals.
Parameters
----------
data : array, shape (trials, channels, samples) or (channels, samples)
Epoched or continuous data set.
Returns
-------
predicted... |
def is_stable(self):
m, mp = self.coef.shape
p = mp // m
assert(mp == m * p) # TODO: replace with raise?
top_block = []
for i in range(p):
top_block.append(self.coef[:, i::p])
top_block = np.hstack(top_block)
im = np.eye(m)
eye_bloc... | Test if VAR model is stable.
This function tests stability of the VAR model as described in [1]_.
Returns
-------
out : bool
True if the model is stable.
References
----------
.. [1] H. Lütkepohl, "New Introduction to Multiple Time Series
... |
def fetch(dataset="mi", datadir=datadir):
if dataset not in datasets:
raise ValueError("Example data '{}' not available.".format(dataset))
else:
files = datasets[dataset]["files"]
url = datasets[dataset]["url"]
md5 = datasets[dataset]["md5"]
if not isdir(datadir):
... | Fetch example dataset.
If the requested dataset is not found in the location specified by
`datadir`, the function attempts to download it.
Parameters
----------
dataset : str
Which dataset to load. Currently only 'mi' is supported.
datadir : str
Path to the storage location of ... |
def supports_undefined(self):
# Test
try:
yes = self(const.UNDEFINED) is not const.UNDEFINED
except (Invalid, SchemaError):
yes = False
# Remember (lame @cached_property)
self.__dict__['supports_undefined'] = yes
return yes | Test whether this schema supports Undefined.
A Schema that supports `Undefined`, when given `Undefined`, should return some value (other than `Undefined`)
without raising errors.
This is designed to support a very special case like that:
```python
Schema(Default(0)).supports_u... |
def get_schema_type(cls, schema):
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):
... | Get schema type for the argument
:param schema: Schema to analyze
:return: COMPILED_TYPE constant
:rtype: str|None |
def priority(self):
# 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] | Get priority for this Schema.
Used to sort mapping keys
:rtype: int |
def sort_schemas(cls, schemas_list):
return sorted(schemas_list,
key=lambda x: (
# Top-level priority:
# priority of the schema itself
x.priority,
# Second-level priority (for m... | 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] |
def sub_compile(self, schema, path=None, matcher=False):
return type(self)(
schema,
self.path + (path or []),
None,
None,
matcher
) | 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 |
def Invalid(self, message, expected):
def InvalidPartial(provided, path=None, **info):
""" Create an Invalid exception
:type provided: unicode
:type path: list|None
:rtype: Invalid
"""
return Invalid(
message,
... | 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 |
def get_schema_compiler(self, schema):
# 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:... | Get compiler method for the provided schema
:param schema: Schema to analyze
:return: Callable compiled
:rtype: callable|None |
def compile_schema(self, schema):
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) | Compile the current schema into a callable validator
:return: Callable validator
:rtype: callable
:raises SchemaError: Schema compilation error |
def _compile_literal(self, schema):
# 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))
... | Compile literal schema: type and value matching |
def _compile_type(self, schema):
# 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 basestri... | Compile type schema: plain type matching |
def _compile_schema(self, schema):
assert self.matcher == schema.matcher
self.name = schema.name
self.compiled_type = schema.compiled_type
return schema.compiled | Compile another schema |
def _compile_callable(self, schema):
# 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(... | Compile callable: wrap exceptions with correct paths |
def _compile_marker(self, schema):
# 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(Iden... | Compile marker: sub-schema with special type |
def pca_svd(x):
w, s, _ = np.linalg.svd(x, full_matrices=False)
return w, s ** 2 | 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... |
def pca_eig(x):
s, w = np.linalg.eigh(x.dot(x.T))
return w, s | 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,... |
def loadmat(filename):
data = sploadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_keys(data) | 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 |
def _check_keys(dictionary):
for key in dictionary:
if isinstance(dictionary[key], matlab.mio5_params.mat_struct):
dictionary[key] = _todict(dictionary[key])
return dictionary | checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries |
def _todict(matobj):
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... | a recursive function which constructs from matobjects nested dictionaries |
def plainica(x, reducedim=0.99, backend=None, random_state=None):
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:
... | 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... |
def _msge_with_gradient_underdetermined(data, delta, xvschema, skipstep, p):
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_va... | Calculate mean squared generalization error and its gradient for
underdetermined equation system. |
def _msge_with_gradient_overdetermined(data, delta, xvschema, skipstep, p):
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... | Calculate mean squared generalization error and its gradient for
overdetermined equation system. |
def _get_msge_with_gradient_func(shape, p):
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 | Select which function to use for MSGE calculation (over- or
underdetermined). |
def _get_msge_with_gradient(data, delta, xvschema, skipstep, p):
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:... | Calculate mean squared generalization error and its gradient,
automatically selecting the best function. |
def fit(self, data):
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)
... | 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... |
def optimize_order(self, data, min_p=1, max_p=None):
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,
... | 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 :... |
def fromvector(cls, v):
w = v.normalized()
return cls(w.x, w.y, w.z) | Initialize from euclidean vector |
def list(self):
return [self._pos3d.x, self._pos3d.y, self._pos3d.z] | position in 3d space |
def distance(self, other):
return math.acos(self._pos3d.dot(other.vector)) | Distance to another point on the sphere |
def distances(self, points):
return [math.acos(self._pos3d.dot(p.vector)) for p in points] | Distance to other points on the sphere |
def fromiterable(cls, itr):
x, y, z = itr
return cls(x, y, z) | Initialize from iterable |
def fromvector(cls, v):
return cls(v.x, v.y, v.z) | Copy another vector |
def norm2(self):
return self.x * self.x + self.y * self.y + self.z * self.z | Squared norm of the vector |
def rotate(self, l, u):
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)) * se... | rotate l radians around axis u |
def connectivity(measure_names, b, c=None, nfft=512):
con = Connectivity(b, c, nfft)
try:
return getattr(con, measure_names)()
except TypeError:
return dict((m, getattr(con, m)()) for m in measure_names) | 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... |
def Cinv(self):
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]) | Inverse of the noise covariance. |
def A(self):
return fft(np.dstack([np.eye(self.m), -self.b]),
self.nfft * 2 - 1)[:, :, :self.nfft] | Spectral VAR coefficients.
.. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)}
\mathrm{e}^{-2\pi f} |
def S(self):
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.shap... | Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) |
def G(self):
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(),... | Inverse cross-spectral density.
.. math:: \mathbf{G}(f) = \mathbf{A}(f) \mathbf{C}^{-1} \mathbf{A}'(f) |
def COH(self):
S = self.S()
# TODO: can we do that more efficiently?
return S / np.sqrt(np.einsum('ii..., jj... ->ij...', S, S.conj())) | 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... |
def pCOH(self):
G = self.G()
# TODO: can we do that more efficiently?
return G / np.sqrt(np.einsum('ii..., jj... ->ij...', G, G)) | 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... |
def PDC(self):
A = self.A()
return np.abs(A / np.sqrt(np.sum(A.conj() * A, axis=0, keepdims=True))) | 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... |
def ffPDC(self):
A = self.A()
return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2),
keepdims=True))) | Full frequency partial directed coherence.
.. math:: \mathrm{ffPDC}_{ij}(f) =
\\frac{A_{ij}(f)}{\sqrt{\sum_f A_{:j}'(f) A_{:j}(f)}} |
def PDCF(self):
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))) | 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... |
def GPDC(self):
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) | 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:... |
def DTF(self):
H = self.H()
return np.abs(H / np.sqrt(np.sum(H * H.conj(), axis=1, keepdims=True))) | 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... |
def ffDTF(self):
H = self.H()
return np.abs(H * self.nfft / np.sqrt(np.sum(H * H.conj(), axis=(1, 2),
keepdims=True))) | 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... |
def GDTF(self):
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) | 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: ... |
def enrich(self, expected=None, provided=None, path=None, validator=None):
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.prov... | 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... |
def flatten(cls, errors):
ers = []
for e in errors:
if isinstance(e, MultipleInvalid):
ers.extend(cls.flatten(e.errors))
else:
ers.append(e)
return ers | Unwind `MultipleErrors` to have a plain list of `Invalid`
:type errors: list[Invalid|MultipleInvalid]
:rtype: list[Invalid] |
def _fit_ellipsoid_full(locations):
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 | identify all 6 ellipsoid parametes (center, radii) |
def _fit_ellipsoid_partial(locations, cy):
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.shap... | identify only 5 ellipsoid parameters (y-center determined by e.g. Cz) |
def _project_on_ellipsoid(c, r, locations):
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) ... | displace locations to the nearest point on ellipsoid surface |
def cut_segments(x2d, tr, start, stop):
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... | 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... |
def cat_trials(x3d):
x3d = atleast_3d(x3d)
t = x3d.shape[0]
return np.concatenate(np.split(x3d, t, 0), axis=2).squeeze(0) | 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... |
def dot_special(x2d, x3d):
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])]) | 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 ... |
def randomize_phase(data, random_state=None):
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]) | 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... |
def acm(x, l):
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:]
... | 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... |
def surrogate_connectivity(measure_names, data, var, nfft=512, repeats=100,
n_jobs=1, verbose=0, random_state=None):
par, func = parallel_loop(_calc_surrogate, n_jobs=n_jobs, verbose=verbose)
output = par(func(randomize_phase(data, random_state=random_state), var,
... | 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... |
def significance_fdr(p, alpha):
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(... | 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... |
def register_type_name(t, name):
assert isinstance(t, type)
assert isinstance(name, unicode)
__type_names[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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.