id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
7,800
|
kwikteam/phy
|
phy/plot/panzoom.py
|
PanZoom.zoom_delta
|
def zoom_delta(self, d, p=(0., 0.), c=1.):
"""Zoom the view by a given amount."""
dx, dy = d
x0, y0 = p
pan_x, pan_y = self._pan
zoom_x, zoom_y = self._zoom
zoom_x_new, zoom_y_new = (zoom_x * math.exp(c * self._zoom_coeff * dx),
zoom_y * math.exp(c * self._zoom_coeff * dy))
zoom_x_new = max(min(zoom_x_new, self._zmax), self._zmin)
zoom_y_new = max(min(zoom_y_new, self._zmax), self._zmin)
self.zoom = zoom_x_new, zoom_y_new
if self._zoom_to_pointer:
zoom_x, zoom_y = self._zoom_aspect((zoom_x,
zoom_y))
zoom_x_new, zoom_y_new = self._zoom_aspect((zoom_x_new,
zoom_y_new))
self.pan = (pan_x - x0 * (1. / zoom_x - 1. / zoom_x_new),
pan_y - y0 * (1. / zoom_y - 1. / zoom_y_new))
self.update()
|
python
|
def zoom_delta(self, d, p=(0., 0.), c=1.):
"""Zoom the view by a given amount."""
dx, dy = d
x0, y0 = p
pan_x, pan_y = self._pan
zoom_x, zoom_y = self._zoom
zoom_x_new, zoom_y_new = (zoom_x * math.exp(c * self._zoom_coeff * dx),
zoom_y * math.exp(c * self._zoom_coeff * dy))
zoom_x_new = max(min(zoom_x_new, self._zmax), self._zmin)
zoom_y_new = max(min(zoom_y_new, self._zmax), self._zmin)
self.zoom = zoom_x_new, zoom_y_new
if self._zoom_to_pointer:
zoom_x, zoom_y = self._zoom_aspect((zoom_x,
zoom_y))
zoom_x_new, zoom_y_new = self._zoom_aspect((zoom_x_new,
zoom_y_new))
self.pan = (pan_x - x0 * (1. / zoom_x - 1. / zoom_x_new),
pan_y - y0 * (1. / zoom_y - 1. / zoom_y_new))
self.update()
|
[
"def",
"zoom_delta",
"(",
"self",
",",
"d",
",",
"p",
"=",
"(",
"0.",
",",
"0.",
")",
",",
"c",
"=",
"1.",
")",
":",
"dx",
",",
"dy",
"=",
"d",
"x0",
",",
"y0",
"=",
"p",
"pan_x",
",",
"pan_y",
"=",
"self",
".",
"_pan",
"zoom_x",
",",
"zoom_y",
"=",
"self",
".",
"_zoom",
"zoom_x_new",
",",
"zoom_y_new",
"=",
"(",
"zoom_x",
"*",
"math",
".",
"exp",
"(",
"c",
"*",
"self",
".",
"_zoom_coeff",
"*",
"dx",
")",
",",
"zoom_y",
"*",
"math",
".",
"exp",
"(",
"c",
"*",
"self",
".",
"_zoom_coeff",
"*",
"dy",
")",
")",
"zoom_x_new",
"=",
"max",
"(",
"min",
"(",
"zoom_x_new",
",",
"self",
".",
"_zmax",
")",
",",
"self",
".",
"_zmin",
")",
"zoom_y_new",
"=",
"max",
"(",
"min",
"(",
"zoom_y_new",
",",
"self",
".",
"_zmax",
")",
",",
"self",
".",
"_zmin",
")",
"self",
".",
"zoom",
"=",
"zoom_x_new",
",",
"zoom_y_new",
"if",
"self",
".",
"_zoom_to_pointer",
":",
"zoom_x",
",",
"zoom_y",
"=",
"self",
".",
"_zoom_aspect",
"(",
"(",
"zoom_x",
",",
"zoom_y",
")",
")",
"zoom_x_new",
",",
"zoom_y_new",
"=",
"self",
".",
"_zoom_aspect",
"(",
"(",
"zoom_x_new",
",",
"zoom_y_new",
")",
")",
"self",
".",
"pan",
"=",
"(",
"pan_x",
"-",
"x0",
"*",
"(",
"1.",
"/",
"zoom_x",
"-",
"1.",
"/",
"zoom_x_new",
")",
",",
"pan_y",
"-",
"y0",
"*",
"(",
"1.",
"/",
"zoom_y",
"-",
"1.",
"/",
"zoom_y_new",
")",
")",
"self",
".",
"update",
"(",
")"
] |
Zoom the view by a given amount.
|
[
"Zoom",
"the",
"view",
"by",
"a",
"given",
"amount",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L281-L305
|
7,801
|
kwikteam/phy
|
phy/plot/panzoom.py
|
PanZoom.set_range
|
def set_range(self, bounds, keep_aspect=False):
"""Zoom to fit a box."""
# a * (v0 + t) = -1
# a * (v1 + t) = +1
# =>
# a * (v1 - v0) = 2
bounds = np.asarray(bounds, dtype=np.float64)
v0 = bounds[:2]
v1 = bounds[2:]
pan = -.5 * (v0 + v1)
zoom = 2. / (v1 - v0)
if keep_aspect:
zoom = zoom.min() * np.ones(2)
self.set_pan_zoom(pan=pan, zoom=zoom)
|
python
|
def set_range(self, bounds, keep_aspect=False):
"""Zoom to fit a box."""
# a * (v0 + t) = -1
# a * (v1 + t) = +1
# =>
# a * (v1 - v0) = 2
bounds = np.asarray(bounds, dtype=np.float64)
v0 = bounds[:2]
v1 = bounds[2:]
pan = -.5 * (v0 + v1)
zoom = 2. / (v1 - v0)
if keep_aspect:
zoom = zoom.min() * np.ones(2)
self.set_pan_zoom(pan=pan, zoom=zoom)
|
[
"def",
"set_range",
"(",
"self",
",",
"bounds",
",",
"keep_aspect",
"=",
"False",
")",
":",
"# a * (v0 + t) = -1",
"# a * (v1 + t) = +1",
"# =>",
"# a * (v1 - v0) = 2",
"bounds",
"=",
"np",
".",
"asarray",
"(",
"bounds",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"v0",
"=",
"bounds",
"[",
":",
"2",
"]",
"v1",
"=",
"bounds",
"[",
"2",
":",
"]",
"pan",
"=",
"-",
".5",
"*",
"(",
"v0",
"+",
"v1",
")",
"zoom",
"=",
"2.",
"/",
"(",
"v1",
"-",
"v0",
")",
"if",
"keep_aspect",
":",
"zoom",
"=",
"zoom",
".",
"min",
"(",
")",
"*",
"np",
".",
"ones",
"(",
"2",
")",
"self",
".",
"set_pan_zoom",
"(",
"pan",
"=",
"pan",
",",
"zoom",
"=",
"zoom",
")"
] |
Zoom to fit a box.
|
[
"Zoom",
"to",
"fit",
"a",
"box",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L317-L330
|
7,802
|
kwikteam/phy
|
phy/plot/panzoom.py
|
PanZoom.get_range
|
def get_range(self):
"""Return the bounds currently visible."""
p, z = np.asarray(self.pan), np.asarray(self.zoom)
x0, y0 = -1. / z - p
x1, y1 = +1. / z - p
return (x0, y0, x1, y1)
|
python
|
def get_range(self):
"""Return the bounds currently visible."""
p, z = np.asarray(self.pan), np.asarray(self.zoom)
x0, y0 = -1. / z - p
x1, y1 = +1. / z - p
return (x0, y0, x1, y1)
|
[
"def",
"get_range",
"(",
"self",
")",
":",
"p",
",",
"z",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"pan",
")",
",",
"np",
".",
"asarray",
"(",
"self",
".",
"zoom",
")",
"x0",
",",
"y0",
"=",
"-",
"1.",
"/",
"z",
"-",
"p",
"x1",
",",
"y1",
"=",
"+",
"1.",
"/",
"z",
"-",
"p",
"return",
"(",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")"
] |
Return the bounds currently visible.
|
[
"Return",
"the",
"bounds",
"currently",
"visible",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L332-L337
|
7,803
|
kwikteam/phy
|
phy/plot/panzoom.py
|
PanZoom.on_mouse_move
|
def on_mouse_move(self, event):
"""Pan and zoom with the mouse."""
if event.modifiers:
return
if event.is_dragging:
x0, y0 = self._normalize(event.press_event.pos)
x1, y1 = self._normalize(event.last_event.pos)
x, y = self._normalize(event.pos)
dx, dy = x - x1, y - y1
if event.button == 1:
self.pan_delta((dx, dy))
elif event.button == 2:
c = np.sqrt(self.size[0]) * .03
self.zoom_delta((dx, dy), (x0, y0), c=c)
|
python
|
def on_mouse_move(self, event):
"""Pan and zoom with the mouse."""
if event.modifiers:
return
if event.is_dragging:
x0, y0 = self._normalize(event.press_event.pos)
x1, y1 = self._normalize(event.last_event.pos)
x, y = self._normalize(event.pos)
dx, dy = x - x1, y - y1
if event.button == 1:
self.pan_delta((dx, dy))
elif event.button == 2:
c = np.sqrt(self.size[0]) * .03
self.zoom_delta((dx, dy), (x0, y0), c=c)
|
[
"def",
"on_mouse_move",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"modifiers",
":",
"return",
"if",
"event",
".",
"is_dragging",
":",
"x0",
",",
"y0",
"=",
"self",
".",
"_normalize",
"(",
"event",
".",
"press_event",
".",
"pos",
")",
"x1",
",",
"y1",
"=",
"self",
".",
"_normalize",
"(",
"event",
".",
"last_event",
".",
"pos",
")",
"x",
",",
"y",
"=",
"self",
".",
"_normalize",
"(",
"event",
".",
"pos",
")",
"dx",
",",
"dy",
"=",
"x",
"-",
"x1",
",",
"y",
"-",
"y1",
"if",
"event",
".",
"button",
"==",
"1",
":",
"self",
".",
"pan_delta",
"(",
"(",
"dx",
",",
"dy",
")",
")",
"elif",
"event",
".",
"button",
"==",
"2",
":",
"c",
"=",
"np",
".",
"sqrt",
"(",
"self",
".",
"size",
"[",
"0",
"]",
")",
"*",
".03",
"self",
".",
"zoom_delta",
"(",
"(",
"dx",
",",
"dy",
")",
",",
"(",
"x0",
",",
"y0",
")",
",",
"c",
"=",
"c",
")"
] |
Pan and zoom with the mouse.
|
[
"Pan",
"and",
"zoom",
"with",
"the",
"mouse",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L386-L399
|
7,804
|
kwikteam/phy
|
phy/plot/panzoom.py
|
PanZoom.on_mouse_wheel
|
def on_mouse_wheel(self, event):
"""Zoom with the mouse wheel."""
# NOTE: not called on OS X because of touchpad
if event.modifiers:
return
dx = np.sign(event.delta[1]) * self._wheel_coeff
# Zoom toward the mouse pointer.
x0, y0 = self._normalize(event.pos)
self.zoom_delta((dx, dx), (x0, y0))
|
python
|
def on_mouse_wheel(self, event):
"""Zoom with the mouse wheel."""
# NOTE: not called on OS X because of touchpad
if event.modifiers:
return
dx = np.sign(event.delta[1]) * self._wheel_coeff
# Zoom toward the mouse pointer.
x0, y0 = self._normalize(event.pos)
self.zoom_delta((dx, dx), (x0, y0))
|
[
"def",
"on_mouse_wheel",
"(",
"self",
",",
"event",
")",
":",
"# NOTE: not called on OS X because of touchpad",
"if",
"event",
".",
"modifiers",
":",
"return",
"dx",
"=",
"np",
".",
"sign",
"(",
"event",
".",
"delta",
"[",
"1",
"]",
")",
"*",
"self",
".",
"_wheel_coeff",
"# Zoom toward the mouse pointer.",
"x0",
",",
"y0",
"=",
"self",
".",
"_normalize",
"(",
"event",
".",
"pos",
")",
"self",
".",
"zoom_delta",
"(",
"(",
"dx",
",",
"dx",
")",
",",
"(",
"x0",
",",
"y0",
")",
")"
] |
Zoom with the mouse wheel.
|
[
"Zoom",
"with",
"the",
"mouse",
"wheel",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L425-L433
|
7,805
|
kwikteam/phy
|
phy/plot/panzoom.py
|
PanZoom.on_key_press
|
def on_key_press(self, event):
"""Pan and zoom with the keyboard."""
# Zooming with the keyboard.
key = event.key
if event.modifiers:
return
# Pan.
if self.enable_keyboard_pan and key in self._arrows:
self._pan_keyboard(key)
# Zoom.
if key in self._pm:
self._zoom_keyboard(key)
# Reset with 'R'.
if key == 'R':
self.reset()
|
python
|
def on_key_press(self, event):
"""Pan and zoom with the keyboard."""
# Zooming with the keyboard.
key = event.key
if event.modifiers:
return
# Pan.
if self.enable_keyboard_pan and key in self._arrows:
self._pan_keyboard(key)
# Zoom.
if key in self._pm:
self._zoom_keyboard(key)
# Reset with 'R'.
if key == 'R':
self.reset()
|
[
"def",
"on_key_press",
"(",
"self",
",",
"event",
")",
":",
"# Zooming with the keyboard.",
"key",
"=",
"event",
".",
"key",
"if",
"event",
".",
"modifiers",
":",
"return",
"# Pan.",
"if",
"self",
".",
"enable_keyboard_pan",
"and",
"key",
"in",
"self",
".",
"_arrows",
":",
"self",
".",
"_pan_keyboard",
"(",
"key",
")",
"# Zoom.",
"if",
"key",
"in",
"self",
".",
"_pm",
":",
"self",
".",
"_zoom_keyboard",
"(",
"key",
")",
"# Reset with 'R'.",
"if",
"key",
"==",
"'R'",
":",
"self",
".",
"reset",
"(",
")"
] |
Pan and zoom with the keyboard.
|
[
"Pan",
"and",
"zoom",
"with",
"the",
"keyboard",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/panzoom.py#L435-L452
|
7,806
|
kwikteam/phy
|
tools/api.py
|
_replace_docstring_header
|
def _replace_docstring_header(paragraph):
"""Process NumPy-like function docstrings."""
# Replace Markdown headers in docstrings with light headers in bold.
paragraph = re.sub(_docstring_header_pattern,
r'*\1*',
paragraph,
)
paragraph = re.sub(_docstring_parameters_pattern,
r'\n* `\1` (\2)\n',
paragraph,
)
return paragraph
|
python
|
def _replace_docstring_header(paragraph):
"""Process NumPy-like function docstrings."""
# Replace Markdown headers in docstrings with light headers in bold.
paragraph = re.sub(_docstring_header_pattern,
r'*\1*',
paragraph,
)
paragraph = re.sub(_docstring_parameters_pattern,
r'\n* `\1` (\2)\n',
paragraph,
)
return paragraph
|
[
"def",
"_replace_docstring_header",
"(",
"paragraph",
")",
":",
"# Replace Markdown headers in docstrings with light headers in bold.",
"paragraph",
"=",
"re",
".",
"sub",
"(",
"_docstring_header_pattern",
",",
"r'*\\1*'",
",",
"paragraph",
",",
")",
"paragraph",
"=",
"re",
".",
"sub",
"(",
"_docstring_parameters_pattern",
",",
"r'\\n* `\\1` (\\2)\\n'",
",",
"paragraph",
",",
")",
"return",
"paragraph"
] |
Process NumPy-like function docstrings.
|
[
"Process",
"NumPy",
"-",
"like",
"function",
"docstrings",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/tools/api.py#L47-L61
|
7,807
|
kwikteam/phy
|
tools/api.py
|
_iter_vars
|
def _iter_vars(mod):
"""Iterate through a list of variables define in a module's
public namespace."""
vars = sorted(var for var in dir(mod) if _is_public(var))
for var in vars:
yield getattr(mod, var)
|
python
|
def _iter_vars(mod):
"""Iterate through a list of variables define in a module's
public namespace."""
vars = sorted(var for var in dir(mod) if _is_public(var))
for var in vars:
yield getattr(mod, var)
|
[
"def",
"_iter_vars",
"(",
"mod",
")",
":",
"vars",
"=",
"sorted",
"(",
"var",
"for",
"var",
"in",
"dir",
"(",
"mod",
")",
"if",
"_is_public",
"(",
"var",
")",
")",
"for",
"var",
"in",
"vars",
":",
"yield",
"getattr",
"(",
"mod",
",",
"var",
")"
] |
Iterate through a list of variables define in a module's
public namespace.
|
[
"Iterate",
"through",
"a",
"list",
"of",
"variables",
"define",
"in",
"a",
"module",
"s",
"public",
"namespace",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/tools/api.py#L145-L150
|
7,808
|
kwikteam/phy
|
tools/api.py
|
_function_header
|
def _function_header(subpackage, func):
"""Generate the docstring of a function."""
args = inspect.formatargspec(*inspect.getfullargspec(func))
return "{name}{args}".format(name=_full_name(subpackage, func),
args=args,
)
|
python
|
def _function_header(subpackage, func):
"""Generate the docstring of a function."""
args = inspect.formatargspec(*inspect.getfullargspec(func))
return "{name}{args}".format(name=_full_name(subpackage, func),
args=args,
)
|
[
"def",
"_function_header",
"(",
"subpackage",
",",
"func",
")",
":",
"args",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
")",
"return",
"\"{name}{args}\"",
".",
"format",
"(",
"name",
"=",
"_full_name",
"(",
"subpackage",
",",
"func",
")",
",",
"args",
"=",
"args",
",",
")"
] |
Generate the docstring of a function.
|
[
"Generate",
"the",
"docstring",
"of",
"a",
"function",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/tools/api.py#L185-L190
|
7,809
|
kwikteam/phy
|
tools/api.py
|
_doc_method
|
def _doc_method(klass, func):
"""Generate the docstring of a method."""
argspec = inspect.getfullargspec(func)
# Remove first 'self' argument.
if argspec.args and argspec.args[0] == 'self':
del argspec.args[0]
args = inspect.formatargspec(*argspec)
header = "{klass}.{name}{args}".format(klass=klass.__name__,
name=_name(func),
args=args,
)
docstring = _doc(func)
return _concat(header, docstring)
|
python
|
def _doc_method(klass, func):
"""Generate the docstring of a method."""
argspec = inspect.getfullargspec(func)
# Remove first 'self' argument.
if argspec.args and argspec.args[0] == 'self':
del argspec.args[0]
args = inspect.formatargspec(*argspec)
header = "{klass}.{name}{args}".format(klass=klass.__name__,
name=_name(func),
args=args,
)
docstring = _doc(func)
return _concat(header, docstring)
|
[
"def",
"_doc_method",
"(",
"klass",
",",
"func",
")",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
"# Remove first 'self' argument.",
"if",
"argspec",
".",
"args",
"and",
"argspec",
".",
"args",
"[",
"0",
"]",
"==",
"'self'",
":",
"del",
"argspec",
".",
"args",
"[",
"0",
"]",
"args",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"argspec",
")",
"header",
"=",
"\"{klass}.{name}{args}\"",
".",
"format",
"(",
"klass",
"=",
"klass",
".",
"__name__",
",",
"name",
"=",
"_name",
"(",
"func",
")",
",",
"args",
"=",
"args",
",",
")",
"docstring",
"=",
"_doc",
"(",
"func",
")",
"return",
"_concat",
"(",
"header",
",",
"docstring",
")"
] |
Generate the docstring of a method.
|
[
"Generate",
"the",
"docstring",
"of",
"a",
"method",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/tools/api.py#L199-L211
|
7,810
|
kwikteam/phy
|
tools/api.py
|
_doc_property
|
def _doc_property(klass, prop):
"""Generate the docstring of a property."""
header = "{klass}.{name}".format(klass=klass.__name__,
name=_name(prop),
)
docstring = _doc(prop)
return _concat(header, docstring)
|
python
|
def _doc_property(klass, prop):
"""Generate the docstring of a property."""
header = "{klass}.{name}".format(klass=klass.__name__,
name=_name(prop),
)
docstring = _doc(prop)
return _concat(header, docstring)
|
[
"def",
"_doc_property",
"(",
"klass",
",",
"prop",
")",
":",
"header",
"=",
"\"{klass}.{name}\"",
".",
"format",
"(",
"klass",
"=",
"klass",
".",
"__name__",
",",
"name",
"=",
"_name",
"(",
"prop",
")",
",",
")",
"docstring",
"=",
"_doc",
"(",
"prop",
")",
"return",
"_concat",
"(",
"header",
",",
"docstring",
")"
] |
Generate the docstring of a property.
|
[
"Generate",
"the",
"docstring",
"of",
"a",
"property",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/tools/api.py#L214-L220
|
7,811
|
kwikteam/phy
|
tools/api.py
|
_generate_paragraphs
|
def _generate_paragraphs(package, subpackages):
"""Generate the paragraphs of the API documentation."""
# API doc of each module.
for subpackage in _iter_subpackages(package, subpackages):
subpackage_name = subpackage.__name__
yield "## {}".format(subpackage_name)
# Subpackage documentation.
yield _doc(_import_module(subpackage_name))
# List of top-level functions in the subpackage.
for func in _iter_functions(subpackage):
yield '##### ' + _doc_function(subpackage, func)
# All public classes.
for klass in _iter_classes(subpackage):
# Class documentation.
yield "### {}".format(_full_name(subpackage, klass))
yield _doc(klass)
yield "#### Methods"
for method in _iter_methods(klass, package):
yield '##### ' + _doc_method(klass, method)
yield "#### Properties"
for prop in _iter_properties(klass, package):
yield '##### ' + _doc_property(klass, prop)
|
python
|
def _generate_paragraphs(package, subpackages):
"""Generate the paragraphs of the API documentation."""
# API doc of each module.
for subpackage in _iter_subpackages(package, subpackages):
subpackage_name = subpackage.__name__
yield "## {}".format(subpackage_name)
# Subpackage documentation.
yield _doc(_import_module(subpackage_name))
# List of top-level functions in the subpackage.
for func in _iter_functions(subpackage):
yield '##### ' + _doc_function(subpackage, func)
# All public classes.
for klass in _iter_classes(subpackage):
# Class documentation.
yield "### {}".format(_full_name(subpackage, klass))
yield _doc(klass)
yield "#### Methods"
for method in _iter_methods(klass, package):
yield '##### ' + _doc_method(klass, method)
yield "#### Properties"
for prop in _iter_properties(klass, package):
yield '##### ' + _doc_property(klass, prop)
|
[
"def",
"_generate_paragraphs",
"(",
"package",
",",
"subpackages",
")",
":",
"# API doc of each module.",
"for",
"subpackage",
"in",
"_iter_subpackages",
"(",
"package",
",",
"subpackages",
")",
":",
"subpackage_name",
"=",
"subpackage",
".",
"__name__",
"yield",
"\"## {}\"",
".",
"format",
"(",
"subpackage_name",
")",
"# Subpackage documentation.",
"yield",
"_doc",
"(",
"_import_module",
"(",
"subpackage_name",
")",
")",
"# List of top-level functions in the subpackage.",
"for",
"func",
"in",
"_iter_functions",
"(",
"subpackage",
")",
":",
"yield",
"'##### '",
"+",
"_doc_function",
"(",
"subpackage",
",",
"func",
")",
"# All public classes.",
"for",
"klass",
"in",
"_iter_classes",
"(",
"subpackage",
")",
":",
"# Class documentation.",
"yield",
"\"### {}\"",
".",
"format",
"(",
"_full_name",
"(",
"subpackage",
",",
"klass",
")",
")",
"yield",
"_doc",
"(",
"klass",
")",
"yield",
"\"#### Methods\"",
"for",
"method",
"in",
"_iter_methods",
"(",
"klass",
",",
"package",
")",
":",
"yield",
"'##### '",
"+",
"_doc_method",
"(",
"klass",
",",
"method",
")",
"yield",
"\"#### Properties\"",
"for",
"prop",
"in",
"_iter_properties",
"(",
"klass",
",",
"package",
")",
":",
"yield",
"'##### '",
"+",
"_doc_property",
"(",
"klass",
",",
"prop",
")"
] |
Generate the paragraphs of the API documentation.
|
[
"Generate",
"the",
"paragraphs",
"of",
"the",
"API",
"documentation",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/tools/api.py#L260-L289
|
7,812
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor._add_field_column
|
def _add_field_column(self, field): # pragma: no cover
"""Add a column for a given label field."""
@self.add_column(name=field)
def get_my_label(cluster_id):
return self.cluster_meta.get(field, cluster_id)
|
python
|
def _add_field_column(self, field): # pragma: no cover
"""Add a column for a given label field."""
@self.add_column(name=field)
def get_my_label(cluster_id):
return self.cluster_meta.get(field, cluster_id)
|
[
"def",
"_add_field_column",
"(",
"self",
",",
"field",
")",
":",
"# pragma: no cover",
"@",
"self",
".",
"add_column",
"(",
"name",
"=",
"field",
")",
"def",
"get_my_label",
"(",
"cluster_id",
")",
":",
"return",
"self",
".",
"cluster_meta",
".",
"get",
"(",
"field",
",",
"cluster_id",
")"
] |
Add a column for a given label field.
|
[
"Add",
"a",
"column",
"for",
"a",
"given",
"label",
"field",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L234-L238
|
7,813
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor._emit_select
|
def _emit_select(self, cluster_ids, **kwargs):
"""Choose spikes from the specified clusters and emit the
`select` event on the GUI."""
# Remove non-existing clusters from the selection.
cluster_ids = self._keep_existing_clusters(cluster_ids)
logger.debug("Select cluster(s): %s.",
', '.join(map(str, cluster_ids)))
self.emit('select', cluster_ids, **kwargs)
|
python
|
def _emit_select(self, cluster_ids, **kwargs):
"""Choose spikes from the specified clusters and emit the
`select` event on the GUI."""
# Remove non-existing clusters from the selection.
cluster_ids = self._keep_existing_clusters(cluster_ids)
logger.debug("Select cluster(s): %s.",
', '.join(map(str, cluster_ids)))
self.emit('select', cluster_ids, **kwargs)
|
[
"def",
"_emit_select",
"(",
"self",
",",
"cluster_ids",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove non-existing clusters from the selection.",
"cluster_ids",
"=",
"self",
".",
"_keep_existing_clusters",
"(",
"cluster_ids",
")",
"logger",
".",
"debug",
"(",
"\"Select cluster(s): %s.\"",
",",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"cluster_ids",
")",
")",
")",
"self",
".",
"emit",
"(",
"'select'",
",",
"cluster_ids",
",",
"*",
"*",
"kwargs",
")"
] |
Choose spikes from the specified clusters and emit the
`select` event on the GUI.
|
[
"Choose",
"spikes",
"from",
"the",
"specified",
"clusters",
"and",
"emit",
"the",
"select",
"event",
"on",
"the",
"GUI",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L336-L343
|
7,814
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor._update_cluster_view
|
def _update_cluster_view(self):
"""Initialize the cluster view with cluster data."""
logger.log(5, "Update the cluster view.")
cluster_ids = [int(c) for c in self.clustering.cluster_ids]
self.cluster_view.set_rows(cluster_ids)
|
python
|
def _update_cluster_view(self):
"""Initialize the cluster view with cluster data."""
logger.log(5, "Update the cluster view.")
cluster_ids = [int(c) for c in self.clustering.cluster_ids]
self.cluster_view.set_rows(cluster_ids)
|
[
"def",
"_update_cluster_view",
"(",
"self",
")",
":",
"logger",
".",
"log",
"(",
"5",
",",
"\"Update the cluster view.\"",
")",
"cluster_ids",
"=",
"[",
"int",
"(",
"c",
")",
"for",
"c",
"in",
"self",
".",
"clustering",
".",
"cluster_ids",
"]",
"self",
".",
"cluster_view",
".",
"set_rows",
"(",
"cluster_ids",
")"
] |
Initialize the cluster view with cluster data.
|
[
"Initialize",
"the",
"cluster",
"view",
"with",
"cluster",
"data",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L379-L383
|
7,815
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor._update_similarity_view
|
def _update_similarity_view(self):
"""Update the similarity view with matches for the specified
clusters."""
if not self.similarity:
return
selection = self.cluster_view.selected
if not len(selection):
return
cluster_id = selection[0]
cluster_ids = self.clustering.cluster_ids
self._best = cluster_id
logger.log(5, "Update the similarity view.")
# This is a list of pairs (closest_cluster, similarity).
similarities = self.similarity(cluster_id)
# We save the similarity values wrt the currently-selected clusters.
# Note that we keep the order of the output of the self.similary()
# function.
clusters_sim = OrderedDict([(int(cl), s) for (cl, s) in similarities])
# List of similar clusters, remove non-existing ones.
clusters = [c for c in clusters_sim.keys()
if c in cluster_ids]
# The similarity view will use these values.
self._current_similarity_values = clusters_sim
# Set the rows of the similarity view.
# TODO: instead of the self._current_similarity_values hack,
# give the possibility to specify the values here (?).
self.similarity_view.set_rows([c for c in clusters
if c not in selection])
|
python
|
def _update_similarity_view(self):
"""Update the similarity view with matches for the specified
clusters."""
if not self.similarity:
return
selection = self.cluster_view.selected
if not len(selection):
return
cluster_id = selection[0]
cluster_ids = self.clustering.cluster_ids
self._best = cluster_id
logger.log(5, "Update the similarity view.")
# This is a list of pairs (closest_cluster, similarity).
similarities = self.similarity(cluster_id)
# We save the similarity values wrt the currently-selected clusters.
# Note that we keep the order of the output of the self.similary()
# function.
clusters_sim = OrderedDict([(int(cl), s) for (cl, s) in similarities])
# List of similar clusters, remove non-existing ones.
clusters = [c for c in clusters_sim.keys()
if c in cluster_ids]
# The similarity view will use these values.
self._current_similarity_values = clusters_sim
# Set the rows of the similarity view.
# TODO: instead of the self._current_similarity_values hack,
# give the possibility to specify the values here (?).
self.similarity_view.set_rows([c for c in clusters
if c not in selection])
|
[
"def",
"_update_similarity_view",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"similarity",
":",
"return",
"selection",
"=",
"self",
".",
"cluster_view",
".",
"selected",
"if",
"not",
"len",
"(",
"selection",
")",
":",
"return",
"cluster_id",
"=",
"selection",
"[",
"0",
"]",
"cluster_ids",
"=",
"self",
".",
"clustering",
".",
"cluster_ids",
"self",
".",
"_best",
"=",
"cluster_id",
"logger",
".",
"log",
"(",
"5",
",",
"\"Update the similarity view.\"",
")",
"# This is a list of pairs (closest_cluster, similarity).",
"similarities",
"=",
"self",
".",
"similarity",
"(",
"cluster_id",
")",
"# We save the similarity values wrt the currently-selected clusters.",
"# Note that we keep the order of the output of the self.similary()",
"# function.",
"clusters_sim",
"=",
"OrderedDict",
"(",
"[",
"(",
"int",
"(",
"cl",
")",
",",
"s",
")",
"for",
"(",
"cl",
",",
"s",
")",
"in",
"similarities",
"]",
")",
"# List of similar clusters, remove non-existing ones.",
"clusters",
"=",
"[",
"c",
"for",
"c",
"in",
"clusters_sim",
".",
"keys",
"(",
")",
"if",
"c",
"in",
"cluster_ids",
"]",
"# The similarity view will use these values.",
"self",
".",
"_current_similarity_values",
"=",
"clusters_sim",
"# Set the rows of the similarity view.",
"# TODO: instead of the self._current_similarity_values hack,",
"# give the possibility to specify the values here (?).",
"self",
".",
"similarity_view",
".",
"set_rows",
"(",
"[",
"c",
"for",
"c",
"in",
"clusters",
"if",
"c",
"not",
"in",
"selection",
"]",
")"
] |
Update the similarity view with matches for the specified
clusters.
|
[
"Update",
"the",
"similarity",
"view",
"with",
"matches",
"for",
"the",
"specified",
"clusters",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L385-L412
|
7,816
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.on_cluster
|
def on_cluster(self, up):
"""Update the cluster views after clustering actions."""
similar = self.similarity_view.selected
# Reinitialize the cluster view if clusters have changed.
if up.added:
self._update_cluster_view()
# Select all new clusters in view 1.
if up.history == 'undo':
# Select the clusters that were selected before the undone
# action.
clusters_0, clusters_1 = up.undo_state[0]['selection']
# Select rows in the tables.
self.cluster_view.select(clusters_0, up=up)
self.similarity_view.select(clusters_1, up=up)
elif up.added:
if up.description == 'assign':
# NOTE: we change the order such that the last selected
# cluster (with a new color) is the split cluster.
added = list(up.added[1:]) + [up.added[0]]
else:
added = up.added
# Select the new clusters in the cluster view.
self.cluster_view.select(added, up=up)
if similar:
self.similarity_view.next()
elif up.metadata_changed:
# Select next in similarity view if all moved are in that view.
if set(up.metadata_changed) <= set(similar):
next_cluster = self.similarity_view.get_next_id()
self._update_similarity_view()
if next_cluster is not None:
# Select the cluster in the similarity view.
self.similarity_view.select([next_cluster])
# Otherwise, select next in cluster view.
else:
self._update_cluster_view()
# Determine if there is a next cluster set from a
# previous clustering action.
cluster = up.metadata_changed[0]
next_cluster = self.cluster_meta.get('next_cluster', cluster)
logger.debug("Get next_cluster for %d: %s.",
cluster, next_cluster)
# If there is not, fallback on the next cluster in the list.
if next_cluster is None:
self.cluster_view.select([cluster], do_emit=False)
self.cluster_view.next()
else:
self.cluster_view.select([next_cluster])
|
python
|
def on_cluster(self, up):
"""Update the cluster views after clustering actions."""
similar = self.similarity_view.selected
# Reinitialize the cluster view if clusters have changed.
if up.added:
self._update_cluster_view()
# Select all new clusters in view 1.
if up.history == 'undo':
# Select the clusters that were selected before the undone
# action.
clusters_0, clusters_1 = up.undo_state[0]['selection']
# Select rows in the tables.
self.cluster_view.select(clusters_0, up=up)
self.similarity_view.select(clusters_1, up=up)
elif up.added:
if up.description == 'assign':
# NOTE: we change the order such that the last selected
# cluster (with a new color) is the split cluster.
added = list(up.added[1:]) + [up.added[0]]
else:
added = up.added
# Select the new clusters in the cluster view.
self.cluster_view.select(added, up=up)
if similar:
self.similarity_view.next()
elif up.metadata_changed:
# Select next in similarity view if all moved are in that view.
if set(up.metadata_changed) <= set(similar):
next_cluster = self.similarity_view.get_next_id()
self._update_similarity_view()
if next_cluster is not None:
# Select the cluster in the similarity view.
self.similarity_view.select([next_cluster])
# Otherwise, select next in cluster view.
else:
self._update_cluster_view()
# Determine if there is a next cluster set from a
# previous clustering action.
cluster = up.metadata_changed[0]
next_cluster = self.cluster_meta.get('next_cluster', cluster)
logger.debug("Get next_cluster for %d: %s.",
cluster, next_cluster)
# If there is not, fallback on the next cluster in the list.
if next_cluster is None:
self.cluster_view.select([cluster], do_emit=False)
self.cluster_view.next()
else:
self.cluster_view.select([next_cluster])
|
[
"def",
"on_cluster",
"(",
"self",
",",
"up",
")",
":",
"similar",
"=",
"self",
".",
"similarity_view",
".",
"selected",
"# Reinitialize the cluster view if clusters have changed.",
"if",
"up",
".",
"added",
":",
"self",
".",
"_update_cluster_view",
"(",
")",
"# Select all new clusters in view 1.",
"if",
"up",
".",
"history",
"==",
"'undo'",
":",
"# Select the clusters that were selected before the undone",
"# action.",
"clusters_0",
",",
"clusters_1",
"=",
"up",
".",
"undo_state",
"[",
"0",
"]",
"[",
"'selection'",
"]",
"# Select rows in the tables.",
"self",
".",
"cluster_view",
".",
"select",
"(",
"clusters_0",
",",
"up",
"=",
"up",
")",
"self",
".",
"similarity_view",
".",
"select",
"(",
"clusters_1",
",",
"up",
"=",
"up",
")",
"elif",
"up",
".",
"added",
":",
"if",
"up",
".",
"description",
"==",
"'assign'",
":",
"# NOTE: we change the order such that the last selected",
"# cluster (with a new color) is the split cluster.",
"added",
"=",
"list",
"(",
"up",
".",
"added",
"[",
"1",
":",
"]",
")",
"+",
"[",
"up",
".",
"added",
"[",
"0",
"]",
"]",
"else",
":",
"added",
"=",
"up",
".",
"added",
"# Select the new clusters in the cluster view.",
"self",
".",
"cluster_view",
".",
"select",
"(",
"added",
",",
"up",
"=",
"up",
")",
"if",
"similar",
":",
"self",
".",
"similarity_view",
".",
"next",
"(",
")",
"elif",
"up",
".",
"metadata_changed",
":",
"# Select next in similarity view if all moved are in that view.",
"if",
"set",
"(",
"up",
".",
"metadata_changed",
")",
"<=",
"set",
"(",
"similar",
")",
":",
"next_cluster",
"=",
"self",
".",
"similarity_view",
".",
"get_next_id",
"(",
")",
"self",
".",
"_update_similarity_view",
"(",
")",
"if",
"next_cluster",
"is",
"not",
"None",
":",
"# Select the cluster in the similarity view.",
"self",
".",
"similarity_view",
".",
"select",
"(",
"[",
"next_cluster",
"]",
")",
"# Otherwise, select next in cluster view.",
"else",
":",
"self",
".",
"_update_cluster_view",
"(",
")",
"# Determine if there is a next cluster set from a",
"# previous clustering action.",
"cluster",
"=",
"up",
".",
"metadata_changed",
"[",
"0",
"]",
"next_cluster",
"=",
"self",
".",
"cluster_meta",
".",
"get",
"(",
"'next_cluster'",
",",
"cluster",
")",
"logger",
".",
"debug",
"(",
"\"Get next_cluster for %d: %s.\"",
",",
"cluster",
",",
"next_cluster",
")",
"# If there is not, fallback on the next cluster in the list.",
"if",
"next_cluster",
"is",
"None",
":",
"self",
".",
"cluster_view",
".",
"select",
"(",
"[",
"cluster",
"]",
",",
"do_emit",
"=",
"False",
")",
"self",
".",
"cluster_view",
".",
"next",
"(",
")",
"else",
":",
"self",
".",
"cluster_view",
".",
"select",
"(",
"[",
"next_cluster",
"]",
")"
] |
Update the cluster views after clustering actions.
|
[
"Update",
"the",
"cluster",
"views",
"after",
"clustering",
"actions",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L438-L488
|
7,817
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.select
|
def select(self, *cluster_ids):
"""Select a list of clusters."""
# HACK: allow for `select(1, 2, 3)` in addition to `select([1, 2, 3])`
# This makes it more convenient to select multiple clusters with
# the snippet: `:c 1 2 3` instead of `:c 1,2,3`.
if cluster_ids and isinstance(cluster_ids[0], (tuple, list)):
cluster_ids = list(cluster_ids[0]) + list(cluster_ids[1:])
# Remove non-existing clusters from the selection.
cluster_ids = self._keep_existing_clusters(cluster_ids)
# Update the cluster view selection.
self.cluster_view.select(cluster_ids)
|
python
|
def select(self, *cluster_ids):
"""Select a list of clusters."""
# HACK: allow for `select(1, 2, 3)` in addition to `select([1, 2, 3])`
# This makes it more convenient to select multiple clusters with
# the snippet: `:c 1 2 3` instead of `:c 1,2,3`.
if cluster_ids and isinstance(cluster_ids[0], (tuple, list)):
cluster_ids = list(cluster_ids[0]) + list(cluster_ids[1:])
# Remove non-existing clusters from the selection.
cluster_ids = self._keep_existing_clusters(cluster_ids)
# Update the cluster view selection.
self.cluster_view.select(cluster_ids)
|
[
"def",
"select",
"(",
"self",
",",
"*",
"cluster_ids",
")",
":",
"# HACK: allow for `select(1, 2, 3)` in addition to `select([1, 2, 3])`",
"# This makes it more convenient to select multiple clusters with",
"# the snippet: `:c 1 2 3` instead of `:c 1,2,3`.",
"if",
"cluster_ids",
"and",
"isinstance",
"(",
"cluster_ids",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"cluster_ids",
"=",
"list",
"(",
"cluster_ids",
"[",
"0",
"]",
")",
"+",
"list",
"(",
"cluster_ids",
"[",
"1",
":",
"]",
")",
"# Remove non-existing clusters from the selection.",
"cluster_ids",
"=",
"self",
".",
"_keep_existing_clusters",
"(",
"cluster_ids",
")",
"# Update the cluster view selection.",
"self",
".",
"cluster_view",
".",
"select",
"(",
"cluster_ids",
")"
] |
Select a list of clusters.
|
[
"Select",
"a",
"list",
"of",
"clusters",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L556-L566
|
7,818
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.merge
|
def merge(self, cluster_ids=None, to=None):
"""Merge the selected clusters."""
if cluster_ids is None:
cluster_ids = self.selected
if len(cluster_ids or []) <= 1:
return
self.clustering.merge(cluster_ids, to=to)
self._global_history.action(self.clustering)
|
python
|
def merge(self, cluster_ids=None, to=None):
"""Merge the selected clusters."""
if cluster_ids is None:
cluster_ids = self.selected
if len(cluster_ids or []) <= 1:
return
self.clustering.merge(cluster_ids, to=to)
self._global_history.action(self.clustering)
|
[
"def",
"merge",
"(",
"self",
",",
"cluster_ids",
"=",
"None",
",",
"to",
"=",
"None",
")",
":",
"if",
"cluster_ids",
"is",
"None",
":",
"cluster_ids",
"=",
"self",
".",
"selected",
"if",
"len",
"(",
"cluster_ids",
"or",
"[",
"]",
")",
"<=",
"1",
":",
"return",
"self",
".",
"clustering",
".",
"merge",
"(",
"cluster_ids",
",",
"to",
"=",
"to",
")",
"self",
".",
"_global_history",
".",
"action",
"(",
"self",
".",
"clustering",
")"
] |
Merge the selected clusters.
|
[
"Merge",
"the",
"selected",
"clusters",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L575-L582
|
7,819
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.split
|
def split(self, spike_ids=None, spike_clusters_rel=0):
"""Split the selected spikes."""
if spike_ids is None:
spike_ids = self.emit('request_split', single=True)
spike_ids = np.asarray(spike_ids, dtype=np.int64)
assert spike_ids.dtype == np.int64
assert spike_ids.ndim == 1
if len(spike_ids) == 0:
msg = ("You first need to select spikes in the feature "
"view with a few Ctrl+Click around the spikes "
"that you want to split.")
self.emit('error', msg)
return
self.clustering.split(spike_ids,
spike_clusters_rel=spike_clusters_rel)
self._global_history.action(self.clustering)
|
python
|
def split(self, spike_ids=None, spike_clusters_rel=0):
"""Split the selected spikes."""
if spike_ids is None:
spike_ids = self.emit('request_split', single=True)
spike_ids = np.asarray(spike_ids, dtype=np.int64)
assert spike_ids.dtype == np.int64
assert spike_ids.ndim == 1
if len(spike_ids) == 0:
msg = ("You first need to select spikes in the feature "
"view with a few Ctrl+Click around the spikes "
"that you want to split.")
self.emit('error', msg)
return
self.clustering.split(spike_ids,
spike_clusters_rel=spike_clusters_rel)
self._global_history.action(self.clustering)
|
[
"def",
"split",
"(",
"self",
",",
"spike_ids",
"=",
"None",
",",
"spike_clusters_rel",
"=",
"0",
")",
":",
"if",
"spike_ids",
"is",
"None",
":",
"spike_ids",
"=",
"self",
".",
"emit",
"(",
"'request_split'",
",",
"single",
"=",
"True",
")",
"spike_ids",
"=",
"np",
".",
"asarray",
"(",
"spike_ids",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"assert",
"spike_ids",
".",
"dtype",
"==",
"np",
".",
"int64",
"assert",
"spike_ids",
".",
"ndim",
"==",
"1",
"if",
"len",
"(",
"spike_ids",
")",
"==",
"0",
":",
"msg",
"=",
"(",
"\"You first need to select spikes in the feature \"",
"\"view with a few Ctrl+Click around the spikes \"",
"\"that you want to split.\"",
")",
"self",
".",
"emit",
"(",
"'error'",
",",
"msg",
")",
"return",
"self",
".",
"clustering",
".",
"split",
"(",
"spike_ids",
",",
"spike_clusters_rel",
"=",
"spike_clusters_rel",
")",
"self",
".",
"_global_history",
".",
"action",
"(",
"self",
".",
"clustering",
")"
] |
Split the selected spikes.
|
[
"Split",
"the",
"selected",
"spikes",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L584-L599
|
7,820
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.get_labels
|
def get_labels(self, field):
"""Return the labels of all clusters, for a given field."""
return {c: self.cluster_meta.get(field, c)
for c in self.clustering.cluster_ids}
|
python
|
def get_labels(self, field):
"""Return the labels of all clusters, for a given field."""
return {c: self.cluster_meta.get(field, c)
for c in self.clustering.cluster_ids}
|
[
"def",
"get_labels",
"(",
"self",
",",
"field",
")",
":",
"return",
"{",
"c",
":",
"self",
".",
"cluster_meta",
".",
"get",
"(",
"field",
",",
"c",
")",
"for",
"c",
"in",
"self",
".",
"clustering",
".",
"cluster_ids",
"}"
] |
Return the labels of all clusters, for a given field.
|
[
"Return",
"the",
"labels",
"of",
"all",
"clusters",
"for",
"a",
"given",
"field",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L610-L613
|
7,821
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.label
|
def label(self, name, value, cluster_ids=None):
"""Assign a label to clusters.
Example: `quality 3`
"""
if cluster_ids is None:
cluster_ids = self.cluster_view.selected
if not hasattr(cluster_ids, '__len__'):
cluster_ids = [cluster_ids]
if len(cluster_ids) == 0:
return
self.cluster_meta.set(name, cluster_ids, value)
self._global_history.action(self.cluster_meta)
|
python
|
def label(self, name, value, cluster_ids=None):
"""Assign a label to clusters.
Example: `quality 3`
"""
if cluster_ids is None:
cluster_ids = self.cluster_view.selected
if not hasattr(cluster_ids, '__len__'):
cluster_ids = [cluster_ids]
if len(cluster_ids) == 0:
return
self.cluster_meta.set(name, cluster_ids, value)
self._global_history.action(self.cluster_meta)
|
[
"def",
"label",
"(",
"self",
",",
"name",
",",
"value",
",",
"cluster_ids",
"=",
"None",
")",
":",
"if",
"cluster_ids",
"is",
"None",
":",
"cluster_ids",
"=",
"self",
".",
"cluster_view",
".",
"selected",
"if",
"not",
"hasattr",
"(",
"cluster_ids",
",",
"'__len__'",
")",
":",
"cluster_ids",
"=",
"[",
"cluster_ids",
"]",
"if",
"len",
"(",
"cluster_ids",
")",
"==",
"0",
":",
"return",
"self",
".",
"cluster_meta",
".",
"set",
"(",
"name",
",",
"cluster_ids",
",",
"value",
")",
"self",
".",
"_global_history",
".",
"action",
"(",
"self",
".",
"cluster_meta",
")"
] |
Assign a label to clusters.
Example: `quality 3`
|
[
"Assign",
"a",
"label",
"to",
"clusters",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L615-L628
|
7,822
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.move
|
def move(self, group, cluster_ids=None):
"""Assign a group to some clusters.
Example: `good`
"""
if isinstance(cluster_ids, string_types):
logger.warn("The list of clusters should be a list of integers, "
"not a string.")
return
self.label('group', group, cluster_ids=cluster_ids)
|
python
|
def move(self, group, cluster_ids=None):
"""Assign a group to some clusters.
Example: `good`
"""
if isinstance(cluster_ids, string_types):
logger.warn("The list of clusters should be a list of integers, "
"not a string.")
return
self.label('group', group, cluster_ids=cluster_ids)
|
[
"def",
"move",
"(",
"self",
",",
"group",
",",
"cluster_ids",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"cluster_ids",
",",
"string_types",
")",
":",
"logger",
".",
"warn",
"(",
"\"The list of clusters should be a list of integers, \"",
"\"not a string.\"",
")",
"return",
"self",
".",
"label",
"(",
"'group'",
",",
"group",
",",
"cluster_ids",
"=",
"cluster_ids",
")"
] |
Assign a group to some clusters.
Example: `good`
|
[
"Assign",
"a",
"group",
"to",
"some",
"clusters",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L630-L640
|
7,823
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.next
|
def next(self):
"""Select the next cluster."""
if not self.selected:
self.cluster_view.next()
else:
self.similarity_view.next()
|
python
|
def next(self):
"""Select the next cluster."""
if not self.selected:
self.cluster_view.next()
else:
self.similarity_view.next()
|
[
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"selected",
":",
"self",
".",
"cluster_view",
".",
"next",
"(",
")",
"else",
":",
"self",
".",
"similarity_view",
".",
"next",
"(",
")"
] |
Select the next cluster.
|
[
"Select",
"the",
"next",
"cluster",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L670-L675
|
7,824
|
kwikteam/phy
|
phy/cluster/supervisor.py
|
Supervisor.save
|
def save(self):
"""Save the manual clustering back to disk."""
spike_clusters = self.clustering.spike_clusters
groups = {c: self.cluster_meta.get('group', c) or 'unsorted'
for c in self.clustering.cluster_ids}
# List of tuples (field_name, dictionary).
labels = [(field, self.get_labels(field))
for field in self.cluster_meta.fields
if field not in ('next_cluster')]
# TODO: add option in add_field to declare a field unsavable.
self.emit('request_save', spike_clusters, groups, *labels)
# Cache the spikes_per_cluster array.
self._save_spikes_per_cluster()
|
python
|
def save(self):
"""Save the manual clustering back to disk."""
spike_clusters = self.clustering.spike_clusters
groups = {c: self.cluster_meta.get('group', c) or 'unsorted'
for c in self.clustering.cluster_ids}
# List of tuples (field_name, dictionary).
labels = [(field, self.get_labels(field))
for field in self.cluster_meta.fields
if field not in ('next_cluster')]
# TODO: add option in add_field to declare a field unsavable.
self.emit('request_save', spike_clusters, groups, *labels)
# Cache the spikes_per_cluster array.
self._save_spikes_per_cluster()
|
[
"def",
"save",
"(",
"self",
")",
":",
"spike_clusters",
"=",
"self",
".",
"clustering",
".",
"spike_clusters",
"groups",
"=",
"{",
"c",
":",
"self",
".",
"cluster_meta",
".",
"get",
"(",
"'group'",
",",
"c",
")",
"or",
"'unsorted'",
"for",
"c",
"in",
"self",
".",
"clustering",
".",
"cluster_ids",
"}",
"# List of tuples (field_name, dictionary).",
"labels",
"=",
"[",
"(",
"field",
",",
"self",
".",
"get_labels",
"(",
"field",
")",
")",
"for",
"field",
"in",
"self",
".",
"cluster_meta",
".",
"fields",
"if",
"field",
"not",
"in",
"(",
"'next_cluster'",
")",
"]",
"# TODO: add option in add_field to declare a field unsavable.",
"self",
".",
"emit",
"(",
"'request_save'",
",",
"spike_clusters",
",",
"groups",
",",
"*",
"labels",
")",
"# Cache the spikes_per_cluster array.",
"self",
".",
"_save_spikes_per_cluster",
"(",
")"
] |
Save the manual clustering back to disk.
|
[
"Save",
"the",
"manual",
"clustering",
"back",
"to",
"disk",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/supervisor.py#L692-L704
|
7,825
|
kwikteam/phy
|
phy/cluster/_utils.py
|
create_cluster_meta
|
def create_cluster_meta(cluster_groups):
"""Return a ClusterMeta instance with cluster group support."""
meta = ClusterMeta()
meta.add_field('group')
cluster_groups = cluster_groups or {}
data = {c: {'group': v} for c, v in cluster_groups.items()}
meta.from_dict(data)
return meta
|
python
|
def create_cluster_meta(cluster_groups):
"""Return a ClusterMeta instance with cluster group support."""
meta = ClusterMeta()
meta.add_field('group')
cluster_groups = cluster_groups or {}
data = {c: {'group': v} for c, v in cluster_groups.items()}
meta.from_dict(data)
return meta
|
[
"def",
"create_cluster_meta",
"(",
"cluster_groups",
")",
":",
"meta",
"=",
"ClusterMeta",
"(",
")",
"meta",
".",
"add_field",
"(",
"'group'",
")",
"cluster_groups",
"=",
"cluster_groups",
"or",
"{",
"}",
"data",
"=",
"{",
"c",
":",
"{",
"'group'",
":",
"v",
"}",
"for",
"c",
",",
"v",
"in",
"cluster_groups",
".",
"items",
"(",
")",
"}",
"meta",
".",
"from_dict",
"(",
"data",
")",
"return",
"meta"
] |
Return a ClusterMeta instance with cluster group support.
|
[
"Return",
"a",
"ClusterMeta",
"instance",
"with",
"cluster",
"group",
"support",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L35-L44
|
7,826
|
kwikteam/phy
|
phy/cluster/_utils.py
|
ClusterMeta.add_field
|
def add_field(self, name, default_value=None):
"""Add a field with an optional default value."""
self._fields[name] = default_value
def func(cluster):
return self.get(name, cluster)
setattr(self, name, func)
|
python
|
def add_field(self, name, default_value=None):
"""Add a field with an optional default value."""
self._fields[name] = default_value
def func(cluster):
return self.get(name, cluster)
setattr(self, name, func)
|
[
"def",
"add_field",
"(",
"self",
",",
"name",
",",
"default_value",
"=",
"None",
")",
":",
"self",
".",
"_fields",
"[",
"name",
"]",
"=",
"default_value",
"def",
"func",
"(",
"cluster",
")",
":",
"return",
"self",
".",
"get",
"(",
"name",
",",
"cluster",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"func",
")"
] |
Add a field with an optional default value.
|
[
"Add",
"a",
"field",
"with",
"an",
"optional",
"default",
"value",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L116-L123
|
7,827
|
kwikteam/phy
|
phy/cluster/_utils.py
|
ClusterMeta.set
|
def set(self, field, clusters, value, add_to_stack=True):
"""Set the value of one of several clusters."""
# Add the field if it doesn't exist.
if field not in self._fields:
self.add_field(field)
assert field in self._fields
clusters = _as_list(clusters)
for cluster in clusters:
if cluster not in self._data:
self._data[cluster] = {}
self._data[cluster][field] = value
up = UpdateInfo(description='metadata_' + field,
metadata_changed=clusters,
metadata_value=value,
)
undo_state = self.emit('request_undo_state', up)
if add_to_stack:
self._undo_stack.add((clusters, field, value, up, undo_state))
self.emit('cluster', up)
return up
|
python
|
def set(self, field, clusters, value, add_to_stack=True):
"""Set the value of one of several clusters."""
# Add the field if it doesn't exist.
if field not in self._fields:
self.add_field(field)
assert field in self._fields
clusters = _as_list(clusters)
for cluster in clusters:
if cluster not in self._data:
self._data[cluster] = {}
self._data[cluster][field] = value
up = UpdateInfo(description='metadata_' + field,
metadata_changed=clusters,
metadata_value=value,
)
undo_state = self.emit('request_undo_state', up)
if add_to_stack:
self._undo_stack.add((clusters, field, value, up, undo_state))
self.emit('cluster', up)
return up
|
[
"def",
"set",
"(",
"self",
",",
"field",
",",
"clusters",
",",
"value",
",",
"add_to_stack",
"=",
"True",
")",
":",
"# Add the field if it doesn't exist.",
"if",
"field",
"not",
"in",
"self",
".",
"_fields",
":",
"self",
".",
"add_field",
"(",
"field",
")",
"assert",
"field",
"in",
"self",
".",
"_fields",
"clusters",
"=",
"_as_list",
"(",
"clusters",
")",
"for",
"cluster",
"in",
"clusters",
":",
"if",
"cluster",
"not",
"in",
"self",
".",
"_data",
":",
"self",
".",
"_data",
"[",
"cluster",
"]",
"=",
"{",
"}",
"self",
".",
"_data",
"[",
"cluster",
"]",
"[",
"field",
"]",
"=",
"value",
"up",
"=",
"UpdateInfo",
"(",
"description",
"=",
"'metadata_'",
"+",
"field",
",",
"metadata_changed",
"=",
"clusters",
",",
"metadata_value",
"=",
"value",
",",
")",
"undo_state",
"=",
"self",
".",
"emit",
"(",
"'request_undo_state'",
",",
"up",
")",
"if",
"add_to_stack",
":",
"self",
".",
"_undo_stack",
".",
"add",
"(",
"(",
"clusters",
",",
"field",
",",
"value",
",",
"up",
",",
"undo_state",
")",
")",
"self",
".",
"emit",
"(",
"'cluster'",
",",
"up",
")",
"return",
"up"
] |
Set the value of one of several clusters.
|
[
"Set",
"the",
"value",
"of",
"one",
"of",
"several",
"clusters",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L140-L163
|
7,828
|
kwikteam/phy
|
phy/cluster/_utils.py
|
ClusterMeta.get
|
def get(self, field, cluster):
"""Retrieve the value of one cluster."""
if _is_list(cluster):
return [self.get(field, c) for c in cluster]
assert field in self._fields
default = self._fields[field]
return self._data.get(cluster, {}).get(field, default)
|
python
|
def get(self, field, cluster):
"""Retrieve the value of one cluster."""
if _is_list(cluster):
return [self.get(field, c) for c in cluster]
assert field in self._fields
default = self._fields[field]
return self._data.get(cluster, {}).get(field, default)
|
[
"def",
"get",
"(",
"self",
",",
"field",
",",
"cluster",
")",
":",
"if",
"_is_list",
"(",
"cluster",
")",
":",
"return",
"[",
"self",
".",
"get",
"(",
"field",
",",
"c",
")",
"for",
"c",
"in",
"cluster",
"]",
"assert",
"field",
"in",
"self",
".",
"_fields",
"default",
"=",
"self",
".",
"_fields",
"[",
"field",
"]",
"return",
"self",
".",
"_data",
".",
"get",
"(",
"cluster",
",",
"{",
"}",
")",
".",
"get",
"(",
"field",
",",
"default",
")"
] |
Retrieve the value of one cluster.
|
[
"Retrieve",
"the",
"value",
"of",
"one",
"cluster",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L165-L171
|
7,829
|
kwikteam/phy
|
phy/cluster/_utils.py
|
ClusterMeta.set_from_descendants
|
def set_from_descendants(self, descendants):
"""Update metadata of some clusters given the metadata of their
ascendants."""
for field in self.fields:
# This gives a set of metadata values of all the parents
# of any new cluster.
candidates = defaultdict(set)
for old, new in descendants:
candidates[new].add(self.get(field, old))
# Loop over all new clusters.
for new, vals in candidates.items():
vals = list(vals)
default = self._fields[field]
# If all the parents have the same value, assign it to
# the new cluster if it is not the default.
if len(vals) == 1 and vals[0] != default:
self.set(field, new, vals[0])
|
python
|
def set_from_descendants(self, descendants):
"""Update metadata of some clusters given the metadata of their
ascendants."""
for field in self.fields:
# This gives a set of metadata values of all the parents
# of any new cluster.
candidates = defaultdict(set)
for old, new in descendants:
candidates[new].add(self.get(field, old))
# Loop over all new clusters.
for new, vals in candidates.items():
vals = list(vals)
default = self._fields[field]
# If all the parents have the same value, assign it to
# the new cluster if it is not the default.
if len(vals) == 1 and vals[0] != default:
self.set(field, new, vals[0])
|
[
"def",
"set_from_descendants",
"(",
"self",
",",
"descendants",
")",
":",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"# This gives a set of metadata values of all the parents",
"# of any new cluster.",
"candidates",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"old",
",",
"new",
"in",
"descendants",
":",
"candidates",
"[",
"new",
"]",
".",
"add",
"(",
"self",
".",
"get",
"(",
"field",
",",
"old",
")",
")",
"# Loop over all new clusters.",
"for",
"new",
",",
"vals",
"in",
"candidates",
".",
"items",
"(",
")",
":",
"vals",
"=",
"list",
"(",
"vals",
")",
"default",
"=",
"self",
".",
"_fields",
"[",
"field",
"]",
"# If all the parents have the same value, assign it to",
"# the new cluster if it is not the default.",
"if",
"len",
"(",
"vals",
")",
"==",
"1",
"and",
"vals",
"[",
"0",
"]",
"!=",
"default",
":",
"self",
".",
"set",
"(",
"field",
",",
"new",
",",
"vals",
"[",
"0",
"]",
")"
] |
Update metadata of some clusters given the metadata of their
ascendants.
|
[
"Update",
"metadata",
"of",
"some",
"clusters",
"given",
"the",
"metadata",
"of",
"their",
"ascendants",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L173-L191
|
7,830
|
kwikteam/phy
|
phy/cluster/_utils.py
|
ClusterMeta.undo
|
def undo(self):
"""Undo the last metadata change.
Returns
-------
up : UpdateInfo instance
"""
args = self._undo_stack.back()
if args is None:
return
self._data = deepcopy(self._data_base)
for clusters, field, value, up, undo_state in self._undo_stack:
if clusters is not None:
self.set(field, clusters, value, add_to_stack=False)
# Return the UpdateInfo instance of the undo action.
up, undo_state = args[-2:]
up.history = 'undo'
up.undo_state = undo_state
self.emit('cluster', up)
return up
|
python
|
def undo(self):
"""Undo the last metadata change.
Returns
-------
up : UpdateInfo instance
"""
args = self._undo_stack.back()
if args is None:
return
self._data = deepcopy(self._data_base)
for clusters, field, value, up, undo_state in self._undo_stack:
if clusters is not None:
self.set(field, clusters, value, add_to_stack=False)
# Return the UpdateInfo instance of the undo action.
up, undo_state = args[-2:]
up.history = 'undo'
up.undo_state = undo_state
self.emit('cluster', up)
return up
|
[
"def",
"undo",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"_undo_stack",
".",
"back",
"(",
")",
"if",
"args",
"is",
"None",
":",
"return",
"self",
".",
"_data",
"=",
"deepcopy",
"(",
"self",
".",
"_data_base",
")",
"for",
"clusters",
",",
"field",
",",
"value",
",",
"up",
",",
"undo_state",
"in",
"self",
".",
"_undo_stack",
":",
"if",
"clusters",
"is",
"not",
"None",
":",
"self",
".",
"set",
"(",
"field",
",",
"clusters",
",",
"value",
",",
"add_to_stack",
"=",
"False",
")",
"# Return the UpdateInfo instance of the undo action.",
"up",
",",
"undo_state",
"=",
"args",
"[",
"-",
"2",
":",
"]",
"up",
".",
"history",
"=",
"'undo'",
"up",
".",
"undo_state",
"=",
"undo_state",
"self",
".",
"emit",
"(",
"'cluster'",
",",
"up",
")",
"return",
"up"
] |
Undo the last metadata change.
Returns
-------
up : UpdateInfo instance
|
[
"Undo",
"the",
"last",
"metadata",
"change",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L194-L217
|
7,831
|
kwikteam/phy
|
phy/cluster/_utils.py
|
ClusterMeta.redo
|
def redo(self):
"""Redo the next metadata change.
Returns
-------
up : UpdateInfo instance
"""
args = self._undo_stack.forward()
if args is None:
return
clusters, field, value, up, undo_state = args
self.set(field, clusters, value, add_to_stack=False)
# Return the UpdateInfo instance of the redo action.
up.history = 'redo'
self.emit('cluster', up)
return up
|
python
|
def redo(self):
"""Redo the next metadata change.
Returns
-------
up : UpdateInfo instance
"""
args = self._undo_stack.forward()
if args is None:
return
clusters, field, value, up, undo_state = args
self.set(field, clusters, value, add_to_stack=False)
# Return the UpdateInfo instance of the redo action.
up.history = 'redo'
self.emit('cluster', up)
return up
|
[
"def",
"redo",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"_undo_stack",
".",
"forward",
"(",
")",
"if",
"args",
"is",
"None",
":",
"return",
"clusters",
",",
"field",
",",
"value",
",",
"up",
",",
"undo_state",
"=",
"args",
"self",
".",
"set",
"(",
"field",
",",
"clusters",
",",
"value",
",",
"add_to_stack",
"=",
"False",
")",
"# Return the UpdateInfo instance of the redo action.",
"up",
".",
"history",
"=",
"'redo'",
"self",
".",
"emit",
"(",
"'cluster'",
",",
"up",
")",
"return",
"up"
] |
Redo the next metadata change.
Returns
-------
up : UpdateInfo instance
|
[
"Redo",
"the",
"next",
"metadata",
"change",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_utils.py#L219-L237
|
7,832
|
kwikteam/phy
|
phy/plot/utils.py
|
_get_boxes
|
def _get_boxes(pos, size=None, margin=0, keep_aspect_ratio=True):
"""Generate non-overlapping boxes in NDC from a set of positions."""
# Get x, y.
pos = np.asarray(pos, dtype=np.float64)
x, y = pos.T
x = x[:, np.newaxis]
y = y[:, np.newaxis]
w, h = size if size is not None else _get_box_size(x, y, margin=margin)
x0, y0 = x - w, y - h
x1, y1 = x + w, y + h
# Renormalize the whole thing by keeping the aspect ratio.
x0min, y0min, x1max, y1max = x0.min(), y0.min(), x1.max(), y1.max()
if not keep_aspect_ratio:
b = (x0min, y0min, x1max, y1max)
else:
dx = x1max - x0min
dy = y1max - y0min
if dx > dy:
b = (x0min, (y1max + y0min) / 2. - dx / 2.,
x1max, (y1max + y0min) / 2. + dx / 2.)
else:
b = ((x1max + x0min) / 2. - dy / 2., y0min,
(x1max + x0min) / 2. + dy / 2., y1max)
r = Range(from_bounds=b,
to_bounds=(-1, -1, 1, 1))
return np.c_[r.apply(np.c_[x0, y0]), r.apply(np.c_[x1, y1])]
|
python
|
def _get_boxes(pos, size=None, margin=0, keep_aspect_ratio=True):
"""Generate non-overlapping boxes in NDC from a set of positions."""
# Get x, y.
pos = np.asarray(pos, dtype=np.float64)
x, y = pos.T
x = x[:, np.newaxis]
y = y[:, np.newaxis]
w, h = size if size is not None else _get_box_size(x, y, margin=margin)
x0, y0 = x - w, y - h
x1, y1 = x + w, y + h
# Renormalize the whole thing by keeping the aspect ratio.
x0min, y0min, x1max, y1max = x0.min(), y0.min(), x1.max(), y1.max()
if not keep_aspect_ratio:
b = (x0min, y0min, x1max, y1max)
else:
dx = x1max - x0min
dy = y1max - y0min
if dx > dy:
b = (x0min, (y1max + y0min) / 2. - dx / 2.,
x1max, (y1max + y0min) / 2. + dx / 2.)
else:
b = ((x1max + x0min) / 2. - dy / 2., y0min,
(x1max + x0min) / 2. + dy / 2., y1max)
r = Range(from_bounds=b,
to_bounds=(-1, -1, 1, 1))
return np.c_[r.apply(np.c_[x0, y0]), r.apply(np.c_[x1, y1])]
|
[
"def",
"_get_boxes",
"(",
"pos",
",",
"size",
"=",
"None",
",",
"margin",
"=",
"0",
",",
"keep_aspect_ratio",
"=",
"True",
")",
":",
"# Get x, y.",
"pos",
"=",
"np",
".",
"asarray",
"(",
"pos",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"x",
",",
"y",
"=",
"pos",
".",
"T",
"x",
"=",
"x",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"y",
"=",
"y",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"w",
",",
"h",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_get_box_size",
"(",
"x",
",",
"y",
",",
"margin",
"=",
"margin",
")",
"x0",
",",
"y0",
"=",
"x",
"-",
"w",
",",
"y",
"-",
"h",
"x1",
",",
"y1",
"=",
"x",
"+",
"w",
",",
"y",
"+",
"h",
"# Renormalize the whole thing by keeping the aspect ratio.",
"x0min",
",",
"y0min",
",",
"x1max",
",",
"y1max",
"=",
"x0",
".",
"min",
"(",
")",
",",
"y0",
".",
"min",
"(",
")",
",",
"x1",
".",
"max",
"(",
")",
",",
"y1",
".",
"max",
"(",
")",
"if",
"not",
"keep_aspect_ratio",
":",
"b",
"=",
"(",
"x0min",
",",
"y0min",
",",
"x1max",
",",
"y1max",
")",
"else",
":",
"dx",
"=",
"x1max",
"-",
"x0min",
"dy",
"=",
"y1max",
"-",
"y0min",
"if",
"dx",
">",
"dy",
":",
"b",
"=",
"(",
"x0min",
",",
"(",
"y1max",
"+",
"y0min",
")",
"/",
"2.",
"-",
"dx",
"/",
"2.",
",",
"x1max",
",",
"(",
"y1max",
"+",
"y0min",
")",
"/",
"2.",
"+",
"dx",
"/",
"2.",
")",
"else",
":",
"b",
"=",
"(",
"(",
"x1max",
"+",
"x0min",
")",
"/",
"2.",
"-",
"dy",
"/",
"2.",
",",
"y0min",
",",
"(",
"x1max",
"+",
"x0min",
")",
"/",
"2.",
"+",
"dy",
"/",
"2.",
",",
"y1max",
")",
"r",
"=",
"Range",
"(",
"from_bounds",
"=",
"b",
",",
"to_bounds",
"=",
"(",
"-",
"1",
",",
"-",
"1",
",",
"1",
",",
"1",
")",
")",
"return",
"np",
".",
"c_",
"[",
"r",
".",
"apply",
"(",
"np",
".",
"c_",
"[",
"x0",
",",
"y0",
"]",
")",
",",
"r",
".",
"apply",
"(",
"np",
".",
"c_",
"[",
"x1",
",",
"y1",
"]",
")",
"]"
] |
Generate non-overlapping boxes in NDC from a set of positions.
|
[
"Generate",
"non",
"-",
"overlapping",
"boxes",
"in",
"NDC",
"from",
"a",
"set",
"of",
"positions",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/utils.py#L76-L105
|
7,833
|
kwikteam/phy
|
phy/plot/utils.py
|
_get_texture
|
def _get_texture(arr, default, n_items, from_bounds):
"""Prepare data to be uploaded as a texture.
The from_bounds must be specified.
"""
if not hasattr(default, '__len__'): # pragma: no cover
default = [default]
n_cols = len(default)
if arr is None: # pragma: no cover
arr = np.tile(default, (n_items, 1))
assert arr.shape == (n_items, n_cols)
# Convert to 3D texture.
arr = arr[np.newaxis, ...].astype(np.float64)
assert arr.shape == (1, n_items, n_cols)
# NOTE: we need to cast the texture to [0., 1.] (float texture).
# This is easy as soon as we assume that the signal bounds are in
# [-1, 1].
assert len(from_bounds) == 2
m, M = map(float, from_bounds)
assert np.all(arr >= m)
assert np.all(arr <= M)
arr = (arr - m) / (M - m)
assert np.all(arr >= 0)
assert np.all(arr <= 1.)
return arr
|
python
|
def _get_texture(arr, default, n_items, from_bounds):
"""Prepare data to be uploaded as a texture.
The from_bounds must be specified.
"""
if not hasattr(default, '__len__'): # pragma: no cover
default = [default]
n_cols = len(default)
if arr is None: # pragma: no cover
arr = np.tile(default, (n_items, 1))
assert arr.shape == (n_items, n_cols)
# Convert to 3D texture.
arr = arr[np.newaxis, ...].astype(np.float64)
assert arr.shape == (1, n_items, n_cols)
# NOTE: we need to cast the texture to [0., 1.] (float texture).
# This is easy as soon as we assume that the signal bounds are in
# [-1, 1].
assert len(from_bounds) == 2
m, M = map(float, from_bounds)
assert np.all(arr >= m)
assert np.all(arr <= M)
arr = (arr - m) / (M - m)
assert np.all(arr >= 0)
assert np.all(arr <= 1.)
return arr
|
[
"def",
"_get_texture",
"(",
"arr",
",",
"default",
",",
"n_items",
",",
"from_bounds",
")",
":",
"if",
"not",
"hasattr",
"(",
"default",
",",
"'__len__'",
")",
":",
"# pragma: no cover",
"default",
"=",
"[",
"default",
"]",
"n_cols",
"=",
"len",
"(",
"default",
")",
"if",
"arr",
"is",
"None",
":",
"# pragma: no cover",
"arr",
"=",
"np",
".",
"tile",
"(",
"default",
",",
"(",
"n_items",
",",
"1",
")",
")",
"assert",
"arr",
".",
"shape",
"==",
"(",
"n_items",
",",
"n_cols",
")",
"# Convert to 3D texture.",
"arr",
"=",
"arr",
"[",
"np",
".",
"newaxis",
",",
"...",
"]",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"assert",
"arr",
".",
"shape",
"==",
"(",
"1",
",",
"n_items",
",",
"n_cols",
")",
"# NOTE: we need to cast the texture to [0., 1.] (float texture).",
"# This is easy as soon as we assume that the signal bounds are in",
"# [-1, 1].",
"assert",
"len",
"(",
"from_bounds",
")",
"==",
"2",
"m",
",",
"M",
"=",
"map",
"(",
"float",
",",
"from_bounds",
")",
"assert",
"np",
".",
"all",
"(",
"arr",
">=",
"m",
")",
"assert",
"np",
".",
"all",
"(",
"arr",
"<=",
"M",
")",
"arr",
"=",
"(",
"arr",
"-",
"m",
")",
"/",
"(",
"M",
"-",
"m",
")",
"assert",
"np",
".",
"all",
"(",
"arr",
">=",
"0",
")",
"assert",
"np",
".",
"all",
"(",
"arr",
"<=",
"1.",
")",
"return",
"arr"
] |
Prepare data to be uploaded as a texture.
The from_bounds must be specified.
|
[
"Prepare",
"data",
"to",
"be",
"uploaded",
"as",
"a",
"texture",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/utils.py#L122-L147
|
7,834
|
kwikteam/phy
|
phy/plot/utils.py
|
_get_array
|
def _get_array(val, shape, default=None, dtype=np.float64):
"""Ensure an object is an array with the specified shape."""
assert val is not None or default is not None
if hasattr(val, '__len__') and len(val) == 0: # pragma: no cover
val = None
# Do nothing if the array is already correct.
if (isinstance(val, np.ndarray) and
val.shape == shape and
val.dtype == dtype):
return val
out = np.zeros(shape, dtype=dtype)
# This solves `ValueError: could not broadcast input array from shape (n)
# into shape (n, 1)`.
if val is not None and isinstance(val, np.ndarray):
if val.size == out.size:
val = val.reshape(out.shape)
out.flat[:] = val if val is not None else default
assert out.shape == shape
return out
|
python
|
def _get_array(val, shape, default=None, dtype=np.float64):
"""Ensure an object is an array with the specified shape."""
assert val is not None or default is not None
if hasattr(val, '__len__') and len(val) == 0: # pragma: no cover
val = None
# Do nothing if the array is already correct.
if (isinstance(val, np.ndarray) and
val.shape == shape and
val.dtype == dtype):
return val
out = np.zeros(shape, dtype=dtype)
# This solves `ValueError: could not broadcast input array from shape (n)
# into shape (n, 1)`.
if val is not None and isinstance(val, np.ndarray):
if val.size == out.size:
val = val.reshape(out.shape)
out.flat[:] = val if val is not None else default
assert out.shape == shape
return out
|
[
"def",
"_get_array",
"(",
"val",
",",
"shape",
",",
"default",
"=",
"None",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
":",
"assert",
"val",
"is",
"not",
"None",
"or",
"default",
"is",
"not",
"None",
"if",
"hasattr",
"(",
"val",
",",
"'__len__'",
")",
"and",
"len",
"(",
"val",
")",
"==",
"0",
":",
"# pragma: no cover",
"val",
"=",
"None",
"# Do nothing if the array is already correct.",
"if",
"(",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
"and",
"val",
".",
"shape",
"==",
"shape",
"and",
"val",
".",
"dtype",
"==",
"dtype",
")",
":",
"return",
"val",
"out",
"=",
"np",
".",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"# This solves `ValueError: could not broadcast input array from shape (n)",
"# into shape (n, 1)`.",
"if",
"val",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"val",
".",
"size",
"==",
"out",
".",
"size",
":",
"val",
"=",
"val",
".",
"reshape",
"(",
"out",
".",
"shape",
")",
"out",
".",
"flat",
"[",
":",
"]",
"=",
"val",
"if",
"val",
"is",
"not",
"None",
"else",
"default",
"assert",
"out",
".",
"shape",
"==",
"shape",
"return",
"out"
] |
Ensure an object is an array with the specified shape.
|
[
"Ensure",
"an",
"object",
"is",
"an",
"array",
"with",
"the",
"specified",
"shape",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/utils.py#L150-L168
|
7,835
|
kwikteam/phy
|
phy/plot/utils.py
|
_get_index
|
def _get_index(n_items, item_size, n):
"""Prepare an index attribute for GPU uploading."""
index = np.arange(n_items)
index = np.repeat(index, item_size)
index = index.astype(np.float64)
assert index.shape == (n,)
return index
|
python
|
def _get_index(n_items, item_size, n):
"""Prepare an index attribute for GPU uploading."""
index = np.arange(n_items)
index = np.repeat(index, item_size)
index = index.astype(np.float64)
assert index.shape == (n,)
return index
|
[
"def",
"_get_index",
"(",
"n_items",
",",
"item_size",
",",
"n",
")",
":",
"index",
"=",
"np",
".",
"arange",
"(",
"n_items",
")",
"index",
"=",
"np",
".",
"repeat",
"(",
"index",
",",
"item_size",
")",
"index",
"=",
"index",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"assert",
"index",
".",
"shape",
"==",
"(",
"n",
",",
")",
"return",
"index"
] |
Prepare an index attribute for GPU uploading.
|
[
"Prepare",
"an",
"index",
"attribute",
"for",
"GPU",
"uploading",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/utils.py#L225-L231
|
7,836
|
kwikteam/phy
|
phy/plot/utils.py
|
_load_shader
|
def _load_shader(filename):
"""Load a shader file."""
curdir = op.dirname(op.realpath(__file__))
glsl_path = op.join(curdir, 'glsl')
path = op.join(glsl_path, filename)
with open(path, 'r') as f:
return f.read()
|
python
|
def _load_shader(filename):
"""Load a shader file."""
curdir = op.dirname(op.realpath(__file__))
glsl_path = op.join(curdir, 'glsl')
path = op.join(glsl_path, filename)
with open(path, 'r') as f:
return f.read()
|
[
"def",
"_load_shader",
"(",
"filename",
")",
":",
"curdir",
"=",
"op",
".",
"dirname",
"(",
"op",
".",
"realpath",
"(",
"__file__",
")",
")",
"glsl_path",
"=",
"op",
".",
"join",
"(",
"curdir",
",",
"'glsl'",
")",
"path",
"=",
"op",
".",
"join",
"(",
"glsl_path",
",",
"filename",
")",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] |
Load a shader file.
|
[
"Load",
"a",
"shader",
"file",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/utils.py#L242-L248
|
7,837
|
kwikteam/phy
|
phy/utils/_color.py
|
_random_color
|
def _random_color(h_range=(0., 1.),
s_range=(.5, 1.),
v_range=(.5, 1.),
):
"""Generate a random RGB color."""
h, s, v = uniform(*h_range), uniform(*s_range), uniform(*v_range)
r, g, b = hsv_to_rgb(np.array([[[h, s, v]]])).flat
return r, g, b
|
python
|
def _random_color(h_range=(0., 1.),
s_range=(.5, 1.),
v_range=(.5, 1.),
):
"""Generate a random RGB color."""
h, s, v = uniform(*h_range), uniform(*s_range), uniform(*v_range)
r, g, b = hsv_to_rgb(np.array([[[h, s, v]]])).flat
return r, g, b
|
[
"def",
"_random_color",
"(",
"h_range",
"=",
"(",
"0.",
",",
"1.",
")",
",",
"s_range",
"=",
"(",
".5",
",",
"1.",
")",
",",
"v_range",
"=",
"(",
".5",
",",
"1.",
")",
",",
")",
":",
"h",
",",
"s",
",",
"v",
"=",
"uniform",
"(",
"*",
"h_range",
")",
",",
"uniform",
"(",
"*",
"s_range",
")",
",",
"uniform",
"(",
"*",
"v_range",
")",
"r",
",",
"g",
",",
"b",
"=",
"hsv_to_rgb",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"[",
"h",
",",
"s",
",",
"v",
"]",
"]",
"]",
")",
")",
".",
"flat",
"return",
"r",
",",
"g",
",",
"b"
] |
Generate a random RGB color.
|
[
"Generate",
"a",
"random",
"RGB",
"color",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/_color.py#L18-L25
|
7,838
|
kwikteam/phy
|
phy/utils/_color.py
|
_is_bright
|
def _is_bright(rgb):
"""Return whether a RGB color is bright or not."""
r, g, b = rgb
gray = 0.299 * r + 0.587 * g + 0.114 * b
return gray >= .5
|
python
|
def _is_bright(rgb):
"""Return whether a RGB color is bright or not."""
r, g, b = rgb
gray = 0.299 * r + 0.587 * g + 0.114 * b
return gray >= .5
|
[
"def",
"_is_bright",
"(",
"rgb",
")",
":",
"r",
",",
"g",
",",
"b",
"=",
"rgb",
"gray",
"=",
"0.299",
"*",
"r",
"+",
"0.587",
"*",
"g",
"+",
"0.114",
"*",
"b",
"return",
"gray",
">=",
".5"
] |
Return whether a RGB color is bright or not.
|
[
"Return",
"whether",
"a",
"RGB",
"color",
"is",
"bright",
"or",
"not",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/_color.py#L28-L32
|
7,839
|
kwikteam/phy
|
phy/utils/_types.py
|
_bunchify
|
def _bunchify(b):
"""Ensure all dict elements are Bunch."""
assert isinstance(b, dict)
b = Bunch(b)
for k in b:
if isinstance(b[k], dict):
b[k] = Bunch(b[k])
return b
|
python
|
def _bunchify(b):
"""Ensure all dict elements are Bunch."""
assert isinstance(b, dict)
b = Bunch(b)
for k in b:
if isinstance(b[k], dict):
b[k] = Bunch(b[k])
return b
|
[
"def",
"_bunchify",
"(",
"b",
")",
":",
"assert",
"isinstance",
"(",
"b",
",",
"dict",
")",
"b",
"=",
"Bunch",
"(",
"b",
")",
"for",
"k",
"in",
"b",
":",
"if",
"isinstance",
"(",
"b",
"[",
"k",
"]",
",",
"dict",
")",
":",
"b",
"[",
"k",
"]",
"=",
"Bunch",
"(",
"b",
"[",
"k",
"]",
")",
"return",
"b"
] |
Ensure all dict elements are Bunch.
|
[
"Ensure",
"all",
"dict",
"elements",
"are",
"Bunch",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/_types.py#L34-L41
|
7,840
|
kwikteam/phy
|
phy/utils/_types.py
|
_as_list
|
def _as_list(obj):
"""Ensure an object is a list."""
if obj is None:
return None
elif isinstance(obj, string_types):
return [obj]
elif isinstance(obj, tuple):
return list(obj)
elif not hasattr(obj, '__len__'):
return [obj]
else:
return obj
|
python
|
def _as_list(obj):
"""Ensure an object is a list."""
if obj is None:
return None
elif isinstance(obj, string_types):
return [obj]
elif isinstance(obj, tuple):
return list(obj)
elif not hasattr(obj, '__len__'):
return [obj]
else:
return obj
|
[
"def",
"_as_list",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"return",
"[",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"return",
"list",
"(",
"obj",
")",
"elif",
"not",
"hasattr",
"(",
"obj",
",",
"'__len__'",
")",
":",
"return",
"[",
"obj",
"]",
"else",
":",
"return",
"obj"
] |
Ensure an object is a list.
|
[
"Ensure",
"an",
"object",
"is",
"a",
"list",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/_types.py#L67-L78
|
7,841
|
kwikteam/phy
|
phy/utils/_types.py
|
_as_array
|
def _as_array(arr, dtype=None):
"""Convert an object to a numerical NumPy array.
Avoid a copy if possible.
"""
if arr is None:
return None
if isinstance(arr, np.ndarray) and dtype is None:
return arr
if isinstance(arr, integer_types + (float,)):
arr = [arr]
out = np.asarray(arr)
if dtype is not None:
if out.dtype != dtype:
out = out.astype(dtype)
if out.dtype not in _ACCEPTED_ARRAY_DTYPES:
raise ValueError("'arr' seems to have an invalid dtype: "
"{0:s}".format(str(out.dtype)))
return out
|
python
|
def _as_array(arr, dtype=None):
"""Convert an object to a numerical NumPy array.
Avoid a copy if possible.
"""
if arr is None:
return None
if isinstance(arr, np.ndarray) and dtype is None:
return arr
if isinstance(arr, integer_types + (float,)):
arr = [arr]
out = np.asarray(arr)
if dtype is not None:
if out.dtype != dtype:
out = out.astype(dtype)
if out.dtype not in _ACCEPTED_ARRAY_DTYPES:
raise ValueError("'arr' seems to have an invalid dtype: "
"{0:s}".format(str(out.dtype)))
return out
|
[
"def",
"_as_array",
"(",
"arr",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"arr",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
"and",
"dtype",
"is",
"None",
":",
"return",
"arr",
"if",
"isinstance",
"(",
"arr",
",",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
":",
"arr",
"=",
"[",
"arr",
"]",
"out",
"=",
"np",
".",
"asarray",
"(",
"arr",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"if",
"out",
".",
"dtype",
"!=",
"dtype",
":",
"out",
"=",
"out",
".",
"astype",
"(",
"dtype",
")",
"if",
"out",
".",
"dtype",
"not",
"in",
"_ACCEPTED_ARRAY_DTYPES",
":",
"raise",
"ValueError",
"(",
"\"'arr' seems to have an invalid dtype: \"",
"\"{0:s}\"",
".",
"format",
"(",
"str",
"(",
"out",
".",
"dtype",
")",
")",
")",
"return",
"out"
] |
Convert an object to a numerical NumPy array.
Avoid a copy if possible.
|
[
"Convert",
"an",
"object",
"to",
"a",
"numerical",
"NumPy",
"array",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/_types.py#L85-L104
|
7,842
|
kwikteam/phy
|
phy/plot/transform.py
|
_glslify
|
def _glslify(r):
"""Transform a string or a n-tuple to a valid GLSL expression."""
if isinstance(r, string_types):
return r
else:
assert 2 <= len(r) <= 4
return 'vec{}({})'.format(len(r), ', '.join(map(str, r)))
|
python
|
def _glslify(r):
"""Transform a string or a n-tuple to a valid GLSL expression."""
if isinstance(r, string_types):
return r
else:
assert 2 <= len(r) <= 4
return 'vec{}({})'.format(len(r), ', '.join(map(str, r)))
|
[
"def",
"_glslify",
"(",
"r",
")",
":",
"if",
"isinstance",
"(",
"r",
",",
"string_types",
")",
":",
"return",
"r",
"else",
":",
"assert",
"2",
"<=",
"len",
"(",
"r",
")",
"<=",
"4",
"return",
"'vec{}({})'",
".",
"format",
"(",
"len",
"(",
"r",
")",
",",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"r",
")",
")",
")"
] |
Transform a string or a n-tuple to a valid GLSL expression.
|
[
"Transform",
"a",
"string",
"or",
"a",
"n",
"-",
"tuple",
"to",
"a",
"valid",
"GLSL",
"expression",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L48-L54
|
7,843
|
kwikteam/phy
|
phy/plot/transform.py
|
TransformChain.get
|
def get(self, class_name):
"""Get a transform in the chain from its name."""
for transform in self.cpu_transforms + self.gpu_transforms:
if transform.__class__.__name__ == class_name:
return transform
|
python
|
def get(self, class_name):
"""Get a transform in the chain from its name."""
for transform in self.cpu_transforms + self.gpu_transforms:
if transform.__class__.__name__ == class_name:
return transform
|
[
"def",
"get",
"(",
"self",
",",
"class_name",
")",
":",
"for",
"transform",
"in",
"self",
".",
"cpu_transforms",
"+",
"self",
".",
"gpu_transforms",
":",
"if",
"transform",
".",
"__class__",
".",
"__name__",
"==",
"class_name",
":",
"return",
"transform"
] |
Get a transform in the chain from its name.
|
[
"Get",
"a",
"transform",
"in",
"the",
"chain",
"from",
"its",
"name",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L291-L295
|
7,844
|
kwikteam/phy
|
phy/plot/transform.py
|
TransformChain.remove
|
def remove(self, name):
"""Remove a transform in the chain."""
cpu_transforms = self._remove_transform(self.cpu_transforms, name)
gpu_transforms = self._remove_transform(self.gpu_transforms, name)
return (TransformChain().add_on_cpu(cpu_transforms).
add_on_gpu(gpu_transforms))
|
python
|
def remove(self, name):
"""Remove a transform in the chain."""
cpu_transforms = self._remove_transform(self.cpu_transforms, name)
gpu_transforms = self._remove_transform(self.gpu_transforms, name)
return (TransformChain().add_on_cpu(cpu_transforms).
add_on_gpu(gpu_transforms))
|
[
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"cpu_transforms",
"=",
"self",
".",
"_remove_transform",
"(",
"self",
".",
"cpu_transforms",
",",
"name",
")",
"gpu_transforms",
"=",
"self",
".",
"_remove_transform",
"(",
"self",
".",
"gpu_transforms",
",",
"name",
")",
"return",
"(",
"TransformChain",
"(",
")",
".",
"add_on_cpu",
"(",
"cpu_transforms",
")",
".",
"add_on_gpu",
"(",
"gpu_transforms",
")",
")"
] |
Remove a transform in the chain.
|
[
"Remove",
"a",
"transform",
"in",
"the",
"chain",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L300-L305
|
7,845
|
kwikteam/phy
|
phy/plot/transform.py
|
TransformChain.apply
|
def apply(self, arr):
"""Apply all CPU transforms on an array."""
for t in self.cpu_transforms:
arr = t.apply(arr)
return arr
|
python
|
def apply(self, arr):
"""Apply all CPU transforms on an array."""
for t in self.cpu_transforms:
arr = t.apply(arr)
return arr
|
[
"def",
"apply",
"(",
"self",
",",
"arr",
")",
":",
"for",
"t",
"in",
"self",
".",
"cpu_transforms",
":",
"arr",
"=",
"t",
".",
"apply",
"(",
"arr",
")",
"return",
"arr"
] |
Apply all CPU transforms on an array.
|
[
"Apply",
"all",
"CPU",
"transforms",
"on",
"an",
"array",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L307-L311
|
7,846
|
kwikteam/phy
|
phy/plot/transform.py
|
TransformChain.inverse
|
def inverse(self):
"""Return the inverse chain of transforms."""
transforms = self.cpu_transforms + self.gpu_transforms
inv_transforms = [transform.inverse()
for transform in transforms[::-1]]
return TransformChain().add_on_cpu(inv_transforms)
|
python
|
def inverse(self):
"""Return the inverse chain of transforms."""
transforms = self.cpu_transforms + self.gpu_transforms
inv_transforms = [transform.inverse()
for transform in transforms[::-1]]
return TransformChain().add_on_cpu(inv_transforms)
|
[
"def",
"inverse",
"(",
"self",
")",
":",
"transforms",
"=",
"self",
".",
"cpu_transforms",
"+",
"self",
".",
"gpu_transforms",
"inv_transforms",
"=",
"[",
"transform",
".",
"inverse",
"(",
")",
"for",
"transform",
"in",
"transforms",
"[",
":",
":",
"-",
"1",
"]",
"]",
"return",
"TransformChain",
"(",
")",
".",
"add_on_cpu",
"(",
"inv_transforms",
")"
] |
Return the inverse chain of transforms.
|
[
"Return",
"the",
"inverse",
"chain",
"of",
"transforms",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L313-L318
|
7,847
|
kwikteam/phy
|
phy/utils/event.py
|
EventEmitter._create_emitter
|
def _create_emitter(self, event):
"""Create a method that emits an event of the same name."""
if not hasattr(self, event):
setattr(self, event,
lambda *args, **kwargs: self.emit(event, *args, **kwargs))
|
python
|
def _create_emitter(self, event):
"""Create a method that emits an event of the same name."""
if not hasattr(self, event):
setattr(self, event,
lambda *args, **kwargs: self.emit(event, *args, **kwargs))
|
[
"def",
"_create_emitter",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"event",
")",
":",
"setattr",
"(",
"self",
",",
"event",
",",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"self",
".",
"emit",
"(",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] |
Create a method that emits an event of the same name.
|
[
"Create",
"a",
"method",
"that",
"emits",
"an",
"event",
"of",
"the",
"same",
"name",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L62-L66
|
7,848
|
kwikteam/phy
|
phy/utils/event.py
|
EventEmitter.connect
|
def connect(self, func=None, event=None, set_method=False):
"""Register a callback function to a given event.
To register a callback function to the `spam` event, where `obj` is
an instance of a class deriving from `EventEmitter`:
```python
@obj.connect
def on_spam(arg1, arg2):
pass
```
This is called when `obj.emit('spam', arg1, arg2)` is called.
Several callback functions can be registered for a given event.
The registration order is conserved and may matter in applications.
"""
if func is None:
return partial(self.connect, set_method=set_method)
# Get the event name from the function.
if event is None:
event = self._get_on_name(func)
# We register the callback function.
self._callbacks[event].append(func)
# A new method self.event() emitting the event is created.
if set_method:
self._create_emitter(event)
return func
|
python
|
def connect(self, func=None, event=None, set_method=False):
"""Register a callback function to a given event.
To register a callback function to the `spam` event, where `obj` is
an instance of a class deriving from `EventEmitter`:
```python
@obj.connect
def on_spam(arg1, arg2):
pass
```
This is called when `obj.emit('spam', arg1, arg2)` is called.
Several callback functions can be registered for a given event.
The registration order is conserved and may matter in applications.
"""
if func is None:
return partial(self.connect, set_method=set_method)
# Get the event name from the function.
if event is None:
event = self._get_on_name(func)
# We register the callback function.
self._callbacks[event].append(func)
# A new method self.event() emitting the event is created.
if set_method:
self._create_emitter(event)
return func
|
[
"def",
"connect",
"(",
"self",
",",
"func",
"=",
"None",
",",
"event",
"=",
"None",
",",
"set_method",
"=",
"False",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"partial",
"(",
"self",
".",
"connect",
",",
"set_method",
"=",
"set_method",
")",
"# Get the event name from the function.",
"if",
"event",
"is",
"None",
":",
"event",
"=",
"self",
".",
"_get_on_name",
"(",
"func",
")",
"# We register the callback function.",
"self",
".",
"_callbacks",
"[",
"event",
"]",
".",
"append",
"(",
"func",
")",
"# A new method self.event() emitting the event is created.",
"if",
"set_method",
":",
"self",
".",
"_create_emitter",
"(",
"event",
")",
"return",
"func"
] |
Register a callback function to a given event.
To register a callback function to the `spam` event, where `obj` is
an instance of a class deriving from `EventEmitter`:
```python
@obj.connect
def on_spam(arg1, arg2):
pass
```
This is called when `obj.emit('spam', arg1, arg2)` is called.
Several callback functions can be registered for a given event.
The registration order is conserved and may matter in applications.
|
[
"Register",
"a",
"callback",
"function",
"to",
"a",
"given",
"event",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L68-L101
|
7,849
|
kwikteam/phy
|
phy/utils/event.py
|
EventEmitter.unconnect
|
def unconnect(self, *funcs):
"""Unconnect specified callback functions."""
for func in funcs:
for callbacks in self._callbacks.values():
if func in callbacks:
callbacks.remove(func)
|
python
|
def unconnect(self, *funcs):
"""Unconnect specified callback functions."""
for func in funcs:
for callbacks in self._callbacks.values():
if func in callbacks:
callbacks.remove(func)
|
[
"def",
"unconnect",
"(",
"self",
",",
"*",
"funcs",
")",
":",
"for",
"func",
"in",
"funcs",
":",
"for",
"callbacks",
"in",
"self",
".",
"_callbacks",
".",
"values",
"(",
")",
":",
"if",
"func",
"in",
"callbacks",
":",
"callbacks",
".",
"remove",
"(",
"func",
")"
] |
Unconnect specified callback functions.
|
[
"Unconnect",
"specified",
"callback",
"functions",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L103-L108
|
7,850
|
kwikteam/phy
|
phy/utils/event.py
|
EventEmitter.emit
|
def emit(self, event, *args, **kwargs):
"""Call all callback functions registered with an event.
Any positional and keyword arguments can be passed here, and they will
be forwarded to the callback functions.
Return the list of callback return results.
"""
callbacks = self._callbacks.get(event, [])
# Call the last callback if this is a single event.
single = kwargs.pop('single', None)
if single and callbacks:
return callbacks[-1](*args, **kwargs)
# Otherwise, return the list of callback outputs.
res = []
for callback in callbacks:
res.append(callback(*args, **kwargs))
return res
|
python
|
def emit(self, event, *args, **kwargs):
"""Call all callback functions registered with an event.
Any positional and keyword arguments can be passed here, and they will
be forwarded to the callback functions.
Return the list of callback return results.
"""
callbacks = self._callbacks.get(event, [])
# Call the last callback if this is a single event.
single = kwargs.pop('single', None)
if single and callbacks:
return callbacks[-1](*args, **kwargs)
# Otherwise, return the list of callback outputs.
res = []
for callback in callbacks:
res.append(callback(*args, **kwargs))
return res
|
[
"def",
"emit",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"callbacks",
"=",
"self",
".",
"_callbacks",
".",
"get",
"(",
"event",
",",
"[",
"]",
")",
"# Call the last callback if this is a single event.",
"single",
"=",
"kwargs",
".",
"pop",
"(",
"'single'",
",",
"None",
")",
"if",
"single",
"and",
"callbacks",
":",
"return",
"callbacks",
"[",
"-",
"1",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Otherwise, return the list of callback outputs.",
"res",
"=",
"[",
"]",
"for",
"callback",
"in",
"callbacks",
":",
"res",
".",
"append",
"(",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"res"
] |
Call all callback functions registered with an event.
Any positional and keyword arguments can be passed here, and they will
be forwarded to the callback functions.
Return the list of callback return results.
|
[
"Call",
"all",
"callback",
"functions",
"registered",
"with",
"an",
"event",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L110-L128
|
7,851
|
kwikteam/phy
|
phy/utils/event.py
|
ProgressReporter.set_progress_message
|
def set_progress_message(self, message, line_break=False):
"""Set a progress message.
The string needs to contain `{progress}`.
"""
end = '\r' if not line_break else None
@self.connect
def on_progress(value, value_max, **kwargs):
kwargs['end'] = None if value == value_max else end
_default_on_progress(message, value, value_max, **kwargs)
|
python
|
def set_progress_message(self, message, line_break=False):
"""Set a progress message.
The string needs to contain `{progress}`.
"""
end = '\r' if not line_break else None
@self.connect
def on_progress(value, value_max, **kwargs):
kwargs['end'] = None if value == value_max else end
_default_on_progress(message, value, value_max, **kwargs)
|
[
"def",
"set_progress_message",
"(",
"self",
",",
"message",
",",
"line_break",
"=",
"False",
")",
":",
"end",
"=",
"'\\r'",
"if",
"not",
"line_break",
"else",
"None",
"@",
"self",
".",
"connect",
"def",
"on_progress",
"(",
"value",
",",
"value_max",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'end'",
"]",
"=",
"None",
"if",
"value",
"==",
"value_max",
"else",
"end",
"_default_on_progress",
"(",
"message",
",",
"value",
",",
"value_max",
",",
"*",
"*",
"kwargs",
")"
] |
Set a progress message.
The string needs to contain `{progress}`.
|
[
"Set",
"a",
"progress",
"message",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L204-L216
|
7,852
|
kwikteam/phy
|
phy/utils/event.py
|
ProgressReporter.set_complete_message
|
def set_complete_message(self, message):
"""Set a complete message."""
@self.connect
def on_complete(**kwargs):
_default_on_complete(message, **kwargs)
|
python
|
def set_complete_message(self, message):
"""Set a complete message."""
@self.connect
def on_complete(**kwargs):
_default_on_complete(message, **kwargs)
|
[
"def",
"set_complete_message",
"(",
"self",
",",
"message",
")",
":",
"@",
"self",
".",
"connect",
"def",
"on_complete",
"(",
"*",
"*",
"kwargs",
")",
":",
"_default_on_complete",
"(",
"message",
",",
"*",
"*",
"kwargs",
")"
] |
Set a complete message.
|
[
"Set",
"a",
"complete",
"message",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L218-L223
|
7,853
|
kwikteam/phy
|
phy/utils/plugin.py
|
get_plugin
|
def get_plugin(name):
"""Get a plugin class from its name."""
for plugin in IPluginRegistry.plugins:
if name in plugin.__name__:
return plugin
raise ValueError("The plugin %s cannot be found." % name)
|
python
|
def get_plugin(name):
"""Get a plugin class from its name."""
for plugin in IPluginRegistry.plugins:
if name in plugin.__name__:
return plugin
raise ValueError("The plugin %s cannot be found." % name)
|
[
"def",
"get_plugin",
"(",
"name",
")",
":",
"for",
"plugin",
"in",
"IPluginRegistry",
".",
"plugins",
":",
"if",
"name",
"in",
"plugin",
".",
"__name__",
":",
"return",
"plugin",
"raise",
"ValueError",
"(",
"\"The plugin %s cannot be found.\"",
"%",
"name",
")"
] |
Get a plugin class from its name.
|
[
"Get",
"a",
"plugin",
"class",
"from",
"its",
"name",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/plugin.py#L50-L55
|
7,854
|
kwikteam/phy
|
phy/utils/plugin.py
|
discover_plugins
|
def discover_plugins(dirs):
"""Discover the plugin classes contained in Python files.
Parameters
----------
dirs : list
List of directory names to scan.
Returns
-------
plugins : list
List of plugin classes.
"""
# Scan all subdirectories recursively.
for path in _iter_plugin_files(dirs):
filename = op.basename(path)
subdir = op.dirname(path)
modname, ext = op.splitext(filename)
file, path, descr = imp.find_module(modname, [subdir])
if file:
# Loading the module registers the plugin in
# IPluginRegistry.
try:
mod = imp.load_module(modname, file, path, descr) # noqa
except Exception as e: # pragma: no cover
logger.exception(e)
finally:
file.close()
return IPluginRegistry.plugins
|
python
|
def discover_plugins(dirs):
"""Discover the plugin classes contained in Python files.
Parameters
----------
dirs : list
List of directory names to scan.
Returns
-------
plugins : list
List of plugin classes.
"""
# Scan all subdirectories recursively.
for path in _iter_plugin_files(dirs):
filename = op.basename(path)
subdir = op.dirname(path)
modname, ext = op.splitext(filename)
file, path, descr = imp.find_module(modname, [subdir])
if file:
# Loading the module registers the plugin in
# IPluginRegistry.
try:
mod = imp.load_module(modname, file, path, descr) # noqa
except Exception as e: # pragma: no cover
logger.exception(e)
finally:
file.close()
return IPluginRegistry.plugins
|
[
"def",
"discover_plugins",
"(",
"dirs",
")",
":",
"# Scan all subdirectories recursively.",
"for",
"path",
"in",
"_iter_plugin_files",
"(",
"dirs",
")",
":",
"filename",
"=",
"op",
".",
"basename",
"(",
"path",
")",
"subdir",
"=",
"op",
".",
"dirname",
"(",
"path",
")",
"modname",
",",
"ext",
"=",
"op",
".",
"splitext",
"(",
"filename",
")",
"file",
",",
"path",
",",
"descr",
"=",
"imp",
".",
"find_module",
"(",
"modname",
",",
"[",
"subdir",
"]",
")",
"if",
"file",
":",
"# Loading the module registers the plugin in",
"# IPluginRegistry.",
"try",
":",
"mod",
"=",
"imp",
".",
"load_module",
"(",
"modname",
",",
"file",
",",
"path",
",",
"descr",
")",
"# noqa",
"except",
"Exception",
"as",
"e",
":",
"# pragma: no cover",
"logger",
".",
"exception",
"(",
"e",
")",
"finally",
":",
"file",
".",
"close",
"(",
")",
"return",
"IPluginRegistry",
".",
"plugins"
] |
Discover the plugin classes contained in Python files.
Parameters
----------
dirs : list
List of directory names to scan.
Returns
-------
plugins : list
List of plugin classes.
|
[
"Discover",
"the",
"plugin",
"classes",
"contained",
"in",
"Python",
"files",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/plugin.py#L81-L112
|
7,855
|
kwikteam/phy
|
phy/gui/gui.py
|
GUI.add_view
|
def add_view(self,
view,
name=None,
position=None,
closable=False,
floatable=True,
floating=None):
"""Add a widget to the main window."""
# Set the name in the view.
view.view_index = self._get_view_index(view)
# The view name is `<class_name><view_index>`, e.g. `MyView0`.
view.name = name or view.__class__.__name__ + str(view.view_index)
# Get the Qt canvas for VisPy and matplotlib views.
widget = _try_get_vispy_canvas(view)
widget = _try_get_matplotlib_canvas(widget)
dock_widget = _create_dock_widget(widget, view.name,
closable=closable,
floatable=floatable,
)
self.addDockWidget(_get_dock_position(position), dock_widget)
if floating is not None:
dock_widget.setFloating(floating)
dock_widget.view = view
# Emit the close_view event when the dock widget is closed.
@dock_widget.connect_
def on_close_widget():
self.emit('close_view', view)
dock_widget.show()
self.emit('add_view', view)
logger.log(5, "Add %s to GUI.", view.name)
return dock_widget
|
python
|
def add_view(self,
view,
name=None,
position=None,
closable=False,
floatable=True,
floating=None):
"""Add a widget to the main window."""
# Set the name in the view.
view.view_index = self._get_view_index(view)
# The view name is `<class_name><view_index>`, e.g. `MyView0`.
view.name = name or view.__class__.__name__ + str(view.view_index)
# Get the Qt canvas for VisPy and matplotlib views.
widget = _try_get_vispy_canvas(view)
widget = _try_get_matplotlib_canvas(widget)
dock_widget = _create_dock_widget(widget, view.name,
closable=closable,
floatable=floatable,
)
self.addDockWidget(_get_dock_position(position), dock_widget)
if floating is not None:
dock_widget.setFloating(floating)
dock_widget.view = view
# Emit the close_view event when the dock widget is closed.
@dock_widget.connect_
def on_close_widget():
self.emit('close_view', view)
dock_widget.show()
self.emit('add_view', view)
logger.log(5, "Add %s to GUI.", view.name)
return dock_widget
|
[
"def",
"add_view",
"(",
"self",
",",
"view",
",",
"name",
"=",
"None",
",",
"position",
"=",
"None",
",",
"closable",
"=",
"False",
",",
"floatable",
"=",
"True",
",",
"floating",
"=",
"None",
")",
":",
"# Set the name in the view.",
"view",
".",
"view_index",
"=",
"self",
".",
"_get_view_index",
"(",
"view",
")",
"# The view name is `<class_name><view_index>`, e.g. `MyView0`.",
"view",
".",
"name",
"=",
"name",
"or",
"view",
".",
"__class__",
".",
"__name__",
"+",
"str",
"(",
"view",
".",
"view_index",
")",
"# Get the Qt canvas for VisPy and matplotlib views.",
"widget",
"=",
"_try_get_vispy_canvas",
"(",
"view",
")",
"widget",
"=",
"_try_get_matplotlib_canvas",
"(",
"widget",
")",
"dock_widget",
"=",
"_create_dock_widget",
"(",
"widget",
",",
"view",
".",
"name",
",",
"closable",
"=",
"closable",
",",
"floatable",
"=",
"floatable",
",",
")",
"self",
".",
"addDockWidget",
"(",
"_get_dock_position",
"(",
"position",
")",
",",
"dock_widget",
")",
"if",
"floating",
"is",
"not",
"None",
":",
"dock_widget",
".",
"setFloating",
"(",
"floating",
")",
"dock_widget",
".",
"view",
"=",
"view",
"# Emit the close_view event when the dock widget is closed.",
"@",
"dock_widget",
".",
"connect_",
"def",
"on_close_widget",
"(",
")",
":",
"self",
".",
"emit",
"(",
"'close_view'",
",",
"view",
")",
"dock_widget",
".",
"show",
"(",
")",
"self",
".",
"emit",
"(",
"'add_view'",
",",
"view",
")",
"logger",
".",
"log",
"(",
"5",
",",
"\"Add %s to GUI.\"",
",",
"view",
".",
"name",
")",
"return",
"dock_widget"
] |
Add a widget to the main window.
|
[
"Add",
"a",
"widget",
"to",
"the",
"main",
"window",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L267-L302
|
7,856
|
kwikteam/phy
|
phy/gui/gui.py
|
GUI.list_views
|
def list_views(self, name='', is_visible=True):
"""List all views which name start with a given string."""
children = self.findChildren(QWidget)
return [child.view for child in children
if isinstance(child, QDockWidget) and
child.view.name.startswith(name) and
(child.isVisible() if is_visible else True) and
child.width() >= 10 and
child.height() >= 10
]
|
python
|
def list_views(self, name='', is_visible=True):
"""List all views which name start with a given string."""
children = self.findChildren(QWidget)
return [child.view for child in children
if isinstance(child, QDockWidget) and
child.view.name.startswith(name) and
(child.isVisible() if is_visible else True) and
child.width() >= 10 and
child.height() >= 10
]
|
[
"def",
"list_views",
"(",
"self",
",",
"name",
"=",
"''",
",",
"is_visible",
"=",
"True",
")",
":",
"children",
"=",
"self",
".",
"findChildren",
"(",
"QWidget",
")",
"return",
"[",
"child",
".",
"view",
"for",
"child",
"in",
"children",
"if",
"isinstance",
"(",
"child",
",",
"QDockWidget",
")",
"and",
"child",
".",
"view",
".",
"name",
".",
"startswith",
"(",
"name",
")",
"and",
"(",
"child",
".",
"isVisible",
"(",
")",
"if",
"is_visible",
"else",
"True",
")",
"and",
"child",
".",
"width",
"(",
")",
">=",
"10",
"and",
"child",
".",
"height",
"(",
")",
">=",
"10",
"]"
] |
List all views which name start with a given string.
|
[
"List",
"all",
"views",
"which",
"name",
"start",
"with",
"a",
"given",
"string",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L304-L313
|
7,857
|
kwikteam/phy
|
phy/gui/gui.py
|
GUI.get_view
|
def get_view(self, name, is_visible=True):
"""Return a view from its name."""
views = self.list_views(name, is_visible=is_visible)
return views[0] if views else None
|
python
|
def get_view(self, name, is_visible=True):
"""Return a view from its name."""
views = self.list_views(name, is_visible=is_visible)
return views[0] if views else None
|
[
"def",
"get_view",
"(",
"self",
",",
"name",
",",
"is_visible",
"=",
"True",
")",
":",
"views",
"=",
"self",
".",
"list_views",
"(",
"name",
",",
"is_visible",
"=",
"is_visible",
")",
"return",
"views",
"[",
"0",
"]",
"if",
"views",
"else",
"None"
] |
Return a view from its name.
|
[
"Return",
"a",
"view",
"from",
"its",
"name",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L315-L318
|
7,858
|
kwikteam/phy
|
phy/gui/gui.py
|
GUI.view_count
|
def view_count(self):
"""Return the number of opened views."""
views = self.list_views()
counts = defaultdict(lambda: 0)
for view in views:
counts[view.name] += 1
return dict(counts)
|
python
|
def view_count(self):
"""Return the number of opened views."""
views = self.list_views()
counts = defaultdict(lambda: 0)
for view in views:
counts[view.name] += 1
return dict(counts)
|
[
"def",
"view_count",
"(",
"self",
")",
":",
"views",
"=",
"self",
".",
"list_views",
"(",
")",
"counts",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"for",
"view",
"in",
"views",
":",
"counts",
"[",
"view",
".",
"name",
"]",
"+=",
"1",
"return",
"dict",
"(",
"counts",
")"
] |
Return the number of opened views.
|
[
"Return",
"the",
"number",
"of",
"opened",
"views",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L320-L326
|
7,859
|
kwikteam/phy
|
phy/gui/gui.py
|
GUI.get_menu
|
def get_menu(self, name):
"""Return or create a menu."""
if name not in self._menus:
self._menus[name] = self.menuBar().addMenu(name)
return self._menus[name]
|
python
|
def get_menu(self, name):
"""Return or create a menu."""
if name not in self._menus:
self._menus[name] = self.menuBar().addMenu(name)
return self._menus[name]
|
[
"def",
"get_menu",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_menus",
":",
"self",
".",
"_menus",
"[",
"name",
"]",
"=",
"self",
".",
"menuBar",
"(",
")",
".",
"addMenu",
"(",
"name",
")",
"return",
"self",
".",
"_menus",
"[",
"name",
"]"
] |
Return or create a menu.
|
[
"Return",
"or",
"create",
"a",
"menu",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L331-L335
|
7,860
|
kwikteam/phy
|
phy/gui/gui.py
|
GUI.restore_geometry_state
|
def restore_geometry_state(self, gs):
"""Restore the position of the main window and the docks.
The gui widgets need to be recreated first.
This function can be called in `on_show()`.
"""
if not gs:
return
if gs.get('geometry', None):
self.restoreGeometry((gs['geometry']))
if gs.get('state', None):
self.restoreState((gs['state']))
|
python
|
def restore_geometry_state(self, gs):
"""Restore the position of the main window and the docks.
The gui widgets need to be recreated first.
This function can be called in `on_show()`.
"""
if not gs:
return
if gs.get('geometry', None):
self.restoreGeometry((gs['geometry']))
if gs.get('state', None):
self.restoreState((gs['state']))
|
[
"def",
"restore_geometry_state",
"(",
"self",
",",
"gs",
")",
":",
"if",
"not",
"gs",
":",
"return",
"if",
"gs",
".",
"get",
"(",
"'geometry'",
",",
"None",
")",
":",
"self",
".",
"restoreGeometry",
"(",
"(",
"gs",
"[",
"'geometry'",
"]",
")",
")",
"if",
"gs",
".",
"get",
"(",
"'state'",
",",
"None",
")",
":",
"self",
".",
"restoreState",
"(",
"(",
"gs",
"[",
"'state'",
"]",
")",
")"
] |
Restore the position of the main window and the docks.
The gui widgets need to be recreated first.
This function can be called in `on_show()`.
|
[
"Restore",
"the",
"position",
"of",
"the",
"main",
"window",
"and",
"the",
"docks",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L377-L390
|
7,861
|
kwikteam/phy
|
phy/gui/gui.py
|
GUIState.update_view_state
|
def update_view_state(self, view, state):
"""Update the state of a view."""
if view.name not in self:
self[view.name] = Bunch()
self[view.name].update(state)
|
python
|
def update_view_state(self, view, state):
"""Update the state of a view."""
if view.name not in self:
self[view.name] = Bunch()
self[view.name].update(state)
|
[
"def",
"update_view_state",
"(",
"self",
",",
"view",
",",
"state",
")",
":",
"if",
"view",
".",
"name",
"not",
"in",
"self",
":",
"self",
"[",
"view",
".",
"name",
"]",
"=",
"Bunch",
"(",
")",
"self",
"[",
"view",
".",
"name",
"]",
".",
"update",
"(",
"state",
")"
] |
Update the state of a view.
|
[
"Update",
"the",
"state",
"of",
"a",
"view",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L415-L419
|
7,862
|
kwikteam/phy
|
phy/gui/gui.py
|
GUIState.load
|
def load(self):
"""Load the state from the JSON file in the config dir."""
if not op.exists(self.path):
logger.debug("The GUI state file `%s` doesn't exist.", self.path)
# TODO: create the default state.
return
assert op.exists(self.path)
logger.debug("Load the GUI state from `%s`.", self.path)
self.update(_bunchify(_load_json(self.path)))
|
python
|
def load(self):
"""Load the state from the JSON file in the config dir."""
if not op.exists(self.path):
logger.debug("The GUI state file `%s` doesn't exist.", self.path)
# TODO: create the default state.
return
assert op.exists(self.path)
logger.debug("Load the GUI state from `%s`.", self.path)
self.update(_bunchify(_load_json(self.path)))
|
[
"def",
"load",
"(",
"self",
")",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"logger",
".",
"debug",
"(",
"\"The GUI state file `%s` doesn't exist.\"",
",",
"self",
".",
"path",
")",
"# TODO: create the default state.",
"return",
"assert",
"op",
".",
"exists",
"(",
"self",
".",
"path",
")",
"logger",
".",
"debug",
"(",
"\"Load the GUI state from `%s`.\"",
",",
"self",
".",
"path",
")",
"self",
".",
"update",
"(",
"_bunchify",
"(",
"_load_json",
"(",
"self",
".",
"path",
")",
")",
")"
] |
Load the state from the JSON file in the config dir.
|
[
"Load",
"the",
"state",
"from",
"the",
"JSON",
"file",
"in",
"the",
"config",
"dir",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L425-L433
|
7,863
|
kwikteam/phy
|
phy/gui/gui.py
|
GUIState.save
|
def save(self):
"""Save the state to the JSON file in the config dir."""
logger.debug("Save the GUI state to `%s`.", self.path)
_save_json(self.path, {k: v for k, v in self.items()
if k not in ('config_dir', 'name')})
|
python
|
def save(self):
"""Save the state to the JSON file in the config dir."""
logger.debug("Save the GUI state to `%s`.", self.path)
_save_json(self.path, {k: v for k, v in self.items()
if k not in ('config_dir', 'name')})
|
[
"def",
"save",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Save the GUI state to `%s`.\"",
",",
"self",
".",
"path",
")",
"_save_json",
"(",
"self",
".",
"path",
",",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"(",
"'config_dir'",
",",
"'name'",
")",
"}",
")"
] |
Save the state to the JSON file in the config dir.
|
[
"Save",
"the",
"state",
"to",
"the",
"JSON",
"file",
"in",
"the",
"config",
"dir",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L435-L439
|
7,864
|
kwikteam/phy
|
phy/io/context.py
|
Context.cache
|
def cache(self, f):
"""Cache a function using the context's cache directory."""
if self._memory is None: # pragma: no cover
logger.debug("Joblib is not installed: skipping cacheing.")
return f
assert f
# NOTE: discard self in instance methods.
if 'self' in inspect.getargspec(f).args:
ignore = ['self']
else:
ignore = None
disk_cached = self._memory.cache(f, ignore=ignore)
return disk_cached
|
python
|
def cache(self, f):
"""Cache a function using the context's cache directory."""
if self._memory is None: # pragma: no cover
logger.debug("Joblib is not installed: skipping cacheing.")
return f
assert f
# NOTE: discard self in instance methods.
if 'self' in inspect.getargspec(f).args:
ignore = ['self']
else:
ignore = None
disk_cached = self._memory.cache(f, ignore=ignore)
return disk_cached
|
[
"def",
"cache",
"(",
"self",
",",
"f",
")",
":",
"if",
"self",
".",
"_memory",
"is",
"None",
":",
"# pragma: no cover",
"logger",
".",
"debug",
"(",
"\"Joblib is not installed: skipping cacheing.\"",
")",
"return",
"f",
"assert",
"f",
"# NOTE: discard self in instance methods.",
"if",
"'self'",
"in",
"inspect",
".",
"getargspec",
"(",
"f",
")",
".",
"args",
":",
"ignore",
"=",
"[",
"'self'",
"]",
"else",
":",
"ignore",
"=",
"None",
"disk_cached",
"=",
"self",
".",
"_memory",
".",
"cache",
"(",
"f",
",",
"ignore",
"=",
"ignore",
")",
"return",
"disk_cached"
] |
Cache a function using the context's cache directory.
|
[
"Cache",
"a",
"function",
"using",
"the",
"context",
"s",
"cache",
"directory",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L73-L85
|
7,865
|
kwikteam/phy
|
phy/io/context.py
|
Context.memcache
|
def memcache(self, f):
"""Cache a function in memory using an internal dictionary."""
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(f)
def memcached(*args):
"""Cache the function in memory."""
# The arguments need to be hashable. Much faster than using hash().
h = args
out = cache.get(h, None)
if out is None:
out = f(*args)
cache[h] = out
return out
return memcached
|
python
|
def memcache(self, f):
"""Cache a function in memory using an internal dictionary."""
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(f)
def memcached(*args):
"""Cache the function in memory."""
# The arguments need to be hashable. Much faster than using hash().
h = args
out = cache.get(h, None)
if out is None:
out = f(*args)
cache[h] = out
return out
return memcached
|
[
"def",
"memcache",
"(",
"self",
",",
"f",
")",
":",
"name",
"=",
"_fullname",
"(",
"f",
")",
"cache",
"=",
"self",
".",
"load_memcache",
"(",
"name",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"memcached",
"(",
"*",
"args",
")",
":",
"\"\"\"Cache the function in memory.\"\"\"",
"# The arguments need to be hashable. Much faster than using hash().",
"h",
"=",
"args",
"out",
"=",
"cache",
".",
"get",
"(",
"h",
",",
"None",
")",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"f",
"(",
"*",
"args",
")",
"cache",
"[",
"h",
"]",
"=",
"out",
"return",
"out",
"return",
"memcached"
] |
Cache a function in memory using an internal dictionary.
|
[
"Cache",
"a",
"function",
"in",
"memory",
"using",
"an",
"internal",
"dictionary",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L106-L121
|
7,866
|
kwikteam/phy
|
phy/io/context.py
|
Context.save
|
def save(self, name, data, location='local', kind='json'):
"""Save a dictionary in a JSON file within the cache directory."""
file_ext = '.json' if kind == 'json' else '.pkl'
path = self._get_path(name, location, file_ext=file_ext)
_ensure_dir_exists(op.dirname(path))
logger.debug("Save data to `%s`.", path)
if kind == 'json':
_save_json(path, data)
else:
_save_pickle(path, data)
|
python
|
def save(self, name, data, location='local', kind='json'):
"""Save a dictionary in a JSON file within the cache directory."""
file_ext = '.json' if kind == 'json' else '.pkl'
path = self._get_path(name, location, file_ext=file_ext)
_ensure_dir_exists(op.dirname(path))
logger.debug("Save data to `%s`.", path)
if kind == 'json':
_save_json(path, data)
else:
_save_pickle(path, data)
|
[
"def",
"save",
"(",
"self",
",",
"name",
",",
"data",
",",
"location",
"=",
"'local'",
",",
"kind",
"=",
"'json'",
")",
":",
"file_ext",
"=",
"'.json'",
"if",
"kind",
"==",
"'json'",
"else",
"'.pkl'",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"file_ext",
")",
"_ensure_dir_exists",
"(",
"op",
".",
"dirname",
"(",
"path",
")",
")",
"logger",
".",
"debug",
"(",
"\"Save data to `%s`.\"",
",",
"path",
")",
"if",
"kind",
"==",
"'json'",
":",
"_save_json",
"(",
"path",
",",
"data",
")",
"else",
":",
"_save_pickle",
"(",
"path",
",",
"data",
")"
] |
Save a dictionary in a JSON file within the cache directory.
|
[
"Save",
"a",
"dictionary",
"in",
"a",
"JSON",
"file",
"within",
"the",
"cache",
"directory",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L129-L138
|
7,867
|
kwikteam/phy
|
phy/io/context.py
|
Context.load
|
def load(self, name, location='local'):
"""Load saved data from the cache directory."""
path = self._get_path(name, location, file_ext='.json')
if op.exists(path):
return _load_json(path)
path = self._get_path(name, location, file_ext='.pkl')
if op.exists(path):
return _load_pickle(path)
logger.debug("The file `%s` doesn't exist.", path)
return {}
|
python
|
def load(self, name, location='local'):
"""Load saved data from the cache directory."""
path = self._get_path(name, location, file_ext='.json')
if op.exists(path):
return _load_json(path)
path = self._get_path(name, location, file_ext='.pkl')
if op.exists(path):
return _load_pickle(path)
logger.debug("The file `%s` doesn't exist.", path)
return {}
|
[
"def",
"load",
"(",
"self",
",",
"name",
",",
"location",
"=",
"'local'",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"'.json'",
")",
"if",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"_load_json",
"(",
"path",
")",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"'.pkl'",
")",
"if",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"_load_pickle",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"\"The file `%s` doesn't exist.\"",
",",
"path",
")",
"return",
"{",
"}"
] |
Load saved data from the cache directory.
|
[
"Load",
"saved",
"data",
"from",
"the",
"cache",
"directory",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L140-L149
|
7,868
|
kwikteam/phy
|
phy/utils/config.py
|
_ensure_dir_exists
|
def _ensure_dir_exists(path):
"""Ensure a directory exists."""
if not op.exists(path):
os.makedirs(path)
assert op.exists(path) and op.isdir(path)
|
python
|
def _ensure_dir_exists(path):
"""Ensure a directory exists."""
if not op.exists(path):
os.makedirs(path)
assert op.exists(path) and op.isdir(path)
|
[
"def",
"_ensure_dir_exists",
"(",
"path",
")",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"assert",
"op",
".",
"exists",
"(",
"path",
")",
"and",
"op",
".",
"isdir",
"(",
"path",
")"
] |
Ensure a directory exists.
|
[
"Ensure",
"a",
"directory",
"exists",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/config.py#L32-L36
|
7,869
|
kwikteam/phy
|
phy/utils/config.py
|
load_config
|
def load_config(path=None):
"""Load a Python or JSON config file."""
if not path or not op.exists(path):
return Config()
path = op.realpath(path)
dirpath, filename = op.split(path)
file_ext = op.splitext(path)[1]
logger.debug("Load config file `%s`.", path)
if file_ext == '.py':
config = PyFileConfigLoader(filename, dirpath,
log=logger).load_config()
elif file_ext == '.json':
config = JSONFileConfigLoader(filename, dirpath,
log=logger).load_config()
return config
|
python
|
def load_config(path=None):
"""Load a Python or JSON config file."""
if not path or not op.exists(path):
return Config()
path = op.realpath(path)
dirpath, filename = op.split(path)
file_ext = op.splitext(path)[1]
logger.debug("Load config file `%s`.", path)
if file_ext == '.py':
config = PyFileConfigLoader(filename, dirpath,
log=logger).load_config()
elif file_ext == '.json':
config = JSONFileConfigLoader(filename, dirpath,
log=logger).load_config()
return config
|
[
"def",
"load_config",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
"or",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"Config",
"(",
")",
"path",
"=",
"op",
".",
"realpath",
"(",
"path",
")",
"dirpath",
",",
"filename",
"=",
"op",
".",
"split",
"(",
"path",
")",
"file_ext",
"=",
"op",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"logger",
".",
"debug",
"(",
"\"Load config file `%s`.\"",
",",
"path",
")",
"if",
"file_ext",
"==",
"'.py'",
":",
"config",
"=",
"PyFileConfigLoader",
"(",
"filename",
",",
"dirpath",
",",
"log",
"=",
"logger",
")",
".",
"load_config",
"(",
")",
"elif",
"file_ext",
"==",
"'.json'",
":",
"config",
"=",
"JSONFileConfigLoader",
"(",
"filename",
",",
"dirpath",
",",
"log",
"=",
"logger",
")",
".",
"load_config",
"(",
")",
"return",
"config"
] |
Load a Python or JSON config file.
|
[
"Load",
"a",
"Python",
"or",
"JSON",
"config",
"file",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/config.py#L39-L53
|
7,870
|
kwikteam/phy
|
phy/utils/config.py
|
save_config
|
def save_config(path, config):
"""Save a config object to a JSON file."""
import json
config['version'] = 1
with open(path, 'w') as f:
json.dump(config, f)
|
python
|
def save_config(path, config):
"""Save a config object to a JSON file."""
import json
config['version'] = 1
with open(path, 'w') as f:
json.dump(config, f)
|
[
"def",
"save_config",
"(",
"path",
",",
"config",
")",
":",
"import",
"json",
"config",
"[",
"'version'",
"]",
"=",
"1",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"config",
",",
"f",
")"
] |
Save a config object to a JSON file.
|
[
"Save",
"a",
"config",
"object",
"to",
"a",
"JSON",
"file",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/config.py#L94-L99
|
7,871
|
kwikteam/phy
|
phy/electrode/mea.py
|
_edges_to_adjacency_list
|
def _edges_to_adjacency_list(edges):
"""Convert a list of edges into an adjacency list."""
adj = {}
for i, j in edges:
if i in adj: # pragma: no cover
ni = adj[i]
else:
ni = adj[i] = set()
if j in adj:
nj = adj[j]
else:
nj = adj[j] = set()
ni.add(j)
nj.add(i)
return adj
|
python
|
def _edges_to_adjacency_list(edges):
"""Convert a list of edges into an adjacency list."""
adj = {}
for i, j in edges:
if i in adj: # pragma: no cover
ni = adj[i]
else:
ni = adj[i] = set()
if j in adj:
nj = adj[j]
else:
nj = adj[j] = set()
ni.add(j)
nj.add(i)
return adj
|
[
"def",
"_edges_to_adjacency_list",
"(",
"edges",
")",
":",
"adj",
"=",
"{",
"}",
"for",
"i",
",",
"j",
"in",
"edges",
":",
"if",
"i",
"in",
"adj",
":",
"# pragma: no cover",
"ni",
"=",
"adj",
"[",
"i",
"]",
"else",
":",
"ni",
"=",
"adj",
"[",
"i",
"]",
"=",
"set",
"(",
")",
"if",
"j",
"in",
"adj",
":",
"nj",
"=",
"adj",
"[",
"j",
"]",
"else",
":",
"nj",
"=",
"adj",
"[",
"j",
"]",
"=",
"set",
"(",
")",
"ni",
".",
"add",
"(",
"j",
")",
"nj",
".",
"add",
"(",
"i",
")",
"return",
"adj"
] |
Convert a list of edges into an adjacency list.
|
[
"Convert",
"a",
"list",
"of",
"edges",
"into",
"an",
"adjacency",
"list",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L24-L38
|
7,872
|
kwikteam/phy
|
phy/electrode/mea.py
|
_probe_positions
|
def _probe_positions(probe, group):
"""Return the positions of a probe channel group."""
positions = probe['channel_groups'][group]['geometry']
channels = _probe_channels(probe, group)
return np.array([positions[channel] for channel in channels])
|
python
|
def _probe_positions(probe, group):
"""Return the positions of a probe channel group."""
positions = probe['channel_groups'][group]['geometry']
channels = _probe_channels(probe, group)
return np.array([positions[channel] for channel in channels])
|
[
"def",
"_probe_positions",
"(",
"probe",
",",
"group",
")",
":",
"positions",
"=",
"probe",
"[",
"'channel_groups'",
"]",
"[",
"group",
"]",
"[",
"'geometry'",
"]",
"channels",
"=",
"_probe_channels",
"(",
"probe",
",",
"group",
")",
"return",
"np",
".",
"array",
"(",
"[",
"positions",
"[",
"channel",
"]",
"for",
"channel",
"in",
"channels",
"]",
")"
] |
Return the positions of a probe channel group.
|
[
"Return",
"the",
"positions",
"of",
"a",
"probe",
"channel",
"group",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L53-L57
|
7,873
|
kwikteam/phy
|
phy/electrode/mea.py
|
_probe_adjacency_list
|
def _probe_adjacency_list(probe):
"""Return an adjacency list of a whole probe."""
cgs = probe['channel_groups'].values()
graphs = [cg['graph'] for cg in cgs]
edges = list(itertools.chain(*graphs))
adjacency_list = _edges_to_adjacency_list(edges)
return adjacency_list
|
python
|
def _probe_adjacency_list(probe):
"""Return an adjacency list of a whole probe."""
cgs = probe['channel_groups'].values()
graphs = [cg['graph'] for cg in cgs]
edges = list(itertools.chain(*graphs))
adjacency_list = _edges_to_adjacency_list(edges)
return adjacency_list
|
[
"def",
"_probe_adjacency_list",
"(",
"probe",
")",
":",
"cgs",
"=",
"probe",
"[",
"'channel_groups'",
"]",
".",
"values",
"(",
")",
"graphs",
"=",
"[",
"cg",
"[",
"'graph'",
"]",
"for",
"cg",
"in",
"cgs",
"]",
"edges",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"graphs",
")",
")",
"adjacency_list",
"=",
"_edges_to_adjacency_list",
"(",
"edges",
")",
"return",
"adjacency_list"
] |
Return an adjacency list of a whole probe.
|
[
"Return",
"an",
"adjacency",
"list",
"of",
"a",
"whole",
"probe",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L69-L75
|
7,874
|
kwikteam/phy
|
phy/electrode/mea.py
|
load_probe
|
def load_probe(name):
"""Load one of the built-in probes."""
if op.exists(name):
# The argument can be either a path to a PRB file.
path = name
else:
# Or the name of a built-in probe.
curdir = op.realpath(op.dirname(__file__))
path = op.join(curdir, 'probes/{}.prb'.format(name))
if not op.exists(path):
raise IOError("The probe `{}` cannot be found.".format(name))
return MEA(probe=_read_python(path))
|
python
|
def load_probe(name):
"""Load one of the built-in probes."""
if op.exists(name):
# The argument can be either a path to a PRB file.
path = name
else:
# Or the name of a built-in probe.
curdir = op.realpath(op.dirname(__file__))
path = op.join(curdir, 'probes/{}.prb'.format(name))
if not op.exists(path):
raise IOError("The probe `{}` cannot be found.".format(name))
return MEA(probe=_read_python(path))
|
[
"def",
"load_probe",
"(",
"name",
")",
":",
"if",
"op",
".",
"exists",
"(",
"name",
")",
":",
"# The argument can be either a path to a PRB file.",
"path",
"=",
"name",
"else",
":",
"# Or the name of a built-in probe.",
"curdir",
"=",
"op",
".",
"realpath",
"(",
"op",
".",
"dirname",
"(",
"__file__",
")",
")",
"path",
"=",
"op",
".",
"join",
"(",
"curdir",
",",
"'probes/{}.prb'",
".",
"format",
"(",
"name",
")",
")",
"if",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"\"The probe `{}` cannot be found.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"MEA",
"(",
"probe",
"=",
"_read_python",
"(",
"path",
")",
")"
] |
Load one of the built-in probes.
|
[
"Load",
"one",
"of",
"the",
"built",
"-",
"in",
"probes",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L84-L95
|
7,875
|
kwikteam/phy
|
phy/electrode/mea.py
|
list_probes
|
def list_probes():
"""Return the list of built-in probes."""
curdir = op.realpath(op.dirname(__file__))
return [op.splitext(fn)[0] for fn in os.listdir(op.join(curdir, 'probes'))
if fn.endswith('.prb')]
|
python
|
def list_probes():
"""Return the list of built-in probes."""
curdir = op.realpath(op.dirname(__file__))
return [op.splitext(fn)[0] for fn in os.listdir(op.join(curdir, 'probes'))
if fn.endswith('.prb')]
|
[
"def",
"list_probes",
"(",
")",
":",
"curdir",
"=",
"op",
".",
"realpath",
"(",
"op",
".",
"dirname",
"(",
"__file__",
")",
")",
"return",
"[",
"op",
".",
"splitext",
"(",
"fn",
")",
"[",
"0",
"]",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"op",
".",
"join",
"(",
"curdir",
",",
"'probes'",
")",
")",
"if",
"fn",
".",
"endswith",
"(",
"'.prb'",
")",
"]"
] |
Return the list of built-in probes.
|
[
"Return",
"the",
"list",
"of",
"built",
"-",
"in",
"probes",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L98-L102
|
7,876
|
kwikteam/phy
|
phy/electrode/mea.py
|
linear_positions
|
def linear_positions(n_channels):
"""Linear channel positions along the vertical axis."""
return np.c_[np.zeros(n_channels),
np.linspace(0., 1., n_channels)]
|
python
|
def linear_positions(n_channels):
"""Linear channel positions along the vertical axis."""
return np.c_[np.zeros(n_channels),
np.linspace(0., 1., n_channels)]
|
[
"def",
"linear_positions",
"(",
"n_channels",
")",
":",
"return",
"np",
".",
"c_",
"[",
"np",
".",
"zeros",
"(",
"n_channels",
")",
",",
"np",
".",
"linspace",
"(",
"0.",
",",
"1.",
",",
"n_channels",
")",
"]"
] |
Linear channel positions along the vertical axis.
|
[
"Linear",
"channel",
"positions",
"along",
"the",
"vertical",
"axis",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L182-L185
|
7,877
|
kwikteam/phy
|
phy/electrode/mea.py
|
staggered_positions
|
def staggered_positions(n_channels):
"""Generate channel positions for a staggered probe."""
i = np.arange(n_channels - 1)
x, y = (-1) ** i * (5 + i), 10 * (i + 1)
pos = np.flipud(np.r_[np.zeros((1, 2)), np.c_[x, y]])
return pos
|
python
|
def staggered_positions(n_channels):
"""Generate channel positions for a staggered probe."""
i = np.arange(n_channels - 1)
x, y = (-1) ** i * (5 + i), 10 * (i + 1)
pos = np.flipud(np.r_[np.zeros((1, 2)), np.c_[x, y]])
return pos
|
[
"def",
"staggered_positions",
"(",
"n_channels",
")",
":",
"i",
"=",
"np",
".",
"arange",
"(",
"n_channels",
"-",
"1",
")",
"x",
",",
"y",
"=",
"(",
"-",
"1",
")",
"**",
"i",
"*",
"(",
"5",
"+",
"i",
")",
",",
"10",
"*",
"(",
"i",
"+",
"1",
")",
"pos",
"=",
"np",
".",
"flipud",
"(",
"np",
".",
"r_",
"[",
"np",
".",
"zeros",
"(",
"(",
"1",
",",
"2",
")",
")",
",",
"np",
".",
"c_",
"[",
"x",
",",
"y",
"]",
"]",
")",
"return",
"pos"
] |
Generate channel positions for a staggered probe.
|
[
"Generate",
"channel",
"positions",
"for",
"a",
"staggered",
"probe",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L188-L193
|
7,878
|
kwikteam/phy
|
phy/electrode/mea.py
|
MEA.change_channel_group
|
def change_channel_group(self, group):
"""Change the current channel group."""
assert self._probe is not None
self._channels = _probe_channels(self._probe, group)
self._positions = _probe_positions(self._probe, group)
|
python
|
def change_channel_group(self, group):
"""Change the current channel group."""
assert self._probe is not None
self._channels = _probe_channels(self._probe, group)
self._positions = _probe_positions(self._probe, group)
|
[
"def",
"change_channel_group",
"(",
"self",
",",
"group",
")",
":",
"assert",
"self",
".",
"_probe",
"is",
"not",
"None",
"self",
".",
"_channels",
"=",
"_probe_channels",
"(",
"self",
".",
"_probe",
",",
"group",
")",
"self",
".",
"_positions",
"=",
"_probe_positions",
"(",
"self",
".",
"_probe",
",",
"group",
")"
] |
Change the current channel group.
|
[
"Change",
"the",
"current",
"channel",
"group",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L171-L175
|
7,879
|
kwikteam/phy
|
phy/gui/widgets.py
|
HTMLWidget.build
|
def build(self):
"""Build the full HTML source."""
if self.is_built(): # pragma: no cover
return
with _wait_signal(self.loadFinished, 20):
self.rebuild()
self._built = True
|
python
|
def build(self):
"""Build the full HTML source."""
if self.is_built(): # pragma: no cover
return
with _wait_signal(self.loadFinished, 20):
self.rebuild()
self._built = True
|
[
"def",
"build",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_built",
"(",
")",
":",
"# pragma: no cover",
"return",
"with",
"_wait_signal",
"(",
"self",
".",
"loadFinished",
",",
"20",
")",
":",
"self",
".",
"rebuild",
"(",
")",
"self",
".",
"_built",
"=",
"True"
] |
Build the full HTML source.
|
[
"Build",
"the",
"full",
"HTML",
"source",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L171-L177
|
7,880
|
kwikteam/phy
|
phy/gui/widgets.py
|
HTMLWidget.add_to_js
|
def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var)
|
python
|
def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var)
|
[
"def",
"add_to_js",
"(",
"self",
",",
"name",
",",
"var",
")",
":",
"frame",
"=",
"self",
".",
"page",
"(",
")",
".",
"mainFrame",
"(",
")",
"frame",
".",
"addToJavaScriptWindowObject",
"(",
"name",
",",
"var",
")"
] |
Add an object to Javascript.
|
[
"Add",
"an",
"object",
"to",
"Javascript",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L185-L188
|
7,881
|
kwikteam/phy
|
phy/gui/widgets.py
|
HTMLWidget.eval_js
|
def eval_js(self, expr):
"""Evaluate a Javascript expression."""
if not self.is_built():
self._pending_js_eval.append(expr)
return
logger.log(5, "Evaluate Javascript: `%s`.", expr)
out = self.page().mainFrame().evaluateJavaScript(expr)
return _to_py(out)
|
python
|
def eval_js(self, expr):
"""Evaluate a Javascript expression."""
if not self.is_built():
self._pending_js_eval.append(expr)
return
logger.log(5, "Evaluate Javascript: `%s`.", expr)
out = self.page().mainFrame().evaluateJavaScript(expr)
return _to_py(out)
|
[
"def",
"eval_js",
"(",
"self",
",",
"expr",
")",
":",
"if",
"not",
"self",
".",
"is_built",
"(",
")",
":",
"self",
".",
"_pending_js_eval",
".",
"append",
"(",
"expr",
")",
"return",
"logger",
".",
"log",
"(",
"5",
",",
"\"Evaluate Javascript: `%s`.\"",
",",
"expr",
")",
"out",
"=",
"self",
".",
"page",
"(",
")",
".",
"mainFrame",
"(",
")",
".",
"evaluateJavaScript",
"(",
"expr",
")",
"return",
"_to_py",
"(",
"out",
")"
] |
Evaluate a Javascript expression.
|
[
"Evaluate",
"a",
"Javascript",
"expression",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L190-L197
|
7,882
|
kwikteam/phy
|
phy/gui/widgets.py
|
Table.add_column
|
def add_column(self, func, name=None, show=True):
"""Add a column function which takes an id as argument and
returns a value."""
assert func
name = name or func.__name__
if name == '<lambda>':
raise ValueError("Please provide a valid name for " + name)
d = {'func': func,
'show': show,
}
self._columns[name] = d
# Update the headers in the widget.
data = _create_json_dict(cols=self.column_names,
)
self.eval_js('table.setHeaders({});'.format(data))
return func
|
python
|
def add_column(self, func, name=None, show=True):
"""Add a column function which takes an id as argument and
returns a value."""
assert func
name = name or func.__name__
if name == '<lambda>':
raise ValueError("Please provide a valid name for " + name)
d = {'func': func,
'show': show,
}
self._columns[name] = d
# Update the headers in the widget.
data = _create_json_dict(cols=self.column_names,
)
self.eval_js('table.setHeaders({});'.format(data))
return func
|
[
"def",
"add_column",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
",",
"show",
"=",
"True",
")",
":",
"assert",
"func",
"name",
"=",
"name",
"or",
"func",
".",
"__name__",
"if",
"name",
"==",
"'<lambda>'",
":",
"raise",
"ValueError",
"(",
"\"Please provide a valid name for \"",
"+",
"name",
")",
"d",
"=",
"{",
"'func'",
":",
"func",
",",
"'show'",
":",
"show",
",",
"}",
"self",
".",
"_columns",
"[",
"name",
"]",
"=",
"d",
"# Update the headers in the widget.",
"data",
"=",
"_create_json_dict",
"(",
"cols",
"=",
"self",
".",
"column_names",
",",
")",
"self",
".",
"eval_js",
"(",
"'table.setHeaders({});'",
".",
"format",
"(",
"data",
")",
")",
"return",
"func"
] |
Add a column function which takes an id as argument and
returns a value.
|
[
"Add",
"a",
"column",
"function",
"which",
"takes",
"an",
"id",
"as",
"argument",
"and",
"returns",
"a",
"value",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L252-L269
|
7,883
|
kwikteam/phy
|
phy/gui/widgets.py
|
Table.column_names
|
def column_names(self):
"""List of column names."""
return [name for (name, d) in self._columns.items()
if d.get('show', True)]
|
python
|
def column_names(self):
"""List of column names."""
return [name for (name, d) in self._columns.items()
if d.get('show', True)]
|
[
"def",
"column_names",
"(",
"self",
")",
":",
"return",
"[",
"name",
"for",
"(",
"name",
",",
"d",
")",
"in",
"self",
".",
"_columns",
".",
"items",
"(",
")",
"if",
"d",
".",
"get",
"(",
"'show'",
",",
"True",
")",
"]"
] |
List of column names.
|
[
"List",
"of",
"column",
"names",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L272-L275
|
7,884
|
kwikteam/phy
|
phy/gui/widgets.py
|
Table._get_row
|
def _get_row(self, id):
"""Create a row dictionary for a given object id."""
return {name: d['func'](id) for (name, d) in self._columns.items()}
|
python
|
def _get_row(self, id):
"""Create a row dictionary for a given object id."""
return {name: d['func'](id) for (name, d) in self._columns.items()}
|
[
"def",
"_get_row",
"(",
"self",
",",
"id",
")",
":",
"return",
"{",
"name",
":",
"d",
"[",
"'func'",
"]",
"(",
"id",
")",
"for",
"(",
"name",
",",
"d",
")",
"in",
"self",
".",
"_columns",
".",
"items",
"(",
")",
"}"
] |
Create a row dictionary for a given object id.
|
[
"Create",
"a",
"row",
"dictionary",
"for",
"a",
"given",
"object",
"id",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L277-L279
|
7,885
|
kwikteam/phy
|
phy/gui/widgets.py
|
Table.set_rows
|
def set_rows(self, ids):
"""Set the rows of the table."""
# NOTE: make sure we have integers and not np.generic objects.
assert all(isinstance(i, int) for i in ids)
# Determine the sort column and dir to set after the rows.
sort_col, sort_dir = self.current_sort
default_sort_col, default_sort_dir = self.default_sort
sort_col = sort_col or default_sort_col
sort_dir = sort_dir or default_sort_dir or 'desc'
# Set the rows.
logger.log(5, "Set %d rows in the table.", len(ids))
items = [self._get_row(id) for id in ids]
# Sort the rows before passing them to the widget.
# if sort_col:
# items = sorted(items, key=itemgetter(sort_col),
# reverse=(sort_dir == 'desc'))
data = _create_json_dict(items=items,
cols=self.column_names,
)
self.eval_js('table.setData({});'.format(data))
# Sort.
if sort_col:
self.sort_by(sort_col, sort_dir)
|
python
|
def set_rows(self, ids):
"""Set the rows of the table."""
# NOTE: make sure we have integers and not np.generic objects.
assert all(isinstance(i, int) for i in ids)
# Determine the sort column and dir to set after the rows.
sort_col, sort_dir = self.current_sort
default_sort_col, default_sort_dir = self.default_sort
sort_col = sort_col or default_sort_col
sort_dir = sort_dir or default_sort_dir or 'desc'
# Set the rows.
logger.log(5, "Set %d rows in the table.", len(ids))
items = [self._get_row(id) for id in ids]
# Sort the rows before passing them to the widget.
# if sort_col:
# items = sorted(items, key=itemgetter(sort_col),
# reverse=(sort_dir == 'desc'))
data = _create_json_dict(items=items,
cols=self.column_names,
)
self.eval_js('table.setData({});'.format(data))
# Sort.
if sort_col:
self.sort_by(sort_col, sort_dir)
|
[
"def",
"set_rows",
"(",
"self",
",",
"ids",
")",
":",
"# NOTE: make sure we have integers and not np.generic objects.",
"assert",
"all",
"(",
"isinstance",
"(",
"i",
",",
"int",
")",
"for",
"i",
"in",
"ids",
")",
"# Determine the sort column and dir to set after the rows.",
"sort_col",
",",
"sort_dir",
"=",
"self",
".",
"current_sort",
"default_sort_col",
",",
"default_sort_dir",
"=",
"self",
".",
"default_sort",
"sort_col",
"=",
"sort_col",
"or",
"default_sort_col",
"sort_dir",
"=",
"sort_dir",
"or",
"default_sort_dir",
"or",
"'desc'",
"# Set the rows.",
"logger",
".",
"log",
"(",
"5",
",",
"\"Set %d rows in the table.\"",
",",
"len",
"(",
"ids",
")",
")",
"items",
"=",
"[",
"self",
".",
"_get_row",
"(",
"id",
")",
"for",
"id",
"in",
"ids",
"]",
"# Sort the rows before passing them to the widget.",
"# if sort_col:",
"# items = sorted(items, key=itemgetter(sort_col),",
"# reverse=(sort_dir == 'desc'))",
"data",
"=",
"_create_json_dict",
"(",
"items",
"=",
"items",
",",
"cols",
"=",
"self",
".",
"column_names",
",",
")",
"self",
".",
"eval_js",
"(",
"'table.setData({});'",
".",
"format",
"(",
"data",
")",
")",
"# Sort.",
"if",
"sort_col",
":",
"self",
".",
"sort_by",
"(",
"sort_col",
",",
"sort_dir",
")"
] |
Set the rows of the table.
|
[
"Set",
"the",
"rows",
"of",
"the",
"table",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L281-L307
|
7,886
|
kwikteam/phy
|
phy/gui/widgets.py
|
Table.sort_by
|
def sort_by(self, name, sort_dir='asc'):
"""Sort by a given variable."""
logger.log(5, "Sort by `%s` %s.", name, sort_dir)
self.eval_js('table.sortBy("{}", "{}");'.format(name, sort_dir))
|
python
|
def sort_by(self, name, sort_dir='asc'):
"""Sort by a given variable."""
logger.log(5, "Sort by `%s` %s.", name, sort_dir)
self.eval_js('table.sortBy("{}", "{}");'.format(name, sort_dir))
|
[
"def",
"sort_by",
"(",
"self",
",",
"name",
",",
"sort_dir",
"=",
"'asc'",
")",
":",
"logger",
".",
"log",
"(",
"5",
",",
"\"Sort by `%s` %s.\"",
",",
"name",
",",
"sort_dir",
")",
"self",
".",
"eval_js",
"(",
"'table.sortBy(\"{}\", \"{}\");'",
".",
"format",
"(",
"name",
",",
"sort_dir",
")",
")"
] |
Sort by a given variable.
|
[
"Sort",
"by",
"a",
"given",
"variable",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L309-L312
|
7,887
|
kwikteam/phy
|
phy/gui/widgets.py
|
Table.select
|
def select(self, ids, do_emit=True, **kwargs):
"""Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`.
"""
# Select the rows without emiting the event.
self.eval_js('table.select({}, false);'.format(dumps(ids)))
if do_emit:
# Emit the event manually if needed.
self.emit('select', ids, **kwargs)
|
python
|
def select(self, ids, do_emit=True, **kwargs):
"""Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`.
"""
# Select the rows without emiting the event.
self.eval_js('table.select({}, false);'.format(dumps(ids)))
if do_emit:
# Emit the event manually if needed.
self.emit('select', ids, **kwargs)
|
[
"def",
"select",
"(",
"self",
",",
"ids",
",",
"do_emit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Select the rows without emiting the event.",
"self",
".",
"eval_js",
"(",
"'table.select({}, false);'",
".",
"format",
"(",
"dumps",
"(",
"ids",
")",
")",
")",
"if",
"do_emit",
":",
"# Emit the event manually if needed.",
"self",
".",
"emit",
"(",
"'select'",
",",
"ids",
",",
"*",
"*",
"kwargs",
")"
] |
Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`.
|
[
"Select",
"some",
"rows",
"in",
"the",
"table",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L332-L342
|
7,888
|
kwikteam/phy
|
phy/cluster/views/trace.py
|
TraceView.set_interval
|
def set_interval(self, interval=None, change_status=True,
force_update=False):
"""Display the traces and spikes in a given interval."""
if interval is None:
interval = self._interval
interval = self._restrict_interval(interval)
if not force_update and interval == self._interval:
return
self._interval = interval
start, end = interval
self.clear()
# Set the status message.
if change_status:
self.set_status('Interval: {:.3f} s - {:.3f} s'.format(start, end))
# Load the traces.
traces = self.traces(interval)
# Find the data bounds.
ymin, ymax = traces.data.min(), traces.data.max()
data_bounds = (start, ymin, end, ymax)
# Used for spike click.
self._data_bounds = data_bounds
self._waveform_times = []
# Plot the traces.
self._plot_traces(traces.data,
color=traces.get('color', None),
data_bounds=data_bounds,
)
# Plot the spikes.
waveforms = traces.waveforms
assert isinstance(waveforms, list)
for w in waveforms:
self._plot_waveforms(waveforms=w.data,
color=w.color,
channel_ids=w.get('channel_ids', None),
start_time=w.start_time,
data_bounds=data_bounds,
)
self._waveform_times.append((w.start_time,
w.spike_id,
w.spike_cluster,
w.get('channel_ids', None),
))
# Plot the labels.
if self.do_show_labels:
self._plot_labels(traces.data, data_bounds=data_bounds)
self.build()
self.update()
|
python
|
def set_interval(self, interval=None, change_status=True,
force_update=False):
"""Display the traces and spikes in a given interval."""
if interval is None:
interval = self._interval
interval = self._restrict_interval(interval)
if not force_update and interval == self._interval:
return
self._interval = interval
start, end = interval
self.clear()
# Set the status message.
if change_status:
self.set_status('Interval: {:.3f} s - {:.3f} s'.format(start, end))
# Load the traces.
traces = self.traces(interval)
# Find the data bounds.
ymin, ymax = traces.data.min(), traces.data.max()
data_bounds = (start, ymin, end, ymax)
# Used for spike click.
self._data_bounds = data_bounds
self._waveform_times = []
# Plot the traces.
self._plot_traces(traces.data,
color=traces.get('color', None),
data_bounds=data_bounds,
)
# Plot the spikes.
waveforms = traces.waveforms
assert isinstance(waveforms, list)
for w in waveforms:
self._plot_waveforms(waveforms=w.data,
color=w.color,
channel_ids=w.get('channel_ids', None),
start_time=w.start_time,
data_bounds=data_bounds,
)
self._waveform_times.append((w.start_time,
w.spike_id,
w.spike_cluster,
w.get('channel_ids', None),
))
# Plot the labels.
if self.do_show_labels:
self._plot_labels(traces.data, data_bounds=data_bounds)
self.build()
self.update()
|
[
"def",
"set_interval",
"(",
"self",
",",
"interval",
"=",
"None",
",",
"change_status",
"=",
"True",
",",
"force_update",
"=",
"False",
")",
":",
"if",
"interval",
"is",
"None",
":",
"interval",
"=",
"self",
".",
"_interval",
"interval",
"=",
"self",
".",
"_restrict_interval",
"(",
"interval",
")",
"if",
"not",
"force_update",
"and",
"interval",
"==",
"self",
".",
"_interval",
":",
"return",
"self",
".",
"_interval",
"=",
"interval",
"start",
",",
"end",
"=",
"interval",
"self",
".",
"clear",
"(",
")",
"# Set the status message.",
"if",
"change_status",
":",
"self",
".",
"set_status",
"(",
"'Interval: {:.3f} s - {:.3f} s'",
".",
"format",
"(",
"start",
",",
"end",
")",
")",
"# Load the traces.",
"traces",
"=",
"self",
".",
"traces",
"(",
"interval",
")",
"# Find the data bounds.",
"ymin",
",",
"ymax",
"=",
"traces",
".",
"data",
".",
"min",
"(",
")",
",",
"traces",
".",
"data",
".",
"max",
"(",
")",
"data_bounds",
"=",
"(",
"start",
",",
"ymin",
",",
"end",
",",
"ymax",
")",
"# Used for spike click.",
"self",
".",
"_data_bounds",
"=",
"data_bounds",
"self",
".",
"_waveform_times",
"=",
"[",
"]",
"# Plot the traces.",
"self",
".",
"_plot_traces",
"(",
"traces",
".",
"data",
",",
"color",
"=",
"traces",
".",
"get",
"(",
"'color'",
",",
"None",
")",
",",
"data_bounds",
"=",
"data_bounds",
",",
")",
"# Plot the spikes.",
"waveforms",
"=",
"traces",
".",
"waveforms",
"assert",
"isinstance",
"(",
"waveforms",
",",
"list",
")",
"for",
"w",
"in",
"waveforms",
":",
"self",
".",
"_plot_waveforms",
"(",
"waveforms",
"=",
"w",
".",
"data",
",",
"color",
"=",
"w",
".",
"color",
",",
"channel_ids",
"=",
"w",
".",
"get",
"(",
"'channel_ids'",
",",
"None",
")",
",",
"start_time",
"=",
"w",
".",
"start_time",
",",
"data_bounds",
"=",
"data_bounds",
",",
")",
"self",
".",
"_waveform_times",
".",
"append",
"(",
"(",
"w",
".",
"start_time",
",",
"w",
".",
"spike_id",
",",
"w",
".",
"spike_cluster",
",",
"w",
".",
"get",
"(",
"'channel_ids'",
",",
"None",
")",
",",
")",
")",
"# Plot the labels.",
"if",
"self",
".",
"do_show_labels",
":",
"self",
".",
"_plot_labels",
"(",
"traces",
".",
"data",
",",
"data_bounds",
"=",
"data_bounds",
")",
"self",
".",
"build",
"(",
")",
"self",
".",
"update",
"(",
")"
] |
Display the traces and spikes in a given interval.
|
[
"Display",
"the",
"traces",
"and",
"spikes",
"in",
"a",
"given",
"interval",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L246-L300
|
7,889
|
kwikteam/phy
|
phy/cluster/views/trace.py
|
TraceView.half_duration
|
def half_duration(self):
"""Half of the duration of the current interval."""
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5
|
python
|
def half_duration(self):
"""Half of the duration of the current interval."""
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5
|
[
"def",
"half_duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"_interval",
"is",
"not",
"None",
":",
"a",
",",
"b",
"=",
"self",
".",
"_interval",
"return",
"(",
"b",
"-",
"a",
")",
"*",
".5",
"else",
":",
"return",
"self",
".",
"interval_duration",
"*",
".5"
] |
Half of the duration of the current interval.
|
[
"Half",
"of",
"the",
"duration",
"of",
"the",
"current",
"interval",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L384-L390
|
7,890
|
kwikteam/phy
|
phy/cluster/views/trace.py
|
TraceView.go_right
|
def go_right(self):
"""Go to right."""
start, end = self._interval
delay = (end - start) * .2
self.shift(delay)
|
python
|
def go_right(self):
"""Go to right."""
start, end = self._interval
delay = (end - start) * .2
self.shift(delay)
|
[
"def",
"go_right",
"(",
"self",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"_interval",
"delay",
"=",
"(",
"end",
"-",
"start",
")",
"*",
".2",
"self",
".",
"shift",
"(",
"delay",
")"
] |
Go to right.
|
[
"Go",
"to",
"right",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L401-L405
|
7,891
|
kwikteam/phy
|
phy/cluster/views/trace.py
|
TraceView.go_left
|
def go_left(self):
"""Go to left."""
start, end = self._interval
delay = (end - start) * .2
self.shift(-delay)
|
python
|
def go_left(self):
"""Go to left."""
start, end = self._interval
delay = (end - start) * .2
self.shift(-delay)
|
[
"def",
"go_left",
"(",
"self",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"_interval",
"delay",
"=",
"(",
"end",
"-",
"start",
")",
"*",
".2",
"self",
".",
"shift",
"(",
"-",
"delay",
")"
] |
Go to left.
|
[
"Go",
"to",
"left",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L407-L411
|
7,892
|
kwikteam/phy
|
phy/cluster/views/trace.py
|
TraceView.widen
|
def widen(self):
"""Increase the interval size."""
t, h = self.time, self.half_duration
h *= self.scaling_coeff_x
self.set_interval((t - h, t + h))
|
python
|
def widen(self):
"""Increase the interval size."""
t, h = self.time, self.half_duration
h *= self.scaling_coeff_x
self.set_interval((t - h, t + h))
|
[
"def",
"widen",
"(",
"self",
")",
":",
"t",
",",
"h",
"=",
"self",
".",
"time",
",",
"self",
".",
"half_duration",
"h",
"*=",
"self",
".",
"scaling_coeff_x",
"self",
".",
"set_interval",
"(",
"(",
"t",
"-",
"h",
",",
"t",
"+",
"h",
")",
")"
] |
Increase the interval size.
|
[
"Increase",
"the",
"interval",
"size",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L413-L417
|
7,893
|
kwikteam/phy
|
phy/cluster/views/trace.py
|
TraceView.narrow
|
def narrow(self):
"""Decrease the interval size."""
t, h = self.time, self.half_duration
h /= self.scaling_coeff_x
self.set_interval((t - h, t + h))
|
python
|
def narrow(self):
"""Decrease the interval size."""
t, h = self.time, self.half_duration
h /= self.scaling_coeff_x
self.set_interval((t - h, t + h))
|
[
"def",
"narrow",
"(",
"self",
")",
":",
"t",
",",
"h",
"=",
"self",
".",
"time",
",",
"self",
".",
"half_duration",
"h",
"/=",
"self",
".",
"scaling_coeff_x",
"self",
".",
"set_interval",
"(",
"(",
"t",
"-",
"h",
",",
"t",
"+",
"h",
")",
")"
] |
Decrease the interval size.
|
[
"Decrease",
"the",
"interval",
"size",
"."
] |
7e9313dc364304b7d2bd03b92938347343703003
|
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L419-L423
|
7,894
|
robmarkcole/HASS-data-detective
|
detective/auth.py
|
auth_from_hass_config
|
def auth_from_hass_config(path=None, **kwargs):
"""Initialize auth from HASS config."""
if path is None:
path = config.find_hass_config()
return Auth(os.path.join(path, ".storage/auth"), **kwargs)
|
python
|
def auth_from_hass_config(path=None, **kwargs):
"""Initialize auth from HASS config."""
if path is None:
path = config.find_hass_config()
return Auth(os.path.join(path, ".storage/auth"), **kwargs)
|
[
"def",
"auth_from_hass_config",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"config",
".",
"find_hass_config",
"(",
")",
"return",
"Auth",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\".storage/auth\"",
")",
",",
"*",
"*",
"kwargs",
")"
] |
Initialize auth from HASS config.
|
[
"Initialize",
"auth",
"from",
"HASS",
"config",
"."
] |
f67dfde9dd63a3af411944d1857b0835632617c5
|
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/auth.py#L8-L13
|
7,895
|
robmarkcole/HASS-data-detective
|
detective/auth.py
|
Auth.user_name
|
def user_name(self, user_id):
"""Return name for user."""
user = self.users.get(user_id)
if user is None:
return "Unknown user ({})".format(user_id)
return user["name"]
|
python
|
def user_name(self, user_id):
"""Return name for user."""
user = self.users.get(user_id)
if user is None:
return "Unknown user ({})".format(user_id)
return user["name"]
|
[
"def",
"user_name",
"(",
"self",
",",
"user_id",
")",
":",
"user",
"=",
"self",
".",
"users",
".",
"get",
"(",
"user_id",
")",
"if",
"user",
"is",
"None",
":",
"return",
"\"Unknown user ({})\"",
".",
"format",
"(",
"user_id",
")",
"return",
"user",
"[",
"\"name\"",
"]"
] |
Return name for user.
|
[
"Return",
"name",
"for",
"user",
"."
] |
f67dfde9dd63a3af411944d1857b0835632617c5
|
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/auth.py#L35-L42
|
7,896
|
robmarkcole/HASS-data-detective
|
detective/config.py
|
default_hass_config_dir
|
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
|
python
|
def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant")
|
[
"def",
"default_hass_config_dir",
"(",
")",
":",
"data_dir",
"=",
"os",
".",
"getenv",
"(",
"\"APPDATA\"",
")",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
"else",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\".homeassistant\"",
")"
] |
Put together the default configuration directory based on the OS.
|
[
"Put",
"together",
"the",
"default",
"configuration",
"directory",
"based",
"on",
"the",
"OS",
"."
] |
f67dfde9dd63a3af411944d1857b0835632617c5
|
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L10-L13
|
7,897
|
robmarkcole/HASS-data-detective
|
detective/config.py
|
find_hass_config
|
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
|
python
|
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
)
|
[
"def",
"find_hass_config",
"(",
")",
":",
"if",
"\"HASSIO_TOKEN\"",
"in",
"os",
".",
"environ",
":",
"return",
"\"/config\"",
"config_dir",
"=",
"default_hass_config_dir",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"config_dir",
")",
":",
"return",
"config_dir",
"raise",
"ValueError",
"(",
"\"Unable to automatically find the location of Home Assistant \"",
"\"config. Please pass it in.\"",
")"
] |
Try to find HASS config.
|
[
"Try",
"to",
"find",
"HASS",
"config",
"."
] |
f67dfde9dd63a3af411944d1857b0835632617c5
|
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L16-L29
|
7,898
|
robmarkcole/HASS-data-detective
|
detective/config.py
|
_secret_yaml
|
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
|
python
|
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None
|
[
"def",
"_secret_yaml",
"(",
"loader",
",",
"node",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"loader",
".",
"name",
")",
",",
"\"secrets.yaml\"",
")",
"try",
":",
"with",
"open",
"(",
"fname",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"secret_file",
":",
"secrets",
"=",
"YAML",
"(",
"typ",
"=",
"\"safe\"",
")",
".",
"load",
"(",
"secret_file",
")",
"except",
"FileNotFoundError",
":",
"raise",
"ValueError",
"(",
"\"Secrets file {} not found\"",
".",
"format",
"(",
"fname",
")",
")",
"from",
"None",
"try",
":",
"return",
"secrets",
"[",
"node",
".",
"value",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Secret {} not found\"",
".",
"format",
"(",
"node",
".",
"value",
")",
")",
"from",
"None"
] |
Load secrets and embed it into the configuration YAML.
|
[
"Load",
"secrets",
"and",
"embed",
"it",
"into",
"the",
"configuration",
"YAML",
"."
] |
f67dfde9dd63a3af411944d1857b0835632617c5
|
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L36-L49
|
7,899
|
robmarkcole/HASS-data-detective
|
detective/config.py
|
_include_yaml
|
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
|
python
|
def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
|
[
"def",
"_include_yaml",
"(",
"loader",
",",
"node",
")",
":",
"return",
"load_yaml",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"loader",
".",
"name",
")",
",",
"node",
".",
"value",
")",
")"
] |
Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
|
[
"Load",
"another",
"YAML",
"file",
"and",
"embeds",
"it",
"using",
"the",
"!include",
"tag",
"."
] |
f67dfde9dd63a3af411944d1857b0835632617c5
|
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L52-L58
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.