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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
wonambi-python/wonambi | wonambi/widgets/overview.py | Overview.display_markers | def display_markers(self):
"""Mark all the markers, from the dataset.
This function should be called only when we load the dataset or when
we change the settings.
"""
for rect in self.idx_markers:
self.scene.removeItem(rect)
self.idx_markers = []
markers = []
if self.parent.info.markers is not None:
if self.parent.value('marker_show'):
markers = self.parent.info.markers
for mrk in markers:
rect = QGraphicsRectItem(mrk['start'],
BARS['markers']['pos0'],
mrk['end'] - mrk['start'],
BARS['markers']['pos1'])
self.scene.addItem(rect)
color = self.parent.value('marker_color')
rect.setPen(QPen(QColor(color)))
rect.setBrush(QBrush(QColor(color)))
rect.setZValue(-5)
self.idx_markers.append(rect) | python | def display_markers(self):
"""Mark all the markers, from the dataset.
This function should be called only when we load the dataset or when
we change the settings.
"""
for rect in self.idx_markers:
self.scene.removeItem(rect)
self.idx_markers = []
markers = []
if self.parent.info.markers is not None:
if self.parent.value('marker_show'):
markers = self.parent.info.markers
for mrk in markers:
rect = QGraphicsRectItem(mrk['start'],
BARS['markers']['pos0'],
mrk['end'] - mrk['start'],
BARS['markers']['pos1'])
self.scene.addItem(rect)
color = self.parent.value('marker_color')
rect.setPen(QPen(QColor(color)))
rect.setBrush(QBrush(QColor(color)))
rect.setZValue(-5)
self.idx_markers.append(rect) | [
"def",
"display_markers",
"(",
"self",
")",
":",
"for",
"rect",
"in",
"self",
".",
"idx_markers",
":",
"self",
".",
"scene",
".",
"removeItem",
"(",
"rect",
")",
"self",
".",
"idx_markers",
"=",
"[",
"]",
"markers",
"=",
"[",
"]",
"if",
"self",
".",
... | Mark all the markers, from the dataset.
This function should be called only when we load the dataset or when
we change the settings. | [
"Mark",
"all",
"the",
"markers",
"from",
"the",
"dataset",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L267-L293 | train | 23,500 |
wonambi-python/wonambi | wonambi/widgets/overview.py | Overview.mark_stages | def mark_stages(self, start_time, length, stage_name):
"""Mark stages, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
stage_name : str
one of the stages defined in global stages.
"""
y_pos = BARS['stage']['pos0']
current_stage = STAGES.get(stage_name, STAGES['Unknown'])
# the -1 is really important, otherwise we stay on the edge of the rect
old_score = self.scene.itemAt(start_time + length / 2,
y_pos +
current_stage['pos0'] +
current_stage['pos1'] - 1,
self.transform())
# check we are not removing the black border
if old_score is not None and old_score.pen() == NoPen:
lg.debug('Removing old score at {}'.format(start_time))
self.scene.removeItem(old_score)
self.idx_annot.remove(old_score)
rect = QGraphicsRectItem(start_time,
y_pos + current_stage['pos0'],
length,
current_stage['pos1'])
rect.setPen(NoPen)
rect.setBrush(current_stage['color'])
self.scene.addItem(rect)
self.idx_annot.append(rect) | python | def mark_stages(self, start_time, length, stage_name):
"""Mark stages, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
stage_name : str
one of the stages defined in global stages.
"""
y_pos = BARS['stage']['pos0']
current_stage = STAGES.get(stage_name, STAGES['Unknown'])
# the -1 is really important, otherwise we stay on the edge of the rect
old_score = self.scene.itemAt(start_time + length / 2,
y_pos +
current_stage['pos0'] +
current_stage['pos1'] - 1,
self.transform())
# check we are not removing the black border
if old_score is not None and old_score.pen() == NoPen:
lg.debug('Removing old score at {}'.format(start_time))
self.scene.removeItem(old_score)
self.idx_annot.remove(old_score)
rect = QGraphicsRectItem(start_time,
y_pos + current_stage['pos0'],
length,
current_stage['pos1'])
rect.setPen(NoPen)
rect.setBrush(current_stage['color'])
self.scene.addItem(rect)
self.idx_annot.append(rect) | [
"def",
"mark_stages",
"(",
"self",
",",
"start_time",
",",
"length",
",",
"stage_name",
")",
":",
"y_pos",
"=",
"BARS",
"[",
"'stage'",
"]",
"[",
"'pos0'",
"]",
"current_stage",
"=",
"STAGES",
".",
"get",
"(",
"stage_name",
",",
"STAGES",
"[",
"'Unknown'... | Mark stages, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
stage_name : str
one of the stages defined in global stages. | [
"Mark",
"stages",
"only",
"add",
"the",
"new",
"ones",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L351-L386 | train | 23,501 |
wonambi-python/wonambi | wonambi/widgets/overview.py | Overview.mark_quality | def mark_quality(self, start_time, length, qual_name):
"""Mark signal quality, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
qual_name : str
one of the stages defined in global stages.
"""
y_pos = BARS['quality']['pos0']
height = 10
# the -1 is really important, otherwise we stay on the edge of the rect
old_score = self.scene.itemAt(start_time + length / 2,
y_pos + height - 1,
self.transform())
# check we are not removing the black border
if old_score is not None and old_score.pen() == NoPen:
lg.debug('Removing old score at {}'.format(start_time))
self.scene.removeItem(old_score)
self.idx_annot.remove(old_score)
if qual_name == 'Poor':
rect = QGraphicsRectItem(start_time, y_pos, length, height)
rect.setPen(NoPen)
rect.setBrush(Qt.black)
self.scene.addItem(rect)
self.idx_annot.append(rect) | python | def mark_quality(self, start_time, length, qual_name):
"""Mark signal quality, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
qual_name : str
one of the stages defined in global stages.
"""
y_pos = BARS['quality']['pos0']
height = 10
# the -1 is really important, otherwise we stay on the edge of the rect
old_score = self.scene.itemAt(start_time + length / 2,
y_pos + height - 1,
self.transform())
# check we are not removing the black border
if old_score is not None and old_score.pen() == NoPen:
lg.debug('Removing old score at {}'.format(start_time))
self.scene.removeItem(old_score)
self.idx_annot.remove(old_score)
if qual_name == 'Poor':
rect = QGraphicsRectItem(start_time, y_pos, length, height)
rect.setPen(NoPen)
rect.setBrush(Qt.black)
self.scene.addItem(rect)
self.idx_annot.append(rect) | [
"def",
"mark_quality",
"(",
"self",
",",
"start_time",
",",
"length",
",",
"qual_name",
")",
":",
"y_pos",
"=",
"BARS",
"[",
"'quality'",
"]",
"[",
"'pos0'",
"]",
"height",
"=",
"10",
"# the -1 is really important, otherwise we stay on the edge of the rect",
"old_sc... | Mark signal quality, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
qual_name : str
one of the stages defined in global stages. | [
"Mark",
"signal",
"quality",
"only",
"add",
"the",
"new",
"ones",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L388-L419 | train | 23,502 |
wonambi-python/wonambi | wonambi/widgets/overview.py | Overview.mark_cycles | def mark_cycles(self, start_time, length, end=False):
"""Mark cycle bound, only add the new one.
Parameters
----------
start_time: int
start time in s of the bounding epoch
length : int
duration in s of the epoch being scored.
end: bool
If True, marker will be a cycle end marker; otherwise, it's start.
"""
y_pos = STAGES['cycle']['pos0']
height = STAGES['cycle']['pos1']
color = STAGES['cycle']['color']
# the -1 is really important, otherwise we stay on the edge of the rect
old_rect = self.scene.itemAt(start_time + length / 2,
y_pos + height - 1,
self.transform())
# check we are not removing the black border
if old_rect is not None and old_rect.pen() == NoPen:
lg.debug('Removing old score at {}'.format(start_time))
self.scene.removeItem(old_rect)
self.idx_annot.remove(old_rect)
rect = QGraphicsRectItem(start_time, y_pos, 30, height)
rect.setPen(NoPen)
rect.setBrush(color)
self.scene.addItem(rect)
self.idx_annot.append(rect)
if end:
start_time -= 120
kink_hi = QGraphicsRectItem(start_time, y_pos, 150, 1)
kink_hi.setPen(NoPen)
kink_hi.setBrush(color)
self.scene.addItem(kink_hi)
self.idx_annot.append(kink_hi)
kink_lo = QGraphicsRectItem(start_time, y_pos + height, 150, 1)
kink_lo.setPen(NoPen)
kink_lo.setBrush(color)
self.scene.addItem(kink_lo)
self.idx_annot.append(kink_lo) | python | def mark_cycles(self, start_time, length, end=False):
"""Mark cycle bound, only add the new one.
Parameters
----------
start_time: int
start time in s of the bounding epoch
length : int
duration in s of the epoch being scored.
end: bool
If True, marker will be a cycle end marker; otherwise, it's start.
"""
y_pos = STAGES['cycle']['pos0']
height = STAGES['cycle']['pos1']
color = STAGES['cycle']['color']
# the -1 is really important, otherwise we stay on the edge of the rect
old_rect = self.scene.itemAt(start_time + length / 2,
y_pos + height - 1,
self.transform())
# check we are not removing the black border
if old_rect is not None and old_rect.pen() == NoPen:
lg.debug('Removing old score at {}'.format(start_time))
self.scene.removeItem(old_rect)
self.idx_annot.remove(old_rect)
rect = QGraphicsRectItem(start_time, y_pos, 30, height)
rect.setPen(NoPen)
rect.setBrush(color)
self.scene.addItem(rect)
self.idx_annot.append(rect)
if end:
start_time -= 120
kink_hi = QGraphicsRectItem(start_time, y_pos, 150, 1)
kink_hi.setPen(NoPen)
kink_hi.setBrush(color)
self.scene.addItem(kink_hi)
self.idx_annot.append(kink_hi)
kink_lo = QGraphicsRectItem(start_time, y_pos + height, 150, 1)
kink_lo.setPen(NoPen)
kink_lo.setBrush(color)
self.scene.addItem(kink_lo)
self.idx_annot.append(kink_lo) | [
"def",
"mark_cycles",
"(",
"self",
",",
"start_time",
",",
"length",
",",
"end",
"=",
"False",
")",
":",
"y_pos",
"=",
"STAGES",
"[",
"'cycle'",
"]",
"[",
"'pos0'",
"]",
"height",
"=",
"STAGES",
"[",
"'cycle'",
"]",
"[",
"'pos1'",
"]",
"color",
"=",
... | Mark cycle bound, only add the new one.
Parameters
----------
start_time: int
start time in s of the bounding epoch
length : int
duration in s of the epoch being scored.
end: bool
If True, marker will be a cycle end marker; otherwise, it's start. | [
"Mark",
"cycle",
"bound",
"only",
"add",
"the",
"new",
"one",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L421-L467 | train | 23,503 |
wonambi-python/wonambi | wonambi/widgets/overview.py | Overview.mousePressEvent | def mousePressEvent(self, event):
"""Jump to window when user clicks on overview.
Parameters
----------
event : instance of QtCore.QEvent
it contains the position that was clicked.
"""
if self.scene is not None:
x_in_scene = self.mapToScene(event.pos()).x()
window_length = self.parent.value('window_length')
window_start = int(floor(x_in_scene / window_length) *
window_length)
if self.parent.notes.annot is not None:
window_start = self.parent.notes.annot.get_epoch_start(
window_start)
self.update_position(window_start) | python | def mousePressEvent(self, event):
"""Jump to window when user clicks on overview.
Parameters
----------
event : instance of QtCore.QEvent
it contains the position that was clicked.
"""
if self.scene is not None:
x_in_scene = self.mapToScene(event.pos()).x()
window_length = self.parent.value('window_length')
window_start = int(floor(x_in_scene / window_length) *
window_length)
if self.parent.notes.annot is not None:
window_start = self.parent.notes.annot.get_epoch_start(
window_start)
self.update_position(window_start) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"scene",
"is",
"not",
"None",
":",
"x_in_scene",
"=",
"self",
".",
"mapToScene",
"(",
"event",
".",
"pos",
"(",
")",
")",
".",
"x",
"(",
")",
"window_length",
"=",
"s... | Jump to window when user clicks on overview.
Parameters
----------
event : instance of QtCore.QEvent
it contains the position that was clicked. | [
"Jump",
"to",
"window",
"when",
"user",
"clicks",
"on",
"overview",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L494-L510 | train | 23,504 |
wonambi-python/wonambi | wonambi/widgets/overview.py | Overview.reset | def reset(self):
"""Reset the widget, and clear the scene."""
self.minimum = None
self.maximum = None
self.start_time = None # datetime, absolute start time
self.idx_current = None
self.idx_markers = []
self.idx_annot = []
if self.scene is not None:
self.scene.clear()
self.scene = None | python | def reset(self):
"""Reset the widget, and clear the scene."""
self.minimum = None
self.maximum = None
self.start_time = None # datetime, absolute start time
self.idx_current = None
self.idx_markers = []
self.idx_annot = []
if self.scene is not None:
self.scene.clear()
self.scene = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"minimum",
"=",
"None",
"self",
".",
"maximum",
"=",
"None",
"self",
".",
"start_time",
"=",
"None",
"# datetime, absolute start time",
"self",
".",
"idx_current",
"=",
"None",
"self",
".",
"idx_markers",
... | Reset the widget, and clear the scene. | [
"Reset",
"the",
"widget",
"and",
"clear",
"the",
"scene",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L512-L524 | train | 23,505 |
wonambi-python/wonambi | wonambi/viz/plot_3d.py | _prepare_colors | def _prepare_colors(color, values, limits_c, colormap, alpha, chan=None):
"""Return colors for all the channels based on various inputs.
Parameters
----------
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (0 = transparent, 1 = opaque)
chan : instance of Channels
use labels to create channel groups
Returns
-------
1d / 2d array
colors for all the channels or for each channel individually
tuple of two float or None
limits for the values
"""
if values is not None:
if limits_c is None:
limits_c = array([-1, 1]) * nanmax(abs(values))
norm_values = normalize(values, *limits_c)
cm = get_colormap(colormap)
colors = cm[norm_values]
elif color is not None:
colors = ColorArray(color)
else:
cm = get_colormap('hsl')
group_idx = _chan_groups_to_index(chan)
colors = cm[group_idx]
if alpha is not None:
colors.alpha = alpha
return colors, limits_c | python | def _prepare_colors(color, values, limits_c, colormap, alpha, chan=None):
"""Return colors for all the channels based on various inputs.
Parameters
----------
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (0 = transparent, 1 = opaque)
chan : instance of Channels
use labels to create channel groups
Returns
-------
1d / 2d array
colors for all the channels or for each channel individually
tuple of two float or None
limits for the values
"""
if values is not None:
if limits_c is None:
limits_c = array([-1, 1]) * nanmax(abs(values))
norm_values = normalize(values, *limits_c)
cm = get_colormap(colormap)
colors = cm[norm_values]
elif color is not None:
colors = ColorArray(color)
else:
cm = get_colormap('hsl')
group_idx = _chan_groups_to_index(chan)
colors = cm[group_idx]
if alpha is not None:
colors.alpha = alpha
return colors, limits_c | [
"def",
"_prepare_colors",
"(",
"color",
",",
"values",
",",
"limits_c",
",",
"colormap",
",",
"alpha",
",",
"chan",
"=",
"None",
")",
":",
"if",
"values",
"is",
"not",
"None",
":",
"if",
"limits_c",
"is",
"None",
":",
"limits_c",
"=",
"array",
"(",
"... | Return colors for all the channels based on various inputs.
Parameters
----------
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (0 = transparent, 1 = opaque)
chan : instance of Channels
use labels to create channel groups
Returns
-------
1d / 2d array
colors for all the channels or for each channel individually
tuple of two float or None
limits for the values | [
"Return",
"colors",
"for",
"all",
"the",
"channels",
"based",
"on",
"various",
"inputs",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/plot_3d.py#L146-L191 | train | 23,506 |
wonambi-python/wonambi | wonambi/viz/plot_3d.py | Viz3.add_surf | def add_surf(self, surf, color=SKIN_COLOR, vertex_colors=None,
values=None, limits_c=None, colormap=COLORMAP, alpha=1,
colorbar=False):
"""Add surfaces to the visualization.
Parameters
----------
surf : instance of wonambi.attr.anat.Surf
surface to be plotted
color : tuple or ndarray, optional
4-element tuple, representing RGB and alpha, between 0 and 1
vertex_colors : ndarray
ndarray with n vertices x 4 to specify color of each vertex
values : ndarray, optional
vector with values for each vertex
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (1 = opaque)
colorbar : bool
add a colorbar at the back of the surface
"""
colors, limits = _prepare_colors(color=color, values=values,
limits_c=limits_c, colormap=colormap,
alpha=alpha)
# meshdata uses numpy array, in the correct dimension
vertex_colors = colors.rgba
if vertex_colors.shape[0] == 1:
vertex_colors = tile(vertex_colors, (surf.n_vert, 1))
meshdata = MeshData(vertices=surf.vert, faces=surf.tri,
vertex_colors=vertex_colors)
mesh = SurfaceMesh(meshdata)
self._add_mesh(mesh)
# adjust camera
surf_center = mean(surf.vert, axis=0)
if surf_center[0] < 0:
azimuth = 270
else:
azimuth = 90
self._view.camera.azimuth = azimuth
self._view.camera.center = surf_center
self._surf.append(mesh)
if colorbar:
self._view.add(_colorbar_for_surf(colormap, limits)) | python | def add_surf(self, surf, color=SKIN_COLOR, vertex_colors=None,
values=None, limits_c=None, colormap=COLORMAP, alpha=1,
colorbar=False):
"""Add surfaces to the visualization.
Parameters
----------
surf : instance of wonambi.attr.anat.Surf
surface to be plotted
color : tuple or ndarray, optional
4-element tuple, representing RGB and alpha, between 0 and 1
vertex_colors : ndarray
ndarray with n vertices x 4 to specify color of each vertex
values : ndarray, optional
vector with values for each vertex
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (1 = opaque)
colorbar : bool
add a colorbar at the back of the surface
"""
colors, limits = _prepare_colors(color=color, values=values,
limits_c=limits_c, colormap=colormap,
alpha=alpha)
# meshdata uses numpy array, in the correct dimension
vertex_colors = colors.rgba
if vertex_colors.shape[0] == 1:
vertex_colors = tile(vertex_colors, (surf.n_vert, 1))
meshdata = MeshData(vertices=surf.vert, faces=surf.tri,
vertex_colors=vertex_colors)
mesh = SurfaceMesh(meshdata)
self._add_mesh(mesh)
# adjust camera
surf_center = mean(surf.vert, axis=0)
if surf_center[0] < 0:
azimuth = 270
else:
azimuth = 90
self._view.camera.azimuth = azimuth
self._view.camera.center = surf_center
self._surf.append(mesh)
if colorbar:
self._view.add(_colorbar_for_surf(colormap, limits)) | [
"def",
"add_surf",
"(",
"self",
",",
"surf",
",",
"color",
"=",
"SKIN_COLOR",
",",
"vertex_colors",
"=",
"None",
",",
"values",
"=",
"None",
",",
"limits_c",
"=",
"None",
",",
"colormap",
"=",
"COLORMAP",
",",
"alpha",
"=",
"1",
",",
"colorbar",
"=",
... | Add surfaces to the visualization.
Parameters
----------
surf : instance of wonambi.attr.anat.Surf
surface to be plotted
color : tuple or ndarray, optional
4-element tuple, representing RGB and alpha, between 0 and 1
vertex_colors : ndarray
ndarray with n vertices x 4 to specify color of each vertex
values : ndarray, optional
vector with values for each vertex
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (1 = opaque)
colorbar : bool
add a colorbar at the back of the surface | [
"Add",
"surfaces",
"to",
"the",
"visualization",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/plot_3d.py#L42-L93 | train | 23,507 |
wonambi-python/wonambi | wonambi/viz/plot_3d.py | Viz3.add_chan | def add_chan(self, chan, color=None, values=None, limits_c=None,
colormap=CHAN_COLORMAP, alpha=None, colorbar=False):
"""Add channels to visualization
Parameters
----------
chan : instance of Channels
channels to plot
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (0 = transparent, 1 = opaque)
colorbar : bool
add a colorbar at the back of the surface
"""
# reuse previous limits
if limits_c is None and self._chan_limits is not None:
limits_c = self._chan_limits
chan_colors, limits = _prepare_colors(color=color, values=values,
limits_c=limits_c,
colormap=colormap, alpha=alpha,
chan=chan)
self._chan_limits = limits
xyz = chan.return_xyz()
marker = Markers()
marker.set_data(pos=xyz, size=CHAN_SIZE, face_color=chan_colors)
self._add_mesh(marker)
if colorbar:
self._view.add(_colorbar_for_surf(colormap, limits)) | python | def add_chan(self, chan, color=None, values=None, limits_c=None,
colormap=CHAN_COLORMAP, alpha=None, colorbar=False):
"""Add channels to visualization
Parameters
----------
chan : instance of Channels
channels to plot
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (0 = transparent, 1 = opaque)
colorbar : bool
add a colorbar at the back of the surface
"""
# reuse previous limits
if limits_c is None and self._chan_limits is not None:
limits_c = self._chan_limits
chan_colors, limits = _prepare_colors(color=color, values=values,
limits_c=limits_c,
colormap=colormap, alpha=alpha,
chan=chan)
self._chan_limits = limits
xyz = chan.return_xyz()
marker = Markers()
marker.set_data(pos=xyz, size=CHAN_SIZE, face_color=chan_colors)
self._add_mesh(marker)
if colorbar:
self._view.add(_colorbar_for_surf(colormap, limits)) | [
"def",
"add_chan",
"(",
"self",
",",
"chan",
",",
"color",
"=",
"None",
",",
"values",
"=",
"None",
",",
"limits_c",
"=",
"None",
",",
"colormap",
"=",
"CHAN_COLORMAP",
",",
"alpha",
"=",
"None",
",",
"colorbar",
"=",
"False",
")",
":",
"# reuse previo... | Add channels to visualization
Parameters
----------
chan : instance of Channels
channels to plot
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_c : tuple of 2 floats, optional
min and max values to normalize the color
colormap : str
one of the colormaps in vispy
alpha : float
transparency (0 = transparent, 1 = opaque)
colorbar : bool
add a colorbar at the back of the surface | [
"Add",
"channels",
"to",
"visualization"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/plot_3d.py#L95-L133 | train | 23,508 |
wonambi-python/wonambi | wonambi/trans/select.py | select | def select(data, trial=None, invert=False, **axes_to_select):
"""Define the selection of trials, using ranges or actual values.
Parameters
----------
data : instance of Data
data to select from.
trial : list of int or ndarray (dtype='i'), optional
index of trials of interest
**axes_to_select, optional
Values need to be tuple or list. If the values in one axis are string,
then you need to specify all the strings that you want. If the values
are numeric, then you should specify the range (you cannot specify
single values, nor multiple values). To select only up to one point,
you can use (None, value_of_interest)
invert : bool
take the opposite selection
Returns
-------
instance, same class as input
data where selection has been applied.
"""
if trial is not None and not isinstance(trial, Iterable):
raise TypeError('Trial needs to be iterable.')
for axis_to_select, values_to_select in axes_to_select.items():
if (not isinstance(values_to_select, Iterable) or
isinstance(values_to_select, str)):
raise TypeError(axis_to_select + ' needs to be iterable.')
if trial is None:
trial = range(data.number_of('trial'))
else:
trial = trial
if invert:
trial = setdiff1d(range(data.number_of('trial')), trial)
# create empty axis
output = data._copy(axis=False)
for one_axis in output.axis:
output.axis[one_axis] = empty(len(trial), dtype='O')
output.data = empty(len(trial), dtype='O')
to_select = {}
for cnt, i in enumerate(trial):
lg.debug('Selection on trial {0: 6}'.format(i))
for one_axis in output.axis:
values = data.axis[one_axis][i]
if one_axis in axes_to_select.keys():
values_to_select = axes_to_select[one_axis]
if len(values_to_select) == 0:
selected_values = ()
elif isinstance(values_to_select[0], str):
selected_values = asarray(values_to_select, dtype='U')
else:
if (values_to_select[0] is None and
values_to_select[1] is None):
bool_values = ones(len(values), dtype=bool)
elif values_to_select[0] is None:
bool_values = values < values_to_select[1]
elif values_to_select[1] is None:
bool_values = values_to_select[0] <= values
else:
bool_values = ((values_to_select[0] <= values) &
(values < values_to_select[1]))
selected_values = values[bool_values]
if invert:
selected_values = setdiff1d(values, selected_values)
lg.debug('In axis {0}, selecting {1: 6} '
'values'.format(one_axis,
len(selected_values)))
to_select[one_axis] = selected_values
else:
lg.debug('In axis ' + one_axis + ', selecting all the '
'values')
selected_values = data.axis[one_axis][i]
output.axis[one_axis][cnt] = selected_values
output.data[cnt] = data(trial=i, **to_select)
return output | python | def select(data, trial=None, invert=False, **axes_to_select):
"""Define the selection of trials, using ranges or actual values.
Parameters
----------
data : instance of Data
data to select from.
trial : list of int or ndarray (dtype='i'), optional
index of trials of interest
**axes_to_select, optional
Values need to be tuple or list. If the values in one axis are string,
then you need to specify all the strings that you want. If the values
are numeric, then you should specify the range (you cannot specify
single values, nor multiple values). To select only up to one point,
you can use (None, value_of_interest)
invert : bool
take the opposite selection
Returns
-------
instance, same class as input
data where selection has been applied.
"""
if trial is not None and not isinstance(trial, Iterable):
raise TypeError('Trial needs to be iterable.')
for axis_to_select, values_to_select in axes_to_select.items():
if (not isinstance(values_to_select, Iterable) or
isinstance(values_to_select, str)):
raise TypeError(axis_to_select + ' needs to be iterable.')
if trial is None:
trial = range(data.number_of('trial'))
else:
trial = trial
if invert:
trial = setdiff1d(range(data.number_of('trial')), trial)
# create empty axis
output = data._copy(axis=False)
for one_axis in output.axis:
output.axis[one_axis] = empty(len(trial), dtype='O')
output.data = empty(len(trial), dtype='O')
to_select = {}
for cnt, i in enumerate(trial):
lg.debug('Selection on trial {0: 6}'.format(i))
for one_axis in output.axis:
values = data.axis[one_axis][i]
if one_axis in axes_to_select.keys():
values_to_select = axes_to_select[one_axis]
if len(values_to_select) == 0:
selected_values = ()
elif isinstance(values_to_select[0], str):
selected_values = asarray(values_to_select, dtype='U')
else:
if (values_to_select[0] is None and
values_to_select[1] is None):
bool_values = ones(len(values), dtype=bool)
elif values_to_select[0] is None:
bool_values = values < values_to_select[1]
elif values_to_select[1] is None:
bool_values = values_to_select[0] <= values
else:
bool_values = ((values_to_select[0] <= values) &
(values < values_to_select[1]))
selected_values = values[bool_values]
if invert:
selected_values = setdiff1d(values, selected_values)
lg.debug('In axis {0}, selecting {1: 6} '
'values'.format(one_axis,
len(selected_values)))
to_select[one_axis] = selected_values
else:
lg.debug('In axis ' + one_axis + ', selecting all the '
'values')
selected_values = data.axis[one_axis][i]
output.axis[one_axis][cnt] = selected_values
output.data[cnt] = data(trial=i, **to_select)
return output | [
"def",
"select",
"(",
"data",
",",
"trial",
"=",
"None",
",",
"invert",
"=",
"False",
",",
"*",
"*",
"axes_to_select",
")",
":",
"if",
"trial",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"trial",
",",
"Iterable",
")",
":",
"raise",
"TypeEr... | Define the selection of trials, using ranges or actual values.
Parameters
----------
data : instance of Data
data to select from.
trial : list of int or ndarray (dtype='i'), optional
index of trials of interest
**axes_to_select, optional
Values need to be tuple or list. If the values in one axis are string,
then you need to specify all the strings that you want. If the values
are numeric, then you should specify the range (you cannot specify
single values, nor multiple values). To select only up to one point,
you can use (None, value_of_interest)
invert : bool
take the opposite selection
Returns
-------
instance, same class as input
data where selection has been applied. | [
"Define",
"the",
"selection",
"of",
"trials",
"using",
"ranges",
"or",
"actual",
"values",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L179-L267 | train | 23,509 |
wonambi-python/wonambi | wonambi/trans/select.py | resample | def resample(data, s_freq=None, axis='time', ftype='fir', n=None):
"""Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsample on (most likely 'time')
ftype : str
filter type to apply. The default here is 'fir', like Matlab but unlike
the default in scipy, because it works better
n : int
The order of the filter (1 less than the length for ‘fir’).
Returns
-------
instance of Data
downsampled data
"""
output = data._copy()
ratio = int(data.s_freq / s_freq)
for i in range(data.number_of('trial')):
output.data[i] = decimate(data.data[i], ratio,
axis=data.index_of(axis),
zero_phase=True)
n_samples = output.data[i].shape[data.index_of(axis)]
output.axis[axis][i] = linspace(data.axis[axis][i][0],
data.axis[axis][i][-1] +
1 / data.s_freq,
n_samples)
output.s_freq = s_freq
return output | python | def resample(data, s_freq=None, axis='time', ftype='fir', n=None):
"""Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsample on (most likely 'time')
ftype : str
filter type to apply. The default here is 'fir', like Matlab but unlike
the default in scipy, because it works better
n : int
The order of the filter (1 less than the length for ‘fir’).
Returns
-------
instance of Data
downsampled data
"""
output = data._copy()
ratio = int(data.s_freq / s_freq)
for i in range(data.number_of('trial')):
output.data[i] = decimate(data.data[i], ratio,
axis=data.index_of(axis),
zero_phase=True)
n_samples = output.data[i].shape[data.index_of(axis)]
output.axis[axis][i] = linspace(data.axis[axis][i][0],
data.axis[axis][i][-1] +
1 / data.s_freq,
n_samples)
output.s_freq = s_freq
return output | [
"def",
"resample",
"(",
"data",
",",
"s_freq",
"=",
"None",
",",
"axis",
"=",
"'time'",
",",
"ftype",
"=",
"'fir'",
",",
"n",
"=",
"None",
")",
":",
"output",
"=",
"data",
".",
"_copy",
"(",
")",
"ratio",
"=",
"int",
"(",
"data",
".",
"s_freq",
... | Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsample on (most likely 'time')
ftype : str
filter type to apply. The default here is 'fir', like Matlab but unlike
the default in scipy, because it works better
n : int
The order of the filter (1 less than the length for ‘fir’).
Returns
-------
instance of Data
downsampled data | [
"Downsample",
"the",
"data",
"after",
"applying",
"a",
"filter",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L270-L308 | train | 23,510 |
wonambi-python/wonambi | wonambi/trans/select.py | fetch | def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None,
cycle=None, chan_full=None, epoch=None, epoch_dur=30,
epoch_overlap=0, epoch_step=None, reject_epoch=False,
reject_artf=False, min_dur=0, buffer=0):
"""Create instance of Segments for analysis, complete with info about
stage, cycle, channel, event type. Segments contains only metadata until
.read_data is called.
Parameters
----------
dataset : instance of Dataset
info about record
annot : instance of Annotations
scoring info
cat : tuple of int
Determines where the signal is concatenated.
If cat[0] is 1, cycles will be concatenated.
If cat[1] is 1, different stages will be concatenated.
If cat[2] is 1, discontinuous signal within a same condition
(stage, cycle, event type) will be concatenated.
If cat[3] is 1, events of different types will be concatenated.
0 in any position indicates no concatenation.
evt_type: list of str, optional
Enter a list of event types to get events; otherwise, epochs will
be returned.
stage: list of str, optional
Stage(s) of interest. If None, stage is ignored.
cycle: list of tuple of two float, optional
Cycle(s) of interest, as start and end times in seconds from record
start. If None, cycles are ignored.
chan_full: list of str or None
Channel(s) of interest, only used for events (epochs have no
channel). Channel format is 'chan_name (group_name)'.
If used for epochs, separate segments will be returned for each
channel; this is necessary for channel-specific artefact removal (see
reject_artf below). If None, channel is ignored.
epoch : str, optional
If 'locked', returns epochs locked to staging. If 'unlocked', divides
signal (with specified concatenation) into epochs of duration epoch_dur
starting at first sample of every segment and discarding any remainder.
If None, longest run of signal is returned.
epoch_dur : float
only for epoch='unlocked'. Duration of epochs returned, in seconds.
epoch_overlap : float
only for epoch='unlocked'. Ratio of overlap between two consecutive
segments. Value between 0 and 1. Overriden by step.
epoch_step : float
only for epoch='unlocked'. Time between consecutive epoch starts, in
seconds. Overrides epoch_overlap/
reject_epoch: bool
If True, epochs marked as 'Poor' quality or staged as 'Artefact' will
be rejected (and the signal segmented in consequence). Has no effect on
event selection.
reject_artf : bool
If True, excludes events marked as 'Artefact'. If chan_full is
specified, only artefacts marked on a given channel are removed from
that channel. Signal is segmented in consequence.
If None, Artefact events are ignored.
min_dur : float
Minimum duration of segments returned, in seconds.
buffer : float
adds this many seconds of signal before and after each segment
Returns
-------
instance of Segments
metadata for all analysis segments
"""
bundles = get_times(annot, evt_type=evt_type, stage=stage, cycle=cycle,
chan=chan_full, exclude=reject_epoch, buffer=buffer)
# Remove artefacts
if reject_artf and bundles:
for bund in bundles:
bund['times'] = remove_artf_evts(bund['times'], annot,
bund['chan'], min_dur=0)
# Divide bundles into segments to be concatenated
if bundles:
if 'locked' == epoch:
bundles = _divide_bundles(bundles)
elif 'unlocked' == epoch:
if epoch_step is not None:
step = epoch_step
else:
step = epoch_dur - (epoch_dur * epoch_overlap)
bundles = _concat(bundles, cat)
bundles = _find_intervals(bundles, epoch_dur, step)
elif not epoch:
bundles = _concat(bundles, cat)
# Minimum duration
bundles = _longer_than(bundles, min_dur)
segments = Segments(dataset)
segments.segments = bundles
return segments | python | def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None,
cycle=None, chan_full=None, epoch=None, epoch_dur=30,
epoch_overlap=0, epoch_step=None, reject_epoch=False,
reject_artf=False, min_dur=0, buffer=0):
"""Create instance of Segments for analysis, complete with info about
stage, cycle, channel, event type. Segments contains only metadata until
.read_data is called.
Parameters
----------
dataset : instance of Dataset
info about record
annot : instance of Annotations
scoring info
cat : tuple of int
Determines where the signal is concatenated.
If cat[0] is 1, cycles will be concatenated.
If cat[1] is 1, different stages will be concatenated.
If cat[2] is 1, discontinuous signal within a same condition
(stage, cycle, event type) will be concatenated.
If cat[3] is 1, events of different types will be concatenated.
0 in any position indicates no concatenation.
evt_type: list of str, optional
Enter a list of event types to get events; otherwise, epochs will
be returned.
stage: list of str, optional
Stage(s) of interest. If None, stage is ignored.
cycle: list of tuple of two float, optional
Cycle(s) of interest, as start and end times in seconds from record
start. If None, cycles are ignored.
chan_full: list of str or None
Channel(s) of interest, only used for events (epochs have no
channel). Channel format is 'chan_name (group_name)'.
If used for epochs, separate segments will be returned for each
channel; this is necessary for channel-specific artefact removal (see
reject_artf below). If None, channel is ignored.
epoch : str, optional
If 'locked', returns epochs locked to staging. If 'unlocked', divides
signal (with specified concatenation) into epochs of duration epoch_dur
starting at first sample of every segment and discarding any remainder.
If None, longest run of signal is returned.
epoch_dur : float
only for epoch='unlocked'. Duration of epochs returned, in seconds.
epoch_overlap : float
only for epoch='unlocked'. Ratio of overlap between two consecutive
segments. Value between 0 and 1. Overriden by step.
epoch_step : float
only for epoch='unlocked'. Time between consecutive epoch starts, in
seconds. Overrides epoch_overlap/
reject_epoch: bool
If True, epochs marked as 'Poor' quality or staged as 'Artefact' will
be rejected (and the signal segmented in consequence). Has no effect on
event selection.
reject_artf : bool
If True, excludes events marked as 'Artefact'. If chan_full is
specified, only artefacts marked on a given channel are removed from
that channel. Signal is segmented in consequence.
If None, Artefact events are ignored.
min_dur : float
Minimum duration of segments returned, in seconds.
buffer : float
adds this many seconds of signal before and after each segment
Returns
-------
instance of Segments
metadata for all analysis segments
"""
bundles = get_times(annot, evt_type=evt_type, stage=stage, cycle=cycle,
chan=chan_full, exclude=reject_epoch, buffer=buffer)
# Remove artefacts
if reject_artf and bundles:
for bund in bundles:
bund['times'] = remove_artf_evts(bund['times'], annot,
bund['chan'], min_dur=0)
# Divide bundles into segments to be concatenated
if bundles:
if 'locked' == epoch:
bundles = _divide_bundles(bundles)
elif 'unlocked' == epoch:
if epoch_step is not None:
step = epoch_step
else:
step = epoch_dur - (epoch_dur * epoch_overlap)
bundles = _concat(bundles, cat)
bundles = _find_intervals(bundles, epoch_dur, step)
elif not epoch:
bundles = _concat(bundles, cat)
# Minimum duration
bundles = _longer_than(bundles, min_dur)
segments = Segments(dataset)
segments.segments = bundles
return segments | [
"def",
"fetch",
"(",
"dataset",
",",
"annot",
",",
"cat",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
",",
"evt_type",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"cycle",
"=",
"None",
",",
"chan_full",
"=",
"None",
",",
"epoch",
"=",
... | Create instance of Segments for analysis, complete with info about
stage, cycle, channel, event type. Segments contains only metadata until
.read_data is called.
Parameters
----------
dataset : instance of Dataset
info about record
annot : instance of Annotations
scoring info
cat : tuple of int
Determines where the signal is concatenated.
If cat[0] is 1, cycles will be concatenated.
If cat[1] is 1, different stages will be concatenated.
If cat[2] is 1, discontinuous signal within a same condition
(stage, cycle, event type) will be concatenated.
If cat[3] is 1, events of different types will be concatenated.
0 in any position indicates no concatenation.
evt_type: list of str, optional
Enter a list of event types to get events; otherwise, epochs will
be returned.
stage: list of str, optional
Stage(s) of interest. If None, stage is ignored.
cycle: list of tuple of two float, optional
Cycle(s) of interest, as start and end times in seconds from record
start. If None, cycles are ignored.
chan_full: list of str or None
Channel(s) of interest, only used for events (epochs have no
channel). Channel format is 'chan_name (group_name)'.
If used for epochs, separate segments will be returned for each
channel; this is necessary for channel-specific artefact removal (see
reject_artf below). If None, channel is ignored.
epoch : str, optional
If 'locked', returns epochs locked to staging. If 'unlocked', divides
signal (with specified concatenation) into epochs of duration epoch_dur
starting at first sample of every segment and discarding any remainder.
If None, longest run of signal is returned.
epoch_dur : float
only for epoch='unlocked'. Duration of epochs returned, in seconds.
epoch_overlap : float
only for epoch='unlocked'. Ratio of overlap between two consecutive
segments. Value between 0 and 1. Overriden by step.
epoch_step : float
only for epoch='unlocked'. Time between consecutive epoch starts, in
seconds. Overrides epoch_overlap/
reject_epoch: bool
If True, epochs marked as 'Poor' quality or staged as 'Artefact' will
be rejected (and the signal segmented in consequence). Has no effect on
event selection.
reject_artf : bool
If True, excludes events marked as 'Artefact'. If chan_full is
specified, only artefacts marked on a given channel are removed from
that channel. Signal is segmented in consequence.
If None, Artefact events are ignored.
min_dur : float
Minimum duration of segments returned, in seconds.
buffer : float
adds this many seconds of signal before and after each segment
Returns
-------
instance of Segments
metadata for all analysis segments | [
"Create",
"instance",
"of",
"Segments",
"for",
"analysis",
"complete",
"with",
"info",
"about",
"stage",
"cycle",
"channel",
"event",
"type",
".",
"Segments",
"contains",
"only",
"metadata",
"until",
".",
"read_data",
"is",
"called",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L311-L413 | train | 23,511 |
wonambi-python/wonambi | wonambi/trans/select.py | get_times | def get_times(annot, evt_type=None, stage=None, cycle=None, chan=None,
exclude=False, buffer=0):
"""Get start and end times for selected segments of data, bundled
together with info.
Parameters
----------
annot: instance of Annotations
The annotation file containing events and epochs
evt_type: list of str, optional
Enter a list of event types to get events; otherwise, epochs will
be returned.
stage: list of str, optional
Stage(s) of interest. If None, stage is ignored.
cycle: list of tuple of two float, optional
Cycle(s) of interest, as start and end times in seconds from record
start. If None, cycles are ignored.
chan: list of str or tuple of None
Channel(s) of interest. Channel format is 'chan_name (group_name)'.
If None, channel is ignored.
exclude: bool
Exclude epochs by quality. If True, epochs marked as 'Poor' quality
or staged as 'Artefact' will be rejected (and the signal segmented
in consequence). Has no effect on event selection.
buffer : float
adds this many seconds of signal before and after each segment
Returns
-------
list of dict
Each dict has times (the start and end times of each segment, as
list of tuple of float), stage, cycle, chan, name (event type,
if applicable)
Notes
-----
This function returns epoch or event start and end times, bundled
together according to the specified parameters.
Presently, setting exclude to True does not exclude events found in Poor
signal epochs. The rationale is that events would never be marked in Poor
signal epochs. If they were automatically detected, these epochs would
have been left out during detection. If they were manually marked, then
it must have been Good signal. At the moment, in the GUI, the exclude epoch
option is disabled when analyzing events, but we could fix the code if we
find a use case for rejecting events based on the quality of the epoch
signal.
"""
getter = annot.get_epochs
last = annot.last_second
if stage is None:
stage = (None,)
if cycle is None:
cycle = (None,)
if chan is None:
chan = (None,)
if evt_type is None:
evt_type = (None,)
elif isinstance(evt_type[0], str):
getter = annot.get_events
if chan != (None,):
chan.append('') # also retrieve events marked on all channels
else:
lg.error('Event type must be list/tuple of str or None')
qual = None
if exclude:
qual = 'Good'
bundles = []
for et in evt_type:
for ch in chan:
for cyc in cycle:
for ss in stage:
st_input = ss
if ss is not None:
st_input = (ss,)
evochs = getter(name=et, time=cyc, chan=(ch,),
stage=st_input, qual=qual)
if evochs:
times = [(
max(e['start'] - buffer, 0),
min(e['end'] + buffer, last)) for e in evochs]
times = sorted(times, key=lambda x: x[0])
one_bundle = {'times': times,
'stage': ss,
'cycle': cyc,
'chan': ch,
'name': et}
bundles.append(one_bundle)
return bundles | python | def get_times(annot, evt_type=None, stage=None, cycle=None, chan=None,
exclude=False, buffer=0):
"""Get start and end times for selected segments of data, bundled
together with info.
Parameters
----------
annot: instance of Annotations
The annotation file containing events and epochs
evt_type: list of str, optional
Enter a list of event types to get events; otherwise, epochs will
be returned.
stage: list of str, optional
Stage(s) of interest. If None, stage is ignored.
cycle: list of tuple of two float, optional
Cycle(s) of interest, as start and end times in seconds from record
start. If None, cycles are ignored.
chan: list of str or tuple of None
Channel(s) of interest. Channel format is 'chan_name (group_name)'.
If None, channel is ignored.
exclude: bool
Exclude epochs by quality. If True, epochs marked as 'Poor' quality
or staged as 'Artefact' will be rejected (and the signal segmented
in consequence). Has no effect on event selection.
buffer : float
adds this many seconds of signal before and after each segment
Returns
-------
list of dict
Each dict has times (the start and end times of each segment, as
list of tuple of float), stage, cycle, chan, name (event type,
if applicable)
Notes
-----
This function returns epoch or event start and end times, bundled
together according to the specified parameters.
Presently, setting exclude to True does not exclude events found in Poor
signal epochs. The rationale is that events would never be marked in Poor
signal epochs. If they were automatically detected, these epochs would
have been left out during detection. If they were manually marked, then
it must have been Good signal. At the moment, in the GUI, the exclude epoch
option is disabled when analyzing events, but we could fix the code if we
find a use case for rejecting events based on the quality of the epoch
signal.
"""
getter = annot.get_epochs
last = annot.last_second
if stage is None:
stage = (None,)
if cycle is None:
cycle = (None,)
if chan is None:
chan = (None,)
if evt_type is None:
evt_type = (None,)
elif isinstance(evt_type[0], str):
getter = annot.get_events
if chan != (None,):
chan.append('') # also retrieve events marked on all channels
else:
lg.error('Event type must be list/tuple of str or None')
qual = None
if exclude:
qual = 'Good'
bundles = []
for et in evt_type:
for ch in chan:
for cyc in cycle:
for ss in stage:
st_input = ss
if ss is not None:
st_input = (ss,)
evochs = getter(name=et, time=cyc, chan=(ch,),
stage=st_input, qual=qual)
if evochs:
times = [(
max(e['start'] - buffer, 0),
min(e['end'] + buffer, last)) for e in evochs]
times = sorted(times, key=lambda x: x[0])
one_bundle = {'times': times,
'stage': ss,
'cycle': cyc,
'chan': ch,
'name': et}
bundles.append(one_bundle)
return bundles | [
"def",
"get_times",
"(",
"annot",
",",
"evt_type",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"cycle",
"=",
"None",
",",
"chan",
"=",
"None",
",",
"exclude",
"=",
"False",
",",
"buffer",
"=",
"0",
")",
":",
"getter",
"=",
"annot",
".",
"get_epoch... | Get start and end times for selected segments of data, bundled
together with info.
Parameters
----------
annot: instance of Annotations
The annotation file containing events and epochs
evt_type: list of str, optional
Enter a list of event types to get events; otherwise, epochs will
be returned.
stage: list of str, optional
Stage(s) of interest. If None, stage is ignored.
cycle: list of tuple of two float, optional
Cycle(s) of interest, as start and end times in seconds from record
start. If None, cycles are ignored.
chan: list of str or tuple of None
Channel(s) of interest. Channel format is 'chan_name (group_name)'.
If None, channel is ignored.
exclude: bool
Exclude epochs by quality. If True, epochs marked as 'Poor' quality
or staged as 'Artefact' will be rejected (and the signal segmented
in consequence). Has no effect on event selection.
buffer : float
adds this many seconds of signal before and after each segment
Returns
-------
list of dict
Each dict has times (the start and end times of each segment, as
list of tuple of float), stage, cycle, chan, name (event type,
if applicable)
Notes
-----
This function returns epoch or event start and end times, bundled
together according to the specified parameters.
Presently, setting exclude to True does not exclude events found in Poor
signal epochs. The rationale is that events would never be marked in Poor
signal epochs. If they were automatically detected, these epochs would
have been left out during detection. If they were manually marked, then
it must have been Good signal. At the moment, in the GUI, the exclude epoch
option is disabled when analyzing events, but we could fix the code if we
find a use case for rejecting events based on the quality of the epoch
signal. | [
"Get",
"start",
"and",
"end",
"times",
"for",
"selected",
"segments",
"of",
"data",
"bundled",
"together",
"with",
"info",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L416-L512 | train | 23,512 |
wonambi-python/wonambi | wonambi/trans/select.py | _longer_than | def _longer_than(segments, min_dur):
"""Remove segments longer than min_dur."""
if min_dur <= 0.:
return segments
long_enough = []
for seg in segments:
if sum([t[1] - t[0] for t in seg['times']]) >= min_dur:
long_enough.append(seg)
return long_enough | python | def _longer_than(segments, min_dur):
"""Remove segments longer than min_dur."""
if min_dur <= 0.:
return segments
long_enough = []
for seg in segments:
if sum([t[1] - t[0] for t in seg['times']]) >= min_dur:
long_enough.append(seg)
return long_enough | [
"def",
"_longer_than",
"(",
"segments",
",",
"min_dur",
")",
":",
"if",
"min_dur",
"<=",
"0.",
":",
"return",
"segments",
"long_enough",
"=",
"[",
"]",
"for",
"seg",
"in",
"segments",
":",
"if",
"sum",
"(",
"[",
"t",
"[",
"1",
"]",
"-",
"t",
"[",
... | Remove segments longer than min_dur. | [
"Remove",
"segments",
"longer",
"than",
"min_dur",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L515-L526 | train | 23,513 |
wonambi-python/wonambi | wonambi/trans/select.py | _concat | def _concat(bundles, cat=(0, 0, 0, 0)):
"""Prepare event or epoch start and end times for concatenation."""
chan = sorted(set([x['chan'] for x in bundles]))
cycle = sorted(set([x['cycle'] for x in bundles]))
stage = sorted(set([x['stage'] for x in bundles]))
evt_type = sorted(set([x['name'] for x in bundles]))
all_cycle = None
all_stage = None
all_evt_type = None
if cycle[0] is not None:
all_cycle = ', '.join([str(c) for c in cycle])
if stage[0] is not None:
all_stage = ', '.join(stage)
if evt_type[0] is not None:
all_evt_type = ', '.join(evt_type)
if cat[0]:
cycle = [all_cycle]
if cat[1]:
stage = [all_stage]
if cat[3]:
evt_type = [all_evt_type]
to_concat = []
for ch in chan:
for cyc in cycle:
for st in stage:
for et in evt_type:
new_times = []
for bund in bundles:
chan_cond = ch == bund['chan']
cyc_cond = cyc in (bund['cycle'], all_cycle)
st_cond = st in (bund['stage'], all_stage)
et_cond = et in (bund['name'], all_evt_type)
if chan_cond and cyc_cond and st_cond and et_cond:
new_times.extend(bund['times'])
new_times = sorted(new_times, key=lambda x: x[0])
new_bund = {'times': new_times,
'chan': ch,
'cycle': cyc,
'stage': st,
'name': et
}
to_concat.append(new_bund)
if not cat[2]:
to_concat_new = []
for bund in to_concat:
last = None
bund['times'].append((inf,inf))
start = 0
for i, j in enumerate(bund['times']):
if last is not None:
if not isclose(j[0], last, abs_tol=0.01):
new_times = bund['times'][start:i]
new_bund = bund.copy()
new_bund['times'] = new_times
to_concat_new.append(new_bund)
start = i
last = j[1]
to_concat = to_concat_new
to_concat = [x for x in to_concat if x['times']]
return to_concat | python | def _concat(bundles, cat=(0, 0, 0, 0)):
"""Prepare event or epoch start and end times for concatenation."""
chan = sorted(set([x['chan'] for x in bundles]))
cycle = sorted(set([x['cycle'] for x in bundles]))
stage = sorted(set([x['stage'] for x in bundles]))
evt_type = sorted(set([x['name'] for x in bundles]))
all_cycle = None
all_stage = None
all_evt_type = None
if cycle[0] is not None:
all_cycle = ', '.join([str(c) for c in cycle])
if stage[0] is not None:
all_stage = ', '.join(stage)
if evt_type[0] is not None:
all_evt_type = ', '.join(evt_type)
if cat[0]:
cycle = [all_cycle]
if cat[1]:
stage = [all_stage]
if cat[3]:
evt_type = [all_evt_type]
to_concat = []
for ch in chan:
for cyc in cycle:
for st in stage:
for et in evt_type:
new_times = []
for bund in bundles:
chan_cond = ch == bund['chan']
cyc_cond = cyc in (bund['cycle'], all_cycle)
st_cond = st in (bund['stage'], all_stage)
et_cond = et in (bund['name'], all_evt_type)
if chan_cond and cyc_cond and st_cond and et_cond:
new_times.extend(bund['times'])
new_times = sorted(new_times, key=lambda x: x[0])
new_bund = {'times': new_times,
'chan': ch,
'cycle': cyc,
'stage': st,
'name': et
}
to_concat.append(new_bund)
if not cat[2]:
to_concat_new = []
for bund in to_concat:
last = None
bund['times'].append((inf,inf))
start = 0
for i, j in enumerate(bund['times']):
if last is not None:
if not isclose(j[0], last, abs_tol=0.01):
new_times = bund['times'][start:i]
new_bund = bund.copy()
new_bund['times'] = new_times
to_concat_new.append(new_bund)
start = i
last = j[1]
to_concat = to_concat_new
to_concat = [x for x in to_concat if x['times']]
return to_concat | [
"def",
"_concat",
"(",
"bundles",
",",
"cat",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
":",
"chan",
"=",
"sorted",
"(",
"set",
"(",
"[",
"x",
"[",
"'chan'",
"]",
"for",
"x",
"in",
"bundles",
"]",
")",
")",
"cycle",
"=",
"sorte... | Prepare event or epoch start and end times for concatenation. | [
"Prepare",
"event",
"or",
"epoch",
"start",
"and",
"end",
"times",
"for",
"concatenation",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L529-L607 | train | 23,514 |
wonambi-python/wonambi | wonambi/trans/select.py | _divide_bundles | def _divide_bundles(bundles):
"""Take each subsegment inside a bundle and put it in its own bundle,
copying the bundle metadata."""
divided = []
for bund in bundles:
for t in bund['times']:
new_bund = bund.copy()
new_bund['times'] = [t]
divided.append(new_bund)
return divided | python | def _divide_bundles(bundles):
"""Take each subsegment inside a bundle and put it in its own bundle,
copying the bundle metadata."""
divided = []
for bund in bundles:
for t in bund['times']:
new_bund = bund.copy()
new_bund['times'] = [t]
divided.append(new_bund)
return divided | [
"def",
"_divide_bundles",
"(",
"bundles",
")",
":",
"divided",
"=",
"[",
"]",
"for",
"bund",
"in",
"bundles",
":",
"for",
"t",
"in",
"bund",
"[",
"'times'",
"]",
":",
"new_bund",
"=",
"bund",
".",
"copy",
"(",
")",
"new_bund",
"[",
"'times'",
"]",
... | Take each subsegment inside a bundle and put it in its own bundle,
copying the bundle metadata. | [
"Take",
"each",
"subsegment",
"inside",
"a",
"bundle",
"and",
"put",
"it",
"in",
"its",
"own",
"bundle",
"copying",
"the",
"bundle",
"metadata",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L610-L621 | train | 23,515 |
wonambi-python/wonambi | wonambi/trans/select.py | _find_intervals | def _find_intervals(bundles, duration, step):
"""Divide bundles into segments of a certain duration and a certain step,
discarding any remainder."""
segments = []
for bund in bundles:
beg, end = bund['times'][0][0], bund['times'][-1][1]
if end - beg >= duration:
new_begs = arange(beg, end - duration, step)
for t in new_begs:
seg = bund.copy()
seg['times'] = [(t, t + duration)]
segments.append(seg)
return segments | python | def _find_intervals(bundles, duration, step):
"""Divide bundles into segments of a certain duration and a certain step,
discarding any remainder."""
segments = []
for bund in bundles:
beg, end = bund['times'][0][0], bund['times'][-1][1]
if end - beg >= duration:
new_begs = arange(beg, end - duration, step)
for t in new_begs:
seg = bund.copy()
seg['times'] = [(t, t + duration)]
segments.append(seg)
return segments | [
"def",
"_find_intervals",
"(",
"bundles",
",",
"duration",
",",
"step",
")",
":",
"segments",
"=",
"[",
"]",
"for",
"bund",
"in",
"bundles",
":",
"beg",
",",
"end",
"=",
"bund",
"[",
"'times'",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"bund",
"[",... | Divide bundles into segments of a certain duration and a certain step,
discarding any remainder. | [
"Divide",
"bundles",
"into",
"segments",
"of",
"a",
"certain",
"duration",
"and",
"a",
"certain",
"step",
"discarding",
"any",
"remainder",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L624-L639 | train | 23,516 |
wonambi-python/wonambi | wonambi/trans/select.py | _create_data | def _create_data(data, active_chan, ref_chan=[], grp_name=None):
"""Create data after montage.
Parameters
----------
data : instance of ChanTime
the raw data
active_chan : list of str
the channel(s) of interest, without reference or group
ref_chan : list of str
reference channel(s), without group
grp_name : str
name of channel group, if applicable
Returns
-------
instance of ChanTime
the re-referenced data
"""
output = ChanTime()
output.s_freq = data.s_freq
output.start_time = data.start_time
output.axis['time'] = data.axis['time']
output.axis['chan'] = empty(1, dtype='O')
output.data = empty(1, dtype='O')
output.data[0] = empty((len(active_chan), data.number_of('time')[0]),
dtype='f')
sel_data = _select_channels(data, active_chan + ref_chan)
data1 = montage(sel_data, ref_chan=ref_chan)
data1.data[0] = nan_to_num(data1.data[0])
all_chan_grp_name = []
for i, chan in enumerate(active_chan):
chan_grp_name = chan
if grp_name:
chan_grp_name = chan + ' (' + grp_name + ')'
all_chan_grp_name.append(chan_grp_name)
dat = data1(chan=chan, trial=0)
output.data[0][i, :] = dat
output.axis['chan'][0] = asarray(all_chan_grp_name, dtype='U')
return output | python | def _create_data(data, active_chan, ref_chan=[], grp_name=None):
"""Create data after montage.
Parameters
----------
data : instance of ChanTime
the raw data
active_chan : list of str
the channel(s) of interest, without reference or group
ref_chan : list of str
reference channel(s), without group
grp_name : str
name of channel group, if applicable
Returns
-------
instance of ChanTime
the re-referenced data
"""
output = ChanTime()
output.s_freq = data.s_freq
output.start_time = data.start_time
output.axis['time'] = data.axis['time']
output.axis['chan'] = empty(1, dtype='O')
output.data = empty(1, dtype='O')
output.data[0] = empty((len(active_chan), data.number_of('time')[0]),
dtype='f')
sel_data = _select_channels(data, active_chan + ref_chan)
data1 = montage(sel_data, ref_chan=ref_chan)
data1.data[0] = nan_to_num(data1.data[0])
all_chan_grp_name = []
for i, chan in enumerate(active_chan):
chan_grp_name = chan
if grp_name:
chan_grp_name = chan + ' (' + grp_name + ')'
all_chan_grp_name.append(chan_grp_name)
dat = data1(chan=chan, trial=0)
output.data[0][i, :] = dat
output.axis['chan'][0] = asarray(all_chan_grp_name, dtype='U')
return output | [
"def",
"_create_data",
"(",
"data",
",",
"active_chan",
",",
"ref_chan",
"=",
"[",
"]",
",",
"grp_name",
"=",
"None",
")",
":",
"output",
"=",
"ChanTime",
"(",
")",
"output",
".",
"s_freq",
"=",
"data",
".",
"s_freq",
"output",
".",
"start_time",
"=",
... | Create data after montage.
Parameters
----------
data : instance of ChanTime
the raw data
active_chan : list of str
the channel(s) of interest, without reference or group
ref_chan : list of str
reference channel(s), without group
grp_name : str
name of channel group, if applicable
Returns
-------
instance of ChanTime
the re-referenced data | [
"Create",
"data",
"after",
"montage",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L642-L687 | train | 23,517 |
wonambi-python/wonambi | wonambi/trans/select.py | _select_channels | def _select_channels(data, channels):
"""Select channels.
Parameters
----------
data : instance of ChanTime
data with all the channels
channels : list
channels of interest
Returns
-------
instance of ChanTime
data with only channels of interest
Notes
-----
This function does the same as wonambi.trans.select, but it's much faster.
wonambi.trans.Select needs to flexible for any data type, here we assume
that we have one trial, and that channel is the first dimension.
"""
output = data._copy()
chan_list = list(data.axis['chan'][0])
idx_chan = [chan_list.index(i_chan) for i_chan in channels]
output.data[0] = data.data[0][idx_chan, :]
output.axis['chan'][0] = asarray(channels)
return output | python | def _select_channels(data, channels):
"""Select channels.
Parameters
----------
data : instance of ChanTime
data with all the channels
channels : list
channels of interest
Returns
-------
instance of ChanTime
data with only channels of interest
Notes
-----
This function does the same as wonambi.trans.select, but it's much faster.
wonambi.trans.Select needs to flexible for any data type, here we assume
that we have one trial, and that channel is the first dimension.
"""
output = data._copy()
chan_list = list(data.axis['chan'][0])
idx_chan = [chan_list.index(i_chan) for i_chan in channels]
output.data[0] = data.data[0][idx_chan, :]
output.axis['chan'][0] = asarray(channels)
return output | [
"def",
"_select_channels",
"(",
"data",
",",
"channels",
")",
":",
"output",
"=",
"data",
".",
"_copy",
"(",
")",
"chan_list",
"=",
"list",
"(",
"data",
".",
"axis",
"[",
"'chan'",
"]",
"[",
"0",
"]",
")",
"idx_chan",
"=",
"[",
"chan_list",
".",
"i... | Select channels.
Parameters
----------
data : instance of ChanTime
data with all the channels
channels : list
channels of interest
Returns
-------
instance of ChanTime
data with only channels of interest
Notes
-----
This function does the same as wonambi.trans.select, but it's much faster.
wonambi.trans.Select needs to flexible for any data type, here we assume
that we have one trial, and that channel is the first dimension. | [
"Select",
"channels",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L718-L746 | train | 23,518 |
wonambi-python/wonambi | wonambi/widgets/creation.py | create_widgets | def create_widgets(MAIN):
"""Create all the widgets and dockwidgets. It also creates actions to
toggle views of dockwidgets in dockwidgets.
"""
""" ------ CREATE WIDGETS ------ """
MAIN.labels = Labels(MAIN)
MAIN.channels = Channels(MAIN)
MAIN.notes = Notes(MAIN)
MAIN.merge_dialog = MergeDialog(MAIN)
MAIN.export_events_dialog = ExportEventsDialog(MAIN)
MAIN.export_dataset_dialog = ExportDatasetDialog(MAIN)
MAIN.spindle_dialog = SpindleDialog(MAIN)
MAIN.slow_wave_dialog = SWDialog(MAIN)
MAIN.analysis_dialog = AnalysisDialog(MAIN)
#MAIN.plot_dialog = PlotDialog(MAIN)
MAIN.overview = Overview(MAIN)
MAIN.spectrum = Spectrum(MAIN)
MAIN.traces = Traces(MAIN)
MAIN.video = Video(MAIN)
MAIN.settings = Settings(MAIN) # depends on all widgets apart from Info
MAIN.info = Info(MAIN) # this has to be the last, it depends on settings
MAIN.setCentralWidget(MAIN.traces)
""" ------ LIST DOCKWIDGETS ------ """
new_docks = [{'name': 'Information',
'widget': MAIN.info,
'main_area': Qt.LeftDockWidgetArea,
'extra_area': Qt.RightDockWidgetArea,
},
{'name': 'Labels',
'widget': MAIN.labels,
'main_area': Qt.RightDockWidgetArea,
'extra_area': Qt.LeftDockWidgetArea,
},
{'name': 'Channels',
'widget': MAIN.channels,
'main_area': Qt.RightDockWidgetArea,
'extra_area': Qt.LeftDockWidgetArea,
},
{'name': 'Spectrum',
'widget': MAIN.spectrum,
'main_area': Qt.RightDockWidgetArea,
'extra_area': Qt.LeftDockWidgetArea,
},
{'name': 'Annotations',
'widget': MAIN.notes,
'main_area': Qt.LeftDockWidgetArea,
'extra_area': Qt.RightDockWidgetArea,
},
{'name': 'Video',
'widget': MAIN.video,
'main_area': Qt.LeftDockWidgetArea,
'extra_area': Qt.RightDockWidgetArea,
},
{'name': 'Overview',
'widget': MAIN.overview,
'main_area': Qt.BottomDockWidgetArea,
'extra_area': Qt.TopDockWidgetArea,
},
]
""" ------ CREATE DOCKWIDGETS ------ """
idx_docks = {}
actions = MAIN.action
actions['dockwidgets'] = []
for dock in new_docks:
dockwidget = QDockWidget(dock['name'], MAIN)
dockwidget.setWidget(dock['widget'])
dockwidget.setAllowedAreas(dock['main_area'] | dock['extra_area'])
dockwidget.setObjectName(dock['name']) # savestate
idx_docks[dock['name']] = dockwidget
MAIN.addDockWidget(dock['main_area'], dockwidget)
dockwidget_action = dockwidget.toggleViewAction()
dockwidget_action.setIcon(QIcon(ICON['widget']))
actions['dockwidgets'].append(dockwidget_action)
""" ------ ORGANIZE DOCKWIDGETS ------ """
MAIN.tabifyDockWidget(idx_docks['Information'],
idx_docks['Video'])
MAIN.tabifyDockWidget(idx_docks['Channels'],
idx_docks['Labels'])
idx_docks['Information'].raise_() | python | def create_widgets(MAIN):
"""Create all the widgets and dockwidgets. It also creates actions to
toggle views of dockwidgets in dockwidgets.
"""
""" ------ CREATE WIDGETS ------ """
MAIN.labels = Labels(MAIN)
MAIN.channels = Channels(MAIN)
MAIN.notes = Notes(MAIN)
MAIN.merge_dialog = MergeDialog(MAIN)
MAIN.export_events_dialog = ExportEventsDialog(MAIN)
MAIN.export_dataset_dialog = ExportDatasetDialog(MAIN)
MAIN.spindle_dialog = SpindleDialog(MAIN)
MAIN.slow_wave_dialog = SWDialog(MAIN)
MAIN.analysis_dialog = AnalysisDialog(MAIN)
#MAIN.plot_dialog = PlotDialog(MAIN)
MAIN.overview = Overview(MAIN)
MAIN.spectrum = Spectrum(MAIN)
MAIN.traces = Traces(MAIN)
MAIN.video = Video(MAIN)
MAIN.settings = Settings(MAIN) # depends on all widgets apart from Info
MAIN.info = Info(MAIN) # this has to be the last, it depends on settings
MAIN.setCentralWidget(MAIN.traces)
""" ------ LIST DOCKWIDGETS ------ """
new_docks = [{'name': 'Information',
'widget': MAIN.info,
'main_area': Qt.LeftDockWidgetArea,
'extra_area': Qt.RightDockWidgetArea,
},
{'name': 'Labels',
'widget': MAIN.labels,
'main_area': Qt.RightDockWidgetArea,
'extra_area': Qt.LeftDockWidgetArea,
},
{'name': 'Channels',
'widget': MAIN.channels,
'main_area': Qt.RightDockWidgetArea,
'extra_area': Qt.LeftDockWidgetArea,
},
{'name': 'Spectrum',
'widget': MAIN.spectrum,
'main_area': Qt.RightDockWidgetArea,
'extra_area': Qt.LeftDockWidgetArea,
},
{'name': 'Annotations',
'widget': MAIN.notes,
'main_area': Qt.LeftDockWidgetArea,
'extra_area': Qt.RightDockWidgetArea,
},
{'name': 'Video',
'widget': MAIN.video,
'main_area': Qt.LeftDockWidgetArea,
'extra_area': Qt.RightDockWidgetArea,
},
{'name': 'Overview',
'widget': MAIN.overview,
'main_area': Qt.BottomDockWidgetArea,
'extra_area': Qt.TopDockWidgetArea,
},
]
""" ------ CREATE DOCKWIDGETS ------ """
idx_docks = {}
actions = MAIN.action
actions['dockwidgets'] = []
for dock in new_docks:
dockwidget = QDockWidget(dock['name'], MAIN)
dockwidget.setWidget(dock['widget'])
dockwidget.setAllowedAreas(dock['main_area'] | dock['extra_area'])
dockwidget.setObjectName(dock['name']) # savestate
idx_docks[dock['name']] = dockwidget
MAIN.addDockWidget(dock['main_area'], dockwidget)
dockwidget_action = dockwidget.toggleViewAction()
dockwidget_action.setIcon(QIcon(ICON['widget']))
actions['dockwidgets'].append(dockwidget_action)
""" ------ ORGANIZE DOCKWIDGETS ------ """
MAIN.tabifyDockWidget(idx_docks['Information'],
idx_docks['Video'])
MAIN.tabifyDockWidget(idx_docks['Channels'],
idx_docks['Labels'])
idx_docks['Information'].raise_() | [
"def",
"create_widgets",
"(",
"MAIN",
")",
":",
"\"\"\" ------ CREATE WIDGETS ------ \"\"\"",
"MAIN",
".",
"labels",
"=",
"Labels",
"(",
"MAIN",
")",
"MAIN",
".",
"channels",
"=",
"Channels",
"(",
"MAIN",
")",
"MAIN",
".",
"notes",
"=",
"Notes",
"(",
"MAIN",... | Create all the widgets and dockwidgets. It also creates actions to
toggle views of dockwidgets in dockwidgets. | [
"Create",
"all",
"the",
"widgets",
"and",
"dockwidgets",
".",
"It",
"also",
"creates",
"actions",
"to",
"toggle",
"views",
"of",
"dockwidgets",
"in",
"dockwidgets",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/creation.py#L31-L118 | train | 23,519 |
wonambi-python/wonambi | wonambi/widgets/creation.py | create_actions | def create_actions(MAIN):
"""Create all the possible actions."""
actions = MAIN.action # actions was already taken
""" ------ OPEN SETTINGS ------ """
actions['open_settings'] = QAction(QIcon(ICON['settings']), 'Settings',
MAIN)
actions['open_settings'].triggered.connect(MAIN.show_settings)
""" ------ CLOSE WINDOW ------ """
actions['close_wndw'] = QAction(QIcon(ICON['quit']), 'Quit', MAIN)
actions['close_wndw'].triggered.connect(MAIN.close)
""" ------ ABOUT ------ """
actions['about'] = QAction('About WONAMBI', MAIN)
actions['about'].triggered.connect(MAIN.about)
actions['aboutqt'] = QAction('About Qt', MAIN)
actions['aboutqt'].triggered.connect(lambda: QMessageBox.aboutQt(MAIN)) | python | def create_actions(MAIN):
"""Create all the possible actions."""
actions = MAIN.action # actions was already taken
""" ------ OPEN SETTINGS ------ """
actions['open_settings'] = QAction(QIcon(ICON['settings']), 'Settings',
MAIN)
actions['open_settings'].triggered.connect(MAIN.show_settings)
""" ------ CLOSE WINDOW ------ """
actions['close_wndw'] = QAction(QIcon(ICON['quit']), 'Quit', MAIN)
actions['close_wndw'].triggered.connect(MAIN.close)
""" ------ ABOUT ------ """
actions['about'] = QAction('About WONAMBI', MAIN)
actions['about'].triggered.connect(MAIN.about)
actions['aboutqt'] = QAction('About Qt', MAIN)
actions['aboutqt'].triggered.connect(lambda: QMessageBox.aboutQt(MAIN)) | [
"def",
"create_actions",
"(",
"MAIN",
")",
":",
"actions",
"=",
"MAIN",
".",
"action",
"# actions was already taken",
"\"\"\" ------ OPEN SETTINGS ------ \"\"\"",
"actions",
"[",
"'open_settings'",
"]",
"=",
"QAction",
"(",
"QIcon",
"(",
"ICON",
"[",
"'settings'",
"... | Create all the possible actions. | [
"Create",
"all",
"the",
"possible",
"actions",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/creation.py#L121-L139 | train | 23,520 |
wonambi-python/wonambi | wonambi/widgets/creation.py | create_toolbar | def create_toolbar(MAIN):
"""Create the various toolbars."""
actions = MAIN.action
toolbar = MAIN.addToolBar('File Management')
toolbar.setObjectName('File Management') # for savestate
toolbar.addAction(MAIN.info.action['open_dataset'])
toolbar.addSeparator()
toolbar.addAction(MAIN.channels.action['load_channels'])
toolbar.addAction(MAIN.channels.action['save_channels'])
toolbar.addSeparator()
toolbar.addAction(MAIN.notes.action['new_annot'])
toolbar.addAction(MAIN.notes.action['load_annot'])
""" ------ SCROLL ------ """
actions = MAIN.traces.action
toolbar = MAIN.addToolBar('Scroll')
toolbar.setObjectName('Scroll') # for savestate
toolbar.addAction(actions['step_prev'])
toolbar.addAction(actions['step_next'])
toolbar.addAction(actions['page_prev'])
toolbar.addAction(actions['page_next'])
toolbar.addSeparator()
toolbar.addAction(actions['X_more'])
toolbar.addAction(actions['X_less'])
toolbar.addSeparator()
toolbar.addAction(actions['Y_less'])
toolbar.addAction(actions['Y_more'])
toolbar.addAction(actions['Y_wider'])
toolbar.addAction(actions['Y_tighter'])
""" ------ ANNOTATIONS ------ """
actions = MAIN.notes.action
toolbar = MAIN.addToolBar('Annotations')
toolbar.setObjectName('Annotations')
toolbar.addAction(actions['new_bookmark'])
toolbar.addSeparator()
toolbar.addAction(actions['new_event'])
toolbar.addWidget(MAIN.notes.idx_eventtype)
toolbar.addSeparator()
toolbar.addWidget(MAIN.notes.idx_stage)
toolbar.addWidget(MAIN.notes.idx_quality) | python | def create_toolbar(MAIN):
"""Create the various toolbars."""
actions = MAIN.action
toolbar = MAIN.addToolBar('File Management')
toolbar.setObjectName('File Management') # for savestate
toolbar.addAction(MAIN.info.action['open_dataset'])
toolbar.addSeparator()
toolbar.addAction(MAIN.channels.action['load_channels'])
toolbar.addAction(MAIN.channels.action['save_channels'])
toolbar.addSeparator()
toolbar.addAction(MAIN.notes.action['new_annot'])
toolbar.addAction(MAIN.notes.action['load_annot'])
""" ------ SCROLL ------ """
actions = MAIN.traces.action
toolbar = MAIN.addToolBar('Scroll')
toolbar.setObjectName('Scroll') # for savestate
toolbar.addAction(actions['step_prev'])
toolbar.addAction(actions['step_next'])
toolbar.addAction(actions['page_prev'])
toolbar.addAction(actions['page_next'])
toolbar.addSeparator()
toolbar.addAction(actions['X_more'])
toolbar.addAction(actions['X_less'])
toolbar.addSeparator()
toolbar.addAction(actions['Y_less'])
toolbar.addAction(actions['Y_more'])
toolbar.addAction(actions['Y_wider'])
toolbar.addAction(actions['Y_tighter'])
""" ------ ANNOTATIONS ------ """
actions = MAIN.notes.action
toolbar = MAIN.addToolBar('Annotations')
toolbar.setObjectName('Annotations')
toolbar.addAction(actions['new_bookmark'])
toolbar.addSeparator()
toolbar.addAction(actions['new_event'])
toolbar.addWidget(MAIN.notes.idx_eventtype)
toolbar.addSeparator()
toolbar.addWidget(MAIN.notes.idx_stage)
toolbar.addWidget(MAIN.notes.idx_quality) | [
"def",
"create_toolbar",
"(",
"MAIN",
")",
":",
"actions",
"=",
"MAIN",
".",
"action",
"toolbar",
"=",
"MAIN",
".",
"addToolBar",
"(",
"'File Management'",
")",
"toolbar",
".",
"setObjectName",
"(",
"'File Management'",
")",
"# for savestate",
"toolbar",
".",
... | Create the various toolbars. | [
"Create",
"the",
"various",
"toolbars",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/creation.py#L327-L371 | train | 23,521 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.update_evt_types | def update_evt_types(self):
"""Update the event types list when dialog is opened."""
self.event_types = self.parent.notes.annot.event_types
self.idx_evt_type.clear()
self.frequency['norm_evt_type'].clear()
for ev in self.event_types:
self.idx_evt_type.addItem(ev)
self.frequency['norm_evt_type'].addItem(ev) | python | def update_evt_types(self):
"""Update the event types list when dialog is opened."""
self.event_types = self.parent.notes.annot.event_types
self.idx_evt_type.clear()
self.frequency['norm_evt_type'].clear()
for ev in self.event_types:
self.idx_evt_type.addItem(ev)
self.frequency['norm_evt_type'].addItem(ev) | [
"def",
"update_evt_types",
"(",
"self",
")",
":",
"self",
".",
"event_types",
"=",
"self",
".",
"parent",
".",
"notes",
".",
"annot",
".",
"event_types",
"self",
".",
"idx_evt_type",
".",
"clear",
"(",
")",
"self",
".",
"frequency",
"[",
"'norm_evt_type'",... | Update the event types list when dialog is opened. | [
"Update",
"the",
"event",
"types",
"list",
"when",
"dialog",
"is",
"opened",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L843-L850 | train | 23,522 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.toggle_concatenate | def toggle_concatenate(self):
"""Enable and disable concatenation options."""
if not (self.chunk['epoch'].isChecked() and
self.lock_to_staging.get_value()):
for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage,
self.idx_evt_type],
[self.cat['chan'], self.cat['cycle'],
self.cat['stage'], self.cat['evt_type']]):
if len(i.selectedItems()) > 1:
j.setEnabled(True)
else:
j.setEnabled(False)
j.setChecked(False)
if not self.chunk['event'].isChecked():
self.cat['evt_type'].setEnabled(False)
if not self.cat['discontinuous'].get_value():
self.cat['chan'].setEnabled(False)
self.cat['chan'].setChecked(False)
self.update_nseg() | python | def toggle_concatenate(self):
"""Enable and disable concatenation options."""
if not (self.chunk['epoch'].isChecked() and
self.lock_to_staging.get_value()):
for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage,
self.idx_evt_type],
[self.cat['chan'], self.cat['cycle'],
self.cat['stage'], self.cat['evt_type']]):
if len(i.selectedItems()) > 1:
j.setEnabled(True)
else:
j.setEnabled(False)
j.setChecked(False)
if not self.chunk['event'].isChecked():
self.cat['evt_type'].setEnabled(False)
if not self.cat['discontinuous'].get_value():
self.cat['chan'].setEnabled(False)
self.cat['chan'].setChecked(False)
self.update_nseg() | [
"def",
"toggle_concatenate",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"chunk",
"[",
"'epoch'",
"]",
".",
"isChecked",
"(",
")",
"and",
"self",
".",
"lock_to_staging",
".",
"get_value",
"(",
")",
")",
":",
"for",
"i",
",",
"j",
"in",
"z... | Enable and disable concatenation options. | [
"Enable",
"and",
"disable",
"concatenation",
"options",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L934-L955 | train | 23,523 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.toggle_pac | def toggle_pac(self):
"""Enable and disable PAC options."""
if Pac is not None:
pac_on = self.pac['pac_on'].get_value()
self.pac['prep'].setEnabled(pac_on)
self.pac['box_metric'].setEnabled(pac_on)
self.pac['box_complex'].setEnabled(pac_on)
self.pac['box_surro'].setEnabled(pac_on)
self.pac['box_opts'].setEnabled(pac_on)
if not pac_on:
self.pac['prep'].set_value(False)
if Pac is not None and pac_on:
pac = self.pac
hilb_on = pac['hilbert_on'].isChecked()
wav_on = pac['wavelet_on'].isChecked()
for button in pac['hilbert'].values():
button[0].setEnabled(hilb_on)
if button[1] is not None:
button[1].setEnabled(hilb_on)
pac['wav_width'][0].setEnabled(wav_on)
pac['wav_width'][1].setEnabled(wav_on)
if pac['metric'].get_value() in [
'Kullback-Leibler Distance',
'Heights ratio']:
pac['nbin'][0].setEnabled(True)
pac['nbin'][1].setEnabled(True)
else:
pac['nbin'][0].setEnabled(False)
pac['nbin'][1].setEnabled(False)
if pac['metric'] == 'ndPac':
for button in pac['surro'].values():
button[0].setEnabled(False)
if button[1] is not None:
button[1].setEnabled(False)
pac['surro']['pval'][0].setEnabled(True)
ndpac_on = pac['metric'].get_value() == 'ndPac'
surro_on = logical_and(pac['surro_method'].get_value() != ''
'No surrogates', not ndpac_on)
norm_on = pac['surro_norm'].get_value() != 'No normalization'
blocks_on = 'across time' in pac['surro_method'].get_value()
pac['surro_method'].setEnabled(not ndpac_on)
for button in pac['surro'].values():
button[0].setEnabled(surro_on and norm_on)
if button[1] is not None:
button[1].setEnabled(surro_on and norm_on)
pac['surro']['nblocks'][0].setEnabled(blocks_on)
pac['surro']['nblocks'][1].setEnabled(blocks_on)
if ndpac_on:
pac['surro_method'].set_value('No surrogates')
pac['surro']['pval'][0].setEnabled(True) | python | def toggle_pac(self):
"""Enable and disable PAC options."""
if Pac is not None:
pac_on = self.pac['pac_on'].get_value()
self.pac['prep'].setEnabled(pac_on)
self.pac['box_metric'].setEnabled(pac_on)
self.pac['box_complex'].setEnabled(pac_on)
self.pac['box_surro'].setEnabled(pac_on)
self.pac['box_opts'].setEnabled(pac_on)
if not pac_on:
self.pac['prep'].set_value(False)
if Pac is not None and pac_on:
pac = self.pac
hilb_on = pac['hilbert_on'].isChecked()
wav_on = pac['wavelet_on'].isChecked()
for button in pac['hilbert'].values():
button[0].setEnabled(hilb_on)
if button[1] is not None:
button[1].setEnabled(hilb_on)
pac['wav_width'][0].setEnabled(wav_on)
pac['wav_width'][1].setEnabled(wav_on)
if pac['metric'].get_value() in [
'Kullback-Leibler Distance',
'Heights ratio']:
pac['nbin'][0].setEnabled(True)
pac['nbin'][1].setEnabled(True)
else:
pac['nbin'][0].setEnabled(False)
pac['nbin'][1].setEnabled(False)
if pac['metric'] == 'ndPac':
for button in pac['surro'].values():
button[0].setEnabled(False)
if button[1] is not None:
button[1].setEnabled(False)
pac['surro']['pval'][0].setEnabled(True)
ndpac_on = pac['metric'].get_value() == 'ndPac'
surro_on = logical_and(pac['surro_method'].get_value() != ''
'No surrogates', not ndpac_on)
norm_on = pac['surro_norm'].get_value() != 'No normalization'
blocks_on = 'across time' in pac['surro_method'].get_value()
pac['surro_method'].setEnabled(not ndpac_on)
for button in pac['surro'].values():
button[0].setEnabled(surro_on and norm_on)
if button[1] is not None:
button[1].setEnabled(surro_on and norm_on)
pac['surro']['nblocks'][0].setEnabled(blocks_on)
pac['surro']['nblocks'][1].setEnabled(blocks_on)
if ndpac_on:
pac['surro_method'].set_value('No surrogates')
pac['surro']['pval'][0].setEnabled(True) | [
"def",
"toggle_pac",
"(",
"self",
")",
":",
"if",
"Pac",
"is",
"not",
"None",
":",
"pac_on",
"=",
"self",
".",
"pac",
"[",
"'pac_on'",
"]",
".",
"get_value",
"(",
")",
"self",
".",
"pac",
"[",
"'prep'",
"]",
".",
"setEnabled",
"(",
"pac_on",
")",
... | Enable and disable PAC options. | [
"Enable",
"and",
"disable",
"PAC",
"options",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1043-L1098 | train | 23,524 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.update_nseg | def update_nseg(self):
"""Update the number of segments, displayed in the dialog."""
self.nseg = 0
if self.one_grp:
segments = self.get_segments()
if segments is not None:
self.nseg = len(segments)
self.show_nseg.setText('Number of segments: ' + str(self.nseg))
times = [t for seg in segments for t in seg['times']]
self.parent.overview.mark_poi(times)
else:
self.show_nseg.setText('No valid segments')
self.toggle_freq() | python | def update_nseg(self):
"""Update the number of segments, displayed in the dialog."""
self.nseg = 0
if self.one_grp:
segments = self.get_segments()
if segments is not None:
self.nseg = len(segments)
self.show_nseg.setText('Number of segments: ' + str(self.nseg))
times = [t for seg in segments for t in seg['times']]
self.parent.overview.mark_poi(times)
else:
self.show_nseg.setText('No valid segments')
self.toggle_freq() | [
"def",
"update_nseg",
"(",
"self",
")",
":",
"self",
".",
"nseg",
"=",
"0",
"if",
"self",
".",
"one_grp",
":",
"segments",
"=",
"self",
".",
"get_segments",
"(",
")",
"if",
"segments",
"is",
"not",
"None",
":",
"self",
".",
"nseg",
"=",
"len",
"(",... | Update the number of segments, displayed in the dialog. | [
"Update",
"the",
"number",
"of",
"segments",
"displayed",
"in",
"the",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1123-L1138 | train | 23,525 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.check_all_local | def check_all_local(self):
"""Check or uncheck all local event parameters."""
all_local_chk = self.event['global']['all_local'].isChecked()
for buttons in self.event['local'].values():
buttons[0].setChecked(all_local_chk)
buttons[1].setEnabled(buttons[0].isChecked()) | python | def check_all_local(self):
"""Check or uncheck all local event parameters."""
all_local_chk = self.event['global']['all_local'].isChecked()
for buttons in self.event['local'].values():
buttons[0].setChecked(all_local_chk)
buttons[1].setEnabled(buttons[0].isChecked()) | [
"def",
"check_all_local",
"(",
"self",
")",
":",
"all_local_chk",
"=",
"self",
".",
"event",
"[",
"'global'",
"]",
"[",
"'all_local'",
"]",
".",
"isChecked",
"(",
")",
"for",
"buttons",
"in",
"self",
".",
"event",
"[",
"'local'",
"]",
".",
"values",
"(... | Check or uncheck all local event parameters. | [
"Check",
"or",
"uncheck",
"all",
"local",
"event",
"parameters",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1140-L1145 | train | 23,526 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.check_all_local_prep | def check_all_local_prep(self):
"""Check or uncheck all enabled event pre-processing."""
all_local_pp_chk = self.event['global']['all_local_prep'].isChecked()
for buttons in self.event['local'].values():
if buttons[1].isEnabled():
buttons[1].setChecked(all_local_pp_chk) | python | def check_all_local_prep(self):
"""Check or uncheck all enabled event pre-processing."""
all_local_pp_chk = self.event['global']['all_local_prep'].isChecked()
for buttons in self.event['local'].values():
if buttons[1].isEnabled():
buttons[1].setChecked(all_local_pp_chk) | [
"def",
"check_all_local_prep",
"(",
"self",
")",
":",
"all_local_pp_chk",
"=",
"self",
".",
"event",
"[",
"'global'",
"]",
"[",
"'all_local_prep'",
"]",
".",
"isChecked",
"(",
")",
"for",
"buttons",
"in",
"self",
".",
"event",
"[",
"'local'",
"]",
".",
"... | Check or uncheck all enabled event pre-processing. | [
"Check",
"or",
"uncheck",
"all",
"enabled",
"event",
"pre",
"-",
"processing",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1147-L1152 | train | 23,527 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.uncheck_all_local | def uncheck_all_local(self):
"""Uncheck 'all local' box when a local event is unchecked."""
for buttons in self.event['local'].values():
if not buttons[0].get_value():
self.event['global']['all_local'].setChecked(False)
if buttons[1].isEnabled() and not buttons[1].get_value():
self.event['global']['all_local_prep'].setChecked(False) | python | def uncheck_all_local(self):
"""Uncheck 'all local' box when a local event is unchecked."""
for buttons in self.event['local'].values():
if not buttons[0].get_value():
self.event['global']['all_local'].setChecked(False)
if buttons[1].isEnabled() and not buttons[1].get_value():
self.event['global']['all_local_prep'].setChecked(False) | [
"def",
"uncheck_all_local",
"(",
"self",
")",
":",
"for",
"buttons",
"in",
"self",
".",
"event",
"[",
"'local'",
"]",
".",
"values",
"(",
")",
":",
"if",
"not",
"buttons",
"[",
"0",
"]",
".",
"get_value",
"(",
")",
":",
"self",
".",
"event",
"[",
... | Uncheck 'all local' box when a local event is unchecked. | [
"Uncheck",
"all",
"local",
"box",
"when",
"a",
"local",
"event",
"is",
"unchecked",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1154-L1160 | train | 23,528 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.get_segments | def get_segments(self):
"""Get segments for analysis. Creates instance of trans.Segments."""
# Chunking
chunk = {k: v.isChecked() for k, v in self.chunk.items()}
lock_to_staging = self.lock_to_staging.get_value()
epoch_dur = self.epoch_param['dur'].get_value()
epoch_overlap = self.epoch_param['overlap_val'].value()
epoch_step = None
epoch = None
if chunk['epoch']:
if lock_to_staging:
epoch = 'locked'
else:
epoch = 'unlocked'
if self.epoch_param['step'].isChecked():
epoch_step = self.epoch_param['step_val'].get_value()
if epoch_step <= 0:
epoch_step = 0.1
# Which channel(s)
self.chan = self.get_channels() # chan name without group
if not self.chan:
return
# Which event type(s)
chan_full = None
evt_type = None
if chunk['event']:
if self.evt_chan_only.get_value():
chan_full = [i + ' (' + self.idx_group.currentText() + ''
')' for i in self.chan]
evt_type = self.idx_evt_type.selectedItems()
if not evt_type:
return
else:
evt_type = [x.text() for x in evt_type]
# Which cycle(s)
cycle = self.cycle = self.get_cycles()
# Which stage(s)
stage = self.idx_stage.selectedItems()
if not stage:
stage = self.stage = None
else:
stage = self.stage = [
x.text() for x in self.idx_stage.selectedItems()]
# Concatenation
cat = {k: v.get_value() for k, v in self.cat.items()}
cat = (int(cat['cycle']), int(cat['stage']),
int(cat['discontinuous']), int(cat['evt_type']))
# Artefact event rejection
reject_event = self.reject_event.get_value()
if reject_event == 'channel-specific':
chan_full = [i + ' (' + self.idx_group.currentText() + ''
')' for i in self.chan]
reject_artf = True
elif reject_event == 'from any channel':
reject_artf = True
else:
reject_artf = False
# Other options
min_dur = self.min_dur.get_value()
reject_epoch = self.reject_epoch.get_value()
# Generate title for summary plot
self.title = self.make_title(chan_full, cycle, stage, evt_type)
segments = fetch(self.parent.info.dataset,
self.parent.notes.annot, cat=cat,
evt_type=evt_type, stage=stage, cycle=cycle,
chan_full=chan_full, epoch=epoch,
epoch_dur=epoch_dur, epoch_overlap=epoch_overlap,
epoch_step=epoch_step, reject_epoch=reject_epoch,
reject_artf=reject_artf, min_dur=min_dur)
return segments | python | def get_segments(self):
"""Get segments for analysis. Creates instance of trans.Segments."""
# Chunking
chunk = {k: v.isChecked() for k, v in self.chunk.items()}
lock_to_staging = self.lock_to_staging.get_value()
epoch_dur = self.epoch_param['dur'].get_value()
epoch_overlap = self.epoch_param['overlap_val'].value()
epoch_step = None
epoch = None
if chunk['epoch']:
if lock_to_staging:
epoch = 'locked'
else:
epoch = 'unlocked'
if self.epoch_param['step'].isChecked():
epoch_step = self.epoch_param['step_val'].get_value()
if epoch_step <= 0:
epoch_step = 0.1
# Which channel(s)
self.chan = self.get_channels() # chan name without group
if not self.chan:
return
# Which event type(s)
chan_full = None
evt_type = None
if chunk['event']:
if self.evt_chan_only.get_value():
chan_full = [i + ' (' + self.idx_group.currentText() + ''
')' for i in self.chan]
evt_type = self.idx_evt_type.selectedItems()
if not evt_type:
return
else:
evt_type = [x.text() for x in evt_type]
# Which cycle(s)
cycle = self.cycle = self.get_cycles()
# Which stage(s)
stage = self.idx_stage.selectedItems()
if not stage:
stage = self.stage = None
else:
stage = self.stage = [
x.text() for x in self.idx_stage.selectedItems()]
# Concatenation
cat = {k: v.get_value() for k, v in self.cat.items()}
cat = (int(cat['cycle']), int(cat['stage']),
int(cat['discontinuous']), int(cat['evt_type']))
# Artefact event rejection
reject_event = self.reject_event.get_value()
if reject_event == 'channel-specific':
chan_full = [i + ' (' + self.idx_group.currentText() + ''
')' for i in self.chan]
reject_artf = True
elif reject_event == 'from any channel':
reject_artf = True
else:
reject_artf = False
# Other options
min_dur = self.min_dur.get_value()
reject_epoch = self.reject_epoch.get_value()
# Generate title for summary plot
self.title = self.make_title(chan_full, cycle, stage, evt_type)
segments = fetch(self.parent.info.dataset,
self.parent.notes.annot, cat=cat,
evt_type=evt_type, stage=stage, cycle=cycle,
chan_full=chan_full, epoch=epoch,
epoch_dur=epoch_dur, epoch_overlap=epoch_overlap,
epoch_step=epoch_step, reject_epoch=reject_epoch,
reject_artf=reject_artf, min_dur=min_dur)
return segments | [
"def",
"get_segments",
"(",
"self",
")",
":",
"# Chunking",
"chunk",
"=",
"{",
"k",
":",
"v",
".",
"isChecked",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"chunk",
".",
"items",
"(",
")",
"}",
"lock_to_staging",
"=",
"self",
".",
"lock_to_s... | Get segments for analysis. Creates instance of trans.Segments. | [
"Get",
"segments",
"for",
"analysis",
".",
"Creates",
"instance",
"of",
"trans",
".",
"Segments",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1391-L1476 | train | 23,529 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.transform_data | def transform_data(self, data):
"""Apply pre-processing transformation to data, and add it to data
dict.
Parameters
---------
data : instance of Segments
segments including 'data' (ChanTime)
Returns
-------
instance of Segments
same object with transformed data as 'trans_data' (ChanTime)
"""
trans = self.trans
differ = trans['diff'].get_value()
bandpass = trans['bandpass'].get_value()
notch1 = trans['notch1'].get_value()
notch2 = trans['notch2'].get_value()
for seg in data:
dat = seg['data']
if differ:
dat = math(dat, operator=diff, axis='time')
if bandpass != 'none':
order = trans['bp']['order'][1].get_value()
f1 = trans['bp']['f1'][1].get_value()
f2 = trans['bp']['f2'][1].get_value()
if f1 == '':
f1 = None
if f2 == '':
f2 = None
dat = filter_(dat, low_cut=f1, high_cut=f2, order=order,
ftype=bandpass)
if notch1 != 'none':
order = trans['n1']['order'][1].get_value()
cf = trans['n1']['cf'][1].get_value()
hbw = trans['n1']['bw'][1].get_value() / 2.0
lo_pass = cf - hbw
hi_pass = cf + hbw
dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1)
dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1)
if notch2 != 'none':
order = trans['n2']['order'][1].get_value()
cf = trans['n2']['cf'][1].get_value()
hbw = trans['n2']['bw'][1].get_value() / 2.0
lo_pass = cf - hbw
hi_pass = cf + hbw
dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1)
dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1)
seg['trans_data'] = dat
return data | python | def transform_data(self, data):
"""Apply pre-processing transformation to data, and add it to data
dict.
Parameters
---------
data : instance of Segments
segments including 'data' (ChanTime)
Returns
-------
instance of Segments
same object with transformed data as 'trans_data' (ChanTime)
"""
trans = self.trans
differ = trans['diff'].get_value()
bandpass = trans['bandpass'].get_value()
notch1 = trans['notch1'].get_value()
notch2 = trans['notch2'].get_value()
for seg in data:
dat = seg['data']
if differ:
dat = math(dat, operator=diff, axis='time')
if bandpass != 'none':
order = trans['bp']['order'][1].get_value()
f1 = trans['bp']['f1'][1].get_value()
f2 = trans['bp']['f2'][1].get_value()
if f1 == '':
f1 = None
if f2 == '':
f2 = None
dat = filter_(dat, low_cut=f1, high_cut=f2, order=order,
ftype=bandpass)
if notch1 != 'none':
order = trans['n1']['order'][1].get_value()
cf = trans['n1']['cf'][1].get_value()
hbw = trans['n1']['bw'][1].get_value() / 2.0
lo_pass = cf - hbw
hi_pass = cf + hbw
dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1)
dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1)
if notch2 != 'none':
order = trans['n2']['order'][1].get_value()
cf = trans['n2']['cf'][1].get_value()
hbw = trans['n2']['bw'][1].get_value() / 2.0
lo_pass = cf - hbw
hi_pass = cf + hbw
dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1)
dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1)
seg['trans_data'] = dat
return data | [
"def",
"transform_data",
"(",
"self",
",",
"data",
")",
":",
"trans",
"=",
"self",
".",
"trans",
"differ",
"=",
"trans",
"[",
"'diff'",
"]",
".",
"get_value",
"(",
")",
"bandpass",
"=",
"trans",
"[",
"'bandpass'",
"]",
".",
"get_value",
"(",
")",
"no... | Apply pre-processing transformation to data, and add it to data
dict.
Parameters
---------
data : instance of Segments
segments including 'data' (ChanTime)
Returns
-------
instance of Segments
same object with transformed data as 'trans_data' (ChanTime) | [
"Apply",
"pre",
"-",
"processing",
"transformation",
"to",
"data",
"and",
"add",
"it",
"to",
"data",
"dict",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1478-L1537 | train | 23,530 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.save_as | def save_as(self):
"""Dialog for getting name, location of data export file."""
filename = splitext(
self.parent.notes.annot.xml_file)[0] + '_data'
filename, _ = QFileDialog.getSaveFileName(self, 'Export analysis data',
filename,
'CSV (*.csv)')
if filename == '':
return
self.filename = filename
short_filename = short_strings(basename(self.filename))
self.idx_filename.setText(short_filename) | python | def save_as(self):
"""Dialog for getting name, location of data export file."""
filename = splitext(
self.parent.notes.annot.xml_file)[0] + '_data'
filename, _ = QFileDialog.getSaveFileName(self, 'Export analysis data',
filename,
'CSV (*.csv)')
if filename == '':
return
self.filename = filename
short_filename = short_strings(basename(self.filename))
self.idx_filename.setText(short_filename) | [
"def",
"save_as",
"(",
"self",
")",
":",
"filename",
"=",
"splitext",
"(",
"self",
".",
"parent",
".",
"notes",
".",
"annot",
".",
"xml_file",
")",
"[",
"0",
"]",
"+",
"'_data'",
"filename",
",",
"_",
"=",
"QFileDialog",
".",
"getSaveFileName",
"(",
... | Dialog for getting name, location of data export file. | [
"Dialog",
"for",
"getting",
"name",
"location",
"of",
"data",
"export",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1539-L1551 | train | 23,531 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.plot_freq | def plot_freq(self, x, y, title='', ylabel=None, scale='semilogy'):
"""Plot mean frequency spectrum and display in dialog.
Parameters
----------
x : list
vector with frequencies
y : ndarray
vector with amplitudes
title : str
plot title
ylabel : str
plot y label
scale : str
semilogy, loglog or linear
"""
freq = self.frequency
scaling = freq['scaling'].get_value()
if ylabel is None:
if freq['complex'].get_value():
ylabel = 'Amplitude (uV)'
elif 'power' == scaling:
ylabel = 'Power spectral density (uV ** 2 / Hz)'
elif 'energy' == scaling:
ylabel = 'Energy spectral density (uV ** 2)'
self.parent.plot_dialog = PlotDialog(self.parent)
self.parent.plot_dialog.canvas.plot(x, y, title, ylabel, scale=scale)
self.parent.show_plot_dialog() | python | def plot_freq(self, x, y, title='', ylabel=None, scale='semilogy'):
"""Plot mean frequency spectrum and display in dialog.
Parameters
----------
x : list
vector with frequencies
y : ndarray
vector with amplitudes
title : str
plot title
ylabel : str
plot y label
scale : str
semilogy, loglog or linear
"""
freq = self.frequency
scaling = freq['scaling'].get_value()
if ylabel is None:
if freq['complex'].get_value():
ylabel = 'Amplitude (uV)'
elif 'power' == scaling:
ylabel = 'Power spectral density (uV ** 2 / Hz)'
elif 'energy' == scaling:
ylabel = 'Energy spectral density (uV ** 2)'
self.parent.plot_dialog = PlotDialog(self.parent)
self.parent.plot_dialog.canvas.plot(x, y, title, ylabel, scale=scale)
self.parent.show_plot_dialog() | [
"def",
"plot_freq",
"(",
"self",
",",
"x",
",",
"y",
",",
"title",
"=",
"''",
",",
"ylabel",
"=",
"None",
",",
"scale",
"=",
"'semilogy'",
")",
":",
"freq",
"=",
"self",
".",
"frequency",
"scaling",
"=",
"freq",
"[",
"'scaling'",
"]",
".",
"get_val... | Plot mean frequency spectrum and display in dialog.
Parameters
----------
x : list
vector with frequencies
y : ndarray
vector with amplitudes
title : str
plot title
ylabel : str
plot y label
scale : str
semilogy, loglog or linear | [
"Plot",
"mean",
"frequency",
"spectrum",
"and",
"display",
"in",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1880-L1909 | train | 23,532 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.export_pac | def export_pac(self, xpac, fpha, famp, desc):
"""Write PAC analysis data to CSV."""
filename = splitext(self.filename)[0] + '_pac.csv'
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Duration',
'Stitch',
'Stage',
'Cycle',
'Event type',
'Channel',
]
spacer = [''] * (len(heading_row_1) - 1)
heading_row_2 = []
for fp in fpha:
fp_str = str(fp[0]) + '-' + str(fp[1])
for fa in famp:
fa_str = str(fa[0]) + '-' + str(fa[1])
heading_row_2.append(fp_str + '_' + fa_str + '_pac')
if 'pval' in xpac[list(xpac.keys())[0]].keys():
heading_row_3 = [x[:-4] + '_pval' for x in heading_row_2]
heading_row_2.extend(heading_row_3)
with open(filename, 'w', newline='') as f:
lg.info('Writing to ' + str(filename))
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(heading_row_1 + heading_row_2)
csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
csv_file.writerow(['SD'] + spacer + list(desc['sd']))
csv_file.writerow(['Mean of ln'] + spacer + list(desc['mean_log']))
csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))
idx = 0
for chan in xpac.keys():
for i, j in enumerate(xpac[chan]['times']):
idx += 1
cyc = None
if xpac[chan]['cycle'][i] is not None:
cyc = xpac[chan]['cycle'][i][2]
data_row = list(ravel(xpac[chan]['data'][i, :, :]))
pval_row = []
if 'pval' in xpac[chan]:
pval_row = list(ravel(xpac[chan]['pval'][i, :, :]))
csv_file.writerow([idx,
j[0],
j[1],
xpac[chan]['duration'][i],
xpac[chan]['n_stitch'][i],
xpac[chan]['stage'][i],
cyc,
xpac[chan]['name'][i],
chan,
] + data_row + pval_row) | python | def export_pac(self, xpac, fpha, famp, desc):
"""Write PAC analysis data to CSV."""
filename = splitext(self.filename)[0] + '_pac.csv'
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Duration',
'Stitch',
'Stage',
'Cycle',
'Event type',
'Channel',
]
spacer = [''] * (len(heading_row_1) - 1)
heading_row_2 = []
for fp in fpha:
fp_str = str(fp[0]) + '-' + str(fp[1])
for fa in famp:
fa_str = str(fa[0]) + '-' + str(fa[1])
heading_row_2.append(fp_str + '_' + fa_str + '_pac')
if 'pval' in xpac[list(xpac.keys())[0]].keys():
heading_row_3 = [x[:-4] + '_pval' for x in heading_row_2]
heading_row_2.extend(heading_row_3)
with open(filename, 'w', newline='') as f:
lg.info('Writing to ' + str(filename))
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(heading_row_1 + heading_row_2)
csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
csv_file.writerow(['SD'] + spacer + list(desc['sd']))
csv_file.writerow(['Mean of ln'] + spacer + list(desc['mean_log']))
csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))
idx = 0
for chan in xpac.keys():
for i, j in enumerate(xpac[chan]['times']):
idx += 1
cyc = None
if xpac[chan]['cycle'][i] is not None:
cyc = xpac[chan]['cycle'][i][2]
data_row = list(ravel(xpac[chan]['data'][i, :, :]))
pval_row = []
if 'pval' in xpac[chan]:
pval_row = list(ravel(xpac[chan]['pval'][i, :, :]))
csv_file.writerow([idx,
j[0],
j[1],
xpac[chan]['duration'][i],
xpac[chan]['n_stitch'][i],
xpac[chan]['stage'][i],
cyc,
xpac[chan]['name'][i],
chan,
] + data_row + pval_row) | [
"def",
"export_pac",
"(",
"self",
",",
"xpac",
",",
"fpha",
",",
"famp",
",",
"desc",
")",
":",
"filename",
"=",
"splitext",
"(",
"self",
".",
"filename",
")",
"[",
"0",
"]",
"+",
"'_pac.csv'",
"heading_row_1",
"=",
"[",
"'Segment index'",
",",
"'Start... | Write PAC analysis data to CSV. | [
"Write",
"PAC",
"analysis",
"data",
"to",
"CSV",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2135-L2198 | train | 23,533 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.compute_evt_params | def compute_evt_params(self):
"""Compute event parameters."""
ev = self.event
glob = {k: v.get_value() for k, v in ev['global'].items()}
params = {k: v[0].get_value() for k, v in ev['local'].items()}
prep = {k: v[1].get_value() for k, v in ev['local'].items()}
slopes = {k: v.get_value() for k, v in ev['sw'].items()}
f1 = ev['f1'].get_value()
f2 = ev['f2'].get_value()
if not f2:
f2 = None
band = (f1, f2)
if not (slopes['avg_slope'] or slopes['max_slope']):
slopes = None
evt_dat = event_params(self.data, params, band=band, slopes=slopes,
prep=prep, parent=self)
count = None
density = None
if glob['count']:
count = len(self.data)
if glob['density']:
epoch_dur = glob['density_per']
# get period of interest based on stage and cycle selection
poi = get_times(self.parent.notes.annot, stage=self.stage,
cycle=self.cycle, exclude=True)
total_dur = sum([x[1] - x[0] for y in poi for x in y['times']])
density = len(self.data) / (total_dur / epoch_dur)
return evt_dat, count, density | python | def compute_evt_params(self):
"""Compute event parameters."""
ev = self.event
glob = {k: v.get_value() for k, v in ev['global'].items()}
params = {k: v[0].get_value() for k, v in ev['local'].items()}
prep = {k: v[1].get_value() for k, v in ev['local'].items()}
slopes = {k: v.get_value() for k, v in ev['sw'].items()}
f1 = ev['f1'].get_value()
f2 = ev['f2'].get_value()
if not f2:
f2 = None
band = (f1, f2)
if not (slopes['avg_slope'] or slopes['max_slope']):
slopes = None
evt_dat = event_params(self.data, params, band=band, slopes=slopes,
prep=prep, parent=self)
count = None
density = None
if glob['count']:
count = len(self.data)
if glob['density']:
epoch_dur = glob['density_per']
# get period of interest based on stage and cycle selection
poi = get_times(self.parent.notes.annot, stage=self.stage,
cycle=self.cycle, exclude=True)
total_dur = sum([x[1] - x[0] for y in poi for x in y['times']])
density = len(self.data) / (total_dur / epoch_dur)
return evt_dat, count, density | [
"def",
"compute_evt_params",
"(",
"self",
")",
":",
"ev",
"=",
"self",
".",
"event",
"glob",
"=",
"{",
"k",
":",
"v",
".",
"get_value",
"(",
")",
"for",
"k",
",",
"v",
"in",
"ev",
"[",
"'global'",
"]",
".",
"items",
"(",
")",
"}",
"params",
"="... | Compute event parameters. | [
"Compute",
"event",
"parameters",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2200-L2231 | train | 23,534 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | AnalysisDialog.make_title | def make_title(self, chan, cycle, stage, evt_type):
"""Make a title for plots, etc."""
cyc_str = None
if cycle is not None:
cyc_str = [str(c[2]) for c in cycle]
cyc_str[0] = 'cycle ' + cyc_str[0]
title = [' + '.join([str(x) for x in y]) for y in [chan, cyc_str,
stage, evt_type] if y is not None]
return ', '.join(title) | python | def make_title(self, chan, cycle, stage, evt_type):
"""Make a title for plots, etc."""
cyc_str = None
if cycle is not None:
cyc_str = [str(c[2]) for c in cycle]
cyc_str[0] = 'cycle ' + cyc_str[0]
title = [' + '.join([str(x) for x in y]) for y in [chan, cyc_str,
stage, evt_type] if y is not None]
return ', '.join(title) | [
"def",
"make_title",
"(",
"self",
",",
"chan",
",",
"cycle",
",",
"stage",
",",
"evt_type",
")",
":",
"cyc_str",
"=",
"None",
"if",
"cycle",
"is",
"not",
"None",
":",
"cyc_str",
"=",
"[",
"str",
"(",
"c",
"[",
"2",
"]",
")",
"for",
"c",
"in",
"... | Make a title for plots, etc. | [
"Make",
"a",
"title",
"for",
"plots",
"etc",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2233-L2243 | train | 23,535 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | PlotCanvas.plot | def plot(self, x, y, title, ylabel, scale='semilogy', idx_lim=(1, -1)):
"""Plot the data.
Parameters
----------
x : ndarray
vector with frequencies
y : ndarray
vector with amplitudes
title : str
title of the plot, to appear above it
ylabel : str
label for the y-axis
scale : str
'log y-axis', 'log both axes' or 'linear', to set axis scaling
idx_lim : tuple of (int or None)
indices of the data to plot. by default, the first value is left
out, because of assymptotic tendencies near 0 Hz.
"""
x = x[slice(*idx_lim)]
y = y[slice(*idx_lim)]
ax = self.figure.add_subplot(111)
ax.set_title(title)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel(ylabel)
if 'semilogy' == scale:
ax.semilogy(x, y, 'r-')
elif 'loglog' == scale:
ax.loglog(x, y, 'r-')
elif 'linear' == scale:
ax.plot(x, y, 'r-') | python | def plot(self, x, y, title, ylabel, scale='semilogy', idx_lim=(1, -1)):
"""Plot the data.
Parameters
----------
x : ndarray
vector with frequencies
y : ndarray
vector with amplitudes
title : str
title of the plot, to appear above it
ylabel : str
label for the y-axis
scale : str
'log y-axis', 'log both axes' or 'linear', to set axis scaling
idx_lim : tuple of (int or None)
indices of the data to plot. by default, the first value is left
out, because of assymptotic tendencies near 0 Hz.
"""
x = x[slice(*idx_lim)]
y = y[slice(*idx_lim)]
ax = self.figure.add_subplot(111)
ax.set_title(title)
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel(ylabel)
if 'semilogy' == scale:
ax.semilogy(x, y, 'r-')
elif 'loglog' == scale:
ax.loglog(x, y, 'r-')
elif 'linear' == scale:
ax.plot(x, y, 'r-') | [
"def",
"plot",
"(",
"self",
",",
"x",
",",
"y",
",",
"title",
",",
"ylabel",
",",
"scale",
"=",
"'semilogy'",
",",
"idx_lim",
"=",
"(",
"1",
",",
"-",
"1",
")",
")",
":",
"x",
"=",
"x",
"[",
"slice",
"(",
"*",
"idx_lim",
")",
"]",
"y",
"=",... | Plot the data.
Parameters
----------
x : ndarray
vector with frequencies
y : ndarray
vector with amplitudes
title : str
title of the plot, to appear above it
ylabel : str
label for the y-axis
scale : str
'log y-axis', 'log both axes' or 'linear', to set axis scaling
idx_lim : tuple of (int or None)
indices of the data to plot. by default, the first value is left
out, because of assymptotic tendencies near 0 Hz. | [
"Plot",
"the",
"data",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2262-L2293 | train | 23,536 |
wonambi-python/wonambi | wonambi/widgets/analysis.py | PlotDialog.create_dialog | def create_dialog(self):
"""Create the basic dialog."""
self.bbox = QDialogButtonBox(QDialogButtonBox.Close)
self.idx_close = self.bbox.button(QDialogButtonBox.Close)
self.idx_close.pressed.connect(self.reject)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(self.bbox)
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addLayout(btnlayout)
layout.addStretch(1)
self.setLayout(layout) | python | def create_dialog(self):
"""Create the basic dialog."""
self.bbox = QDialogButtonBox(QDialogButtonBox.Close)
self.idx_close = self.bbox.button(QDialogButtonBox.Close)
self.idx_close.pressed.connect(self.reject)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(self.bbox)
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addLayout(btnlayout)
layout.addStretch(1)
self.setLayout(layout) | [
"def",
"create_dialog",
"(",
"self",
")",
":",
"self",
".",
"bbox",
"=",
"QDialogButtonBox",
"(",
"QDialogButtonBox",
".",
"Close",
")",
"self",
".",
"idx_close",
"=",
"self",
".",
"bbox",
".",
"button",
"(",
"QDialogButtonBox",
".",
"Close",
")",
"self",
... | Create the basic dialog. | [
"Create",
"the",
"basic",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2310-L2325 | train | 23,537 |
wonambi-python/wonambi | wonambi/detect/arousal.py | make_arousals | def make_arousals(events, time, s_freq):
"""Create dict for each arousal, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 5 matrix with start, end samples
data : ndarray (dtype='float')
vector with the data
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
Returns
-------
list of dict
list of all the arousals, with information about start, end,
duration (s),
"""
arousals = []
for ev in events:
one_ar = {'start': time[ev[0]],
'end': time[ev[1] - 1],
'dur': (ev[1] - ev[0]) / s_freq,
}
arousals.append(one_ar)
return arousals | python | def make_arousals(events, time, s_freq):
"""Create dict for each arousal, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 5 matrix with start, end samples
data : ndarray (dtype='float')
vector with the data
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
Returns
-------
list of dict
list of all the arousals, with information about start, end,
duration (s),
"""
arousals = []
for ev in events:
one_ar = {'start': time[ev[0]],
'end': time[ev[1] - 1],
'dur': (ev[1] - ev[0]) / s_freq,
}
arousals.append(one_ar)
return arousals | [
"def",
"make_arousals",
"(",
"events",
",",
"time",
",",
"s_freq",
")",
":",
"arousals",
"=",
"[",
"]",
"for",
"ev",
"in",
"events",
":",
"one_ar",
"=",
"{",
"'start'",
":",
"time",
"[",
"ev",
"[",
"0",
"]",
"]",
",",
"'end'",
":",
"time",
"[",
... | Create dict for each arousal, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 5 matrix with start, end samples
data : ndarray (dtype='float')
vector with the data
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
Returns
-------
list of dict
list of all the arousals, with information about start, end,
duration (s), | [
"Create",
"dict",
"for",
"each",
"arousal",
"based",
"on",
"events",
"of",
"time",
"points",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/arousal.py#L233-L261 | train | 23,538 |
wonambi-python/wonambi | wonambi/dataset.py | _convert_time_to_sample | def _convert_time_to_sample(abs_time, dataset):
"""Convert absolute time into samples.
Parameters
----------
abs_time : dat
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
dataset : instance of wonambi.Dataset
dataset to get sampling frequency and start time
Returns
-------
int
sample (from the starting of the recording).
"""
if isinstance(abs_time, datetime):
abs_time = abs_time - dataset.header['start_time']
if not isinstance(abs_time, timedelta):
try:
abs_time = timedelta(seconds=float(abs_time))
except TypeError as err:
if isinstance(abs_time, int64):
# timedelta and int64: http://bugs.python.org/issue5476
abs_time = timedelta(seconds=int(abs_time))
else:
raise err
sample = int(ceil(abs_time.total_seconds() * dataset.header['s_freq']))
return sample | python | def _convert_time_to_sample(abs_time, dataset):
"""Convert absolute time into samples.
Parameters
----------
abs_time : dat
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
dataset : instance of wonambi.Dataset
dataset to get sampling frequency and start time
Returns
-------
int
sample (from the starting of the recording).
"""
if isinstance(abs_time, datetime):
abs_time = abs_time - dataset.header['start_time']
if not isinstance(abs_time, timedelta):
try:
abs_time = timedelta(seconds=float(abs_time))
except TypeError as err:
if isinstance(abs_time, int64):
# timedelta and int64: http://bugs.python.org/issue5476
abs_time = timedelta(seconds=int(abs_time))
else:
raise err
sample = int(ceil(abs_time.total_seconds() * dataset.header['s_freq']))
return sample | [
"def",
"_convert_time_to_sample",
"(",
"abs_time",
",",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"abs_time",
",",
"datetime",
")",
":",
"abs_time",
"=",
"abs_time",
"-",
"dataset",
".",
"header",
"[",
"'start_time'",
"]",
"if",
"not",
"isinstance",
"(",... | Convert absolute time into samples.
Parameters
----------
abs_time : dat
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
dataset : instance of wonambi.Dataset
dataset to get sampling frequency and start time
Returns
-------
int
sample (from the starting of the recording). | [
"Convert",
"absolute",
"time",
"into",
"samples",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L36-L67 | train | 23,539 |
wonambi-python/wonambi | wonambi/dataset.py | detect_format | def detect_format(filename):
"""Detect file format.
Parameters
----------
filename : str or Path
name of the filename or directory.
Returns
-------
class used to read the data.
"""
filename = Path(filename)
if filename.is_dir():
if list(filename.glob('*.stc')) and list(filename.glob('*.erd')):
return Ktlx
elif (filename / 'patient.info').exists():
return Moberg
elif (filename / 'info.xml').exists():
return EgiMff
elif list(filename.glob('*.openephys')):
return OpenEphys
elif list(filename.glob('*.txt')):
return Text
else:
raise UnrecognizedFormat('Unrecognized format for directory ' +
str(filename))
else:
if filename.suffix == '.won':
return Wonambi
if filename.suffix.lower() == '.trc':
return Micromed
if filename.suffix == '.set':
return EEGLAB
if filename.suffix == '.edf':
return Edf
if filename.suffix == '.abf':
return Abf
if filename.suffix == '.vhdr' or filename.suffix == '.eeg':
return BrainVision
if filename.suffix == '.dat': # very general
try:
_read_header_length(filename)
except (AttributeError, ValueError): # there is no HeaderLen
pass
else:
return BCI2000
with filename.open('rb') as f:
file_header = f.read(8)
if file_header in (b'NEURALCD', b'NEURALSG', b'NEURALEV'):
return BlackRock
elif file_header[:6] == b'MATLAB': # we might need to read more
return FieldTrip
if filename.suffix.lower() == '.txt':
with filename.open('rt') as f:
first_line = f.readline()
if '.rr' in first_line[-4:]:
return LyonRRI
else:
raise UnrecognizedFormat('Unrecognized format for file ' +
str(filename)) | python | def detect_format(filename):
"""Detect file format.
Parameters
----------
filename : str or Path
name of the filename or directory.
Returns
-------
class used to read the data.
"""
filename = Path(filename)
if filename.is_dir():
if list(filename.glob('*.stc')) and list(filename.glob('*.erd')):
return Ktlx
elif (filename / 'patient.info').exists():
return Moberg
elif (filename / 'info.xml').exists():
return EgiMff
elif list(filename.glob('*.openephys')):
return OpenEphys
elif list(filename.glob('*.txt')):
return Text
else:
raise UnrecognizedFormat('Unrecognized format for directory ' +
str(filename))
else:
if filename.suffix == '.won':
return Wonambi
if filename.suffix.lower() == '.trc':
return Micromed
if filename.suffix == '.set':
return EEGLAB
if filename.suffix == '.edf':
return Edf
if filename.suffix == '.abf':
return Abf
if filename.suffix == '.vhdr' or filename.suffix == '.eeg':
return BrainVision
if filename.suffix == '.dat': # very general
try:
_read_header_length(filename)
except (AttributeError, ValueError): # there is no HeaderLen
pass
else:
return BCI2000
with filename.open('rb') as f:
file_header = f.read(8)
if file_header in (b'NEURALCD', b'NEURALSG', b'NEURALEV'):
return BlackRock
elif file_header[:6] == b'MATLAB': # we might need to read more
return FieldTrip
if filename.suffix.lower() == '.txt':
with filename.open('rt') as f:
first_line = f.readline()
if '.rr' in first_line[-4:]:
return LyonRRI
else:
raise UnrecognizedFormat('Unrecognized format for file ' +
str(filename)) | [
"def",
"detect_format",
"(",
"filename",
")",
":",
"filename",
"=",
"Path",
"(",
"filename",
")",
"if",
"filename",
".",
"is_dir",
"(",
")",
":",
"if",
"list",
"(",
"filename",
".",
"glob",
"(",
"'*.stc'",
")",
")",
"and",
"list",
"(",
"filename",
".... | Detect file format.
Parameters
----------
filename : str or Path
name of the filename or directory.
Returns
-------
class used to read the data. | [
"Detect",
"file",
"format",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L70-L142 | train | 23,540 |
wonambi-python/wonambi | wonambi/dataset.py | Dataset.read_videos | def read_videos(self, begtime=None, endtime=None):
"""Return list of videos with start and end times for a period.
Parameters
----------
begtime : int or datedelta or datetime or list
start of the data to read;
if it's int, it's assumed it's s;
if it's datedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
endtime : int or datedelta or datetime
end of the data to read;
if it's int, it's assumed it's s;
if it's datedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
Returns
-------
list of path
list of absolute paths (as str) to the movie files
float
time in s from the beginning of the first movie when the part of
interest starts
float
time in s from the beginning of the last movie when the part of
interest ends
Raises
------
OSError
when there are no video files at all
IndexError
when there are video files, but the interval of interest is not in
the list of files.
"""
if isinstance(begtime, datetime):
begtime = begtime - self.header['start_time']
if isinstance(begtime, timedelta):
begtime = begtime.total_seconds()
if isinstance(endtime, datetime):
endtime = endtime - self.header['start_time']
if isinstance(endtime, timedelta):
endtime = endtime.total_seconds()
videos = self.dataset.return_videos(begtime, endtime)
"""
try
except AttributeError:
lg.debug('This format does not have video')
videos = None
"""
return videos | python | def read_videos(self, begtime=None, endtime=None):
"""Return list of videos with start and end times for a period.
Parameters
----------
begtime : int or datedelta or datetime or list
start of the data to read;
if it's int, it's assumed it's s;
if it's datedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
endtime : int or datedelta or datetime
end of the data to read;
if it's int, it's assumed it's s;
if it's datedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
Returns
-------
list of path
list of absolute paths (as str) to the movie files
float
time in s from the beginning of the first movie when the part of
interest starts
float
time in s from the beginning of the last movie when the part of
interest ends
Raises
------
OSError
when there are no video files at all
IndexError
when there are video files, but the interval of interest is not in
the list of files.
"""
if isinstance(begtime, datetime):
begtime = begtime - self.header['start_time']
if isinstance(begtime, timedelta):
begtime = begtime.total_seconds()
if isinstance(endtime, datetime):
endtime = endtime - self.header['start_time']
if isinstance(endtime, timedelta):
endtime = endtime.total_seconds()
videos = self.dataset.return_videos(begtime, endtime)
"""
try
except AttributeError:
lg.debug('This format does not have video')
videos = None
"""
return videos | [
"def",
"read_videos",
"(",
"self",
",",
"begtime",
"=",
"None",
",",
"endtime",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"begtime",
",",
"datetime",
")",
":",
"begtime",
"=",
"begtime",
"-",
"self",
".",
"header",
"[",
"'start_time'",
"]",
"if",... | Return list of videos with start and end times for a period.
Parameters
----------
begtime : int or datedelta or datetime or list
start of the data to read;
if it's int, it's assumed it's s;
if it's datedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
endtime : int or datedelta or datetime
end of the data to read;
if it's int, it's assumed it's s;
if it's datedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
Returns
-------
list of path
list of absolute paths (as str) to the movie files
float
time in s from the beginning of the first movie when the part of
interest starts
float
time in s from the beginning of the last movie when the part of
interest ends
Raises
------
OSError
when there are no video files at all
IndexError
when there are video files, but the interval of interest is not in
the list of files. | [
"Return",
"list",
"of",
"videos",
"with",
"start",
"and",
"end",
"times",
"for",
"a",
"period",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L219-L272 | train | 23,541 |
wonambi-python/wonambi | wonambi/dataset.py | Dataset.read_data | def read_data(self, chan=None, begtime=None, endtime=None, begsam=None,
endsam=None, s_freq=None):
"""Read the data and creates a ChanTime instance
Parameters
----------
chan : list of strings
names of the channels to read
begtime : int or datedelta or datetime or list
start of the data to read;
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
endtime : int or datedelta or datetime
end of the data to read;
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
begsam : int
first sample (this sample will be included)
endsam : int
last sample (this sample will NOT be included)
s_freq : int
sampling frequency of the data
Returns
-------
An instance of ChanTime
Notes
-----
begsam and endsam follow Python convention, which starts at zero,
includes begsam but DOES NOT include endsam.
If begtime and endtime are a list, they both need the exact same
length and the data will be stored in trials.
If neither begtime or begsam are specified, it starts from the first
sample. If neither endtime or endsam are specified, it reads until the
end.
"""
data = ChanTime()
data.start_time = self.header['start_time']
data.s_freq = s_freq = s_freq if s_freq else self.header['s_freq']
if chan is None:
chan = self.header['chan_name']
if not (isinstance(chan, list) or isinstance(chan, tuple)):
raise TypeError('Parameter "chan" should be a list')
add_ref = False
if '_REF' in chan:
add_ref = True
chan[:] = [x for x in chan if x != '_REF']
idx_chan = [self.header['chan_name'].index(x) for x in chan]
if begtime is None and begsam is None:
begsam = 0
if endtime is None and endsam is None:
endsam = self.header['n_samples']
if begtime is not None:
if not isinstance(begtime, list):
begtime = [begtime]
begsam = []
for one_begtime in begtime:
begsam.append(_convert_time_to_sample(one_begtime, self))
if endtime is not None:
if not isinstance(endtime, list):
endtime = [endtime]
endsam = []
for one_endtime in endtime:
endsam.append(_convert_time_to_sample(one_endtime, self))
if not isinstance(begsam, list):
begsam = [begsam]
if not isinstance(endsam, list):
endsam = [endsam]
if len(begsam) != len(endsam):
raise ValueError('There should be the same number of start and ' +
'end point')
n_trl = len(begsam)
data.axis['chan'] = empty(n_trl, dtype='O')
data.axis['time'] = empty(n_trl, dtype='O')
data.data = empty(n_trl, dtype='O')
for i, one_begsam, one_endsam in zip(range(n_trl), begsam, endsam):
dataset = self.dataset
lg.debug('begsam {0: 6}, endsam {1: 6}'.format(one_begsam,
one_endsam))
dat = dataset.return_dat(idx_chan, one_begsam, one_endsam)
chan_in_dat = chan
if add_ref:
zero_ref = zeros((1, one_endsam - one_begsam))
dat = concatenate((dat, zero_ref), axis=0)
chan_in_dat.append('_REF')
data.data[i] = dat
data.axis['chan'][i] = asarray(chan_in_dat, dtype='U')
data.axis['time'][i] = (arange(one_begsam, one_endsam) / s_freq)
return data | python | def read_data(self, chan=None, begtime=None, endtime=None, begsam=None,
endsam=None, s_freq=None):
"""Read the data and creates a ChanTime instance
Parameters
----------
chan : list of strings
names of the channels to read
begtime : int or datedelta or datetime or list
start of the data to read;
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
endtime : int or datedelta or datetime
end of the data to read;
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
begsam : int
first sample (this sample will be included)
endsam : int
last sample (this sample will NOT be included)
s_freq : int
sampling frequency of the data
Returns
-------
An instance of ChanTime
Notes
-----
begsam and endsam follow Python convention, which starts at zero,
includes begsam but DOES NOT include endsam.
If begtime and endtime are a list, they both need the exact same
length and the data will be stored in trials.
If neither begtime or begsam are specified, it starts from the first
sample. If neither endtime or endsam are specified, it reads until the
end.
"""
data = ChanTime()
data.start_time = self.header['start_time']
data.s_freq = s_freq = s_freq if s_freq else self.header['s_freq']
if chan is None:
chan = self.header['chan_name']
if not (isinstance(chan, list) or isinstance(chan, tuple)):
raise TypeError('Parameter "chan" should be a list')
add_ref = False
if '_REF' in chan:
add_ref = True
chan[:] = [x for x in chan if x != '_REF']
idx_chan = [self.header['chan_name'].index(x) for x in chan]
if begtime is None and begsam is None:
begsam = 0
if endtime is None and endsam is None:
endsam = self.header['n_samples']
if begtime is not None:
if not isinstance(begtime, list):
begtime = [begtime]
begsam = []
for one_begtime in begtime:
begsam.append(_convert_time_to_sample(one_begtime, self))
if endtime is not None:
if not isinstance(endtime, list):
endtime = [endtime]
endsam = []
for one_endtime in endtime:
endsam.append(_convert_time_to_sample(one_endtime, self))
if not isinstance(begsam, list):
begsam = [begsam]
if not isinstance(endsam, list):
endsam = [endsam]
if len(begsam) != len(endsam):
raise ValueError('There should be the same number of start and ' +
'end point')
n_trl = len(begsam)
data.axis['chan'] = empty(n_trl, dtype='O')
data.axis['time'] = empty(n_trl, dtype='O')
data.data = empty(n_trl, dtype='O')
for i, one_begsam, one_endsam in zip(range(n_trl), begsam, endsam):
dataset = self.dataset
lg.debug('begsam {0: 6}, endsam {1: 6}'.format(one_begsam,
one_endsam))
dat = dataset.return_dat(idx_chan, one_begsam, one_endsam)
chan_in_dat = chan
if add_ref:
zero_ref = zeros((1, one_endsam - one_begsam))
dat = concatenate((dat, zero_ref), axis=0)
chan_in_dat.append('_REF')
data.data[i] = dat
data.axis['chan'][i] = asarray(chan_in_dat, dtype='U')
data.axis['time'][i] = (arange(one_begsam, one_endsam) / s_freq)
return data | [
"def",
"read_data",
"(",
"self",
",",
"chan",
"=",
"None",
",",
"begtime",
"=",
"None",
",",
"endtime",
"=",
"None",
",",
"begsam",
"=",
"None",
",",
"endsam",
"=",
"None",
",",
"s_freq",
"=",
"None",
")",
":",
"data",
"=",
"ChanTime",
"(",
")",
... | Read the data and creates a ChanTime instance
Parameters
----------
chan : list of strings
names of the channels to read
begtime : int or datedelta or datetime or list
start of the data to read;
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
endtime : int or datedelta or datetime
end of the data to read;
if it's int or float, it's assumed it's s;
if it's timedelta, it's assumed from the start of the recording;
if it's datetime, it's assumed it's absolute time.
It can also be a list of any of the above type.
begsam : int
first sample (this sample will be included)
endsam : int
last sample (this sample will NOT be included)
s_freq : int
sampling frequency of the data
Returns
-------
An instance of ChanTime
Notes
-----
begsam and endsam follow Python convention, which starts at zero,
includes begsam but DOES NOT include endsam.
If begtime and endtime are a list, they both need the exact same
length and the data will be stored in trials.
If neither begtime or begsam are specified, it starts from the first
sample. If neither endtime or endsam are specified, it reads until the
end. | [
"Read",
"the",
"data",
"and",
"creates",
"a",
"ChanTime",
"instance"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L274-L379 | train | 23,542 |
wonambi-python/wonambi | wonambi/ioeeg/moberg.py | _read_dat | def _read_dat(x):
"""read 24bit binary data and convert them to numpy.
Parameters
----------
x : bytes
bytes (length should be divisible by 3)
Returns
-------
numpy vector
vector with the signed 24bit values
Notes
-----
It's pretty slow but it's pretty a PITA to read 24bit as far as I can tell.
"""
n_smp = int(len(x) / DATA_PRECISION)
dat = zeros(n_smp)
for i in range(n_smp):
i0 = i * DATA_PRECISION
i1 = i0 + DATA_PRECISION
dat[i] = int.from_bytes(x[i0:i1], byteorder='little', signed=True)
return dat | python | def _read_dat(x):
"""read 24bit binary data and convert them to numpy.
Parameters
----------
x : bytes
bytes (length should be divisible by 3)
Returns
-------
numpy vector
vector with the signed 24bit values
Notes
-----
It's pretty slow but it's pretty a PITA to read 24bit as far as I can tell.
"""
n_smp = int(len(x) / DATA_PRECISION)
dat = zeros(n_smp)
for i in range(n_smp):
i0 = i * DATA_PRECISION
i1 = i0 + DATA_PRECISION
dat[i] = int.from_bytes(x[i0:i1], byteorder='little', signed=True)
return dat | [
"def",
"_read_dat",
"(",
"x",
")",
":",
"n_smp",
"=",
"int",
"(",
"len",
"(",
"x",
")",
"/",
"DATA_PRECISION",
")",
"dat",
"=",
"zeros",
"(",
"n_smp",
")",
"for",
"i",
"in",
"range",
"(",
"n_smp",
")",
":",
"i0",
"=",
"i",
"*",
"DATA_PRECISION",
... | read 24bit binary data and convert them to numpy.
Parameters
----------
x : bytes
bytes (length should be divisible by 3)
Returns
-------
numpy vector
vector with the signed 24bit values
Notes
-----
It's pretty slow but it's pretty a PITA to read 24bit as far as I can tell. | [
"read",
"24bit",
"binary",
"data",
"and",
"convert",
"them",
"to",
"numpy",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/moberg.py#L163-L188 | train | 23,543 |
wonambi-python/wonambi | wonambi/ioeeg/egimff.py | _read_chan_name | def _read_chan_name(orig):
"""Read channel labels, which can be across xml files.
Parameters
----------
orig : dict
contains the converted xml information
Returns
-------
list of str
list of channel names
ndarray
vector to indicate to which signal a channel belongs to
Notes
-----
This assumes that the PIB Box is the second signal.
"""
sensors = orig['sensorLayout'][1]
eeg_chan = []
for one_sensor in sensors:
if one_sensor['type'] in ('0', '1'):
if one_sensor['name'] is not None:
eeg_chan.append(one_sensor['name'])
else:
eeg_chan.append(one_sensor['number'])
pns_chan = []
if 'pnsSet' in orig:
pnsSet = orig['pnsSet'][1]
for one_sensor in pnsSet:
pns_chan.append(one_sensor['name'])
return eeg_chan + pns_chan, len(eeg_chan) | python | def _read_chan_name(orig):
"""Read channel labels, which can be across xml files.
Parameters
----------
orig : dict
contains the converted xml information
Returns
-------
list of str
list of channel names
ndarray
vector to indicate to which signal a channel belongs to
Notes
-----
This assumes that the PIB Box is the second signal.
"""
sensors = orig['sensorLayout'][1]
eeg_chan = []
for one_sensor in sensors:
if one_sensor['type'] in ('0', '1'):
if one_sensor['name'] is not None:
eeg_chan.append(one_sensor['name'])
else:
eeg_chan.append(one_sensor['number'])
pns_chan = []
if 'pnsSet' in orig:
pnsSet = orig['pnsSet'][1]
for one_sensor in pnsSet:
pns_chan.append(one_sensor['name'])
return eeg_chan + pns_chan, len(eeg_chan) | [
"def",
"_read_chan_name",
"(",
"orig",
")",
":",
"sensors",
"=",
"orig",
"[",
"'sensorLayout'",
"]",
"[",
"1",
"]",
"eeg_chan",
"=",
"[",
"]",
"for",
"one_sensor",
"in",
"sensors",
":",
"if",
"one_sensor",
"[",
"'type'",
"]",
"in",
"(",
"'0'",
",",
"... | Read channel labels, which can be across xml files.
Parameters
----------
orig : dict
contains the converted xml information
Returns
-------
list of str
list of channel names
ndarray
vector to indicate to which signal a channel belongs to
Notes
-----
This assumes that the PIB Box is the second signal. | [
"Read",
"channel",
"labels",
"which",
"can",
"be",
"across",
"xml",
"files",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/egimff.py#L427-L462 | train | 23,544 |
wonambi-python/wonambi | wonambi/ioeeg/wonambi.py | write_wonambi | def write_wonambi(data, filename, subj_id='', dtype='float64'):
"""Write file in simple Wonambi format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (the extensions .won and .dat will be added)
subj_id : str
subject id
dtype : str
numpy dtype in which you want to save the data
Notes
-----
Wonambi format creates two files, one .won with the dataset info as json
file and one .dat with the memmap recordings.
It will happily overwrite any existing file with the same name.
Memory-mapped matrices are column-major, Fortran-style, to be compatible
with Matlab.
"""
filename = Path(filename)
json_file = filename.with_suffix('.won')
memmap_file = filename.with_suffix('.dat')
start_time = data.start_time + timedelta(seconds=data.axis['time'][0][0])
start_time_str = start_time.strftime('%Y-%m-%d %H:%M:%S.%f')
dataset = {'subj_id': subj_id,
'start_time': start_time_str,
's_freq': data.s_freq,
'chan_name': list(data.axis['chan'][0]),
'n_samples': int(data.number_of('time')[0]),
'dtype': dtype,
}
with json_file.open('w') as f:
dump(dataset, f, sort_keys=True, indent=4)
memshape = (len(dataset['chan_name']),
dataset['n_samples'])
mem = memmap(str(memmap_file), dtype, mode='w+', shape=memshape, order='F')
mem[:, :] = data.data[0]
mem.flush() | python | def write_wonambi(data, filename, subj_id='', dtype='float64'):
"""Write file in simple Wonambi format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (the extensions .won and .dat will be added)
subj_id : str
subject id
dtype : str
numpy dtype in which you want to save the data
Notes
-----
Wonambi format creates two files, one .won with the dataset info as json
file and one .dat with the memmap recordings.
It will happily overwrite any existing file with the same name.
Memory-mapped matrices are column-major, Fortran-style, to be compatible
with Matlab.
"""
filename = Path(filename)
json_file = filename.with_suffix('.won')
memmap_file = filename.with_suffix('.dat')
start_time = data.start_time + timedelta(seconds=data.axis['time'][0][0])
start_time_str = start_time.strftime('%Y-%m-%d %H:%M:%S.%f')
dataset = {'subj_id': subj_id,
'start_time': start_time_str,
's_freq': data.s_freq,
'chan_name': list(data.axis['chan'][0]),
'n_samples': int(data.number_of('time')[0]),
'dtype': dtype,
}
with json_file.open('w') as f:
dump(dataset, f, sort_keys=True, indent=4)
memshape = (len(dataset['chan_name']),
dataset['n_samples'])
mem = memmap(str(memmap_file), dtype, mode='w+', shape=memshape, order='F')
mem[:, :] = data.data[0]
mem.flush() | [
"def",
"write_wonambi",
"(",
"data",
",",
"filename",
",",
"subj_id",
"=",
"''",
",",
"dtype",
"=",
"'float64'",
")",
":",
"filename",
"=",
"Path",
"(",
"filename",
")",
"json_file",
"=",
"filename",
".",
"with_suffix",
"(",
"'.won'",
")",
"memmap_file",
... | Write file in simple Wonambi format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (the extensions .won and .dat will be added)
subj_id : str
subject id
dtype : str
numpy dtype in which you want to save the data
Notes
-----
Wonambi format creates two files, one .won with the dataset info as json
file and one .dat with the memmap recordings.
It will happily overwrite any existing file with the same name.
Memory-mapped matrices are column-major, Fortran-style, to be compatible
with Matlab. | [
"Write",
"file",
"in",
"simple",
"Wonambi",
"format",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/wonambi.py#L120-L168 | train | 23,545 |
wonambi-python/wonambi | wonambi/attr/anat.py | _read_geometry | def _read_geometry(surf_file):
"""Read a triangular format Freesurfer surface mesh.
Parameters
----------
surf_file : str
path to surface file
Returns
-------
coords : numpy.ndarray
nvtx x 3 array of vertex (x, y, z) coordinates
faces : numpy.ndarray
nfaces x 3 array of defining mesh triangles
Notes
-----
This function comes from nibabel, but it doesn't use numpy because numpy
doesn't return the correct values in Python 3.
"""
with open(surf_file, 'rb') as f:
filebytes = f.read()
assert filebytes[:3] == b'\xff\xff\xfe'
i0 = filebytes.index(b'\x0A\x0A') + 2
i1 = i0 + 4
vnum = unpack('>i', filebytes[i0:i1])[0]
i0 = i1
i1 += 4
fnum = unpack('>i', filebytes[i0:i1])[0]
i0 = i1
i1 += 4 * vnum * 3
verts = unpack('>' + 'f' * vnum * 3, filebytes[i0:i1])
i0 = i1
i1 += 4 * fnum * 3
faces = unpack('>' + 'i' * fnum * 3, filebytes[i0:i1])
verts = asarray(verts).reshape(vnum, 3)
faces = asarray(faces).reshape(fnum, 3)
return verts, faces | python | def _read_geometry(surf_file):
"""Read a triangular format Freesurfer surface mesh.
Parameters
----------
surf_file : str
path to surface file
Returns
-------
coords : numpy.ndarray
nvtx x 3 array of vertex (x, y, z) coordinates
faces : numpy.ndarray
nfaces x 3 array of defining mesh triangles
Notes
-----
This function comes from nibabel, but it doesn't use numpy because numpy
doesn't return the correct values in Python 3.
"""
with open(surf_file, 'rb') as f:
filebytes = f.read()
assert filebytes[:3] == b'\xff\xff\xfe'
i0 = filebytes.index(b'\x0A\x0A') + 2
i1 = i0 + 4
vnum = unpack('>i', filebytes[i0:i1])[0]
i0 = i1
i1 += 4
fnum = unpack('>i', filebytes[i0:i1])[0]
i0 = i1
i1 += 4 * vnum * 3
verts = unpack('>' + 'f' * vnum * 3, filebytes[i0:i1])
i0 = i1
i1 += 4 * fnum * 3
faces = unpack('>' + 'i' * fnum * 3, filebytes[i0:i1])
verts = asarray(verts).reshape(vnum, 3)
faces = asarray(faces).reshape(fnum, 3)
return verts, faces | [
"def",
"_read_geometry",
"(",
"surf_file",
")",
":",
"with",
"open",
"(",
"surf_file",
",",
"'rb'",
")",
"as",
"f",
":",
"filebytes",
"=",
"f",
".",
"read",
"(",
")",
"assert",
"filebytes",
"[",
":",
"3",
"]",
"==",
"b'\\xff\\xff\\xfe'",
"i0",
"=",
"... | Read a triangular format Freesurfer surface mesh.
Parameters
----------
surf_file : str
path to surface file
Returns
-------
coords : numpy.ndarray
nvtx x 3 array of vertex (x, y, z) coordinates
faces : numpy.ndarray
nfaces x 3 array of defining mesh triangles
Notes
-----
This function comes from nibabel, but it doesn't use numpy because numpy
doesn't return the correct values in Python 3. | [
"Read",
"a",
"triangular",
"format",
"Freesurfer",
"surface",
"mesh",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/anat.py#L33-L72 | train | 23,546 |
wonambi-python/wonambi | wonambi/attr/anat.py | import_freesurfer_LUT | def import_freesurfer_LUT(fs_lut=None):
"""Import Look-up Table with colors and labels for anatomical regions.
It's necessary that Freesurfer is installed and that the environmental
variable 'FREESURFER_HOME' is present.
Parameters
----------
fs_lut : str or Path
path to file called FreeSurferColorLUT.txt
Returns
-------
idx : list of int
indices of regions
label : list of str
names of the brain regions
rgba : numpy.ndarray
one row is a brain region and the columns are the RGB + alpha colors
"""
if fs_lut is not None:
lg.info('Reading user-specified lookuptable {}'.format(fs_lut))
fs_lut = Path(fs_lut)
else:
try:
fs_home = environ['FREESURFER_HOME']
except KeyError:
raise OSError('Freesurfer is not installed or FREESURFER_HOME is '
'not defined as environmental variable')
else:
fs_lut = Path(fs_home) / 'FreeSurferColorLUT.txt'
lg.info('Reading lookuptable in FREESURFER_HOME {}'.format(fs_lut))
idx = []
label = []
rgba = empty((0, 4))
with fs_lut.open('r') as f:
for l in f:
if len(l) <= 1 or l[0] == '#' or l[0] == '\r':
continue
(t0, t1, t2, t3, t4, t5) = [t(s) for t, s in
zip((int, str, int, int, int, int),
l.split())]
idx.append(t0)
label.append(t1)
rgba = vstack((rgba, array([t2, t3, t4, t5])))
return idx, label, rgba | python | def import_freesurfer_LUT(fs_lut=None):
"""Import Look-up Table with colors and labels for anatomical regions.
It's necessary that Freesurfer is installed and that the environmental
variable 'FREESURFER_HOME' is present.
Parameters
----------
fs_lut : str or Path
path to file called FreeSurferColorLUT.txt
Returns
-------
idx : list of int
indices of regions
label : list of str
names of the brain regions
rgba : numpy.ndarray
one row is a brain region and the columns are the RGB + alpha colors
"""
if fs_lut is not None:
lg.info('Reading user-specified lookuptable {}'.format(fs_lut))
fs_lut = Path(fs_lut)
else:
try:
fs_home = environ['FREESURFER_HOME']
except KeyError:
raise OSError('Freesurfer is not installed or FREESURFER_HOME is '
'not defined as environmental variable')
else:
fs_lut = Path(fs_home) / 'FreeSurferColorLUT.txt'
lg.info('Reading lookuptable in FREESURFER_HOME {}'.format(fs_lut))
idx = []
label = []
rgba = empty((0, 4))
with fs_lut.open('r') as f:
for l in f:
if len(l) <= 1 or l[0] == '#' or l[0] == '\r':
continue
(t0, t1, t2, t3, t4, t5) = [t(s) for t, s in
zip((int, str, int, int, int, int),
l.split())]
idx.append(t0)
label.append(t1)
rgba = vstack((rgba, array([t2, t3, t4, t5])))
return idx, label, rgba | [
"def",
"import_freesurfer_LUT",
"(",
"fs_lut",
"=",
"None",
")",
":",
"if",
"fs_lut",
"is",
"not",
"None",
":",
"lg",
".",
"info",
"(",
"'Reading user-specified lookuptable {}'",
".",
"format",
"(",
"fs_lut",
")",
")",
"fs_lut",
"=",
"Path",
"(",
"fs_lut",
... | Import Look-up Table with colors and labels for anatomical regions.
It's necessary that Freesurfer is installed and that the environmental
variable 'FREESURFER_HOME' is present.
Parameters
----------
fs_lut : str or Path
path to file called FreeSurferColorLUT.txt
Returns
-------
idx : list of int
indices of regions
label : list of str
names of the brain regions
rgba : numpy.ndarray
one row is a brain region and the columns are the RGB + alpha colors | [
"Import",
"Look",
"-",
"up",
"Table",
"with",
"colors",
"and",
"labels",
"for",
"anatomical",
"regions",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/anat.py#L97-L144 | train | 23,547 |
wonambi-python/wonambi | wonambi/attr/anat.py | Freesurfer.find_brain_region | def find_brain_region(self, abs_pos, parc_type='aparc', max_approx=None,
exclude_regions=None):
"""Find the name of the brain region in which an electrode is located.
Parameters
----------
abs_pos : numpy.ndarray
3x0 vector with the position of interest.
parc_type : str
'aparc', 'aparc.a2009s', 'BA', 'BA.thresh', or 'aparc.DKTatlas40'
'aparc.DKTatlas40' is only for recent freesurfer versions
max_approx : int, optional
max approximation to define position of the electrode.
exclude_regions : list of str or empty list
do not report regions if they contain these substrings. None means
that it does not exclude any region.
Notes
-----
It determines the possible brain region in which one electrode is
present, based on Freesurfer segmentation. You can imagine that
sometimes one electrode is not perfectly located within one region,
but it's a few mm away. The parameter "approx" specifies this tolerance
where each value is one mm. It keeps on searching in larger and larger
spots until it finds at least one region which is not white matter. If
there are multiple regions, it returns the region with the most
detection.
Minimal value is 0, which means only if the electrode is in the
precise location.
If you want to exclude white matter regions with 'aparc', use
exclude_regions = ('White', 'WM', 'Unknown')
and with 'aparc.a2009s', use:
exclude_regions = ('White-Matter')
"""
# convert to freesurfer coordinates of the MRI
pos = around(dot(FS_AFFINE, append(abs_pos, 1)))[:3].astype(int)
lg.debug('Position in the MRI matrix: {}'.format(pos))
mri_dat, _ = self.read_seg(parc_type)
if max_approx is None:
max_approx = 3
for approx in range(max_approx + 1):
lg.debug('Trying approx {} out of {}'.format(approx, max_approx))
regions = _find_neighboring_regions(pos, mri_dat,
self.lookuptable, approx,
exclude_regions)
if regions:
break
if regions:
c_regions = Counter(regions)
return c_regions.most_common(1)[0][0], approx
else:
return '--not found--', approx | python | def find_brain_region(self, abs_pos, parc_type='aparc', max_approx=None,
exclude_regions=None):
"""Find the name of the brain region in which an electrode is located.
Parameters
----------
abs_pos : numpy.ndarray
3x0 vector with the position of interest.
parc_type : str
'aparc', 'aparc.a2009s', 'BA', 'BA.thresh', or 'aparc.DKTatlas40'
'aparc.DKTatlas40' is only for recent freesurfer versions
max_approx : int, optional
max approximation to define position of the electrode.
exclude_regions : list of str or empty list
do not report regions if they contain these substrings. None means
that it does not exclude any region.
Notes
-----
It determines the possible brain region in which one electrode is
present, based on Freesurfer segmentation. You can imagine that
sometimes one electrode is not perfectly located within one region,
but it's a few mm away. The parameter "approx" specifies this tolerance
where each value is one mm. It keeps on searching in larger and larger
spots until it finds at least one region which is not white matter. If
there are multiple regions, it returns the region with the most
detection.
Minimal value is 0, which means only if the electrode is in the
precise location.
If you want to exclude white matter regions with 'aparc', use
exclude_regions = ('White', 'WM', 'Unknown')
and with 'aparc.a2009s', use:
exclude_regions = ('White-Matter')
"""
# convert to freesurfer coordinates of the MRI
pos = around(dot(FS_AFFINE, append(abs_pos, 1)))[:3].astype(int)
lg.debug('Position in the MRI matrix: {}'.format(pos))
mri_dat, _ = self.read_seg(parc_type)
if max_approx is None:
max_approx = 3
for approx in range(max_approx + 1):
lg.debug('Trying approx {} out of {}'.format(approx, max_approx))
regions = _find_neighboring_regions(pos, mri_dat,
self.lookuptable, approx,
exclude_regions)
if regions:
break
if regions:
c_regions = Counter(regions)
return c_regions.most_common(1)[0][0], approx
else:
return '--not found--', approx | [
"def",
"find_brain_region",
"(",
"self",
",",
"abs_pos",
",",
"parc_type",
"=",
"'aparc'",
",",
"max_approx",
"=",
"None",
",",
"exclude_regions",
"=",
"None",
")",
":",
"# convert to freesurfer coordinates of the MRI",
"pos",
"=",
"around",
"(",
"dot",
"(",
"FS... | Find the name of the brain region in which an electrode is located.
Parameters
----------
abs_pos : numpy.ndarray
3x0 vector with the position of interest.
parc_type : str
'aparc', 'aparc.a2009s', 'BA', 'BA.thresh', or 'aparc.DKTatlas40'
'aparc.DKTatlas40' is only for recent freesurfer versions
max_approx : int, optional
max approximation to define position of the electrode.
exclude_regions : list of str or empty list
do not report regions if they contain these substrings. None means
that it does not exclude any region.
Notes
-----
It determines the possible brain region in which one electrode is
present, based on Freesurfer segmentation. You can imagine that
sometimes one electrode is not perfectly located within one region,
but it's a few mm away. The parameter "approx" specifies this tolerance
where each value is one mm. It keeps on searching in larger and larger
spots until it finds at least one region which is not white matter. If
there are multiple regions, it returns the region with the most
detection.
Minimal value is 0, which means only if the electrode is in the
precise location.
If you want to exclude white matter regions with 'aparc', use
exclude_regions = ('White', 'WM', 'Unknown')
and with 'aparc.a2009s', use:
exclude_regions = ('White-Matter') | [
"Find",
"the",
"name",
"of",
"the",
"brain",
"region",
"in",
"which",
"an",
"electrode",
"is",
"located",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/anat.py#L237-L293 | train | 23,548 |
wonambi-python/wonambi | wonambi/attr/anat.py | Freesurfer.read_seg | def read_seg(self, parc_type='aparc'):
"""Read the MRI segmentation.
Parameters
----------
parc_type : str
'aparc' or 'aparc.a2009s'
Returns
-------
numpy.ndarray
3d matrix with values
numpy.ndarray
4x4 affine matrix
"""
seg_file = self.dir / 'mri' / (parc_type + '+aseg.mgz')
seg_mri = load(seg_file)
seg_aff = seg_mri.affine
seg_dat = seg_mri.get_data()
return seg_dat, seg_aff | python | def read_seg(self, parc_type='aparc'):
"""Read the MRI segmentation.
Parameters
----------
parc_type : str
'aparc' or 'aparc.a2009s'
Returns
-------
numpy.ndarray
3d matrix with values
numpy.ndarray
4x4 affine matrix
"""
seg_file = self.dir / 'mri' / (parc_type + '+aseg.mgz')
seg_mri = load(seg_file)
seg_aff = seg_mri.affine
seg_dat = seg_mri.get_data()
return seg_dat, seg_aff | [
"def",
"read_seg",
"(",
"self",
",",
"parc_type",
"=",
"'aparc'",
")",
":",
"seg_file",
"=",
"self",
".",
"dir",
"/",
"'mri'",
"/",
"(",
"parc_type",
"+",
"'+aseg.mgz'",
")",
"seg_mri",
"=",
"load",
"(",
"seg_file",
")",
"seg_aff",
"=",
"seg_mri",
".",... | Read the MRI segmentation.
Parameters
----------
parc_type : str
'aparc' or 'aparc.a2009s'
Returns
-------
numpy.ndarray
3d matrix with values
numpy.ndarray
4x4 affine matrix | [
"Read",
"the",
"MRI",
"segmentation",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/anat.py#L320-L339 | train | 23,549 |
wonambi-python/wonambi | wonambi/trans/merge.py | concatenate | def concatenate(data, axis):
"""Concatenate multiple trials into one trials, according to any dimension.
Parameters
----------
data : instance of DataTime, DataFreq, or DataTimeFreq
axis : str
axis that you want to concatenate (it can be 'trial')
Returns
-------
instace of same class as input
the data will always have only one trial
Notes
-----
If axis is 'trial', it will add one more dimension, and concatenate based
on it. It will then create a new axis, called 'trial_axis' (not 'trial'
because that axis is hard-coded).
If you want to concatenate across trials, you need:
>>> expand_dims(data1.data[0], axis=1).shape
"""
output = data._copy(axis=False)
for dataaxis in data.axis:
output.axis[dataaxis] = empty(1, dtype='O')
if dataaxis == axis:
output.axis[dataaxis][0] = cat(data.axis[dataaxis])
else:
output.axis[dataaxis][0] = data.axis[dataaxis][0]
if len(unique(output.axis[dataaxis][0])) != len(output.axis[dataaxis][0]):
lg.warning('Axis ' + dataaxis + ' does not have unique values')
output.data = empty(1, dtype='O')
if axis == 'trial':
# create new axis
new_axis = empty(1, dtype='O')
n_trial = data.number_of('trial')
trial_name = ['trial{0:06}'.format(x) for x in range(n_trial)]
new_axis[0] = asarray(trial_name, dtype='U')
output.axis['trial_axis'] = new_axis
# concatenate along the extra dimension
all_trial = []
for one_trial in data.data:
all_trial.append(expand_dims(one_trial, -1))
output.data[0] = cat(all_trial, axis=-1)
else:
output.data[0] = cat(data.data, axis=output.index_of(axis))
return output | python | def concatenate(data, axis):
"""Concatenate multiple trials into one trials, according to any dimension.
Parameters
----------
data : instance of DataTime, DataFreq, or DataTimeFreq
axis : str
axis that you want to concatenate (it can be 'trial')
Returns
-------
instace of same class as input
the data will always have only one trial
Notes
-----
If axis is 'trial', it will add one more dimension, and concatenate based
on it. It will then create a new axis, called 'trial_axis' (not 'trial'
because that axis is hard-coded).
If you want to concatenate across trials, you need:
>>> expand_dims(data1.data[0], axis=1).shape
"""
output = data._copy(axis=False)
for dataaxis in data.axis:
output.axis[dataaxis] = empty(1, dtype='O')
if dataaxis == axis:
output.axis[dataaxis][0] = cat(data.axis[dataaxis])
else:
output.axis[dataaxis][0] = data.axis[dataaxis][0]
if len(unique(output.axis[dataaxis][0])) != len(output.axis[dataaxis][0]):
lg.warning('Axis ' + dataaxis + ' does not have unique values')
output.data = empty(1, dtype='O')
if axis == 'trial':
# create new axis
new_axis = empty(1, dtype='O')
n_trial = data.number_of('trial')
trial_name = ['trial{0:06}'.format(x) for x in range(n_trial)]
new_axis[0] = asarray(trial_name, dtype='U')
output.axis['trial_axis'] = new_axis
# concatenate along the extra dimension
all_trial = []
for one_trial in data.data:
all_trial.append(expand_dims(one_trial, -1))
output.data[0] = cat(all_trial, axis=-1)
else:
output.data[0] = cat(data.data, axis=output.index_of(axis))
return output | [
"def",
"concatenate",
"(",
"data",
",",
"axis",
")",
":",
"output",
"=",
"data",
".",
"_copy",
"(",
"axis",
"=",
"False",
")",
"for",
"dataaxis",
"in",
"data",
".",
"axis",
":",
"output",
".",
"axis",
"[",
"dataaxis",
"]",
"=",
"empty",
"(",
"1",
... | Concatenate multiple trials into one trials, according to any dimension.
Parameters
----------
data : instance of DataTime, DataFreq, or DataTimeFreq
axis : str
axis that you want to concatenate (it can be 'trial')
Returns
-------
instace of same class as input
the data will always have only one trial
Notes
-----
If axis is 'trial', it will add one more dimension, and concatenate based
on it. It will then create a new axis, called 'trial_axis' (not 'trial'
because that axis is hard-coded).
If you want to concatenate across trials, you need:
>>> expand_dims(data1.data[0], axis=1).shape | [
"Concatenate",
"multiple",
"trials",
"into",
"one",
"trials",
"according",
"to",
"any",
"dimension",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/merge.py#L15-L72 | train | 23,550 |
wonambi-python/wonambi | wonambi/ioeeg/lyonrri.py | LyonRRI.return_rri | def return_rri(self, begsam, endsam):
"""Return raw, irregularly-timed RRI."""
interval = endsam - begsam
dat = empty(interval)
k = 0
with open(self.filename, 'rt') as f:
[next(f) for x in range(12)]
for j, datum in enumerate(f):
if begsam <= j < endsam:
dat[k] = float64(datum[:datum.index('\t')])
k += 1
if k == interval:
break
return dat | python | def return_rri(self, begsam, endsam):
"""Return raw, irregularly-timed RRI."""
interval = endsam - begsam
dat = empty(interval)
k = 0
with open(self.filename, 'rt') as f:
[next(f) for x in range(12)]
for j, datum in enumerate(f):
if begsam <= j < endsam:
dat[k] = float64(datum[:datum.index('\t')])
k += 1
if k == interval:
break
return dat | [
"def",
"return_rri",
"(",
"self",
",",
"begsam",
",",
"endsam",
")",
":",
"interval",
"=",
"endsam",
"-",
"begsam",
"dat",
"=",
"empty",
"(",
"interval",
")",
"k",
"=",
"0",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rt'",
")",
"as",
"f",... | Return raw, irregularly-timed RRI. | [
"Return",
"raw",
"irregularly",
"-",
"timed",
"RRI",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/lyonrri.py#L100-L117 | train | 23,551 |
wonambi-python/wonambi | wonambi/widgets/labels.py | Labels.update | def update(self, checked=False, labels=None, custom_labels=None):
"""Use this function when we make changes to the list of labels or when
we load a new dataset.
Parameters
----------
checked : bool
argument from clicked.connect
labels : list of str
list of labels in the dataset (default)
custom_labels : list of str
list of labels from a file
"""
if labels is not None:
self.setEnabled(True)
self.chan_name = labels
self.table.blockSignals(True)
self.table.clearContents()
self.table.setRowCount(len(self.chan_name))
for i, label in enumerate(self.chan_name):
old_label = QTableWidgetItem(label)
old_label.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
if custom_labels is not None and i < len(custom_labels) and custom_labels[i]: # it's not empty string or None
label_txt = custom_labels[i]
else:
label_txt = label
new_label = QTableWidgetItem(label_txt)
self.table.setItem(i, 0, old_label)
self.table.setItem(i, 1, new_label)
self.table.blockSignals(False) | python | def update(self, checked=False, labels=None, custom_labels=None):
"""Use this function when we make changes to the list of labels or when
we load a new dataset.
Parameters
----------
checked : bool
argument from clicked.connect
labels : list of str
list of labels in the dataset (default)
custom_labels : list of str
list of labels from a file
"""
if labels is not None:
self.setEnabled(True)
self.chan_name = labels
self.table.blockSignals(True)
self.table.clearContents()
self.table.setRowCount(len(self.chan_name))
for i, label in enumerate(self.chan_name):
old_label = QTableWidgetItem(label)
old_label.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
if custom_labels is not None and i < len(custom_labels) and custom_labels[i]: # it's not empty string or None
label_txt = custom_labels[i]
else:
label_txt = label
new_label = QTableWidgetItem(label_txt)
self.table.setItem(i, 0, old_label)
self.table.setItem(i, 1, new_label)
self.table.blockSignals(False) | [
"def",
"update",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"labels",
"=",
"None",
",",
"custom_labels",
"=",
"None",
")",
":",
"if",
"labels",
"is",
"not",
"None",
":",
"self",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"chan_name",
"=",... | Use this function when we make changes to the list of labels or when
we load a new dataset.
Parameters
----------
checked : bool
argument from clicked.connect
labels : list of str
list of labels in the dataset (default)
custom_labels : list of str
list of labels from a file | [
"Use",
"this",
"function",
"when",
"we",
"make",
"changes",
"to",
"the",
"list",
"of",
"labels",
"or",
"when",
"we",
"load",
"a",
"new",
"dataset",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/labels.py#L81-L115 | train | 23,552 |
wonambi-python/wonambi | wonambi/trans/peaks.py | peaks | def peaks(data, method='max', axis='time', limits=None):
"""Return the values of an index where the data is at max or min
Parameters
----------
method : str, optional
'max' or 'min'
axis : str, optional
the axis where you want to detect the peaks
limits : tuple of two values, optional
the lowest and highest limits where to search for the peaks
data : instance of Data
one of the datatypes
Returns
-------
instance of Data
with one dimension less that the input data. The actual values in
the data can be not-numberic, for example, if you look for the
max value across electrodes
Notes
-----
This function is useful when you want to find the frequency value at which
the power is the largest, or to find the time point at which the signal is
largest, or the channel at which the activity is largest.
"""
idx_axis = data.index_of(axis)
output = data._copy()
output.axis.pop(axis)
for trl in range(data.number_of('trial')):
values = data.axis[axis][trl]
dat = data(trial=trl)
if limits is not None:
limits = (values < limits[0]) | (values > limits[1])
idx = [slice(None)] * len(data.list_of_axes)
idx[idx_axis] = limits
dat[idx] = nan
if method == 'max':
peak_val = nanargmax(dat, axis=idx_axis)
elif method == 'min':
peak_val = nanargmin(dat, axis=idx_axis)
output.data[trl] = values[peak_val]
return output | python | def peaks(data, method='max', axis='time', limits=None):
"""Return the values of an index where the data is at max or min
Parameters
----------
method : str, optional
'max' or 'min'
axis : str, optional
the axis where you want to detect the peaks
limits : tuple of two values, optional
the lowest and highest limits where to search for the peaks
data : instance of Data
one of the datatypes
Returns
-------
instance of Data
with one dimension less that the input data. The actual values in
the data can be not-numberic, for example, if you look for the
max value across electrodes
Notes
-----
This function is useful when you want to find the frequency value at which
the power is the largest, or to find the time point at which the signal is
largest, or the channel at which the activity is largest.
"""
idx_axis = data.index_of(axis)
output = data._copy()
output.axis.pop(axis)
for trl in range(data.number_of('trial')):
values = data.axis[axis][trl]
dat = data(trial=trl)
if limits is not None:
limits = (values < limits[0]) | (values > limits[1])
idx = [slice(None)] * len(data.list_of_axes)
idx[idx_axis] = limits
dat[idx] = nan
if method == 'max':
peak_val = nanargmax(dat, axis=idx_axis)
elif method == 'min':
peak_val = nanargmin(dat, axis=idx_axis)
output.data[trl] = values[peak_val]
return output | [
"def",
"peaks",
"(",
"data",
",",
"method",
"=",
"'max'",
",",
"axis",
"=",
"'time'",
",",
"limits",
"=",
"None",
")",
":",
"idx_axis",
"=",
"data",
".",
"index_of",
"(",
"axis",
")",
"output",
"=",
"data",
".",
"_copy",
"(",
")",
"output",
".",
... | Return the values of an index where the data is at max or min
Parameters
----------
method : str, optional
'max' or 'min'
axis : str, optional
the axis where you want to detect the peaks
limits : tuple of two values, optional
the lowest and highest limits where to search for the peaks
data : instance of Data
one of the datatypes
Returns
-------
instance of Data
with one dimension less that the input data. The actual values in
the data can be not-numberic, for example, if you look for the
max value across electrodes
Notes
-----
This function is useful when you want to find the frequency value at which
the power is the largest, or to find the time point at which the signal is
largest, or the channel at which the activity is largest. | [
"Return",
"the",
"values",
"of",
"an",
"index",
"where",
"the",
"data",
"is",
"at",
"max",
"or",
"min"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/peaks.py#L9-L58 | train | 23,553 |
wonambi-python/wonambi | wonambi/trans/analyze.py | export_freq | def export_freq(xfreq, filename, desc=None):
"""Write frequency analysis data to CSV.
Parameters
----------
xfreq : list of dict
spectral data, one dict per segment, where 'data' is ChanFreq
filename : str
output filename
desc : dict of ndarray
descriptives
'"""
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Duration',
'Stitches',
'Stage',
'Cycle',
'Event type',
'Channel',
]
spacer = [''] * (len(heading_row_1) - 1)
freq = list(xfreq[0]['data'].axis['freq'][0])
with open(filename, 'w', newline='') as f:
lg.info('Writing to ' + str(filename))
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(heading_row_1 + freq)
if desc:
csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
csv_file.writerow(['SD'] + spacer + list(desc['sd']))
csv_file.writerow(['Mean of ln'] + spacer + list(
desc['mean_log']))
csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))
idx = 0
for seg in xfreq:
for chan in seg['data'].axis['chan'][0]:
idx += 1
cyc = None
if seg['cycle'] is not None:
cyc = seg['cycle'][2]
data_row = list(seg['data'](chan=chan)[0])
csv_file.writerow([idx,
seg['start'],
seg['end'],
seg['duration'],
seg['n_stitch'],
seg['stage'],
cyc,
seg['name'],
chan,
] + data_row) | python | def export_freq(xfreq, filename, desc=None):
"""Write frequency analysis data to CSV.
Parameters
----------
xfreq : list of dict
spectral data, one dict per segment, where 'data' is ChanFreq
filename : str
output filename
desc : dict of ndarray
descriptives
'"""
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Duration',
'Stitches',
'Stage',
'Cycle',
'Event type',
'Channel',
]
spacer = [''] * (len(heading_row_1) - 1)
freq = list(xfreq[0]['data'].axis['freq'][0])
with open(filename, 'w', newline='') as f:
lg.info('Writing to ' + str(filename))
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(heading_row_1 + freq)
if desc:
csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
csv_file.writerow(['SD'] + spacer + list(desc['sd']))
csv_file.writerow(['Mean of ln'] + spacer + list(
desc['mean_log']))
csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))
idx = 0
for seg in xfreq:
for chan in seg['data'].axis['chan'][0]:
idx += 1
cyc = None
if seg['cycle'] is not None:
cyc = seg['cycle'][2]
data_row = list(seg['data'](chan=chan)[0])
csv_file.writerow([idx,
seg['start'],
seg['end'],
seg['duration'],
seg['n_stitch'],
seg['stage'],
cyc,
seg['name'],
chan,
] + data_row) | [
"def",
"export_freq",
"(",
"xfreq",
",",
"filename",
",",
"desc",
"=",
"None",
")",
":",
"heading_row_1",
"=",
"[",
"'Segment index'",
",",
"'Start time'",
",",
"'End time'",
",",
"'Duration'",
",",
"'Stitches'",
",",
"'Stage'",
",",
"'Cycle'",
",",
"'Event ... | Write frequency analysis data to CSV.
Parameters
----------
xfreq : list of dict
spectral data, one dict per segment, where 'data' is ChanFreq
filename : str
output filename
desc : dict of ndarray
descriptives | [
"Write",
"frequency",
"analysis",
"data",
"to",
"CSV",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/analyze.py#L294-L352 | train | 23,554 |
wonambi-python/wonambi | wonambi/trans/analyze.py | export_freq_band | def export_freq_band(xfreq, bands, filename):
"""Write frequency analysis data to CSV by pre-defined band."""
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Duration',
'Stitches',
'Stage',
'Cycle',
'Event type',
'Channel',
]
spacer = [''] * (len(heading_row_1) - 1)
band_hdr = [str(b1) + '-' + str(b2) for b1, b2 in bands]
xband = xfreq.copy()
for seg in xband:
bandlist = []
for i, b in enumerate(bands):
pwr, _ = band_power(seg['data'], b)
bandlist.append(pwr)
seg['band'] = bandlist
as_matrix = asarray([
[x['band'][y][chan] for y in range(len(x['band']))] \
for x in xband for chan in x['band'][0].keys()])
desc = get_descriptives(as_matrix)
with open(filename, 'w', newline='') as f:
lg.info('Writing to ' + str(filename))
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(heading_row_1 + band_hdr)
csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
csv_file.writerow(['SD'] + spacer + list(desc['sd']))
csv_file.writerow(['Mean of ln'] + spacer + list(desc['mean_log']))
csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))
idx = 0
for seg in xband:
for chan in seg['band'][0].keys():
idx += 1
cyc = None
if seg['cycle'] is not None:
cyc = seg['cycle'][2]
data_row = list(
[seg['band'][x][chan] for x in range(
len(seg['band']))])
csv_file.writerow([idx,
seg['start'],
seg['end'],
seg['duration'],
seg['n_stitch'],
seg['stage'],
cyc,
seg['name'],
chan,
] + data_row) | python | def export_freq_band(xfreq, bands, filename):
"""Write frequency analysis data to CSV by pre-defined band."""
heading_row_1 = ['Segment index',
'Start time',
'End time',
'Duration',
'Stitches',
'Stage',
'Cycle',
'Event type',
'Channel',
]
spacer = [''] * (len(heading_row_1) - 1)
band_hdr = [str(b1) + '-' + str(b2) for b1, b2 in bands]
xband = xfreq.copy()
for seg in xband:
bandlist = []
for i, b in enumerate(bands):
pwr, _ = band_power(seg['data'], b)
bandlist.append(pwr)
seg['band'] = bandlist
as_matrix = asarray([
[x['band'][y][chan] for y in range(len(x['band']))] \
for x in xband for chan in x['band'][0].keys()])
desc = get_descriptives(as_matrix)
with open(filename, 'w', newline='') as f:
lg.info('Writing to ' + str(filename))
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(heading_row_1 + band_hdr)
csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
csv_file.writerow(['SD'] + spacer + list(desc['sd']))
csv_file.writerow(['Mean of ln'] + spacer + list(desc['mean_log']))
csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))
idx = 0
for seg in xband:
for chan in seg['band'][0].keys():
idx += 1
cyc = None
if seg['cycle'] is not None:
cyc = seg['cycle'][2]
data_row = list(
[seg['band'][x][chan] for x in range(
len(seg['band']))])
csv_file.writerow([idx,
seg['start'],
seg['end'],
seg['duration'],
seg['n_stitch'],
seg['stage'],
cyc,
seg['name'],
chan,
] + data_row) | [
"def",
"export_freq_band",
"(",
"xfreq",
",",
"bands",
",",
"filename",
")",
":",
"heading_row_1",
"=",
"[",
"'Segment index'",
",",
"'Start time'",
",",
"'End time'",
",",
"'Duration'",
",",
"'Stitches'",
",",
"'Stage'",
",",
"'Cycle'",
",",
"'Event type'",
"... | Write frequency analysis data to CSV by pre-defined band. | [
"Write",
"frequency",
"analysis",
"data",
"to",
"CSV",
"by",
"pre",
"-",
"defined",
"band",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/analyze.py#L355-L417 | train | 23,555 |
wonambi-python/wonambi | wonambi/attr/annotations.py | create_empty_annotations | def create_empty_annotations(xml_file, dataset):
"""Create an empty annotation file.
Notes
-----
Dates are made time-zone unaware.
"""
xml_file = Path(xml_file)
root = Element('annotations')
root.set('version', VERSION)
info = SubElement(root, 'dataset')
x = SubElement(info, 'filename')
x.text = str(dataset.filename)
x = SubElement(info, 'path') # not to be relied on
x.text = str(dataset.filename)
x = SubElement(info, 'start_time')
start_time = dataset.header['start_time'].replace(tzinfo=None)
x.text = start_time.isoformat()
first_sec = 0
last_sec = int(dataset.header['n_samples'] /
dataset.header['s_freq']) # in s
x = SubElement(info, 'first_second')
x.text = str(first_sec)
x = SubElement(info, 'last_second')
x.text = str(last_sec)
xml = parseString(tostring(root))
with xml_file.open('w') as f:
f.write(xml.toxml()) | python | def create_empty_annotations(xml_file, dataset):
"""Create an empty annotation file.
Notes
-----
Dates are made time-zone unaware.
"""
xml_file = Path(xml_file)
root = Element('annotations')
root.set('version', VERSION)
info = SubElement(root, 'dataset')
x = SubElement(info, 'filename')
x.text = str(dataset.filename)
x = SubElement(info, 'path') # not to be relied on
x.text = str(dataset.filename)
x = SubElement(info, 'start_time')
start_time = dataset.header['start_time'].replace(tzinfo=None)
x.text = start_time.isoformat()
first_sec = 0
last_sec = int(dataset.header['n_samples'] /
dataset.header['s_freq']) # in s
x = SubElement(info, 'first_second')
x.text = str(first_sec)
x = SubElement(info, 'last_second')
x.text = str(last_sec)
xml = parseString(tostring(root))
with xml_file.open('w') as f:
f.write(xml.toxml()) | [
"def",
"create_empty_annotations",
"(",
"xml_file",
",",
"dataset",
")",
":",
"xml_file",
"=",
"Path",
"(",
"xml_file",
")",
"root",
"=",
"Element",
"(",
"'annotations'",
")",
"root",
".",
"set",
"(",
"'version'",
",",
"VERSION",
")",
"info",
"=",
"SubElem... | Create an empty annotation file.
Notes
-----
Dates are made time-zone unaware. | [
"Create",
"an",
"empty",
"annotation",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L115-L146 | train | 23,556 |
wonambi-python/wonambi | wonambi/attr/annotations.py | create_annotation | def create_annotation(xml_file, from_fasst):
"""Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
-------
instance of Annotations
TODO
----
Merge create_annotation and create_empty_annotations
"""
xml_file = Path(xml_file)
try:
mat = loadmat(str(from_fasst), variable_names='D', struct_as_record=False,
squeeze_me=True)
except ValueError:
raise UnrecognizedFormat(str(from_fasst) + ' does not look like a FASST .mat file')
D = mat['D']
info = D.other.info
score = D.other.CRC.score
microsecond, second = modf(info.hour[2])
start_time = datetime(*info.date, int(info.hour[0]), int(info.hour[1]),
int(second), int(microsecond * 1e6))
first_sec = score[3, 0][0]
last_sec = score[0, 0].shape[0] * score[2, 0]
root = Element('annotations')
root.set('version', VERSION)
info = SubElement(root, 'dataset')
x = SubElement(info, 'filename')
x.text = D.other.info.fname
x = SubElement(info, 'path') # not to be relied on
x.text = D.other.info.fname
x = SubElement(info, 'start_time')
x.text = start_time.isoformat()
x = SubElement(info, 'first_second')
x.text = str(int(first_sec))
x = SubElement(info, 'last_second')
x.text = str(int(last_sec))
xml = parseString(tostring(root))
with xml_file.open('w') as f:
f.write(xml.toxml())
annot = Annotations(xml_file)
n_raters = score.shape[1]
for i_rater in range(n_raters):
rater_name = score[1, i_rater]
epoch_length = int(score[2, i_rater])
annot.add_rater(rater_name, epoch_length=epoch_length)
for epoch_start, epoch in enumerate(score[0, i_rater]):
if isnan(epoch):
continue
annot.set_stage_for_epoch(epoch_start * epoch_length,
FASST_STAGE_KEY[int(epoch)], save=False)
annot.save()
return annot | python | def create_annotation(xml_file, from_fasst):
"""Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
-------
instance of Annotations
TODO
----
Merge create_annotation and create_empty_annotations
"""
xml_file = Path(xml_file)
try:
mat = loadmat(str(from_fasst), variable_names='D', struct_as_record=False,
squeeze_me=True)
except ValueError:
raise UnrecognizedFormat(str(from_fasst) + ' does not look like a FASST .mat file')
D = mat['D']
info = D.other.info
score = D.other.CRC.score
microsecond, second = modf(info.hour[2])
start_time = datetime(*info.date, int(info.hour[0]), int(info.hour[1]),
int(second), int(microsecond * 1e6))
first_sec = score[3, 0][0]
last_sec = score[0, 0].shape[0] * score[2, 0]
root = Element('annotations')
root.set('version', VERSION)
info = SubElement(root, 'dataset')
x = SubElement(info, 'filename')
x.text = D.other.info.fname
x = SubElement(info, 'path') # not to be relied on
x.text = D.other.info.fname
x = SubElement(info, 'start_time')
x.text = start_time.isoformat()
x = SubElement(info, 'first_second')
x.text = str(int(first_sec))
x = SubElement(info, 'last_second')
x.text = str(int(last_sec))
xml = parseString(tostring(root))
with xml_file.open('w') as f:
f.write(xml.toxml())
annot = Annotations(xml_file)
n_raters = score.shape[1]
for i_rater in range(n_raters):
rater_name = score[1, i_rater]
epoch_length = int(score[2, i_rater])
annot.add_rater(rater_name, epoch_length=epoch_length)
for epoch_start, epoch in enumerate(score[0, i_rater]):
if isnan(epoch):
continue
annot.set_stage_for_epoch(epoch_start * epoch_length,
FASST_STAGE_KEY[int(epoch)], save=False)
annot.save()
return annot | [
"def",
"create_annotation",
"(",
"xml_file",
",",
"from_fasst",
")",
":",
"xml_file",
"=",
"Path",
"(",
"xml_file",
")",
"try",
":",
"mat",
"=",
"loadmat",
"(",
"str",
"(",
"from_fasst",
")",
",",
"variable_names",
"=",
"'D'",
",",
"struct_as_record",
"=",... | Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
-------
instance of Annotations
TODO
----
Merge create_annotation and create_empty_annotations | [
"Create",
"annotations",
"by",
"importing",
"from",
"FASST",
"sleep",
"scoring",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L149-L220 | train | 23,557 |
wonambi-python/wonambi | wonambi/attr/annotations.py | update_annotation_version | def update_annotation_version(xml_file):
"""Update the fields that have changed over different versions.
Parameters
----------
xml_file : path to file
xml file with the sleep scoring
Notes
-----
new in version 4: use 'marker_name' instead of simply 'name' etc
new in version 5: use 'bookmark' instead of 'marker'
"""
with open(xml_file, 'r') as f:
s = f.read()
m = search('<annotations version="([0-9]*)">', s)
current = int(m.groups()[0])
if current < 4:
s = sub('<marker><name>(.*?)</name><time>(.*?)</time></marker>',
'<marker><marker_name>\g<1></marker_name><marker_start>\g<2></marker_start><marker_end>\g<2></marker_end><marker_chan/></marker>',
s)
if current < 5:
s = s.replace('marker', 'bookmark')
# note indentation
s = sub('<annotations version="[0-9]*">',
'<annotations version="5">', s)
with open(xml_file, 'w') as f:
f.write(s) | python | def update_annotation_version(xml_file):
"""Update the fields that have changed over different versions.
Parameters
----------
xml_file : path to file
xml file with the sleep scoring
Notes
-----
new in version 4: use 'marker_name' instead of simply 'name' etc
new in version 5: use 'bookmark' instead of 'marker'
"""
with open(xml_file, 'r') as f:
s = f.read()
m = search('<annotations version="([0-9]*)">', s)
current = int(m.groups()[0])
if current < 4:
s = sub('<marker><name>(.*?)</name><time>(.*?)</time></marker>',
'<marker><marker_name>\g<1></marker_name><marker_start>\g<2></marker_start><marker_end>\g<2></marker_end><marker_chan/></marker>',
s)
if current < 5:
s = s.replace('marker', 'bookmark')
# note indentation
s = sub('<annotations version="[0-9]*">',
'<annotations version="5">', s)
with open(xml_file, 'w') as f:
f.write(s) | [
"def",
"update_annotation_version",
"(",
"xml_file",
")",
":",
"with",
"open",
"(",
"xml_file",
",",
"'r'",
")",
"as",
"f",
":",
"s",
"=",
"f",
".",
"read",
"(",
")",
"m",
"=",
"search",
"(",
"'<annotations version=\"([0-9]*)\">'",
",",
"s",
")",
"curren... | Update the fields that have changed over different versions.
Parameters
----------
xml_file : path to file
xml file with the sleep scoring
Notes
-----
new in version 4: use 'marker_name' instead of simply 'name' etc
new in version 5: use 'bookmark' instead of 'marker' | [
"Update",
"the",
"fields",
"that",
"have",
"changed",
"over",
"different",
"versions",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L2050-L2082 | train | 23,558 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.load | def load(self):
"""Load xml from file."""
lg.info('Loading ' + str(self.xml_file))
update_annotation_version(self.xml_file)
xml = parse(self.xml_file)
return xml.getroot() | python | def load(self):
"""Load xml from file."""
lg.info('Loading ' + str(self.xml_file))
update_annotation_version(self.xml_file)
xml = parse(self.xml_file)
return xml.getroot() | [
"def",
"load",
"(",
"self",
")",
":",
"lg",
".",
"info",
"(",
"'Loading '",
"+",
"str",
"(",
"self",
".",
"xml_file",
")",
")",
"update_annotation_version",
"(",
"self",
".",
"xml_file",
")",
"xml",
"=",
"parse",
"(",
"self",
".",
"xml_file",
")",
"r... | Load xml from file. | [
"Load",
"xml",
"from",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L240-L246 | train | 23,559 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.save | def save(self):
"""Save xml to file."""
if self.rater is not None:
self.rater.set('modified', datetime.now().isoformat())
xml = parseString(tostring(self.root))
with open(self.xml_file, 'w') as f:
f.write(xml.toxml()) | python | def save(self):
"""Save xml to file."""
if self.rater is not None:
self.rater.set('modified', datetime.now().isoformat())
xml = parseString(tostring(self.root))
with open(self.xml_file, 'w') as f:
f.write(xml.toxml()) | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"rater",
"is",
"not",
"None",
":",
"self",
".",
"rater",
".",
"set",
"(",
"'modified'",
",",
"datetime",
".",
"now",
"(",
")",
".",
"isoformat",
"(",
")",
")",
"xml",
"=",
"parseString",
"(... | Save xml to file. | [
"Save",
"xml",
"to",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L248-L255 | train | 23,560 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.add_bookmark | def add_bookmark(self, name, time, chan=''):
"""Add a new bookmark
Parameters
----------
name : str
name of the bookmark
time : (float, float)
float with start and end time in s
Raises
------
IndexError
When there is no selected rater
"""
try:
bookmarks = self.rater.find('bookmarks')
except AttributeError:
raise IndexError('You need to have at least one rater')
new_bookmark = SubElement(bookmarks, 'bookmark')
bookmark_name = SubElement(new_bookmark, 'bookmark_name')
bookmark_name.text = name
bookmark_time = SubElement(new_bookmark, 'bookmark_start')
bookmark_time.text = str(time[0])
bookmark_time = SubElement(new_bookmark, 'bookmark_end')
bookmark_time.text = str(time[1])
if isinstance(chan, (tuple, list)):
chan = ', '.join(chan)
event_chan = SubElement(new_bookmark, 'bookmark_chan')
event_chan.text = chan
self.save() | python | def add_bookmark(self, name, time, chan=''):
"""Add a new bookmark
Parameters
----------
name : str
name of the bookmark
time : (float, float)
float with start and end time in s
Raises
------
IndexError
When there is no selected rater
"""
try:
bookmarks = self.rater.find('bookmarks')
except AttributeError:
raise IndexError('You need to have at least one rater')
new_bookmark = SubElement(bookmarks, 'bookmark')
bookmark_name = SubElement(new_bookmark, 'bookmark_name')
bookmark_name.text = name
bookmark_time = SubElement(new_bookmark, 'bookmark_start')
bookmark_time.text = str(time[0])
bookmark_time = SubElement(new_bookmark, 'bookmark_end')
bookmark_time.text = str(time[1])
if isinstance(chan, (tuple, list)):
chan = ', '.join(chan)
event_chan = SubElement(new_bookmark, 'bookmark_chan')
event_chan.text = chan
self.save() | [
"def",
"add_bookmark",
"(",
"self",
",",
"name",
",",
"time",
",",
"chan",
"=",
"''",
")",
":",
"try",
":",
"bookmarks",
"=",
"self",
".",
"rater",
".",
"find",
"(",
"'bookmarks'",
")",
"except",
"AttributeError",
":",
"raise",
"IndexError",
"(",
"'You... | Add a new bookmark
Parameters
----------
name : str
name of the bookmark
time : (float, float)
float with start and end time in s
Raises
------
IndexError
When there is no selected rater | [
"Add",
"a",
"new",
"bookmark"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L645-L677 | train | 23,561 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.remove_bookmark | def remove_bookmark(self, name=None, time=None, chan=None):
"""if you call it without arguments, it removes ALL the bookmarks."""
bookmarks = self.rater.find('bookmarks')
for m in bookmarks:
bookmark_name = m.find('bookmark_name').text
bookmark_start = float(m.find('bookmark_start').text)
bookmark_end = float(m.find('bookmark_end').text)
bookmark_chan = m.find('bookmark_chan').text
if bookmark_chan is None: # xml doesn't store empty string
bookmark_chan = ''
if name is None:
name_cond = True
else:
name_cond = bookmark_name == name
if time is None:
time_cond = True
else:
time_cond = (time[0] <= bookmark_end and
time[1] >= bookmark_start)
if chan is None:
chan_cond = True
else:
chan_cond = bookmark_chan == chan
if name_cond and time_cond and chan_cond:
bookmarks.remove(m)
self.save() | python | def remove_bookmark(self, name=None, time=None, chan=None):
"""if you call it without arguments, it removes ALL the bookmarks."""
bookmarks = self.rater.find('bookmarks')
for m in bookmarks:
bookmark_name = m.find('bookmark_name').text
bookmark_start = float(m.find('bookmark_start').text)
bookmark_end = float(m.find('bookmark_end').text)
bookmark_chan = m.find('bookmark_chan').text
if bookmark_chan is None: # xml doesn't store empty string
bookmark_chan = ''
if name is None:
name_cond = True
else:
name_cond = bookmark_name == name
if time is None:
time_cond = True
else:
time_cond = (time[0] <= bookmark_end and
time[1] >= bookmark_start)
if chan is None:
chan_cond = True
else:
chan_cond = bookmark_chan == chan
if name_cond and time_cond and chan_cond:
bookmarks.remove(m)
self.save() | [
"def",
"remove_bookmark",
"(",
"self",
",",
"name",
"=",
"None",
",",
"time",
"=",
"None",
",",
"chan",
"=",
"None",
")",
":",
"bookmarks",
"=",
"self",
".",
"rater",
".",
"find",
"(",
"'bookmarks'",
")",
"for",
"m",
"in",
"bookmarks",
":",
"bookmark... | if you call it without arguments, it removes ALL the bookmarks. | [
"if",
"you",
"call",
"it",
"without",
"arguments",
"it",
"removes",
"ALL",
"the",
"bookmarks",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L679-L711 | train | 23,562 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.remove_event_type | def remove_event_type(self, name):
"""Remove event type based on name."""
if name not in self.event_types:
lg.info('Event type ' + name + ' was not found.')
events = self.rater.find('events')
# list is necessary so that it does not remove in place
for e in list(events):
if e.get('type') == name:
events.remove(e)
self.save() | python | def remove_event_type(self, name):
"""Remove event type based on name."""
if name not in self.event_types:
lg.info('Event type ' + name + ' was not found.')
events = self.rater.find('events')
# list is necessary so that it does not remove in place
for e in list(events):
if e.get('type') == name:
events.remove(e)
self.save() | [
"def",
"remove_event_type",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"event_types",
":",
"lg",
".",
"info",
"(",
"'Event type '",
"+",
"name",
"+",
"' was not found.'",
")",
"events",
"=",
"self",
".",
"rater",
".",
"... | Remove event type based on name. | [
"Remove",
"event",
"type",
"based",
"on",
"name",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L787-L800 | train | 23,563 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.remove_event | def remove_event(self, name=None, time=None, chan=None):
"""get events inside window."""
events = self.rater.find('events')
if name is not None:
pattern = "event_type[@type='" + name + "']"
else:
pattern = "event_type"
if chan is not None:
if isinstance(chan, (tuple, list)):
chan = ', '.join(chan)
for e_type in list(events.iterfind(pattern)):
for e in e_type:
event_start = float(e.find('event_start').text)
event_end = float(e.find('event_end').text)
event_chan = e.find('event_chan').text
if time is None:
time_cond = True
else:
time_cond = allclose(time[0], event_start) and allclose(
time[1], event_end)
if chan is None:
chan_cond = True
else:
chan_cond = event_chan == chan
if time_cond and chan_cond:
e_type.remove(e)
self.save() | python | def remove_event(self, name=None, time=None, chan=None):
"""get events inside window."""
events = self.rater.find('events')
if name is not None:
pattern = "event_type[@type='" + name + "']"
else:
pattern = "event_type"
if chan is not None:
if isinstance(chan, (tuple, list)):
chan = ', '.join(chan)
for e_type in list(events.iterfind(pattern)):
for e in e_type:
event_start = float(e.find('event_start').text)
event_end = float(e.find('event_end').text)
event_chan = e.find('event_chan').text
if time is None:
time_cond = True
else:
time_cond = allclose(time[0], event_start) and allclose(
time[1], event_end)
if chan is None:
chan_cond = True
else:
chan_cond = event_chan == chan
if time_cond and chan_cond:
e_type.remove(e)
self.save() | [
"def",
"remove_event",
"(",
"self",
",",
"name",
"=",
"None",
",",
"time",
"=",
"None",
",",
"chan",
"=",
"None",
")",
":",
"events",
"=",
"self",
".",
"rater",
".",
"find",
"(",
"'events'",
")",
"if",
"name",
"is",
"not",
"None",
":",
"pattern",
... | get events inside window. | [
"get",
"events",
"inside",
"window",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L907-L941 | train | 23,564 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.epochs | def epochs(self):
"""Get epochs as generator
Returns
-------
list of dict
each epoch is defined by start_time and end_time (in s in reference
to the start of the recordings) and a string of the sleep stage,
and a string of the signal quality.
If you specify stages_of_interest, only epochs belonging to those
stages will be included (can be an empty list).
Raises
------
IndexError
When there is no rater / epochs at all
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
for one_epoch in self.rater.iterfind('stages/epoch'):
epoch = {'start': int(one_epoch.find('epoch_start').text),
'end': int(one_epoch.find('epoch_end').text),
'stage': one_epoch.find('stage').text,
'quality': one_epoch.find('quality').text
}
yield epoch | python | def epochs(self):
"""Get epochs as generator
Returns
-------
list of dict
each epoch is defined by start_time and end_time (in s in reference
to the start of the recordings) and a string of the sleep stage,
and a string of the signal quality.
If you specify stages_of_interest, only epochs belonging to those
stages will be included (can be an empty list).
Raises
------
IndexError
When there is no rater / epochs at all
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
for one_epoch in self.rater.iterfind('stages/epoch'):
epoch = {'start': int(one_epoch.find('epoch_start').text),
'end': int(one_epoch.find('epoch_end').text),
'stage': one_epoch.find('stage').text,
'quality': one_epoch.find('quality').text
}
yield epoch | [
"def",
"epochs",
"(",
"self",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
")",
"for",
"one_epoch",
"in",
"self",
".",
"rater",
".",
"iterfind",
"(",
"'stages/epoch'",
")",
":",... | Get epochs as generator
Returns
-------
list of dict
each epoch is defined by start_time and end_time (in s in reference
to the start of the recordings) and a string of the sleep stage,
and a string of the signal quality.
If you specify stages_of_interest, only epochs belonging to those
stages will be included (can be an empty list).
Raises
------
IndexError
When there is no rater / epochs at all | [
"Get",
"epochs",
"as",
"generator"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1081-L1107 | train | 23,565 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.get_stage_for_epoch | def get_stage_for_epoch(self, epoch_start, window_length=None,
attr='stage'):
"""Return stage for one specific epoch.
Parameters
----------
id_epoch : str
index of the epoch
attr : str, optional
'stage' or 'quality'
Returns
-------
stage : str
description of the stage.
"""
for epoch in self.epochs:
if epoch['start'] == epoch_start:
return epoch[attr]
if window_length is not None:
epoch_length = epoch['end'] - epoch['start']
if logical_and(window_length < epoch_length,
0 <= \
(epoch_start - epoch['start']) < epoch_length):
return epoch[attr] | python | def get_stage_for_epoch(self, epoch_start, window_length=None,
attr='stage'):
"""Return stage for one specific epoch.
Parameters
----------
id_epoch : str
index of the epoch
attr : str, optional
'stage' or 'quality'
Returns
-------
stage : str
description of the stage.
"""
for epoch in self.epochs:
if epoch['start'] == epoch_start:
return epoch[attr]
if window_length is not None:
epoch_length = epoch['end'] - epoch['start']
if logical_and(window_length < epoch_length,
0 <= \
(epoch_start - epoch['start']) < epoch_length):
return epoch[attr] | [
"def",
"get_stage_for_epoch",
"(",
"self",
",",
"epoch_start",
",",
"window_length",
"=",
"None",
",",
"attr",
"=",
"'stage'",
")",
":",
"for",
"epoch",
"in",
"self",
".",
"epochs",
":",
"if",
"epoch",
"[",
"'start'",
"]",
"==",
"epoch_start",
":",
"retu... | Return stage for one specific epoch.
Parameters
----------
id_epoch : str
index of the epoch
attr : str, optional
'stage' or 'quality'
Returns
-------
stage : str
description of the stage. | [
"Return",
"stage",
"for",
"one",
"specific",
"epoch",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1166-L1191 | train | 23,566 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.set_stage_for_epoch | def set_stage_for_epoch(self, epoch_start, name, attr='stage', save=True):
"""Change the stage for one specific epoch.
Parameters
----------
epoch_start : int
start time of the epoch, in seconds
name : str
description of the stage or qualifier.
attr : str, optional
either 'stage' or 'quality'
save : bool
whether to save every time one epoch is scored
Raises
------
KeyError
When the epoch_start is not in the list of epochs.
IndexError
When there is no rater / epochs at all
Notes
-----
In the GUI, you want to save as often as possible, even if it slows
down the program, but it's the safer option. But if you're converting
a dataset, you want to save at the end. Do not forget to save!
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
for one_epoch in self.rater.iterfind('stages/epoch'):
if int(one_epoch.find('epoch_start').text) == epoch_start:
one_epoch.find(attr).text = name
if save:
self.save()
return
raise KeyError('epoch starting at ' + str(epoch_start) + ' not found') | python | def set_stage_for_epoch(self, epoch_start, name, attr='stage', save=True):
"""Change the stage for one specific epoch.
Parameters
----------
epoch_start : int
start time of the epoch, in seconds
name : str
description of the stage or qualifier.
attr : str, optional
either 'stage' or 'quality'
save : bool
whether to save every time one epoch is scored
Raises
------
KeyError
When the epoch_start is not in the list of epochs.
IndexError
When there is no rater / epochs at all
Notes
-----
In the GUI, you want to save as often as possible, even if it slows
down the program, but it's the safer option. But if you're converting
a dataset, you want to save at the end. Do not forget to save!
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
for one_epoch in self.rater.iterfind('stages/epoch'):
if int(one_epoch.find('epoch_start').text) == epoch_start:
one_epoch.find(attr).text = name
if save:
self.save()
return
raise KeyError('epoch starting at ' + str(epoch_start) + ' not found') | [
"def",
"set_stage_for_epoch",
"(",
"self",
",",
"epoch_start",
",",
"name",
",",
"attr",
"=",
"'stage'",
",",
"save",
"=",
"True",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
"... | Change the stage for one specific epoch.
Parameters
----------
epoch_start : int
start time of the epoch, in seconds
name : str
description of the stage or qualifier.
attr : str, optional
either 'stage' or 'quality'
save : bool
whether to save every time one epoch is scored
Raises
------
KeyError
When the epoch_start is not in the list of epochs.
IndexError
When there is no rater / epochs at all
Notes
-----
In the GUI, you want to save as often as possible, even if it slows
down the program, but it's the safer option. But if you're converting
a dataset, you want to save at the end. Do not forget to save! | [
"Change",
"the",
"stage",
"for",
"one",
"specific",
"epoch",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1212-L1249 | train | 23,567 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.set_cycle_mrkr | def set_cycle_mrkr(self, epoch_start, end=False):
"""Mark epoch start as cycle start or end.
Parameters
----------
epoch_start: int
start time of the epoch, in seconds
end : bool
If True, marked as cycle end; otherwise, marks cycle start
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
bound = 'start'
if end:
bound = 'end'
for one_epoch in self.rater.iterfind('stages/epoch'):
if int(one_epoch.find('epoch_start').text) == epoch_start:
cycles = self.rater.find('cycles')
name = 'cyc_' + bound
new_bound = SubElement(cycles, name)
new_bound.text = str(int(epoch_start))
self.save()
return
raise KeyError('epoch starting at ' + str(epoch_start) + ' not found') | python | def set_cycle_mrkr(self, epoch_start, end=False):
"""Mark epoch start as cycle start or end.
Parameters
----------
epoch_start: int
start time of the epoch, in seconds
end : bool
If True, marked as cycle end; otherwise, marks cycle start
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
bound = 'start'
if end:
bound = 'end'
for one_epoch in self.rater.iterfind('stages/epoch'):
if int(one_epoch.find('epoch_start').text) == epoch_start:
cycles = self.rater.find('cycles')
name = 'cyc_' + bound
new_bound = SubElement(cycles, name)
new_bound.text = str(int(epoch_start))
self.save()
return
raise KeyError('epoch starting at ' + str(epoch_start) + ' not found') | [
"def",
"set_cycle_mrkr",
"(",
"self",
",",
"epoch_start",
",",
"end",
"=",
"False",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
")",
"bound",
"=",
"'start'",
"if",
"end",
":",
... | Mark epoch start as cycle start or end.
Parameters
----------
epoch_start: int
start time of the epoch, in seconds
end : bool
If True, marked as cycle end; otherwise, marks cycle start | [
"Mark",
"epoch",
"start",
"as",
"cycle",
"start",
"or",
"end",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1251-L1277 | train | 23,568 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.remove_cycle_mrkr | def remove_cycle_mrkr(self, epoch_start):
"""Remove cycle marker at epoch_start.
Parameters
----------
epoch_start: int
start time of epoch, in seconds
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
cycles = self.rater.find('cycles')
for one_mrkr in cycles.iterfind('cyc_start'):
if int(one_mrkr.text) == epoch_start:
cycles.remove(one_mrkr)
self.save()
return
for one_mrkr in cycles.iterfind('cyc_end'):
if int(one_mrkr.text) == epoch_start:
cycles.remove(one_mrkr)
self.save()
return
raise KeyError('cycle marker at ' + str(epoch_start) + ' not found') | python | def remove_cycle_mrkr(self, epoch_start):
"""Remove cycle marker at epoch_start.
Parameters
----------
epoch_start: int
start time of epoch, in seconds
"""
if self.rater is None:
raise IndexError('You need to have at least one rater')
cycles = self.rater.find('cycles')
for one_mrkr in cycles.iterfind('cyc_start'):
if int(one_mrkr.text) == epoch_start:
cycles.remove(one_mrkr)
self.save()
return
for one_mrkr in cycles.iterfind('cyc_end'):
if int(one_mrkr.text) == epoch_start:
cycles.remove(one_mrkr)
self.save()
return
raise KeyError('cycle marker at ' + str(epoch_start) + ' not found') | [
"def",
"remove_cycle_mrkr",
"(",
"self",
",",
"epoch_start",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
")",
"cycles",
"=",
"self",
".",
"rater",
".",
"find",
"(",
"'cycles'",
... | Remove cycle marker at epoch_start.
Parameters
----------
epoch_start: int
start time of epoch, in seconds | [
"Remove",
"cycle",
"marker",
"at",
"epoch_start",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1279-L1302 | train | 23,569 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.clear_cycles | def clear_cycles(self):
"""Remove all cycle markers in current rater."""
if self.rater is None:
raise IndexError('You need to have at least one rater')
cycles = self.rater.find('cycles')
for cyc in list(cycles):
cycles.remove(cyc)
self.save() | python | def clear_cycles(self):
"""Remove all cycle markers in current rater."""
if self.rater is None:
raise IndexError('You need to have at least one rater')
cycles = self.rater.find('cycles')
for cyc in list(cycles):
cycles.remove(cyc)
self.save() | [
"def",
"clear_cycles",
"(",
"self",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
")",
"cycles",
"=",
"self",
".",
"rater",
".",
"find",
"(",
"'cycles'",
")",
"for",
"cyc",
"in... | Remove all cycle markers in current rater. | [
"Remove",
"all",
"cycle",
"markers",
"in",
"current",
"rater",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1304-L1313 | train | 23,570 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.get_cycles | def get_cycles(self):
"""Return the cycle start and end times.
Returns
-------
list of tuple of float
start and end times for each cycle, in seconds from recording start
and the cycle index starting at 1
"""
cycles = self.rater.find('cycles')
if not cycles:
return None
starts = sorted(
[float(mrkr.text) for mrkr in cycles.findall('cyc_start')])
ends = sorted(
[float(mrkr.text) for mrkr in cycles.findall('cyc_end')])
cyc_list = []
if not starts or not ends:
return None
if all(i < starts[0] for i in ends):
raise ValueError('First cycle has no start.')
for (this_start, next_start) in zip(starts, starts[1:] + [inf]):
# if an end is smaller than the next start, make it the end
# otherwise, the next_start is the end
end_between_starts = [end for end in ends \
if this_start < end <= next_start]
if len(end_between_starts) > 1:
raise ValueError('Found more than one cycle end for same '
'cycle')
if end_between_starts:
one_cycle = (this_start, end_between_starts[0])
else:
one_cycle = (this_start, next_start)
if one_cycle[1] == inf:
raise ValueError('Last cycle has no end.')
cyc_list.append(one_cycle)
output = []
for i, j in enumerate(cyc_list):
cyc = j[0], j[1], i + 1
output.append(cyc)
return output | python | def get_cycles(self):
"""Return the cycle start and end times.
Returns
-------
list of tuple of float
start and end times for each cycle, in seconds from recording start
and the cycle index starting at 1
"""
cycles = self.rater.find('cycles')
if not cycles:
return None
starts = sorted(
[float(mrkr.text) for mrkr in cycles.findall('cyc_start')])
ends = sorted(
[float(mrkr.text) for mrkr in cycles.findall('cyc_end')])
cyc_list = []
if not starts or not ends:
return None
if all(i < starts[0] for i in ends):
raise ValueError('First cycle has no start.')
for (this_start, next_start) in zip(starts, starts[1:] + [inf]):
# if an end is smaller than the next start, make it the end
# otherwise, the next_start is the end
end_between_starts = [end for end in ends \
if this_start < end <= next_start]
if len(end_between_starts) > 1:
raise ValueError('Found more than one cycle end for same '
'cycle')
if end_between_starts:
one_cycle = (this_start, end_between_starts[0])
else:
one_cycle = (this_start, next_start)
if one_cycle[1] == inf:
raise ValueError('Last cycle has no end.')
cyc_list.append(one_cycle)
output = []
for i, j in enumerate(cyc_list):
cyc = j[0], j[1], i + 1
output.append(cyc)
return output | [
"def",
"get_cycles",
"(",
"self",
")",
":",
"cycles",
"=",
"self",
".",
"rater",
".",
"find",
"(",
"'cycles'",
")",
"if",
"not",
"cycles",
":",
"return",
"None",
"starts",
"=",
"sorted",
"(",
"[",
"float",
"(",
"mrkr",
".",
"text",
")",
"for",
"mrk... | Return the cycle start and end times.
Returns
-------
list of tuple of float
start and end times for each cycle, in seconds from recording start
and the cycle index starting at 1 | [
"Return",
"the",
"cycle",
"start",
"and",
"end",
"times",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1315-L1366 | train | 23,571 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.switch | def switch(self, time=None):
"""Obtain switch parameter, ie number of times the stage shifts."""
stag_to_int = {'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 5, 'Wake': 0}
hypno = [stag_to_int[x['stage']] for x in self.get_epochs(time=time) \
if x['stage'] in stag_to_int.keys()]
return sum(asarray(diff(hypno), dtype=bool)) | python | def switch(self, time=None):
"""Obtain switch parameter, ie number of times the stage shifts."""
stag_to_int = {'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 5, 'Wake': 0}
hypno = [stag_to_int[x['stage']] for x in self.get_epochs(time=time) \
if x['stage'] in stag_to_int.keys()]
return sum(asarray(diff(hypno), dtype=bool)) | [
"def",
"switch",
"(",
"self",
",",
"time",
"=",
"None",
")",
":",
"stag_to_int",
"=",
"{",
"'NREM1'",
":",
"1",
",",
"'NREM2'",
":",
"2",
",",
"'NREM3'",
":",
"3",
",",
"'REM'",
":",
"5",
",",
"'Wake'",
":",
"0",
"}",
"hypno",
"=",
"[",
"stag_t... | Obtain switch parameter, ie number of times the stage shifts. | [
"Obtain",
"switch",
"parameter",
"ie",
"number",
"of",
"times",
"the",
"stage",
"shifts",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1368-L1374 | train | 23,572 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.slp_frag | def slp_frag(self, time=None):
"""Obtain sleep fragmentation parameter, ie number of stage shifts to
a lighter stage."""
epochs = self.get_epochs(time=time)
stage_int = {'Wake': 0, 'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 2}
hypno_str = [x['stage'] for x in epochs \
if x['stage'] in stage_int.keys()]
hypno_int = [stage_int[x] for x in hypno_str]
frag = sum(asarray(clip(diff(hypno_int), a_min=None, a_max=0),
dtype=bool))
# N3 to REM doesn't count
n3_to_rem = 0
for i, j in enumerate(hypno_str[:-1]):
if j == 'NREM3':
if hypno_str[i + 1] == 'REM':
n3_to_rem += 1
return frag - n3_to_rem | python | def slp_frag(self, time=None):
"""Obtain sleep fragmentation parameter, ie number of stage shifts to
a lighter stage."""
epochs = self.get_epochs(time=time)
stage_int = {'Wake': 0, 'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 2}
hypno_str = [x['stage'] for x in epochs \
if x['stage'] in stage_int.keys()]
hypno_int = [stage_int[x] for x in hypno_str]
frag = sum(asarray(clip(diff(hypno_int), a_min=None, a_max=0),
dtype=bool))
# N3 to REM doesn't count
n3_to_rem = 0
for i, j in enumerate(hypno_str[:-1]):
if j == 'NREM3':
if hypno_str[i + 1] == 'REM':
n3_to_rem += 1
return frag - n3_to_rem | [
"def",
"slp_frag",
"(",
"self",
",",
"time",
"=",
"None",
")",
":",
"epochs",
"=",
"self",
".",
"get_epochs",
"(",
"time",
"=",
"time",
")",
"stage_int",
"=",
"{",
"'Wake'",
":",
"0",
",",
"'NREM1'",
":",
"1",
",",
"'NREM2'",
":",
"2",
",",
"'NRE... | Obtain sleep fragmentation parameter, ie number of stage shifts to
a lighter stage. | [
"Obtain",
"sleep",
"fragmentation",
"parameter",
"ie",
"number",
"of",
"stage",
"shifts",
"to",
"a",
"lighter",
"stage",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1376-L1395 | train | 23,573 |
wonambi-python/wonambi | wonambi/attr/annotations.py | Annotations.export | def export(self, file_to_export, xformat='csv'):
"""Export epochwise annotations to csv file.
Parameters
----------
file_to_export : path to file
file to write to
"""
if 'csv' == xformat:
with open(file_to_export, 'w', newline='') as f:
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(('clock start time', 'start', 'end',
'stage'))
for epoch in self.epochs:
epoch_time = (self.start_time +
timedelta(seconds=epoch['start']))
csv_file.writerow((epoch_time.strftime('%H:%M:%S'),
epoch['start'],
epoch['end'],
epoch['stage']))
if 'remlogic' in xformat:
columns = 'Time [hh:mm:ss]\tEvent\tDuration[s]\n'
if 'remlogic_fr' == xformat:
columns = 'Heure [hh:mm:ss]\tEvénement\tDurée[s]\n'
patient_id = splitext(basename(self.dataset))[0]
rec_date = self.start_time.strftime('%d/%m/%Y')
stkey = {v:k for k, v in REMLOGIC_STAGE_KEY.items()}
stkey['Artefact'] = 'SLEEP-UNSCORED'
stkey['Unknown'] = 'SLEEP-UNSCORED'
stkey['Movement'] = 'SLEEP-UNSCORED'
with open(file_to_export, 'w') as f:
f.write('RemLogic Event Export\n')
f.write('Patient:\t' + patient_id + '\n')
f.write('Patient ID:\t' + patient_id + '\n')
f.write('Recording Date:\t' + rec_date + '\n')
f.write('\n')
f.write('Events Included:\n')
for i in sorted(set([stkey[x['stage']] for x in self.epochs])):
f.write(i + '\n')
f.write('\n')
f.write(columns)
for epoch in self.epochs:
epoch_time = (self.start_time +
timedelta(seconds=epoch['start']))
f.write((epoch_time.strftime('%Y-%m-%dT%H:%M:%S.000000') +
'\t' +
stkey[epoch['stage']] +
'\t' +
str(self.epoch_length) +
'\n')) | python | def export(self, file_to_export, xformat='csv'):
"""Export epochwise annotations to csv file.
Parameters
----------
file_to_export : path to file
file to write to
"""
if 'csv' == xformat:
with open(file_to_export, 'w', newline='') as f:
csv_file = writer(f)
csv_file.writerow(['Wonambi v{}'.format(__version__)])
csv_file.writerow(('clock start time', 'start', 'end',
'stage'))
for epoch in self.epochs:
epoch_time = (self.start_time +
timedelta(seconds=epoch['start']))
csv_file.writerow((epoch_time.strftime('%H:%M:%S'),
epoch['start'],
epoch['end'],
epoch['stage']))
if 'remlogic' in xformat:
columns = 'Time [hh:mm:ss]\tEvent\tDuration[s]\n'
if 'remlogic_fr' == xformat:
columns = 'Heure [hh:mm:ss]\tEvénement\tDurée[s]\n'
patient_id = splitext(basename(self.dataset))[0]
rec_date = self.start_time.strftime('%d/%m/%Y')
stkey = {v:k for k, v in REMLOGIC_STAGE_KEY.items()}
stkey['Artefact'] = 'SLEEP-UNSCORED'
stkey['Unknown'] = 'SLEEP-UNSCORED'
stkey['Movement'] = 'SLEEP-UNSCORED'
with open(file_to_export, 'w') as f:
f.write('RemLogic Event Export\n')
f.write('Patient:\t' + patient_id + '\n')
f.write('Patient ID:\t' + patient_id + '\n')
f.write('Recording Date:\t' + rec_date + '\n')
f.write('\n')
f.write('Events Included:\n')
for i in sorted(set([stkey[x['stage']] for x in self.epochs])):
f.write(i + '\n')
f.write('\n')
f.write(columns)
for epoch in self.epochs:
epoch_time = (self.start_time +
timedelta(seconds=epoch['start']))
f.write((epoch_time.strftime('%Y-%m-%dT%H:%M:%S.000000') +
'\t' +
stkey[epoch['stage']] +
'\t' +
str(self.epoch_length) +
'\n')) | [
"def",
"export",
"(",
"self",
",",
"file_to_export",
",",
"xformat",
"=",
"'csv'",
")",
":",
"if",
"'csv'",
"==",
"xformat",
":",
"with",
"open",
"(",
"file_to_export",
",",
"'w'",
",",
"newline",
"=",
"''",
")",
"as",
"f",
":",
"csv_file",
"=",
"wri... | Export epochwise annotations to csv file.
Parameters
----------
file_to_export : path to file
file to write to | [
"Export",
"epochwise",
"annotations",
"to",
"csv",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1440-L1499 | train | 23,574 |
wonambi-python/wonambi | wonambi/widgets/info.py | Info.create | def create(self):
"""Create the widget layout with all the information."""
b0 = QGroupBox('Dataset')
form = QFormLayout()
b0.setLayout(form)
open_rec = QPushButton('Open Dataset...')
open_rec.clicked.connect(self.open_dataset)
open_rec.setToolTip('Click here to open a new recording')
self.idx_filename = open_rec
self.idx_s_freq = QLabel('')
self.idx_n_chan = QLabel('')
self.idx_start_time = QLabel('')
self.idx_end_time = QLabel('')
form.addRow('Filename:', self.idx_filename)
form.addRow('Sampl. Freq:', self.idx_s_freq)
form.addRow('N. Channels:', self.idx_n_chan)
form.addRow('Start Time: ', self.idx_start_time)
form.addRow('End Time: ', self.idx_end_time)
b1 = QGroupBox('View')
form = QFormLayout()
b1.setLayout(form)
self.idx_start = QLabel('')
self.idx_start.setToolTip('Start time in seconds from the beginning of'
' the recordings')
self.idx_length = QLabel('')
self.idx_length.setToolTip('Duration of the time window in seconds')
self.idx_scaling = QLabel('')
self.idx_scaling.setToolTip('Global scaling for all the channels')
self.idx_distance = QLabel('')
self.idx_distance.setToolTip('Visual distances between the traces of '
'individual channels')
form.addRow('Start Time:', self.idx_start)
form.addRow('Length:', self.idx_length)
form.addRow('Scaling:', self.idx_scaling)
form.addRow('Distance:', self.idx_distance)
layout = QVBoxLayout()
layout.addWidget(b0)
layout.addWidget(b1)
self.setLayout(layout) | python | def create(self):
"""Create the widget layout with all the information."""
b0 = QGroupBox('Dataset')
form = QFormLayout()
b0.setLayout(form)
open_rec = QPushButton('Open Dataset...')
open_rec.clicked.connect(self.open_dataset)
open_rec.setToolTip('Click here to open a new recording')
self.idx_filename = open_rec
self.idx_s_freq = QLabel('')
self.idx_n_chan = QLabel('')
self.idx_start_time = QLabel('')
self.idx_end_time = QLabel('')
form.addRow('Filename:', self.idx_filename)
form.addRow('Sampl. Freq:', self.idx_s_freq)
form.addRow('N. Channels:', self.idx_n_chan)
form.addRow('Start Time: ', self.idx_start_time)
form.addRow('End Time: ', self.idx_end_time)
b1 = QGroupBox('View')
form = QFormLayout()
b1.setLayout(form)
self.idx_start = QLabel('')
self.idx_start.setToolTip('Start time in seconds from the beginning of'
' the recordings')
self.idx_length = QLabel('')
self.idx_length.setToolTip('Duration of the time window in seconds')
self.idx_scaling = QLabel('')
self.idx_scaling.setToolTip('Global scaling for all the channels')
self.idx_distance = QLabel('')
self.idx_distance.setToolTip('Visual distances between the traces of '
'individual channels')
form.addRow('Start Time:', self.idx_start)
form.addRow('Length:', self.idx_length)
form.addRow('Scaling:', self.idx_scaling)
form.addRow('Distance:', self.idx_distance)
layout = QVBoxLayout()
layout.addWidget(b0)
layout.addWidget(b1)
self.setLayout(layout) | [
"def",
"create",
"(",
"self",
")",
":",
"b0",
"=",
"QGroupBox",
"(",
"'Dataset'",
")",
"form",
"=",
"QFormLayout",
"(",
")",
"b0",
".",
"setLayout",
"(",
"form",
")",
"open_rec",
"=",
"QPushButton",
"(",
"'Open Dataset...'",
")",
"open_rec",
".",
"clicke... | Create the widget layout with all the information. | [
"Create",
"the",
"widget",
"layout",
"with",
"all",
"the",
"information",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L90-L135 | train | 23,575 |
wonambi-python/wonambi | wonambi/widgets/info.py | Info.open_dataset | def open_dataset(self, recent=None, debug_filename=None, bids=False):
"""Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read
"""
if recent:
filename = recent
elif debug_filename is not None:
filename = debug_filename
else:
try:
dir_name = dirname(self.filename)
except (AttributeError, TypeError):
dir_name = self.parent.value('recording_dir')
file_or_dir = choose_file_or_dir()
if file_or_dir == 'dir':
filename = QFileDialog.getExistingDirectory(self,
'Open directory',
dir_name)
elif file_or_dir == 'file':
filename, _ = QFileDialog.getOpenFileName(self, 'Open file',
dir_name)
elif file_or_dir == 'abort':
return
if filename == '':
return
# clear previous dataset once the user opens another dataset
if self.dataset is not None:
self.parent.reset()
self.parent.statusBar().showMessage('Reading dataset: ' +
basename(filename))
lg.info('Reading dataset: ' + str(filename))
self.filename = filename # temp
self.dataset = Dataset(filename) #temp
#==============================================================================
# try:
# self.filename = filename
# self.dataset = Dataset(filename)
# except FileNotFoundError:
# msg = 'File ' + basename(filename) + ' cannot be read'
# self.parent.statusBar().showMessage(msg)
# lg.info(msg)
# error_dialog = QErrorMessage()
# error_dialog.setWindowTitle('Error opening dataset')
# error_dialog.showMessage(msg)
# if debug_filename is None:
# error_dialog.exec()
# return
#
# except BaseException as err:
# self.parent.statusBar().showMessage(str(err))
# lg.info('Error ' + str(err))
# error_dialog = QErrorMessage()
# error_dialog.setWindowTitle('Error opening dataset')
# error_dialog.showMessage(str(err))
# if debug_filename is None:
# error_dialog.exec()
# return
#==============================================================================
self.action['export'].setEnabled(True)
self.parent.statusBar().showMessage('')
self.parent.update() | python | def open_dataset(self, recent=None, debug_filename=None, bids=False):
"""Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read
"""
if recent:
filename = recent
elif debug_filename is not None:
filename = debug_filename
else:
try:
dir_name = dirname(self.filename)
except (AttributeError, TypeError):
dir_name = self.parent.value('recording_dir')
file_or_dir = choose_file_or_dir()
if file_or_dir == 'dir':
filename = QFileDialog.getExistingDirectory(self,
'Open directory',
dir_name)
elif file_or_dir == 'file':
filename, _ = QFileDialog.getOpenFileName(self, 'Open file',
dir_name)
elif file_or_dir == 'abort':
return
if filename == '':
return
# clear previous dataset once the user opens another dataset
if self.dataset is not None:
self.parent.reset()
self.parent.statusBar().showMessage('Reading dataset: ' +
basename(filename))
lg.info('Reading dataset: ' + str(filename))
self.filename = filename # temp
self.dataset = Dataset(filename) #temp
#==============================================================================
# try:
# self.filename = filename
# self.dataset = Dataset(filename)
# except FileNotFoundError:
# msg = 'File ' + basename(filename) + ' cannot be read'
# self.parent.statusBar().showMessage(msg)
# lg.info(msg)
# error_dialog = QErrorMessage()
# error_dialog.setWindowTitle('Error opening dataset')
# error_dialog.showMessage(msg)
# if debug_filename is None:
# error_dialog.exec()
# return
#
# except BaseException as err:
# self.parent.statusBar().showMessage(str(err))
# lg.info('Error ' + str(err))
# error_dialog = QErrorMessage()
# error_dialog.setWindowTitle('Error opening dataset')
# error_dialog.showMessage(str(err))
# if debug_filename is None:
# error_dialog.exec()
# return
#==============================================================================
self.action['export'].setEnabled(True)
self.parent.statusBar().showMessage('')
self.parent.update() | [
"def",
"open_dataset",
"(",
"self",
",",
"recent",
"=",
"None",
",",
"debug_filename",
"=",
"None",
",",
"bids",
"=",
"False",
")",
":",
"if",
"recent",
":",
"filename",
"=",
"recent",
"elif",
"debug_filename",
"is",
"not",
"None",
":",
"filename",
"=",
... | Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read | [
"Open",
"a",
"new",
"dataset",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L174-L248 | train | 23,576 |
wonambi-python/wonambi | wonambi/widgets/info.py | Info.display_dataset | def display_dataset(self):
"""Update the widget with information about the dataset."""
header = self.dataset.header
self.parent.setWindowTitle(basename(self.filename))
short_filename = short_strings(basename(self.filename))
self.idx_filename.setText(short_filename)
self.idx_s_freq.setText(str(header['s_freq']))
self.idx_n_chan.setText(str(len(header['chan_name'])))
start_time = header['start_time'].strftime('%b-%d %H:%M:%S')
self.idx_start_time.setText(start_time)
end_time = (header['start_time'] +
timedelta(seconds=header['n_samples'] / header['s_freq']))
self.idx_end_time.setText(end_time.strftime('%b-%d %H:%M:%S')) | python | def display_dataset(self):
"""Update the widget with information about the dataset."""
header = self.dataset.header
self.parent.setWindowTitle(basename(self.filename))
short_filename = short_strings(basename(self.filename))
self.idx_filename.setText(short_filename)
self.idx_s_freq.setText(str(header['s_freq']))
self.idx_n_chan.setText(str(len(header['chan_name'])))
start_time = header['start_time'].strftime('%b-%d %H:%M:%S')
self.idx_start_time.setText(start_time)
end_time = (header['start_time'] +
timedelta(seconds=header['n_samples'] / header['s_freq']))
self.idx_end_time.setText(end_time.strftime('%b-%d %H:%M:%S')) | [
"def",
"display_dataset",
"(",
"self",
")",
":",
"header",
"=",
"self",
".",
"dataset",
".",
"header",
"self",
".",
"parent",
".",
"setWindowTitle",
"(",
"basename",
"(",
"self",
".",
"filename",
")",
")",
"short_filename",
"=",
"short_strings",
"(",
"base... | Update the widget with information about the dataset. | [
"Update",
"the",
"widget",
"with",
"information",
"about",
"the",
"dataset",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L250-L263 | train | 23,577 |
wonambi-python/wonambi | wonambi/widgets/info.py | Info.display_view | def display_view(self):
"""Update information about the size of the traces."""
self.idx_start.setText(str(self.parent.value('window_start')))
self.idx_length.setText(str(self.parent.value('window_length')))
self.idx_scaling.setText(str(self.parent.value('y_scale')))
self.idx_distance.setText(str(self.parent.value('y_distance'))) | python | def display_view(self):
"""Update information about the size of the traces."""
self.idx_start.setText(str(self.parent.value('window_start')))
self.idx_length.setText(str(self.parent.value('window_length')))
self.idx_scaling.setText(str(self.parent.value('y_scale')))
self.idx_distance.setText(str(self.parent.value('y_distance'))) | [
"def",
"display_view",
"(",
"self",
")",
":",
"self",
".",
"idx_start",
".",
"setText",
"(",
"str",
"(",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
")",
")",
"self",
".",
"idx_length",
".",
"setText",
"(",
"str",
"(",
"self",
".... | Update information about the size of the traces. | [
"Update",
"information",
"about",
"the",
"size",
"of",
"the",
"traces",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L265-L270 | train | 23,578 |
wonambi-python/wonambi | wonambi/widgets/info.py | Info.reset | def reset(self):
"""Reset widget to original state."""
self.filename = None
self.dataset = None
# about the recordings
self.idx_filename.setText('Open Recordings...')
self.idx_s_freq.setText('')
self.idx_n_chan.setText('')
self.idx_start_time.setText('')
self.idx_end_time.setText('')
# about the visualization
self.idx_scaling.setText('')
self.idx_distance.setText('')
self.idx_length.setText('')
self.idx_start.setText('') | python | def reset(self):
"""Reset widget to original state."""
self.filename = None
self.dataset = None
# about the recordings
self.idx_filename.setText('Open Recordings...')
self.idx_s_freq.setText('')
self.idx_n_chan.setText('')
self.idx_start_time.setText('')
self.idx_end_time.setText('')
# about the visualization
self.idx_scaling.setText('')
self.idx_distance.setText('')
self.idx_length.setText('')
self.idx_start.setText('') | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"filename",
"=",
"None",
"self",
".",
"dataset",
"=",
"None",
"# about the recordings",
"self",
".",
"idx_filename",
".",
"setText",
"(",
"'Open Recordings...'",
")",
"self",
".",
"idx_s_freq",
".",
"setTex... | Reset widget to original state. | [
"Reset",
"widget",
"to",
"original",
"state",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L272-L288 | train | 23,579 |
wonambi-python/wonambi | wonambi/widgets/info.py | ExportDatasetDialog.update | def update(self):
"""Get info from dataset before opening dialog."""
self.filename = self.parent.info.dataset.filename
self.chan = self.parent.info.dataset.header['chan_name']
for chan in self.chan:
self.idx_chan.addItem(chan) | python | def update(self):
"""Get info from dataset before opening dialog."""
self.filename = self.parent.info.dataset.filename
self.chan = self.parent.info.dataset.header['chan_name']
for chan in self.chan:
self.idx_chan.addItem(chan) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"filename",
"=",
"self",
".",
"parent",
".",
"info",
".",
"dataset",
".",
"filename",
"self",
".",
"chan",
"=",
"self",
".",
"parent",
".",
"info",
".",
"dataset",
".",
"header",
"[",
"'chan_name'"... | Get info from dataset before opening dialog. | [
"Get",
"info",
"from",
"dataset",
"before",
"opening",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L460-L466 | train | 23,580 |
wonambi-python/wonambi | wonambi/utils/simulate.py | create_channels | def create_channels(chan_name=None, n_chan=None):
"""Create instance of Channels with random xyz coordinates
Parameters
----------
chan_name : list of str
names of the channels
n_chan : int
if chan_name is not specified, this defines the number of channels
Returns
-------
instance of Channels
where the location of the channels is random
"""
if chan_name is not None:
n_chan = len(chan_name)
elif n_chan is not None:
chan_name = _make_chan_name(n_chan)
else:
raise TypeError('You need to specify either the channel names (chan_name) or the number of channels (n_chan)')
xyz = round(random.randn(n_chan, 3) * 10, decimals=2)
return Channels(chan_name, xyz) | python | def create_channels(chan_name=None, n_chan=None):
"""Create instance of Channels with random xyz coordinates
Parameters
----------
chan_name : list of str
names of the channels
n_chan : int
if chan_name is not specified, this defines the number of channels
Returns
-------
instance of Channels
where the location of the channels is random
"""
if chan_name is not None:
n_chan = len(chan_name)
elif n_chan is not None:
chan_name = _make_chan_name(n_chan)
else:
raise TypeError('You need to specify either the channel names (chan_name) or the number of channels (n_chan)')
xyz = round(random.randn(n_chan, 3) * 10, decimals=2)
return Channels(chan_name, xyz) | [
"def",
"create_channels",
"(",
"chan_name",
"=",
"None",
",",
"n_chan",
"=",
"None",
")",
":",
"if",
"chan_name",
"is",
"not",
"None",
":",
"n_chan",
"=",
"len",
"(",
"chan_name",
")",
"elif",
"n_chan",
"is",
"not",
"None",
":",
"chan_name",
"=",
"_mak... | Create instance of Channels with random xyz coordinates
Parameters
----------
chan_name : list of str
names of the channels
n_chan : int
if chan_name is not specified, this defines the number of channels
Returns
-------
instance of Channels
where the location of the channels is random | [
"Create",
"instance",
"of",
"Channels",
"with",
"random",
"xyz",
"coordinates"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/utils/simulate.py#L145-L170 | train | 23,581 |
wonambi-python/wonambi | wonambi/utils/simulate.py | _color_noise | def _color_noise(x, s_freq, coef=0):
"""Add some color to the noise by changing the power spectrum.
Parameters
----------
x : ndarray
one vector of the original signal
s_freq : int
sampling frequency
coef : float
coefficient to apply (0 -> white noise, 1 -> pink, 2 -> brown,
-1 -> blue)
Returns
-------
ndarray
one vector of the colored noise.
"""
# convert to freq domain
y = fft(x)
ph = angle(y)
m = abs(y)
# frequencies for each fft value
freq = linspace(0, s_freq / 2, int(len(m) / 2) + 1)
freq = freq[1:-1]
# create new power spectrum
m1 = zeros(len(m))
# leave zero alone, and multiply the rest by the function
m1[1:int(len(m) / 2)] = m[1:int(len(m) / 2)] * f(freq, coef)
# simmetric around nyquist freq
m1[int(len(m1) / 2 + 1):] = m1[1:int(len(m1) / 2)][::-1]
# reconstruct the signal
y1 = m1 * exp(1j * ph)
return real(ifft(y1)) | python | def _color_noise(x, s_freq, coef=0):
"""Add some color to the noise by changing the power spectrum.
Parameters
----------
x : ndarray
one vector of the original signal
s_freq : int
sampling frequency
coef : float
coefficient to apply (0 -> white noise, 1 -> pink, 2 -> brown,
-1 -> blue)
Returns
-------
ndarray
one vector of the colored noise.
"""
# convert to freq domain
y = fft(x)
ph = angle(y)
m = abs(y)
# frequencies for each fft value
freq = linspace(0, s_freq / 2, int(len(m) / 2) + 1)
freq = freq[1:-1]
# create new power spectrum
m1 = zeros(len(m))
# leave zero alone, and multiply the rest by the function
m1[1:int(len(m) / 2)] = m[1:int(len(m) / 2)] * f(freq, coef)
# simmetric around nyquist freq
m1[int(len(m1) / 2 + 1):] = m1[1:int(len(m1) / 2)][::-1]
# reconstruct the signal
y1 = m1 * exp(1j * ph)
return real(ifft(y1)) | [
"def",
"_color_noise",
"(",
"x",
",",
"s_freq",
",",
"coef",
"=",
"0",
")",
":",
"# convert to freq domain",
"y",
"=",
"fft",
"(",
"x",
")",
"ph",
"=",
"angle",
"(",
"y",
")",
"m",
"=",
"abs",
"(",
"y",
")",
"# frequencies for each fft value",
"freq",
... | Add some color to the noise by changing the power spectrum.
Parameters
----------
x : ndarray
one vector of the original signal
s_freq : int
sampling frequency
coef : float
coefficient to apply (0 -> white noise, 1 -> pink, 2 -> brown,
-1 -> blue)
Returns
-------
ndarray
one vector of the colored noise. | [
"Add",
"some",
"color",
"to",
"the",
"noise",
"by",
"changing",
"the",
"power",
"spectrum",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/utils/simulate.py#L173-L209 | train | 23,582 |
wonambi-python/wonambi | wonambi/ioeeg/openephys.py | _read_openephys | def _read_openephys(openephys_file):
"""Read the channel labels and their respective files from the
'Continuous_Data.openephys' file
Parameters
----------
openephys_file : Path
path to Continuous_Data.openephys inside the open-ephys folder
Returns
-------
int
sampling frequency
list of dict
list of channels containing the label, the filename and the gain
"""
root = ElementTree.parse(openephys_file).getroot()
channels = []
for recording in root:
s_freq = float(recording.attrib['samplerate'])
for processor in recording:
for channel in processor:
channels.append(channel.attrib)
return s_freq, channels | python | def _read_openephys(openephys_file):
"""Read the channel labels and their respective files from the
'Continuous_Data.openephys' file
Parameters
----------
openephys_file : Path
path to Continuous_Data.openephys inside the open-ephys folder
Returns
-------
int
sampling frequency
list of dict
list of channels containing the label, the filename and the gain
"""
root = ElementTree.parse(openephys_file).getroot()
channels = []
for recording in root:
s_freq = float(recording.attrib['samplerate'])
for processor in recording:
for channel in processor:
channels.append(channel.attrib)
return s_freq, channels | [
"def",
"_read_openephys",
"(",
"openephys_file",
")",
":",
"root",
"=",
"ElementTree",
".",
"parse",
"(",
"openephys_file",
")",
".",
"getroot",
"(",
")",
"channels",
"=",
"[",
"]",
"for",
"recording",
"in",
"root",
":",
"s_freq",
"=",
"float",
"(",
"rec... | Read the channel labels and their respective files from the
'Continuous_Data.openephys' file
Parameters
----------
openephys_file : Path
path to Continuous_Data.openephys inside the open-ephys folder
Returns
-------
int
sampling frequency
list of dict
list of channels containing the label, the filename and the gain | [
"Read",
"the",
"channel",
"labels",
"and",
"their",
"respective",
"files",
"from",
"the",
"Continuous_Data",
".",
"openephys",
"file"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/openephys.py#L166-L191 | train | 23,583 |
wonambi-python/wonambi | wonambi/ioeeg/openephys.py | _read_date | def _read_date(settings_file):
"""Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
-----
The start time is present in the header of each file. This might be useful
if 'settings.xml' is not present.
"""
root = ElementTree.parse(settings_file).getroot()
for e0 in root:
if e0.tag == 'INFO':
for e1 in e0:
if e1.tag == 'DATE':
break
return datetime.strptime(e1.text, '%d %b %Y %H:%M:%S') | python | def _read_date(settings_file):
"""Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
-----
The start time is present in the header of each file. This might be useful
if 'settings.xml' is not present.
"""
root = ElementTree.parse(settings_file).getroot()
for e0 in root:
if e0.tag == 'INFO':
for e1 in e0:
if e1.tag == 'DATE':
break
return datetime.strptime(e1.text, '%d %b %Y %H:%M:%S') | [
"def",
"_read_date",
"(",
"settings_file",
")",
":",
"root",
"=",
"ElementTree",
".",
"parse",
"(",
"settings_file",
")",
".",
"getroot",
"(",
")",
"for",
"e0",
"in",
"root",
":",
"if",
"e0",
".",
"tag",
"==",
"'INFO'",
":",
"for",
"e1",
"in",
"e0",
... | Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
-----
The start time is present in the header of each file. This might be useful
if 'settings.xml' is not present. | [
"Get",
"the",
"data",
"from",
"the",
"settings",
".",
"xml",
"file"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/openephys.py#L194-L219 | train | 23,584 |
wonambi-python/wonambi | wonambi/ioeeg/openephys.py | _read_n_samples | def _read_n_samples(channel_file):
"""Calculate the number of samples based on the file size
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
int
number of blocks (i.e. records, in which the data is cut)
int
number of samples
"""
n_blocks = int((channel_file.stat().st_size - HDR_LENGTH) / BLK_SIZE)
n_samples = n_blocks * BLK_LENGTH
return n_blocks, n_samples | python | def _read_n_samples(channel_file):
"""Calculate the number of samples based on the file size
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
int
number of blocks (i.e. records, in which the data is cut)
int
number of samples
"""
n_blocks = int((channel_file.stat().st_size - HDR_LENGTH) / BLK_SIZE)
n_samples = n_blocks * BLK_LENGTH
return n_blocks, n_samples | [
"def",
"_read_n_samples",
"(",
"channel_file",
")",
":",
"n_blocks",
"=",
"int",
"(",
"(",
"channel_file",
".",
"stat",
"(",
")",
".",
"st_size",
"-",
"HDR_LENGTH",
")",
"/",
"BLK_SIZE",
")",
"n_samples",
"=",
"n_blocks",
"*",
"BLK_LENGTH",
"return",
"n_bl... | Calculate the number of samples based on the file size
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
int
number of blocks (i.e. records, in which the data is cut)
int
number of samples | [
"Calculate",
"the",
"number",
"of",
"samples",
"based",
"on",
"the",
"file",
"size"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/openephys.py#L222-L239 | train | 23,585 |
wonambi-python/wonambi | wonambi/ioeeg/openephys.py | _read_header | def _read_header(filename):
"""Read the text header for each file
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
dict
header
"""
with filename.open('rb') as f:
h = f.read(HDR_LENGTH).decode()
header = {}
for line in h.split('\n'):
if '=' in line:
key, value = line.split(' = ')
key = key.strip()[7:]
value = value.strip()[:-1]
header[key] = value
return header | python | def _read_header(filename):
"""Read the text header for each file
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
dict
header
"""
with filename.open('rb') as f:
h = f.read(HDR_LENGTH).decode()
header = {}
for line in h.split('\n'):
if '=' in line:
key, value = line.split(' = ')
key = key.strip()[7:]
value = value.strip()[:-1]
header[key] = value
return header | [
"def",
"_read_header",
"(",
"filename",
")",
":",
"with",
"filename",
".",
"open",
"(",
"'rb'",
")",
"as",
"f",
":",
"h",
"=",
"f",
".",
"read",
"(",
"HDR_LENGTH",
")",
".",
"decode",
"(",
")",
"header",
"=",
"{",
"}",
"for",
"line",
"in",
"h",
... | Read the text header for each file
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
dict
header | [
"Read",
"the",
"text",
"header",
"for",
"each",
"file"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/openephys.py#L242-L266 | train | 23,586 |
wonambi-python/wonambi | wonambi/ioeeg/openephys.py | _check_header | def _check_header(channel_file, s_freq):
"""For each file, make sure that the header is consistent with the
information in the text file.
Parameters
----------
channel_file : Path
path to single filename with the header
s_freq : int
sampling frequency
Returns
-------
int
gain from digital to microvolts (the same information is stored in
the Continuous_Data.openephys but I trust the header for each file more.
"""
hdr = _read_header(channel_file)
assert int(hdr['header_bytes']) == HDR_LENGTH
assert int(hdr['blockLength']) == BLK_LENGTH
assert int(hdr['sampleRate']) == s_freq
return float(hdr['bitVolts']) | python | def _check_header(channel_file, s_freq):
"""For each file, make sure that the header is consistent with the
information in the text file.
Parameters
----------
channel_file : Path
path to single filename with the header
s_freq : int
sampling frequency
Returns
-------
int
gain from digital to microvolts (the same information is stored in
the Continuous_Data.openephys but I trust the header for each file more.
"""
hdr = _read_header(channel_file)
assert int(hdr['header_bytes']) == HDR_LENGTH
assert int(hdr['blockLength']) == BLK_LENGTH
assert int(hdr['sampleRate']) == s_freq
return float(hdr['bitVolts']) | [
"def",
"_check_header",
"(",
"channel_file",
",",
"s_freq",
")",
":",
"hdr",
"=",
"_read_header",
"(",
"channel_file",
")",
"assert",
"int",
"(",
"hdr",
"[",
"'header_bytes'",
"]",
")",
"==",
"HDR_LENGTH",
"assert",
"int",
"(",
"hdr",
"[",
"'blockLength'",
... | For each file, make sure that the header is consistent with the
information in the text file.
Parameters
----------
channel_file : Path
path to single filename with the header
s_freq : int
sampling frequency
Returns
-------
int
gain from digital to microvolts (the same information is stored in
the Continuous_Data.openephys but I trust the header for each file more. | [
"For",
"each",
"file",
"make",
"sure",
"that",
"the",
"header",
"is",
"consistent",
"with",
"the",
"information",
"in",
"the",
"text",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/openephys.py#L269-L292 | train | 23,587 |
wonambi-python/wonambi | wonambi/detect/agreement.py | MatchedEvents.all_to_annot | def all_to_annot(self, annot, names=['TPd', 'TPs', 'FP', 'FN']):
"""Convenience function to write all events to XML by category, showing
overlapping TP detection and TP standard."""
self.to_annot(annot, 'tp_det', names[0])
self.to_annot(annot, 'tp_std', names[1])
self.to_annot(annot, 'fp', names[2])
self.to_annot(annot, 'fn', names[3]) | python | def all_to_annot(self, annot, names=['TPd', 'TPs', 'FP', 'FN']):
"""Convenience function to write all events to XML by category, showing
overlapping TP detection and TP standard."""
self.to_annot(annot, 'tp_det', names[0])
self.to_annot(annot, 'tp_std', names[1])
self.to_annot(annot, 'fp', names[2])
self.to_annot(annot, 'fn', names[3]) | [
"def",
"all_to_annot",
"(",
"self",
",",
"annot",
",",
"names",
"=",
"[",
"'TPd'",
",",
"'TPs'",
",",
"'FP'",
",",
"'FN'",
"]",
")",
":",
"self",
".",
"to_annot",
"(",
"annot",
",",
"'tp_det'",
",",
"names",
"[",
"0",
"]",
")",
"self",
".",
"to_a... | Convenience function to write all events to XML by category, showing
overlapping TP detection and TP standard. | [
"Convenience",
"function",
"to",
"write",
"all",
"events",
"to",
"XML",
"by",
"category",
"showing",
"overlapping",
"TP",
"detection",
"and",
"TP",
"standard",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/agreement.py#L102-L108 | train | 23,588 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | convert_sample_to_video_time | def convert_sample_to_video_time(sample, orig_s_freq, sampleStamp,
sampleTime):
"""Convert sample number to video time, using snc information.
Parameters
----------
sample : int
sample that you want to convert in time
orig_s_freq : int
sampling frequency (used as backup)
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Returns
-------
instance of datetime
absolute time of the sample.
Notes
-----
Note that there is a discrepancy of 4 or 5 hours between the time in
snc and the time in the header. I'm pretty sure that the time in the
header is accurate, so we use that. I think that the time in snc does
not take into account the time zone (that'd explain the 4 or 5
depending on summertime). This time is only used to get the right video
so we call this "video time".
"""
if sample < sampleStamp[0]:
s_freq = orig_s_freq
id0 = 0
elif sample > sampleStamp[-1]:
s_freq = orig_s_freq
id0 = len(sampleStamp) - 1
else:
id0 = where(asarray(sampleStamp) <= sample)[0][-1]
id1 = where(asarray(sampleStamp) >= sample)[0][0]
if id0 == id1:
return sampleTime[id0]
s_freq = ((sampleStamp[id1] - sampleStamp[id0]) /
(sampleTime[id1] - sampleTime[id0]).total_seconds())
time_diff = timedelta(seconds=(sample - sampleStamp[id0]) / s_freq)
return sampleTime[id0] + time_diff | python | def convert_sample_to_video_time(sample, orig_s_freq, sampleStamp,
sampleTime):
"""Convert sample number to video time, using snc information.
Parameters
----------
sample : int
sample that you want to convert in time
orig_s_freq : int
sampling frequency (used as backup)
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Returns
-------
instance of datetime
absolute time of the sample.
Notes
-----
Note that there is a discrepancy of 4 or 5 hours between the time in
snc and the time in the header. I'm pretty sure that the time in the
header is accurate, so we use that. I think that the time in snc does
not take into account the time zone (that'd explain the 4 or 5
depending on summertime). This time is only used to get the right video
so we call this "video time".
"""
if sample < sampleStamp[0]:
s_freq = orig_s_freq
id0 = 0
elif sample > sampleStamp[-1]:
s_freq = orig_s_freq
id0 = len(sampleStamp) - 1
else:
id0 = where(asarray(sampleStamp) <= sample)[0][-1]
id1 = where(asarray(sampleStamp) >= sample)[0][0]
if id0 == id1:
return sampleTime[id0]
s_freq = ((sampleStamp[id1] - sampleStamp[id0]) /
(sampleTime[id1] - sampleTime[id0]).total_seconds())
time_diff = timedelta(seconds=(sample - sampleStamp[id0]) / s_freq)
return sampleTime[id0] + time_diff | [
"def",
"convert_sample_to_video_time",
"(",
"sample",
",",
"orig_s_freq",
",",
"sampleStamp",
",",
"sampleTime",
")",
":",
"if",
"sample",
"<",
"sampleStamp",
"[",
"0",
"]",
":",
"s_freq",
"=",
"orig_s_freq",
"id0",
"=",
"0",
"elif",
"sample",
">",
"sampleSt... | Convert sample number to video time, using snc information.
Parameters
----------
sample : int
sample that you want to convert in time
orig_s_freq : int
sampling frequency (used as backup)
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Returns
-------
instance of datetime
absolute time of the sample.
Notes
-----
Note that there is a discrepancy of 4 or 5 hours between the time in
snc and the time in the header. I'm pretty sure that the time in the
header is accurate, so we use that. I think that the time in snc does
not take into account the time zone (that'd explain the 4 or 5
depending on summertime). This time is only used to get the right video
so we call this "video time". | [
"Convert",
"sample",
"number",
"to",
"video",
"time",
"using",
"snc",
"information",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L62-L106 | train | 23,589 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _find_channels | def _find_channels(note):
"""Find the channel names within a string.
The channel names are stored in the .ent file. We can read the file with
_read_ent and we can parse most of the notes (comments) with _read_notes
however the note containing the montage cannot be read because it's too
complex. So, instead of parsing it, we just pass the string of the note
around. This function takes the string and finds where the channel
definition is.
Parameters
----------
note : str
string read from .ent file, it's the note which contains montage.
Returns
-------
chan_name : list of str
the names of the channels.
"""
id_ch = note.index('ChanNames')
chan_beg = note.index('(', id_ch)
chan_end = note.index(')', chan_beg)
note_with_chan = note[chan_beg + 1:chan_end]
return [x.strip('" ') for x in note_with_chan.split(',')] | python | def _find_channels(note):
"""Find the channel names within a string.
The channel names are stored in the .ent file. We can read the file with
_read_ent and we can parse most of the notes (comments) with _read_notes
however the note containing the montage cannot be read because it's too
complex. So, instead of parsing it, we just pass the string of the note
around. This function takes the string and finds where the channel
definition is.
Parameters
----------
note : str
string read from .ent file, it's the note which contains montage.
Returns
-------
chan_name : list of str
the names of the channels.
"""
id_ch = note.index('ChanNames')
chan_beg = note.index('(', id_ch)
chan_end = note.index(')', chan_beg)
note_with_chan = note[chan_beg + 1:chan_end]
return [x.strip('" ') for x in note_with_chan.split(',')] | [
"def",
"_find_channels",
"(",
"note",
")",
":",
"id_ch",
"=",
"note",
".",
"index",
"(",
"'ChanNames'",
")",
"chan_beg",
"=",
"note",
".",
"index",
"(",
"'('",
",",
"id_ch",
")",
"chan_end",
"=",
"note",
".",
"index",
"(",
"')'",
",",
"chan_beg",
")"... | Find the channel names within a string.
The channel names are stored in the .ent file. We can read the file with
_read_ent and we can parse most of the notes (comments) with _read_notes
however the note containing the montage cannot be read because it's too
complex. So, instead of parsing it, we just pass the string of the note
around. This function takes the string and finds where the channel
definition is.
Parameters
----------
note : str
string read from .ent file, it's the note which contains montage.
Returns
-------
chan_name : list of str
the names of the channels. | [
"Find",
"the",
"channel",
"names",
"within",
"a",
"string",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L253-L278 | train | 23,590 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _find_start_time | def _find_start_time(hdr, s_freq):
"""Find the start time, usually in STC, but if that's not correct, use ERD
Parameters
----------
hdr : dict
header with stc (and stamps) and erd
s_freq : int
sampling frequency
Returns
-------
datetime
either from stc or from erd
Notes
-----
Sometimes, but rather rarely, there is a mismatch between the time in the
stc and the time in the erd. For some reason, the time in the stc is way
off (by hours), which is clearly not correct.
We can try to reconstruct the actual time, but looking at the ERD time
(of any file apart from the first one) and compute the original time back
based on the offset of the number of samples in stc. For some reason, this
is not the same for all the ERD, but the jitter is in the order of 1-2s
which is acceptable for our purposes (probably, but be careful about the
notes).
"""
start_time = hdr['stc']['creation_time']
for one_stamp in hdr['stamps']:
if one_stamp['segment_name'].decode() == hdr['erd']['filename']:
offset = one_stamp['start_stamp']
break
erd_time = (hdr['erd']['creation_time'] -
timedelta(seconds=offset / s_freq)).replace(microsecond=0)
stc_erd_diff = (start_time - erd_time).total_seconds()
if stc_erd_diff > START_TIME_TOL:
lg.warn('Time difference between ERD and STC is {} s so using ERD time'
' at {}'.format(stc_erd_diff, erd_time))
start_time = erd_time
return start_time | python | def _find_start_time(hdr, s_freq):
"""Find the start time, usually in STC, but if that's not correct, use ERD
Parameters
----------
hdr : dict
header with stc (and stamps) and erd
s_freq : int
sampling frequency
Returns
-------
datetime
either from stc or from erd
Notes
-----
Sometimes, but rather rarely, there is a mismatch between the time in the
stc and the time in the erd. For some reason, the time in the stc is way
off (by hours), which is clearly not correct.
We can try to reconstruct the actual time, but looking at the ERD time
(of any file apart from the first one) and compute the original time back
based on the offset of the number of samples in stc. For some reason, this
is not the same for all the ERD, but the jitter is in the order of 1-2s
which is acceptable for our purposes (probably, but be careful about the
notes).
"""
start_time = hdr['stc']['creation_time']
for one_stamp in hdr['stamps']:
if one_stamp['segment_name'].decode() == hdr['erd']['filename']:
offset = one_stamp['start_stamp']
break
erd_time = (hdr['erd']['creation_time'] -
timedelta(seconds=offset / s_freq)).replace(microsecond=0)
stc_erd_diff = (start_time - erd_time).total_seconds()
if stc_erd_diff > START_TIME_TOL:
lg.warn('Time difference between ERD and STC is {} s so using ERD time'
' at {}'.format(stc_erd_diff, erd_time))
start_time = erd_time
return start_time | [
"def",
"_find_start_time",
"(",
"hdr",
",",
"s_freq",
")",
":",
"start_time",
"=",
"hdr",
"[",
"'stc'",
"]",
"[",
"'creation_time'",
"]",
"for",
"one_stamp",
"in",
"hdr",
"[",
"'stamps'",
"]",
":",
"if",
"one_stamp",
"[",
"'segment_name'",
"]",
".",
"dec... | Find the start time, usually in STC, but if that's not correct, use ERD
Parameters
----------
hdr : dict
header with stc (and stamps) and erd
s_freq : int
sampling frequency
Returns
-------
datetime
either from stc or from erd
Notes
-----
Sometimes, but rather rarely, there is a mismatch between the time in the
stc and the time in the erd. For some reason, the time in the stc is way
off (by hours), which is clearly not correct.
We can try to reconstruct the actual time, but looking at the ERD time
(of any file apart from the first one) and compute the original time back
based on the offset of the number of samples in stc. For some reason, this
is not the same for all the ERD, but the jitter is in the order of 1-2s
which is acceptable for our purposes (probably, but be careful about the
notes). | [
"Find",
"the",
"start",
"time",
"usually",
"in",
"STC",
"but",
"if",
"that",
"s",
"not",
"correct",
"use",
"ERD"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L281-L325 | train | 23,591 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_ent | def _read_ent(ent_file):
"""Read notes stored in .ent file.
This is a basic implementation, that relies on turning the information in
the string in the dict format, and then evaluate it. It's not very flexible
and it might not read some notes, but it's fast. I could not implement a
nice, recursive approach.
Returns
-------
allnote : a list of dict
where each dict contains keys such as:
- type
- length : length of the note in B,
- prev_length : length of the previous note in B,
- unused,
- value : the actual content of the note.
Notes
-----
The notes are stored in a format called 'Excel list' but could not find
more information. It's based on "(" and "(.", and I found it very hard to
parse. With some basic regex and substitution, it can be evaluated into
a dict, with sub dictionaries. However, the note containing the name of the
electrodes (I think they called it "montage") cannot be parsed, because
it's too complicated. If it cannot be converted into a dict, the whole
string is passed as value.
"""
with ent_file.open('rb') as f:
f.seek(352) # end of header
note_hdr_length = 16
allnote = []
while True:
note = {}
note['type'], = unpack('<i', f.read(4))
note['length'], = unpack('<i', f.read(4))
note['prev_length'], = unpack('<i', f.read(4))
note['unused'], = unpack('<i', f.read(4))
if not note['type']:
break
s = f.read(note['length'] - note_hdr_length)
s = s[:-2] # it ends with one empty byte
s = s.decode('utf-8', errors='replace')
s1 = s.replace('\n', ' ')
s1 = s1.replace('\\xd ', '')
s1 = s1.replace('(.', '{')
s1 = sub(r'\(([A-Za-z0-9," ]*)\)', r'[\1]', s1)
s1 = s1.replace(')', '}')
# s1 = s1.replace('",', '" :')
s1 = sub(r'(\{[\w"]*),', r'\1 :', s1)
s1 = s1.replace('{"', '"')
s1 = s1.replace('},', ',')
s1 = s1.replace('}}', '}')
s1 = sub(r'\(([0-9 ,-\.]*)\}', r'[\1]', s1)
try:
note['value'] = eval(s1)
except:
note['value'] = s
allnote.append(note)
return allnote | python | def _read_ent(ent_file):
"""Read notes stored in .ent file.
This is a basic implementation, that relies on turning the information in
the string in the dict format, and then evaluate it. It's not very flexible
and it might not read some notes, but it's fast. I could not implement a
nice, recursive approach.
Returns
-------
allnote : a list of dict
where each dict contains keys such as:
- type
- length : length of the note in B,
- prev_length : length of the previous note in B,
- unused,
- value : the actual content of the note.
Notes
-----
The notes are stored in a format called 'Excel list' but could not find
more information. It's based on "(" and "(.", and I found it very hard to
parse. With some basic regex and substitution, it can be evaluated into
a dict, with sub dictionaries. However, the note containing the name of the
electrodes (I think they called it "montage") cannot be parsed, because
it's too complicated. If it cannot be converted into a dict, the whole
string is passed as value.
"""
with ent_file.open('rb') as f:
f.seek(352) # end of header
note_hdr_length = 16
allnote = []
while True:
note = {}
note['type'], = unpack('<i', f.read(4))
note['length'], = unpack('<i', f.read(4))
note['prev_length'], = unpack('<i', f.read(4))
note['unused'], = unpack('<i', f.read(4))
if not note['type']:
break
s = f.read(note['length'] - note_hdr_length)
s = s[:-2] # it ends with one empty byte
s = s.decode('utf-8', errors='replace')
s1 = s.replace('\n', ' ')
s1 = s1.replace('\\xd ', '')
s1 = s1.replace('(.', '{')
s1 = sub(r'\(([A-Za-z0-9," ]*)\)', r'[\1]', s1)
s1 = s1.replace(')', '}')
# s1 = s1.replace('",', '" :')
s1 = sub(r'(\{[\w"]*),', r'\1 :', s1)
s1 = s1.replace('{"', '"')
s1 = s1.replace('},', ',')
s1 = s1.replace('}}', '}')
s1 = sub(r'\(([0-9 ,-\.]*)\}', r'[\1]', s1)
try:
note['value'] = eval(s1)
except:
note['value'] = s
allnote.append(note)
return allnote | [
"def",
"_read_ent",
"(",
"ent_file",
")",
":",
"with",
"ent_file",
".",
"open",
"(",
"'rb'",
")",
"as",
"f",
":",
"f",
".",
"seek",
"(",
"352",
")",
"# end of header",
"note_hdr_length",
"=",
"16",
"allnote",
"=",
"[",
"]",
"while",
"True",
":",
"not... | Read notes stored in .ent file.
This is a basic implementation, that relies on turning the information in
the string in the dict format, and then evaluate it. It's not very flexible
and it might not read some notes, but it's fast. I could not implement a
nice, recursive approach.
Returns
-------
allnote : a list of dict
where each dict contains keys such as:
- type
- length : length of the note in B,
- prev_length : length of the previous note in B,
- unused,
- value : the actual content of the note.
Notes
-----
The notes are stored in a format called 'Excel list' but could not find
more information. It's based on "(" and "(.", and I found it very hard to
parse. With some basic regex and substitution, it can be evaluated into
a dict, with sub dictionaries. However, the note containing the name of the
electrodes (I think they called it "montage") cannot be parsed, because
it's too complicated. If it cannot be converted into a dict, the whole
string is passed as value. | [
"Read",
"notes",
"stored",
"in",
".",
"ent",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L353-L414 | train | 23,592 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_packet | def _read_packet(f, pos, n_smp, n_allchan, abs_delta):
"""
Read a packet of compressed data
Parameters
----------
f : instance of opened file
erd file
pos : int
index of the start of the packet in the file (in bytes from beginning
of the file)
n_smp : int
number of samples to read
n_allchan : int
number of channels (we should specify if shorted or not)
abs_delta: byte
if the delta has this value, it means that you should read the absolute
value at the end of packet. If schema is 7, the length is 1; if schema
is 8 or 9, the length is 2.
Returns
-------
ndarray
data read in the packet up to n_smp.
Notes
-----
TODO: shorted chan. If I remember correctly, deltamask includes all the
channels, but the absolute values are only used for not-shorted channels
TODO: implement schema 7, which is slightly different, but I don't remember
where exactly.
"""
if len(abs_delta) == 1: # schema 7
abs_delta = unpack('b', abs_delta)[0]
else: # schema 8, 9
abs_delta = unpack('h', abs_delta)[0]
l_deltamask = int(ceil(n_allchan / BITS_IN_BYTE))
dat = empty((n_allchan, n_smp), dtype=int32)
f.seek(pos)
for i_smp in range(n_smp):
eventbite = f.read(1)
try:
assert eventbite in (b'\x00', b'\x01')
except:
raise Exception('at pos ' + str(i_smp) +
', eventbite (should be x00 or x01): ' +
str(eventbite))
byte_deltamask = unpack('<' + 'B' * l_deltamask, f.read(l_deltamask))
deltamask = unpackbits(array(byte_deltamask[::-1], dtype ='uint8'))
deltamask = deltamask[:-n_allchan-1:-1]
n_bytes = int(deltamask.sum()) + deltamask.shape[0]
deltamask = deltamask.astype('bool')
# numpy has a weird way of handling string/bytes.
# We create a byte representation, because then tostring() works fine
delta_dtype = empty(n_allchan, dtype='a1')
delta_dtype[deltamask] = 'h'
delta_dtype[~deltamask] = 'b'
relval = array(unpack('<' + delta_dtype.tostring().decode(),
f.read(n_bytes)))
read_abs = (delta_dtype == b'h') & (relval == abs_delta)
dat[~read_abs, i_smp] = dat[~read_abs, i_smp - 1] + relval[~read_abs]
dat[read_abs, i_smp] = fromfile(f, 'i', count=read_abs.sum())
return dat | python | def _read_packet(f, pos, n_smp, n_allchan, abs_delta):
"""
Read a packet of compressed data
Parameters
----------
f : instance of opened file
erd file
pos : int
index of the start of the packet in the file (in bytes from beginning
of the file)
n_smp : int
number of samples to read
n_allchan : int
number of channels (we should specify if shorted or not)
abs_delta: byte
if the delta has this value, it means that you should read the absolute
value at the end of packet. If schema is 7, the length is 1; if schema
is 8 or 9, the length is 2.
Returns
-------
ndarray
data read in the packet up to n_smp.
Notes
-----
TODO: shorted chan. If I remember correctly, deltamask includes all the
channels, but the absolute values are only used for not-shorted channels
TODO: implement schema 7, which is slightly different, but I don't remember
where exactly.
"""
if len(abs_delta) == 1: # schema 7
abs_delta = unpack('b', abs_delta)[0]
else: # schema 8, 9
abs_delta = unpack('h', abs_delta)[0]
l_deltamask = int(ceil(n_allchan / BITS_IN_BYTE))
dat = empty((n_allchan, n_smp), dtype=int32)
f.seek(pos)
for i_smp in range(n_smp):
eventbite = f.read(1)
try:
assert eventbite in (b'\x00', b'\x01')
except:
raise Exception('at pos ' + str(i_smp) +
', eventbite (should be x00 or x01): ' +
str(eventbite))
byte_deltamask = unpack('<' + 'B' * l_deltamask, f.read(l_deltamask))
deltamask = unpackbits(array(byte_deltamask[::-1], dtype ='uint8'))
deltamask = deltamask[:-n_allchan-1:-1]
n_bytes = int(deltamask.sum()) + deltamask.shape[0]
deltamask = deltamask.astype('bool')
# numpy has a weird way of handling string/bytes.
# We create a byte representation, because then tostring() works fine
delta_dtype = empty(n_allchan, dtype='a1')
delta_dtype[deltamask] = 'h'
delta_dtype[~deltamask] = 'b'
relval = array(unpack('<' + delta_dtype.tostring().decode(),
f.read(n_bytes)))
read_abs = (delta_dtype == b'h') & (relval == abs_delta)
dat[~read_abs, i_smp] = dat[~read_abs, i_smp - 1] + relval[~read_abs]
dat[read_abs, i_smp] = fromfile(f, 'i', count=read_abs.sum())
return dat | [
"def",
"_read_packet",
"(",
"f",
",",
"pos",
",",
"n_smp",
",",
"n_allchan",
",",
"abs_delta",
")",
":",
"if",
"len",
"(",
"abs_delta",
")",
"==",
"1",
":",
"# schema 7",
"abs_delta",
"=",
"unpack",
"(",
"'b'",
",",
"abs_delta",
")",
"[",
"0",
"]",
... | Read a packet of compressed data
Parameters
----------
f : instance of opened file
erd file
pos : int
index of the start of the packet in the file (in bytes from beginning
of the file)
n_smp : int
number of samples to read
n_allchan : int
number of channels (we should specify if shorted or not)
abs_delta: byte
if the delta has this value, it means that you should read the absolute
value at the end of packet. If schema is 7, the length is 1; if schema
is 8 or 9, the length is 2.
Returns
-------
ndarray
data read in the packet up to n_smp.
Notes
-----
TODO: shorted chan. If I remember correctly, deltamask includes all the
channels, but the absolute values are only used for not-shorted channels
TODO: implement schema 7, which is slightly different, but I don't remember
where exactly. | [
"Read",
"a",
"packet",
"of",
"compressed",
"data"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L417-L489 | train | 23,593 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_erd | def _read_erd(erd_file, begsam, endsam):
"""Read the raw data and return a matrix, converted to microvolts.
Parameters
----------
erd_file : str
one of the .erd files to read
begsam : int
index of the first sample to read
endsam : int
index of the last sample (excluded, per python convention)
Returns
-------
numpy.ndarray
2d matrix with the data, as read from the file
Error
-----
It checks whether the event byte (the first byte) is x00 as expected.
It can also be x01, meaning that an event was generated by an external
trigger. According to the manual, "a photic stimulator is the only
supported device which generates an external trigger."
If the eventbyte is something else, it throws an error.
Notes
-----
Each sample point consists of these parts:
- Event Byte
- Frequency byte (only if file_schema >= 8 and one chan has != freq)
- Delta mask (only if file_schema >= 8)
- Delta Information
- Absolute Channel Values
Event Byte:
Bit 0 of the event byte indicates the presence of the external trigger
during the sample period. It's very rare.
Delta Mask:
Bit-mask of a size int( number_of_channels / 8 + 0.5). Each 1 in the mask
indicates that corresponding channel has 2*n bit delta, 0 means that
corresponding channel has n bit delta.
The rest of the byte of the delta mask is filled with "1".
If file_schema <= 7, it generates a "fake" delta, where everything is 0.
Some channels are shorted (i.e. not recorded), however they are stored in
a non-intuitive way: deltamask takes them into account, but for the rest
they are never used/recorded. So, we need to keep track both of all the
channels (including the non-shorted) and of the actual channels only.
When we save the data as memory-mapped, we only save the real channels.
However, the data in the output have both shorted and non-shorted channels.
Shorted channels have NaN's only.
About the actual implementation, we always follow the python convention
that the first sample is included and the last sample is not.
"""
hdr = _read_hdr_file(erd_file)
n_allchan = hdr['num_channels']
shorted = hdr['shorted'] # does this exist for Schema 7 at all?
n_shorted = sum(shorted)
if n_shorted > 0:
raise NotImplementedError('shorted channels not tested yet')
if hdr['file_schema'] in (7,):
abs_delta = b'\x80' # one byte: 10000000
raise NotImplementedError('schema 7 not tested yet')
if hdr['file_schema'] in (8, 9):
abs_delta = b'\xff\xff'
n_smp = endsam - begsam
data = empty((n_allchan, n_smp))
data.fill(NaN)
# it includes the sample in both cases
etc = _read_etc(erd_file.with_suffix('.etc'))
all_beg = etc['samplestamp']
all_end = etc['samplestamp'] + etc['sample_span'] - 1
try:
begrec = where((all_end >= begsam))[0][0]
endrec = where((all_beg < endsam))[0][-1]
except IndexError:
return data
with erd_file.open('rb') as f:
for rec in range(begrec, endrec + 1):
# [begpos_rec, endpos_rec]
begpos_rec = begsam - all_beg[rec]
endpos_rec = endsam - all_beg[rec]
begpos_rec = max(begpos_rec, 0)
endpos_rec = min(endpos_rec, all_end[rec] - all_beg[rec] + 1)
# [d1, d2)
d1 = begpos_rec + all_beg[rec] - begsam
d2 = endpos_rec + all_beg[rec] - begsam
dat = _read_packet(f, etc['offset'][rec], endpos_rec, n_allchan,
abs_delta)
data[:, d1:d2] = dat[:, begpos_rec:endpos_rec]
# fill up the output data, put NaN for shorted channels
if n_shorted > 0:
full_channels = where(asarray([x == 0 for x in shorted]))[0]
output = empty((n_allchan, n_smp))
output.fill(NaN)
output[full_channels, :] = data
else:
output = data
factor = _calculate_conversion(hdr)
return expand_dims(factor, 1) * output | python | def _read_erd(erd_file, begsam, endsam):
"""Read the raw data and return a matrix, converted to microvolts.
Parameters
----------
erd_file : str
one of the .erd files to read
begsam : int
index of the first sample to read
endsam : int
index of the last sample (excluded, per python convention)
Returns
-------
numpy.ndarray
2d matrix with the data, as read from the file
Error
-----
It checks whether the event byte (the first byte) is x00 as expected.
It can also be x01, meaning that an event was generated by an external
trigger. According to the manual, "a photic stimulator is the only
supported device which generates an external trigger."
If the eventbyte is something else, it throws an error.
Notes
-----
Each sample point consists of these parts:
- Event Byte
- Frequency byte (only if file_schema >= 8 and one chan has != freq)
- Delta mask (only if file_schema >= 8)
- Delta Information
- Absolute Channel Values
Event Byte:
Bit 0 of the event byte indicates the presence of the external trigger
during the sample period. It's very rare.
Delta Mask:
Bit-mask of a size int( number_of_channels / 8 + 0.5). Each 1 in the mask
indicates that corresponding channel has 2*n bit delta, 0 means that
corresponding channel has n bit delta.
The rest of the byte of the delta mask is filled with "1".
If file_schema <= 7, it generates a "fake" delta, where everything is 0.
Some channels are shorted (i.e. not recorded), however they are stored in
a non-intuitive way: deltamask takes them into account, but for the rest
they are never used/recorded. So, we need to keep track both of all the
channels (including the non-shorted) and of the actual channels only.
When we save the data as memory-mapped, we only save the real channels.
However, the data in the output have both shorted and non-shorted channels.
Shorted channels have NaN's only.
About the actual implementation, we always follow the python convention
that the first sample is included and the last sample is not.
"""
hdr = _read_hdr_file(erd_file)
n_allchan = hdr['num_channels']
shorted = hdr['shorted'] # does this exist for Schema 7 at all?
n_shorted = sum(shorted)
if n_shorted > 0:
raise NotImplementedError('shorted channels not tested yet')
if hdr['file_schema'] in (7,):
abs_delta = b'\x80' # one byte: 10000000
raise NotImplementedError('schema 7 not tested yet')
if hdr['file_schema'] in (8, 9):
abs_delta = b'\xff\xff'
n_smp = endsam - begsam
data = empty((n_allchan, n_smp))
data.fill(NaN)
# it includes the sample in both cases
etc = _read_etc(erd_file.with_suffix('.etc'))
all_beg = etc['samplestamp']
all_end = etc['samplestamp'] + etc['sample_span'] - 1
try:
begrec = where((all_end >= begsam))[0][0]
endrec = where((all_beg < endsam))[0][-1]
except IndexError:
return data
with erd_file.open('rb') as f:
for rec in range(begrec, endrec + 1):
# [begpos_rec, endpos_rec]
begpos_rec = begsam - all_beg[rec]
endpos_rec = endsam - all_beg[rec]
begpos_rec = max(begpos_rec, 0)
endpos_rec = min(endpos_rec, all_end[rec] - all_beg[rec] + 1)
# [d1, d2)
d1 = begpos_rec + all_beg[rec] - begsam
d2 = endpos_rec + all_beg[rec] - begsam
dat = _read_packet(f, etc['offset'][rec], endpos_rec, n_allchan,
abs_delta)
data[:, d1:d2] = dat[:, begpos_rec:endpos_rec]
# fill up the output data, put NaN for shorted channels
if n_shorted > 0:
full_channels = where(asarray([x == 0 for x in shorted]))[0]
output = empty((n_allchan, n_smp))
output.fill(NaN)
output[full_channels, :] = data
else:
output = data
factor = _calculate_conversion(hdr)
return expand_dims(factor, 1) * output | [
"def",
"_read_erd",
"(",
"erd_file",
",",
"begsam",
",",
"endsam",
")",
":",
"hdr",
"=",
"_read_hdr_file",
"(",
"erd_file",
")",
"n_allchan",
"=",
"hdr",
"[",
"'num_channels'",
"]",
"shorted",
"=",
"hdr",
"[",
"'shorted'",
"]",
"# does this exist for Schema 7 ... | Read the raw data and return a matrix, converted to microvolts.
Parameters
----------
erd_file : str
one of the .erd files to read
begsam : int
index of the first sample to read
endsam : int
index of the last sample (excluded, per python convention)
Returns
-------
numpy.ndarray
2d matrix with the data, as read from the file
Error
-----
It checks whether the event byte (the first byte) is x00 as expected.
It can also be x01, meaning that an event was generated by an external
trigger. According to the manual, "a photic stimulator is the only
supported device which generates an external trigger."
If the eventbyte is something else, it throws an error.
Notes
-----
Each sample point consists of these parts:
- Event Byte
- Frequency byte (only if file_schema >= 8 and one chan has != freq)
- Delta mask (only if file_schema >= 8)
- Delta Information
- Absolute Channel Values
Event Byte:
Bit 0 of the event byte indicates the presence of the external trigger
during the sample period. It's very rare.
Delta Mask:
Bit-mask of a size int( number_of_channels / 8 + 0.5). Each 1 in the mask
indicates that corresponding channel has 2*n bit delta, 0 means that
corresponding channel has n bit delta.
The rest of the byte of the delta mask is filled with "1".
If file_schema <= 7, it generates a "fake" delta, where everything is 0.
Some channels are shorted (i.e. not recorded), however they are stored in
a non-intuitive way: deltamask takes them into account, but for the rest
they are never used/recorded. So, we need to keep track both of all the
channels (including the non-shorted) and of the actual channels only.
When we save the data as memory-mapped, we only save the real channels.
However, the data in the output have both shorted and non-shorted channels.
Shorted channels have NaN's only.
About the actual implementation, we always follow the python convention
that the first sample is included and the last sample is not. | [
"Read",
"the",
"raw",
"data",
"and",
"return",
"a",
"matrix",
"converted",
"to",
"microvolts",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L492-L607 | train | 23,594 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_etc | def _read_etc(etc_file):
"""Return information about table of content for each erd.
"""
etc_type = dtype([('offset', '<i'),
('samplestamp', '<i'),
('sample_num', '<i'),
('sample_span', '<h'),
('unknown', '<h')])
with etc_file.open('rb') as f:
f.seek(352) # end of header
etc = fromfile(f, dtype=etc_type)
return etc | python | def _read_etc(etc_file):
"""Return information about table of content for each erd.
"""
etc_type = dtype([('offset', '<i'),
('samplestamp', '<i'),
('sample_num', '<i'),
('sample_span', '<h'),
('unknown', '<h')])
with etc_file.open('rb') as f:
f.seek(352) # end of header
etc = fromfile(f, dtype=etc_type)
return etc | [
"def",
"_read_etc",
"(",
"etc_file",
")",
":",
"etc_type",
"=",
"dtype",
"(",
"[",
"(",
"'offset'",
",",
"'<i'",
")",
",",
"(",
"'samplestamp'",
",",
"'<i'",
")",
",",
"(",
"'sample_num'",
",",
"'<i'",
")",
",",
"(",
"'sample_span'",
",",
"'<h'",
")"... | Return information about table of content for each erd. | [
"Return",
"information",
"about",
"table",
"of",
"content",
"for",
"each",
"erd",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L610-L623 | train | 23,595 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_snc | def _read_snc(snc_file):
"""Read Synchronization File and return sample stamp and time
Returns
-------
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Notes
-----
The synchronization file is used to calculate a FILETIME given a sample
stamp (and vise-versa). Theoretically, it is possible to calculate a sample
stamp's FILETIME given the FILETIME of sample stamp zero (when sampling
started) and the sample rate. However, because the sample rate cannot be
represented with full precision the accuracy of the FILETIME calculation is
affected.
To compensate for the lack of accuracy, the synchronization file maintains
a sample stamp-to-computer time (called, MasterTime) mapping. Interpolation
is then used to calculate a FILETIME given a sample stamp (and vise-versa).
The attributes, sampleStamp and sampleTime, are used to predict (using
interpolation) the FILETIME based upon a given sample stamp (and
vise-versa). Currently, the only use for this conversion process is to
enable correlation of EEG (sample_stamp) data with other sources of data
such as Video (which works in FILETIME).
"""
snc_raw_dtype = dtype([('sampleStamp', '<i'),
('sampleTime', '<q')])
with snc_file.open('rb') as f:
f.seek(352) # end of header
snc_raw = fromfile(f, dtype=snc_raw_dtype)
sampleStamp = snc_raw['sampleStamp']
sampleTime = asarray([_filetime_to_dt(x) for x in snc_raw['sampleTime']])
return sampleStamp, sampleTime | python | def _read_snc(snc_file):
"""Read Synchronization File and return sample stamp and time
Returns
-------
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Notes
-----
The synchronization file is used to calculate a FILETIME given a sample
stamp (and vise-versa). Theoretically, it is possible to calculate a sample
stamp's FILETIME given the FILETIME of sample stamp zero (when sampling
started) and the sample rate. However, because the sample rate cannot be
represented with full precision the accuracy of the FILETIME calculation is
affected.
To compensate for the lack of accuracy, the synchronization file maintains
a sample stamp-to-computer time (called, MasterTime) mapping. Interpolation
is then used to calculate a FILETIME given a sample stamp (and vise-versa).
The attributes, sampleStamp and sampleTime, are used to predict (using
interpolation) the FILETIME based upon a given sample stamp (and
vise-versa). Currently, the only use for this conversion process is to
enable correlation of EEG (sample_stamp) data with other sources of data
such as Video (which works in FILETIME).
"""
snc_raw_dtype = dtype([('sampleStamp', '<i'),
('sampleTime', '<q')])
with snc_file.open('rb') as f:
f.seek(352) # end of header
snc_raw = fromfile(f, dtype=snc_raw_dtype)
sampleStamp = snc_raw['sampleStamp']
sampleTime = asarray([_filetime_to_dt(x) for x in snc_raw['sampleTime']])
return sampleStamp, sampleTime | [
"def",
"_read_snc",
"(",
"snc_file",
")",
":",
"snc_raw_dtype",
"=",
"dtype",
"(",
"[",
"(",
"'sampleStamp'",
",",
"'<i'",
")",
",",
"(",
"'sampleTime'",
",",
"'<q'",
")",
"]",
")",
"with",
"snc_file",
".",
"open",
"(",
"'rb'",
")",
"as",
"f",
":",
... | Read Synchronization File and return sample stamp and time
Returns
-------
sampleStamp : list of int
Sample number from start of study
sampleTime : list of datetime.datetime
File time representation of sampleStamp
Notes
-----
The synchronization file is used to calculate a FILETIME given a sample
stamp (and vise-versa). Theoretically, it is possible to calculate a sample
stamp's FILETIME given the FILETIME of sample stamp zero (when sampling
started) and the sample rate. However, because the sample rate cannot be
represented with full precision the accuracy of the FILETIME calculation is
affected.
To compensate for the lack of accuracy, the synchronization file maintains
a sample stamp-to-computer time (called, MasterTime) mapping. Interpolation
is then used to calculate a FILETIME given a sample stamp (and vise-versa).
The attributes, sampleStamp and sampleTime, are used to predict (using
interpolation) the FILETIME based upon a given sample stamp (and
vise-versa). Currently, the only use for this conversion process is to
enable correlation of EEG (sample_stamp) data with other sources of data
such as Video (which works in FILETIME). | [
"Read",
"Synchronization",
"File",
"and",
"return",
"sample",
"stamp",
"and",
"time"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L626-L665 | train | 23,596 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_stc | def _read_stc(stc_file):
"""Read Segment Table of Contents file.
Returns
-------
hdr : dict
- next_segment : Sample frequency in Hertz
- final : Number of channels stored
- padding : Padding
stamps : ndarray of dtype
- segment_name : Name of ERD / ETC file segment
- start_stamp : First sample stamp that is found in the ERD / ETC pair
- end_stamp : Last sample stamp that is still found in the ERD / ETC
pair
- sample_num : Number of samples actually being recorded (gaps in the
data are not included in this number)
- sample_span : Number of samples in that .erd file
Notes
-----
The Segment Table of Contents file is an index into pairs of (raw data file
/ table of contents file). It is used for mapping samples file segments.
EEG raw data is split into segments in order to break a single file size
limit (used to be 2GB) while still allowing quick searches. This file ends
in the extension '.stc'. Default segment size (size of ERD file after which
it is closed and new [ERD / ETC] pair is opened) is 50MB. The file starts
with a generic EEG file header, and is followed by a series of fixed length
records called the STC entries. ERD segments are named according to the
following schema:
- <FIRST_NAME>, <LAST_NAME>_<GUID>.ERD (first)
- <FIRST_NAME>, <LAST_NAME>_<GUID>.ETC (first)
- <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ERD (second and subsequent)
- <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ETC (second and subsequent)
<INDEX> is formatted with "%03d" format specifier and starts at 1 (initial
value being 0 and omitted for compatibility with the previous versions).
"""
hdr = _read_hdr_file(stc_file) # read header the normal way
stc_dtype = dtype([('segment_name', 'a256'),
('start_stamp', '<i'),
('end_stamp', '<i'),
('sample_num', '<i'),
('sample_span', '<i')])
with stc_file.open('rb') as f:
f.seek(352) # end of header
hdr['next_segment'] = unpack('<i', f.read(4))[0]
hdr['final'] = unpack('<i', f.read(4))[0]
hdr['padding'] = unpack('<' + 'i' * 12, f.read(48))
stamps = fromfile(f, dtype=stc_dtype)
return hdr, stamps | python | def _read_stc(stc_file):
"""Read Segment Table of Contents file.
Returns
-------
hdr : dict
- next_segment : Sample frequency in Hertz
- final : Number of channels stored
- padding : Padding
stamps : ndarray of dtype
- segment_name : Name of ERD / ETC file segment
- start_stamp : First sample stamp that is found in the ERD / ETC pair
- end_stamp : Last sample stamp that is still found in the ERD / ETC
pair
- sample_num : Number of samples actually being recorded (gaps in the
data are not included in this number)
- sample_span : Number of samples in that .erd file
Notes
-----
The Segment Table of Contents file is an index into pairs of (raw data file
/ table of contents file). It is used for mapping samples file segments.
EEG raw data is split into segments in order to break a single file size
limit (used to be 2GB) while still allowing quick searches. This file ends
in the extension '.stc'. Default segment size (size of ERD file after which
it is closed and new [ERD / ETC] pair is opened) is 50MB. The file starts
with a generic EEG file header, and is followed by a series of fixed length
records called the STC entries. ERD segments are named according to the
following schema:
- <FIRST_NAME>, <LAST_NAME>_<GUID>.ERD (first)
- <FIRST_NAME>, <LAST_NAME>_<GUID>.ETC (first)
- <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ERD (second and subsequent)
- <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ETC (second and subsequent)
<INDEX> is formatted with "%03d" format specifier and starts at 1 (initial
value being 0 and omitted for compatibility with the previous versions).
"""
hdr = _read_hdr_file(stc_file) # read header the normal way
stc_dtype = dtype([('segment_name', 'a256'),
('start_stamp', '<i'),
('end_stamp', '<i'),
('sample_num', '<i'),
('sample_span', '<i')])
with stc_file.open('rb') as f:
f.seek(352) # end of header
hdr['next_segment'] = unpack('<i', f.read(4))[0]
hdr['final'] = unpack('<i', f.read(4))[0]
hdr['padding'] = unpack('<' + 'i' * 12, f.read(48))
stamps = fromfile(f, dtype=stc_dtype)
return hdr, stamps | [
"def",
"_read_stc",
"(",
"stc_file",
")",
":",
"hdr",
"=",
"_read_hdr_file",
"(",
"stc_file",
")",
"# read header the normal way",
"stc_dtype",
"=",
"dtype",
"(",
"[",
"(",
"'segment_name'",
",",
"'a256'",
")",
",",
"(",
"'start_stamp'",
",",
"'<i'",
")",
",... | Read Segment Table of Contents file.
Returns
-------
hdr : dict
- next_segment : Sample frequency in Hertz
- final : Number of channels stored
- padding : Padding
stamps : ndarray of dtype
- segment_name : Name of ERD / ETC file segment
- start_stamp : First sample stamp that is found in the ERD / ETC pair
- end_stamp : Last sample stamp that is still found in the ERD / ETC
pair
- sample_num : Number of samples actually being recorded (gaps in the
data are not included in this number)
- sample_span : Number of samples in that .erd file
Notes
-----
The Segment Table of Contents file is an index into pairs of (raw data file
/ table of contents file). It is used for mapping samples file segments.
EEG raw data is split into segments in order to break a single file size
limit (used to be 2GB) while still allowing quick searches. This file ends
in the extension '.stc'. Default segment size (size of ERD file after which
it is closed and new [ERD / ETC] pair is opened) is 50MB. The file starts
with a generic EEG file header, and is followed by a series of fixed length
records called the STC entries. ERD segments are named according to the
following schema:
- <FIRST_NAME>, <LAST_NAME>_<GUID>.ERD (first)
- <FIRST_NAME>, <LAST_NAME>_<GUID>.ETC (first)
- <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ERD (second and subsequent)
- <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ETC (second and subsequent)
<INDEX> is formatted with "%03d" format specifier and starts at 1 (initial
value being 0 and omitted for compatibility with the previous versions). | [
"Read",
"Segment",
"Table",
"of",
"Contents",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L668-L722 | train | 23,597 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | _read_vtc | def _read_vtc(vtc_file):
"""Read the VTC file.
Parameters
----------
vtc_file : str
path to vtc file
Returns
-------
mpg_file : list of str
list of avi files
start_time : list of datetime
list of start time of the avi files
end_time : list of datetime
list of end time of the avi files
"""
with vtc_file.open('rb') as f:
filebytes = f.read()
hdr = {}
hdr['file_guid'] = hexlify(filebytes[:16])
# not sure about the 4 Bytes inbetween
i = 20
mpg_file = []
start_time = []
end_time = []
while i < len(filebytes):
mpg_file.append(_make_str(unpack('c' * 261, filebytes[i:i + 261])))
i += 261
Location = filebytes[i:i + 16]
correct = b'\xff\xfe\xf8^\xfc\xdc\xe5D\x8f\xae\x19\xf5\xd6"\xb6\xd4'
assert Location == correct
i += 16
start_time.append(_filetime_to_dt(unpack('<q',
filebytes[i:(i + 8)])[0]))
i += 8
end_time.append(_filetime_to_dt(unpack('<q',
filebytes[i:(i + 8)])[0]))
i += 8
return mpg_file, start_time, end_time | python | def _read_vtc(vtc_file):
"""Read the VTC file.
Parameters
----------
vtc_file : str
path to vtc file
Returns
-------
mpg_file : list of str
list of avi files
start_time : list of datetime
list of start time of the avi files
end_time : list of datetime
list of end time of the avi files
"""
with vtc_file.open('rb') as f:
filebytes = f.read()
hdr = {}
hdr['file_guid'] = hexlify(filebytes[:16])
# not sure about the 4 Bytes inbetween
i = 20
mpg_file = []
start_time = []
end_time = []
while i < len(filebytes):
mpg_file.append(_make_str(unpack('c' * 261, filebytes[i:i + 261])))
i += 261
Location = filebytes[i:i + 16]
correct = b'\xff\xfe\xf8^\xfc\xdc\xe5D\x8f\xae\x19\xf5\xd6"\xb6\xd4'
assert Location == correct
i += 16
start_time.append(_filetime_to_dt(unpack('<q',
filebytes[i:(i + 8)])[0]))
i += 8
end_time.append(_filetime_to_dt(unpack('<q',
filebytes[i:(i + 8)])[0]))
i += 8
return mpg_file, start_time, end_time | [
"def",
"_read_vtc",
"(",
"vtc_file",
")",
":",
"with",
"vtc_file",
".",
"open",
"(",
"'rb'",
")",
"as",
"f",
":",
"filebytes",
"=",
"f",
".",
"read",
"(",
")",
"hdr",
"=",
"{",
"}",
"hdr",
"[",
"'file_guid'",
"]",
"=",
"hexlify",
"(",
"filebytes",
... | Read the VTC file.
Parameters
----------
vtc_file : str
path to vtc file
Returns
-------
mpg_file : list of str
list of avi files
start_time : list of datetime
list of start time of the avi files
end_time : list of datetime
list of end time of the avi files | [
"Read",
"the",
"VTC",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L725-L767 | train | 23,598 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | Ktlx._read_hdr_dir | def _read_hdr_dir(self):
"""Read the header for basic information.
Returns
-------
hdr : dict
- 'erd': header of .erd file
- 'stc': general part of .stc file
- 'stamps' : time stamp for each file
Also, it adds the attribute
_basename : Path
the name of the files inside the directory
"""
foldername = Path(self.filename)
stc_file = foldername / (foldername.stem + '.stc')
if stc_file.exists():
self._filename = stc_file.with_suffix('')
else: # if the folder was renamed
stc_file = list(foldername.glob('*.stc'))
if len(stc_file) == 1:
self._filename = foldername / stc_file[0].stem
elif len(stc_file) == 0:
raise FileNotFoundError('Could not find any .stc file.')
else:
raise OSError('Found too many .stc files: ' +
'\n'.join(str(x) for x in stc_file))
hdr = {}
# use .erd because it has extra info, such as sampling freq
# try to read any possible ERD (in case one or two ERD are missing)
# don't read very first erd because creation_time is slightly off
for erd_file in foldername.glob(self._filename.stem + '_*.erd'):
try:
hdr['erd'] = _read_hdr_file(erd_file)
# we need this to look up stc
hdr['erd'].update({'filename': erd_file.stem})
break
except (FileNotFoundError, PermissionError):
pass
stc = _read_stc(self._filename.with_suffix('.stc'))
hdr['stc'], hdr['stamps'] = stc
return hdr | python | def _read_hdr_dir(self):
"""Read the header for basic information.
Returns
-------
hdr : dict
- 'erd': header of .erd file
- 'stc': general part of .stc file
- 'stamps' : time stamp for each file
Also, it adds the attribute
_basename : Path
the name of the files inside the directory
"""
foldername = Path(self.filename)
stc_file = foldername / (foldername.stem + '.stc')
if stc_file.exists():
self._filename = stc_file.with_suffix('')
else: # if the folder was renamed
stc_file = list(foldername.glob('*.stc'))
if len(stc_file) == 1:
self._filename = foldername / stc_file[0].stem
elif len(stc_file) == 0:
raise FileNotFoundError('Could not find any .stc file.')
else:
raise OSError('Found too many .stc files: ' +
'\n'.join(str(x) for x in stc_file))
hdr = {}
# use .erd because it has extra info, such as sampling freq
# try to read any possible ERD (in case one or two ERD are missing)
# don't read very first erd because creation_time is slightly off
for erd_file in foldername.glob(self._filename.stem + '_*.erd'):
try:
hdr['erd'] = _read_hdr_file(erd_file)
# we need this to look up stc
hdr['erd'].update({'filename': erd_file.stem})
break
except (FileNotFoundError, PermissionError):
pass
stc = _read_stc(self._filename.with_suffix('.stc'))
hdr['stc'], hdr['stamps'] = stc
return hdr | [
"def",
"_read_hdr_dir",
"(",
"self",
")",
":",
"foldername",
"=",
"Path",
"(",
"self",
".",
"filename",
")",
"stc_file",
"=",
"foldername",
"/",
"(",
"foldername",
".",
"stem",
"+",
"'.stc'",
")",
"if",
"stc_file",
".",
"exists",
"(",
")",
":",
"self",... | Read the header for basic information.
Returns
-------
hdr : dict
- 'erd': header of .erd file
- 'stc': general part of .stc file
- 'stamps' : time stamp for each file
Also, it adds the attribute
_basename : Path
the name of the files inside the directory | [
"Read",
"the",
"header",
"for",
"basic",
"information",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L845-L893 | train | 23,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.